How to open a PowerPoint slide using Excel VBA?

Question: Sub Day1()

Dim objPPT As Object

Set objPPT = CreateObject("PowerPoint.Application")
Set PowerPoint.Slide = 5
objPPT.Visible = True

objPPT.Presentations.Open "C:\Users\Me\Desktop\Macro Test\Day 1.pptx"

End Sub

I want this to open the fifth slide on my PowerPoint presentation.
Answer: Your example code is almost right. Just needed to use the right object, and select the slide.
Dim objPPT As Object
Set objPPT = CreateObject("PowerPoint.Application")

objPPT.Visible = True

objPPT.Presentations.Open("your file")

objPPT.Slides(5).Select

Comment: Or use ActiveWindow.View.GoToSlide(5)


ARIMA model for a single variable with hidden context

Question: I have a signal which measures the power of a machine. I have been asked to fit an ARIMA model for this signal in order to find anomalies.
However as far as I know, the power of the machine is controlled by several factors, like: human control (i.e. an operator can increase, decrease, turn off, ... the power as he needs of as he is requested), automatic control (i.e. when for instance the internal temperature of the machine is too high it limits itself power, or if the power is not used for a given time the machine automatically turns off, ...), external control (i.e. some day it rains and the machine performs badly, ...), and of course some randomness.
My question is: from a methodological point of view, does it even make sense to fit an ARIMA model of this signal (and of this signal ONLY) without considering the context i.e. what the operator does, what the machine does, external factors? Maybe the power of the machine is "10" in the last six months, now it becomes "100" just because someone has decided so, how can I know if this is an anomaly or an intended behavior? How can the ARIMA model fit without these information? Or is the ARIMA model "strong enough" to handle all these "hidden" contexts?
Comment: It seems like a methodology has been dictated to you from on high. In my (professional) context, this happens sometimes too. Do you have the ability/latitude to suggest something different? Sometimes this requires educating your audience. That said, with ARIMA you can include additional regressors so you could include those other factors if you have the data on them. Without the additional regressors ARIMA will do poorly-- it will either not fit the level shifts, or it will incorrectly fit it not understanding the mechanism.
Comment: Yes I can try to suggest something different, but I'll have to explain why. My hunch says that an ARIMA model with one variable in a real case analysis makes no sense, but I'd like to confront with you to understand if I'm right and how to formally prove that in order to propose something else.
Answer: My suggestion is that you consider approach than ARIMA if necessary, which is typically used for forecasting. Anomaly detection appears to be the goal here. There are several options available in R and SAS (where I have experience). You didn't mention a particular language or software so I won't comment on all the ones I'm aware of for now, though I will show one example below.
Time series anomaly detection will use a time series forecasting framework to detect outliers-- you might even find one in your software that uses ARIMA as its base, in which case you could get away with not explaining a different method. You need a method that does both time-series anomaly detection and can include regressors.
I like using tsoutliers in R. Using the built-in R dataset LakeHuron, there's a one line call to produce a plot showing the presence, magnitude and type of outliers (level shifts, temporary pulses, outliers): plot(tsoutliers::tso(LakeHuron)). The tso function accomodates regressors as well. Perhaps most importantly for you, "The original framework is based on ARIMA time series models" (direct quote from the documentation).

SAS example, per request. I no longer have SAS so I can only talk about it more generally. I have done this previously with PROC UCM (Unobserved Component Models), so this is not an ARIMA based approach. It is probably possible to get something out of PROC ARIMA.
PROC UCM includes many statements-- it can be quite complex. There's no automatic optimisation, unlike R, so you will need to specify the appropriate components for the model (such as trend, level, season). The Model and RANDOMREG statements allow you to include regressors.
One of the optional statements is OUTLIER. This allows you to set the threshold for outlier detection and will output the outliers that are identified. You can use ODS tables to output this to a data set.
Comment: Thanks a lot, can you share an example code in SAS as well?
Comment: Do you have SAS/ETS?
Comment: Yes I have that package
Comment: editing my answer.


Como instalar um Windows Service sem Setup?

Question: Tenho um projeto de Windows Service no Visual Studio em C#, porém, preciso instalar este projeto a partir de linhas de código, sem utilizar o Installutil do console e nem o Setup do Visual Studio.
Tem alguma maneira de fazer isso?
Answer: Pode-se usar a classe ManagedInstallerClass (responsável por lidar com a funcionalidade do Installutil), mais especificamente, o método InstallHelper:
static void Main(string[] args) {
    if (System.Environment.UserInteractive) {
        if (args.Length > 0) {
            switch (args[0]) {
                case "-install": {
                   ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                   break;
                }
                case "-uninstall": {
                   ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                   break;
                }
            }
        }
    }
    else {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new MyService() };
        ServiceBase.Run(ServicesToRun);
    }
}

Fonte
Exemplo de uso:

Instalar: meuProjeto.exe -install
Desinstalar: meuProjeto.exe -uninstall


Modified Pólya-Eggenberger Urn Problem

Question: An urn contains $0$ black balls and $n$ white balls. $k$ balls are picked up at random and replaced by $k$ black balls. This process repeats itself till all the balls in the urn are black.
What is the expected number of black balls in the urn after $j$ steps of picking up?
Answer: Focus on one ball. The chance that it has not been replaced after $j$ trials is $(1-{k\over n})^j$. The chance that it has been replaced is $1-(1-{k\over n})^j$, and so the expected number of replaced (black) balls after $j$ trials is
$$n\left(1-\left(1-{k\over n}\right)^j\right).$$
This problem is very similar to this one.

Modified Pólya-Eggenberger Urn Problem


How to set Munin Critical/Warning alerts when value are under a threshold and not over?

Question: I am trying to do a simple alert in Munin checking SW RAID 1 status where a metric of 2 disks is healthy, 1 disk is Warning and 0 disks is Critical.
All the Munin monitors I've seen are triggered when a value is too high e.g. Disk space is over 90% but in my case, I want the reverse. I can't seem to find anything in the Munin docs that support this.
I know I could reverse the logic such that it monitors the number of unhealthy disks, i.e. 0 healthy, 1 Warning and 2 Critical but it just seems neater the other way around.
Answer: From http://guide.munin-monitoring.org/en/latest/reference/plugin.html#plugin-attributes-data on the warning / critical section it says:
Attribute:  {fieldname}.critical
Value:  integer or decimal numbers (both may be signed)
Type:   optional
Description:    Can be a max value or a range separated by colon. E.g. "min:", ":max", "min:max", "max". Used by munin-limits to submit an error code indicating critical state if the value fetched is outside the given range.
See also:   Let Munin croak alarm
Default:

Interestingly, though at http://guide.munin-monitoring.org/en/latest/reference/munin.conf.html#munin-conf it says:

The value at which munin-limits will mark the service as being in a
critical state. Value can be a single number to specify a limit that
must be passed or they can be a comma separated pair of numbers
defining a valid range of values.

So, not sure if it is either, or just one - I have seen reference to the : values elsewhere too. Good luck!
Answer: The answer from Bryan is linking to the correct documentation. As i needed to solve this for another plugin of ours. The output of such a plugin should be:
sudo munin-run my_plugin
raid_disks_healthy.value 3

sudo munin-run my_plugin config
...
raid_disks_healthy.warning 2:
raid_disks_healthy.critical 1:

meaning less than 2 healthy disks is warning, less than 1 healthy disk is critical


What is the token for the file download link of a media entity?

Question: Using the linked_field module and the [paragraph:field_pbpresentation_file:entity:url] token, I get the edit link for the media entity, not the link to download the file itself.
What token should I use for the download link?
Answer: You probably want the URL of the file entity, not the media entity.
You have to find out the field name of the file field in the media entity. If you are using a core preinstalled media type it could be for example field_media_file. Then you can access the file entity and the URL:
[paragraph:field_pbpresentation_file:entity:field_media_file:entity:url]


Dynamo db export to csv

Question: I have a serverless project, I'm trying to export Dynamo DB tables into single csv, and then upload it to S3.
All npm modules i checked export single table. Is there a way to export multiple table data into one single csv?
Answer: To export as a CSV, adding onto @dixon1e post, use jq in the shell. With DynamoDb run:
aws dynamodb scan --table-name my-table --select ALL_ATTRIBUTES --page-size 500 --max-items 100000 --output json | jq -r '.Items' | jq -r '(.[0] | keys_unsorted) as $keys | $keys, map([.[ $keys[] ].S])[] | @csv' > export.my-table.csv

Answer: The AWS CLI can be used to download data from Dynamo DB:
aws dynamodb scan --table-name my-table --select ALL_ATTRIBUTES --page-size 500 --max-items 100000

The --page-size is important, there is a limit of 1M (megabyte) for every query result.
Comment: It scans the table and returns a DynamoDB DSL style objects in JSON format.
To make this a CSV you'll need more work around this

Dynamo db export to csv


Mounting Solaris UFS partition on Debian(with FreeBSD kernel)

Question: I have some disks that were being used on a Solaris system. The disks are formatted as UFS.
I attached them to a Debian system (with FreeBSD kernel. Debian/kFreeBSD), but I cannot mount them.
<code>$ mount -t ufs /dev/da2s1 /mnt/diska
mount: /dev/da2s1 : Invalid argument
</code>
Also the tunefs.ufs does not work;
<code>$ tunefs.ufs -p /dev/da2s1
tunefs.ufs: /dev/da2s1: could not read superblock to fill out disk
</code>
Is there an incompatibility between FreeBSD UFS and Solaris UFS? Is it possible to mount one, under the other OS ?
Note: tunefs.ufs works on the root partition
<code>$ tunefs.ufs -p /dev/da7s2
tunefs.ufs: ACLs: (-a)                                         disabled
tunefs.ufs: MAC multilabel: (-l)                               disabled
tunefs.ufs: soft updates: (-n)                                 disabled
tunefs.ufs: gjournal: (-J)                                     disabled
tunefs.ufs: maximum blocks per file in a cylinder group: (-e)  2048
tunefs.ufs: average file size: (-f)                            16384
tunefs.ufs: average number of files in a directory: (-s)       64
tunefs.ufs: minimum percentage of free space: (-m)             8%
tunefs.ufs: optimization preference: (-o)                      time
tunefs.ufs: volume label: (-L)
</code>
Answer: FreeBSD UFS2 and Solaris UFS, while sharing some original structure have somewhat diverged so I'm unsure freeBSD can mount it. Was your UFS file system properly unmounted ?
EDIT: Also, if the file system was created on SPARC hardware, it won't be mountable on x86 as the format is architecture dependent.
Comment: I mounted and unmounted under solaris but it did not work. I also wanted to try read-only UFS code in Linux, but it alse gave errors. I guess solaris UFS is very lonely :-/
Comment: Also, the UFS was created on x86 hardware.
Comment: Most Gnu/Linux distributions should be able to directly mount in read-only mode an ufs slice created on Solaris running on x86 hardware. eg: "mount -r /dev/sdb5 /mnt".
Answer: Did you halted the solaris system without the unmount?
As far as I know you can safely mount a cleanly-unmounted Solaris UFS, otherwise it's really a layout compatibility issue. I'd try to do the same also with a recent GNU/Linux kernel
Comment: I have tried explicitly mounting and umounting the disks. But I still get the same message. I tried mounting in Ubuntu, but It gave an error message about superblock's magic number(can't remember exact message)


How can I create a View to give me a list of nodes that share a nodereference with the User's profile?

Question: I have a "Company" node type and a "Content" node type.
In my User profiles I have added a nodereference to the appropriate Company node, and
in the Content nodes, I have also added a nodereference to the Company owning the content.
What I am trying to do is to construct a view that will present the logged-in user a list of all Content nodes owned by (i.e. with references to) the user's company.
Pseudo-sql would be something like this:
<code>SELECT n.title FROM node n,user u WHERE
n.company_reference = u.company_reference AND logged_in_user.uid = u.uid
</code>
There ought to be a way to do this via Views, I just have been unable to figure out how, so any suggestions or pointers will be greatly appreciated
Answer: did something similar using panels and view panes. Without panels I'm not sure how I would approach it. You can create a view that lists all the content nodes. then create a display of that view that is a "content pane" (requires panels). Go into advanced, and create a "contextual filter" based on the criteria you want (in your case it would be your node reference to the company). Then click "argument input" under pane settings. you should now be able to add this pane to a panel and pass it the correct argument. I know it's a little confusing written out .... but with this setup you could for instance make a panel that shows the user, the users company, and a list of the content nodes owned by that company.
I've posted this a couple times here, only because it really helped me understand contextual filters and how you can build some pretty awesome things just using them with views and panels
http://dev.nodeone.se/en/learn-page-manager-part-5-views-content-panes-basics
Comment: Thanks - I did try this, pretty explicitly following the steps in the video you linked. It all worked great EXCEPT it never actually would show me any data ;-/. The View pane worked fine, but only when I tested it in Views UI. I imagine I could get it to work eventually, but just didn't have time to mess with it. It was faster and more straightforward (if less flexible) to write a new module instead.


Problemas para copilar codigo, pyinstaller

Question: tudo bem?  Eu estou travado 100% com um programa que estou fazendo que não funciona de nenhuma forma apos eu copilar, sempre é apresentado esse erro:

Porém o programa funciona normalmente pelo VisualStudioCode ou o Pycharm, só sempre da erro na hora de copilar, eu ja fiz diversars coisas diferentes, ja mudei versões das lib, ja alterei a estrutura do codigo, ja mudei as versões do pyinstaller, ja tentei adicionar os modulos das lib manualmente, mas nadaaa funciona, sempre da erro, as lib que estou usando dentro do codigo são: playwright, os, PyAutoGUI e PySimpleGUI;
Será que um anjo de Deus ja passou por isso e consegue me ajudar???
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Para o pessoal que passou por esse problema, uma maneira que consegui resolver foi desatualizando a versão do greenlet para 1.1.3 e também modifiquei uma linha do meu codigo onde está o playwright:
<code>    self.brow = self.p.chromium.launch(headless=False, executable_path=r'files\chrome-win\chrome.exe')
</code>
eu adicionei esse executable_path, que teve a função de localizar o navegador que será executado, depois disso deu tudo certo.


varchar column sorted by itself

Question:
I have table with columns, some columns are varchar. I have noticed that the rows in the table are sorted automatically. I, instead, want the rows to be in the same order as they are inserted into the table. Any clues? Please note that I haven't applied any ORDER BY clause and Dates are all same for the columns.
As is evident that although I added Testing Book 3 first, it automatically came below the Testing Book 2 which is not desired.
Is it because my PK is composite?
Comment: Add an automatically incremented ID column as a PK.
Comment: Can't do that, My table structure does not allow me to do that. I have already specified PK on a group of columns.
Comment: What columns are in the composite PK that you have specified?
Comment: The rows in the table are **not** sorted automatically - in fact, in a SQL Server table, there is **no** inherent sort order at all. The data in SQL Server is not sorted - only your output can be sorted - **if and only if** you provide an `ORDER BY` clause.
Comment: Composite Key

invoice_ID (numeric), invoice_account (varchar), invoice_item (varchar)
Comment: Well, I have posted the screenshot as well showing sorting, and I am sure that I havn't specified any order by clause.
Comment: @SamarthAgarwal, you may be seeing sorting, but it is not **guaranteed** sorting; it is just what SQL Server did at that moment, even if it happens the same way 1000 times in a row. As I, and now marc_s, have said, the **ONLY** way to guarantee a particular sort is via ORDER BY.
Comment: In the picture above, I have clearly inserted the 2nd row before the 1st row then how come it is shown 2nd. I just need to understand where I am lacking, no offence.
Comment: @SamarthAgarwal: you are confusing what "appears" to be happening with what is actually happening. The rows are not _necessarily_ stored in the order they were inserted. And depending on how you organized your CLUSTERED index, doing a REBUILD can change the physical location of the data pages. And that is all irrelevant if the query goes parallel as the different threads can be reassembled in any particular order. The **ONLY** way that SQL Server knows what the end-result sorting should be is via the ORDER BY clause. There is no other way to get consistent / guaranteed sorting.
Answer: You did not specify exactly which RDBMS you are using, but I can say the following with regards to Microsoft SQL Server:

You CANNOT guarantee ANY predictable / repeatable ordering without an ORDER BY clause
If you want rows to be ordered by when they were inserted, you need to: add a new column that is either an IDENTITY (could be INT or BIGINT) or a DATETIME / DATETIME2 datatype with a default constraint of GETDATE() or GETUTCDATE() AND ORDER BY this new field
The new field has nothing to do with a PK. This is in reference to a suggestion someone else made. A PK is for relationships, not sorting, and while an IDENTITY is typically used for a PK, there are plenty of situations to have a PK of one or more non-auto-incrementing fields and still have an auto-incrementing field.
If you need the detail on what millisecond / nanosecond the records are inserted as well as the guaranteed / repeatable sort, then do both the DATETIME / DATETIME2 and IDENTITY fields.
Adding one, or both, of these fields does not imply any specific index structure. Their existence merely allows you to create one or more indexes that would include them to enforce your desired ordering.
Comment: If they were truly inserted at the same time, then the ordering of those rows doesn't matter according to your criteria.
Comment: There is one more concern. I am inserting some rows at once, so, they will have the same datetime, then how do I order them?
Comment: @SamarthAgarwal, I agree with Ben in that if they were inserted at the same time and you want them to be in that order, then there is truly no difference between two (or more) rows inserted at the same millisecond (or nanosecond if using DATETIME2). _However_, if you want a predictable / repeatable sort, then that is why I also suggested adding an INT / BIGINT field that is marked as IDENTITY instead of doing the DATETIME / DATETIME2 field. If you need the detail on what millisecond the records are inserted plus the repeatable sort, then do _both_ the DATETIME and IDENTITY fields.
Comment: Well i assumed the same **but** they are getting sorted right after getting inserted. Note: It all works fine if I remove the Composite PK. Any Clues?
Comment: @SamarthAgarwal: NO, it is NOT working fine when you remove the PK. You are just seeing the order that the rows are in based on several factors that could all change. That is why I keep stressing _guaranteed_ and _repeatable_. What you are seeing is NOT a sort but a coincidental ordering that matches your expectations. Once the data is large enough to maybe cause the optimizer to choose a parallel plan, you will see rather "odd" sorting. That is why you **need** an ORDER BY clause. End. Of. Story. Put the PK back, add the 1 or 2 fields, and use it/them in an ORDER BY. There is no other way.
Comment: Ok ok don't be angry. :) Thanks
Comment: @SamarthAgarwal: you are welcome, and sorry to show frustration.
Answer: Please note that SQL does not guarantee ordering when inserting or selecting rows.
You can see answers for a question similar to yours here
The way I would do ordering by insertion is I would add DATETIME column that gets a date/time value of when you do insert. (How this can be done you can see in the accepted answer to this question)
Then during selects make an order by on the DATETIME column

varchar column sorted by itself


How many infinite subsets of N are there anyway?

Question: I was reading 2 proofs

one that the powerset of $ N$ has a higher cardinality than $N$
two a proof that the cardinality of the set of all finite subsets of $N$ has the same  cardinality than $N$

That made me wonder the difference between these two sets is the set of Infinite subsets of $N$ so how many are there of these, and how do they look?
Comment: Well, you've answered it: the set of finite subsets is countable; the power set is uncountable; therefore the set of infinite subsets is uncountable (with the same cardinality as the power set).
Comment: (Note that the duplicate answers your question on two accounts: the first being the fact that subsets of $\Bbb N$ with the same cardinality are in fact infinite; the second is that every infinite subset of $\Bbb N$ in fact has the same cardinality as $\Bbb N$ so this is actually the same question. Hence my vote to close it as a duplicate.)
Comment: (I somehow feel that I close a lot of your questions as duplicates. I hope you are not offended, or take it personally. I really have nothing against you!)
Comment: @AsafKaragila sorry my fault forgot to check for duplicates
Answer: $P(N)$ has higher cardinality than $N$. Let $I(N)$ be the set of all infinite subsets of $N$, and $F(N)$ the set of all finite subsets of $N$.
We have $P(N)=I(N) \cup F(N)$.
Let $A,B$ two infinite set, we have $card(A \cup B)= \max(card(A), card(B))$.
So, if $I(N)<P(N)$, as $F(N)=N$ and $N<P(N)$, $P(N)=\max (F(N), I(N))=\max(N,I(N))=I(N)<P(N)$.
There is a contradiction. So $I(N) \geq P(N)$. But, $I(N) \subset P(N) \implies I(N)\leq P(N)$.
So $I(N)=P(N)$
Comment: is P(N) = $\aleph_1$?
Answer: Exactly as @mjqxxxx says, you've already practically answered it.  The proof is simple.  Let $\mathcal{F}=\{E\in\mathcal{P}(\mathbb{N}):|E|<\infty\}$ and $\mathcal{I}=\mathcal{P}(\mathbb{N})\backslash \mathcal{F}$.  Suppose to the contrary that $\mathcal{I}$ is countable.  Then $\mathcal{I}\cup\mathcal{F}=\mathcal{P}(\mathbb{N})$ is a countable union of countable sets and therefore countable.  But, as you mention, $\mathcal{P}(\mathbb{N})$ is uncountable, leading to a contradiction.  Therefore $\mathcal{I}$ is uncountable.
What do sets in $\mathcal{I}$ look like?  Well, since it is uncountable there is no way to write them all down, but there are several notable examples.  It contains for example all co-finite sets, sets of the form $\mathbb{N}\backslash E$ where $|E|<\infty$, but even these are only countable in number.  It also includes sets such as the set of all prime numbers.  The set of all numbers with a 5 somewhere in their decimal representation, and anything else you can come up with where it is unbounded above.


Execute shell command without filtering from Vim

Question: I want to select a block of text (for example, V%) and use the text as input to a shell command (for example, wc or pbcopy) - but I don't want to alter the current buffer - I just want to see the output of the command (if any) then continue editing without any changes.
Typing V%!wc translates to :'<,'>!wc and switches the block of text for the output of the wc command.
How do you pipe a chunk of text to an arbitrary shell command without affecting the current buffer?
Comment: If you want to pipe your text selection into the OS clipboard (pbcopy on OS X), you can just use the * yank buffer. In visual mode type: "*y
Answer: Select your block of text, then type these keys :w !sh
The whole thing should look like:
:'<,'>w !sh

That's it. Only took me 8 years to learn that one : )
note: typing : after selecting text produces :'<,'> a range indicating selection start and end.
Update 2016: This is really just one use of the generic:
'<,'>w !cli_command

Which basically lets you "send" arbitrary parts of your file to external commands and see the results in a temporary vi window without altering your buffer. Other useful examples would be:
'<,'>w !wc
'<,'>w !to_file my_file

I honestly find it more useful to alter the current buffer. This variety is simply:
'<,'>!wc
'<,'>!to_file my_file

Comment: Awesome, neat and builtin --- all one could hope for.
Comment: Documented at `:help :write_c` for those curious.
Answer: One possibility would be to use system() in a custom command, something like this:
command! -range -nargs=1 SendToCommand <line1>,<line2>call SendToCommand(<q-args>)

function! SendToCommand(UserCommand) range
    " Get a list of lines containing the selected range
    let SelectedLines = getline(a:firstline,a:lastline)
    " Convert to a single string suitable for passing to the command
    let ScriptInput = join(SelectedLines, "\n") . "\n"
    " Run the command
    let result = system(a:UserCommand, ScriptInput)
    " Echo the result (could just do "echo system(....)")
    echo result
endfunction

Call this with (e.g.):
:'<,'>SendToCommand wc -w

Note that if you press V%:, the :'<,'> will be entered for you.
:help command
:help command-range
:help command-nargs
:help q-args
:help function
:help system()
:help function-range

Comment: My first thought was that it looked really chunky and verbose, but after adding chucking it in my .vimrc and adding a mapping, it's perfect:

vmap # :SendToCommand

Now I can just do V%# and bang out the command name.  Just what I wanted.
Comment: Glad you like it!  Your mapping looks like a good idea (I do tend to go for long and verbose command names and rely on tab-completion to save me the effort).  Consider putting it in `~/.vim/plugin/sendtocommand.vim` or `~/.vim/autoload/sendtocommand.vim` (the latter will require some changes) to help keep your vimrc manageable.
Answer: Update: my answer is nonsense.
@pixelearth's answer is good, but I had a little trouble understanding what he did exactly, so I wrote the following. This sequence of commands let's you execute wc -l on your visual selection. wc -l simply counts the number of lines passed to it.

In Vim go into Visual Mode using v
Select a few lines by going down: jjjj
Type : which Vim will translate to :'<,'>
Type w !wc -l, your complete commandline should now be :'<,'>w !wc -l
Press Enter to get the result of your command (in this example it would be 4)
Press Enter to continue editing

I don't understand what exactly happens at step 3 and 4 but I do know that it works.
Comment: Revisiting this after several years, I can see that while what you're doing isn't exactly the same thing, it's still really cool. You're basically using the selected text as INPUT for following command. Equally useful.
Comment: For those confused about the `'<,'>` bit: check out `:help '<` and `:help mark-motions` inside Vim. Things that start with apostrophe (`'`) are "marks". Vim has these special marks for the beginning and end of the visual selection. A colon-command in Vim can be applied to a given region of the file by specifying that region (with marks, or other methods) just after the colon. So `:'<,'>...` reads as "From mark `<` to mark `>`, run command `...`"
Comment: This isn't really the same thing at all. What you're doing is manually typing the command !wc -l, what is being done above is that the command you want to execute IS ALREADY IN THE VIM FILE. So if you had wc -l on a line by itself, you could use the method above to pipe THAT command to !sh (the shell).
Comment: @pixelearth You're right, I just did not understand the original question.
Comment: If your answer is nonsense (as you state), why don't you delete it?
Answer: I know it's not the ideal solution, but if all else fails, you could always just press u after running the command to undo the buffer change.
Comment: Sure, that's what I do currently - I'm just hoping I'm missing something.  I guess if there isn't a built-in way of doing this, a small cmap could do the trick - anyone got a ready-made one?
Comment: After glancing around on meta-SO, using `backticks around text` apparently is supposed to allow code-formatting in comments.


Git log list commits excluding cherry-picked from the first branch

Question: For example I have this commit history

Let say at some point release1 was released to production and after couple of days, release2 branch was released.

branch relase1 contains 2 commits (4 & 5) that was cherry-picked from master
branch release2 contains 2 commits (8 & 9) that was also cherry-picked from master.

cherry-pick was never done with -x argument.
I want to get all commit for release2 that "wasn't release yet at that point" this means commit (6,7,8,9) that is marked by green circle.
What would be the easiest way to do this?
Example of the repository in github
Update 1 (git cherry)
$ git cherry -v release1 release2
- 91785f2be363244a1da4459746fce6a6ea28c2b5 4
- e88de1f8b62213089b300e3143c4caf509b5c13b 5
- 9d23e9c7e6f769c3bbb44ad42bc7b708b4b0a9e6 6
- 6fb71e4406e0b127e06f6e5b145de8a9d39db01e 7
- 6276becc413494b7724a4dd8b852234f4b71e913 8
- 6dd3b5b75222c02c921c9c20bcaee83e1c8be746 9

With cherry, it seems that I still got 4 and 5 which both are form master
Update 2 (--left-right --cherry-mark)
$ git log --left-right --cherry-mark --pretty=oneline --abbrev-commit  release2...release1
= 6dd3b5b 9
= 6276bec 8
> caa4e2f 5
= 0230a1f 4
= 6fb71e4 7
= 9d23e9c 6
= e88de1f 5
= 91785f2 4

This gives me everything except 5 is cherry-marked, which I have a hard time to explain
Update 3 with non empty commit
In original attempt, I created each commit with --allow-empty. As pointed below it created hash of an empty tree.
After recreating the the repository with real content, I get the desire result with both answer below git cherry and --left-right --cherry-mark
Comment: would have been easier if you had merged instead of cherry picked
Comment: you repo do not have branch...
Comment: sorry you are right, pushed all the branch
Answer: Note that your linked repository contains 15 completely empty commits.  By "empty commits" I don't just mean the kind of no-change commits that git commit --allow-empty allows, but rather completely empty: each commit has no files at all, just a commit message.  (More precisely, every commit has the empty tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904 as its tree.)  So every commit in your repository is patch-ID equivalent to every other commit in your repository.
That (mostly) explains why your update-2 section shows the output that it does: commit 6dd3b5b is patch-equivalent to commits 6276bec, 9d23e9c, and so on.  The puzzle is why commit caa4e2f is not paired up with another, since it too is patch-equivalent to every other commit.  In any case, this is almost an example of a false positive, but here it's really more of a true positive: these commits are all the same, and can therefore be discarded without effect.

Git's revision-walking commands (git log and git rev-list) can use git patch-id to mark patch-equivalent commits.  This is not foolproof, but if a commit was cherry-picked without manual intervention, the patch IDs of the copy and the original will match.
To see how to use this, look at the git log or git rev-list documentation (the section about this is shared across both sets of documentation—as is the underlying implementation—so I linked to just one).  Jump down to the section on the --left-right option.  Note that --left-right only makes sense when combined with symmetric difference, which in this case means using the syntax release1...release2 or release2...release1.  Note that there are three, not two, dots, between the two names here.
Using the three dots and --left-right, Git will enumerate commits 5 and 4 that are reachable from release1, and also the two different commits 5 and 4 that are reachable from release2.  (Of course, Git will first enumerate commits 9, 8, 7, and 6 that are reachable from release2, before enumerating the 5 and 4 that are reachable from release2 but not release1.  As you can see, it's probably a mistake to call these four different commits by the same two names.  They have different hash IDs for a reason: they are different commits.  Call them 5A and 5B and 4A and 4B if you like, or maybe 5.1 and 5.2 to add the release number, but give them distinct names!)
So far, that's not very much help: you have got Git showing you commits 5.1 and 4.1 from release1, marked with < or > depending on which side of the three dots the name release1 is on.  And, you have Git showing you commits 9, 8, 7, 6, 5.2, and 4.2 from release2, marked with the other marker.  But this is the all-important starting point.  You can now switch from --left-right to --left-only or --right-only, to tell Git don't show me one of the two sets, even though you're still enumerating all the commits it.
With or without the left or right only options, you can add --cherry-mark, to tell Git: Run git patch-id on every commit in both sets.  When a commit in the left-side set has the same patch ID as a commit in the right-side set, mark that commit with an equals sign =.  Otherwise, mark the commit with a plus-sign +.
So, in this case if you run:
git rev-list --left-right --cherry-mark --abbrev-commit release2...release1

you'll see (assuming the hash ID of commit 9 starts with 999999, etc):
<9999999
<8888888
<7777777
<6666666
=5200000
=4200000
=5100000
=4100000

So the commits you want are exactly those marked with <.  Using release1...release2, the commits you want are exactly those marked with >.
Assuming all of the above makes sense, now read the --cherry-pick section.
Note that if you had to resolve a conflict when cherry-picking, the patch IDs of the original commit and its copy won't match.  Such a commit won't be omitted by this process.  It's also possible to get a false match.  This tends to occur with a fix that just consists of, e.g., moving some opening and closing braces around: the patch ID is formed by stripping not only the line numbers, but also whitespace.  So reducing two different (by indentation and line number) brace-changing commits to patch IDs collapses commits that should be different.  Hence my statement at the top about this not being foolproof: you can get both false negatives (cherry-pick with merge conflict resolved) and false positives (conflated commits that are actually different).
Comment: The git documentation on "git log --cherry-mark" always melts my brain.
Comment: @G.SylvieDavies Here, have some some refresher for your [sanity](https://git-man-page-generator.lokaltog.net/).
Comment: I came back to this answer after a while and still impress how thoroughly it was explained. I find that I always learn something new every time with git.
Answer: With the git cherry command you can find commits that have not been applied in an upstream branch. From man git-cherry, the synopsis looks like:
git cherry [<upstream> [ [<limit>]]]

and the description

Determine whether there are commits in ..<upstream> that are equivalent to those in the range <limit>...
The equivalence test is based on the diff, after removing whitespace and line numbers. git-cherry therefore detects when commits have been "copied" by means of git-cherry-pick(1), git-am(1) or git-rebase(1).
Outputs the SHA1 of every commit in <limit>.., prefixed with - for commits that have an equivalent in <upstream>, and + for commits that do not.

So, to find commits in release2 that have no equivalent commit in release1, you could do
git cherry release1 release2 | grep '^+' | cut -d' ' -f2


Good approximations for CDFs

Question: As you probably know, the CDFs for many widely-used distributions are difficult, if not impossible, to express in closed form without the use of special functions

The normal distribution uses $\mathrm{erf}$.
Student's $t$-distribution requires the incomplete beta function or the Euler gamma function
The $\chi^2$ distribution requires the Euler gamma function and the lower incomplete gamma function.

I could continue, but you get the idea. Unfortunately, all of these functions share the property of being impossible to compute.
Does anybody know of a good (freely accessible) resource for approximating these various CDFs? Since I'm after p-values, I'm especially interested in approximations which are accurate for extreme values.
Comment: [R](http://cran.r-project.org/)
Comment: Let me add this: what precisely do you mean by "impossible to compute"?  *All* the functions you name are no more "impossible" or difficult to compute than, say, $\exp$, $\sin$, $\cos$, or even $\sqrt{}$ for that matter.
Comment: Sqrt is easy to compute with a simple Newton iteration. The common transcendental functions such as $\sin$ can be computed with a truncated Taylor series. But I'm not aware of any known method that computes $\mathrm{erf}$. That's kind of the point of me asking.
Comment: See https://stats.stackexchange.com/questions/7200/evaluate-definite-interval-of-normal-distribution/29899#29899 for $\operatorname{erf}.$ It might give you some sense of how it becomes possible to compute values of transcendental functions.
Comment: See https://stats.stackexchange.com/questions/191492/how-does-saddlepoint-approximation-work/191781#191781
Answer: To expand on @whuber's comments.  What is wrong with the approximations that already exist?
You say that the square root is easy to compute, but the newton iteration approximates the square root, but does not give its exact value (unless you happen to have a situation where the root is rational and you get lucky in the itteration and rounding).  So if you are happy with an approximation method for square roots and others then you should be happy approximating the erf and other functions, and those approximations already exist.
You could approximate the approximations that already exist with splines or logsplines or taylor series, or ..., but what advantage do these less accurate approximations of approximations have over the existing approximations?
The wikipedia link for the error function has many different approximations for it along with a long list of programs that implement approximations, those should fill your definition of good and freely accessable (for some on the list) resources.  I would expect there will be similar links to the other functions mentioned.
But why not just use R?
Comment: Did you follow the link in the answer? Did you read the page?  Did you look at R like @whuber suggested (and provided a link)?  Did you google (or other search) for "error function" or "library distribution function" or other possibilities?
Comment: "What is wrong with the approximations that already exist?" I don't know what they are? Which is why I'm asking about them?
Answer: You can take a look into the GNU Scientific Library (gsl) which is free to use:
https://www.gnu.org/software/gsl/doc/html/randist.html?highlight=tdist#
However, you need to look into the code to understand the algorithms if needed. The algorithms are really precise as they employ different methods depending on the parameters. So, it is complicated to understand them without prior knowledge.
Another easy to undestand resource is the famous book "Numerical recipes in C" http://numerical.recipes/, with a very good chapter for the algorithms.
Press, William H., Saul A. Teukolsky, William T. Vetterling, and Brian P. Flannery. "Numerical recipes in C." (1988).
Comment: please add full references for you link and your second book. Thanks!
Comment: Thanks for your feedback. I will add it!

Good approximations for CDFs


How to remove and add joins to a view?

Question: Because of some buggy handlers I need to write a hook that will:

Get location_instance table's alias from the original query
Remove location_instance table join
Remove that alias join
Remove a location table join
Add 2 new joins

Apparently views does things a little differently so I can't just <code>$query->join()</code> my way to freedom. How exactly do I accomplish the above?
Answer: This is an issue I have been sturggling with myself.  You may want to start by looking at hook_views_query_alter() and read this related Drupal Answers question.
Then you can use these functions: views_plugin_query_default to actually affect change on your query.

How to remove and add joins to a view?


HTTPS over third-party SSH tunnel. Is it safe?

Question: I just get a Linux server from a third-party. Then I create a SSH tunnel via SecureCRT: https://www.vandyke.com/support/tips/socksproxy.html , where the Linux server is used as the Gateway Server.
However, the Linux server is not 100% safe since it is managed by a third-party. Now if I connect to a HTTPS server via the SSH tunnel, will the password sent to the HTTPS server be stolen by the administrators of the Linux server?
Answer: HTTPS over a third-party SSH tunnel is no less secure than SSH over untrusted networks and internet is by definition an untrusted network.
HTTPS encrypts end-to-end and no party in-between can decrypt the message unless they possessed the keys (or downgraded the connection, or tricked the user to trust attacker's certificate, but no attack on HTTPS is facilitated by using an underlying tunneling protocol).

Also you don't send any password to the HTTPS server. A password might be a part of the data transmitted over the secure HTTPS channel, but no password is used for the HTTPS implementation/connection itself.
Comment: HTTPS does not warn when the public key changes (unless it's invalid) but SSH usually does warn when the public (host) key changes. So the "trick the user to trust an altered key" part is the most insecure I guess.
Comment: True, it is up to the https site owner to do key pinning and hsts.


How can I make nodeunit report previous errors?

Question: I'm currently testing for the existence of a property in a response object. But if it doesn't exist the next test makes the whole thing fll on knees because test.done() never gets called.
foo.execute( function( error, response ) {

  test.ok( typeof response.request != 'undefined',
    "The response should have a request property" );

  test.equal( response.request.method, 'GET',
    "The request header should reflect the method used." );

  test.done();

});

The result is....

FAILURES: Undone tests (or their setups/teardowns):
  - PostResourseGetSucceeds
To fix this, make sure all tests call test.done()

How can I either make the test still report the initial test?  I've tried putting in an if statements but it just seems to cumbersome.
foo.execute( function( error, response ) {

  test.ok( typeof response.request != 'undefined',
    "The response should have a request property" );

  if ( typeof response.request != 'undefined' ) {
    test.equal( response.request.method, 'GET',
      "The request header should reflect the method used." );
  }

  test.done();

});

Answer: I fell upon a simple solution, try and catch.
foo.execute( function( error, response ) {

  try {

    test.ok( typeof response.request != 'undefined',
      "The response should have a request property" );

    test.equal( response.request.method, 'GET',
      "The request header should reflect the method used." );

  }
  catch(e) {
    test.ok( false, "Not all tests were run." );
  };

  test.done();

});


comparing population variance vs variance of sample means

Question: I have a data set as
lab6data <- c(2,5,4,6,7,8,4,5,9,7,3,4,7,12,4,10,9,7,8,11,8,
              6,13,9,6,7,4,5,2,3,10,13,4,12,9,6,7,3,4,2)

variance of the population is 9.522436 mean of the data set is 6.625
Then I took 30 random samples from the data set which has 5 elements without replacements.
Mean of the sample mean is 6.6 and variance of the sample means is 1.873103 now I need to compare these population variance & mean with the mean and variance of sample means.
Is there any theory to do that? Please help me to compare them and to ensure the values I got are correct.
Comment: Should it be mean of sample variance instead of variance of sample mean?
Answer: There is definitely theory to this, depending on what you want to conclude from your comparison.
If you would want to check whether the sample is representative for the entire population for instance.
This link gives a superficial idea: https://www.statpac.com/manual/index.htm?turl=compareasamplemeantoapopulationmean.htm
The general idea would be to calculate the probability that such differences occur by random chance, or that they have a structural cause. For this I would refer you to theory on hypothesis testing, p-values & t-testing.
Hope this helps!
Answer: I wrote a little R code to visualize each sample distribution. This shows the law of large numbers visually by sample distribution (there are other, arguably better ways to visualize this).
Basically, we see the probability density of each sample (n = 30). The white vertical line is the population mean. All sample means cluster around the population mean, and if we ran this an infinite number of times, we would end up with sample mean identical to the population mean.

Since I found this on Stack Overflow, here's the code:
require(tidyverse)
set.seed(123)

map_df(1:30,function(x){
  a <- sample(lab6data,5,replace = F)
  as_data_frame(a)
}) %>%
  mutate(sample = as.factor(flatten_dbl(map(1:30,function(x){
    rep(x,5)
  })))) %>%
  ggplot(aes(value,color = sample,fill = sample))+
    geom_density(aes(color  = sample),show.legend = F,alpha = .25)+
  geom_vline(xintercept = 6.6,color = 'white')+
  scale_x_continuous(breaks = seq(1,20,1))+
scale_fill_grey()+
scale_color_grey()+
      theme_bw()+
  theme(panel.grid = element_blank(),
        panel.border = element_blank())


HTML5 Video not showing on Mac OS X (Desktop) CNA (Captive Network Assistant)

Question: I'm building a captive portal for free wifi access. When user connects, the CNA pops up in the screen where my portal is loaded.
Problem: HTML5 video is not being displayed in OS X desktop. Even iPhone can show it, desktop doesn't. I cannot even inspect anything in this evil browser (can it be called a browser? I don't think so).
My video code:
<video id="promo-video" height="100%" width="100%" preload="auto" autoplay="" muted="" webkit-playsinline="" playsinline="">
  <source src="externalUrlToVideo" type="video/mp4">
</video>

Remember, this very same code shows video on iOS (but doesn't autoplay... for now it's a minor problem).
Some screenshots* that may help some. Video should be played in the right column:

CNA doesn't loads video

What happens when I right-click video then  click "Show controls"
Also, when I right-click then click "Open video in a new window", it shows only a video player, but nothing to be showed in it. Obviously, play button doesn't make it work...
Answer: You could try adding the type="" attribute to the source. Include the video MIME-type there, e.g.
type="video/mp4"

Also, I don't think video will autoplay on iOS. Historically it has prevented auto-playing because of data charges for downloading video content. I'm not sure if I recently read somewhere that was changing. From a user perspective it's arguably unfair to hammer their data allowance with auto-playing videos even if the aesthetic or UX is improved by it.
Comment: Safari and other webkit browser are now able to do autoplay on iOS. In android, some browsers are able to autoplay if video is muted. I'm using user gesture when it's not possible. Thanks for the answer, I'm gonna test it and feedback you.
Comment: Did not work =( But it was well observed, just updated my code and my question, thank you. Ps.: can you upvote the question? ty @Taintedmedialtd
Comment: OK, sounds like the browser doesn't support the video format. Few questions:
What browser is it and what version?
Is video/mp4 the correct file format?
Can you tell me where the video is streaming from? E.g. YouTube, Vimeo, locally hosted etc?
How does your browser fare on the "caniuse" support tables for the correct file format: http://caniuse.com/#feat=video - if you go there and look at the sub-features you'll see 4 video formats. Most modern browsers have aligned on mp4 but historically you had to provide more than 1 source to satisfy them all.
Comment: Video isn't hosted locally, but in another amazon server that I use. It's not a regular browser... it's a captive window where user can login and start using free wifi... It's called CNA (Captive Network Assistant) if I'm not wrong. Strange fact is that iOS has also a CNA, and there the video can be played... same thing in Android native browser. Desktop OS X doesn't
Comment: Then I'm out of my depth, never had the pleasure. Did a quick search and found someone with a similar problem: https://forums.developer.apple.com/thread/9981
Someone suggested loading it in an iframe but I don't see that working to be honest.


Linear diophantine equation solution existence

Question: Given the linear diophantine equation
$$ax+by=c $$
I have to show that it has solution if and only if $gcd(a,b)$ divides $c$.
$$1)\Rightarrow $$
Let $m=gcd(a,b)$ then
$$a'x+b'y=c'$$
where $gcd(a',b')=1$, but how can I continue from here?
$$2) \Leftarrow $$
I don't know even how to start. I've never studied seriously number theory until now, and I'm self-studying so this is difficult to me. Any help will be appreciated.
Should I use the division theorem? I mean that, for $a,b\neq0 \in \mathbb{Z}$ there exists numbers $q, 0\leq r <|b|$ such that $a=bq+r$
$$ $$
Answer: $\Rightarrow)$Every number that divides $a$ and $b$ divides $c$, so $gcd(a,b)|c$.
$\Leftarrow)$If $gcd(a,b)|c$, then $\frac{a}{gcd(a,b)}x+\frac{b}{gcd(a,b)}y=\frac{c}{gcd(a,b)}$ has a solution. Here $\frac{a}{gcd(a,b)}$ and $\frac{b}{gcd(a,b)}$ are coprime. In other words, you need to show: if $a,b$ coprime, then there exists $x,y$ such that $ax+by=1$. To show this, you need to use Euclidean algorithm.

Showing $a,b$ coprime $\Rightarrow ax+by=1$.
With loss of generality, assume $a>b>0$. By division we have $$a=bq+r_1$$where $0<r_1<b$. Notice that $gcd(b,r_1)|a$, and hence $gcd(b,r_1)=1$ as $a,b$ coprime. Similarly, we have $$b=r_1q_1+r_2$$with $gcd(r_1,r_2)|b$ and so $gcd(r_1,r_2)=1$ since $b,r_1$ coprime. Continue this division and say it eventually stops at $$r_{n-1}=r_nq_n$$Then $r_n=1$ since $gcd(r_{n-1},r_n)=1$.
For simplicity, let us assume $r_2=1$. Then $r_1q_1=b-1$. Subing in the first equation gives $$aq_1=bq+(b-1)$$which is what you want.
Comment: Yes, and particularly $gcd(a,b)$ divides $a$ and $b$.
Comment: @Nivalth, see my additional explanation.
Comment: Thanks, I'm going to think about this
Comment: the $\Rightarrow$ part. I understand that given the equation, every number that divides $ax$ and $by$ divides $c$ and hence every number that divides $a$ and $b$ divides $c$?. I'm kind of confused with this implication, sorry.
Comment: the $\Leftarrow$ part: I don't see how the equation $ax+by=1$ comes. Does $a$ there mean $a'=\frac{a}{gcd(a,b)}$ and the same for $b$?. I don't see how the Euclidean algorithm may help me showing that $1=ax+by$. Shall I use it to $gcd(a',b')=1$ and find that indeed there exists $x$ and $y$ that solve the equation? Thanks for your time
Comment: May the solution be the Bézout identity?
Comment: Yes, if you can show that when $a,b$ coprime, there exist $x,y$ such that $ax+by=1$, then $acx+bcy=c$ for any $c$, then you can show $ax+by=c$ has solution when $gcd(a,b)|c$.
Comment: hi, I'm still stuck showing that $ax+by=1$ can you give me another hint? Thanks, and sorry, it may seem trivial but this is kind of difficult to me
Answer: m = gcd(a, b)

a = m*i
b = m*j

a*x + b*y = c
m*i*x + m*j*y = c
m * (i*x + j*y) = c

so the first equation have a solution then you should be able to write c in a form:
c = m * k
k = i*x + j*y


searching more than 1 array index values from database in one query

Question: i am doing a search from database. user will enter string. this string will be converted into array then this array indexed values will be checked from table to find the match.
I am using loop to traverse array query execution is in that loop, it searches fine but if there was more than one index to search it shows the last index searched values.
i know know that's not a proper way to search.
how can i do this.
<code>SqlConnection conOpen;
string[] arrayList;
protected void Page_Load(object sender, EventArgs e)
{
    DataLayer datalayer = new DataLayer();
    conOpen = datalayer.connectionOpen();

    string myString = Request.QueryString["searchText"].ToString();
    char[] separator = new char[] { ' ' };
    arrayList = myString.Split(separator);
    for (int i = 0; i <= arrayList.GetUpperBound(0); i++)
    {
        Response.Write(arrayList[i]);

        string asd = arrayList[i];

        String arrayQuery = "Select * from tbl_products where product_name LIKE '%" + @asd + "%'";

        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(arrayQuery, conOpen);
        da.Fill(ds, "tbl_products");
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}
</code>
Answer: I'm too clear on what your final result is supposed to be but I'm going to guess.  I think what you are asking is that you want the query to search for every instance of the search items (seperated by a space) the users put in the input element and return ALL of these findings to your GridView.  Ok.  So I would suggest you loop to "build" your sql statement and then run the sql and bind the data AFTER the loop (not during).
One more important element is that you should most definitely parametrize these values since it's coming from user input in order to prevent SQL-Injection.  Please forgive any typos (it is late).
<code>        DataLayer datalayer = new DataLayer();
        conOpen = datalayer.connectionOpen();

        string myString = Request.QueryString["searchText"].ToString();
        char[] separator = new char[] { ' ' };
        arrayList = myString.Split(separator);
        StringBuilder arrayQuery = new StringBuilder();
        SqlCommand myCommand = new SqlCommand();

        for (int i = 0; i < arrayList.Length; i++)
        {
            if (i==0)
            {
                arrayQuery.Append("Select * from tbl_products where product_name LIKE @asd" + i);
            } else{
                arrayQuery.Append(" OR product_name LIKE @asd" + i );
            }

            myCommand.Parameters.AddWithValue("@asd" + i, "%" + arrayList[i] + "%");
        }

        myCommand.CommandText = arrayQuery.ToString();
        myCommand.Connection = conOpen;
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(myCommand);
        da.Fill(ds, "tbl_products");
        GridView1.DataSource = ds;
        GridView1.DataBind();
</code>
Comment: 'Index was outside the bounds of the array' error on using **.lengh**
Comment: 'Incorrect syntax near the keyword 'LIKE'' , your code looks good but i don't know why it is not displaying any result
Comment: Didn't generating any result.
Comment: Oh right.  Forgot that when I transferred your sql into parameters you need to remove the single quotes.
Comment: Done it you have to use '""product_name""' again in else query


Best approach for time series

Question: What approach would be best for time series that tracked user generate some events (activitie is file creation - from 0 files per day - 18 files per day ). I determined that number of events per day follow negative binomial distribution and I used pseudo random generator to generate / simulate user behavior, but I don t know how to determine time of events(creation). Final goal is simulation of this user so if there is 4 events (user created 4 files that day) when in simulation that will be scheduled durring 24 h. Do I need to filter data in a way to have one data set 1 event/day, second dataset with 2 events/day and so on .. or some other approach.
Answer: SARIMA model https://autobox.com/pdfs/SARMAX.pdf identification is the answer following the ITERATIVE process here https://autobox.com/pdfs/ARIMA%20FLOW%20CHART.pdf . I strongly suggest that you consider approaches that allow for latent determinstic structure to be identified and incorporated as compared to freely available dated solutions that assume that there is no deterministic structure AND no outliers/pulses AND that the model parameters are constant over time AND that model error variance is constant over time.
The true Gold Standard of time series model identification includes an iterative process not just a single list-based presumptive approach that sometime is suggested here. Carefully ask and know the assumptions underlying all statistical tests . Read about A. Wald here https://medium.com/@penguinpress/an-excerpt-from-how-not-to-be-wrong-by-jordan-ellenberg-664e708cfc3d .  A mathematician is always asking, "What assumptions are you making? And are they justified?"
Read closely the advice of @AdamO "The correlogram should be calculated from residuals using a model that controls for intervention administration, otherwise the intervention effects are taken to be Gaussian noise, underestimating the actual autoregressive effect." from Interrupted Time Series Analysis - ARIMAX for High Frequency Biological Data? . In layman's words don't over-trust or over-believe the acf/pacf if there are possible untreated deterministic structure in your data.

Best approach for time series


PySide Node Graph connect items

Question: The purpose of this code is node graph kind of UI.
Double click creates rectangles and right click connects them with line. If you move on of the rectangle the corresponding end of line moves with it. The problem is that the line moves only with first two rectangles. If you create another pair of rectangles and connect them with line it stops moving. I have started to learn PySide/PyQt recently so maybe I don't understand all code.
Here is the code:
https://github.com/cyberiRex/irex/blob/master/nodeGraph
Comment: I just understand, please [edit](https://stackoverflow.com/posts/46142167/edit) and improve the explanation of your question
Comment: Although it lacks verifications to your code this works, I obtain the following having certain provisions like adding the following `if event.button() == Qt.RightButton:
            if len(self.selectedItems()) == 2:`.In the end I get the following: http://imgur.com/a/TtEeQ
Comment: Yes, but curve does not updates.
Comment: To what curve do you mean, to the red line ?, explain yourself better please.
Comment: You want the red lines to move when the rectangles move?
Comment: Yes. Actually, the line moves but only if there are only two rectangles in the scene. If you create another pair of rectangles and connect them with red line it does not moves.
Answer: The Code that generates this error is the following one:
self.selectedItems()[0].linkToItem = item
self.selectedItems()[1].linkToItem = item

Let's say that one node is already connected to another by a link, when another link is added, the previous link is removed, which is why they are disconnected.
The logic like this will continue generating similar errors so the solution I propose is a new solution logic, for this I base on the following example Elastic Nodes Example. From what you can take as a basis to understand the logic of my solution, obviously I have made some variants to meet your requirements.
In a first part I have replaced the base classes to QGraphicsRectItem and QGraphicsLineItem to reduce implementation. The logic is based on giving each Edge 2 Node to which they connect so that when it is updated take as reference to the nodes. in addition each node stores a list of the edges so that it executes the update every time the node is moved. The following code implements the above:
class SceneClass(QGraphicsScene):
    grid = 30

    def __init__(self, parent=None):
        QGraphicsScene.__init__(self, QRectF(-1000, -1000, 2000, 2000), parent)

    def drawBackground(self, painter, rect):
        painter.fillRect(rect, QColor(30, 30, 30))
        left = int(rect.left()) - int((rect.left()) % self.grid)
        top = int(rect.top()) - int((rect.top()) % self.grid)
        right = int(rect.right())
        bottom = int(rect.bottom())
        lines = []
        for x in range(left, right, self.grid):
            lines.append(QLine(x, top, x, bottom))
        for y in range(top, bottom, self.grid):
            lines.append(QLine(left, y, right, y))
        painter.setPen(QPen(QColor(50, 50, 50)))
        painter.drawLines(lines)

    def mouseDoubleClickEvent(self, event):
        node = Node()
        self.addItem(node)
        node.setPos(event.scenePos())
        QGraphicsScene.mouseMoveEvent(self, event)

    def mousePressEvent(self, event):
        if event.button() == Qt.RightButton:
            if len(self.selectedItems()) == 2:
                edge = Edge(self.selectedItems()[0], self.selectedItems()[1])
                self.addItem(edge)
        QGraphicsScene.mousePressEvent(self, event)

class Node(QGraphicsRectItem):
    def __init__(self, rect=QRectF(-75, -15, 150, 30), parent=None):
        QGraphicsRectItem.__init__(self, rect, parent)
        self.edges = []
        self.setZValue(1)
        self.setBrush(Qt.darkGray)
        self.setFlags(QGraphicsItem.ItemIsMovable |
                      QGraphicsItem.ItemIsSelectable |
                      QGraphicsItem.ItemSendsGeometryChanges)

    def addEdge(self, edge):
        self.edges.append(edge)

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemSelectedChange:
            self.setBrush(Qt.green if value else Qt.darkGray)

        if change == QGraphicsItem.ItemPositionHasChanged:
            for edge in self.edges:
                edge.adjust()

        return QGraphicsItem.itemChange(self, change, value)

class Edge(QGraphicsLineItem):
    def __init__(self, source, dest, parent=None):
        QGraphicsLineItem.__init__(self, parent)
        self.source = source
        self.dest = dest
        self.source.addEdge(self)
        self.dest.addEdge(self)
        self.setPen(QPen(Qt.red, 1.75))
        self.adjust()

    def adjust(self):
        self.prepareGeometryChange()
        self.setLine(QLineF(self.dest.pos(), self.source.pos()))

Obtaining what is shown in the following image:

The complete example can be found in the following link

PySide Node Graph connect items


Div nesting issue with Gumby framework grid

Question: Using the Gumby Framework I'm encountering issues nesting divs.
I'm trying to nest a three and seven column grid within a ten column grid.
I've tried a few variations with my HTML/CSS to no avail. Figure I must be missing something fairly simple.
Site Link
HTML code example:

Text removed

Core Services

Comment: What are you specifically trying to make this area of your page look like?
Comment: Just to mention: you can't use class names starting with number (100width).
Comment: Good catch! I know better too.
Answer: The framework isn't "smart". Everything is based on 12 or 16 columns. So you've got to do all the thinking for things of this nature. If you want a 3-7 centered container within a 12 column grid, the following code does just that:

3 col

7 col

Here's why: 10 columns = 10 of 12(for argument's sake), 3 columns and 7 columns within that container are actually a 30% of 12 column next to a 70% of 12 column residing inside a 83.333% of 12 column container. Throwing class="ten columns" on the container doesn't fire some kind of recursive function to "reset" the container as a 10 column grid system; thus,  the goofy margins, padding, etc. It's actually working as expected. Hope that makes sense.
Comment: Just to make sure I'm following you on this: The framework is using its normal percentage based values, but when it comes to nesting, 100% of the containing DIV isn't the equivalent to 100% of the 12 columns grid.
Comment: No, it is not 100% of the 12. It's now 100% of parent container 10, which is quite a bit narrower than 12. Easiest way to see this in action: `div { outline:1px dotted; margin:5% }`, then `` Obviously, #3 will be much narrower than #1. To your dilemma, you could write some CSS to accomodate your one-off situations: `.ten.columns > .three.columns {...} .ten.columns > .seven.columns {...}`
Comment: Another method, if you don't like the one above: | 1 Col | 3 Col | 7 Col | 1 Col |. Still...it's up to you, the author, to wrap your head around how 10col actually works within the confines of that framework.
Comment: Thank you so much. My comments wasn't clear, I get now it's 100% of the 10 rather than the 12. So it all makes sense. Just thought initially that the framework was somehow able to account for that in the nesting. I think it's because we're used to using 960.gs
Comment: One more thing, as a generality is it even possible to match widths within nested grids? If 5 columns is 29.7% of the full 16 column grid I'm assuming in most cases it would be impossible to match the fixed width (280px with 5 columns) using columns in a nested grid?
Comment: It's absolutely possible, but the math makes my head hurt. Here's a simple design:** **http://jsfiddle.net/Ejzws/** **It's fluid (percentage based), and nested. (Keep in mind, all that CSS for just nesting a pair of singles.) - oh...and that last column is mislabeled as nested


How to get a filter option like SSMS with Visual studio's Server explorer?

Question: I am using Linq to Sql, for which I am using Visual Studio's Server Explorer to drag and drop stored procedures.
Now the thing is my database has around 200-300 stored procedures, and searching for the stored procedure I want becomes a task in itself.
I was wondering if there is a way I could use filter like I remember using with Sql Server Management Studio.
Any Ideas ?
Answer: Yes, install the Productivity Power Tools extension. That will add a new "Solution Navigator" tabbed control, from which you can make a "global" text search in your solution.
It will show you everything that matches the partial entered text (xml files, cs files, classes, methods, etc).
That is very close to what you need.


How to set kint() to be closed by default?

Question: I find that when expanding Kint widgets, if the object is sufficiently large, the loading time can be quite slow. It appears, when you expand the root level, it also expands child objects. I would prefer that it keeps all children closed until I decide to expand; although I'm not sure if this will have any impact on performance.
Where can I configure Kint for Drupal?
Comment: It's all closed by default on my version. Which version of Drupal and Devel are you using ?
Comment: 8.1.0 and 1.x-dev latest at time of writing. Just to clarify, it's closed by default at the root level - it's when you expand it, child objects tend to be expanded as well. I find myself having to go through and collapse them manually.
Comment: That's stragne because it's not like that on my side using same version as yours.
Answer: I know this is an old question, but I just figured this out and this question comes up first on google.
The option is already there. What you need to do is click next to the plus sign (the text next to it) not the actual plus sign itself. Clicking the plus sign will expand everything, clicking the title, path or array key will just expand the immediate node below it.
I went through almost a whole project thinking Kint() unusable when it's really just a confusing UI choice.
Comment: Doesnt help that much, its expanded by default, and I have to click on all the variables roots that I don't want opened.


Segmentation fault (core dumped) in a simple C code

Question: I am new in C. I am referring to the book "The C Programming Language" by Brian W Kernighian and Dennis Ritchie.
There is a code for pointer increment and assignment given in the book as follows.
#include<stdio.h>

int main()
    {
        char *s = "Goal";
        char *t = "Home";
        while(*s++ = *t++) printf(*s);
        return 0;
    }

The code is saved and compiled using the command
gcc ptr.c -o ptr -std=c99

Now on running the code by running command
./ptr

I get the following error

Segmentation fault (core dumped)

The error seems to be inside the while loop condition.
But the code is exactly as given in the book.
What am I missing?
Comment: @starblue It's not. As K&R noted it: "Although this may seem cryptic at first sight, the notational convenience is considerable, and the idiom should be mastered, because you will see it frequently in C programs."
Comment: Note that `while(*s++ = *t++)` is absolutely horrible style.
Comment: @JSmyth Have you considered that K&R might be wrong?
Comment: @starblue i.e. wrong commenting on the style of the language they introduced by their very own selves? If what you wanted to say was that there's a better, widely adopted way of doing the same - please share here.
Comment: You should avoid putting assignments in the middle of expressions, as that quickly becomes unreadable or even results in unspecified behavior. Here we have three assignments, including `=`, which can easily be confused with `==`, which will generate a warning if sensible compiler options are used.
Comment: @starblue what would those sensible compiler options be? Just wanna try myself if I get a warning. I will use GCC.
Answer: s and t are both string literals, and you can't modify a string literal. But this piece of code
*s++ = *t++

will modify s, which causes segmentation fault.
To fix it, use a char array. I also modified the printf part to make it legal.
#include<stdio.h>

int main()
{
    char arr[] = "Goal";
    char *s = arr;
    char *t = "Home";
    while(*s++ = *t++)
        ;
    printf("%s\n", arr);
    return 0;
}

However, I think this program is better done using an individual function to copy the string, the program will look clearer.
#include<stdio.h>
void my_strcpy(char *s, char *t);

int main()
{
    char s[] = "Goal";
    char *t = "Home";
    my_strcpy(s, t);
    printf("%s\n", s);
    return 0;
}

void my_strcpy(char *s, char *t)
{
    while(*s++ = *t++)
        ;
}

Comment: ummm, if you do that then `s++` won't compile
Comment: After changing `char *s = "Goal";` to `char s[] = "Goal";`, the program would not compile. I get the following error on compilation. `ptr3.c: In function 'main':
ptr3.c:7:10: error: lvalue required as increment operand
`
Comment: @ajb Fixed. I guess the original program in the book is supposed to pass `s` as a function argument though. In that way, it will decay to a pointer.
Comment: still not fixed, it's still going to try to read at a bad address
Comment: This code seems to fix all the problems. But I do need to understand what error was I making. Can you explain?
Comment: @user2801303 The error is that you try to modify a string literal. I added a second program, that should be a better version. Remember that when array names are passed as function argument, they decay to a pointer.
Comment: If you copied the program straight out of the book, then the error was either (1) you typed something wrong, or (2) you copied a program that the authors were giving you as an example of what **not** to do.  Unfortunately, I don't have the book so I can't really give you an answer.
Comment: The my_strcpy function as mentioned by @YuHao was exactly what was given in the book.
Answer: The problem is that printf expects the first parameter to be a char *, that is, something that points to a character, or the address of a character.  When you say printf(*s) you're passing it an actual character, i.e. a number from 0 to 255 or -128 to 127, and the program is going to treat that number as an address, which isn't going to be a valid address on your system.
Comment: Even when I change the printf statement to something trivial like `printf("hello");` inside the loop, I get the same error. This implies that the problem is not within the printf statement.
Comment: @user2801303 There were two problems.  One was inside the `printf`.
Answer: When ever we say *s = "hello" , s is pointing to an address which is present in text segment("hello" goes into text segment). So obviously changing the value of text segment results in SEGV termination.
And for s[] = "hello" if we do *s++, we are incrementing (modifying) the base address so we got "lvalue required as increment operand" error.


List value of a dict goes infinite depth during iteration

Question: Here is a puzzling question. I have a dict with list values. I iterate over this dict twice: a normal iteration first, and then a second iteration where I assign an index to the iteration variable. This ends up modifying the last dict value and it becomes of infinite depth (the 3 dots signify that the list is infinite depth).
Here is a simple example:
Input Code:
a = {1 : [2], 3: [4]}

for i,j in a.items():
  pass

for i,j[0] in a.items():
  pass

print(a)

Output:
{1: [2], 3: [[...]]}

How does this happen?
Comment: If you skip the first iteration, you would get an error because you can't reference `j[0]` if `j` has not been defined.
Comment: @khelwood Thanks. Yes. I had a `j` from a previous run, so it wasn't showing error for me. But yes it will show error in a fresh run. I am modifying the quesiton.
Answer: At the end of your first iteration, j is the last value in your dictionary, [3].
You then iterate through the dictionary again, setting j[0] to each value in the dictionary. Since j is referring to a list inside your dictionary, it is that list inside the dictionary that you are altering. And the final effect of the alteration is that j[0] is the last value in the dictionary: j itself.
If you skipped the first iteration, you would either get a NameError because you can't reference j[0] without first defining j; or you would be mutating some different list from a previous usage of the variable j.


What is the use of class MouseMotionAdapter when we have class MouseAdapter?

Question: I create the following applet-->
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Adapting extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseAdapter(this));
}
}//end of class

class MyMouseAdapter extends MouseAdapter
{
Adapting a;
public MyMouseAdapter(Adapting a)
{
this.a=a;
}

public void mouseClicked(MouseEvent me)
{
a.setBackground(Color.red);
}

public void mouseMoved(MouseEvent me)
{
a.showStatus("Moving Mouse at "+me.getX()+","+me.getY());
}
}
/*<applet code=Adapting height=500 width=600></applet>*/

For both the listeners corresponding to MouseEvent, i.e MouseListener and MouseMotionListener, i use the adapter class MouseAdapter. If, the MouseAdapter class is getting my work done for listening Mouse Motion Events also, what is the use of the class MouseMotionAdapter ?
Comment: May be it was created to keep a naming convention. You have a `MouseAdapter` for `MouseListener` and correspondingly a `MouseMotionAdapter` for `MouseMotionListener`.
Answer: MouseAdapter implements more interfaces and contains more methods than MouseMotionAdapter, so it can be more cumbersome to use in an IDE and perhaps have some minor performance implications.
If you need a MouseListener as well as a MouseMotionListener, you should use a MouseAdapter. If you don't need the MouseListener aspect, then you can use MouseMotionAdapter. Since you seem to be overriding mouseClicked, which is declared in MouseListener, stick with MouseAdapter.


Where to fulfill a variable to show in view file?

Question: I want to show a dropdown in a form in a Yii project with for items. I know I can use
echo $form->dropDownList($model,'element_id', $Options);

in _form.php view file.
Where is the best place to fulfill $options variable ? in which file ? view ? controller ?
Answer: The current model is the best option for this purpose because _form.php has access to the model and so you can get the data easily. While you can pass data from the controller to _form.php, this is more work.
If you want to populate data from the database - for example, you want to show countries from a database table tbl_countries - you can write a function in your model to load them:
/* Get all countries. */
public function getCountries(){
  $allCountries =  Countries::model()->findAll();
  return CHtml::listData($allCountries, "id", "name")
}

This will give you an array with the id numbers as keys and the country names as values. You can then call this function from your view file:
echo $form->dropDownList($model,'element_id', $model->countries());

Answer: You should pass your variables from your controller to your view. The data in your variable should come from a model.
Answer: $options will be used in more views? if the answer is yes, i would put it on the main controller (the one all your controllers extends) or in the main.php.
If that variable will be used just in one view and regards to clases, ids, the place should be in the same view


Using brackets/parentheses in EBNF or GNU Bison grammar

Question: I am defining my own grammar for a parser generator that outputs C/C++ code. I chose Bison for this, but have run into a problemm. I would like to use brackets ("(", ")") within rules, but Bison doesn't accept themFor example, to declare a character I use (the three dots are instead of all other possible ASCII characters):
character: "'" ("\0" | "\t" | "\n" | " " | "!" | ... | "}" | "~") "'";

As you can see, I use brackets to say that a character must have a quotation mark, any character and then another quotation mark.
I do something similar for an integer:
integer: (["-"] digits) | "0";

Is there any way of achieving something similar in Bison? Alternatively, is there a parser generator that accepts EBNF, or even just brackets and that outputs c++ code?
Comment: Normally, the lexical analysis should be done in flex
Answer: Bison does not support EBNF, only BNF, so if you want optional or grouped things, you'll have to write the rule yourself:
character: '\'' character_char '\''
character_char: '\0' | '\t' | ...

integer: opt_negate digits | '0'
opt_negate: | '-'

Also, note that " characters in bison don't denote literals, so won't do what you want (and are generally useless, as you can't refer to them easily in the lexer).  Always use ' -- single quotes -- for literal.
In addition, anything that can be recognized by a regular expression (like these examples), should probably be recognized in the lexer and returned to the bison parser as a single token -- it's much simpler, clearer, and more efficient.


How can I create a packet capture file on a headless server for a single process?

Question: I'm writing a python script on a headless server, and I'd like to see the packet capture output for the script.
I can't run ettercap or Wireshark on the server as there is too much other noise (besides, wireshark is a GUI tool). I do  have sudo access, however.
Is there any way that I can capture the packets generated by that script only? Preferably in a format that can be loaded into Wireshark (Not mandatory, however, I can trudge through the text if necessary)
Comment: Try tcpdump and some filters.
Comment: or TShark, bundled with Wireshark: http://ask.wireshark.org/questions/5800/wireshark-from-command-line
Answer: Wireshark has a command line utility. I have used it on remote computers where I only had console access, it works quite well. Takes only a few minutes of reading the parameters to learn how to use it.
C:\Program Files (x86)\Wireshark>dumpcap.exe -h
Dumpcap 1.10.3 (SVN Rev 53022 from /trunk-1.10)
Capture network packets and dump them into a pcapng file.
See http://www.wireshark.org for more information.

Usage: dumpcap [options] ...

Capture interface:
  -i <interface>           name or idx of interface (def: first non-loopback),
                           or for remote capturing, use one of these formats:
                               rpcap://<host>/<interface>
                               TCP@<host>:<port>
  -f <capture filter>      packet filter in libpcap filter syntax
  -s <snaplen>             packet snapshot length (def: 65535)
  -p                       don't capture in promiscuous mode
  -B <buffer size>         size of kernel buffer in MB (def: 2MB)
  -y <link type>           link layer type (def: first appropriate)
  -D                       print list of interfaces and exit
  -L                       print list of link-layer types of iface and exit
  -d                       print generated BPF code for capture filter
  -k                       set channel on wifi interface <freq>,[<type>]
  -S                       print statistics for each interface once per second
  -M                       for -D, -L, and -S, produce machine-readable output

RPCAP options:
  -r                       don't ignore own RPCAP traffic in capture
  -u                       use UDP for RPCAP data transfer
  -A <user>:<password>     use RPCAP password authentication
  -m <sampling type>       use packet sampling
                           count:NUM - capture one packet of every NUM
                           timer:NUM - capture no more than 1 packet in NUM ms
Stop conditions:
  -c <packet count>        stop after n packets (def: infinite)
  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds
                           filesize:NUM - stop this file after NUM KB
                              files:NUM - stop after NUM files
Output (files):
  -w <filename>            name of file to save (def: tempfile)
  -g                       enable group read access on the output file(s)
  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs
                           filesize:NUM - switch to next file after NUM KB
                              files:NUM - ringbuffer: replace after NUM files
  -n                       use pcapng format instead of pcap (default)
  -P                       use libpcap format instead of pcapng

Miscellaneous:
  -N <packet_limit>        maximum number of packets buffered within dumpcap
  -C <byte_limit>          maximum number of bytes used for buffering packets wi
thin dumpcap
  -t                       use a separate thread per interface
  -q                       don't report packet capture counts
  -v                       print version information and exit
  -h                       display this help and exit

Example: dumpcap -i eth0 -a duration:60 -w output.pcapng
"Capture packets from interface eth0 until 60s passed into output.pcapng"

Use Ctrl-C to stop capturing at any time.

Answer: Yes, you can with iptables and dumpcap. Summary:
# iptables -A OUTPUT -m owner --pid-owner 1000 -j CONNMARK --set-mark 1
# iptables -A INPUT -m connmark --mark 1 -j NFLOG --nflog-group 30
# iptables -A OUTPUT -m connmark --mark 1 -j NFLOG --nflog-group 30
# dumpcap -i nflog:30 -w pid-1000.pcap

This will capture all traffic with process ID 1000. These command have to be run on the host itself (which is where the PID info is available).
Answer: Another option is to pipe dumpcap output over SSH into wireshark running in on your local machine.
wireshark -k -i <(ssh -l USER REMOTEHOST "dumpcap -i lo -P -w - -f 'not tcp port 22'")

This will open an instance of wireshark locally displaying traffic from the remote machine. You will likely want to amend the filter not tcp port 22 to prevent piping too much traffic across the network.


React - synchronous txt file to string?

Question: I'm absolutely baffled by this one...
In my React project with create-react-app, I have a standalone js file in which I'd like to read a string from a txt file.  The txt file is part of a project and not on a server.
I can't seem to find any answers of how to complete this seemingly trivial task in a synchronous manner.  These would seem like obvious options:
import text from './data/text.txt';

const text = require('./data/text.txt');

Both lines above return a new path that includes /static/media/, which I can access through localhost in the browser, but that doesn't help me.
I can use JSON but it's almost a matter of principle at this point.  It just seems ridiculous that I can't read a simple txt file.
Comment: It is not a trivial task in react (a client side library). You should have a input with type `file` and then use `FileReader` object or `Blob` to read content of the file.
Answer: You can use webpack raw-loader to directly import raw files into your project.
Install:
$ npm install raw-loader --save-dev

Config:
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.txt$/i,
        use: 'raw-loader',
      },
    ],
  },
};

Usage:
import text from './data/text.txt';
console.log(text);  // This line will print out the content of the text file in the console

React - synchronous txt file to string?


How to set up equations to find the volume for solid of revolution?

Question:
Let $R$ be the region bounded by the graphs of $y =\sqrt x$, $y=2$, and $x=0$.
Find the volume of the solid generated by revolving $R$ about the $x$-axis;
Find the volume of the solid generated by revolving $R$ about the $y$-axis;
Find the volume of the solid generated by revolving $R$ about the line $x = 4$;
Find the volume of the solid generated by revolving $R$ about the line $y = 2$.

I am trying to set up these integrals, I know how to solve them but I always have a hard time setting them up, any help would be greatly appreciated :)
Comment: I would suggest to draw a picture. Then sketch what each of the solids look like.
Comment: It is easier if we see how you are setting them up and point out if there are mistakes or you show your effort and tell us where you are stuck. Sketching should help as called out by Matti P.
Answer: First off, a (correct-ish) drawing always helps. Always.
Also, practice. There is no way around it: in order to really learn how to do this well enough to be confident you can do it on an exam, you just have to do it a bunch of times. No amount of answers on math forums or videos on youtube is going to change that.
With that said, here is a quick breakdown of the standard method:

Decide whether you want to integrate with respect to $x$ or $y$ (the final form of the integrand depends on this choice in relation to the axis of rotation)
Divide whatever axis you chose to integrate with respect to into little pieces
Slice up the plane region we're after into strips according to the division form point 2
Rotate these slices the same way as the whole region, find the volume of each small corresponding figure, this is your integrand

The dependence mentioned in point 1 determines the basic shape of the figures in point 4, and from here the two names "washer method" and "(cylindrical) shell method" are born. I'll do the first two problems, both times integrating with respect to $x$, to illustrate both methods.
So, without further ado, here is a drawing of the relevant region of the plane:

This you should be able to do on a piece of paper. If not exactly, then at least a close enough sketch to recognize the basic shape, to determine distances, and to determine intersection points. It is also more important than the two other figures in this answer.
The actual volumes are a bit harder to draw, but if you can sort-of imagine them from the above figure, you'll be in pretty good shape. Anyways, here is the result of taking the above figure, and rotate it about the $x$-axis:

The volume we are after is the region that is between the green parabola and the blue plane, and inside the red cylinder.
Since we are integrating with respect to $x$, we divide the $x$-axis into many small pieces of width $\Delta x$ (for simplicity, say they are all equally wide). For each narrow piece, there is a corresponding strip of the planar region. Now rotate such a strip about the $x$ axis. It will look a like a coin with a hole in it (except perhaps the very first and the very last slice). If you've ever been to a hardware store and bought washers, that's exactly what they look like. Hence the name for this method: the washer method.
We want to add together the volume of each little washer-shaped slice. If the slices are thin enough, it won't matter much that the inner hole in the wacher has a slanted edge. We can just pretend that it is a flat cylinder with a cylindrical piece missing. The volume of such a slice is the volume of the large cylinder minus the volume of the small cylinder.
More symbolically, let's take the slice at some particular value $x$ along the $x$-axis. The slice has width $\Delta x$, the outer radius of the cylinder is $2$, and the inner radius is $\sqrt x$. The volume of the slice is therefore
$$
\pi\cdot 2^2\cdot \Delta x - \pi\cdot \sqrt x^2\cdot \Delta x = \pi\left(2^2 - \sqrt x^2\right)\Delta x
$$
This is basically all done now. The range of valid $x$-values (i.e. the $x$-values for which our volume exists) is $0$ to $4$. As we take thinner and thinner slices, the sum of the volume of all of them turns into an integral as $\Delta x$ turns into $dx$, and we get
$$
\int_0^4\pi\left(2^2-\sqrt x^2\right)dx
$$
What about rotation about the $y$ axis? In that case, the region ends up looking something like this:

Which is to say, the volume we're after is the upside-down mountaintop that lies between the green bowl and the red plane. Again, we integrate with respect to $x$, so we divide the $x$-axis into small pieces of width $\Delta x$. Again slice the planar region into vertical strips, but this time rotate them about the $y$-axis. The resulting figure will now be a thin-walled tube / pipe, rather than a flat washer. This is where the name comes from: the cylindrical shell method.
We are after the volume of each shell, and from there want to sum them up to get the volume of the entire figure. So, take an arbitrary $x$-value. What is the volume of the corresponding shell? The shell is a cylinder with a smaller cylinder taken out. The volume is the difference between these two.
More symbolically, they both have height $2-\sqrt x$, the inner cylinder has radius $x$, and the outer cylinder has radius $x + \Delta x$. So its volume is
$$
\pi\left(x + \Delta x\right)^2(2-\sqrt x) - \pi\cdot x^2\cdot(2-\sqrt x) = \pi\left(2x\Delta x + \Delta x^2\right)(2-\sqrt x)
$$
And here we get to another part of integral calculus that might seem hand-wavey: If $\Delta x$ is small enough, then $\Delta x^2$ is vanishingly small compared to $2x\Delta x$ for all but the innermost few shells. So as we pass to the limit of $\Delta x\to 0$, we can just ignore the squared $\Delta x^2$ term. And thus we have our integrand. Again, the bounds for $x$ is $0$ to $4$. So the volume becomes
$$
\int_0^4\pi\cdot 2x\cdot(2-\sqrt x)dx
$$


How to preview *.docx and *.xlsx inside the application using Library like 'ngx-doc-viewer2'

Question: It's been 3 days, I am searching for a solution to display my *.docx and *.xlxs file in my angular application. I have an API which is returning the files as blob. Now, I want to use that blob to show the file. I can easily download the file using window.open(blobLink), however, my main task was to view the file. So, I searched and found ngx-doc-viewer and it does not work with the blob link as I currently found and file needed to be publicly accessible. But, my application will run in the local network. So, how can I solve this problem. Here is my *.ts and HTML code below=>
TS
getFile(fileData: File) {
        this.tempBlob= null;

        this.ProposalService.getFile(fileData).subscribe(
            (retFileData: any) => {
                this.tempRetFileData = retFileData;
            },
            (err: Error) => {

            },
            () => {
                const blob = new Blob([this.tempRetFileData], { type: this.contentType });
                this.docURL = window.URL.createObjectURL(blob);
            }
        );
    }

HTML
<ngx-doc-viewer [url]="docURL" viewer="google" style="width:100%;height:50vh;"></ngx-doc-viewer>

Answer: For blob type use viewer="mammoth":
<ngx-doc-viewer [url]="docURL" **viewer="mammoth"** style="width:100%;height:50vh;"></ngx-doc-viewer>

To use mammoth, also add:
npm install mammoth --save

and make sure mammoth.browser.min.js is loaded. For the angular/cli you would add the following in angular.json:
    "scripts": [
        "node_modules/mammoth/mammoth.browser.min.js"
    ]

Comment: not working for me... Is it works for anyone.. can we preview document from local blob url?


do the sum of two commerce_price field with programming api

Question: I want to do the sum of two commerce_price fields and set the result in another one.
i've tried to just add the related ['amount'] values and set the result into another price field but it looses the components (VAT, taxes...).
Is there a commerce api call to do that ?
Such as :
<code>add_price($price1,$price2)
</code>
returning the full added price with all it's component ?
Thx
Answer: There is no basic price addition function, though we have API enhancements on the roadmap for Commerce 2.x. I'd take a look at what commerce_order_calculate_total() is doing to figure the order total price field; you have to sum the amounts, like you've already discovered, and you then use commerce_price_components_combine() to merge the two price fields' components arrays together. Hope that helps!