Package all Perl module dependencies?

Question: I've found myself on CentOS without root access, and with a very lame Perl that doesn't even have ExtUtils::MakeMaker.
Does there exist something that could produce an archive of a module's dependencies, for my to unwrap into a directory that I could put into @INC?
Comment: I'd look into building my own perl with perlbrew somewhere that doesn't require root access.
Comment: https://metacpan.org/release/App-FatPacker
Comment: That's my last resort, I'm working with the Perl Virtue of Laziness....
Comment: I usually find perlbrew to be a lot more satisfying for my laziness then trying to cope with environment support for modules :)
Answer: use App::cpanminus
cd ~/bin
curl -LO http://xrl.us/cpanm
chmod +x cpanm

export ROOT=/some/directory
export PERL5LIB=${ROOT}/lib/perl5

Then, install ExtUtils::MakeMaker and Module::CoreList.  You can't do a simple installation because these modules are used by cpanm, and it doesn't look in the unpacked source directory for them.  So, get cpanm to download them, and do a semi-manual install. It actually installs three distributions (the above two and ExtUtils::Install), which is why you get to invoke the build mantra three times:
PERL_MM_OPT=INSTALLBASE=$ROOT ./cpanm -L $ROOT --look ExtUtils::MakeMaker Module::CoreList
perl Makefile.PL
make && make install
exit
perl Makefile.PL
make && make install
exit
perl Makefile.PL
make && make install
exit

It unpacks and cds into each distribution's directory successively. At least that's what happens on a bare-bones CentOS 6 install I just happen to have lying around.
After that, you should be able to install your module and its dependencies via
./cpanm -L $ROOT <module name, or url, or tarball goes here>

Look at the cpanm docs for more info.
Answer: You could use perlbrew to innstall a full new Perl with user access.
http://perlbrew.pl/
#install perlbrew
wget -O - http://install.perlbrew.pl | bash

# install new perl for youurself
perlbrew install perl-5.16.0
# set aliases
perlbrew switch perl-5.16.0

#reinstall all moodules for new perl http://perlbrew.pl/Reinstall-All-Modules-On-New-Perl.html
perlbrew list-modules | perlbrew exec --with perl-5.16.0 cpanm

#how to install/recompile third party modules
https://github.com/lecstor/DevNotes/wiki/Image-Magick-with-Perlbrew

Regards,
Comment: This doesn't answer the question. It tries to solve the same problem in a completely different way that the OP had commented was not acceptable half an hour before the answer was posted.
Answer: Download and untar ExtUtils::MakeMaker, create a directory lib under your home directory, install via:
perl Makefile.PL PREFIX=~/lib LIB=~/lib

Now that module is installed I suggest you use local::lib (easy install via the bootstrap method in the documentation) to install modules:
perl -MCPAN -Mlocal::lib -e 'CPAN::install(MIME::Lite)' # Replace MIME::Lite with what you want to install.

Here MIME::Lite gets installed via cpan to your local lib directory.
Prelbrew won't take long to set up, and you likely have an easier time of things in the long run.
Edit, too long for comment.
@LeeGee Perhaps I wasn't specific enough.
The method described will allow you to get around the restricted version of perl you have access to, and allow installaton of modules to another location.
If you want to package your app on another machine you could use either PAR or pp to create a standalone package of code & modules, or a stand alone executable.
Failing that Module::ScanDeps will find a scripts dependencies
Comment: @LeeGee I've updated my answer, the update was too long for comments. There's no point expecting people to explain downvotes, even if it is playing by the house rules.
Comment: Would be nice to know why this was down-voted. It is not an exact answer, but an explanation for down votes is encouraged by the FAQ, I believe.

Package all Perl module dependencies?


How many ordered pairs of real numbers (a, b) satisfy equality?

Question: $$
\lim_{x\to 0} \frac{\sin^{2}x}{e^{ax}-2bx-1}=\frac{1}{2}
$$
I think it's zero .... I used L'hopital I took the derivative above and below to not get a 0/0 limit. AE was $\frac {0} {(ae ^ {ax}) - 2b}$
Answer: \begin{align}
\lim\limits_{x\to0}\frac{\sin^2x}{e^{ax}-2bx-1}&=\lim\limits_{x\to0}\frac{\sin 2x}{ae^{ax}-2b}& \textrm{(L'H)} \\
&=\lim\limits_{x\to0} \frac{2\cos2x}{a^2e^{ax}} &\textrm{(L'H)} \\
&=\frac{2}{a^2}
\end{align}
Since the value of the limit is independent of $\require{enclose}\enclose{horizontalstrike}{b}$, and $\require{enclose}\enclose{horizontalstrike}{a-2}$ satisfies the limit, there are infinitely many pairs of ordered pairs$\require{enclose}\enclose{horizontalstrike}{(a,b)}$.  The general solution is $\require{enclose}\enclose{horizontalstrike}{(a,b)=(2,b),\ b\in\mathbb{R}.}$
EDIT:  In order to apply L'H in the second step of the calculations, the denominator $ae^{ax}-2b$ has to be equal to $0$ when $x=0$.  Solving:
\begin{align}
ae^{ax}-2b&=0\\
ae^0-2b&=0\\
a-2b&=0\\
a&=2b
\end{align}
Once we have this, recognize that $a=\pm2$ satisfies the limit, and as such, $b=\pm1$.  Therefore, the only real ordered pairs $(a,b$) are $(2,1)$ or $(-2,-1)$.
Comment: Small correction. The general solution should be $(a, b) = (\pm 2, b), b \in \mathbb{R}$
Comment: The condition $a=2b$ needs to hold, otherwise you cannot use L'H in step 2. The only solution acceptable would be $(2,1)$ and $(-2, -1)$.
Comment: Yes, I recognized this right after, writing an edit atm.
Answer: Following the advice of EuxHenH, we use l'Hopital on $\frac{2\sin{x}\cos{x}}{ae^{ax}-2b}$ to get $$\lim_{x \rightarrow 0} {\frac{2(\cos^2{x} - \sin^2{x})}{a^2e^{ax}-2b}} = \lim _{x \rightarrow 0}{\frac{2\cos{(2x)}}{a^2e^{2bx}}} = \frac{2}{a^2}$$
Thus the solution set is $(a, b) = (\pm 2, b) \ \forall \ b \in \mathbb{R}$.


Prove that $\lim\limits_{n\to\infty} \int\limits_X f_nd\mu=\int\limits_X fd\mu$

Question: $(X,\mathscr{M},\mu)$ is a measurable space and $f_n,g_n,f,g$ are all measurable functions defined on $X$. The following conditions are satisfied:
(i) $f_n\to f\;\&\;g_n\to g$ almost everywhere on $X$
(ii) $|f_n|\leq g_n$ and $\int\limits_X g_nd\mu<\infty\;\forall\; n\geq1$
(iii) $\lim\limits_{n\to\infty}\int\limits_X g_nd\mu=\int\limits_X gd\mu<\infty$
Prove $\lim\limits_{n\to\infty}\int\limits_X f_nd\mu=\int\limits_X fd\mu$.
Attempt at answer:
I know that since $f_n,g_n,f,g$ are all measurable, then $|f_n|,|g_n|,|f|,|g|$ are all measurable. Also that $f_n\to f\;\&\;g_n\to g$ almost everywhere on $X$ implies $f_n\to f\;\&\;g_n\to g$ almost uniform convergence on $X$ implies $f_n\to f\;\&\;g_n\to g$ in measure on $X$.
It's almost like "Lebesgue's Dominated Convergence Thm", but I have "almost everyhwere" convergence. Does that make a difference, or am I just making up differences where there are none? Any help/advice would be remarkably useful.
Comment: Your result is effectively the Lebesgue Dominated Convergence Theorem. Almost everywhere convergence (for the purposes of Lebesgue) is the same as regular convergence since the points at which they do not agree is a set of measure zero and these differences won't be picked up by the Lebesgue integral. So you can think of this statement as a slightly more general version.
Answer: Hint: use Fatou's lemma with the sequences $(g_n-f_n,n\geqslant 1)$ and $(g_n+f_n,n\geqslant 1)$.
Note that when $g_n=g$ for all $n$, it's exactly the dominated convergence theorem. This gives a generalization.
Comment: I thought Fatou's Lemma required non-negative sequences.
Comment: So are these sequences, or I missed something? (yes, it does require non-negativeness)
Comment: Why do you think they're non-negative?
Comment: Nevermind...I'm just frazzled and missing the painfully obvoius. Thank you! ^_^
Comment: No problem, the devil is in the details so you are right to check everything is fine.


Integral of random variable

Question: I have an integral I need to evaluate that contains a random variable? How would I go about doing something like that. For instance lets say I have a random variable $C$ with PDF $f_C(x)=1/N \; 0\le x\le N$ (Uniform distribution) and I have an integral
$$
\int\limits_a^bC\mathrm{d}x
$$
Can I evaluate an integral like the above? What if the integral was:
$$
\int\limits_a^bCf(x)\mathrm{d}x
$$
Could I evaluate that integral? If yes, then how?
Comment: The intent of your question is not completely clear to me. You define the density of $C$ over the same variable you're taking the integral over. Did you mean to integrate the density with respect to $dx$? If on the other hand you're integrating the random variable rather than its density, is $C$ a constant (but random) value over the range of $x$, or is it a different, independent, uniform value *at every value of $x$ in $(a,b)$*? Some context might help.
Comment: Ohh okay I think I realize what your saying... now that I've taken a couple minutes off I see that the question actually doesn't make much sense C doesn't have to be inside the integral. It doesn't depend on x.
Answer: Doesn't make much sense. Remember that $C$ is a (measurable) map from $\Omega$ (the underlying sample space) to $\mathbb{R}$. Hence, strictly speaking
$$
  \int_a^b C \,dx = \int_a^b C(\omega) \,dx = C(\omega) \int_a^b  \,dx = C(\omega) \cdot (b-a) \, .
$$
(P.S. When you have a stochastic process $Z:\Omega\times\mathbb{R}\to\mathbb{R}$, then under certain conditions $I:\Omega\to\mathbb{R}$ defined by
$$
  I(\omega) = \int_a^b Z(\omega,x)\,dx
$$
is a random variable. For details, take a look at the classic probability books by Loève, Neuveu and Doob.)

Integral of random variable


Como ler um inteiro sem limite de digitos em C

Question: Tem alguma forma de ler um inteiro do teclado sem controlo de limite de dígitos. Tipo eu preciso de passar um numero gigante via teclado para uma variável e depois passar os todos os dígitos desse numero para os nos de uma  lista. Alguma sugestão?
Comment: Sim, leia em buffer controlado (talvez apenas 100 dígitos por vez?) e mande para uma estrutura de dados chamada `BigInt`.
Comment: como assim? uso a funcao fgets()
Comment: Essa pergunta já passou por aqui, infelizmente não a consegui encontrar
Answer: Você pode usar um buffer de chars grande o bastantes para acomodar os inteiros como uma string.
Operações com números inteiros grandes podem ser feitas com a utilização de uma biblioteca da GNU chamada gmplib.
Segue um exemplo onde os dois argumentos (inteiros grandes) passados para a main() são multiplicados e seu resultado exibido na tela:
#include <gmp.h>
#include <stdio.h>

#define MAX_BUF_LEN    (128)

int main( int argc, char * argv[] )
{
    char res[ MAX_BUF_LEN ];

    mpz_t a, b, c;

    mpz_init(a);
    mpz_init(b);
    mpz_init(c);

    mpz_set_str( a, argv[1], 10 );
    mpz_set_str( b, argv[2], 10 );

    mpz_mul( c, a, b );

    mpz_get_str( res, 10, c );

    printf("%s\n", res );

    mpz_clear(a);
    mpz_clear(b);
    mpz_clear(c);

    return 0;
}

compilando:
$ gcc -lgmp -Wall bigintmul.c -o bigintmul

Testando:
$ ./bigintmul 1234567890123456789012345678901234567890 9876543219876543219876543219876543210

Saída:
12193263124676116335924401657049230176967230591384377380136092059011263526900

Checando:


How to determine if % selecting Option A is statistically different from selecting Option B in a survey?

Question: I ran a survey on pricing and asked respondents to choose between option A or Option B. 61% chose option A and 39% chose Option B. The sample size is 90. How do I determine if the % selection Option A is statistically significant? What test do I run and how?
The cross tab tables show stat tests across the rows (e.g., the % of Group 1 choosing option A is statistically different from group 2 choosing option A). However, I want to compare within the column (i.e., Is the % choosing Option A statistically different from the % choosing Option B at a confidence interval of 95% and 90%)
I would like to do in Excel. Not sure how to use Binom.Dist formula. I have a feeling that would be the right test but I am not certain.
Answer:
I ran a survey on pricing and asked respondents to choose between option A or Option B. 61% chose option A and 39% chose Option B. The sample size is 90. How do I determine if the % selection Option A is statistically significant? What test do I run and how?

Note that with selection among options, the proportions selecting the options are not independent (with two options, there's perfect negative dependence).
Testing if the proportion of A and B are different is the same as testing whether the proportion of A is different from $\frac{1}{2}$.
So if we were to take the number choosing A (55 out of 90) as the number of successes in a binomial, where under the null, $p=\frac{1}{2}$, we can use binom.dist.
The required probability for a two tailed test would be the probability of 55 or more and the symmetrical probability on the other side (but since we have p=0.5 under the null, we can just double the tail area).
binom.dist with the cumulative argument set to be TRUE returns the cumulative distribution function (cdf).
So =1-binom.dist(54,90,0.5,TRUE) is the probability of 55 or more; we need to double that for the two tailed test.
Hence =2*(1-binom.dist(54,90,0.5,TRUE)) is the required p-value (which gives $p= 0.0446$).
But with such large samples, you could easily use the normal approximation (I'd use the continuity correction in the symmetric case)
Comment: I've expanded the abbreviation "cdf" in the answer. You compare the p-value (see the first sentence [here](http://en.wikipedia.org/wiki/P-value)) with your significance level (if $p\leq \alpha$, you reject the null). See also [here](http://stats.stackexchange.com/questions/44769/understanding-p-value), [here](http://stats.stackexchange.com/questions/60825/is-a-p-value-of-0-04993-enough-to-reject-null-hypothesis/72594#72594) and [here](http://stats.stackexchange.com/questions/45889/confused-about-region-of-rejection-vs-p-value)
Comment: Thank you for the quick and great response. I would like to ask a quick follow up. How do I know if the p-value proves a statistically significant or disproves the null? Also, I am not sure what is meant by cdf.
Comment: Very helpful - last question if I may. assuming 95% confidence, would significance be .05 or .025? I assume .05, however, I am not sure if we should divide .05 by two due to the two-tailed test. Thanks again - you are a huge help.
Comment: One more "last" question as well. You used 54 in the formula and not 55. Why 54?
Comment: Because I wanted $P(X\geq 55)=1-P(X<55) = 1-P(X\leq 54)$, where $X$ is the number selecting $A$. (Then of course, I wanted to double that.) ... The first thing follows from the definition of *p-value*, the rest is elementary probability on a variable representing a count.


Writing to file throws TypeError: 'Nonetype' object is not iterable

Question: A file 'modify.txt' contains three cities:
Mumbai
London
Berlin

When I use the write(), I get the error:
for line in lines:
TypeError: 'NoneType' object is not iterable

file_name = 'modify.txt'
with open(file_name, 'a') as my_modifications:
    lines = my_modifications.write("New York\n")

for line in lines:
    print(f"{line.strip()}")

Similar issue persists when I use integers in the write(), I get 'int' object is not iterable.
My objective is to display the updated output from the text file after executing the write()
Comment: Always check [the docs](https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects): *"`f.write(string)` writes the contents of string to the file, __returning the number of characters written__."*
Comment: I've removed my answer since it was off target, but I point out, as edited, you must indent within a context manager, otherwise the file is already closed. I assume this was just a format issue.
Comment: That's because writing to a file (`.write`) does not return a list of lines. What's the behaviour you're expecting?
Comment: What is you goal here? Do you want to write lines to a file, or read them? Why do you expect or even need `write` to return what was written? You already know that as you literally pass it to the method to write... (i.e. `"New York\n"`)
Comment: I have modified the question to explain what I'm trying to achieve. Have eliminated the read() block of code.
Answer: As already mentioned in the comments f.write(string) returns the number of characters written. This means that your variable lines is not iterable. That's why you get an error.
First step (write content to the file)
with open("modify.txt", "a") as f:
    f.write("New York\n")

Second step (read each line from the file)
with open("modify.txt", "r") as f:
    for line in f:
        print(line.strip())


Recording Digital Piano (Headphone Out to a Mono In) with an Audio Interface?

Question: I'm trying to figure out how to record my Roland FP-30 digital piano.
I have a Focusrite Scarlett Solo (2nd Gen), which has only one instrument/line input (I assume it's a balanced mono input, but then again how is it different from an unbalanced stereo since they both have 1 tip + 2 rings?)
Since the FP-30 doesn't have dedicated line outs, I can't use its L/Mono channel to connect to the interface in mono. So I have to use a headphone out for that purpose.
I'd like to know if it's okay to connect an unbalanced stereo signal to a balanced mono and what cable should I use for that?
A regular TRS to TRS stereo cable? A stereo TRS to mono TS cable (though I'm not sure it's going to be any different from using a regular stereo cable)? A stereo TRS to two mono TS splitter (and connect only left channel to the interface)? Will there be any difference between these cables?
I'm asking all that because I heard that it's not safe to connect a stereo output to a mono input without a dedicated adapter that utilizes resistors to prevent back-feeding (have no idea what that adapter is), otherwise there could be damage. It's also good to know these things to avoid problems down the road.
I was also thinking about connecting directly to my laptop's Mic in port (also mono), will it be any better/worse than using my Focusrite Scarlett Solo?
Thanks a lot in advance!
Comment: Not quite a duplicate, but answer is the same: https://music.stackexchange.com/questions/85939/no-sound-is-coming-to-focusrite-scarlett-2i2-when-connected-to-emulated-output-o/85952#85952
Comment: Yeah, except that his audio interface has two line inputs, while mine has only one. My digital piano, on the other hand, has stereo recorded piano sound. Thanks for pointing to that post anyway, since I now know that a regular stereo cable will not work since the input of my interface expects a balanced mono signal. So the question is whether it's better to use a stereo TRS to TS mono cable, or stereo to two mono TS splitter and connect only TS end? Also, not sure about my laptop, which most likely has an unbalanced mono, so doesn't expect balanced signal. Will stereo cable do in that case?
Comment: Also, would be great to hear overall thoughts on how "safe" either of these setups is going to be as well as how much the audio quality is going to suffer except for obviously downgrading from stereo to mono sound?
Answer: Stereo TRS is very different from balanced TRS. You should not use a TRS to TRS cable. It will lead to ugly phasing effects.
The TRS connector in the piano is really only meant to drive stereo headphones. However, it is common to use it as stereo line out. Connecting the left and right signal will force the built in headphone amp to produce a mono mix. It will probably just work, but it is not intended for that.
The TRS connector in the sound interface will be engineered to accept both balanced and unbalanced (mono) signals.
So... Here are your options:

Get a stereo audio interface
Connect with the USB connector (as a midi controller) and use piano sounds from your computer.
Check if your piano has mono sounds (it usually does). Then get a stereo jack to 2 mono jack cable, and connect only one of them with the audio interface.
Just connect with a mono jack cable. It does effectively the same as Your Uncle Bobs suggested custom cable. But note that the headphone plug (and its amp) were not designed for that.
Comment: Note that using a mono cable will result in a 6dB higher noise floor than using a pseudo-balanced cable. But when recording modern equipment that may be less of a concern than when recording vintage analog synths.
Answer: An external USB audio interface will always deliver much better quality that the built-in audio chip in your laptop, so I would definitely try to record the piano that way.
While connecting a headphone output to a line input is not ideal compared to using an actual line-level output, it should work and will not damage anything. Make sure the audio interface is in line-level mode, and not in microphone or Hi-Z guitar mode. Combining the two channels of a stereo output on modern equipment is also unproblematic.
I'd suggest you make a pseudo-balanced cable with two TRS jacks, with at the piano side: wire 1 connected to Tip+Ring, wire 2 connected to Sleeve, cable screen unconnected, and at the interface side: wire 1 connected to Tip, wire 2 to Ring and cable screen to Sleeve.
<code>INSTRUMENT                     INTERFACE

   Tip +
       |
  Ring +---------wire 1---------- Tip

Sleeve ----------wire 2---------- Ring

       ----------screen---------- Sleeve
</code>
Then mark the jacks as input and output, so that you don't accidentally connect it the wrong way round. (You would notice immediately, though. One output channel would be connected to both Tip and Ring at the interface side, so you'd get no sound.)


Independence of linear combinations of random variables

Question: This seems like a straightforward question, but I'm having trouble finding anything on it.
Suppose we have a set of random variables, $X = (X_1,...,X_p)$ (the components of which may not be independent), and another random variable $Y$. If $X \perp Y$ (jointly independent), then is it true that $a^T X \perp Y$, for some vector of constants $a$?
Answer: Yes. Since independence states that the joint probabilty of any sets $\{X \in A\}\;$ and $\{Y \in B\}\;$ equals the product of both probabilities.
Comment: Is your questions answered or do you need a more detailed explanation?
Comment: Thanks for you response and for checking in. I'm not sure I understand the answer. I understand that for $X \perp Y$, $P(X \in A, Y \in B) = P(X \in A)P(Y \in B)$, but what does this tell me about $P(X_1 + X_2 \in C, Y \in B)$ (which is what I'm after with the linear combination idea, where here $p=2$)?
Comment: No problem. $X \perp Y \Rightarrow \forall A_1, ..., A_p, B\colon$

$$P(X_1 \in A_1, ..., X_p \in A_p, Y \in B) = P(X_1 \in A_1, ..., X_p \in A_p)P(Y \in B)$$

which especially holds for all $C$ in your example, since $\{X_1 + X_2 \in C\} \Rightarrow \{X_1 \in \tilde{A}_1, X_2 \in \tilde{A}_2\}$ for appropriate sets $\tilde{A}_1, \tilde{A}_2.$
Comment: Right - thanks very much!


xaml/wpf TabControl how to Stretch using 100% of the screen

Question: Im starting working on this new world, i have some programming background but not at wpf/xaml.
Im having an issue with TabControl.
I dont know why, even using Width="Auto" or HorizontalAlignment="Stretch" i cant figure out how.
Please see this picture to see the result
Im trying that the ending of the tabitem goes to the end of screen use all the space on the right and get fixed, like using width=100%.
can someone help me on this please?
Thanks in advance.
here's the code
<DockPanel Height="auto" Width="Auto" Background="#FFF0EEEE"
               VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
              LastChildFill="True">
        <ScrollViewer IsTabStop="True" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Width="auto" HorizontalAlignment="Stretch">

            <Grid Name="body" Width="auto" HorizontalAlignment="Stretch">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>

                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Grid Grid.Row="0" Grid.Column="0" Width="auto" HorizontalAlignment="Stretch" >

                    <materialDesign:Card Padding="32" Margin="16">
                        <WrapPanel DockPanel.Dock="Top" Orientation="Vertical"  >

                            <TextBlock Style="{DynamicResource H5}">project</TextBlock>
                            <TextBlock FontWeight="Medium" FontSize="14.4" Style="{DynamicResource Roboto}" Width="Auto" HorizontalAlignment="Stretch">
                                <TabControl Margin="10" HorizontalAlignment="Stretch" BorderBrush="#0E5080" BorderThickness="1" Width="auto"  >
                                    <TabItem Header="Home 1" Width="auto" HorizontalAlignment="Stretch">
                                            <TextBlock>asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd </TextBlock>
                                    </TabItem>
                                    <TabItem Header="Home 2" Name="test2" HorizontalAlignment="Stretch">
                                            <TextBlock>asd local</TextBlock>
                                    </TabItem>
                                    <TabItem Header="Home 3" Name="test3" Width="Auto">
                                        <TextBlock>asd ftp</TextBlock>
                                    </TabItem>
                                    <TabItem Header="Home 3">
                                        <TextBlock>asd sftp</TextBlock>
                                    </TabItem>
                                </TabControl>
                            </TextBlock>

                        </WrapPanel>
                    </materialDesign:Card>
                </Grid>

                <Grid Grid.Row="1" Grid.Column="0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="43*"/>
                        <RowDefinition Height="77*"/>
                    </Grid.RowDefinitions>
                    <materialDesign:Card Padding="32" Margin="16,16,16,16" Grid.RowSpan="2">
                        asd
                    </materialDesign:Card>
                </Grid>
            </Grid>
        </ScrollViewer>
    </DockPanel>

Comment: Hi, welcome to SO. I didn't try to run your xaml, but I have a few observations: 1) A TabControl inside a TextBlock? that seems a bad idea. 2) The WrapPanel also seems to me a good panel in this case, could be replaced by a StackPanel. Something that can help you is to color the background of your containers, so that you realize what element need to be set the width
Answer: Replace the wrappanel with a stackpanel. And you had quite some strange and redundant xaml in your code (too many unused grids, textblock surrounding tabcontrol, ...). I cleaned it up a bit. You could remove the dockpanel, too, i guess.
<DockPanel Height="auto" Width="Auto" Background="#FFF0EEEE"
           VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
           LastChildFill="True">
    <ScrollViewer IsTabStop="True" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Width="auto" HorizontalAlignment="Stretch">
        <Grid Name="body">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <materialDesign:Card Grid.Row="0" Padding="32" Margin="16">
                <StackPanel Orientation="Vertical">
                    <TextBlock Style="{DynamicResource H5}">project</TextBlock>
                    <TabControl Margin="10" BorderBrush="#0E5080" BorderThickness="1">
                        <TabItem Header="Home 1">
                            <TextBlock>asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd </TextBlock>
                        </TabItem>
                        <TabItem Header="Home 2" Name="test2">
                            <TextBlock>asd local</TextBlock>
                        </TabItem>
                        <TabItem Header="Home 3" Name="test3">
                            <TextBlock>asd ftp</TextBlock>
                        </TabItem>
                        <TabItem Header="Home 3">
                            <TextBlock>asd sftp</TextBlock>
                        </TabItem>
                    </TabControl>
                </StackPanel>
            </materialDesign:Card>
            <materialDesign:Card Grid.Row="1" Padding="32" Margin="16">
                asd
            </materialDesign:Card>
        </Grid>
    </ScrollViewer>
</DockPanel>

Comment: Dear @Blechdose,
Thank you so much for your answer.
That works perfectly. i will consider your sugestions in the code.
Sorry for the redundant things.. im learning this new world for me.
Thanks again.
Answer: One way would be to use data-binding. If you are new to it, there are several sources out there, e.g.: here or here.
Therefore you could set a name to your WrapPanel and bind the width of the TabControl to the width of the WrapPanel.

<WrapPanel x:Name="MyWrapPanel" DockPanel.Dock="Top" Orientation="Vertical" >
    <TextBlock FontWeight="Medium" FontSize="14.4" >

        <TabControl Width="{Binding ActualWidth, ElementName=MyWrapPanel}" Margin="10" HorizontalAlignment="Stretch" BorderBrush="#0E5080" BorderThickness="1">
            <TabItem IsSelected="True" Header="Home 1" HorizontalAlignment="Stretch">
                <TextBlock>asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd </TextBlock>
            </TabItem>
        </TabControl>
    </TextBlock>
</WrapPanel>

Anyway I would suggest to refactor your XAML as it contains some unnecessary UI-elements.
Comment: Thank you for your help @oRole, i just tested the first solution appear here and it works.


Redis object serialization backwards compatibility

Question: We serialized the following java entity and stored into Redis:
public class Foo {
    public String bar;
}

then our application v2 modified the class Foo as:
public class Foo {
    public String bar;
    public Integer eggs;
    public Datetime happen;
}

Now when application v2 goes into production, in Redis, both Serialized Foo V1 and serialized Foo V2 are stored, and theirfore our application receives exceptions when deserialize objects from Redis. And now I've broken backwards compatibility.
It's not allowed to clean objects in Redis when our application upgrades from v1 to v2 because of business reasons.
Which approach is the best practice to avoid such backwards compatibility issue when design Redis data objects? Thanks.
Comment: This doesn't appear to be an issue with Redis proper as I've done this from c#, but rather possibly an issue with your redis client.  What's the specific error you're getting?
Comment: Agree with @Fred, this is about how you serialized and version your injects as opposed to Redis. You will need to be more specific as to how you are serializing. Are you storing it as JSON, BSON, using msgpack, converting to a custom string representation, or some other way? Without those details the best you can hope for is a general "Search google for serializing java objects to a string" pointer.
Comment: @Fred, The Real Bill, you guys are right, actually it's a object mapping and serialization issue
Answer: I think you can fix it by configuring your JSON library
If you are using Jackson library you have the option to ignore unknown properties by using
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

and if you are using the gson library you can use a cool feature that it has as version, by annotating your java classes with @Version annotation and it gives you the flexibility to have two different version of JSON co-existing together
Hope this helps
Comment: I solved the problem by myself. It's the client deserialization issue and I fixed it. Thank you.


Average Point Estimates but also considering confidence intervals

Question: I'm looking at feature importance. I have a set of point estimates for features I would like to rank from two different models. I also have their confidence intervals.
What is the best way to rank these point estimates while also accounting for the confidence intervals?
I don't think it makes sense to rank point estimates by averaging their magnitude without accounting for the confidence intervals.
EDIT:
Following something similar to this (in the feature importance section where they compare different model feature importance outputs):
https://www.r-bloggers.com/iml-and-h2o-machine-learning-model-interpretability-and-feature-explanation/
Comment: There might be some insights to be gained from meta-analysis which accounts for precision of individual estimates but I do not know how that fits into the machine learning world.
Comment: It sounds similar to the problems of ranking sets of ratings where the ratings are uncertain (e.g. consider ratings out of 5 where one item has two ratings both of 5 stars while another has 100 ratings but an average of 4.8 stars (a few of the ratings were 4 stars, all the rest were 5 stars). Should the item with only two ratings really be regarded as the better of the two? If thats relevant to you, there are several questions on site related to that sort of problem and a search should turn some if them up.
Answer: Have you considered ranking them on the absolute value of their $t$-statistics? Or is there something deeper that I missed?
Comment: Let's say I do a permutation feature importance for two different models. I get their point estimates and confidence intervals for both models. Averaging their point estimates make sense to rank. But does it make sense to average the confidence intervals as well?
Comment: t statistics for what tests?
Comment: $t$-statistics for your point estimates. Your confidence intervals are usually the point estimate $\pm$ some number of standard errors of the estimates. The $t$-statistics are the points estimates divided by those standard errors.
Comment: I don't think you can average those CIs because they are not from the same model and multicollinearity issues could cause them to behave oddly when that amount of uncertainty would not be present in a model with all features. Also... I would never jump to using machine learning concepts before trying something simple from statistics that has been studied in far more depth.
Answer: If the goal is to rank the estimates according to the magnitude of the point
estimates, that seems simple. It is unclear from what you say how or why the the confidence intervals (CIs)
should be involved in the ranking.
If the concern is that some CIs are longer
than others, so that the order of ranking of the true population means
might be different, you can make a graph to show the lengths of the CIs as
well as the point estimates to make it clear that there are some overlaps.
Here are five datasets along with their point and interval estimates.
The five population standard deviations are all the same, but the
sample sizes are different, so the lengths of the CIs also differ.
[Sampling, computations, and graphics in R.]
# sample data
set.seed(804)
x1 = rnorm(30, 50, 5)
x2 = rnorm(25, 55, 5)
x3 = rnorm(35, 60, 5)
x4 = rnorm(30, 65, 5)
x5 = rnorm(35, 70, 5)

# compute means
a1 = mean(x1)
a2 = mean(x2)
a3 = mean(x3)
a4 = mean(x4)
a5 = mean(x5)
a = c(a1,a2,a3,a4,a5);  a
[1] 49.90262 55.30521 58.99290 65.29689 70.16361

# use t test to compute t confidence intervals
CI1 = t.test(x1)$conf.int
CI2 = t.test(x2)$conf.int
CI3 = t.test(x3)$conf.int
CI4 = t.test(x4)$conf.int
CI5 = t.test(x5)$conf.int
CI = cbind(CI1, CI2, CI3, CI4, CI5);  CI
          CI1      CI2      CI3      CI4      CI5
[1,] 47.57335 53.78918 57.36025 63.37359 68.36907
[2,] 52.23188 56.82125 60.62555 67.22020 71.95815

# make plot
mn = min(CI[1,]); mx = max(CI[2,])
plot(1:5, a, ylim=c(mn,mx), pch=19)
for (i in 1:5) {
 lines(c(i,i), CI[,i], col="red", lwd=2) }

There is some slight overlapping of CIs among the samples, but
the ranking of the point estimates seems clear. If you use this style of
graphic, be sure to make it clear that the red lines are CIs.
[In some fields similar plots are used to display standard deviations,
standard errors, or other descriptive statistics.]
In R, the boxplot procedure will show boxplots of a number of
samples with 'notches' in the sides of the boxes showing nonparametric
confidence intervals for population medians. [These CIs are calibrated
for comparing two samples at a time for significant differences.]
boxplot(x1,x2,x3,x4,x5, col="skyblue2", pch=19, notch=T)

Comment: I've edited my question to make it more clear. I think the problem is that I have two models which I want to use to estimate feature importances for the data. I'm averaging the point estimates from both models, but I don't think it makes sense to not consider the confidence intervals. For example one feature could have a large confidence interval and their is high uncertainty for how it should be rank. I want to consider those in rankings.
Comment: You have _changed_ your question--but, for me, not clarified it. You still have two potentially conflicting attributes, sizes of point estimates and lengths of CIs, with no clear criterion how to reconcile them. Seems wrong not to show both both point estimate and CI in a graph or chart. // Maybe rank tops (or bottoms) of CIs. What is the **purpose** of making a ranking? // How would you rank what kind of animal makes the best pet (maybe among: cat, dog, hamster, iguana, parakeet, parrot)?


What references should be cited to support using 30 as a large enough sample size?

Question: I have read/heard many times that the sample size of at least 30 units is considered as "large sample" (normality assumptions of means usually approximately holds due to the CLT, ...).  Therefore, in my experiments, I usually generate samples of 30 units. Can you please give me some reference which should be cited when using sample size 30?
Comment: Acceptance of n=30 as boundary of small and large samples is not well supported by any statistical technique.
Comment: Without reference to the number of parameters you try to estimate, or equivalently the kind of model your are working with, it seems rather difficult to give you a clear answer.
Comment: One reference you can now cite (as of 2013) for why 30 units is *not* necessarily sufficient -- and showing that there can be no correct reference supporting your claim -- appears here on CV at https://stats.stackexchange.com/questions/69898.
Answer: Actually, the "magic number" 30 is a fallacy. See Jacob's Cohen's delightful paper, Things I Have Learned (So Far) (Am. Psych. December 1990 45 #12, pp 1304-1312). This myth is his first example of how "some things you learn aren't so".

[O]ne of my fellow doctoral candidates undertook a dissertation [with] a sample of only 20 cases per group. ... [L]ater I discovered ... that for a two-independent-group-mean comparison with $n = 30$ per group at the sanctified two-tailed $.05$ level, the probability that a medium-sized effect would be labeled as significant by ... a t test was only $.47$. Thus, it was approximately a coin flip whether one would get a significant result, even though, in reality, the effect size was meaningful. ... [My friend] ended up with nonsignificant results–with which he proceeded to demolish an important branch of psychoanalytic theory.
Comment: Beautiful reference--and spot on relevant.  Thank you.
Answer: The choice of n = 30 for a boundary between small and large samples is a rule of thumb, only. There is a large number of books that quote (around) this value, for example, Hogg and Tanis' Probability and Statistical Inference (7e) says "greater than 25 or 30".
That said, the story told to me was that the only reason 30 was regarded as a good boundary was because it made for pretty Student's t tables in the back of textbooks to fit nicely on one page.  That, and the critical values (between Student's t and Normal) are only off by approximately up to 0.25, anyway, from df = 30 to df = infinity.  For hand computation the difference didn't really matter.
Nowadays it is easy to compute critical values for all sorts of things to 15 decimal places.  On top of that we have resampling and permutation methods for which we aren't even restricted to parametric population distributions.
In practice I never rely on n = 30.  Plot the data.  Superimpose a normal distribution, if you like.  Visually assess whether a normal approximation is appropriate (and ask whether an approximation is even really needed).  If generating samples for research and an approximation is obligatory, generate enough of a sample size to make the approximation as close as desired (or as close as computationally feasible).
Comment: Here's a page on exactly how good the normal approximation of the t distribution is for n=30.  http://www.johndcook.com/normal_approx_to_t.html
Answer: Mostly arbitrary rule of thumb. This statement depends on a number of factor to be true. For example on the distribution of the data. If the data comes from a Cauchy for example, even 30^30 observations are not enough to estimate the mean (in that case even an infinite number of observations would not be enough to cause $\bar{\mu}^{(n)}$ to converge). This number (30) is also false if the values you draw are not independent from one another (again, you may have that there are no convergence at all, regardless of sample size).
More generally, the CLT needs essentially two pillars to hold:

That the random variables are independent: that you can re-order your observations without losing any information*.
That the r.v. come from a distribution with finite second moments: meaning that the classical estimators of mean and s.d. tend to converge as sample size increases.

(Both these condition can be somewhat weakened, but the differences are largely of theoretical nature)
Comment: Your example illustrates the value of robust statistics.  The *sample median* estimates the location parameter of a Cauchy distribution well.  One could argue that the weakest link in using a t-test with 30 samples is the t-test, not the 30 samples.
Comment: A sample size 50,000 is insufficient for the CLT to work well enough to compute a confidence interval for the mean of a log-normal distribution.
Comment: John:> "One could argue that the weakest link in using a t-test with 30 samples is the t-test, not the 30 samples". Very true, and also the assumption that the data is *iid*. Also, the median is MLE for Cauchy distributed random variables (and hence efficient), but in general you could need more than 30 observations.
Comment: Not all versions of the CLT rely on being identically distributed, nor even independence. The basic ones taught to undergrads often do, but there are versions that don't make both assumptions e.g. the [Lyapunov CLT](http://en.wikipedia.org/wiki/Central_limit_theorem#Lyapunov_CLT) assumes independence but not identical distributions, and the independence condition can also be relaxed, for example [see here](http://en.wikipedia.org/wiki/Central_limit_theorem#CLT_under_weak_dependence). That 'reordering' thing is also not the same as independence. Some forms of dependence don't rely on order.
Answer: IMO, it all depends on what you want to use your sample for.  Two "silly" examples to illustrate what I mean: If you need to estimate a mean, 30 observations is more than enough.  If you need to estimate a linear regression with 100 predictors, 30 observations will not be close to enough.
Answer: This is meant to supplement user1108's answer stating that:

That said, the story told to me was that the only reason 30 was regarded as a good boundary was because it made for pretty Student's t tables in the back of textbooks to fit nicely on one page. That, and the critical values (between Student's t and Normal) are only off by approximately up to 0.25, anyway, from df = 30 to df = infinity. For hand computation the difference didn't really matter.

I did some investigation on this issue, and the earliest source I can find is Fisher's Statistical Methods for Research Workers (1925). I remember examining a copy of this text (you can see http://psychclassics.yorku.ca/Fisher/Methods/, for example) and noticing that the following table neatly fit on one page.

From what I recall reading in the text, there is nothing justifying why Fisher chose to stop at $n = 30$. So as far as I know, the only justification for this is that such tables can fit neatly on one page back in the day.


Question about derivations of "CS231N Backpropagation gradient"

Question: There is a great explanation of the calculation of backpropagation gradient in the CS231n class. Please find the question here.
twolffpiggott's answer improved my general understanding. However, I've got stuck at one of the derivations. My first question is about this formula:
$$  \frac{\partial\mathcal{L}_i}{\partial \boldsymbol{w_j}} = \sum_{k=1}^{K} \frac{\partial\mathcal{L}_i}{\partial f_k} \times \frac{\partial f_k}{\partial \boldsymbol{w_j}} .$$
How do you convert into the second line, which is:
$$ \frac{\partial\mathcal{L}_i}{\partial f_j} \times \frac{\partial f_j}{\partial \boldsymbol{w_j}}$$
In other words, how did $\sum$ turned into the second line?
The second question is about $k$. May I kindly ask, what is $k$ in those lines? Is it different from $j$?
Thanks in advance for your time.
Answer: As written in the answer you mention the sum disappears because among all the $f_k$ only $f_j$ depends on $w_j$. Therefore, for $k \neq j$, $\dfrac{\partial f_k}{\partial w_j}=0$.
$k$ and $j$ are indices, they can be considered as "mute", because they do not represent anything. You can write the same equations with $k$ replaced by $j$ and $j$ replaced by $k$. However we usually like using $k$ for summation and $j$ as a particular index, but that is only a choice.


What's the easiest way to do a FULL backup/restore in Windows 7?

Question: I want to be able to backup my Windows 7 system, then restore it.  When I restore my backup, I want to do a FULL restore--that is, if I created files on my desktop or installed software after the backup, they should be deleted when I restore my backup.
So far I've tried the built-in Windows backup and restore, as well as restore points.  In both cases, files were still on my desktop that I created AFTER the backup/restore-point was created.
How do I do it?
Comment: You'd want a full disk image.
Comment: Easiest way to do this? Will I need third-party software?
Answer: If you want a full disk backup, I'd use a linux live disk and make a binary copy with the dd command.
Something less extreme might be Norton Ghost.
Comment: The OP has already demonstrated an extreme lack of knowledge in this area, so how do you think he/she would cope with the command line? Suggesting *nix commands to a Windows person is seldom good advise, especially with so many point an click solutions available.
Comment: +1 dd sounds like a simple solution, I may try that at some point
Comment: @JohnGardeniers the OP does say he knows what dd is in the comment above yours.
Comment: and the OP says he has linux experience in his profile + I gave him an alternative.
Comment: I'm not a Windows person ;) if I was I'd know how to do this.
Answer: There are third-party imaging tools, such as Acronis TrueImage, that can make an image backup for you. Windows Backup SHOULD also be able to make a full system backup for you. Perhaps the issue is how you're restoring it. According to this Microsoft site, You should be able to restore a backup from within Windows, or the boot menu. Just make sure that you're making a full system backup for yourself, and not just backing up your personal user files.
Comment: Thanks for the term "full disk image", searching for this led me to the answer: restoring a full disk image is arguably hidden in the Windows Backup options.
Comment: You can do a "full disk image" restore from a windows 7 boot disk and selecting repair.  it will allow you to specify the backup location and allow you to restore the machine to its former start.  Just keep in mind that if you try to swap hardware around, you will run into issues (like a smaller hard drive), and those issues will be difficult to resolve from within the repair restore utility


What is the need of ellipsis[...] while modifying array values in numpy?

Question: import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)

for x in np.nditer(a, op_flags = ['readwrite']):
   x[...] = 2*x
print 'Modified array is:'
print a

In the above code, why can't we simply write x=2*x instead of x[...]=2*x?
Comment: @user2285236: `x = 2*x` doesn't create a new variable. It's just that the variable isn't the thing we need to change. Assigning to the variable doesn't help us.
Comment: If you are a numpy beginner, don't spend much time on `nditer`.  Focus on whole array operations, like `b=2*a`.  Even when you must use iteration, it isn't the fastest or simplest.
Comment: If you write `x = 2*x` inside that loop, you just create a new variable x (different from the one that comes from the iteration) and assign the result to it. With `x[...] = 2*x`, you are modifying x directly. You might want to check [this post](https://nedbatchelder.com/text/names.html).
Comment: What was wrong with this question that somebody downvoted it?
Comment: The main `nditer` tutorial, https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html, is most useful if you read all the way to the end, and experiment with the `cython` port.  Otherwise you'll get a false sense of its usefulness.
Comment: See also https://stackoverflow.com/q/42190783
Answer: No matter what kind of object we were iterating over or how that object was implemented, it would be almost impossible for x = 2*x to do anything useful to that object. x = 2*x is an assignment to the variable x; even if the previous contents of the x variable were obtained by iterating over some object, a new assignment to x would not affect the object we're iterating over.
In this specific case, iterating over a NumPy array with np.nditer(a, op_flags = ['readwrite']), each iteration of the loop sets x to a zero-dimensional array that's a writeable view of a cell of a. x[...] = 2*x writes to the contents of the zero-dimensional array, rather than rebinding the x variable. Since the array is a view of a cell of a, this assignment writes to the corresponding cell of a.
This is very similar to the difference between l = [] and l[:] = [] with ordinary lists, where l[:] = [] will clear an existing list and l = [] will replace the list with a new, empty list without modifying the original. Lists don't support views or zero-dimensional lists, though.
Comment: The fact that `x` is 0d, and requires `x[..,]` instead of `x[:]` is part of why `nditer` is unsuitable for numpy beginners.


Ionic Mobile First Integration

Question: I developed Ionic Side Menu app and integrated IBM MobileFirst Platform Foundation 7.1 using the below link.
https://www.raymondcamden.com/2015/03/23/working-with-ibm-mobilefirst-and-the-ionic-framework/
When I tried to build & run its throwing an error

worklight.js:5383 Uncaught Exception: Uncaught Error:
  [$injector:modulerr] Failed to instantiate module ng due to:
  TypeError: Cannot set property 'aHrefSanitizationWhitelist' of null
      at $$SanitizeUriProvider

I googled and found the below Stack overflow link, but tried with using latest angular version still same issue.

AngularJS 1.5 error bootstrap IBM Mobilefirst
Failed to instantiate module error in Angular js
https://github.com/angular/angular.js/issues/9692

IBM MobileFirst Platform Foundation 7.1
Java SDK 1.8
IONIC version 1.7.14
app.js

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a  attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
   /* if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }*/
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

    .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'templates/menu.html',
    controller: 'AppCtrl'
  })

  .state('app.search', {
    url: '/search',
    views: {
      'menuContent': {
        templateUrl: 'templates/search.html'
      }
    }
  })

  .state('app.browse', {
      url: '/browse',
      views: {
        'menuContent': {
          templateUrl: 'templates/browse.html'
        }
      }
    })
    .state('app.playlists', {
      url: '/playlists',
      views: {
        'menuContent': {
          templateUrl: 'templates/playlists.html',
          controller: 'PlaylistsCtrl'
        }
      }
    })

  .state('app.single', {
    url: '/playlists/:playlistId',
    views: {
      'menuContent': {
        templateUrl: 'templates/playlist.html',
        controller: 'PlaylistCtrl'
      }
    }
  });
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/playlists');
});
index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <ion-nav-view></ion-nav-view>

Comment: Please show the `app.js` and `index.html`.
Comment: I edited the question, Please find it
Comment: I do not see reference to the `SanitizeUriProvider` in your code, you have the appropriate script in place and referenced in your app?
Comment: SanitizeUriProvider is in ionic.bundle.js
Comment: Have you added reference to `ng-sanitize` in your angular module?
Comment: I didnt add ngSanitize in angular module
Comment: I added ngSanitize in angular module, run and preview the app then still i am getting the same error
Comment: Nothing to do with ngSanitize - it's an incompatibility between MFP and Angular > 1.5.  Please don't downvote if you don't understand the issue!  See Idan's answer.
Answer: Since Angular seems to be the only variable that changes, this could potentially be an Angular issue instead.
I'd suggest trying the updated version of this
https://github.com/csantanapr/mfp-ionic-templates
Comment: As suggested I tried with ionic version 1.2.4 then i got localhost error and I also tried with ionic 1.3.22 then getting same error : worklight.js:5383 Uncaught Exception: Uncaught Error: [$injector:modulerr] Failed to instantiate module ng due to:
TypeError: Cannot set property 'aHrefSanitizationWhitelist' of null
    at $$SanitizeUriProvider
Answer: Update: MobileFirst Platform Foundation 7.1 now supports Angular 1.5; upgrade to the latest available iFix from IBM Fix Central.
there is an incompatibility between Angular 1.5 and MFP 7.1.
To successfully make an Ionic app with MFP 7.1, an ionic version below 1.3 must be used (1.2.4 Copenhagen is the latest).
Ionic 1.3 introduced Angular 1.5
Comment: @MadhuMadhuri Have you tried it on the emulator/native rather than the preview?
Comment: I didnt try it in the emulator. I just run and  preview the App
Comment: @MadhuMadhuri  try with emulator also with my answered.if you failed let me know !
Comment: Idan - this is an issue with MFP 8.0's Cordova projects, too.  Not just MFP 7.1
Comment: Better open a PMR.
Comment: I've also pinged the dev team.
Comment: Is there an update concerning MFP 8 and Angular 1.5 ? @IdanAdar
Comment: There has not been a proper reproduction of the error in MFP 8. If you can proper a sample the shows the error it will be investigated.
Comment: @IdanAdar I have having this error with MFPv8 and angular js v1.5.3
Comment: @IdanAdar does this incopatibility exist between v1.5.3 and MFP 7.0?
Comment: @IdanAdar I tried and I get a similar error, that's why I am asking. Is there a fix for mobileFirst 7.0 as well?
Comment: Try the latest iFix from IBM Fix Central for 7.0; if it fails still you need to open a PMR.

Ionic Mobile First Integration


Filtrar valores específicos de uma variável

Question: Eu tenho um conjunto de dados e gostaria de filtrar alguns valores da variável y. Por exemplo, de 0 a 0.3 e o valor de 1. Tenho usado o filter do dplyr e não consegui.
x <- c(6, 3, 7, 2, 7, 9)

y <- c(0, 0.2, 0.5, 0.4, 0.3, 1)

d <- data.frame(x, y)

d %>%
 filter(y == 1, y <= 0.3)

Comment: Porquê o voto para baixo? A pergunta tem uma descrição do problema, dados e o código da tentativa de solução. O código estar errado *não* é motivo para votos negativos, se estivesse certo não era preciso perguntar, não é?
Answer: No seu código você está fazendo o mesmo que:
d %>%
 filter(y == 1.0) %>%
 filter(y <= 0.3)

Assim, não sobrará nenhuma observação. Você precisa usar o operador |, que implica na operação OU.
d %>%
  filter(y == 1 | y <= 0.3)

E ainda se desejar adicionar a condição maior que 0, seria:
d %>%
  filter(y == 1 | (y >= 0 & y <= 0.3))

ou utilizando between
d %>%
  filter(y == 1 | between(y,0,0.3))

Comment: Eu tenho feito também um gráfico mas ele ficou com os valores vazios no meio, como nesse gráfico que adicionei a minha pergunta. Eu queria saber se posso cortar o eixo do X de 0.25 até 0.9.
Comment: @JeanneFranco eu não vi o gráfico, mas se estiver utilizando o `ggplot2` a partir do comando `scale_x_continuous(limits = c(.25,.90))` seria possível


passando paramentos para função REACT TYPESCRIPT

Question: function handleOpenUpdateTaskModal (valor){
   setIsUpdateTaskModalOpen(true);
   console.log(valor)
}

Primeiro erro no valor da função (Parameter 'valor' implicitly has an 'any' type.ts(7006))
Segundo erro no onClick (Type 'void' is not assignable to type 'MouseEventHandler | undefined'.ts(2322))
Answer: Primeiro erro
function handleOpenUpdateTaskModal (valor: string)

Segundo erro
onClick={() => handleOpenUpdateTaskModal('VALOR')}

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Muito obrigado !


Atomic compare exchange. Is it correct?

Question: I want to atomically add 1 to a counter under certain conditions, but I'm not sure if following is correct in a threaded environment:
void UpdateCounterAndLastSessionIfMoreThan60Seconds() const {
    auto currentTime = timeProvider->GetCurrentTime();
    auto currentLastSession = lastSession.load();
    bool shouldIncrement = (currentTime - currentLastSession >= 1 * 60);

    if (shouldIncrement) {
        auto isUpdate = lastSession.compare_exchange_strong(currentLastSession, currentTime);
        if (isUpdate)
            changes.fetch_add(1);
    }
}

private:
    std::shared_ptr<Time> timeProvider;
    mutable std::atomic<time_t> lastSession;
    mutable std::atomic<uint32_t> changes;

I don't want to increment changes multiple times if 2 threads simultaneously evaluate to shouldIncrement = true and isUpdate = true also (only one should increment changes in that case)
Answer: I'm no C++ expert, but it looks to me like you've got a race condition between the evaluation of "isUpdate" and the call to "fetch_add(1)".
So I think the answer to your question "Is this thread safe?" is "No, it is not".
Comment: If this thread is the thread that correctly updated lastSession (if that is correct) than fetch_add should be ok for that thread.
Comment: @Ghita Yes, but by "correct in a threaded environment" I took you to mean cases where 2 or more threads may be running concurrently. If threads 1 and 2 both evaluate isUpdate before either one calls fetch_add(), then both will call fetch_add(), which is what you don't want.
Comment: fetch_add() is done only by 1 thread because compare_exchange is an atomic read-modify-write operation
Answer: It is at least a bit iffy, as following scenario will show:
First thread 1 does these:
auto currentTime = timeProvider->GetCurrentTime();
auto currentLastSession = lastSession.load();
bool shouldIncrement = (currentTime - currentLastSession >= 1 * 60);

Then thread 2 does the same 3 statements, but so that currentTime is more than it just was for Thread 1.
Then thread 1 continues to update lastSession with it's time, which is less than thread 2's time.
Then thread 2 gets its turn, but fails to update lastSession, because thread 1 changed the value already.
So end result is, lastSession is outdated, because thread 2 failed to update it to the latest value. This might not matter in all cases, situation might be fixed very soon after, but it's one ugly corner which might break some assumptions somewhere, if not with current code then after some later changes.

Another thing to note is, lastSession and chnages are not atomically in sync. Other threads occasionally see changed lastSession with changes counter still not incremeted for that change. Again this is something which might not matter, but it's easy to forget something like this and accidentally code something which assumes they are in sync.

I'm not immediately sure if you can make this 100% safe with just atomics. Wrap it in a mutex instead.
Comment: Yes, minutes is misleading in the context of the example. Updated the sample code, stil the issues with multiple updates to former "minutes"
Comment: As far as I can see, `minutes`/`changes` will not be updated, unless `compare_exchange_strong` succeeded. So there's no chance of it getting updated too many times. Two threads can't update the time value from same previous value, because after it is atomically updated, the other thread sees different value and update fails.
Comment: Yes, you are right, that I was thinking in the first place :-). Changes is guaranteed to update only once indeed
Comment: In my case the fact that a possibly older lastSession is written is no problem as long as +1 is done correctly (once). I think that justifies using no locks on a concurrent server
Comment: Unless you have a lot of threads calling that functions hundreds of times per second, I would play it safe and use a mutex... You could still use atomics to read the value in consistent state, and only use mutex to protect modification. Well, except if it's a problem if `lastSession` and `changes` are not atomically in sync, but that's problem with your current code too.

Atomic compare exchange. Is it correct?


Quickest way to find smallest Hamming distance in a list of fixed-length hexes

Question: I'm using Imagehash in Python to generate 48-digit hexadecimal hashes of around 30,000 images, which I'm storing in a list of dictionaries (the phashes as well as some other image properties). For example:
[{"name":"name1", "phash":"a12a5e81127d890a7c91897edc752b506657233f56c594b7e6575e24e457d465"},
 {"name":"name2", "phash":"a1aa7e011367812a7c9181be9975a9e86657239f3ec09697e6565a24e50bf477"}
 ...
 {"name":"name30000", "phash":"a1aa7e05136f810afc9181ba9951a9686617239f3ec4d497e6765a04e52bfc77"}]

I then have video input from a Raspberry Pi which is phashed, and that hash is compared to this database (given the nature of the Pi camera, the test hash from the video stream will NOT ever match the hashes in the database). Right now I'm doing a dumb loop, which takes about 5 seconds to loop through and check the Hamming distance of each of the ~30,000 pre-calculated hashes, which is way too slow. The Imagehash library I'm using means that the Hamming distance can be calculated simply by doing dbHash1 - testHash. Apparently sorting and doing bisect is not the way to approach this, since sorting is irrelevant to Hamming distances. So, I assume there must be a faster way to get this done? I've read this question regarding metric spaces, but I wanted to check if there's a (relatively) simple Python implementation that someone knows of.
Comment: Ah, I will clarify this in the OP; the test hash I'll be looking up will definitely not match any of the database hashes. I'm looking for the one with the smallest Hamming distance.
Comment: There are a number of data structures that support searching a metric space, see this SO question: http://stackoverflow.com/questions/6389841/efficiently-find-binary-strings-with-low-hamming-distance-in-large-set
Comment: I've seen that one, but I don't know how to implement any of those, and once implemented, how to search them.
Answer: I got an answer from the guy behind ImageHash, Johannes Buchner.
I can store the DB as a 2d matrix:
arr = []
for dbHash in db:
    arr.append(dbHash.hash.flatten())
arr = numpy.array(arr)

Then I can do the comparison against all at the same time:
binarydiff = arr != testhash.hash.reshape((1,-1))
hammingdiff = binarydiff.sum(axis=1)
closestdbHash_i = numpy.argmin(hammingdiff)
closestdbHash = db[closestdbHash_i]

Answer: Scipy's pairwise distance function  supports Hamming distances. I'd try that.
Comment: I already know how to get the Hamming distance from my test hash and all the hashes in the database. What I need is a quick way of doing it that doesn't involve 30,000 loop iterations.
Comment: Scipy's implementation is written in C++ and likely to be fairly optimized. While still reliant on running direct pairwise comparisons, it should be meaningfully faster than something we would code up as a one off. I should have posted that note as a comment though, since it doesn't answer your main question about metric spaces.


Crossover function of two vector error

Question: The Goal of my function is to use a 1 point crossover function between two Vector to get a new hybrid "Son" Vector having some element from the first Vector and some from the second one .
public Vector crossover(int Sol1,int Sol2){
  int size;
  Vector sol1 = new Vector();
  Vector sol2 = new Vector();
  sol1 = (Vector) allpop.get(Sol1);
  sol2 = (Vector) allpop.get(Sol2);
  int crosspoint = (int) sol1.size()/2 ;
  Vector son =  new Vector();
      son= (Vector) sol1.clone() ;
      if (sol1.size() < sol2.size())
            size = sol1.size();
      else size = sol2.size();

  for(int j=(crosspoint-1);j<size;j++)
    son.set(j,sol2.get(j));
         return son;
                                          }

sometimes it works good and sometimes it gives me the "java.lang.ArrayIndexOutOfBoundsException " error .. Some Ideas ?
Comment: Can you give us an exemples of valid & invalid inputs ?
Answer: Attach a debugger, see on what values it fails. I'd wager your crosspoint is equal to zero when sol1.size() is 1 or less, so the index j is equal to -1, which would obviously throw an exception.
Comment: yes you have right i didn't noted that ! could you explain more about how to attach a debugger ?
Comment: Yes, google "debug" and the name of whatever platform you're running this on :)
Answer: Maybe try int crosspoint = (int)(sol1.size() / 2);
Also: crosspoint - 1 needs to be >= 0
Answer: Fixed already :) and here i share the answer with you :)
    public Vector crossover(Vector sot1, Vector sot2) {
    Vector sol1;
    Vector sol2;
    sol1 = copi(sot1);
    sol2 = copi(sot2);
    sol1.removeAll(Collections.singleton(null));
    sol2.removeAll(Collections.singleton(null));
    // int crosspoint = (int) sol1.size()/2 ;
    Vector son = new Vector();
    boolean awal = true;
    int size;
    if (sol1.size() < sol2.size()) {
        size = sol1.size();
        son.setSize(sol1.size());
        Collections.copy(son, sol1);
    } else {
        size = sol2.size();
        son.setSize(sol2.size());
        Collections.copy(son, sol2);
        awal = false;
    }
    int crosspoint = (int) (Math.random() * ((size * 2) / 3)) + 1;
    System.out.println("cross point :" + crosspoint);
    int j = crosspoint;
    if (awal == true) {
        for (j = crosspoint; j < size; j++) {
            //son.removeElementAt(j);
            // son.add(j, sol2.get(j));
            son.set(j, (Capaciter_n_objet) sol2.get(j));
        }
    } else {
        for (j = crosspoint; j < size; j++) {
            // son.removeElementAt(j);
            //son.add(j, sol1.get(j));
            son.set(j, (Capaciter_n_objet) sol1.get(j));
        }
    }
    son.removeAll(Collections.singleton(null));
    correction(son);
    son.removeAll(Collections.singleton(null));
    /* for(int i=0;i<non_packed_objet.size();i++)
     * System.out.println("non packed object : "+non_packed_objet.get(i));*/
    return son;
}

Crossover function of two vector error


Jacobi Theta Functions?

Question: For the Jacobi theta function $\vartheta_3(z|\tau)$ there exists an equality (by Whittaker & Watson)
\begin{equation}
\vartheta_3(z|\tau) = \sum_{n=-\infty}^{\infty} e^{n^2 \pi i \tau + 2 n i z} = \sqrt{\frac{1}{-i\tau}} \sum_{n=-\infty}^{\infty} e^{\frac{(z-n\pi)^2}{\pi i \tau}}
\end{equation}
Is there something similar for this "modified version" of the Jacobi theta function?
$$\sum_{n=1}^{\infty} n\,e^{n^2 \pi i \tau}$$
I tried to use the relation shown above, but it results nothing.

Well, I got a relation for the $n^2$ case
$$\sum_{n=1}^{\infty} n^2\,e^{n^2 \pi i \tau}$$
I just 'broke' the sum into parts,
$$\sum_{n=-\infty}^{-1} + \sum_{n=1}^{\infty}$$
remembering that $n=0$ contributes with nothing, than I took a derivative with respect to $\tau$ and set $z=0$. I got:
$$\sum_{n=1}^\infty n^2\,e^{n^2 \pi i \tau} = \frac{(-i\tau)^{-3/2}}{2\pi} \left(\frac{1}{2}+\sum_{n=1}^\infty e^{\frac{n^2\pi}{i\tau}}\right) - \pi (-i\tau)^{-5/2}\sum_{n=1}^\infty n^2\,e^{\frac{n^2\pi}{i\tau}}$$
It looks like equalities for
$$\sum_{n=1}^\infty n^{2k}\,e^{n^2 \pi i \tau}, \quad k\in\mathbb{N}$$
are allways possible to get by 'recurrence'. The problem is with odd powers...
Comment: I don't think so. After all this identity is a consequence of Poisson summation formula, for which it is essential to sum over all, and not just positive $n$.
Answer: The Fourier transform of $1_{y > 0}$ is $PV.(\frac{1}{2i \pi y})+\frac{1}{2}\delta(y)$, thus the Fourier transform of $y \ 1_{y > 0}$  is $\frac{d}{dy}PV.(\frac{-1}{4\pi^2 y})+\frac{1}{4i \pi}\delta'(y)$
and of
 $T(y) = \sum_{n=1}^\infty n \delta(y-n)$  is $\hat{T}(y)=\sum_n  \frac{d}{dy} PV.(\frac{-1}{4 \pi^2 (y-n)})+\frac{1}{4i\pi}\delta'(y-n)=\sum_n  \frac{d^2}{d^2y} \frac{\log |y-n|}{-4\pi^2}+\frac{1}{4i\pi}\delta'(y-n)$.

With $\hat{h}(y) = e^{-\pi y^2 x},h(y) = \frac{1}{\sqrt{x}}e^{-\pi y^2 /x}$
$$\sum_{n=1}^\infty n e^{- \pi n^2 x} = \langle T, \hat{h} \rangle=\langle \hat{T},h \rangle
 = \sum_{n=-\infty}^\infty \frac{i  n}{2 x^{3/2}}e^{-\pi n^2 /x}-\frac{1}{4\pi^2} \int_{-\infty}^\infty \log |y-n| h''(y)dy$$
Comment: $$\sum _{n=1}^{\infty } \frac{1}{\sqrt{k}} e^{-i k^2 x}=\sum _{n=1}^{\infty } \frac{\pi ^{3/2} e^{\frac{i \pi ^2 n^2}{2 x}} \sqrt[4]{\frac{n^2}{x}} J_{-\frac{1}{4}}\left(\frac{n^2 \pi ^2}{2 x}\right)}{\sqrt[4]{i x}}+\frac{\Gamma \left(\frac{1}{4}\right)}{2 \sqrt[4]{i x}}$$  sorry but i do not see necesary using here  fourier transform if you needed i could calculate sum as typo above
Comment: @capea ???  Why do you want to mention  $\sum_{n \ge 1} n^{-1/2} e^{- n^2 x}$ ? And where do your formulas come from ?
Answer: $$\sum _{k=1}^{\infty } k e^{\pi  i k^2 (-x)}=\sum _{n=1}^{\infty } -\frac{i \left(x+\sqrt[4]{-1} \pi  n \sqrt{x} e^{\frac{i \pi  n^2}{x}} \text{erf}\left(\frac{\sqrt[4]{-1} \sqrt{\pi } n}{\sqrt{x}}\right)\right)}{\pi  x^2}-\frac{i}{2 \pi  x}$$
Comment: Where is it supposed to come from ? What is the Fourier transform of the distribution $\sum_{n=1}^\infty n \delta(x-n)$ ?
Comment: Why you need a Fourier Transform?
Comment: Because $\langle T, \hat{h} \rangle = \langle \hat{T}, h \rangle$. Here we have $h(y) = e^{-\pi y^2 x}, \hat{h}(y) = \frac{1}{\sqrt{y}} e^{-\pi y^2/x}$, the Poisson summation formula is the case  $T = \hat{T} = \sum_n \delta(y-n)$, here we need to apply it with $T = \sum_{n=1}^\infty n \delta(y-n)$.
Comment: See what I get in my answer

Jacobi Theta Functions?


Is there a way to get an OS error code from a std::io::Error?

Question: When I run the following:
use std::fs::File;

fn main() {
    let filename = "not_exists.txt";
    let reader = File::open(filename);

    match reader {
        Ok(_) => println!(" * file '{}' opened successfully.", filename),
        Err(e) => {
            println!("{:?}", &e);
        }
    }
}

The output is:
Os { code: 2, kind: NotFound, message: "No such file or directory" }

Is it possible to get that code as an integer?
Answer: Use io::Error::raw_os_error:
match reader {
    Ok(_) => println!(" * file '{}' opened successfully.", filename),
    Err(e) => println!("{:?}", e.raw_os_error()),
}

Output:
Some(2)

See also:

How does one get the error message as provided by the system without the "os error n" suffix?
Comment: Thanks, that is exactly I was looking for.
Answer: Yes, use the raw_os_error method on std::io::Error. Example:
use std::fs::File;

fn main() {
    let filename = "not_exists.txt";
    let reader = File::open(filename);

    match reader {
        Ok(_) => println!(" * file '{}' opened successfully.", filename),
        Err(e) => {
            println!("{:?} {:?}", e, e.raw_os_error());
        }
    }
}

playground


What are (no3) chords?

Question: I have been reading some sheet music and I see that there are chords like C2(no3). I just play the Cmaj chord with a 2 (d note) added. I'm trying to play these chords properly but I don't understand this (no3). Also when I see chords like C2 do I read this Csus2 (C, D, G notes) or Cmaj2 (C, D, E, G notes). Sry if this isn't clear.
The chord is in the verses of this song.
Answer: The 'no' notation tells you that that chord tone is not present so this is telling you the 3rd of the chord is not there. Any chord with 'no' notation is improper and abuses the notation as it misrepresents what chord is actually there.
Your example is a good example in why this is the case. First of C2 is ambiguous.  It could be Csus2, but I gaurntee they are actually referring to a C9. In either case, saying there is no third is misleading as:

In the Csus2 there is no third.
In C9 the third is a very important chord tone along with the 7th and 9th so it's not really a C9, but a C7sus2.
Comment: In praise charts like these, C2 is a three note chord. You wouldn't see C2 and play C9 or C7, because those chords have innate tension - they sound like they need to resolve somewhere. C2 doesn't have that tension, but it does have a thicker sound than a plain open fifth.
Comment: So, based on Brian's comment, I would guess that this is a C5add9.  A very nice and simple quintal chord.
Comment: @Dom - Definitely.  There are plenty of examples of issues with our notation system, which we often see posted on this site as questions, that result in basically having to write a note on your score.  Quartal and Quintal chords obviously don't conform to the development of the rest of chord theory but you'd think that someone would have come up with a good system by now.
Comment: @tptcat A5 would be an A power chord (root, 5, octave). I think that if those types of chords were more common, we'd be more likely to see a formally recognized notation for them. In most situations we see that quartal and quintel chords are actually just voicings of chords that are triad based like the majority of the rest of our harmonic system, such as in So What, where it is a quartally voiced D-7. So ultimately we're most often thinking of these chords in a way that doesn't require any new notation. What would be required is notation for voicings, which our standard notation doesn't do.
Comment: C7sus2 = C,D,G,Bb  C9=C,E,G,Bb,D.
Comment: @Basstickler most likely. I wish we had chord symbols to represent quartal and quintal chords better.
Comment: This might help discover the ambiguity of the C2: https://www.youtube.com/watch?v=djrY_eFDOwE
Comment: Can this chord also be interpreted as Gsus4?
Comment: @BrianTHOMAS is right. In this genre (contemporary Christian) you will definitely irritate your fellow band members if you include the flattened 7th tone when you see C2. I definitely sympathise with Dom's POV though. When I see F/G I'll often see if I can slip in an F11 ☺!
Comment: Hi guys- just thought id open this years later! I'd be interested to know how one would differentiate between for example, a C7sus2, and a C9 (no 3)?
Answer: Given the genre and the song, the chord is almost certainly a Csus2. On the Tomlin recording, there's no 7th that I can hear.
As to why they wrote it that way, I can't be sure. I've played a lot of similar charts, and there's not a lot of agreement on how to notate second chords. I've seen C2,  Csus2, C2(no3), Cadd2 and Cadd9 all used for the same end result. To be honest, for your (our) purpose, the differences are mostly unimportant. Play CDG by default, and experiment with adding  E. If it sounds good, it's right.
Answer: I am not a 'Piano Musician', however, (no3) appears to me, that the 'Sheet Music, is telling you to move out of the 'first Octave, and play the chord 2 octaves higher, than the one you are in... for the original way the music was intended.
Answer: A #3 Chord', is a minor Chord, where the 3rd degree is 'flatted. A Major 'triad, is a chord comprised of the 1st, 3rd,& 5th degree / C, E, G. A 'minor triad' is C, Eb, G., and/or, depending on the 'Scale Root Choice, a no.#3, in the Key of 'A' would be the C minor.

What are (no3) chords?


Waiting for batch-end

Question: I have 4 lines in my bat file, but my thread goes on before the cmd closes.
Here's my code:
rt = Runtime.getRuntime();
proc = rt.exec("cmd /c start C:\\temp\\test.bat");
if(proc.waitFor() == 0) {
    return "did it";
} else {
    return "nooope";
}

I always get the did it before cmd closes.
Here is my batch-file:
@ECHO off
taskkill /IM "Process.exe" /F
cd "C:\Program Files\ProcessFolder"
START /WAIT Process.exe
START otherProcess.exe
EXIT

any help?
Comment: You should explain or add why you don't want to use threading in your java code and what else comes after your main code. Finding problems without knowing the thread situation of your program is painful because the main thread might end or could be interrupted. So it would be good to post a reduced program which could reproduce the problem.
Comment: Also look at the article linked from the [`runtime.exec` Wiki](http://stackoverflow.com/tags/runtime.exec/info).  Implement the recommendations for most robust use of a `Process`.  Also note that Java has had `ProcessBuilder` since 1.5.  It is better than using `exec` - one reason is that it makes it easy to consume both output streams (mentioned in the linked article).
Answer: The problem is that you're using start - which will start a new shell in which to run the batch file. The original shell then closes, so the process terminates, and your Java program continues.
Remove the start and it should work, in terms of waiting for the batch file to end. However, you've then got the same problem again within the batch file when you start otherProcess.
Either don't use start, or always use start /wait within the batch file.
If you use start /wait within the Java code, however, you'll end up with a command prompt sitting there at the end of the batch file execution, as far as I can tell by experimentation.
Comment: Hey, thanks for the fast answer. The Problem what i have. I can't /wait for the otherProcess, because the Process is a Serverprocess which have to stay alive until the next call for the Program comes. By removing start from java, the batchfile wont run :-(
Comment: @Markus: "won't run" is very vague. What happens when you try? You won't see the batch file in a separate window, but it should work. If you don't want to wait for otherProcess, that's fine, so long as you're happy for the batch file to terminate and the Java code to continue.
Comment: "Wont run" will mean, that the process what normally had killed is staying alive, and no new process starts like before with "start" in java.
Comment: @Markus: I'm afraid I didn't follow that at all - but you certainly *can* run a batch file using `cmd /c path\to\file.bat`. I just did it.
Comment: Sry for doublepost. w/o start in java will work. I entered a wrong batch-filename :-/ Now, that works. Thanks for the Help, you're very good :-)

Waiting for batch-end


Find the general solution of ODE$ 1/16x"(t) + 4x(t) = rt(t)$

Question: I am trying to find the general solution of this ODE, but my solution was told to be incorrect, here is the ODE

$$1/16x"(t) + 4x(t) = r(t) \quad \text { where }r(t) = πt , -1<t<1$$

Here is what i have done:
$$ 1/16 x^2 +4 =0$$
$$k = +- 8i$$
$$ X_h(t) = C_1 \cos8t + C_2 \sin8t$$
$$ \text{ for } X_p(t) = 1/D^2 + 64\times πt$$
$$X_p(t) = πt/64$$
$$\text {General solution } = x(t) = X_c(t) + X_p(t)$$
$$ X(t) = C_1 \cos8t + C_2 \sin8t + πt/64$$
Answer: We have
$$\frac{1}{16}x''+4x=\pi t$$
This will fall to the method of undetermined coefficents. Since $r(t)$ is a first degree polynomial, we use $X_p (t) = A_1 t + A_0 $ as our guess. Plugging in,
$$4 A_1 t + 4 A_0 = \pi t$$
Thus, we have $A_1 = \frac{\pi}{4}$ and $A_0 = 0$. Thus, $X_p(t)=\frac{\pi}{4}t$. The solution to the homogeneous equation is fairly trivial $$\frac{r^2}{16}+4 = 0 \\ r=\pm8i \\ X_h(t)=c_1\cos(8t)+c_2\sin(8t)$$
So, the final solution is $$X(t)=c_1\cos(8t)+c_2\sin(8t)+\frac{\pi}{4}t$$
Comment: is it possible to do this using Fourier series?
Comment: Not quite certain what you mean by this. Elaborate?
Comment: since r(t) is a sawtooth wave , its an odd function hence using Fourier coefficient a_0 and a_n will be 0 and if we calculate b_n ; b_n = 1/L integrate f(x) sin nπt/L dx


Condition for this set of points

Question: This is for a calculator experimental prob. simulation. So, there is circle in a square and the circle is touching all 4 sides of the square. We need to first choose a coordinate system (two dimensional). So, it make sense it place the coordinate system at the center of the square. Then calibrate the coordinate system with units. So, let us make the radius of the circle equal to 1 unit. The devise a condition to define all the points in the circle. The condition in the example was $\sqrt{x^2+y^2}<=1$ and $x$ was the interval $[-1,1]$ and the $y$ interval was $[-1,1]$. How did they come up with this equation? Lets say we have a square inside a square. Lets say the side of the larger square is 96 and the side of the smaller square is 48. How would you calibrate and where is the origin and what is the conditions that defines that set of points?
Please help, I have a test tomorrow.
Comment: Do you know that the equation for a circle, centered at the origin, with radius 1, is $x^2+y^2=1$?
Comment: yes but why is there a square root
Comment: No good reason. With or without the square root, you get the same values of $x$ and $y$.
Comment: how about the square, do i find each function of each line of the suare
Comment: There's only one way to put a circle in a square. There are lots of ways to put a square in a square, and you haven't picked one.
Comment: It is in the middle of the big square and the figure is in the middle of the bigger square and does not touch any of the bigger squares sides or corners.
Comment: And how is it oriented? (and what is the point of the bigger square, anyway? does it actually affect the answer at all?)
Comment: I don't think we are speaking the same language.
Answer: The point of this was to write a program to find the probability of a coordinate falling in the figure out the sample space. So, in the program we can store the sample space on the $x$-axis as an interval called $x$. And we can do the same and make an interval called $y$ for the $y$-axis. Then we can generate a $1000$ trials where the calculator picks a random number from that $x$ and $y$ interval and pairs them together giving us a coordinate. Like this we generate a $1000$ coordinates. Let's say we can define the figure using it boundaries. We can use   each line that makes the figure and find it as a function. Then if we list all the functions and use an inequality to represent not just the lines but also the space inside the figure. So, the calculator checks if the point it generates satisfies the conditions (list of the functions). If a point satisfies the all the inequality-functions then, it is inside the figure. The calculator does this for all the coordinates. It keeps track of the number of coordinates that fell inside of the figure. Then it gives you that number of how many fell inside the figure. Then the calculator displays the number of points that fell inside and it divides it by $1000$ (number of trials) giving you the probability $\left(\frac{\text{number of pairs that fell in the figure}}{1000}\right)$.
So, in this case the condition that represents all the points in the circle and the circle itself is $x^2+y^2<1$ . Then the calculator generates a bunch of points and tests them out and finds out how many fell into the event space and divides it by the number of trials run (number of points tested) giving you the probability. Remember this probability that is generated is just an estimate hence "experimental probability" and not theoretical probability.
Comment: thanks for the help guys!|:)|

Condition for this set of points


Assumption regarding matrix multiplication in mathematical equation

Question: I'm learning about the Polar Sine Transform equation, which is denoted by:

Sorry i had to attach an image, as I do not know how to write the integral part in Mathjax
I'm implementing this in Matlab for an image processing task, $r$ and $\theta$ are polar coordinates of an image block, hence matrices of equal dimension. $n$ and $l$ are integers denoting order and repetition.
Now, I need some help on the $[sin(\pi n r^2) e^{il\theta}]*$ part of the equation. You see I mentioned before that $r$ and $\theta$ are polar coordinates and are represented as a matrix in Matlab for an image block, but I'm not entirely sure if $r^2$ is a power of the matrix $r$ or the element wise power of $r$.
Could anyone explain if it should be interpreted as ordinary matrix power or element wise? Also, for the exponential part of the equation, $i$ is an imaginary unit, hence i wonder if the "*" complex conjugate symbol is used just for that purpose?
EDIT
I forgot to add that for digital images, the PST can be approximately calculated where integral is basically replaced as a sum instead, hence programming wise, we would use the sum.

$H_{nl}(x,y)$ is the same for $sin(\pi n r^2)$ above.
Comment: Long time since I did matlab, but IIRC $l*\theta$ should be the same as $l.\theta$ since $l$ is just a real number. And $\exp(A)$ and $\sin(A)$ is always element based exponentiation/sin in matlab. So what I think you want is something like $\sin(\pi*n*r.^2).\exp(-i*l*\theta)$ for this term.
Comment: So you have a matrix $r$ giving you the value of $r$ for each $(r,\theta)$ point in the 2D mesh and similar for $\theta$? Then it's element based operations all the way.
Comment: Shouldn't it be \frac{2}{\pi} \int_0 ^{2\pi} \int_0 ^1 \left[\sin(\pi n r^2)e^{il\theta})\right]^* f(r,\theta)r\text{d}r\text{d}\theta?
ie $\frac{2}{\pi} \int_0 ^{2\pi} \int_0 ^1 \left[\sin(\pi n r^2)e^{il\theta})\right]^* f(r,\theta)r\text{d}r\text{d}\theta$
Comment: @Winther so it is element based for $r.^2$ and $i*l .^\theta$? Hence the multiplication of the $sin$ and $e$ would be just an ordinary multiplication then?
Comment: @Winther thank you. Also, is there a negative before $i$ in exp or is it a mistype? Currently in Matlab there is no element based exponentiation hence  .* exp($-i * l * \theta)$ would do the same job?
Comment: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: You're mixing up programming and math. In the math, $r$ is a number, which is being integrated over. This is easily seen in this formula because you can see where $r$ is being integrated over. In your implementation, you might define $r$ to be a matrix, so that you can then define a matrix of values of the integrand at each pair $(r,\theta)$ in some grid, and then apply some quadrature rule to this matrix (for fixed $n,l$) to compute each entry of $M$. If you do that, then definitely the $r^2$ in this formula will appear as r.^2 in your program.
Comment: thank you. In this case, my guessing is that for the case of $\theta$ in the exponential part, it would be ordinary multiplication with the imaginary unit i and fixed l? Hence in implementation, it would be $sin(\pi n r.^2) * e^{i l * \theta}$
Comment: Yes that's right (except the multiplication between the sin and the exponential is a .*) Also you can achieve the conjugate in this context by just switching the sign inside the exponential, assuming you don't have any quantities that are unexpectedly complex (like $n$).
Comment: by switching sign do you mean $exp(-i * l * \theta)$ as mentioned by Winther above? If so i totally overlooked that!
Comment: @Maxxx Yep that'll do it.
Comment: thank you very much! Cheers!


Error while converting python 3.7 script to exe using PyInstaller: ModuleNotFoundError

Question: I have created a game in python 3.7 that I want to convert into executable file. I tried py2exe but it does not support 3.7. Then I tried PyInstaller. First, it wasn't building the exe file. Then on making changes suggested in both answers here: An error for generating an exe file using pyinstaller - typeerror: expected str, bytes or os.PathLike object, not NoneType
I got an error saying Error loading python dll when I opened the exe from build folder. The exe in dist folder would close on opening. So I made changes like this: https://stackoverflow.com/a/43762970/10058326
This resulted in no exe in build folder and the exe in dist folder to show:

And these are the warnings generated:
`missing module named 'multiprocessing.forking' - imported by C:\Users\Kunj\PycharmProjects\Alien Shooter\venv\lib\site-packages\PyInstaller\loader\rthooks\pyi_rth_multiprocessing.py (optional)
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named 'win32com.gen_py' - imported by win32com (conditional, optional), C:\Users\Kunj\PycharmProjects\Alien Shooter\venv\lib\site-packages\PyInstaller\loader\rthooks\pyi_rth_win32comgenpy.py (top-level)
missing module named win32trace - imported by win32com.server.dispatcher (optional)
missing module named win32traceutil - imported by win32com.server.dispatcher (delayed, conditional)
missing module named win32con - imported by win32com.client.selecttlb (top-level), win32com.server.policy (top-level), win32com.util (top-level)
missing module named winerror - imported by win32com.client.dynamic (top-level), win32com.client.build (top-level), win32com.client (delayed, conditional, optional), win32com.server.policy (top-level), win32com.server.util (top-level)
missing module named 'pywin.dialogs' - imported by win32com.client.makepy (delayed, conditional)
missing module named pywin - imported by win32com.client.selecttlb (delayed), win32com.client.makepy (delayed)
missing module named win32ui - imported by win32com.client.makepy (delayed)
missing module named pywintypes - imported by win32com.client.build (top-level), win32com.client.dynamic (top-level), win32com.client.gencache (top-level), win32com.client (top-level), win32com.server.policy (top-level)
missing module named pythoncom - imported by win32com (top-level), win32com.client (top-level), win32com.client.dynamic (top-level), win32com.client.build (top-level), win32com.client.util (top-level), win32com.client.gencache (top-level), win32com.client.makepy (top-level), win32com.client.genpy (top-level), win32com.client.selecttlb (top-level), win32com.server.util (top-level), win32com.server.policy (top-level), win32com.server.exception (top-level), win32com.util (top-level), win32com.universal (top-level), win32com.server.dispatcher (top-level)
missing module named win32api - imported by win32com (top-level), pkg_resources._vendor.appdirs (delayed, conditional, optional), win32com.client.selecttlb (top-level), win32com.server.policy (top-level), win32com.util (top-level), win32com.server.dispatcher (top-level)
missing module named pyimod03_importers - imported by C:\Users\Kunj\PycharmProjects\Alien Shooter\venv\lib\site-packages\PyInstaller\loader\rthooks\pyi_rth_pkgres.py (top-level)
missing module named 'com.sun' - imported by pkg_resources._vendor.appdirs (delayed, conditional, optional)
missing module named com - imported by pkg_resources._vendor.appdirs (delayed)
missing module named 'pkg_resources.extern.pyparsing' - imported by pkg_resources._vendor.packaging.requirements (top-level), pkg_resources._vendor.packaging.markers (top-level)
missing module named StringIO - imported by pkg_resources._vendor.six (conditional)
missing module named _uuid - imported by uuid (optional)
missing module named netbios - imported by uuid (delayed)
missing module named win32wnet - imported by uuid (delayed)
missing module named __builtin__ - imported by pkg_resources._vendor.pyparsing (conditional)
missing module named ordereddict - imported by pkg_resources._vendor.pyparsing (optional)
missing module named __main__ - imported by pkg_resources (delayed, optional)
missing module named pkg_resources.extern.packaging - imported by pkg_resources.extern (top-level), pkg_resources (top-level)
missing module named pkg_resources.extern.appdirs - imported by pkg_resources.extern (top-level), pkg_resources (top-level)
missing module named 'pkg_resources.extern.six.moves' - imported by pkg_resources (top-level), pkg_resources._vendor.packaging.requirements (top-level)
missing module named pkg_resources.extern.six - imported by pkg_resources.extern (top-level), pkg_resources (top-level)
missing module named resource - imported by posix (top-level), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level)
missing module named posix - imported by os (conditional, optional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level)
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level)
missing module named 'org.python' - imported by pickle (optional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level), xml.sax (delayed, conditional)
missing module named readline - imported by cmd (delayed, conditional, optional), code (delayed, conditional, optional), pdb (delayed, optional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level)
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level)
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level)
missing module named _winreg - imported by platform (delayed, optional), pygame (conditional), pygame.sysfont (conditional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level), pkg_resources._vendor.appdirs (delayed)
missing module named _scproxy - imported by urllib.request (conditional)
missing module named java - imported by platform (delayed), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level)
missing module named 'java.lang' - imported by platform (delayed, optional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level), xml.sax._exceptions (conditional)
missing module named vms_lib - imported by platform (delayed, conditional, optional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level)
missing module named termios - imported by tty (top-level), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level), getpass (optional)
missing module named grp - imported by shutil (optional), tarfile (optional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level)
missing module named org - imported by copy (optional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level)
missing module named pwd - imported by posixpath (delayed, conditional), shutil (optional), tarfile (optional), http.server (delayed, optional), webbrowser (delayed), distutils.util (delayed, conditional), C:\Users\Kunj\PycharmProjects\Alien Shooter\alien_shooter.py (top-level), netrc (delayed, conditional), getpass (delayed)
missing module named copy_reg - imported by cStringIO (top-level), pygame (conditional)
missing module named 'pygame._view' - imported by pygame (delayed)
missing module named pygame.sdlmain_osx - imported by pygame (top-level), pygame.macosx (top-level)
missing module named OpenGL - imported by pygame (delayed)
missing module named numpy - imported by pygame._numpysurfarray (top-level), pygame._numpysndarray (top-level), pygame (delayed)
missing module named 'pygame.movie' - imported by pygame (optional)
missing module named pygame.SRCALPHA - imported by pygame (top-level), pygame.ftfont (top-level)
missing module named Queue - imported by pygame.threads (conditional)
missing module named Py25Queue - imported by pygame.threads (conditional)
missing module named cStringIO - imported by pygame.compat (conditional)`

I am not able to understand what the error is
Answer: Pyinstaller does not have every module. This means that pyinstaller only supports a select few of modules. Here is a full list of pyinstaller supported modules.
Comment: pywin32 is supported then why is the pywin32comgenpy error generated?