JavaFX native bundle exe is throwing "JavaFx launcher Exception" where as Executable Jar file is perfectly running

Question: For long time I was facing an issue while running the application jar -
I am obfuscating the JAR using Proguard and that JAR file also contains some resource files like images, .version file, etc along with publicCerts.store file.
So to include resource file into final JAR I had specified all the resource files as
-adaptresourcefilecontents **.fxml,**.properties,META-INF/MANIFEST.MF,images/*.jar,*.version,publicCerts.store

but while running my application JAR I was getting execption -
 Exception in Application start method
    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.javafx.main.Main.a(Main.java:642)
    at com.javafx.main.Main.main(Main.java:805)
    Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherIm
    pl.java:403)
    at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:
    47)
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
    at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.AssertionError: java.security.KeyStoreException: Uninitiali
    zed keystore
    at de.schlichtherle.license.LicenseNotary.getPublicKey(Unknown Source)
    at de.schlichtherle.license.LicenseNotary.verify(Unknown Source)
    at de.schlichtherle.license.LicenseManager.verify(Unknown Source)
    at de.schlichtherle.license.LicenseManager.verify(Unknown Source)

    at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
    at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:206)
    at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29
    )
    at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
    ... 1 more
    Caused by: java.security.KeyStoreException: Uninitialized keystore
    at java.security.KeyStore.isKeyEntry(Unknown Source)
    ... 17 more

I thought the obfuscation corrupting the publicCerts.store so use another obfuscation option for publicCerts.store
-adaptresourcefilenames publicCerts.store
-adaptresourcefilecontents **.fxml,**.properties,META-INF/MANIFEST.MF,images/*.jar,.version

and it works. When I used to double click on by application jar it is showing my application window but now the native bundle executable (exe) is showing me this dialog in the same case at the same condition.

Edited -
I have debugged the issue and found that it's throwing exception -
    java.lang.AssertionError: java.security.NoSuchAlgorithmException: PBEWithMD5AndDES SecretKeyFactory not available java.security.NoSuchAlgorithmException: PBEWithMD5AndDES SecretKeyFactory not available

I wonder the native bundle executable (exe) is made up from the same executable but the exe is not working. Here is ANT step to deploy the application and create the native bundle exe.
<target name="CreatingExe" depends="SignedJar">
            <fx:deploy width="800" height="600" nativeBundles="all" outdir="${dist}" outfile="${app.name}">
                <fx:info title="${app.title}"/>
                    <fx:application name="${app.title}" mainClass="${main.class}"/>
                    <fx:resources>
                        <fx:fileset dir="${distBI}" includes="*.jar"/>
                <fx:fileset dir="${WorkingFolder}/temp"/>
            </fx:resources>
         </fx:deploy>
    </target>

FYI : I am running my build on Windows 8 O.S., 64 bit machine. I am deploying my JavaFX application in following steps-
Compiling JavaFX Code.
Creating JAR.
Obfuscating code.
Signing Jar
Creating Executable.
Signing Executable.

Build was successful.

How to exclude publicCerts.store from obfuscation? Why the final exe is not working even the application jar is working? Do I need to specify any thing else in fx:deploy task?
Answer: When building a JavaFx native bundle the ext folder under <JDK.HOME> doesn't get included. What this folder contain is mostly the security stuff.

<copydir src="${java.home}/lib/ext"
    dest="${dist.jar.dir}/bundles/{YOUR.PACKAGE.NAME}/runtime/jre/lib/ext"
    includes="**/*"
/>


Docker executing a command when running an image

Question: I'm using Laravel with docker. Inside my dockerfile I have this command:
RUN php artisan config:cache

This is useful for production since it cache the configuration. When I'm developing I need to be able to change the configuration quite often, so every time I run the image I need to  execute
RUN php artisan config:clear

is there a way to run the docker image with a given command? i.e.:
docker run my_image "php artisan config:clear"

(If you're wondering, I'm doing docker run instead of docker start quite often since I'm building the image quite often.)
I'd like to avoid using CMD inside dockerfile since it's not really needed.
Thanks
Answer: If you want to run the command inside a currently running container you can use the exec command:
$ docker exec yourapp_web_1 php artisan config:clear
Comment: I usually create a ./commands folder in my docker set up. I add stuff like this as a bash script that way I can execute it in an easy way. Something like: `./commands/cc.sh`
Comment: Yeah I know, there is no way to run it from the run command? I'm super busy and lazy, I'd like to avoid running two commands if I can run only one.


Generating a 3-month half life weighting series in R

Question: I am using the lm() and princomp() functions in R to perform regressions on foreign exchange time series. I would like to weight the regressions (and PCA) such that 50% of the influence on the regression comes from the past 3 months, 25% from the previous 3 months, etc, but in a smooth fashion. Both functions take such a weighting series. What is a simple formula for generating a decaying weights series with a half life of 3 months (or any other period, for that matter), in R?
Ideally the sum of the weights will equal 1, although I don't think this is mandatory in lm().
Answer: To be general, let us consider a time series with arbitrary steps.  Therefore, let $k$ be the number of steps in three months and write $\omega_1$ for the weight for the immediately preceding time, $\omega_2$ for the weight preceding it, and so on, so that the sequence of weights
$$(\omega_1, \omega_2, \ldots, \omega_k)$$
is applied to the preceding three months.  The total weight for those three months is the sum of these.
Assumption I:  It is natural to hope that the next sequence of weights starting at $\omega_{k+1}$ be in proportion to the first sequence; the question specifies that the constant of proportionality be $1/2$, entailing
$$\frac{1}{2}(\omega_1, \omega_2, \ldots, \omega_k) = (\omega_{k+1}, \omega_{k+2}, \ldots, \omega_{2k}).$$
The requirement of "smoothness," together with the natural idea of a monotonic decrease in weights over time, suggests that $\omega_{k+1} \lt \omega_k$.  This leads to
Assumption II: We might hope that the sequence of weights could be arranged in geometric proportion, say with constant of proportionality $\rho$, whence
$$\frac{1}{2}\omega_1 = \omega_{k+1} = \rho^k \omega_1.$$
The unique solution is
$$\rho = 2^{-1/k}.$$
Summing these weights over $n$ time steps and requiring them to sum to unity gives
$$1 = \omega_1 + \omega_2 + \cdots + \omega_n = \omega_1(1 + \rho + \rho^2 + \cdots + \rho^{n-1}) = \omega_1 \frac{1-\rho^n}{1-\rho}.$$
It follows that
$$\omega_1 = \frac{1-\rho}{1-\rho^n} = \frac{1-2^{-1/k}}{1-2^{-n/k}}$$
and
$$\omega_i = \rho^{i-1}\omega_1 = 2^{(1-i)/k}\omega_1, \quad i=1, 2, \ldots, n.$$
For example, with $k=3$ (monthly data) and $n=6$ (giving two full three-month periods), $\rho = 2^{-1/3} = 0.793701$, $\omega_1 = 0.275066$, and the sequence of weights for the first three-month period is $0.275066$, $0.21832$, $0.173281$ followed by half these weights for the second three-month period, $0.137533$, $0.10916$, $0.0866403$.

Other solutions to the problem are possible; in particular, there are infinitely many available when we do not make Assumption II.  But Assumption II has the particularly nice property that if you were to combine the data into sequential groups, taking $m$ of them at a time (such as combining daily data into monthly data, with $m \approx 30$), and recalculate the weights, then the sum of the weights for each group will equal the recalculated group weights.
Comment: (+1) Better explanation than mine!  (as usual...)
Comment: Thanks--but the "as usual" is incorrect, IMHO, seeing that you already have posted plenty of superb answers to many questions.  Let's not lose sight of the fact that we make a tradeoff between speed and thoroughness and sometimes speed is valued more.  Regardless, as a community we hope that all correct replies will undergo a process of continual improvement (by their authors and community members) so that eventually each thread will offer at least one great answer to the question.
Answer: Let us assume that you want such a decaying weight to take place over intervals of T time periods, e.g., 91 days in your example (there are 91 days in three months, so you want the weight on day 91 to equal 1/2 the weight on day 0.)  Solve $\exp\{-\lambda T\} = 0.5$ to get $\lambda = -\log(0.5)/T$.  In your case, $\lambda = -0.007617$.  Then the weight assigned to a given time period $t$, $w(t)$, is equal to $\exp\{-\lambda t\}$.
You can see this works, as $w(t+T) = w(T)w(t) = 0.5w(t) \space \forall t$, so $\sum_{t=0}^{T-1}w(t) = 0.5\sum_{t=T}^{2T-1}w(t)$.
The weights can be normalized to sum to one after calculation as above.


cURL and ajax combined timeout

Question: I'm running an ajax request to a via jQuery which has a timeout of 10000 (i.e. 10 seconds).  The ajax request calls a local PHP script and in the script I have a cURL request to an external site with its own timeout of 30 seconds.  Suppose my ajax request takes 8 seconds, and then my cURL request takes 4 seconds.  Will my original ajax request throw an error?  Or will the original ajax request only throw an error if it takes more than 10 seconds to connect to my local script?
Comment: if you have some kind of timeout, it will be called after the time set, So in your case, 10s.
Your full request AJAX + cURL must be less than this time.
Comment: Instead of a comment, would you mind submitting that as the answer so that I can accept it?  Thanks so much.
Answer: f you have some kind of timeout, it will be called after the time set, So in your case, 10s.
Your full request AJAX + cURL must be less than this time.
But the best way to use asynchronous task would be to use callback or promise, so this way you can wait to have a result before updating a view
Answer: The AJAX call timeout would trump any timeout you set in PHP so basically AJAX would timeout or "throw an error" after 10 seconds even though your script would continue running for 30 seconds as you gave in your example.
It's important to note that any processing that happens in your PHP script (Emailing, Database Calls) would continue to happen even though AJAX has timed out but since AJAX has timed out nothing would display on your browser.
Ideally you would want to adjust your code so the two timeouts are similar as it could cause unexpected behavior. For example, users clicking on a button multiple times after thinking there was a failure and having multiple emails or database inserts occur).

cURL and ajax combined timeout


Showing uniqueness of inverse element of an element of a monoid

Question: Question- If $\langle A,*\rangle$ is a semigroup with identity, prove that every element $a \in A$ has at most one inverse.
Proof- Let the identity be $e$. Let us assume that $b_1$, $b_2$ are two distinct inverses of a belonging to $A$.
Thus $a*b_1=b_1*a=e$
Also, $a*b_2=b_2*a=e$
Now, $$\begin{array}{lrcl}
& b_1 & = & b_1 \\
\implies & b_1*(a*b_1) & = & b_1*(a*b_2) \\
\implies & (b_1*a)*b_1 & = & (b_1*a)*b_2 \\
\implies & e*b_1 & = & e*b_2 \\
\implies & b_1 & = & b_2
\end{array}.$$
This contradicts the assumption that $b_1$ and $b_2$ are distinct.
Thus, no element can have multiple inverses.
Thus, the number of inverses is at most $1$.
Please tell me if there is any flaw in reasoning, as I can find none. Further, if my statements can be made clearer, please do comment.
Answer: This looks very clear to me and the proof is simple and sound. If you want to be pedantic, then the first implication maybe needs some justification using the already established fact that $a\ast b_1=e=a\ast b_2$. There is also a slightly short proof, though not by much and it depends on your taste in proof style I guess: $$b_1=b_1\ast e=b_1\ast(a\ast b_2)=(b_1\ast a)\ast b_2=e\ast b_2=b_2$$ In particular I didn't need to make an assumption that $b_1$ and $b_2$ are distinct and reach a contradiction.
Answer: Your proof is valid. I'm rewriting it for formatting purposes.
Proof. Let $e$ be the identity of $A$. For an element, $a\in A$, assume $b_1,b_2$ are both inverse elements of $a$. It follows that $(a*b_1)=(b_1*a)=e$ and $(b_2*a)=(a*b_2)=e$. Thus
\begin{gather}
(a*b_1)=(a*b_2)
\end{gather}
By left-hand multiplication we have
\begin{gather}
b_1(a*b_1)=b_1(a*b_2)
\end{gather}
By associativity of $A$
\begin{gather}
(b_1*a)b_1=(b_1*a)b_2 \implies e*b_1=e*b_2 \implies b_1=b_2
\end{gather}
Therefore the inverse of an element of $A$ is unique.
Answer: I think th word inverse in your question should be considered as the word unit. In fact, in any semigroup with identity 1, two elements for example a and b are said to be inverses of each other if we have different meaning: $$aba=a,~~~bab=b$$ and that's why any regular elemet has at least inverse in the semigroup. I know an example for a semigroup that every element are inverses to each other.
Comment: I have never seen the term used like that before. In all the most common contexts people see monoids, inverse means precisely what the OP means. And unit is definitely not the term he is looking for (a unit is an element which has an inverse).
Comment: Could you give a reference for this meaning?
Comment: @TobiasKildetoft: I know it from Clifford and Preston book.
Comment: @TobiasKildetoft: See [1](http://books.google.com/books?id=4vXG2rjCUmUC&q=reciprocal#v=snippet&q=reciprocal&f=false)page 27 for inverse and see [2](http://books.google.com/books?id=4vXG2rjCUmUC&q=unit#v=snippet&q=unit&f=false) page 21 for unit.
Answer: Your proof looks good. Just one little comment: you do not really need to argue by contradiction. You can just begin by saying: "Suppose that $b_1$ and $b_2$ are inverses for $a$", and then run your argument to conclude $b_1=b_2$. This shows that there can be at most one inverse for any $a$ in a the monoid. This is primarily an aesthetic issue (your proof isn't wrong), but introducing contradiction when you can just argue directly can be a little confusing.


Print out NID of entity reference

Question: I have a custom field that is an entity reference, when using

print render($content['field_call_to_action_1']);

in a content type template it prints out the title Call to Action 1, and the Title of the content that the entity reference is linked too.
How can I just get it to print out the NID instead?
Thanks for your time!
Answer: $content is to be rendered and obeys what you have set in node(other other entity) type's Display Settings (Administer > Structure >Content Types).
What you should use is, $node object.

<?php
print_r($node);
?>

Now you will see a nicely formatted information of $node object which also has the NID you want.
You will be able to access it with this:
$node->field_call_to_action_1['und'][0]['target_id']

Quick hint:If you are trying to build a URL link from this value, have a look at url() and l() functions!
Comment: I don't know is it just my case, but it didn't worked for me. I used 'target_id' instead of 'nid' and worked fine.

Print out NID of entity reference


Why didn't operations on a copy of a list also modify elements in the original list?

Question: In Python everything should be represented with a pointer. Therefore, I expected the following code to modify the original list a as well, since I thought the list copy would contain all the original pointers contained in a:
import copy

a = ["a", "a"]

copy = copy.copy(a)
for (count, e) in enumerate(copy):
    copy[count] += "b"

print copy
print a

I expected to see ["ab", "ab"]. Surprisingly, a still contains ["a", "a"] only while copy indeed contains ["ab", "ab"]. Using copy = list(a) doesn't work either.
I thought this result would only happen if I wrote copy = copy.deepcopy(a).
Where did I get wrong? What is the proper way of acquiring the references to all elements in a list and modifying them in a mirror list? Or is it just not possible in Python?
Comment: @Zizouz212 I prefer to think I answered your question extremely fast :)
Comment: Strings are immutable?
Comment: Strings are immutable.
Comment: @chepner Beat you by 3 seconds :P
Comment: Yeah. You didn't modify the objects. You simply created new ones, and put them in the new list. Strings are immutable - they can't be modified.
Comment: Doing `+=` for a string doesn't modify that string - it simply creates a new one.
Comment: Right, then my question is why didn't the original strings in `a` get replaced by the new ones. Shouldn't the pointers point to the same objects? That's the core of my question I think.
Comment: @JIXiang Read http://nedbatchelder.com/text/names.html.
Comment: You can think of each element in the list as a separate "pointer" that points to an object.  When changing the contents of the list, you are changing what these pointers point to.
Comment: They are different pointers, because there are different objects. If you like memory address', say a had 1 and 2. Copy had 1 and 2, but then you changed it to 3 and 4, when you tried changing the strings. You allocated new strings, you didn't modify the old ones.
Comment: @chepner Thanks for the link. That should help me clarify the issue. I didn't have a solid enough grounding in Python. It seems that the Python Tutorial really just contains the bare minimum of information needed to use Python and I should look for some more references before programming comfortably there.
Answer: You are confused. The entire purpose of using copy.copy is to make a new list with no reference to the old one. If you do want to keep a reference, then don't copy it:
a = ["a", "a"]
copy = a

Comment: @JIXiang Copy will create a new list, but all the elements inside that list are the same. Deepcopy will try to re-create those elements as well.
Comment: @JIXiang: There will be no practical difference unless the elements in the list are mutable, which in this case they are not.
Comment: Thanks. This actually answers my question. So what is supposed to be the difference between `copy` and `deepcopy` in this case?
Comment: Incorrect. `deecopy` removed references entirely. `copy` keeps the references _inside_ the list. Take for example a list of lists: modifying a list inside of a list that's been copied will still modify the original list's internal list as well. There is very much a practical difference, and we're inherently teaching the wrong thing otherwise, for example if the user decided to eventually code Java one day and use char arrays instead of String. EDIT: Didn't see @Zizouz212's comment.
Comment: Also worth noting, the following also makes a copy of the list: `li = list(['a', 'b'])`


What is the inverse Laplace transform of my equation?

Question: What is the inverse Laplace transform of L(s)=$exp[-(1/2)sI]$*$I_0[(1/2)sI]$, where $I_0$ is the modified bessel function of first kind.
I am told that the answer is $\frac{1}{π}$ $\left(\frac{1}{(sI-s^2)}\right)^\frac{1}{2}$
   but I am struggling to achieve this answer.
Can anyone help?
Comment: please use mathjax to format your question. [Here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is a link to a  quick tutorial on how to use it .
Comment: Thank you, I will do that ASAP
Answer: Well, we are looking at the inverse Laplace transform of:
$$\text{y}_{\space\text{n}}\left(t\right):=\mathscr{L}_\text{s}^{-1}\left[\exp\left(-\text{n}\cdot\text{s}\right)\cdot\mathcal{I}_{\space0}\left(\text{n}\cdot\text{s}\right)\right]_{\left(t\right)}\tag1$$
Where $\mathcal{I}_{\space\text{p}}\left(\text{z}\right)$ is the modified Bessel function of the first kind.
Now, using the convolution theorem, of the Laplace transform, we can write:
$$\text{y}_{\space\text{n}}\left(t\right)=\int_0^t\mathscr{L}_\text{s}^{-1}\left[\mathcal{I}_{\space0}\left(\text{n}\cdot\text{s}\right)\right]_{\left(\tau\right)}\cdot\mathscr{L}_\text{s}^{-1}\left[\exp\left(-\text{n}\cdot\text{s}\right)\right]_{\left(t-\tau\right)}\space\text{d}\tau\tag2$$
Using the table of selected Laplace transforms, we can write:
$$\mathscr{L}_\text{s}^{-1}\left[\exp\left(-\text{n}\cdot\text{s}\right)\right]_{\left(t-\tau\right)}=\delta\left(t-\tau-\text{n}\right)\tag3$$
Where $\delta\left(x\right)$ is the Dirac Delta function.
So, we can rewrite equation $\left(2\right)$ as follows:
$$\text{y}_{\space\text{n}}\left(t\right)=\int_0^t\mathscr{L}_\text{s}^{-1}\left[\mathcal{I}_{\space0}\left(\text{n}\cdot\text{s}\right)\right]_{\left(\tau\right)}\cdot\delta\left(t-\tau-\text{n}\right)\space\text{d}\tau\tag4$$
Using the definition of the modified Bessel function of the first kind, we can write:
$$\mathcal{I}_{\space0}\left(\text{n}\cdot\text{s}\right)=\sum_{\text{k}=0}^\infty\frac{1}{\text{k}!}\cdot\frac{1}{\Gamma\left(1+\text{k}\right)}\cdot\left(\frac{\text{n}\cdot\text{s}}{2}\right)^{2\text{k}}\tag5$$
Where $\Gamma\left(\text{s}\right)$ is the Gamma function.
So using the table of selected Laplace transforms, we can write:
$$\mathscr{L}_\text{s}^{-1}\left[\mathcal{I}_{\space0}\left(\text{n}\cdot\text{s}\right)\right]_{\left(\tau\right)}=\sum_{\text{k}=0}^\infty\frac{1}{\text{k}!}\cdot\frac{1}{\Gamma\left(1+\text{k}\right)}\cdot\mathscr{L}_\text{s}^{-1}\left[\left(\frac{\text{n}\cdot\text{s}}{2}\right)^{2\text{k}}\right]_{\left(\tau\right)}=$$
$$\sum_{\text{k}=0}^\infty\frac{1}{\text{k}!}\cdot\frac{1}{\Gamma\left(1+\text{k}\right)}\cdot\frac{1}{\Gamma\left(-2\text{k}\right)}\cdot\left(\frac{\text{n}}{2}\right)^{2\text{k}}\cdot\frac{1}{\tau^{1+2\text{k}}}\tag6$$
Now, we can rewrite equation $\left(4\right)$ as follows:
$$\text{y}_{\space\text{n}}\left(t\right)=\int_0^t\left\{\sum_{\text{k}=0}^\infty\frac{1}{\text{k}!}\cdot\frac{1}{\Gamma\left(1+\text{k}\right)}\cdot\frac{1}{\Gamma\left(-2\text{k}\right)}\cdot\left(\frac{\text{n}}{2}\right)^{2\text{k}}\cdot\frac{1}{\tau^{1+2\text{k}}}\right\}\cdot\delta\left(t-\tau-\text{n}\right)\space\text{d}\tau=$$
$$\sum_{\text{k}=0}^\infty\frac{1}{\text{k}!}\cdot\frac{1}{\Gamma\left(1+\text{k}\right)}\cdot\frac{1}{\Gamma\left(-2\text{k}\right)}\cdot\left(\frac{\text{n}}{2}\right)^{2\text{k}}\int_0^t\frac{\delta\left(t-\tau-\text{n}\right)}{\tau^{1+2\text{k}}}\space\text{d}\tau\tag7$$
When $\text{n}>0\space\wedge\space\text{k}\ge0\space\wedge\space t\ge0$, we can write:
$$\int_0^t\frac{\delta\left(t-\tau-\text{n}\right)}{\tau^{1+2\text{k}}}\space\text{d}\tau=\frac{2\cdot\theta\left(t\right)-1}{\left(t-\text{n}\right)^{1+2\text{k}}}\cdot\theta\left(t-\text{n}-t\cdot\theta\left(-t\right)\right)\cdot\theta\left(\text{n}-t+t\cdot\theta\left(t\right)\right)\tag8$$
Where $\theta\left(\text{a}\right)$ is the Heaviside step function.
Answer: This is pretty straightforward if one writes
$$I_0(z) = \frac1{\pi} \int_{-1}^1 dv \, (1-v^2)^{-1/2} \, e^{z v} $$
Then, letting $a=I/2 \gt 0$,
$$\begin{align} f(t) &= \frac1{i 2 \pi} \int_{c-i \infty}^{c+i \infty} ds \, I_0(a s) e^{(t-a) s}\\ &= \frac1{\pi} \int_{-1}^1 dv \, (1-v^2)^{-1/2} \frac1{i 2 \pi} \int_{c-i \infty}^{c+i \infty} ds \, e^{(t-a+a v)s} \\ &= \frac1{\pi} \int_{-1}^1 dv \, (1-v^2)^{-1/2} \delta(a v+t-a) \\ &= \frac1{\pi a} \left (1- \left (1-\frac{t}{a} \right )^2 \right )^{-1/2} \\ &= \frac1{\pi} (2 a t-t^2)^{-1/2} \end{align} $$
That said, note that for the argument of the delta function inside the $v$-integral to vanish, $t \in [0,2 a]$.  Noting that I defined $a=I/2$, the ILT for the given Laplace transform is

$$f(t) = \frac1{\pi} (I t-t^2)^{-1/2} \theta(t) \theta(I-t) $$


VB.NET Active Reports

Question: I have a VB active report which has many different attributes. The report contains attributes area, balance, id and status and is currently grouped my area. What I need to do now is remove all lines from the report where the balance is equal to 0 and the status equal to deactive. The information for the active report is from my database. Thus I think the best way would be to only select records where the balance is not 0 and status not equal to deactive. Is there a way I can query my database and have the active report be based off the query results? Is there an easy way to do this? Thanks for any help.
Comment: You asked "Is there a way I can query my database and have the active report be based off the query results?"...that is the standard way you write a report, you'd have to work harder to not get the data from the DB.  Can you please edit your question to include details of where you get your data from now if it is not a DB data source with a select statement?
Answer: Yes, the best way to do this is to change the query so that only the minimum records you need are actually coming into the report. The Modify Data Sources at Run Time topic from the documentation shows how to modify that SQL statement in the code dynamically at runtime.
If you can hard-code the SQL query for the report you should probably just modify the SQL at design time inside the designer. This Bind Reports to a Data Source topic shows you how to do that.
You can also programatically control the visibility of fields/textboxes based on the data using the Format event of the section containing those controls (most likely Detail_Format), but it sounds to me like modifying the SQL query is your best bet.

VB.NET Active Reports


Android- A textView trouble

Question: i am a quite new android programmer and facing strange error on TextView. I want to write a text into EditText field and with a Buttons help, want to show it on a TextView. But when i run it on my phone, i put some text and hit the Button it changes the TextView into this:
"android.widget.EditT
ext{4279e770
VFED..CL..F.....
.......... app:id/
editText}"
package com.example.tolgaen.tutorial;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText input=(EditText)findViewById(R.id.editText);
    final TextView monitor=(TextView)findViewById(R.id.textView);
    Button button=(Button)findViewById(R.id.myButton);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            monitor.setText(input.toString());
        }
    });
  }
}

It does not give any error message on logcat and i cannot figure out where the problem is?
Answer: you have to use the getText () method to obtain an Editable object that you can transform a string using toString ()
monitor.setText(input.getText());

If you need the text as string should be
String str = input.getText().toString();

Comment: toString is not necessary because method setText() has CharSequence as parameter
Comment: of course you would have to not use the toString () unless you really need a string

Android- A textView trouble


Simplenews newsletter unsubscribe page- Access denied

Question: I am using Simplenews newsletter module on my Drupal-7 website to send newsletters, but when you click on the unsuscribe link, the user gets an access denied page-you need an account to view this page etc.
Where can I make this page visible to all users or/and change what this page says?
 For example, instead of Access denied to show an image or say "Error" or something else.
Answer: The access arguments for that page are subscribe to newsletters, meaning that you need to grant that permission to anonymous users, in order to allow them to unsubscribe without logging in.
Here's how to do that:

Navigate to /admin/people/permissions.
Find "subscribe to newsletters" item.
Grant the permission to anonymous users.

Note: I just told you how to allow to do it for everyone. You need to evaluate if this fits your website and workflows.
Comment: You're welcome! Glad it helped.


How can I make a usable backup of the site on CD?

Question: The client would like to archive off a copy of their drupal 7 site every 6 months or so. By archiving, they are referring to copying the site (in a usable format) onto a cd.
What are some of the options for doing this?
Comment: Cd's??? What is this, the 90s. If your client really wants a backup that he can actually have, use something like http://drupal.org/project/backup_migrate_dropbox
Comment: What do you mean by usable ? Your client will be able to use/browse the site directly on the cd or just a normal backup ?
Answer: The Backup and Upgrade module can be used to schedule automated database backups. One of those backups, combined with the codebase, gives you a full backup of the site. If this is to be burned to a disc every 6 months, I wouldn't bother automating anything - the time investment won't be worth the future time savings.
Comment: Thank you @YuriyBabenko
So are you saying it's best to burn a compelte site, including all the includes etc onto a cd? I was hoping there would be a way for the client to somehow back it all up from the front end (somehow?).
Comment: I'm not aware of any front end tools to make such backups. Some webhosts provide interfaces to schedule automatic backups, but the backups usually live on their servers. Burning backups to CDs is a pretty antiquated approach.
Answer: You should just use this: http://drupal.org/project/backup_migrate_dropbox as it will backup directly to your dropbox account or straight into your clients computer. From there you can just burn the CD or do whatever you want with the files. You have have it automated and it can backup every couple of days or months if you like. Just set and forget it kind of thing.
Comment: Thank you @duckx
Will a non tecnhican client be able to preview the site as it was online once they burn it onto a cd? Or will they need to make configuration changes in order to browse through the site once burned onto a cd?
Answer: @kine456 : Some years ago, after a client request, I used Server2Go (http://www.server2go-web.de/) and it works pretty well with a small Wordpress site. Stunnix may works as well (http://stunnix.com/prod/aws/).
But it is not, in both case, the way to a store a backup.


java.io.IOException: Input/output error in Jenkins while running Gradle script

Question: Sometimes Jenkins while running Gradle scripts drops this error:
<code>12:48:19 > Could not resolve all dependencies for configuration ':classpath'.
12:48:19    > java.io.IOException: Input/output error
</code>
Rebuild helps, but this didn't happen on old server.
Any suggestions?
Answer: This was caused by several processes which tried to acquire lock of one file.
Fixed by selecting option "Force GRADLE_USER_HOME to use workspace".
Comment: How exactly to "Force GRADLE_USER_HOME to use workspace"?


Why does $\sin^{-1}(\sin(\pi))$ not equal $\pi$

Question: And when does $\sin^{-1}(\sin(x)) = x$
Comment: You will first have to say what you mean by $\sin^{-1}(y)$.
Comment: http://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Principal_values
Answer: The sine function lacks the property of injectivity, which means that it sometimes happens that $\sin x= \sin y$ even though $x\ne y$; for example $\sin 0 = \sin \pi$ even though $0\ne \pi$.  To have a full inverse, a function $f$ must be injective: it must have $f(x)=f(y)$ only when $x=y$. Otherwise it is ambiguous, for each case  where $f(x) = f(y)$ but $x\ne y$, whether the inverse function $f^{-1}$ at $f(x)$ should yield $x$ or $y$.  There are usually many possible choices for $f^{-1}$.
Consider a simpler example, where $f(x) = x^2$.  This function is not injective, since for example $f(7) = f(-7)$.  If we want an inverse for $f$, we need to choose whether $f^{-1}(49)$ will be $7$ or $-7$, and similarly for almost every other value of $f$.  Usually in this case we adopt the rule that whenever there is a choice, $f^{-1}(x)$ is always positive. When we do this we get exactly the square root function $\sqrt x$.  But note that $\sqrt x$ is not a full inverse for $x^2$: We do have $f(f^{-1}(x)) = x$ whenever this is defined, but not $f^{-1}(f(x)) = x$, because for example $f^{-1}(f(-7)) = \sqrt{(-7)^2} = \sqrt{49} = 7$.  Here we have $f^{-1}(f(x)) = x$ only for $x\ge 0$.
We could chose a different partial inverse for $f$. Say $f^{-1}(x) = -\sqrt x$.  This is a perfectly good partial inverse for $f$.  Again we have $f(f^{-1}(x)) = \left(-\sqrt x\right)^2 = x$ for all $x$ for which the expression is well defined, but this time we have $f^{-1}(f(x)) = x$ only for $x\le 0$; for example $f(f^{-1}(49)) = f(-7) = 49$ and $f^{-1}(f(-7)) = f^{-1}(49) = -7,$ but $f^{-1}(f(7)) = f^{-1}(49) = -7\ne 7.$
Or we could choose a still more unusual inverse for $f(x)$. Say that $f^{-1}(x)$ is $\sqrt x$ when the integer part of $x$ is even, and $-\sqrt x$ when the integer part of $x$ is odd.  Then we have $f^{-1}(f(x)) = x$ whenever $x\ge 0$ and its integer part is even, or whenever $x\lt 0$ and its integer part is odd, but not otherwise.  So for example $f^{-1}(f(8.5)) = 8.5$, but $f^{-1}(f(7.5)) = -7.5 \ne 7.5$.
So the set of values $x$ for which $f^{-1}(f(x)) = x$ will depend on how we choose to define the inverse function; when $f$ is not injective, there may be many reasonable ways to define the inverse.
With $\sin$ we have the question of how to define the inverse.  We can't simply say that $\sin^{-1} y$ is "the" value $x$ for which $\sin x = y$, because there are many such $x$ for each $y$. We usually choose the definition  that says that $\sin^{-1} y$ is the value $x$  for which $\sin x = y$ and $-\frac\pi2 \le x \le \frac\pi2$; this definition does select a unique $x$, because the sine function is injective for $x$ between $-\frac\pi2$ and $\frac\pi2$.
For this definition of $\sin^{-1}$, we have the property that $\sin(\sin^{-1}(x)) = x$ everywhere the left-hand side is defined, and $\sin^{-1}(\sin x) = x$ exactly when $-\frac\pi2 \le x \le \frac\pi2$.
Answer: Since, for any $y \in [-1,1]$, several different $x$ have $\sin(x)=y$, either $\sin^{-1}(y)$ is multivalued and so not a function, or you need to restrict its range by taking a principal value.  Usually the later choice is made, with $-\pi/2 \le \sin^{-1}(y) \le  \pi/2$.
So in answer to your title question:  $  \sin^{-1} (\sin (\pi)) \not = \pi$ because $\pi \gt  \pi/2$ and in fact $\sin^{-1} (\sin (\pi)) = \sin^{-1} (0) = 0$.
$\sin^{-1} (\sin (x)) = x $ when $-\pi/2 \le x \le  \pi/2$.


Using Subsonic 3.0 With Silverlight

Question: I am writing a silverlight Line of business application and wanted to use the Subsonic DAL.  The Silverlight Project will not allow me to Add the Subsonic reference with the followng error "You can not add the Subsonic.Core.Dll as it was not built against the Silverlight Runtime".  I assume that I could create a webservice and add the Subsonic to that, but I would like to just add it to the Silverlight Project. Has anyone done this and if so how.  If not is there an easy way to expose the DAL through the Webservice.
Answer: You don't want to access your database directly from your silverlight application. This will create a big security hole. Remember that the silverlight client runs on the clients machine and the traffic between the client and the server can easily be tampered with.
For easy access, to a server side API, you can try .NET RIA Services.
Answer: To clarify the error message: Silverlight is based on .net, but you can't just run any .net assembly in silverlight. This is because a lot of stuff in normal .net is simplified, not allowed or not supported in client-side silverlight, which makes binary compatibility difficult or even pointless.

Using Subsonic 3.0 With Silverlight


Possible to disable jNice (jQuery plugin) for IE6?

Question: We're using the jNice plugin (http://plugins.jquery.com/project/jNice) to style form inputs. It doesn't play well with IE6 and we want to disble it there.
Answer:
Don't add the jNice class to your form element.
Use the following to run jNice:
jQuery(function ($) {
    if (!($.browser.msie && $.browser.version < 7)) {
        $('form').jNice();
    }
});

You can also use the IE conditional markup suggested by others:
<![if gte IE 7]>

<![endif]>

IE conditionals are a better solution because they won't fail in the event of browser spoofing (where the browser pretends it has a different user agent).  However, they don't produce valid XHTML (afaik) and aren't as flexible.
Comment: A much nicer approach than my own (now deleted) attempt.
Comment: Agreed, I had forgotten about jquery's browser detection, this is a very good way to do it.
Comment: IE conditionals are a better solution because they won't fail in the event of browser spoofing (where the browser pretends it has a different user agent).


Create a screensaver preview in Delphi

Question: I've created a screen saver in Delphi 10 Lite, using diffrent descriptions about this question, available on the web. Now, the screen saver works well, one thing is missing: a good working preview on the Screen Saver Settings dialog box. How can it be created? I've read this description: how to make a screen saver preview in Delphi?
but I'd like something more specific, maybe with an example. I'm using Windows 7 Ultimate SP1.
Thanks.
Comment: What is unclear about the instructions on that other question? You have to implement the `/p` command-line argument to accept an `HWND` as input. If provided, you simply render your screensaver normally using that `HWND` as the parent window for your screensaver's UI, otherwise you create your own full-screen `HWND` as the parent window instead.
Comment: There's no such thing as Delphi 10 Lite. What version of Delphi are you really using?
Comment: How your screen saver implemented, exactly?
Answer: The Embarcadero site, provides a fully functional screen saver sample, which includes the   normal execution (run), preview, password setting and so on. Try this article Random Images Screen Saver - a complete screen saver example, the source code can be downloaded from here.
Comment: I don't know what's happening, but I can't properly open the source code: difrent error messages appears. Now I will take a look to the website to see if I can find something useful. Thank you, anyway.
Comment: @LaszloBalazs - I confirm. As usual, the Embarcadero site is broken (The connection has timed out).
Answer: Here's what I did in my little scrub screen saver test (done to see how one works more than it be polished):
WinHandle is the window id passed during the /P switch.  I rigged things (the screen saver just puts up a defined text in different colors with a defined delay between them) for the screen saver to act on a window handle so I didn't have to duplicate the screen saver code itself.  SS_Init initializes things for the screen saver, SS_Start does one step of it, SS_End wraps things up.
if program_state = Preview then  // code before indicates /P was passed
  begin
    { spindle off messages until window is visible }
    while not IsWindowVisible(WinHandle) do
      Application.ProcessMessages;
    { initialize and do screen saver draw }
    start_time := WinMSSinceStart; // timeGetTime
    SS_Init(WinHandle);
    while IsWindowVisible(Winhandle) do
      begin
        if (WinMSSinceStart - Start_Time) >= config_rec.Delay then
          begin
             SS_Start(WinHandle);
             start_time := WinMSSinceStart;
          end;
        Application.ProcessMessages;
        sleep(10);
      end;
    SS_End(Winhandle);
end;

Here's how you set up the TCanvas to draw on the window handle that is passed (this is in SS_Init (but not the whole thing).  MyCanvas is a property I have defined in line with this code:
  { get window dimensions and set up TCanvas }
  GetClientRect(WinHandle, WinRect);
  MyCanvas := TCanvas.Create;
  MyCanvas.Handle := GetDC(Winhandle);

Then when you're done (this is my whole SS_End function):
  ReleaseDC(WinHandle, MyCanvas.Handle);
  MyCanvas.Free;

Hope that helps out.
Comment: Thank you, I will take a look and will come back.

Create a screensaver preview in Delphi


Analytic function - Comparing values using LAG()

Question: Assume following data:
| Col1  |   Col2      |
| 3     |  20-dec-15  |
| 4     |  20-dec-15  |
| 8     |  25-dec-15  |
|10     |  25-dec-15  |

I have to compare the values of column Col1 for a particular date.
For Example: For 20-dec-15 changes occured as 3 changed to 4.
I have to solve this using an analytical function.
Following is the query which I am using
decode(LAG(Col1,1,Col1) OVER (partition by Col2 order by Col2),Col1,0,1) Changes

As Col2 is date column, Partition by date is not working for me. Can we apply date column as Partition?
Expected Result should be:
| Changes  |
| 0        |
| 1        |
| 0        |
| 1        |

Here 1 means Change occured while comparing for same date.
Answer: You need to use trunc() in order to reset the time part to 00:00:00 but you should still keep order by col2 so that all rows on the same day are ordered by the time part:
I also prefer an explicit case for this kind of comparison, personally I find the decode() really hard to read:
select case
         when col1 = lag(col1,1,col1) over (partition by trunc(col2) order by col2) then 0
         else 1
       end as changes
from the_table;

Comment: I tried with to_date(col2) , that seems to be working.
Comment: @subi_speedrunner: `to_date()` converts a **`varchar`** value into a `date` value. Do ***not*** use it on columns defined as `date`. It will first implicitly convert the `date` to a `varchar` just to convert it back to a `date` which it was to begin with.
Comment: Thanks for this info. I will make sure not to use `to_date()` with a `Date` field.


Is it possible to change position of the segment so that it is parallel to Y axis?

Question: Let's consider infinite Cartesian system of coordinates. Assume that in any lattice point (i.e. both coordinates are integers) there is a spike. I have a line segment of length $n$ (it is an integer). It is parallel to X axis, as shown below (image shows only a part of system of coordinates).

I want to make it parallel to Y axis as shown below.

What I can do is rotate and move this line segment, but without raising it up. I can't change shape, length etc. of it. Movement and rotation, as you can see, is limited by the spikes in lattice points. Below is an example of one of possible moves. My question: is it possible to make this line segment parallel to Y-axis?

I do believe that Chinese Remainder Theorem has something to do with this.
Comment: It can be done if and only if the length of line segment is less than $\sqrt{2}$
Comment: Why is that true?
Comment: If the length is less than $\sqrt{2}$ it can be put inside a single square, and from there putting one vertex "close" to a lattice point and rotating the the line about that point you can move the line segment to vertical position. This can be done because diagonal of square has length $\sqrt{2}$. If the length is at least $\sqrt{2}$, just considering one vertex of the line, wherever it is positioned in a single square, you cannot escape that square via rotating because the other end will always be out of the squre, as length is at least the diagonal.
Comment: This is not a mathematical argument, but I don't know why you can't slide the segment to the left so the right end is just shy of a lattice point. Now rotate it counterclockwise so the end is above the lattice point. Slide the segment to the right and increase the angle. Now, instead of the segment being contained between two integers $a$ and $a+1$, now it's between $a$ and $a+2$. If the length of the segment is 2, you are done. If the length is longer, repeat until the segment is vertical.
Comment: @scott I don't think that will work without changing length of the segment. After you've rotated, when you slide right, how do you know the other end part of segment doesn't cross the lattice point? I think it should.
Comment: @user160738 - look at the final graph. If the line is slid left far enough that the right endpoint moves past the nearby lattice point, then the line can be rotated until the rt. end is on the other side of it, then slid right to get the lh vertex around its nearby lattice point. This can continue. I don't know if this is possible for all lengths of lines, but I have little doubt the example can be made vertical.
Comment: @user160738 Lookup [Kakeya needle sets](https://en.wikipedia.org/wiki/Kakeya_set) which can be made arbitrarily small, yet allow a "needle" to be completely turned around inside it. The question asked here is whether such a set exists which does not cross lattice points. Gut guess would be yes, but that's not my cup of tea, so I'll leave it to others to settle.
Answer: Put an edge of the stick in the point $O=(\sqrt 2,1/2)$. Consider all points with integer coordinates which have distance from $0$ not larger than $n+1$ ($n$ is the length of the stick). These are a finite number of points. Order them by their angle with respect to $O$: $\alpha_1, \dots, \alpha_N$. Since $O$ has an irrational coordinate, all points have a different angle (not really important) and moreover if there is a point with angle $\alpha$ there is no point with angle $\alpha+\pi$ (this is used to simplify the algorithm). To make the stick rotate around the point $O$ it is enough to describe a "move" to pass across each pin. Let $\alpha$ be the angle of the pin $P$. Since the circle of radius $n+1$ centered in $O$ contains a finite number of pins, there is a small angle around $\alpha$ and around $\alpha+\pi$ which contains no pins apart from $P$. Also a small circle around $O$ contains no pins (not really needed). The pin can then move in the orange region of the picture. You can easily translate it in the opposite sector, rotate a little and translate back to pass the point $P$.
A very similar problem: http://mathworld.wolfram.com/KakeyaNeedleProblem.html
Comment: very clever approach indeed!!
Comment: Any chance you could illustrate your algorithm with an example? The procedure is not clear to me.
Comment: It is not easy to explain. However I found a simpler algorithm which is maybe more clear. Look again at the answer (and the picture).
Comment: When you say "$-\alpha$", do you mean $\alpha+\pi$? And when you say "... translate it in the opposite sector, rotate a little..." do you mean that you rotate the left end of the stick down, using the point $O$ as axis? If so, I don't see how you know the left end of the stick doesn't cross any spikes.
Comment: @Jens: right: I mean the opposite direction which is $\alpha + \pi$. There are no pins there because the line has irrational slope, so it cannot contain two points with integer coordinates.
Answer: If both the "spikes" and the "segment" are infinitesimally thin, and the plane is infinite, then I do believe it is always possible to rotate the segment to any angle.
I don't have the math-fu to prove this mathematically, but I can describe a simple iterative algorithm that should achieve this rotation:

Move the line segment furthest away from any lattice point (maximizing the minimum distance to a lattice point).
Rotate the line segment (in the same direction), until it reaches the desired orientation, or touches a lattice point.
If the line segment touches only one lattice point, repeat at step 1.
Move the line along its length so that the lattice point stopping the desired rotation is just past the end of the line segment, allowing the line segment to be rotated (in the same direction) again.
Repeat at step 2.

If there is an interesting enough underlying problem here, it would not be that difficult to create a numerical simulator or GUI/minigame for this -- say, using Python and Qt for readability and portability.

I just realized that in the case of infinitely thin spikes and infinitely thin line segment of any length, all possible states can be divided in two categories: "pinned" and "free". The phase space of such a system is continuous (as opposed to discrete), but not completely connected.
(You can think of the phase space of a line segment of some specific length L as an unit cube, possibly repeated inifinitely, depending on how you define the coordinates. The x and y coordinates correspond to the position of the center of the line segment, and the z coordinate corresponds to the orientation, say line segment making angle $z·180°$ with the $x$ axis, measured counterclockwise.)
"Pinned" states are those where no rotation is possible, and movement is restricted to the direction along the line segment. "Free" states are those where rotation is possible at least in one direction; because the line segment is infinitesimally thin, movement is also always possible in the "free" states.
"Free" and "pinned" states may only be connected via states without rotation. If the line segment is long enough to be pinned (in that orientation) by at least four pins, the "pinned" state is disconnected from the "free" states, because movement is only possible along the direction of the line segment, and the line segment stays pinned by at least three pins at all times due to symmetry in the simple cubic lattice.
To prove that a line segment of some length can be rotated to any angle, one needs to prove that the phase space for a line segment of that length has a connected region that includes both the initial and the final orientations.
Based on the existence of algorithms like mine above and the variant gue implemented in their answer, the phase space for the "free" states of a specific length line segment is connected. This connected region contains all orientations of the line segment.
What I do not know, is whether the above is sufficient proof.
The interesting thing, and the reason this question is so tricky to think of, is that for a line segment of sufficient length, the phase space is fragmented: there is one connected "free" region, dotted with small only internally connected "pinned" regions. (Again, I'm not sure I've proven this, but this is my current understanding.)
Thus, the only "risk" in an algorithm that rotates such a line segment is that one of its moves causes the line segment to be "pinned", leading to a deadlock.
Comment: I agree that the problem of "pinning" appears to be an issue. I ran into this when trying manually with $n=10$.
Answer: This is no formal proof. Step by step construction works just fine for $n=4.5$ and $7$. For an arbitrary $n$ I would also support @Nominal Animal's answer, that it is always possible if the spikes and line segment are infinitely small, thin. Images are for $n=4.5$ (the $.5$ happened by accident), for $n=7$ look at the PDF (this is in IPE format, so one can manually recheck).
I guess an argument in the formal proof would be that even for an arbitrary large $n$. If we position the segment $\ell$ in the center of a square such that the endpoints are horizontally aligned with the grid points, then we can rotate $\ell$ past the two grid-points (left/right) where the endpoints of $\ell$ reside.
Comment: A minor comment to your examples: the lengths appear to be $n=4.5$ and $n=7$.
Comment: Hey, yes you are right, my mistake.


Why $sgn(\sigma)=(-1)^{j-1} sgn(\tau)$?

Question: Problem:
Suppose that $\sigma \in \mathcal{S}_k=\{f:\{1,...,k\} \to \{1,...,k\} \mbox{ is bijective} \}$. We know that $\sigma$ has $sgn(\sigma) \in \{-1,1\}$. Suppose that $\sigma(1)=j$.
Let us define $\tau \in \mathcal{S}_{k-1}$ in this way:
$$\tau(i)=
\begin{cases}
\sigma(i+1) \mbox{ if } \sigma(i+1)<j \\ \sigma(i+1)-1 \mbox{ if } \sigma(i+1)>j
\end{cases}  \mbox{      for all }i \in \{1,...,k-1\}$$
Why can we conclude $sgn(\sigma)=(-1)^{j-1}sgn(\tau)$?
Comment: Hint: how can you change $\sigma$ to $\tau$ by exchanging values in pairs?
Comment: @J.G. Could you please explain me more? I cannot understand what are you referring to
Answer: Let $\xi$ be permutation on $\{1,2,\ldots,k\}$ that leaves $\{1,2,\ldots,j-1\}$ unchanged and moves $\{j,j+1,\ldots,k\}$ to $\{k,j,j+1,\ldots,k-1\}$. Then $\xi \circ \sigma$ is basically $\tau$ with $k$ inserted to the beginning – so composing it with $k$-cycle we will get $\tau$ with additional $k$ at the end, which has the same sign as $\tau$. Then, since sign of $t$-cycle is $(-1)^{t-1}$,
$$(-1)^{k-1} \cdot (-1)^{k-j} \cdot sgn(\sigma) = sgn(\tau),$$
which is what we wanted to prove.
Comment: Could you please add more details? What do you mean with "$\xi \circ \sigma$ is basically $\tau$"?

Why $sgn(\sigma)=(-1)^{j-1} sgn(\tau)$?


Mixed model with repeated measures with adjusting for confounding variables

Question: I have a large database with repeated measures of Y at various times. Y is continuous, and I know that its evolution is usually modified by numerous baseline confounders.
I am trying to fit a mixed model. Here is a little reprex in R. I hope that the question won't be too much R-driven.
My actual dataset is much larger (300k+ lines in long) and confounders can be continuous or categorical, but the spirit is the same. In this example, let's say X1 is the variable I hypothesize is influencing the evolution of Y over time, and X2 is a confounder.
library(dplyr)
library(lme4)

df.long = data.frame(
  id=c(rep(c("A", "B", "C"), each=5)),
  time=c(1,2,3,4,5,10,11,12,13,14,5,6,7,8,9),
  y=c(25,32,35,37,40,55,51,59,57,60,10,15,20,30,45)
)
df.baseline = data.frame(
  id=c("A", "B", "C"),
  x1=c(98, 42, 23),
  x2=c(250,390,527)
)

df = df.long %>% left_join(df.baseline, by="id")
df
#    id time  y x1  x2
# 1   A    1 25 98 250
# 2   A    2 32 98 250
# 3   A    4 35 98 250
# 4   A    7 37 98 250
# 5   A    8 40 98 250
# 6   B   10 55 42 390
# 7   B   12 51 42 390
# 8   B   16 59 42 390
#...

I've seen a whole lot of ressources, but very few talks about specific times and even less about adjusting for confounding variables.
In my notebook, there is a small paragraph about the time, saying you should set a specific covariance matrix Toeplitz-like since time3 is more associated to time2 than to time1.
But since I don't have time1 and time3, but a huge set of different times, with unequal delta between them, how can I build such a covariance matrix?  And then how can I apply it to my model ?
Also, how should I put confounders in my model? Some talks about interaction on time (time*x1*x2), but with many confounders it makes little sense to me.
For the record, the best model I've made up so far (based on this answer) is :
lmeModel = lmer(y ~ time + x1 + x2 + (1+ time|id), data=df)

For what I understand, it has random effect on id and should account for the effect of time for each id. But it is not clear if I should keep time as standalone, neither as if the covariance matrix is OK.
DISCLAIMER: this may be a confusing question, but please help me to improve it if you think so.
Answer: A couple of points:

A general model-building strategy for mixed models is that you start with an elaborate/flexible specification of the fixed-effects part, including nonlinear and interactions terms. Then keeping this elaborate fixed-effects structure you build your random-effects part. Typically, you start with a random intercept (that corresponds to constant correlation over time), and you move to random slopes and possibly also higher-order terms, such as nonlinear random slopes. Also, depending on the features of your study it may be required to included random effects for other grouping factors (e.g., in a multilevel design). After you selected your random effects, you can return to the fixed-effects part and try to simplify your model, starting from seeing if you need the complex nonlinear/interaction terms. For more on this, you can have a look at Sections 3.1, 3.2 (also useful 2.4) and 3.9 of my course notes.
When you include random slopes in your random-effects part, you indeed assume that measurements that are closer in time are more strongly correlated than measurements that are further apart. To get a better intuition on how random effects capture correlations, you can have a look at Section 3.3 of my shiny app for my course mentioned above.
Indeed including three-way interactions of time with x1 and x2 can make interpretation difficult. Typically, I only consider interactions of time with other variables for longitudinal data. See again Section 2.4 and 3.2.
Comment: This is a pretty awesome GitHub app, kudos and thanks for sharing it, I've learn a lot !


How can I create a button with an image?

Question: I have an image that i want to use as a button on my page that links to other pages. I want to make it in a way that I can use small and large texts on it.
The image in question:

I have tried something but can go no where with it.
a {
    background:url(http://i.imgur.com/8Isga60.png);
    background-size:contain;
    background-repeat:no-repeat;
    display:inline-block;
    padding:30px 100px;
    height:20px;
    color:black;
    font-size:16px;

}

JS Fiddle
Comment: You should recreate the button in CSS instead of using a static image. That way it will size to whatever content is within it without distorting the style of the button.
Comment: css will not be able to incorporate the design that is in the image :(
Comment: There might be a solution for some length, but at some point an image will always be too small (because it is a fixed size).  You really should consider a pure CSS solution for the button (without image).  Just google "CSS button generator"
Comment: The old-school method of doing this is: http://alistapart.com/article/slidingdoors
Comment: Main requirement is the indent on the sides and the gloss at the bottom as you can see in the image. I have actually tried pure css but can not make the indent and the gloss.
Answer: I would recommend you drop the image idea... that concept is very 2005.  With today's CSS you can easily recreate that image with pure CSS, which then is much more flexible.
If you Google "CSS button generator" you will find many online tools that help you with that... i.e. http://www.cssbuttongenerator.com/
Here is an example I did in 10 seconds and just copied the CSS they provided... granted it is a little convoluted, but it certainly works:

Comment: @user3771900 - You might want to talk to your designer then. A pure CSS solution can get you very close (as Nick R's solution shows) and is much, much, much more flexible.  Pure image solutions will break constantly and are a b***h to maintain.
Comment: We can probably drop most of those `-moz-*` and `-webkit-*` prefixes now (it's *so* 2009).
Comment: Sorry don't want a full CSS button, I need to use the design of the image. Thanks for the time.
Comment: @WesleyMurch - fully agreed.  Just copied/pasted straight from the website to show how quickly you can create a CSS button, with little knowledge of CSS.  But you are right, it should probably be cleaned up.
Comment: @Steve I know Steve I am trying to pursue my designer to dump the image's design.
Answer: You could almost do it in CSS3: JSFiddle Demo
.btn {

    margin:10px;
    color:white;
    font-size:16px;
    border:4px solid #c5c7c9;
    border-radius: 50px 50px;
    display:inline-block;

    /* Drop shadow */
    -webkit-box-shadow: 1px 1px 2px 0px rgba(50, 50, 50, 0.68);
    -moz-box-shadow:    1px 1px 2px 0px rgba(50, 50, 50, 0.68);
    box-shadow:         1px 1px 2px 0px rgba(50, 50, 50, 0.68);

    /* Gradient Background */

    background: rgb(78,186,234); /* Old browsers */

    background: -moz-linear-gradient(left, rgba(78,186,234,1) 0%, rgba(0,121,183,1) 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(78,186,234,1)), color-stop(100%,rgba(0,121,183,1))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(left, rgba(78,186,234,1) 0%,rgba(0,121,183,1) 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(left, rgba(78,186,234,1) 0%,rgba(0,121,183,1) 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(left, rgba(78,186,234,1) 0%,rgba(0,121,183,1) 100%); /* IE10+ */
    background: linear-gradient(to right, rgba(78,186,234,1) 0%,rgba(0,121,183,1) 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#4ebaea', endColorstr='#0079b7',GradientType=1 ); /* IE6-9 */

}

    /* Button Sizes. */
    .btn.large {  padding:30px 60px; }
    .btn.small {   padding:10px 30px; }

HTML
my text here
my text here
my text here long text goes here

Comment: +1 - Very nice demo of how close you can get to the original design and how flexible it gets for long, short, tall content. Nicely done!
Answer: I think you will have to split the image, as If you try to repeat it using it as a complete image, it will also repeat the rounded parts. So take the left and right, and a pixel from the center. See this answer for reference Button using three (3) background images css
The old school version is something like using three classes for left and right and one for center with the repeating background.Create button using 3 images
Now, as mentioned in the comments, unless you are completely decided on the background images part, a pure CSS solution will probably work better.
Comment: That approach is very 2005... we can be much more light-wight and flexible with pure CSS these days.
Comment: While I agree, the OP did not put an age restriction on the solution. Now, I updated the answer, as the old and cool new (and probably more efficient) options have been presented many times in other questions.
Comment: I will have to use the old school idea for now. Thanks @Ernesto
Answer: The problem is the left & right padding, Why not separate the link and the text so it's easy to center the content?
(edit: jsfiddle )

Does not work with larger text

a.sol {
        background:url(http://i.imgur.com/8Isga60.png);
        display:inline-block;
        padding:30px 0px;
        width: 243px;
        height:20px;
        color:white;
        font-size:16px;
        text-align: center;
    }

Answer: Try this:
a{
    background:url(http://i.imgur.com/8Isga60.png) no-repeat center;
    ...
}

However it moves the button too. jsfiddle
You should really look into CSS buttons instead of using images. Try CSS Button Generator


Estimation of order of sum-covering subset

Question: This question is from Tao and Vu's book, Exercise 1.1.7., which is part of the chapter "The probabilistic method".
The problem is:
Problem. Consider a nonempty subset $A$ of finite abelian group $(Z,+)$. Show that there exists a subset $\{v_1,v_2, ..., v_d\}$ of $Z$ with $d=O(\log\frac{|Z|}{|A|}+\log\log(10+|Z|))$ such that
\begin{equation}
 A+\{0,1\}^d \cdot (v_1,v_2, ..., v_d)=\{a+\sum u_i v_i | a\in A, u_i=0 \ \text{or} \ 1 \}=Z.
\end{equation}
I tried to solve this problem, but I am having a hard time to improve this. I'd like to introduce my attempt:
I used the following lemma.
Lemma. Let $A,B$ be nonempty subsets of $Z$, then there exists an $x\in Z$ such that
\begin{equation}
1-\frac{|A\cup(B+x)|}{|Z|}\leq \left( 1-\frac{|A|}{|Z|}\right)\left( 1-\frac{|B|}{|Z|}\right).
\end{equation}
Proof: Let us choose $x$ uniformly random from $Z$ and $(B+x)=B'$. Then $E(|A\cup B'|)=E(|A|+|B'|-|A\cap B'|)$ $=E(|A|)+E(|B'|)-E(|A\cap B'|)$, and $E(|A\cap B'|)=\sum_{x\in Z} P(x\in A\cap B')=\sum_{x\in Z} P(x\in A)P(x\in B')$ $=\displaystyle\sum_{x\in Z}\frac{|A||B'|}{|Z|^2}=|A||B'|/|Z|$. Since $|B'|=|B|$, we deduce $E\left(1-\displaystyle\frac{|A\cup(B')|}{|Z|}\right)= \left( 1-\displaystyle\frac{|A|}{|Z|}\right)\left( 1-\displaystyle\frac{|B|}{|Z|}\right)$.
Now let $A_i=A_{i-1}\cup (A_{i-1}+v_i)$. Then clearly $A_0=A$ and $A_d=A+\{0,1\}^d \cdot (v_1,v_2, ..., v_d)$.
By lemma, we can choose $v_i$ such that $$1-|A_i|/|Z|\leq (1-|A_{i-1}|/|Z|)^2,$$ or $$|A_i|\geq |A_{i-1}|(2-|A_{i-1}|/|Z|).$$ Using this inequality inductively, we get $|A_d|\geq \prod_{1\leq i\leq d}(2-|A_{i-1}|/|{Z}|)|A_0|$. Now, since we can choose $v_i$ such that $|A_i|\gneq|A_{i-1}|$ (if |A_i|=|A_{i-1}|, adding $v_i$ is actually meaningless.), so at least $$|A_d|\geq \prod_{1\leq i \leq d}\left(1+i/|Z|\right) |A_0|.$$
Taking logarithm at both side, we get $\log|A_d|\geq\sum_{1\leq i\leq d}\log(1+i/|Z|)+\log|A|$. We have to choose $d$ satisfying $|A_d|\geq|Z|$ so that $A_d=Z$, so let's find such $d$ with $\sum_{1\leq i\leq d}\log(1+i/|Z|)+\log|A|\geq \log |Z|$.
I want to estimate 'well' $$\sum_{1\leq i\leq d}\log(1+i/|Z|)\sim\int_1^d \log(1+\frac{x}{|Z|})dx\sim (|Z|+d)\log(1+\frac{d}{|Z|})-d$$ so that we can find inequality of $d$.
I am having trouble to make this inequality into usable form.
Also, I worry the assumption of at least part that bounds $|A_d|\geq \prod_{1\leq i \leq d}\left(1+i/|Z|\right) |A_0|$ is overkilling.
Another question, I am undergraduate student and not mathematically mature yet. However, I am very fascinated to analytic number theory and additive combinatorics. I am also interested in ergodic number theory, or ergodic Ramsey theory. However, in my university, classes about these subjects merely opens, so I have to self-study these subjects. Are there any recommendations about studying materials, or curriculums, or anything else?
Any helps will be thankful!
Answer: You have the right construction, just need to arrange the derivation of the final bound a little differently.
Let $\alpha=\lvert A\rvert/\lvert Z\rvert$ and, in general, $\alpha_i=\lvert A_i\rvert/\lvert Z\rvert$. By the construction you outline, with $A_0=A$ and $A_i = A + \{0,1\}^i\cdot (v_1,\ldots,v_i)$ for some suitable choice of $v_i$ we can iteratively ensure that
$$ 1- \alpha_{i+1}\leq (1-\alpha_i)^2.$$
While $\alpha_i\leq 1/2$ this implies that $\alpha_{i+1}\geq \frac{3}{2}\alpha_i$, and so in general $\alpha_d \geq (3/2)^d\alpha$. In particular, there is $d=O(\log(1/\alpha))$ such that $\alpha_d\geq 1/2$.
We now continue the same procedure, but now notice that $(1-\alpha_d)\leq 1/2$, and so in general this iteration will give
$$ 1-\alpha_{d+k} \leq 2^{-2^k}.$$
In particular after $k=O(\log\log \lvert Z\rvert)$ steps we have $1-\alpha_{d+k}< 1/\lvert Z\rvert$, and so $\lvert A_{d+k}\rvert > \lvert Z\rvert-1$, and hence $A_{d+k}=Z$ as required.


Splitting a card deck of 100 cards into two decks of 50 cards

Question: Consider a card game with $100$ playing cards, of which exactly two cards are Jokers. After a good mix, the cards are divided into two piles of $50$ cards each. These are referred to as $Pile1$ and $Pile2$.
Suppose we get the information that at least one of the two jokers is in $Pile1$. What is the probability that the other joker is also in $Pile1$?
We will call the jokers now $Joker1$ and $Joker2$. What is the probability that $Joker2$ is in $Pile1$ if we already know that $Joker1$ is in $Pile1$?
So for the first question we know that one joker was already drawn so we use the Hyper-geometric distribution to find the probability of drawing the second one: $Hyp(99,1,49)(\{1\})$ so we are drawing $49$ from $99$ cards of which only $1$ is a joker and we calculate the probability of one success. And we get $0.25242$.  But I have no idea why naming the jokers would make a difference in the second question.
Would appreciate any help.
Comment: Your result of $0.25242$ is way off. The correct answers to these two questions are approximately $\frac13$ and $\frac12$ respectively. Use [Bayes' theorem](https://en.wikipedia.org/wiki/Bayes%27_theorem) if you want exact values.
Comment: What events have you used in the Bayes theorem to get those numbers? (What is $A$ and what is $B$)
Comment: For example, in the first question, $A$ is "two jokers in Pile$1$" and $B$ is "at least one joker in Pile$1$".
Answer: Perhaps it helps to consider the $4$ a priori cases.  We will label the cases $(i,j)$ for $i,j\in \{1,2\}$, where, say, $(1,2)$ means that $J_1\in \text{Pile}_1$ and $J_2\in \text{Pile}_2$ while $(1,1)$ means that both jokers are in $\text{Pile}_1$.
The probability of each case is:
$P_{1,1}=P_{2,2}= \binom {98}{48}\big / \binom {100}{50}=.2\overline {47}$
$P_{1,2}=P_{2,1}=\binom {98}{49}\big/ \binom {100}{50}=.\overline {25}$
Sanity checks:  Note that these add to $1$ as they should, and note that we expected each case to be around $\frac 14$.
Now, your first question asks:  What is the probability that you are in case $(1,1)$ given that you are not in $(2,2)$?
The answer is, of course, $$\frac {P_{1,1}}{1-P_{2,2}}=\frac {P_{1,1}}{P_{1,1}+P_{1,2}+P_{2,1}}=.328859$$
The second question asks:  What is the probability that you are in $(1,1)$ given that you are either in $(1,1)$ or $(1,2)$?
The answer, of course, is:  $$\frac {P_{1,1}}{P_{1,1}+P_{1,2}}=.\overline {49}$$
Note that these answers are easy to justify intuitively:  if we ignore the slight dependence on the placement of the jokers, each case would have probability exactly $\frac 14$, so the answer to the first question would be $\frac 13$ while the answer to the second would be $\frac 12$.  As expected, we see that the (very minor) dependence changes the intuitive results only slightly.
Comment: If $J_1$ is in pile $1$ then we just need to choose $49$ other cards from the $98$ non-Jokers in order to complete Pile $1$.
Comment: So how would it look like if I wanted to get the exact numbers using Bayes formula?
Comment: I have given you the exact numbers using Bayes' Theorem.  Well, the $.328859$ is rounded down a little.
Comment: sorry, I wasn't able to see that. How did you get the probabilities for the cases?
Comment: I wrote out the computations exactly.  Since each shuffle is equally probable, it's just a matter of counting.  Note that it suffices to look at a single Pile since the contents of one Pile determine the contents of the other.
Comment: For intuition you should consider the "simpler" problem:  Suppose you toss a fair penny and a fair dime. $\#1:$ What's the probability that they both come up $H$ given that at least one of them does?    $\#2:$ What's the probability that they both come up $H$ given that the dime does?
Comment: The answer is $1/2$ for $2$
Comment: Yes, the answer to $\#2$ is $\frac 12$.
Comment: I really can't think about the first question without overwhelming my self.
Comment: Where do the questions $1$ and $2$ even differ?
Comment: Just use the same steps I followed.  For the simpler problem, it is easier to compute the probabilities of each of the $4$ cases.
Comment: [this question](https://math.stackexchange.com/questions/200807/boy-and-girl-paradox) might help with intuition.  Note too:  it's easy to do the experiment to test the computations.  All you need is two coins (or, really, just one since you can throw it twice).
Comment: So we have the $4$ cases ${(H,H),(H,T),(T,H),(T,T)}$ with prob. of $1/4$ each. In $#1$ we take out the case that don't have $H$ in them and calculate the prob. of getting another $H$ which is $1/3$
Comment: In $#2$ we have $\frac{1/4}{1/4+1/4}=1/2$
Comment: I'm still a bit fuzzy on how you got $0.\overline{25}$ for the probability of cases $2$ and $3$.
Comment: Thx, really helped me out a lot :D
Comment: I just thought of a different approach for the first question considering we don't differentiate between $joker_1$ and $joker_2$. We have exactly three outcomes which are $0$, $1$ or $2$ jokers in $Pile_1$. and given that we know that we already have a joker in $Pile_1$ that leaves us with two cases, of which only one has two jokers giving us a probability of $1/2$ .
Comment: @Zntzozt Well, those three cases are not equally probable (that's why I used four cases).  But, yes.  This is the same idea.  Note that it only works exactly in the case where you can disregard the dependence.
Comment: But the distinction between the jokers happens only in the second question.


Using IPS(inverse probability weighting) with a deterministic policy as the logging policy

Question: In a contextual bandit problem, why can't we use inverse probability weighting (inverse propensity score) with a deterministic policy as the logging policy? Could you give me a concrete example?
Answer: Consider a coin-flipping experiment, where we first select a coin (context - $x$), flip the selected coin to receive an action $y$ (head or tail) and finally, based on the context and the action, we receive a reward $\delta(x,y)$. The reward function $\delta(x,y)$ is not known and it is observed only through the experiment results.
Intuitively, we cannot learn from a deterministic policy (that is the coin toss would always return either head or tail for a given coin), because we would never observe the reward for the unseen action - that is the policy does not explore at all.
The IPS estimate tries to estimate the reward received by a logging policy $\pi_0(y|x)$ if we would use an alternative policy $\pi_A(y|x)$ instead of $\pi_0(y|x)$. In our setup, it means that we $N$-times choose a coin ($x_i$) according to some $p(x)$, flip it and based on the coin-flip result $y_i$ (according to $\pi_{0,i}=\pi_0(y=y_i|x=x_i)$) receive a reward for given context and action $\delta_i=\delta(x_i, y_i)$. Thus we have available a collection of tuples $\{(x_i, y_i,\delta_i, \pi_{0,i})\}_{i=1}^N$.
To answer the original question, we consider the IPS derivation as
$$
R(\pi_A)\stackrel{(a)}{=}\mathrm{E}_{x\sim P(x), y\sim \pi_A(y \vert x)} \left[\delta(x,y)\right]
        \stackrel{(b)}{=}\mathrm{E}_{x\sim P(x), y\sim \pi_0(y \vert x)} \left[\frac{\pi_A(y \vert x)}{\pi_0(y \vert x)}\delta(x,y)\right] \\
        \stackrel{(c)}{\approx} \frac{1}{N}\sum_{i=1}^N \frac{\pi_{A}(x_i \vert y_i)}{\pi_{0}(x_i \vert y_i)} \delta_i
= \hat{R}_{\mathrm{IPS}}(\pi_A),
$$
where (a) is the definition of target estimate, (b) is the crucial step for the IPS derivation, where we switch the expectation over $\pi_A$ to expectaion over $\pi_0$. One can see that division by zero occurs if $\pi_0(y|x)=0$ for some $x,y$ (among others, a deterministic $\pi_0$ leads to $\pi_0(y|x)=0$ for some $y$). Monte Carlo approximation is used in (c), where and it basicly aproximate the expectation by empirical mean. Thus we shown that IPS gives an infinite reward estimate in case of deterministic $\pi_0$ that obviously makes no sense in practical applications.


Differences of sets

Question: I struggled proving the following propositions, I'd be glad if anyone could help:
$$ (X \cup Y)\setminus(Y \cap Z)=(X\setminus Y)\cup(Y \setminus Z)\\(X \cup Y)\setminus (Y\cup Z) = X \setminus (Y \cup Z)$$
I shall mention my approach was working cases, along the lines of "if x $\in X $, then...". Though I couldn't work these specific two arguments.
EDIT: I'm asking for the proof. I already validated the arguments using Venn diagrams. If someone can post a proof using algebra of sets I'd apprieciate it.
Comment: When you write $/$ do you mean $\setminus$?
Comment: I do, it ruined my latex code.
Comment: Use `\setminus` to produce $\setminus$.
Comment: I figured, wasn't aware of that tag. Sorry.
Comment: Have you drawn Venn diagrams for the four expressions so you can convince yourself that the identities hold?
Comment: @HenningMakholm I already did, but I just didn't manage to show it algebric-wise.
Answer: Notice, $A=B ⇔ ((\forall x \in A ⇒x\in B) \land (\forall x \in B⇒x\in A))$. Looking at the definition you can notice that the right hand side is nothing but two two directions of subset.
Therefore, suppose $A, B$ are two sets, then to show $A=B$ it suffices to show $(A \subseteq B) \land (B \subseteq A)$.
Now, In order to show $A\subseteq B$. Assume an arbitrary $x \in  A$, then show $x\in B$.
I will show one direction of subset for the first one, the other is quite similar I hope you will be able to do it.
Suppose $x\in ((X\cup Y)\setminus(Y\cap Z))$. Then, $(x\in X \lor x\in Y) \land (x\notin Y\land x\notin Z)$
As you can see, the above atomics follow from the definition of union, intersection, and difference.
Since $(x\in X \lor x\in Y) \land (x\notin Y\land x\notin Z)$, then $((x\in X\land x\notin Y)\lor (x\in Y\land x\notin Z))$. I got these by De Morgan distribution.
Finally, Translate the definitions into the respective symbol:$((x\in X\land x\notin Y)\lor (x\in Y\land x\notin Z))≡x\in ((X\setminus Y)\lor (Y\setminus Z))$
Which implies: $x\in ((X\setminus Y)\cup(Y\setminus Z))$.
Therefore, $((X\cup Y)\setminus (Y\cap Z))\subseteq ((X\setminus Y)\cup(Y\setminus Z))$

Here is another proof with additional explanations
Show that $(X\cup Y)\setminus (Y\cap Z)=(X\setminus Y)\cup(Y\setminus Z)$
Suppose: $$x\in (X\cup Y)\land x\notin (Y\cup Z)$$
Above supposition follows from the definition of difference.$$x\in(X\cup Y)\rightarrow (x\in X \lor x\in Y)\land x\notin (Y\cap Z)\rightarrow (x\notin Y \lor x\notin Z)$$$$Supp. x\in X \land x\notin Y\rightarrow x\in(X\setminus Y)(a)$$$$Supp.x\in X\land x\notin Z\rightarrow x\in(X\setminus Z)(b)$$$$Supp.x\in Y\land x\notin Y\rightarrow \bot$$$$Supp.x\in Y \land x\notin Z \rightarrow x\in (Y\setminus Z)(c)$$
Therefore, from a and c, $$x\in (X\setminus Y)\cup (Y\cap Z)\rightarrow (X\cup Y)\setminus (Y\cap Z)\subseteq(X\setminus Y)\cup(Y\setminus Z)$$
The other direction of subset is very similar to this one, hopefully you can do it.
Comment: I'm aware of how one shall prove the equality of two sets. But I didn't manange to show that $ L.H.S \in R.H.S $ or the vice versa.
Comment: @user-2147482321 I added one direction subset proof for one of it and the rest hopefully you can do yourself.
Comment: Correct me if I'm wrong but as far as I am concered, if $ x \notin ( Y \cap Z), it implies $ x \notin Y \cup x \notin Z. While you stated x not in both. So how you developed (Y and Z)' to Y' and Z' instead of or between them.
Comment: @ILoveMath Let's go back to the definition of an intersection: $A\cap B=\{x|x\in A \land x\in B\}$. I just implemented the definition of an intersection. As a general hint, always keep the set-builder definitions in mind. More than 80 percent of the time it will solve half of the problem.
Comment: @N.F.Taussig Thanks for the correction, it is fixed now.
Comment: First of all, thanks for the help. As for your answer, I know the definition of intersection but it seems odd to me what you did ther because:   $ x not in (X and Y), hence x doesn't belong to X, Y, or both. But you assumed he doesn't belong to both. It's bascially one of De Morgan's law what I'm saying. (X \cap Y)' = X' \cup Y'. Yet you developed it to X' cap Y'.
Comment: @ILoveMath You are welcome. Notice, I did not use De Morgan for the step you are referring to. I only used De Morgan in the very last part. Also, don't think of $x\notin (A \cap B)$ as $x \notin (A \land B)$. Intersection and Union are set-theoretic concepts, and they have set theoretic definitions. They are not necessarily boolean. Also, If you are concerned that the step I took was invalid when I translated $x \notin (A \cap B)$ to $(x \notin A) \land (x \notin B)$. Then rest assured, the step is nothing but the implication of the definition of $A\cap B$
Comment: Okay, to just to clarify. If I know x doesn't belong to the intersection of two sets I can deduce he doesn't belong to them both? (I know it sounds quite stupid but I insisted I should consider the cases where he doesn't belong to only one of them)
Comment: @ILoveMath Yes. However, if x does not belong to the union of two, then you work cases. I think you were confusing union with intersection.
Comment: Quite odd, logically it seems reasonable to me that if an element doesn't belong to the **union** of two sets, **then it shall not be in both sets**. (Since it requires the element to be in at least one of the sets, and if not - 0). Anyway, thanks for the patience dude.
Comment: @ILoveMath I see what you are saying now. That is, if x is not in the intersection it is not necessary that it is in neither. That is true, I should have stated that. However, regardless of that fact, the initial proof is rigorous it does not depend on it. I have added another proof which follows the pattern you are taught. Hopefully it makes sense.
Comment: Yess, that was my point. Thank you! It is clear to me now. Just out of curiosity, how it was valid in your first proof? Or rather, there are times I am allowed to deduce it's not in the intersection? I figure given extra information, though I didn't find anything relevant to that.
Comment: @ILoveMath Notice how we are given that x could be in either in X or Y, but it can not be in the intersection of Y and Z. From that, we can safely say x is not Z if x is in Y. Hence, $x\notin Z$. Also, Notice, if we have an atomic formula $\phi$ we can deduce $\rho \lor  \phi$. using the same logic if you have $x\in \gamma$ you can deduce $x\in (\gamma \cup \delta)$. Using this I got the other formula.
Comment: Thank you! You helped me to get a better grasp at this. Salute.
Comment: @ILoveMath You are welcome, best of luck.

Differences of sets


Como detectar se wi-fi e/ou bluetooth estão ligados

Question: Boa tarde!
Gostaria de saber se alguém conhece algum código fonte aberto para uma aplicação checar se o wi-fi ou Bluetooth estão ligados.
Comment: repetindo a pergunta, pois acho que não ficou claro...Boa tarde Gostaria de saber se alguém sabe se tem alguma aplicação com o código fonte aberto que checa se o wi-fi ou Bluetooth está ligado desnecessariamente.
Comment: Tomara que você não esteja pedindo que faça um app pra você (kkk)
Comment: Olá Klever. Eu até tinha votado pra fechar como fora de escopo, mas retirei o voto porque você já teve uma resposta útil. Ainda assim acho que seria bacana você editar a pergunta pra, ao invés de pedir código fonte aberto, solicitar como se faz o que você quer no Android. Sei que na prática dá no mesmo, mas potencialmente gera respostas melhores e assim a pergunta se torna mais útil para a toda a comunidade.
Comment: Mais uma vez, Boa tarde Gostaria de saber se alguém sabe se tem alguma aplicação com o código fonte aberto= Onde no texto diz que pedi o código fonte: "perguntei se alguém sabe de uma APLICAÇÃO que tenha o seu código fonte disponível. Abs
Answer: Com base no meu comentário e acreditando que você tem conhecimento sobre o que solicita, mostro-lhe esse código fonte aberto que analisa se o wi-fi está ligado.
private static final String DEBUG_TAG = "NetworkStatusExample";
ConnectivityManager connMgr = (ConnectivityManager)
        getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();
networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();
Log.d(DEBUG_TAG, "Wifi conectado: " + isWifiConn);
Log.d(DEBUG_TAG, "3G conectado: " + isMobileConn);

Fonte: http://developer.android.com/training/basics/network-ops/managing.html
Código fonte aberto para Bluetooth

Não há maneira de recuperar uma lista de dispositivos conectados na inicialização do aplicativo. A API Bluetooth não permite que você consulte, em vez disso, permite que você veja as mudanças.
Um trabalho hoaky seria para recuperar a lista de todos os dispositivos emparelhados conhecidos / ...então tentar ligar para cada um (para determinar se você está conectado).
Alternativamente, você pode ter um controle de fundo com a API Bluetooth e escrever os estados do dispositivo.
public void onCreate() {
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
       ... //Device found
    }
    else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
       ... //Device is now connected
    }
    else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
       ... //Done searching
    }
    else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
       ... //Device is about to disconnect
    }
    else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
       ... //Device has disconnected
    }
}
};

Não se esqueça da permissão:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Fonte: https://stackoverflow.com/questions/4715865/how-to-programmatically-tell-if-a-bluetooth-device-is-connected-android-2-2
Comment: Valeu...na verdade tenho uma aplicação, na qual checa alguns itens de segurança do sistema, mas queria do dispositivo, exemplo: "olha você seu  Bluetooth está ligado ou o wi-fi quer deixar ligado". Abs
Comment: Não se esqueça da permissão: ``


Problem with Microsoft.Web.UI.WebControls

Question: I'm troubleshooting some old code that uses the Microsoft.Web.UI.WebControls dll to create tree views and tabstrip controls on some pages. The tabstrip controls are not behaving correctly on our test site. Instead of hiding the portions of the page that are not on the selected tab they show everything. This error doesn't happen when I run the project locally on my computer. I assume there is some kind of configuration difference that I'm not aware of that causes the problem. Has anyone run into this before?
Answer: Yes, the web controls are not installed properly on the server.   I believe you will need to run the .msi or installation package to properly install them .   Make sure they're in the GAC while you're at it (or in the /bin directory), and all that other good stuff.
Comment: They are in the /bin directory of the website (ASP.NET) is that not good enough? They must be in the GAC?
Comment: No, the installer will install other files into some miscellaneous directories of the server I believe.
Comment: This blog posthttp://geekswithblogs.net/ranganh/archive/2006/02/21/70219.aspx
describes some steps for getting the web controls to work with asp.net 2.0 - it involves making some settings to the corresponding web.config, which I could imagine emulate steps otherwise performed by an installer.


How to use Loop using lowriter command on shell

Question: I'm tryingto execute lowriter command several times in a loop:
<code>#!/bin/sh

ROOT_DIRECTORY="docs"

function count_files()
{
    ls -lR $ROOT_DIRECTORY/*.doc | wc -l
}

function get_number_folders()
{
    expr $(count_files) / 100 + 1
}

function create_folders_and_fill_with_files()
{
    for num in $(seq 1 $(get_number_folders))
    do
        #mkdir $ROOT_DIRECTORY/$num
        mv `ls $ROOT_DIRECTORY/*.doc | head -100` $ROOT_DIRECTORY/$num/
        convert_to_pdf $ROOT_DIRECTORY $num
    done
}

function convert_to_pdf()
{
    lowriter -convert-to pdf --outdir ./docs/ $1/$2/*.doc --headless
    set -x
}

create_folders_and_fill_with_files

</code>
Everything "works" fine, but the command was executed only one time.
How can I execute the lowriter command all times that for need.
Thankyou
Answer: I have solved my question adding 2>&1 in the end of the convertion line;
<code>lowriter -convert-to pdf --outdir ./docs/ $1/$2/*.doc --headless 2>&1
</code>


Graphs with large automorphism groups

Question: While most graphs have trivial aut group (https://www.sciencedirect.com/science/article/pii/S0012365X08006900, https://users.renyi.hu/~p_erdos/1963-04.pdf, and also from sage simulations), I am interested in undirected graph families which have large aut groups (preferably exponential in the number of vertices).
Circulant graphs are one example of a graph family which have a non trivial aut group. (They contain the n-cycle), but I am not sure what conditions they need to satisfy for the aut group to be larger than n. (perhaps related to the spectrum of the graph)
I am wondering if there exist infinite families of graphs with large aut group, or methods to construct graphs of a given degree with large aut group. (rather than just isolated examples like the complete graph and the discrete graph)
Comment: https://en.m.wikipedia.org/wiki/Cayley_graph
Comment: For any fixed graph $H$, the disjoint union of $n$ copies of $H$ has $S_n$ as a subgroup of its automorphism group, and thus the family of such disjoint unions has the size of the automorphism group growing exponentially in the number of vertices. I think you might need to nail down some additional conditions to avoid examples like this, which I suspect are not what you intended.
Comment: The line graphs of complete graphs on $n$ vertices have the symmetric group on $n$ points as their automorphism group, and have only $\binom{n}2$ vertices.
Comment: The discrete graphs (no edges) and the complete graphs (all edges) both have the largest possible automorphism group for their size, the full symmetric group on the vertices. Do you want more conditions than what you've stated?
Comment: I meant apart from those two examples yes. Added that in the question
Comment: More generally, if $X$ and $Y$ are two graphs then one can construct various product graphs $X \times Y$ (e.g. https://en.wikipedia.org/wiki/Tensor_product_of_graphs, https://en.wikipedia.org/wiki/Cartesian_product_of_graphs) and these have automorphism group at least as large as the product of the automorphism groups of $X$ and of $Y$. So one can consider e.g. products of cyclic and complete graphs.
Comment: Instead of "methods to construct graphs of a given degree with large aut group" you mean methods to construct graphs of a given **order** with large aut group?
Answer: A good place to look might be families of graphs that are created to test graph isomorphism algorithms. For example, this paper (Benchmark Graphs for Practical Graph Isomorphism) describes the Cai-Fürer Immerman gadgets and Miyazaki graphs.
If you need actual examples of such graphs, it might be convenient to download them from the Nauty/Traces website here, although they may be in other databases of graphs elsewhere.

Graphs with large automorphism groups


How can I include .a libraries in Xcode?

Question: so I've been trying to include the Bullet physics library to my project and Cmake generated an Xcode project for me which built to static libraries or .a files. All the demos work perfectly from within that project, but I need to be able to use them in my project in C++ Xcode, I've already included the necessary headers, but how do I use the .a files in Xcode 4? Or what else should I do?
Comment: Acceptance of past answers should not be a criteria of how this site works - no matter how many points you wish to earn
Comment: @AdrianCornish I have looked into his questions and most of the answers are acceptable.
Comment: @MarkGarcia How so. The OP asked 6 questions 2 of which have been answered.
Comment: @AdrianCornish At the least he could accept on of those answers: http://stackoverflow.com/questions/12772076/what-is-the-operator-for-in-c
Comment: My mistake - 10 questions with 5 answered
Answer: You can just add the .a files to the project in the same way that you add source files or frameworks, i.e. drag them to the project window or use Files => Add Files to "foo"....


Random variable functions and dependence

Question: Say we have two independent random variables $X$ and $Y$.
Furthermore, say we have two functions $f(X,Y)$ and $g(X,Y)$.
Now, we know $f(X,Y)$ and $g(X,Y)$ will not necessarily be independent. So, in order to derive the distribution of
$$Z=f(X,Y) + g(X,Y)\quad\quad(1)$$
I need to know the joint distribution of $f(X,Y)$ and $g(X,Y)$.
My question is, due to the fact that $f(X,Y)$ and $g(X,Y)$ are made up of the same two independent random variables $X$ and $Y$, is it possible to arrive at $(1)$ without the need for a joint distribution?
Comment: Sometimes you may not need to derive the joint distribution of $f$ and $g$. For example, you may be able to use properties of $X,Y,f$ and $g$ to get around it. Or you may be able to write some transformation from $(X,Y)$ directly to $(f+g, w(X,Y))$ in such a way that $w$ is really easy to integrate out, leaving you with the marginal for $f+g$..
Comment: No, it is not. What does it mean to _derive_ $Z$? The _definition_ of $Z$ as the sum of $f(X,Y)$ and $g(X,Y)$ is something that _you_ made up, and it is up to _you_ to explain the reasons why $Z$ equals $f(X,Y)+g(X,Y)$ and not, say, $f(X,Y)+2g(X,Y)$.
Comment: $f(X,Y$ and $g(X,Y)$ are _random variables_. So what does it mean hen you say that you want to _calculate_ $f(X,Y)+g(X,Y)$? That is just a random variable. How do you _calculate_ it?
Comment: @DilipSarwate hopefully it's now fixed
Comment: @DilipSarwate derive the distribution of $Z$
Comment: Define $h(x,y) = f(x,y)+g(x,y)$. Forget about $g$, suppose you're interested in $h$, and let $f$ be *any* hideously complicated function. Your question becomes "is it possible to find the distribution of $h(X,Y)$ without knowing the joint distribution of $f(X,Y)$ and $g(X,Y)=h(X,Y)-f(X,Y)$? From this point of view it should be abundantly clear that $f$ and $g$ are potential distractions: compute the distribution of $h(X,Y)$ however you like. *If it so happens* that $f$ and $h-f$ are so simple that you can easily find their joint distribution and then compute their sum, then so much the better.
Answer: It would depend on the context of the problem. In general, for any $f$ and $g$, yes you would need to find the joint distribution of $f(X,Y)$ and $g(X,Y)$. In some (possibly trivial) cases, this might not be required.
For instance suppose $X, Y \sim N(0,1)$. If $f(X,Y) = X$ and $g(X,Y) = Y - X$, then $Z = Y \sim N(0,1)$. Obviously, the problem can become more complicated if $f$ and $g$ are.


Check Characteristic function

Question: How to check whether $\sin(t)\over t$ is a characteristic function or not?
If $\sin(t)\over t$ is a distribution function.
Comment: You could recognise which distribution that it's a characteristic function of.
Answer: It is not a distribution function because it takes negative values. It is the characteristic function of uniform distribution on $(-1,1)$. Unfortunately, there is no practical way of determining whether a given function is a  characteristic function.

Check Characteristic function


Fill nan in numpy array

Question: Is there a straight forward way of filling nan values in a numpy array when the left and right non nan values match?
For example, if I have an array that has False, False , NaN, NaN, False,  I want the NaN values to also be False.  If the left and right values do not match, I want it to keep the NaN
Comment: `False` is a boolean.  `nan` us a float.
Comment: Try to use numpy.isnan() function
Comment: If you check …. a = np.array([np.NaN, False, np.NaN, True]) … will yield …. array([nan,  0., nan,  1.]) …. which apparently you don't have.  What is your actual array?
Comment: What's the array's dtype and shape?  And in the result?
Answer: Your first task is to reliably identify the np.nan elements.  Because it's  a unique float value, testing isn't trivail.  np.isnan is the best numpy tool.
To mix boolean and float (np.nan) you have to use object dtype:
In [68]: arr = np.array([False, False, np.nan, np.nan, False],object)
In [69]: arr
Out[69]: array([False, False, nan, nan, False], dtype=object)

converting to float changes the False to 0 (and True to 1):
In [70]: arr.astype(float)
Out[70]: array([ 0.,  0., nan, nan,  0.])

np.isnan is a good test for nan, but it only works on floats:
In [71]: np.isnan(arr)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-71-25d2f1dae78d> in <module>
----> 1 np.isnan(arr)

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

In [72]: np.isnan(arr.astype(float))
Out[72]: array([False, False,  True,  True, False])

You could test the object array (or a list) with a helper function and a list comprehension:
In [73]: def foo(x):
    ...:     try:
    ...:         return np.isnan(x)
    ...:     except TypeError:
    ...:         return x
    ...:
In [74]: [foo(x) for x in arr]
Out[74]: [False, False, True, True, False]

Having reliably identified the nan values, you can then apply the before/after logic.  I'm not sure if it's easier with lists or array (your logic isn't entirely clear).
Answer: See also Most efficient way to forward-fill NaN values in numpy array
Pandas offers the interpolate method on data frames. You could use it like this:
interpolate(limit_direction='both').to_numpy().flatten()

A much more specialized method is given below, it allows controlling the B-Spline interpolation parameters, extrapolation and smoothing:
https://github.com/DomTomCat/signalProcessing/blob/main/interpolateNonFiniteValues.py

Fill nan in numpy array