Toolbar Image update when rotating

Question: I have a Xamarin Forms App where I set the Toolbar through an xml file.
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/customToolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="?android:attr/actionBarSize"
android:background="?android:attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<ImageView
android:id="@+id/toolbarImage"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_weight="1"
android:paddingRight="5dp"/>
</android.support.v7.widget.Toolbar>

And set it in the OnCreate method of the MainActivity with
ToolbarResource = Resource.Layout.CustomToolbar;

The ImageView doesn't have a source attribute because the image itself is received as base64 string from the server. To add the picture to the Toolbar I used the OnStart method
ImageView toolbarImg = this.FindViewById<ImageView>(Resource.Id.toolbarImage);
            if(!String.IsNullOrEmpty(imgAsBase64))
            {
                    byte[] imageBytes = Convert.FromBase64String(imgAsBase64);
                    Android.Graphics.Bitmap decodedByte = Android.Graphics.BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
                    toolbarImg.SetImageBitmap(decodedByte);

            }

So far this is working, but when I changed the orientation the image disappeared.
What I have tried was to add the Image in OnConfigurationChanged again but that didn't changed anything.
Also setting the Image of the ImageView to null before assigning the new picture, Invalidate(), PostInvalidate(), RequestLayout() also didn't help. Still when I change the orientation no Image is shown.
Would appreciate some help on this.
Thanks in advance
Comment: First, you can stop changing the orientation to avoid this problem.  Second you can judge in `OnConfigurationChanged` method when the screen has changed its orientation and do something. Please make sure the `imgAsBase64` is right, because the `Activity` will be created again when the screen rotating, and anything will be created again. [This is the abnormal life cycle of the Activity.](https://developer.android.com/guide/components/activities/state-changes.html)
Comment: I need orientation in my app so that isn't a solution. The Image is right, otherwise it wouldn't be showed the first time I start. My approaches in OnConfigurationChanged didn't helped as mentioned in my post
Comment: I mean that that your activity will be `recreated` when your screen rotating, and everything will be re-load. Please see the [`onSaveInstanceState`](https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)) and [`onRestoreInstanceState`](https://developer.android.com/reference/android/app/Activity.html#onRestoreInstanceState(android.os.Bundle)) method.
Comment: The [`OnConfigurationChanged`](https://developer.android.com/reference/android/app/Activity.html#onConfigurationChanged(android.content.res.Configuration)) method will not be called if you haven't set the configChanges attribute in your manifest. Please look at the document.
Comment: There is a solution, move your code from `OnConfigurationChanged` to `OnSaveInstanceState`, and set the image source in your `OnRestoreInstanceState`
Comment: I have `ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize` defined in my MainActivity. I can't really use `onSaveInstanceState` and `onRestoreInstanceState` as this takes about 2 minutes to reload the camera :/
Comment: So, you mean the `byte[]` is right, but it can't be used to your `ImageView`, and the `OnConfigurationChanged` method is not helpful?
Comment: The `byte[]` is correct 100%. And I also can use it in ImageView. My only problem is, that when I rotate the device the Image disappear even thou I explicit set again the picture in `OnConfigurationChanged`
Comment: Still didn't find any solution :/ Does someone has an idea?
Comment: Can you give me a demo which will reproduce your problem?
Comment: Pretty simple demo with nothing in it except the toolbar :D just rotate the device. Problem also occurs with an emulator https://www.file-upload.net/download-12892114/ToolbarTestApp.zip.html
Comment: It's not a .zip file, it is a .exe file,bro. I need .zip file which include your application code that can reproduce your problem, thanks!
Comment: Mh you probably clicked on the ad :D I uploaded it to GitHub https://github.com/AndiAn94/ToolbarTest Happy new year
Comment: Hi, I have update my answer, please try again.
Answer: Two solutions:
1) Remove |ConfigChanges.Orientation from ConfigurationChanges = ConfigChanges.ScreenSize|ConfigChanges.Orientation, that mean your activity will recreate when your screen rotate.
2) Add below code in your OnConfigurationChanged method, above the SetImageToToolbar(); method, like this:
    public override void OnConfigurationChanged(Configuration newConfig)
    {
        base.OnConfigurationChanged(newConfig);
        ToolbarResource = Resource.Layout.CustomToolbar;
        global::Xamarin.Forms.Forms.Init(this, null);
        LoadApplication(new App());
        SetImageToToolbar();
    }

Why should you add these code?
I think there is something wrong in the imgView in your code when screen rotating, so I think the codes in OnCreate() method will help it.
Update:
There is something wrong in the second solution, if you have many pages, it will go wrong, so I provide another solution, use custom NavigationPageRenderer:
1) Add MyNavigationPage in your pcl:
namespace ToolbarTestApp
{
    class MyNavigationPage:NavigationPage
    {
        public MyNavigationPage(Page root) : base(root) {
        }
    }
}

2) Replace MainPage = new MyNavigationPage(new TestPage()); with MainPage = new NavigationPage(new TestPage());
3)Add MyNavigationPageRender in your android project:
[assembly: ExportRenderer(typeof(MyNavigationPage), typeof(MyNavigationPageRender))]
namespace ToolbarTestApp.Droid
{
    class MyNavigationPageRender : NavigationPageRenderer
    {
        public MyNavigationPageRender(Context context) : base(context)
        {
        }

        protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {
            base.OnLayout(changed, l, t, r, b);
            (Xamarin.Forms.Forms.Context as MainActivity).SetImageToToolbar();
        }
    }
}

Change your SetImageToToolbar method to public, and you needn't override OnConfigurationChanged method, just remove it.
Comment: Seems like a good solution. Didn't have the time to try it yet, but as soon as i tried I will accept the answer (: Thanks
Comment: Just tried it out and worked perfectly :) Thanks for your answer

Toolbar Image update when rotating


Solving polynomial equation with calculus

Question: I saw a question stating that
Let $f(x)$ is a polynomial of degree $5 $.
$ x-1|f(x)+1 $ and $x+1|f(x)-1$ . Find $f(x)$ without using calculus.
And because I am not good at calculus , I was not able to solve the question with or without using calculus.
Please help me in solving it.
A hint for how to start could work.
Comment: The two conditions are equivalent to $f(1)=-1$ and $f(-1)=1$ but that's not enough to determine the polynomial univocally.
Comment: But the question is complete
Answer: Followup on previous comment:

The two conditions are equivalent to $f(1)=−1$ and $f(−1)=1$ but that's not enough to determine the polynomial univocally.

Let the quintic be $f(x) = ax^5+bx^4+cx^3+dx^2+ex+f$, then the two conditions give:
$$
\begin{align}
\begin{cases}
a+b+c+d+e+f & = -1 \\
-a+b-c+d-e+f &= 1
\end{cases}
\end{align}
$$
Adding and subtracting the two equations:
$$
\begin{align}
\begin{cases}
a+c+e &= -1 \\
b+d+f & = 0
\end{cases}
\end{align}
$$
The above give the necessary and sufficient relations that the coefficients of $f(x)$ must satisfy, but do not determine $f(x)$ univocally. For example, all of the following satisfy the given conditions:

$f(x) = -x^5$
$f(x) = x^5 - x^3 - x$
$f(x) = x^5 + 3 x^4 - x^3 - 5 x^2 - x + 2$
$f(x) = a x^5 + b x^4 + cx^3 +d x^2 - (a+c+1)x - b-d \quad \text{for} \;\forall a,b,c,d$


Find non-matching pairs in 2 dataframes and make new missing dataframe Python

Question: I have two uneven dataframes that have all the same variables except for a pair of ID values that vary from one to the other.
For example one of the dataframes, df1, looks like this:
Name     Name ID     State     Gen ID      Unit ID
Nikki    9           AZ        1-1         1
Nikki    9           AZ        1-2         2
Nikki    9           AZ        1-3         3
Mondip   101         NY        1A          1A
Mondip   101         NY        1B          1B
James    11          CA        12-1        12
James    11          CA        13-1        13
Sandra   88          NJ        1           1
.
.
.

The other dataframe df2 looks like this:
Name         Name ID     State     Unit ID
Monte        97          PA        4-1
Monte        97          PA        4-2
Nikki Ltd    9           AZ        1
Nikki Ltd    9           AZ        2
Mondip       101         NY        1A
Mondip       101         NY        1B
James        11          CA        12-1
James        11          CA        13-1
.
.
.

As you can see the Gen ID column and the Unit ID column are somehow connected. Sometimes the Unit ID in df2 can be either the Gen ID or the Unit ID in df1.
What I want to do is to create a new dataframe or list of each set of Name, Name ID, and State that does not match df1 and df2. Sometimes the name matches slightly Nikki and Nikki Ltd so I need to take care of this using the Name ID.
For example the new dataframe output df_missing would be:
Name         Name ID     State     Gen ID      Unit ID
Monte        97          PA                    4-1
Monte        97          PA                    4-2
Sandra       88          NJ        1           1

Is there an easy way to do this?
Comment: [Datacompy PyPi](https://pypi.org/project/datacompy/) might be your answer...  I've never used it, let me know if you try it and if it works.
Answer: If we assume that you can identify names that are close enough then the first step would be to replace instances of 'Nikki LTD' with 'Nikki'. Once you do that its a simple matter to identify the names that are not mutual to each dataframe. These names are
 merged_df = pd.concat([df1, df2])
 s1 = set(df1['Name'].unique())
 s2 = set(df2['Name'].unique())
 # read as every in s1 thats not in s2 and everyone in s2 thats not in s1
 mutually_distinct_names = list((s1 - s2).union(s2 - s1))
 missing_df = merged_df[merged_df['Name'].isin(muutally_distinct_names)]


LU Decomposition: difference between between hand calculation and solver?

Question: I have a $3 \times 3$ matrix $A$ and have to perform the $LU$ Factorization (1)
$$ A = \begin{bmatrix}
1 & 2 & 3 \\
1 & -1 & 3 \\
-2 & -10 & -2
\end{bmatrix}$$
Using row reduction, I would first substract the second row by (1/1) the first row which gives (2):
$$ \begin{bmatrix}
1 & 2 & 3 \\
0 & -3 & 0 \\
-2 & -10 & -2
\end{bmatrix}$$
I would then substract the third row by (-2/1) the first row which gives (3)
$$ \begin{bmatrix}
1 & 2 & 3 \\
0 & -3 & 0 \\
0 & -6 & 4
\end{bmatrix}$$
Finally I would substract the third row by (-6/2) the second row which would give (4):
$$ \begin{bmatrix}
1 & 2 & 3 \\
0 & -3 & 0 \\
0 & 0 & 4
\end{bmatrix} = U$$
with the factor found in (2) (3) and (4) I can get the matrix $U$
$$L =  \begin{bmatrix}
1 & 0 & 0 \\
1 & 1 & 0 \\
-2 & 2 & 1
\end{bmatrix}$$
I can verify that $L \times U = A$
However when I compute [L, U] = lu(A) with Octave, I get
$$ U =
\begin{bmatrix}
-2 & -10 & -2 \\
0 & -6 & 2 \\
0 & 0 & 1
\end{bmatrix}$$
and
$$ L=
\begin{bmatrix}
-0.5 & 0.5 & 1 \\
-0.5 & 1 & 0 \\
1 & 0 & 0
\end{bmatrix}$$
Here is the octave / matlab code:
A = [1 2 3; 1 -1 3; -2 -10 -2];
U_hand = [1 2 3; 0 -3 0; 0 0 4];
L_hand = [1 0 0; 1 1 0; -2 2 1];

L_hand * U_hand

[L, U] = lu(A)

How can how explain the differences? I'm probably wrong somewhere but where?
Comment: You're sure that's Octave's output?  $L$ is *not* lower triangular.
Comment: @ecjb: I wonder if Octave is permutting as it goes. Try [l, u, p] = lu (A) and see if $p$ is a permutation result.
Comment: Thanks @Moo : indeed [l, u, p] = lu(A) proves that octave is permutting. For which sake? I don't know
Comment: Thank you @GNUSupporter8964民主女神地下教會. I added the code in the question. I'm probably wrong somewhere but where?
Comment: The odd output from Octave aside, you do realize that LU factorization is not unique, right?
Comment: @amd: "LU factorization is not unique" : I suspected it but didn't know it: thanks
Answer: You shouldn't have got that for your LU decomp. I used python which uses the same LAPACK
import scipy.linalg
import

A = scipy.array([[1 ,2,3],[1, -1, 3 ] ,[-2,-10,-2]])
P,L,U = scipy.linalg.lu(A)

L
Out[3]:
array([[ 1. ,  0. ,  0. ],
       [-0.5,  1. ,  0. ],
       [-0.5,  0.5,  1. ]])

U
Out[4]:
array([[ -2., -10.,  -2.],
       [  0.,  -6.,   2.],
       [  0.,   0.,   1.]])

Upon further inspection. The reference says
It's the product of the permutation matrix and the L matrix

With two output arguments, returns the permuted forms of the upper and
  lower triangular matrices, such that A = L * U. With one output
  argument y, then the matrix returned by the LAPACK routines is
  returned. If the input matrix is sparse then the matrix L is embedded
  into U to give a return value similar to the full case. For both full
  and sparse matrices, lu loses the permutation information.

Which leads to testing it in Python.
Atest = np.dot(P,L)

Out[2]:
array([[-0.5,  0.5,  1. ],
       [-0.5,  1. ,  0. ],
       [ 1. ,  0. ,  0. ]])

Comment: thanks @RHowe, I agree that `Python` could be a good alternative but I take a class which uses `Octave` so I try to do as everybody do. Did you try the code in `octave`?
Comment: i just ran it in octave you're right. I'm looking at the documentation
Comment: updated, its the product of the permutation matrix and the L matrix. its automatically doing it.
Comment: many thanks @RHowe. Do you have a link to the reference?
Comment: https://octave.sourceforge.io/octave/function/lu.html


Basic question regarding addition in $p$-adic integers

Question: I just learned $p$-adic integers and I am confused about something. I was wondering if someone could possibly explain me how it is done.
Suppose I have $\bar{a} = 1 + 0 \cdot p + 0 \cdot p^2 + 0 \cdot p^3 + ... $
and $\bar{b} = 0 + (p-1) \cdot p + (p-1) \cdot p^2 + (p-1) \cdot p^3 + ... $
I know $\mathbb{Z}_p$ forms a ring, but I was wondering what
$\bar{a} - \bar{b}$ was?
Is the situation different from $1 - 0.9999... = 0$ in real numbers?
Thanks!
Answer: First, note that $\bar{b} + 1\cdot p = 0$, so that $-\bar{b} = 1\cdot p$. Then we can compute $\bar{a} - \bar{b} = 1 + 1\cdot p$.
Comment: I see. Thank you! Are there situations like $1 - 0.999999... = 0$ in $p$-adic integers (where one element may have two different representations)?
Comment: Try to construct such an example and see if you are able to.


How do I calculate Fourier Transform of $\frac{\sin t}{t}$?

Question: How do I calculate Fourier Transform of $\,\dfrac{\sin t}{t}$?
I tried to calculate transfrom from $\sin(t)$ and $\frac{1}{t}$ and than multiply but I don't get correct solution.
Answer: The sinc function is not in $L^1({\mathbb R})$, hence you cannot compute its Fourier transform directly, using the formula
$$\hat f(\xi)=\int_{-\infty}^\infty f(x)e^{-2\pi i\xi x}\>dx\ ,\tag{1}$$ or similar. But sinc is in $L^2({\mathbb R})$, hence by a fundamental theorem of Fourier analysis it has a Fourier transform $g\in L^2({\mathbb R})$, and conversely: sinc is the Fourier transform of some $g\in L^2({\mathbb R})$. Fortunately in this example the $g$ is in $L^1$, so that we can directly verify that $\hat g={\rm sinc}$. As sinc is an even function it then follows by the $L^2$ inversion theorem that $\widehat{\rm sinc}=g$.
This $g$ is a rectangle function:
$$g(\xi)=b\quad (-a\leq \xi\leq a), \qquad g(\xi)=0 \quad({\rm otherwise})\ ,\tag{2}$$ whereby the values $a$, $b$ depend on your exact specification of the Fourier transform.
The space $L^p({\mathbb R})$ consists of all functions $f:\>{\mathbb R}\to{\mathbb R}$ having finite integral $\int_{-\infty}^\infty|f(t)|^p\>dt$.  Since $\int_{-\infty}^\infty\bigl|{\rm sinc}(t)\bigl|^2\>dt$ is finite we know that ${\rm sinc}\in L^2({\mathbb R})$. The function $g$ in $(2)$ is in $L^1({\mathbb R})$, hence it is allowed to compute its Fourier transform in the usual way $(1)$. It turns out that $\hat g={\rm sinc}$, up to scaling constants.
Comment: What is L1(R)??
Answer: The reason that your approach failed is that $\frac{1}{t}$ does not have a Fourier Transform.
One possible calculation of the Fourier Transform of $\frac{\sin t}{t}$ is as follows. It's not very rigorous, but it gets the job done and can be made rigorous, if one so wishes, using distributions.
\begin{align}
\hat{f}(\omega)&=\mathcal{F}\left[\frac{\sin t}{t}\right](\omega) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty\frac{\sin t}{t}e^{i\omega t}\,dt\\
\hat{f}'(\omega)&= \frac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty\frac{\sin t}{t}\frac{\partial}{\partial\omega}e^{i\omega t}\,dt\\
&=\frac{i}{\sqrt{2\pi}}\int_{-\infty}^{\infty}\sin t\,e^{i\omega t}\,dt\\
&=\frac{1}{2\sqrt{2\pi}}\left[\int_{-\infty}^\infty e^{i(\omega+1)t}\,dt -
 \int_{-\infty}^\infty e^{i(\omega-1)t}\,dt\right]\\
&=\sqrt{\frac{\pi}{2}}\left[\delta(\omega + 1)+ \delta(\omega - 1)\right]
\end{align}
Now, we know that
$$\hat{f}(0) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty\frac{\sin t}{t}\,dt = \sqrt{\frac{\pi}{2}}$$
and thus, we arrive at $\hat{f}(\omega)$ by integrating $\hat{f}'(\omega)$. Thus, we have:
\begin{align}
\hat{f}(\omega) &= \sqrt{\frac{\pi}{2}}\left[H(\omega + 1) -H(\omega-1)\right]\\
&=\sqrt{\frac{\pi}{2}}H(1-|\omega|)
\end{align}
where $H$ is the Heaviside step function.
Comment: Could you explain the last step where you introduce $\delta(t)$?
Answer: So I'll first note the definition of the sinc() function
$$\mathrm{sinc}\,\,{t} \equiv \dfrac{\sin{\pi t}}{\pi t}$$
and an integral property of the sinc() function that I'll use below
$$\int_{-\infty}^{\infty} \mathrm{sinc}\,\,{at} \,\, \mathrm{d}t = \dfrac{1}{|a|}$$
Here is one method to compute the Fourier Transform of $\dfrac{\sin{t}}{t}$:
$$\begin{align*}F(s) &= \int_{-\infty}^{\infty} \dfrac{\sin{t}}{t} e^{-2\pi i s t}\mathrm{d}t\\
&=\int_{-\infty}^{\infty} \dfrac{\sin{t}\cos{2\pi st}}{t}\mathrm{d}t -i\int_{-\infty}^{\infty} \dfrac{\sin{t}\sin{2\pi st}}{t}\mathrm{d}t\\
&=\int_{-\infty}^{\infty} \dfrac{\sin{t}\cos{2\pi st}}{t}\mathrm{d}t -i0\\
&=\int_{-\infty}^{\infty} \dfrac{\sin(t+2\pi s t)}{2t}+\dfrac{\sin(t-2\pi s t)}{2t}\mathrm{d}t\\
&=\int_{-\infty}^{\infty} \dfrac{\sin\left[\left(\frac{1}{\pi}+2s\right)\pi t\right]}{2t}+\dfrac{\sin\left[\left(\frac{1}{\pi}-2s\right)\pi t\right]}{2t}\mathrm{d}t\\
&=\int_{-\infty}^{\infty} \dfrac{\left(\frac{1}{\pi}+2 s\right)\pi}{2}\mathrm{sinc}\left[\left(\frac{1}{\pi}+2s\right)t\right]+\dfrac{\left(\frac{1}{\pi}-2 s\right)\pi}{2}\mathrm{sinc}\left[\left(\frac{1}{\pi}-2s\right)t\right]\mathrm{d}t\\
&=\pi\left[\dfrac{1}{2}\dfrac{\frac{1}{\pi}+2s}{\left|\frac{1}{\pi}+2s\right|}+\dfrac{1}{2}\dfrac{\frac{1}{\pi}-2s}{\left|\frac{1}{\pi}-2s\right|}\right]\\
&=\pi\left[\dfrac{1}{2}\dfrac{s+\frac{1}{2\pi}}{\left|s+\frac{1}{2\pi}\right|}-\dfrac{1}{2}\dfrac{s-\frac{1}{2\pi}}{\left|s-\frac{1}{2\pi}\right|}\right]\\
&=\pi\left[\dfrac{1}{2}\mathrm{sgn}\left(s+\frac{1}{2\pi}\right)-\dfrac{1}{2}\mathrm{sgn}\left(s-\frac{1}{2\pi}\right)\right]\\
&= \begin{cases}\pi&\quad |s|< \frac{1}{2\pi}\\
0&\quad |s| >\frac{1}{2\pi}\end{cases}
\end{align*}$$
Comment: I had a question: Is it okay for us to compute the integral like this, considering how $\sin t/t$ is not (Lebesgue) integrable?


DPM 2012 - recovering files - How?

Question: Having installed DPM 2012 and created a protection group with a server and selecting a folder on that server when I come to do a recovery it seems I have to recover the whole folder.
Am i missing something; how do I recover a single file from that folder being protected?
Jason
Comment: Are you doing host-based backups (i.e. backing up an entire VM, the equivalent to imaging), or filesystem backups?
Comment: Not backing up an entire VM; just choosing to backup a server
( Physical) and then choose the folder on that server to backup.
cheers, J
Answer: For some reason when in remote desktop it was very hard to click on the folder. when on the main console I've just realised that you need t double click the folder and then you can see the files under it. doh!

DPM 2012 - recovering files - How?


Given a normal distribution, a mean, and standard deviation what is the probability a Variable is in a range

Question:
Possible Duplicate:
Normal distribution probability

Issues getting to the bottom of a HW problem, but I am not looking for the answer, just some guidance.
x has a normal distribution with
   the specified mean = 15.9
   and standard deviation = 3.6
Find the indicated probability P(10 ≤ x ≤ 26)?
I assume i need to take the values 10 and 26 and calculate Z-Scores, and then go the Z-Score table and take the differences in the P-Values?  Is this the right approach or am I missing something?  I followed that reasoning and the answer was wrong - so either I made a rounding  mistake, or have chosen the wrong path.
Thank you for the advice in advance.
Comment: If you can get away from always thinking in terms of $p$ values and $z$ scores and R commands and want to learn how to _use_ tables of normal distribution probabilities (instead of just being told that the answers can be looked up in tables), [this answer](http://math.stackexchange.com/a/202612/15941) on math.SE might be useful.
Answer: Am I missing something or is this basic probability calculus? for any r.v. $X$ with a known cumulative distribution function $F_X (x)$, $P(a<x\leq b) = F_X (b) - F_X (a)$.
Answer: You need to perform transformation of the random variable with distribution
$$
X \sim \mathcal{N}(a=15.9,b^2=3.6^2)
$$
to normal variable
$$
Z \sim \mathcal{N}(0,1)
$$
To do this use the formula:
$$
P(X<m) = P( \frac{X-a}{b} < \frac{m-a}{b})=P(Z<\frac{m-a}{b})
$$
The idea is that the expression $$Z = \frac{X-a}{b} \sim \mathcal{N}(0,1)$$ has standard normal distribution.
Then you can use std. distribution table to get values of $$P(Z<\frac{m-a}{b})$$
Answer: I redid the problem using R (I didn't know the pnorm function existed) as opposed to the Z-sore table and the process was correct (the correct answer was one hundredth off, so I must have made a typo).  I suppose I just assumed I did the problem wrong.
Comment: In R: pnorm(26, 15.9,3.6)-pnorm(10, 15.9,3.6)


EFQ propertyCondition Doesn't work in Simpletest

Question: This Entity Field Query works as expected outside of simpletest:
$query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_exhibition_window_start', 'value', $date, '<=')
  ->fieldCondition('field_exhibition_window_end', 'value', $date, '>=')
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
  ->propertyCondition('status', '0');

Inside of a simpletest, after the creation of an unpublished node within specified parameters, it unexpectedly returns zero results.
However, if I comment out this line:
  ->propertyCondition('status', '0');

(and put a semicolon on the line above) then the query works as expected and returns a node ID. I've even done a node_load() on the node ID returned and inspected the node to be sure that it is, in fact, at that exact moment in time, unpublished.
My simpletest has a user with node access bypass permissions, and I'm using DANGEROUS_ACCESS_CHECK_OPT_OUT, so it doesn't seem like a permissions issue.
Does Simpletest do something weird with EFQs? Why isn't it finding my unpublished node?
Answer: It turns out that the status of my node was, in fact, being set to '1' immediately prior to this query running, but that despite the fact that the node_save() that was called immediately after node_publish_action() should have cleared the cache, node_load() was in fact calling a cached version of the node.
I got around this by adding the TRUE parameter to node_load().
NOTE: You can't skip the middle parameter, á la node_load($nid, TRUE). This is annoying, because it will fail silently and it will just return a boolean FALSE. To get a node without caching, and also without specifying a VID, you must use node_load($nid, NULL, TRUE).
In a simpletest, you can also use a TRUE parameter like so:  drupalWebTestCase::drupalGetNodeByTitle($nid, TRUE).


Iterar um formulário com JS

Question: Tenho um formulário com alguns itens, sendo que algumas células contem os dados de código do banco e código de conta a receber.
Numa mesma célula possuo 2 inputs distintos, um checkbox e um hidden. Eu preciso iterar e pegar os valores de todos os checkboxes que estiverem marcados, incluindo o valor do campo hidden desta célula. Este campo é o código do banco para gerar o boleto.
Ou seja pode ter mais de uma conta a receber de um mesmo banco.
Preciso depois de iterar enviar cada conta a receber para o seu devido boleto.
Segue abaixo um trecho do código:
<form id="frmGrid">

            <input type="checkbox" name="chkboleto" value="119" checked />
            <input type="hidden" name="hdn_banco" value="001" />

            <input type="text" name="name" />

            <input type="text" name="lastname" />

            <input type="checkbox" name="chkboleto" value="120" />
            <input type="hidden" name="hdn_banco" value="001" />

            <input type="text" name="name" />

            <input type="text" name="lastname" />

            <input type="checkbox" name="chkboleto" value="130" checked/>
            <input type="hidden" name="hdn_banco" value="100" />

            <input type="text" name="name"/>

            <input type="text" name="lastname" />

            <input type="checkbox" name="chkboleto" value="140" checked/>
            <input type="hidden" name="hdn_banco" value="100" />

            <input type="text" name="name" />

            <input type="text" name="lastname" />

Answer: É só uma questão de usar seletores do jQuery para achar os elementos. Vou explicá-los:

td:has(input[type='checkbox']): obter todos os td que possuem um input cujo type='checkbox'
de posse dos tds, para cada um deles, obter o input checkbox e o input text, respectivamente:

input[type='checkbox']
input[type='text']

var tds = $("td:has(input[type='checkbox'])");

var msg = "";

$.each(tds, function(i, v) {
  var checkbox = $("input[type='checkbox']", this).val();
  var hidden = $("input[type='hidden']", this).val();
  var data = JSON.stringify({
    checkbox: checkbox,
    hidden: hidden
  });
  msg += data + "\n";
});

alert(msg);

<form id="frmGrid">

        <input type="checkbox" name="chkboleto" value="119" checked />
        <input type="hidden" name="hdn_banco" value="001" />

        <input type="text" name="name" />

        <input type="text" name="lastname" />

        <input type="checkbox" name="chkboleto" value="120" />
        <input type="hidden" name="hdn_banco" value="001" />

        <input type="text" name="name" />

        <input type="text" name="lastname" />

        <input type="checkbox" name="chkboleto" value="130" checked/>
        <input type="hidden" name="hdn_banco" value="100" />

        <input type="text" name="name" />

        <input type="text" name="lastname" />

        <input type="checkbox" name="chkboleto" value="140" checked/>
        <input type="hidden" name="hdn_banco" value="100" />

        <input type="text" name="name" />

        <input type="text" name="lastname" />

Answer: Sugiro ires buscar primeiro os elementos que estão "checados" com
$('input[type="checkbox"]:checked')

depois podes usar essa coleção/array e mapear para teres outro conteúdo lá dentro. Assim iterando podes retornar um objeto com informação desse checkbox e também do próximo elemento hidden que é seu sibing e pode ser obtido atravéz do método .next().
Uma função com isto seria:
var checked = $('input[type="checkbox"]:checked').map(function(){
   var hidden = $(this).next()[0];
    return {
        checkbox: {name: this.name, value: this.value},
        hidden: {name: hidden.name, value: hidden.value}
    }
}).get();

jsFiddle: https://jsfiddle.net/3me57xrh/
e estaria pronto para mandar para o servidor com AJAX como JSON. Algo assim:
$.ajax({
    url: "pagina.php",
    method: "POST",
    data: JSON.stringify(checked),
    dataType: "json",
    success:function(data) {
         alert('dados enviados!';
    }
});

Comment: Muito bom o seu exemplo. Além de me ajudar bastante me fez ir à api do Jquery estudar o que usou no exemplo de resolução que me deste. Se não for abusar demais gostaria que me disesse como gerar mais de um boleto para um banco.
Comment: @Fininhors o que é "boleto"? em Portugal não usamos esse nome.
Comment: Boleto bancário, é um documento que possui um valor a ser pago em um banco(local fisico) ou pelo internet banking.
Comment: @Fininhors queres dizer que queres gerar mais uma `` e enviar para o servidor?
Comment: quero dizer que preciso pegar os pares de codigos hidden.value e this.value e gera um documento. Para cada hidden.value pega-se os referidos valores do chekbox e gera o seu documento. Entendeu??
Comment: @Fininhors a variável `checked` no meu exemplo tem isso. Queres gerar isso no PHP ou JavaScript? para a base de dados ou para o cliente... não entendi bem. Se calhar é melhor fazer outra pergunta e assim tens mais espaço para explicar
Comment: @Sergio Se eu entendi bem, ele basicamente quer fazer um `ajax` pra cada `checkbox`.

Iterar um formulário com JS


DNN: Mapping a fixed length string to another fixed length string

Question: I have a situation where I'd like a DNN to learn the [unknown] mapping between two fixed-length strings. A [simplistic] example:
"-+--++-++-" -> "968"
"+-+-+-+-+-" -> "185"
"-+-+-+++--" -> "766"

I can normalize the characters in the input string to convert them into the numerical inputs required by the DNN but I'm not sure how to structure the output layer (I'm using Keras).
Assuming the output string is 3 characters long:
model = models.Sequential()
model.add(layers.Dense(x1, activation='relu', input_shape=(N,)))
model.add(layers.Dense(x2, activation='relu'))
...
model.add(layers.Dense(3, activation='???'))

I'll need a way to convert the 3 outputs back into characters.
I can't seem to figure out which activation function I should use.
I'll also need to choose appropriate optimizer and loss functions

--
model.compile(optimizer='???', loss='???')

Comment: I think it would help if you described what the strings mean.
Answer: I actually suggest making the output layer Dense(n*k) where $n$ is the number of symbols in the ouput string and $k$ is the alphabet size. Then reshape the output to $n$ by $k$ and apply softmax along the $k$ axis. This will result in a matrix $M$ where $M_{ij}$ is the probability that the $i$th letter is symbol $j$.
At training time, you shouldn't bother with converting the output into characters. Instead, convert the target string to a 1-hot encoding, which will also be an $n$ by $k$ matrix. Apply standard categorical crossentropy loss between the 1-hot encoded target and matrix $M$.
As for optimizer, it usually doesn't matter much. Either Adam or RMSProp should be able to get you good results. For activation, I suggest relu, but the last layer before the softmax should have no activation.
At test time, in order to retrieve the actual output characters, the $i$th output character will be $\text{argmax}_j M_{ij}$.
Comment: Yes, if the string is binary, then encoding as 0.0's and 1.0's should work fine. If it is not binary, then try using a 1-hot encoding for each symbol.
Comment: That does not look completely correct. To be honest, i'm not familiar enough with keras to tell you what the correct way to do this is. However, in tensorflow, it would look something like: `out = tf.nn.softmax(x, dim = 1)` where both `out` and `x` are shaped `n` by `k`. Also, another complication is that we are not dealing with a categorical distribution anymore, but an array of categorical distributions (since each predicted symbol is a categorical variable!), therefore using keras' built in categorical cross-entropy loss may not work. You might have to write your custom loss metric.
Comment: Thank you so much. Do you agree that simply normalizing the input string (into an array of floats) makes sense for the first/input layer?
Comment: Here is a quick [code example](https://gist.github.com/anonymous/eef4e163441fd98e78c901df79287092) of how I've tried to implement your suggestions. I would appreciate it if you'd take a quick look.


Solve $x^{10} + 4x^3 +3x + 4 \equiv 0 \pmod {(4\cdot3)}$

Question: Solve $x^{10} + 4x^3 +3x + 4 \equiv 0 \pmod {(4\cdot3)}$

Work:
Let $P(x) = x^{10} +4x^3+3x+4 \equiv 0 \pmod 2$ and $12=4\cdot3=2^2\cdot3$
We have $P(x) \equiv0 \pmod {2^2}$ and $P(x)\equiv0\pmod3$
For $\pmod {2^2}$,
$x^{10} + 4x^3 +3x + 4 \equiv 0 \pmod 2$
Try $[0],[1]$,
$[0]$ works since $P(0) =4 \equiv0\pmod2$, say $a_1 =0$
$[0]$ lifts to a unique solution to a class that $[a_2] \in \mathbb{Z}_{2^2}$ so that $P(a_2) \equiv 0 \pmod {2^2}$
Solving $P'(a_1)\cdot x =3\cdot{x}\equiv1\pmod2$, $\overline{P'(a_1)}=x=1$
any representative in class of
$a_2 = a_1 -\overline{P'(a_1)}\cdot {P'(a_1)}=3-1\cdot3=0\equiv{0}\pmod{2^2}$
$0\pmod{2^2}$ the only solution to $P(x)\equiv{0}\pmod{2^2}$
For $\pmod3$,
$x^{10} + 4x^3 +3x + 4 \equiv 0 \pmod 3$
Try $[0],[1],[2]$, $[1]$ works. Say $a_2=1$
$P(1)$ is a solution to $\pmod3$
and how do I combine 2 cases??
Answer: If you want $n \equiv 1 \pmod 3$ and $n \equiv 0 \pmod 4$ you can just try the multiples of $4$ until you find one that works.  In this case it is $4$.  So $P(4)\equiv 0 \pmod {12}$.  Here is a check from Alpha
Comment: @Paul:  modulo $12$ there are only three multiples of $4:  0,4,8$  One of them will have each remainder mod $3$, so you want to find the one that is $1 \pmod 3$.  This is a case of the Chinese Remainder Theorem.
Comment: mutliply 4 with??


How to set up effective bidirectional document change sync between MarkLogic DB and file system?

Question: MLCP could be used to export and import documents from file system to and from ML DB.
However it is ineffective to import and export everything.
Only delta changes could be synced.
How to do that?
The first question is how to detect a delta change (new, modify or delete) from both ML and file system.
I could use a file checksum (if the timestamp is not acceptable) to detect changes made on the file system. But how to do that with ML DB? Do I need to use some metadata property like [last change time] or [checksum] to detect that?
The next questions is how to set up orchestration sync. Should I explore Apache NIFI?
(The assumption is to set up bi-directional sync for about once a day. Realtime sync is not required.)
What tools should I use? I believe I need to use MLCP as it is more efficent to handle bulk documents import and export.
Answer: You might not realize it but you are describing event driven architecture and perhaps more specifically event sourcing.
Essentially, you can shift your thinking to see each change on a filesystem or MarkLogic document as an "event". You need a way to capture when these events occur, a log to maintain events in the order they occurred and finally something to process and react to events that have already occurred.
In this case you need something to capture changes to MarkLogic documents (events), something to store those events and something to modify the filesystem to sync to the events. You also need something to capture filesystem changes (events), something to store a record of those events and something to modify MarkLogic to sync to the captured events.
You will need to plan out how to handle when the filesystem and MarkLogic make different changes at the same time to the same document(s). And you need to ensure that changing data in one system to sync with the other system doesn't create an infinite loop of one change bouncing back and forth between these systems.
At best, MarkLogic could capture a log of changes with something like a trigger, transform or API to react to when documents are modified and write a document capturing the change. But, you'll be on the hook to figure out the other components you need.
NiFi could get you further, but NiFi leans more toward being batch-based rather than real-time which could cause collisions of changes in your scenario and you're at the mercy of whether its plugins will do exactly what you need as they are typically not very customizable. NiFi will also be very challenging to maintain the order of changes that occurred independently. NiFi is also not very scalable in my experience with it but YMMV.
I would instead recommend that you look at adopting a message queue for your use case. In particular, I'd suggest taking a look at Kafka. A message queue would allow you to capture events in a central location and process them immediately (reducing the likelihood of change collisions) or at your convenience. The Kafka ecosystem makes it one of the most mature Message Queues as well as one of the simplest to integrate. It already has connectors to capture filesystem changes and the ability to create data pipelines.


Box-Cox transformation of dependent variable only

Question: The function powerTranform from the "car" package in R mentions the following code for Box-Cox transformation for multiple regression:
summary(p1 <- powerTransform(cycles ~ len + amp + load, Wool))
# fit linear model with transformed response:
coef(p1, round=TRUE)
summary(m1 <- lm(bcPower(cycles, p1$roundlam) ~ len + amp + load, Wool))

Is it sensible to apply Box-Cox method to just the dependent variable (and not the whole formula) and proceed with the regression:
library(fifer)
cycles = boxcoxR(cycles)
summary(m1 <- lm(cycles ~ len + amp + load, Wool))

I suspect this method is not right but I am not sure.
Comment: It is possible, of course (if it is sensible is another question). The function `powerTransform` from the `car` package accepts a single vector. So you could use `p1 <- powerTransform(cycles)` and then use `bcPower(cycles, p1$roundlam)` to perform the transformation. Then proceed with the regression as usual.
Comment: @Irish Another explicit purpose of this family of transformations is to help linearize relationships.  At least [Tukey claimed as much.](http://stats.stackexchange.com/a/35717/919) Plausibly, it could be used with predictor series for that purpose.
Comment: @IrishStat While Box and Cox (1964) does largely focus on transformation of DVs, this would be expected, since (as Box&Cox mentions) Box and Tidwell (1962) address transformation of IVs. In addition, section 8 of Box&Cox does discuss simultaneous transformation of both y and the x's. So while the prime focus of the Box&Cox paper itself is on tranformation of IVs I think it's too strong to state it was never intended to relate to independent variables. If we then add Tukey's work on simultaneous transformations of both (where he also includes log as the '0th power'), ...(ctd)
Comment: @IrishStat I don't dispute your evaluation of it; they're frequently overused and like any model selection process there are biases introduced by trying to optimize them. In general transformations, if used at all, should be based on sounder ground (theoretical considerations, for example); if that's unavoidable, the impact of the selection process on inference needs to be properly accounted for.
Comment: It is interesting that the original Box and Cox paper had two examples in which the eventual choices were logging and taking reciprocals respectively, both of which would have been evident to experienced analysts independently of the Box-Cox machinery.. I think that is the way to use it, **as suggestive**; taking the estimated power too literally and using e.g. 0.123 or -0.456 often leads to models that are hard to interpret and fits that can't be reproduced on similar data. (I set aside fitting power laws $y = ax^b$ where taking logarithms is usually natural as a way to estimate parameters.)
Comment: Always helpful to mention the language you are using, here R.
Comment: The explicit purpose of the Box-Cox transformation is to transform the dependent varIable thus de-linking the variance of the model's errors with the expected value of Y. In my opinion it was never intended to be applied to predictor series.
Comment: By mistake I had kept bcpower in second set of statements also. I have corrected it now.
Comment: @whuber Apparently so but I am not sure why any individual X or all X's would need a transformation that was based primarily on the linkage between  the expected value of Y and the model's error variance see http://stats.stackexchange.com/questions/74537/log-or-square-root-transformation-for-arima/74695#74695 and Aksakal's wise reflections here.
Comment: (ctd)... between Box&Tidwell, Box&Cox and Tukey (and some others) we have plenty of basis for considering transformations of both IVs and DVs. It's not so surprising that many implementations of such transformations parameterize transformations in both in the form $(z^\lambda-1)/\lambda$, and so use "Box-Cox" as a catch-all for transformations of both.
Comment: @Glen_b Unwarranted transformations can be like bad drugs and should be studiously avoided but I certainly see the point that you are making. .
Comment: Agree with @NickCox last comment. I often considered Box-Cox, but always ended up not using it, e.g. applying log-transform. This could be the specificity of my models though. We deal with asset prices which tend to be exponentially growing or GBM processes in most cases.
Comment: The brilliance of Box-Cox I think does include (1) the very natural idea that the data themselves can tell you what transformation is indicated (2) the unification of transformations as a family (3) a unifying likelihood approach. On (2) it's bizarre that Tukey's previous paper in _Annals of Mathematical Statistics_ 1957 is not cited, but Box and Cox is not rich in references. Disclaimer: Sir David Cox and I are not related.
Answer: It depends on your process. For instance, your independent variables are stationary, but your dependent variable is not. You observe that it's variance seems to increase with the level. In this case it's appropriate to apply Box-Cox to the dependent variable only.
The point is that you use this particular transformation to solve certain issue such as as heteroscedasticity of certain kind, and if this issue is not present in other variables then do not apply the transformation to them.
UPDATE:
Here's the typical example when Box-Cox is prescribed, it's from this page. You see how the variable seems to swing wider when the level grows. Personally, I would consider an exponential growth with multiplicative errors, but this is a classic example for Box-Cox.

Comment: Whether or not the variance of Y increases/changes with level is not the issue. That kind of non-stationarity or Gaussian violation can often be more easily treated with Intervention Detection schemes. Box-Cox tests ( is a remedy) for the linkage between the expected value of Y and the models error variance ... nothing to do with the variance of Y or X
Comment: @IrishStat The model errors are not observable. It's convenient to talk about them as if we knew them, of course, but the reality's that we don't know them. What you observe is Y and X. When your Y looks like swinging more at higher levels than at lower levels you consider applying Box-Cox.
Comment: http://www.autobox.com/cms/index.php/news/54-data-cleansing-and-automatic-procedures presents a counter example ( start with slide 14 ) where there is larger/ higher variability of Y for higher levels of Y BUT this goes away when you model Y taking into account a few pulses/unusual values. To reiterate the Box_cox test evaluates the dependency/linkage  between Y and the error variance. It has nothing to do with the actual variablility of Y itself.
Comment: @Irish I cannot recognize the data in your analysis beginning at p. 14.  In particular, your plot of annual SD vs. annual mean on p. 15 doesn't look remotely consistent with the data shown on the preceding page. (The plot you describe on p. 15, as I understand it, can be produced in `R` with the commands `x <- matrix(AirPassengers, 12); plot(colMeans(x), apply(x, 2, sd))`)
Comment: @wuber thanks for picking up on this. The plot (inadvertently) shows the relationship between the standard deviation of the transformed data versus the mean of the observed values. If one simply plots the annual standard deviation and the annual mean in the observed metric there is visual linkage. We will fix this. Trust but Verify !
Comment: @wuber after reviewing the results ... if you filter the Y variable by  double differencing (1-B**1)(1-B**12) you get a vector or residuals. The annual standard deviations of those residuals is then plotted versus the annual means of the observed series. This plot suggests that the standard deviations are not linked to the observed means and that there is only one year ( the last) one where the standard deviation is high relative to the mean causing a spurious correlation between them.


with some s having pseudo-elements and others not

Question: 1. quick brown fox
<2. jumped over>
<3. the lazy dog>

I want to have some
s in a single
 styled with ::before and ::after pseudo-elements (the < and > in items 2 and 3 above). Right now, I have it built as two lists. I am trying to find a way to do that using just one
 rather than two, so I can avoid having to use counter-reset.

.li_var {
  counter-reset: lt 1;
}
.li_var > li {
  counter-increment: lt;
}
.li_var > li::before {
  content: "<" counter(lt);
}
.li_var > li::after {
  content: ">";
}

quick brown fox

jumped over

the lazy dog

my working solution:
.li_var {
    list-style-type:none;
}
.li_var > li {
    counter-increment: lt;
}
.li_var > li:before {
    content: counter(lt) '. ';
}
.li_var li:nth-child(2), .li_var li:nth-child(3) {
     margin-left:-.6em;
}
.li_var li:nth-child(2):before, .li_var li:nth-child(3):before {
     content: '<' counter(lt) '. ';
}
.li_var li:nth-child(2):after, .li_var li:nth-child(3):after {
     content:'>';
}

Comment: Logically, does this content belong to two distinct lists? If so, why put it in one list - would this not negatively impact visitors using assistive technology?
Comment: The issue is a conflation of two different lists, or the unnecessary division of one logical list. Either way, you could leave the end-user confused. Imagine I send you to the store to pick up: 1. Cheese, 2. Milk, 3. Cereal, and 1. Bread.
Comment: That depends entirely on the content of the list(s). My only desire here is that you consider the logical structure of what you're building, as much as you consider the visual presentation.
Comment: It really does belong in one list.  I hadn't considered assistive technology.  What would be the issue there?
Comment: Understood.  Do you feel that the issue is resolved by having one list?
Answer: You could use the adjacent sibling combinator, +, in order to select the li elements with preceding li siblings:

.li_var {
    padding-left: 0;
}
.li_var > li {
    counter-increment: lt;
}
.li_var > li:before {
    content: counter(lt) '. ';
}
.li_var > li + li:before {
    content: '<' counter(lt) '. ';
}
.li_var > li + li:after {
    content: '>';
}

quick brown fox

jumped over

the lazy dog

Comment: For my purposes, I ended up using :nth-child instead of the + combinator.
Comment: @Marcelo Probably because I answered first.. not sure though? I just upvoted yours.
Comment: I ran both sets of code and the other rendered more accurately for my situation, because of the padding-left situation - it gave me the idea to do margin-left in my code.  I'm upvoting yours, and I appreciate your answer.
Answer: Based on your desired effect, you can use the first-child, last-child, nth-child, etc CSS selectors to control which elements get styled.
Here is a quick example using first-child:

.li_var > li {
  counter-increment: lt;
}
.li_var > li::before {
  content: "<" counter(lt);
}
.li_var > li::after {
  content: ">";
}
.li_var > li:first-child::before {
  content: "";
}
.li_var > li:first-child::after {
  content: "";
}

quick brown fox

jumped over

the lazy dog

And here is an example using nth-child:

.li_var > li {
  counter-increment: lt;
}
.li_var > li:nth-child(n+2)::before {
  content: "<";
}
.li_var > li:nth-child(n+2)::after {
  content: ">";
}

quick brown fox

jumped over

the lazy dog


How to calculate High Order Moments?

Question: I have a raw data set for Radio Signals (type: complex) and I want to calculate the High Order Moments and Cumulants (see this paper PART: II-A)
In the Paper a Moment(p,q)is defined as following:

I tried to look if there is any implementation of it in python but I only find the K-th centered moment. Also I found an implementation that I did not understand:
def moment(sample, p, q):     #sample is an array of complex values
    m = np.mean((sample**(p-q)) * (np.conjugate(sample)**q))
    return m

and before computing the moments he do the following:
sample = sample/np.power(moment(sample, 2,1), 0.5)

Questions
Can you explain me the difference between M(p,q) and K-th centered moment?
Is the shown implementation of M(p,q) is correct?
What is the reason of recomputing the samples using M(,2,1)?
Comment: as far as I understood it is the `conjugate`
Comment: What is the defn of $x*$?
Answer: The centered moment is something like $\mu_k=E[(x-\bar x)^k]$, while uncentered moment doesn't subtract the mean $M_k=E[x^k]$
Since you deal with complex quantities, you have to adjust the equations so they produce scalar values, not complex, e.g. you can't simply say $x^2$ anymore with complex numbers, you do $x^*x$, where $x^*$ is the conjugate of $x$. So, you don't have simple $M_k$ anymore, for complex quantities it turns into $M_{k,q}=E[x^{k-q}(x^*)^q]$
Here's a simple example. Take a complex number $x=a+ib$, its square is a complex number: $x^2=a^2-b^2+i(a+b)$.
However,
with a conjugate it becomes real: $x^*x=(a-ib)(a+ib)=a^2+b^2$

How to calculate High Order Moments?


error: initializer element is not constant

Question: Estou tentando declarar esse buffer em global e ao compilar apresenta o seguinte erro

error: initializer element is not constant

char    *ls_buffer_PPouAUT =    malloc(5120*sizeof(char));

Como posso resolvê-lo?
Answer: Coloque a variável dentro de uma função.
Não use nada global, é desnecessário em quase todos os casos. Nos casos que pode ser útil precisa saber bem o que está fazendo, entender todas implicações, provavelmente está usando isso inadvertidamente.
Claro, ainda é possível declarar a variável global e inicializá-la dentro da função, idealmente logo no começo da main() para não ficar com estado inválido. Mas evite, é melhor. Crie uma variável local e vai passando como argumento para outras funções ou armazene em uma estrutura que faça sentido.
Variáveis globais são inicializadas durante a compilação. Não pode executar a função malloc() nesse momento, durante a compilação só pode ter valores constantes, assim eles podem ser colocados dentro do executável gerado.
Como esse valor só pode ser conhecido durante a execução, precisa constar em um ponto dentro do fluxo de execução da aplicação. Só as funções possuem fluxo de execução.
É garantido que sizeof char seja 1, então não tem porque usar isso.
Coloquei no GitHub para referência futura.
Comment: obrigado, vou tentar fazer isso, inicializar dentro da função
Comment: O `*sizeof(char)` é completamente desnecessário.
Answer: Usando como referencia  o livro do  Stephen G. Kochan (Programming in C) onde é citado

É possível executar uma função que retorna um valor em tempo de
compilação e usar o resultado como inicializador de uma variável
global. Essa técnica pode ser útil em algumas situações, mas é um
pouco obscura e não é frequentemente usada.

Essa  "obscuridade" dita pelo Kochan  refere se o fato de que essa abordagem  de usar funções de retorno de valores em tempo de compilação para inicializar variáveis globais "pode não ser muito conhecida".
Por tanto, onde esta foi escrito ",durante a compilação só pode ter valores constantes..." complementando,  executar um método que retorna um valor em tempo de compilação e utilizar como inicializador de uma variável global,poderia ser uma solução.
Então qualquer atribuição do valor ao ponteiro global fora de uma função dara erro
porque essa declaração é a inicialização  de uma variável global  que só pode ser feitas com valores constantes em tempo de compilação, fazendo com que o compilador não vai determinar o valor constante em tempo de compilação
Segui um exemplo:
#include <stdio.h>
#include <stdlib.h>

int *ls_buffer_PPouAUT;

//A atribuição do valor ao ponteiro global fora de uma função dará erro
void aloca() {

    ls_buffer_PPouAUT = malloc(sizeof(int));
    if (ls_buffer_PPouAUT == NULL) {
        exit(1);
    }
    // Atribui um valor ao ponteiro global
    *ls_buffer_PPouAUT = 13;
}

int main() {
    aloca();

    printf("global: %d ", *ls_buffer_PPouAUT);
    free(ls_buffer_PPouAUT);
    return 0;
}

Agora nesse caso a variável ls_buffer_PPouAUT é inicializada  e determinada em tempo de execução e o compilador não poderá determinar o valor da constante em tempo de compilação resultando em  initializer element is not constant
#include <stdio.h>
#include <stdlib.h>

int ls_buffer_PPouAUT = rand();

int main() {
    printf("Valor da variável global: %d\n", ls_buffer_PPouAUT);
    return 0;
}


Fundamental property of conditional expectation

Question: I have studied fundamental property of conditional expectation:
$\mathbb{E}[r(X)\mathbb{E}(Y|X)] = \mathbb{E}(r(X)Y] \qquad \text{for every function} \qquad r:S \rightarrow R$
My question is what does mean function $r$. Why left side of equation equals to the right side and what is intution behind this function?
Thanks in advance
Comment: What is the meaning of the sets $S$ and $R$ ?
Comment: You may refer to the lower half of [my answer to another probability problem](http://math.stackexchange.com/a/2148427/290189) for a similar (though not exact) proof.
Comment: Note that we can think of $(X,Y)$ as a random variables that takes values in a subset of $S \times T$

http://www.randomservices.org/random/expect/Conditional.html
Answer: I'm a little confused about the domain/range $S\to R...$ I would think it would just be from the reals to the reals. But, anyway, by function, they mean... function. I don't know another way to put it. Just a function like $r(X)=X^2$ or any other example. The key is that the property holds for any function.
The quickest way to see that the left side equals the right is that $$ r(X)E(Y|X) = E(r(X)Y|X)$$ since you can always pull something conditioned on out of a conditional expectation (when it's conditioned on, it's effectively constant). So plugging this in, we have $$E(r(X)E(Y|X))=E(E(r(X)Y|X)) = E(r(X)Y) $$
where the second equality is the law of total expectation.
Comment: Actually, $S$ may be any measurable space (the one $X$ takes its values in) and $R$ must be $\mathbb R$ the real line.


$(this).data() trims the passed data from a database until a whitespace

Question: Everything works fine except for the part when I am getting a data with a whitespace. I want to get the whole string of data, not the trimmed one.
In my example, every time I get the "data-title" or "data-type", the data will be cut until the whitespace.
I tried placing a static string of data in "data-title" and it worked perfectly. But when I passed a dynamic one, which is from the database, it is trimmed until the whitespace. $row[1] is perfectly shown on a link but is trimmed when it is passed.
HTML
$row[1]

                    <button type="button" class="close" data-dismiss="modal">×</button>

Manage Question

                <form role="form" class="form-horizontal">

                            Question

                                <textarea name="question" class="form-control" id="manage_input_question" placeholder="Question" style="resize:none;"></textarea>

                            Answer Type

                                <select name="type" class="form-control" id="manage_input_type">
                                    <option value="Multiple Choice With Unique Answer">Multiple Choice With Unique Answer</option>
                                    <option value="Multiple Choice With Multiple Answer">Multiple Choice With Multiple Answers</option>
                                    <option value="True or False">True or False</option>
                                    <option value="Identification">Identification</option>
                                </select>

                        <input type="button" id="create_btn" name="create" class="btn btn-primary btn-block" value="Create">

                </form>

JavaScript
$(document).on("click", ".manage_question", function () {
    var question_id = $(this).data('id');
    var question_title = $(this).data('title');
    var question_type = $(this).data('type');

    $(".modal-body #manage_input_question").val( question_title );
    $(".modal-body #manage_input_type").val( question_type );
});

Comment: $(this).data('id').trim() try this
Comment: This works fine for me, [here](https://jsfiddle.net/ujyxaadp/). Can you reproduce it?
Comment: It works fine if I place a static string but not when it is dynamic.
Comment: Can you identify the binary value of the whitespace? I'd suggest it's perhaps not a traditional space, but some other rogue character which is causing your script to fail.
Comment: I can't identify its value because I used a mysqli_real_escape_string() function to place the title of the question to the database. But it is a spacebar when I input the data.
Answer: Ok, I found my mistake here. Instead of
data-id=$row[0] data-title=$row[1] data-type=$row[2]

It should be enclosed with quotes.
data-id=$row[0] data-title='$row[1]' data-type='$row[2]'


How can I call a function each x seconds without stopping the game?

Question: I'm building a project like a player trys to dodge the bullet, so my game calls create_bullet() each time in my while True loop.
I don't know how to call that function with an x time but without using time.sleep() because when I use it, it stops my entire game, even the player movement.
Comment: Time to learn pygame.
Comment: See https://gameprogrammingpatterns.com/game-loop.html, https://eng.libretexts.org/Bookshelves/Computer_Science/Programming_Languages/Book%3A_Making_Games_with_Python_and_Pygame_(Sweigart)/03%3A_Pygame_Basics/3.04%3A_Game_Loops_and_Game_States,  https://stackoverflow.com/questions/54981456/how-to-implement-a-pygame-timed-game-loop and https://stackoverflow.com/questions/16301193/whats-the-proper-way-to-write-a-game-loop-in-python
Comment: You could create a [`threading.Timer`](https://docs.python.org/3/library/threading.html#timer-objects) object that will call a function after a certain amount of time has passed without blocking the rest of your game. If you want this to happen more than once, see [threading.Timer - repeat function every 'n' seconds](https://stackoverflow.com/questions/12435211/threading-timer-repeat-function-every-n-seconds).
Comment: You could generate a custom event on a set time interval and use that to create your bullets, see [this answer](https://stackoverflow.com/a/60880122/2280890) for an example.
Answer: try taking time deltas and check if they are within certain range (5 seconds in this case) you can call your function again. some pseudo code off the top of my head:
tic = some initialized value
while true: # your game's loop

  if (time now - tic) >= 5 seconds:
    tic = time now # update tic
  else:
    let the game loop run
  player.display()
  bullet.display()
  # some game logic happens
  # loop ends and goes back

time.sleep() is not a good way to do it because, as you may already realized, will stop all of the processes running
Answer: Use a timer event pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. The time has to be set in milliseconds.
For a timer event you need to define a unique user events id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event.
interval_in_seconds = 2 # 2 seconds

timer_interval = interval_in_seconds * 1000 # 1000 milliseconds = 1 second
timer_event_id = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event_id, timer_interval)

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

         elif event.type == timer_event_id:

             # call function
             my_funktion()

The timer event can be stopped by passing 0 to the time argument of pygame.time.set_timer.


Continuous surjective mapping from half-open interval to the reals / the Cantor set

Question: 1) Is there a continuous surjective mapping of $(0, 1]$ to $\mathbb{R}$ ?
To me it seems not, but haven't been able to prove why it is false though. I was thinking of finding compact sets contained in (0, 1], and having the right endpoint fixed, e.g $[\frac{1}{2} ,1]$ $[\frac{1}{3}, 1]$, $[\frac{1}{4}, 1]$ etc. But then not sure if this is the right approach or what to do after this.
2) Is there a continuous surjective mapping of $(0, 1]$ to the Cantor Set ?
Again to me it seems not true because Cantor Set is Hausdorff space (to be precise it is Stone space) and we know that the pre-image of continuous functions should conserve compactness if we are mapping to a Hausdorff space, and Cantor Set is compact, but is there any other way to prove this without talking about Hausdorff space or compactness of the Cantor Set?
Comment: 1) consider that the answer is true!. you have to think of function that does not have limit at $0$ and go crazy there...
Comment: Compact Hausdorff is not an obstacle for 2). Take, for instance, the compact Hausdorff interval $[\frac12, 1]$. You can map into that interval nicely by mapping the upper half of $(0, 1]$ via $x\mapsto x$, and the lower half via $x\mapsto 1-x$.
Answer: For 1) consider $\frac{1}{x} \sin\frac{1}{x}$
2) is false since the image of a connected set under a continuous map is connected.


Correct name and technique for 2-5 adjacent strings

Question: I have been learning guitar for almost 1 year now. I mainly play Rocksmith (don't judge me) and Yousician.
I have been nailing a lot of techniques lately e.g. fingertip muting for power chords and my cowboy chords are sounding really good and clear, however I am having some trouble with one final piece which is playing several adjacent strings without hitting the strings around it.
Some example of this that I have run into:
<code>--X--|--X--|--X--|--0--
--X--|--X--|--X--|--0--
--X--|--7--|--X--|--0--
--5--|--7--|--9--|--0--
--5--|--7--|--9--|--X--
--5--|--X--|--X--|--X--
</code>
Or in Rocksmith:

Based on my current experience I assume there is a way to mute the G, B and low E strings in this case, however I have not been able to find a way that feels "correct" so far.
What is a good technique for these notes? I think the reason I am struggling is due to having one finger pressed hard and flat against the fretboard to cover these notes which is really restricting the mobility of my other fingers.
Also, do they have a special name that I can use to look techniques up online (the fact that I can't reference them in search makes it hard to look up)?
Answer: Simplest way is to use hybrid picking - plectrum and fingers together. Especially for this, as you could, for instance, use plectrum/middle/ring fingers for the 3 strings, then move across and do the same, etc.4 strings doesn't need to be problematic, either, just employ pinky. I use this a lot, and it saves muting an in-between string sometimes, say 5, 3 and 2, can be played with plectrum/middle/ring.


Allow traffic from ssl-vpn to enter ipsec tunnel on fortigate

Question: we configured our FortiGate 50B to route traffic from our local net 192.168.10.* (which is our office) to a remote network 172.29.112.* using an ipsec tunnel. Everything works fine as long my computer has an ip from 192.168.10.*.
We can also connect to the office network from at home using a ssl vpn connection. Once connected we receive an ip from 10.41.41.*.
Now I want to allow the traffic flow from 10.41.41.* to 172.29.112.* just like it does from the office network.
Could somebody point me in the right direction what I would need to do?
Thanks, Sascha
Answer: I had this same situation and fixed it by doing adding the policy from the SSL.vpn interface to the IPsec tunnel interface and then from the IPsec tunnel interface back to the SSL.vpn interface.  The issue is what interfaces the traffic is allowed on.  It will not hairpin to an interface that is not defined in a policy.
Answer: I'm in your same situation.
This is what I tried but didn't work (All IPs are an example and were taken from your question):
NAT to a Virtual IP (192.168.10.200)  all traffic coming from SSLVPN (10.41.41.) and going to IPSEC (172.29.112.)  So all SSLVPN traffic is being translated to an internal IP which should go trough the tunnel fine. By this way we could avoid modified IPSEC destination but didn't work.
The only way is to add in both IPSEC sides our SSLVPN network (10.41.41.*), as Alex said so all traffic would be routed fine
Answer: There's some information missing in your question.
Mostly;

Are you NATing traffic inside the IPSEC Tunnel
Are you also managing the peer at the other end of the IPSEC Tunnel

Assuming you are not NATing the traffic in the IPSEC tunnel, this is a quick checklist.
Add the 10.41.41.x subnet to your Interesting traffic
This will indicate that the 10.41.41.x subnet is expected to transit in the IPSEC Tunnel.
You have to make that configuration change on both devices at each end of the IPSEC tunnel.
If this is not done properly, your VPN wont even be able to complete Phase 1 of the IPSEC tunnel.
Add routes
Make sure your SSL VPN sends a proper route to the clients. This mean that the clients should have a route for the 172.29.112.x when connecting to the SSL VPN.
The same is true on the 172.29.112.x network, it needs to know where to route packets to 10.41.41.x .
In some cases, for example if both peers on the IPSEC VPN are also the default routers on their respective network, it might not be needed.
Add policies
I'm not a Fortinet expert but most firewall will also require that you explicitly allow traffic inside a VPN tunnel with policies or ACLs. This is true for both the IPSEC Tunnel and the SSL VPN connectivity.

Like I said, this is a pretty vague answer (i.e. they are pointers) but since there's not much specifics in the question, it's the best I can think of.
Comment: Thanks Alex, for the detailed answer to my imprecise question. (1) No NATing. (2) No, unfortunatly not. I asked the other admin to configure the tunnel to include the missing subnet, but I have to wait for his answer. Once that is done, I'll write a comment about the outcome.
Answer: 1 – Go to Firewall Objects > Address > Addresses > Create New
Create the subnet 172.29.112.0/24 (type Subnet, Interface Any and check Show in Address list) named SubnetRemoteIPSEC
Create another subnet 10.41.41.0/24 (type Subnet, Interface Any and check Show in Address list) named SubnetClientSSL
2 – Go to your VPN SSL Policy and add the SubnetRemoteIPSEC in Local Protected Subnet (you should already have your office subnet here (192.168.10.0/24)).
3 – Add a new policy :
Incoming Interface ssl.root
Source Address SubnetClientSSL
Outgoing Interface Name of your VPN interface
Destination Address all
Schedule Always
Service all
Action Accept
Enable NAT
Use Dynamic IP Pool and Create a pool (you can put the IP LAN of your fortigate 192.168.10.254-192.168.10.254 assuming that 192.168.10.254 is your internal IP).
You will be now able to access to your VPN IPSEC through the VPN SSL.


Find the equation of the tangent to this curve

Question: I'm unsure what I have done is right or not, or my way of thinking.  Please let me know :)
'Find the equation of the normal to the curve $y = x^2 + 4x - 3$ at the point where the curve cuts the Y axis.
So first I'd write it in dy/dx form right?  So $2x^3 + 4$
Then I'd find the value to sub into X?  But what would that be?
Thanks
Comment: I think you mean $2x^{\color{red}{1}}+4$. And what is the $x$-value for _any_ point on the $y$-axis?
Comment: The curve cuts the Y axis when $x=0$. So you know the value to sub into X.
Answer: "Curve cuts the Y axis" -- This means $x = 0$. $$\dfrac{dy}{dx} = 2x + 4$$
So at $x = 0$, $y' = 4$.
The gradient of the normal is $-\dfrac{1}{4}$
Can you go on from here?
Comment: Yes my bad, dydx incorrect!  And thank you!  If the curve cuts the X axis would that still be the same?
Comment: @Alex If the curve cuts the X axis, that means you have to find the zeroes of the equation and evaluate dydx at those points.
Comment: Thank you!  @Airdish!  If we were to say that the NORMAL of the curve, that would just be -1 / gradient correct?
Comment: @Alex Yes that is correct. This is because of the coord. geometry law for perpendicular lines $m_1m_2 = -1$.


Can this integer optimization problem with quadratic-linear piecewise objective & constraints be solved efficiently?

Question: Recently I've been looking into optimization, to try and solve the following problem.
We have several sorts of factory. Each factory-type takes some amount of goods, and produces other goods. The optimisation problem is to try and meet every factory's internal consumption, while overall producing more that $d$, the external demand, of each good. Additionally, we want an integer amount of factories.
Here's a very simple example:
We specify production with a matrix
$$
\begin{pmatrix} 2 & -4 \\ 0 & 1 \\ 0 & 1 \end{pmatrix}
$$
An interpretation could be: A farm makes 2 milk. A dairy takes 4 milk, and makes 1 cheese and 1 pasteurized milk.
If the demand vector is $d = (0 \ \ 2 \ \ 2)^\mathsf{T}$, then the solution will be
$x = (4 \ \ 2)^\mathsf{T}$.
Now, up until this point, this is a LP, and can be solved using standard solvers.
The complication is this: the more factories we have, the greater efficiency in inputs and outputs we have. This scaling factor is specified by the following sort of function.

The idea is that, in the polynomial part, you are benefiting from economies of scale. But after a certain point, you do not get any more multiplicative advantage from placing the factories near each other.
The linear program, abstractly specified, would look something like this:
Let $f$ be the scaling function,
$$\begin{aligned}
  & \mathbf{minimize}(x)\ \ \sum_i (A (f \circ x))_i \\
  & \mathbf{subject\ to} \\
  &\quad A (f \circ x) \geq d \\
  &\quad x_j \geq 0          &(1 \leq j \leq n) \\
  &\quad x_j \in \mathbb{Z}  &(1 \leq j \leq n)
\end{aligned}$$
where $A$ is a matrix, $x$ the input vector we want to minimise, and $\circ$ means element-wise application. (i.e. $f\circ(a_1, a_2, \dots) = (f(a_1), f(a_2), \dots)$.)
My questions are these:

Can the problem, thus specified, be solved 'efficiently'?
(Efficiently not in the abstract complexity sense, but in the sense
of: a reasonably sized problem can be given to a solver and it takes
less than an hour to finish.)

How do I write down this problem in a format a solver can interpret.
I've seen solvers which can take arithmetic expressions, but I haven't seen solvers that can do the sort of piecewise functions I have here.

If the above is too difficult, if I take a linear approximation of the problem, can this be translated efficiently (i.e. no exponential blowup) into something I can give a linear solver?

If even that is too difficult, can I solve the problem by iterating linear problems. An example Idea: start with the maximum efficiency slope, solve that, then adjust the slope depending on the result given then solve that. (This will probably not end up being optimal, but close enough.) Will this, or some other scheme, converge?

Thanks!
Comment: Your scaling function as plotted is not quite convex. It turns linear around 20, but the improvement rate from 20 onward is less than the slope to the left of 20. Is this just a glitch in the plot (meaning the actual scaling function is convex)?
Comment: Unfortunately no. The kink is intentional; the derivatives don't necessarily line up. However, I note that the function is quasi-convex. I've heard you can take quasi-convex functions and do repeated convex optimisations. I don't know if this extends to integer programming, though.
Comment: In fact, it's better than quasi-convex, it's monotone. I was hoping that this would give it some structure that made the problem easier, but this isn't my area, so I don't know if this is actually the case.
Comment: Does $A (f \circ x)$ denote multiplication of the vector $f \circ x$ by a matrix $A,$ or multiplication by a scalar $A,$ or application of a function $A()$ to the vector? If $A$ is a scalar, is it positive? If it is a matrix or function, what properties does it have? Also, what does the summation in the objective sum over? (I suggest editing the question to clarify these rather than answering in comments.)
Comment: I've clarified the variable types in the post. $A(f \circ x)$ is matrix multiplication, with $A$ a matrix, and $f \circ x$ a vector.
Comment: Also, I had an idea on how to solve this. Because $f$ is monotone, you can compute the solution coordinates by inverse mapping. So all you then need is a solver that allows you to 'snap' to points other that the integer points. I'll probably ask another question about if any such thing exists.
Comment: This is called **increasing returns to scale** or **economies of scale**. This concept is used in many economic models. We also have **decreasing returns to scale** (e.g. farmers select first the best farmland). Often this is expressed as a nonlinear production function (and requires nonlinear solvers).
Answer: I'm still not clear on what is being summed in the objective -- the components of $A (f \circ x)$? -- but you can formulate the problem as a mixed integer linear program if you know bounds on $x.$
Assume that $x_i \in \lbrace 0,1,\dots,N_i \rbrace$ for each $i.$ Introduce binary variables $y_{i,j}$ for each $i$ and each $j\in \lbrace 0,1,\dots,N_i \rbrace$ with the constraints $$\sum_{j=0}^{N_i} y_{ij} = 1 \quad \forall i.$$ Also introduce continuous variables $z_i$ defined by the constraints $$z_i = \sum_{j=0}^{N_i} f(j) \cdot y_{ij} \quad \forall i.$$ We set $$x_i = \sum_{j=0}^{N_i} j\cdot y_{ij} \quad \forall i,$$ from which it follows that $z_i=f(x_i)$ and so $z = f \circ x.$ Now minimize the objective (expressed in terms of $z$ rather than $x$) subject to $Az \ge d$ plus the above constraints.
Comment: Ah, right. I want the sum of the components, yes. I will edit to be clearer.


The BCryptPasswordEncoder().encode(plainPassword) not return the same value after each times submit and re-submit

Question: I appy the Spring security in my application and use BCrypt for encode password and I got sometime can login and sometime not logined.I used the code to generate hash password like below:
System.out.println(new BCryptPasswordEncoder().encode("admin"));
And I got many result not the same after re-submit.This is some result print out:
-$2a$10$xbM.XFChI0fV2RYqPe/XSewxSRSzwcbJ5TFAFGACRkTaHWmxL1x..
-$2a$10$VOaha9xUUfzHL0hpd5.HE.RaLx5Gldy/MjapBoQUYYTGVdHLcSh8q
-$2a$10$1/Kf/Un2oQzARrD.SHsh2OC/Dxwpj1aIeatydMEQSbxgfxOkDF27e==
-$2a$10$o61u5t/r0R2jhOouDGWCFuwOLl31NIh8UiDVzRN4TSBybUs4keCmW
That reason sometime I can login and sometime not.
Please help to solve it.
Answer: This is correct; BCryptPasswordEncoder().encode() should always return a different result. That's a security measure which makes it harder to crack the encoded password (this is called "salting passwords")
If you want to know whether a password is correct, you need to use BCryptPasswordEncoder.matches() instead.


Uncaught TypeError: $(...).fullcallendar is not a function

Question: Já tentei de tudo para fazer o fullcalendar funcionar, meu código está assim :
@{
    ViewBag.Title = "Calendario";
    //Layout = "~/Views/Shared/_Layout.cshtml";
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="http://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.css" rel="stylesheet" />

Calendario

Sempre que executo, recebo a seguinte mensagem :

Uncaught TypeError: $(...).fullcallendar is not a function

Alguém pode me ajudar? Não sei se está faltando algum arquivo para mapear, ou se estou utilizando alguma biblioteca errada .
Answer: Há um erro de digitação, você digitou:
$('..').fullcallendar
O correto, é com C maiúsculo e apenas um l em calendar:
$('...').fullCalendar


CentOS 5.10 TCP Sequence Number

Question: We have done a security check on a server and its come back with
Linux Kernel TCP Sequence Number Generation Security Weakness. We are looking to correct this being flagged up on the check
We are using CentOS 5.10 with kernel 2.6.18-371.9.1.el5
Comment: If your security check doesn't tell you more about the vulnerabilities it finds, it's time to switch to a different vendor.
Answer: Sounds like CVE-2011-3188 which has been fixed since the RedHat kernel 2.6.18-274.7.1.el5.
So either that server isn't running the kernel you mention (installed but not rebooted?), it tested the wrong system (some transparent device between the check and the server?) or it is a false positive (unsure why).
Comment: Thanks for the info will get the vendor to check the server again. The server has been rebooted since the kernel updated.

CentOS 5.10 TCP Sequence Number


Is it possible for a left hander to learn guitar right handed?

Question: I am looking to get a guitar for my step son.
He is largely left handed, but currently he plays the drums right handed without any difficulty.
Would the same apply with learning guitar from scratch?
Learning right handed has the obvious advantage that right handed guitars seem to be much more available. Everyone has a right handed guitar, so it would be easier for him to just pick up a friends guitar at a jam. Also, it would be possible for me to play it to show him the ropes.
What is the reasoning behind needing to strum with you dominant hand? Is it learned or is there an essential physiological barrier here that is no point trying to overcome?
I don't want to put him off playing by buying an instrument that he can't play, so will get a lefty if I have to...
Comment: Don't forget every violinist learns to play the same regardless of handedness!
Comment: @MatthewRead the notches in the nut are sized for conventional stringing. Also the bridge is set up to give the right intonation for the conventional strings. Many acoustic guitars have non-adjustable bridges.
Comment: IIRC, Jimi Hendrix was left-handed, but used to play his right-handed electric guitars with left-handed stringing.  Even such asymmetrical guitars as a Fender Stratocaster.  I hear it worked out pretty well for him.
Comment: Many guitars are symmetric and you can just reverse the strings (with caveats, see the next comment.  My guitar has an easily-exchanged nut and reversible bridge).
Comment: Thanks for pointing, the answers there were very helpful, I guess it is just a matter of trying out and finding which one is best, although my main concern was, like many pointed out, the strumming, which I felt could be easier with the left hand. I guess I'll be experimenting with it very soon.
Comment: If it is at all possible get him on a right hand guitar. He will have his strong hand on the neck which would be great.
Comment: I would start with right handed. I am right handed and I learned many task better with the left hand than the right one. Once I had my right hand injured (for a few weeks) and I had to learn to use mouse with my left hand. It felt awkward but after a week my left hand was as precise as the right one. Since then I think the dominant side is maybe overestimated and it is all matter of custom and practice.
Answer: I am left handed, but play guitar right handed with no problems. My 10 year old son does some things left handed and some things right handed (including playing guitar). I think as long as he's not trying to "un-learn" how to play left handed he shouldn't have any issues.
Answer: It's a matter of experimentation.
Some left-handers play right-handed.
Some left-handers play a right-handed guitar, but hold it with the neck to the right, so the bass string is nearest the floor. They learn the chord shapes up-side-down. As you've already observed, this is handy for picking up someone else's guitar and jamming.
Some left-handers play left-handed guitars.
Some right-handers play left-handed guitars. Paul McCartney is a famous example; he is right-handed for most tasks, but he struggled with the guitar until someone suggested he try a left-handed one.
I suppose the easiest way to find out is to watch how he instinctively holds a guitar.
To avoid spending money on a lefty guitar, you could try him out on a right-handed guitar restrung with the strings the other way around. If it turns out to be more than a temporary experiment, you'd want to have the guitar set up for that configuration (adjustments to the nut and the bridge), and of course if there's a scratch plate or a cutaway, those would be in the wrong place -- and when that becomes an irritation, it's time to invest in a left-handed guitar.
Comment: Using a right-handed guitar left-handed, it will be possible to use the lower four strings to play major and minor bar chords in any inversion without "crossing fingers".  I'm right handed, and I haven't tried playing a left-handed guitar, but when I started trying to play the instrument, I was curious to try a left-handed guitar for that reason (as it is, I tune my upper strings to minor thirds to achieve a similar effect).
Comment: What do you mean by "crossing fingers"? It seems to me that playing the mirror image of a F/Fm/B/Bm are all easy enough shapes to achieve.
Comment: An Ab chord (the lowest closed-form bar chord) on the bottom four strings would be 4311XX.  If one reverses the string order, the pinky plays the first (bass) string, the ring finger plays the second string *but may safely touch the first*, and the index finger plays third and fourth strings *but may safely touch the first and second*.
Comment: Good answer. Just one point: so far I know Paul McCartney isn't right-handed but left-handed to most tasks (if not at all) wirting, footing, eating, etc
Answer: I've been playing for 20 years, am left handed, and learned right-handed. In my opinion, this made it easier for me to learn, as my dominant hand was doing the "more complicated" stuff for a long time. The strumming is largely simple motions unless you're looking at playing really sweet fingerstyle (which you shouldn't have a problem with anyhoe if you're picking up piano).
The other major benefit to learning right-handed is that it'll be way easier to play guitars that other people have.
Answer: That your son already plays right-handed drums is a good indicator that he will be able to play right-handed guitar.
I claim this, since the right hand (whether on the hi-hat or ride) in drums plays an identical role to the right hand (strumming) a guitar. Many drum beats require straight 8th/16th notes on the hi-hat (ride), and - at least for acoustic guitar - downstrokes on the guitar are typically straight 8th/16th notes as well. (And accented sticking would be analogous to strum patterns...)
Comment: it is funny that I never thought about this, but the left hand for a right-handed guitar player is actually doing a lot of the hardest bits (at least for rock music).
Answer: Some of my favorite guitarists -- Mark Knopfler and Duane Allman come to mind first -- are left-handed people who play right-handed. And at least one guitarist I know of -- Eric Gales -- is a right-handed guitarist who plays left-handed. Name a way you can play a guitar and I can name a guitarist who made brilliant music like that.
But I would certainly try right-handed before you go left-handed, to see if you could pick that up, because the choices of instruments are just that much greater. If you want a right-handed Strat, you have lots of choices. If you want a left-handed Fender Strat, you have the choice of white, black or sunburst.
Also, consider an orchestra. You think all the people in the strings section are right-handed? But they all play right-handed, because ... if they didn't, they'd always poke each other with the bows.
But, ultimately, for me, I tried to learn lefty, only about 25 years ago, and my left hand always wanted to turn out and my right hand wanted to turn in. Playing lefty just felt wrong. Playing righty might just be wrong for your stepson, like playing lefty is for me.
Comment: I'll add Steve Morse and Mattias Eklundh to the list. I actually asked Mattias how it felt learning to play right-handed guitar and he replied "As far as I'm concerned I'm playing left-handed guitar" ^^
Comment: Also Robert Fripp is left handed but plays right handed.
Comment: Would certainly add Steve Morse, Mattias IA Eklundh and Robert Fripp to the list of my favorite guitarists. Mattias is a _freak_.
Answer: The answer is definitely yes.  The preference for using one hand to another is generally tempered by other activities of skill in these modern times.  It is now more common than ever to find left-handed individuals being able to perform right-handed activities, as you say your step-son can play right handed drums.
I myself was a right-handed guitar (Hendrix) beginner when I was 10 years old and I forced myself to play guitar on the left - my dominant hand (right) thus becoming the strumming hand.  This was not natural for about 3 months but again, the through practice and conditioning, like all skills, this can be acquired.
The reason I will put forward for the dominant hand being the strumming hand is due to rhythm and your possession or control of it.   Ambidexterity (which is rare in guitarists) is where a player has cross-dominance of either hand.  This means that you essentially do not have a MUSCULAR PREFERENCE.    But most of us do not have cross-dominance - but prefer a side.  In fact, humans as a species tend to be more right-handed.  Some studies indicate that this right-handedness has something to do with the right hand's (and the brain's) ability to interpret and perform rhythmic patterns.
HAND PREFERENCE CONSISTENCY AND SIMPLE RHYTHMIC BIMANUAL COORDINATION IN PRESCHOOL CHILDREN
READ THE ABSTRACT
I'm not a neuroscientist, but it's interesting to note that the DOMINANT hand has been observed to be able to carry a constant and "faster" beat. ie. 16ths notes as opposed to 1/4 th notes: similar to a drum pattern for a standard drummer where the high-hat is tapped by the right hand and the "slower" beat is kept by the left.
So, the guitar without the fretting, is essentially a rhythm instrument.  The strumming hand needs to perform a skilled task of keeping time and being dextrous to also be able to accent individual notes/strings.   This is similar to the drummer analogy above.  This preference is innate and "natural" - similar to tapping your hands against your hips, one keeps a fast beat the other keeps a slow beat but both in time - which hand do you prefer for the faster/slower?  This simple test should be a good indicator of which end your guitar will go.
Most people focus solely on the fretting hand as being the driving factor in determining guitar "sides".   I think this is really a judgement of comfort between the jobs that the two hands need to perform: If there is a natural order to strike the strings instead of intricate finger-work you will quickly see this and that should determine whether you are left/right handed.
Comment: So... perhaps this is why lefty drummers usually hit the hi-hat with the left hand? This is some interesting info. I wonder how it affects me now that I'm playing the Stick, tapping the bass strings with the left hand, which is new to the fretboard after years and years of playing guitar and bass...
Answer: If your main aim is to be able to play a regular guitar wherever you go, I would suggest learning regular, but as a pianist I would imagine you could learn either way.
Various famous guitar players learnt the 'wrong' way so it shouldn't stop you, and it will make understanding tablature simpler.
Comment: I am left handed and learned right-handed guitar without too much trouble. The first few weeks are a bit awkward but it goes away completely after the hump. Nice left-orientation classical guitars are extremely expensive and not as common. There is also the consideration that 90% of the people who you hand your guitar to won't be able to play it.
Answer: My brother is left-handed, and learned the bass guitar "normally" (right-handed). When he first picked one up, the right-handed orientation was comfortable to him.
IME, whether you're "left-handed" or "right-handed" at anything is a coin toss. I'm right-handed in almost everything I do, but I shoot left in hockey. It's the oddest thing, cause I bat and golf right-handed (opposite hand position).
I would put the guitar in his hands and ask if it feels comfortable. If it does not, then flip the guitar over. If that feels more "natural" to him, then he's a Southpaw plain and simple, and he has three choices in a right-handed world; learn to play right-handed anyway (despite it feeling "odd"; he will gain some feeling of familiarity with practice), learn to play ambidextrously (so he can play a right or left-handed guitar), or learn to play "upside-down" (quite a few notable Southpaws learned the guitar/bass by flipping a right-hander over so the high E is on top of the guitar, and mirroring all the chord and scale patterns).
Answer: I would definitely recommend learning left-handed. I initially began playing musical instruments (violin)  at an extremely early age, before I or my parents knew I was left-handed. The teacher said "get a right-handed violin because left-handed violins are rare and typically far more expensive". I learned how to play righty, but I was always behind my peers which was frustrating but, in hindsight, was the result of having a more difficult time learning. I still play right-handed, and learned guitar right-handed, and overcame the obstacle, but, in my eyes, any way to remove obstacles in learning a new (and often frustrating) instrument further ensure your maintained level of interest and enjoyment.
Of course, the best answer is to learn both hands...
Comment: I have that kind of feeling too, that I might be a little slow if I decide to go the righty way instead of the natural one. But as I stated before, I really would like the idea of being capable of jamming anywhere, not only when I'm with my custom guitar, although that might be thinking to much ahead. If you managed to survive and overcome your problem with the right-handed violin, I guess I could try it out.
Comment: I understand where you're coming from about having to have your custom guitar for jamming, but if you know you're going to be somewhere that jamming is going to happen then bring your guitar! Playing someone else's guitar kind of sucks. Their action might be too high, too low, or their string gauge could be different than what you're used to. It's nice to be able to just jam with anything on hand, but having your own instrument with you is the way to go.
Answer: My older brother who is left handed learned left handed guitar. I would suggest that you do the same. Do not allow us right handed folks to corrupt you and make you think that you must adapt to our right handed ways! Embrace the left hand and get a left handed guitar.
Answer: Let him try a guitar of each type, but I don't think he will have any problem learning and playing a right-handed guitar. My brother is left handed but he started playing a right-handed bass some years ago, and since then he has been able to play some guitar and uke too with no problem.
Also, as you pointed out, it will be easier for you to teach him (and easier for him to jam with someone's guitar).
But if you can, let him try a left-handed, so he can judge what suits him better, and if the difference isn't noticeable, I'd go right-handed (for the benefits explained before).
Answer: I'm left-handed but I've played guitar right-handed for decades, reaching a rather competent level in classical guitar before I quit at my 20s because I got bored with classical guitar repertoire.
If holding your guitar left-handed feels more natural, go with leftie, whatever the cost. For a beginner a fretting hand might feel having a more demanding job but actually the plucking/picking hand is more important. Yes, even if you like to play slurs and legatos.
That's because you'll always have a better command on your dominant hand. This affects the rhythm and precision, the things that in the end make your playing sound good or bad.
I'm personally learning electric guitar and occasionally thinking about learning to play it left-handed. Especially because I still tend to strum air guitar like a southpaw.
Answer: A friend told me about a show she attended the other night: one guitarist, playing solo. He is left handed and plays a 'normal' guitar upside down (ie the pick guard is above the sound hole and not below), but the strings are strung 'normally' (in other words, the high E is on the top side of the guitar whereas the low E is on the bottom side). As far as I know, Jimi Hendrix used to play a normal guitar but would restring so that the low E as on the top and high E on the bottom.
The obvious advantage of this setup is that the guitarist can play any guitar that he comes across. The obvious disadvantage is that most learning material has to be read in a mirror fashion. Apparently he strums upwards as opposed to the normal down strum.
So, as a left hander, you have a variety of options:

Play right handed (famous examples: Robert Fripp, Mark Knopfler)
Play left handed on a normal guitar, strung reverse (Jimi Hendrix)
Play left handed on a normal guitar, normally strung (above example)
Play a left handed guitar

Final advice: do whatever is most natural for you!
Answer: I am a lefty and play righty guitar. I can finger pick ok and am learning alternating bass finger style and also singing to strumming. The finger picking felt mind bending at first but is getting easier. I picked up a lefthander guitar the other day and it felt super weird. My left hand is however much stronger and more dexterous than my right. Sometimes I wonder if whoever invented guitar had it backwards, or maybe they were a lefty embittered by the righty dominated world and took revenge by making them play backwards. Driving with a stick shift feels good being a lefty, I get to hold the wheel with my dominant hand, and it would feel pretty bizarre the other way around, like in England.
Answer: Do you mean a right handed guitar, left handed?
That is most unconventional, however some people have played like that their whole career.
Albert King

Kristopher Roe Of The Ataris

Gurrumul Yunupingu

But playing a right handed guitar, left handed, with the strings rearranged should be no problem. What ever is most comfortable.
Also, I'd suggest learning on a nylon classical guitar. Restring according to left/right preference.
Answer: Jimmy Hendrix played a right handed guitar left handed his whole life, it is possible but like everything else it will need some practice.


Show $f$ is discontinuous at every $x_{0}$ in $\mathbb{R}$.

Question: Let $f(x)=1$ for rational numbers x, and $f(x)=0$ for irrational numbers. Show $f$ is discontinuous at every $x_{0}$ in $\mathbb{R}$.
I started with the negation of $f$'s discontinuity first.
Proof: Suppose $f$ is continuous at some $x_{0}$ in $\mathbb{R}$.
Then, for all $\varepsilon > 0 $, there exists $\delta > 0$, s.t for all $x$ in $\mathbb{R}$ that satisfies $|x-x_{0}| < \delta$, we have $|f(x)-f(x_{0})| < \varepsilon$.
Let $\varepsilon=1/2$.
We know that for any $B_{\delta}(x_{0})$ for all $x_{0}$ in $\mathbb{R}$, we always can achieve some rational number and irrational number.
Then, for all $x_{0}$ we can always get, $|f(x)-f(x_{0})|=|1-0|=1$.
However, $1>1/2$ is a contradiction.
Hence,   $f$ is discontinuous at every $x_{0}$ in $\mathbb{R}$.
$$\blacksquare$$
Well, it's a very well-known problem, but I did not want to use sequence $(x_{n})$ that converges to $x_{0}$ because not using it seems a little bit easier for me to understand.
Does my proof make sense? Is there a simpler, or shorter approach for this kind of problem?
Comment: Your proof makes sense.
Answer: To use sequences, we can take any $x_0 \in \Bbb{R}$ and using fact, that in each neighbourhood $\left( x_0 - \frac{1}{n}, x_0 + \frac{1}{n} \right)$ exist as rational, so irrational numbers. Constructing appropriate sequences we find, that one have limit $1$, another limit $0$.
Answer: Here it is another way to approach it for the sake of curiosity.
Suppose that $f$ is continuous at $q\in\mathbb{Q}$.
Then for every sequence $q_{n}$ which converges to $q$, the sequence $f(q_{n})$ must converge to $f(q) = 1$.
Based on such assumption, we shall consider the following sequences:
\begin{align*}
\begin{cases}
x_{n} = q + \dfrac{1}{n}\\\\
y_{n} = q + \dfrac{\sqrt{2}}{n}
\end{cases}
\end{align*}
Notice that both $x_{n}$ and $y_{n}$ converges to $q$, but $x_{n}$ is rational and $y_{n}$ is irrational.
Consequently, we have that $f(x_{n}) = 1$ and $f(y_{n}) = 0$, which contradicts our primary assumption.
Similar reasoning applies to the irrational values. Thus $f$ is everywhere discontinuous.


How to specify more than one email address in 'git config --user.email'

Question: I have specified two email addresses in my GitHub account. Now I want to have the same in the command line so my commits are assigned to both email addresses. How is this possible?
Comment: Have you tired a semicolon ;
Comment: http://stackoverflow.com/questions/4220416/can-i-specify-multiple-users-for-myself-in-gitconfig
Answer: You can edit ~/.gitconfig file and add both of your email separated by ;
1. sudo vi ~/.gitconfig
2. name = UserName
   email = firstname.lastname@example.com;email@example.com
3. Save the file.

Comment: Your sample is separated by colon. Should it be colon or semicolon?
Comment: I think this won't work because in the commit log in github, it does not show my name under my commits.