Show that the third derivative of a unit space curve equals $-k^2 \mathbf{t} + k'\mathbf{n} + \mathcal{t}k\mathbf{b}$

Question: Show that the third derivative of a unit space curve equals $-k^2 \mathbf{t} + k'\mathbf{n} + \mathcal{T}k\mathbf{b}$ where $k$ is its curvature and $\mathcal{T}$ is its torsion.
I'm not clear on what the exercise means by $\mathbf{t}, \mathbf{n}, \mathbf{b}$. Does anyone have advice for this?
Answer: This uses fairly standard terminology for 3-dimensional vectors.
$\mathbf{r}$ is a differentiable vector function of time. In this problem it is a unit space curve, so you know that
$$|\mathbf{r}|=1 \quad\text{for all $t$}$$
$\mathbf{t}$ is the unit tangent vector to the curve, which can be defined by
$$\mathbf{t}=\frac{d\mathbf{r}/dt}{|d\mathbf{r}/dt|}$$
$\mathbf{n}$ is the principal unit normal to the curve, which can be defined by
$$\mathbf{n}=\frac{d\mathbf{t}/dt}{|d\mathbf{t}/dt|}$$
$\mathbf{b}$ is the binormal vector of the curve, which is a unit vector orthogonal to both $\mathbf{t}$ and $\mathbf{n}$, which can be defined by
$$\mathbf{b}=\mathbf{t} \times \mathbf{n}$$
There are other definitions, most of them using the arc length, curvature, and torsion functions of the curve. Ask if you need those definitions or more on your problem.
Comment: Oh, I have been seeing those definitions as capital letters. That is what I was confused though now I'm a bit stuck on the actual exercise haha.


Multiple cross validation consistently performing worse than chance

Question: I am calculating accuracy results from a single feature using LDA.  I am very curious why a certain feature consistently performs at less than chance when calculating accuracy using a stratified 10-fold cross validation technique.  I have an equally distributed binary class and performing multiple xvals results in an accuracy that fluctuates fairly tightly around 0.3.
This means the training data is consistently setting a boundary which when tested against is basically the opposite of what was trained on.
I am performing this stratified 10-fold xval 10-20 times and I would expect this to fluctuate around 0.5, but it is fairly static around the 0.3 to 0.4 area.
Thanks for the help!
Comment: What software are you using? Without knowing any specifics theres a good chance you have a bug in your code.
Comment: The other option is a hard overfit or simply inconclusive data.
Answer: So the problem appears to be a small number of samples and the fact that its a horrible feature.  The p-value is close to 1, so the classes are pretty much drawn from the same distribution.  Using synthetic data drawn from the same distribution with small N, I show there is a bias below 0.5 when performing multiple xvals that seems to asymptotically converge to 0.5 as N increases.


How to detect browser tab close event with react js?

Question: I am trying to detect browser tab / browser close event with react js to detect user log out action (call api). I have tried using beforeunload event as
  useEffect(() => {
    window.addEventListener("beforeunload", function(e) {

      let confirmationMessage = "o/";

      (e || window.event).returnValue = confirmationMessage; //Gecko + IE

      console.log("logout !");
      return confirmationMessage; //Webkit, Safari, Chrome

    });
  });

It works fine if user closes the tab but the issue is it is also firing when user reload the page which I dont want for log out action, I've tried searching and tried these solutions as well but no work for me. Are there any solutions to detect only when browser / browser tab closes and not reload ?
Detect browser close event
https://stackoverflow.com/a/5593734/11866037
Warn user before leaving web page with unsaved changes
Answer: you missed to add the return function in your useEffect which runs the cleanup i.e componentWillUnmount.
Your code will look something like this:
useEffect(() => {
    return () => {

       window.addEventListener("beforeunload", function(e) {

      let confirmationMessage = "o/";

      (e || window.event).returnValue = confirmationMessage; //Gecko + IE

      console.log("logout !");
      return confirmationMessage; //Webkit, Safari, Chrome

    });
   }

  });


Increase an Ubuntu Server CPU number on VmWare ESXi

Question: Can I increase the number of processors dedicated to my Ubuntu Server 10.04 virtual machine without creating problems to its functions?
It will be accepted without hassle or I should do something at reboot?
If I take a snapshot before that can I be sure to get back to my working 1 cpu configuration?
Thanks,
D.
Answer: Go ahead and add the extra CPUs, Ubuntu happily accepts them. Just reboot your Ubuntu server after adding the CPUs.
Please be aware that depending on your application the extra virtual CPUs might not actually help you a lot. Usually yes, but there are exceptions, so please test and benchmark your application extensively after CPU upgrade.
Comment: You'll get over that after enough time has passed, just wait until you earn the BOFH badge. If you don't ever break anything, you have not actually even tried to enhance something.
Comment: I run a mysql server on this machine that (only when everyone starts using an application in the morning for 30 minutes) hits 100% cpu use... Will it be useful to add a cpu?
Comment: Just give it a try. :)
Comment: You're right but my hands are always shaking when it comes to "touch" production software / hardware :)
Answer: One thing you have to watch out for is that ESXi will not schedule your VM until it can provide all the vCPUsthat you assigned to it. This may lead to your VM having to wait for vCPU resources to become available which man not be what you want.
Comment: I run a mysql server on this machine that (only when everyone starts using an application in the morning for 30 minutes) hits 100% cpu use... Will it be useful to add a cpu?
Comment: I think this has no longer been the case since ESX(i) 4.0.
Comment: From what I've heard it's better in later versions of ESX(i)4.0 or 4.1 but still exists to some degree.


Naming convention for sheet music?

Question: As far as I can tell there are two different types of sheet music/tablature (there are most likely a whole lot more variations, but for my purposes) where one type aims to let you play your instrument exactly as it is played in the original song.
This is the most common type I find when searching on the web.
Then there is the other type, which is sheet music where it aims to let you replace the vocals of a song with your instrument. This was common back when playing an instrument in school, but it's been extremely difficult to find these types of sheets for pop songs on the web. I'm thinking I need some way to specify what type of sheet I'm looking for, and that's why I'm asking if there are any naming conventions typically used to separate the two types.
If at all relevant, I'm specifically looking for sheets for guitar and piano.
Comment: Lead sheets? As in Real/Fake Books.
Comment: Since you could play any vocal line on your guitar, perhaps you're looking for a combination of the vocal line and the chord structure underpinning it?
Answer: I'm not sure if I have the particular term you're looking for, but two terms are definitely related:
One is what we call the instrumentation of a particular score. By instrumentation, we literally mean "what instruments are used in the score." So if you're looking for scores for just guitar and piano, you're looking only for that specific instrumentation.
Another related term is arrangement. When someone arranges a piece of music, they write the music in a slightly different way, often using a different instrumentation from the original. (Just how an arrangement is different, and how different it is, varies from arrangement to arrangement.) So when a high school band plays a piece, they often play an arrangement of something not written for high school band that has been adapted to be played by those instruments. As such, you may be looking specifically for "guitar and piano arrangements" of particular songs.
Answer: You are looking for an instrumental arrangement, or more specifically a solo piano arrangement.  E.g. solo piano for "My Heart Will Go On"
If you're looking for a guitar piano combo, that would be: _song_ arranged for guitar and piano.

Naming convention for sheet music?


TcxGrid com sub nível, mostrar coluna para expandir níveis na última posição

Question: Ola! Sou iniciante com CxGrid, preciso fazer uma grid com sub nível, porém queria que a coluna que permite expandir os níveis (+) ficasse na última posição das colunas da grid. Não sei se é possível, efetuar tal modificação.
atualmente é mostrado da seguinte maneira:

precisaria efetuar algo semelhante ao seguinte:
Answer: Para manter um registro caso venha a ser útil, segundo o suporte DevExpress a versão atual não suporta esta funcionalidade.
segue resposta deles.


Ramsey number for paths

Question: Let $n = R(P_{r+1}, c)$ be the smallest integer such that if $K_n$ is $c$-edge-coloured, then it contains a monochromatic subgraph isomorphic to $P_{r+1}$, the path of length $r$. I need to show that $R(P_{r+1}, c) \leq r^c + 1$.
I believe that the best known bound is linear in terms of $r$, so this is really rough, but I still can't get anywhere. I have tried modifying the usual proof of Ramsey's theorem, showing that $R(s, t) \leq R(s - 1, t) + R(s, t - 1)$ (Erdos-Szekeres), but to no avail. I have also tried proving the bound:
$$R(P_{r+1}, c) - 1\leq r(R(P_{r+1}, c - 1) - 1)$$
by partitioning a complete graph into a product of $r$ complete subgraphs. I do know know if this bounds holds, but if it did, I would get the desired answer.
Please help with hints, not complete solutions. Thank you.
Answer: We proceed by induction on $c$.
When $c = 1$, $R(P_{r + 1}, 1) \leq r + 1$, since $K_{r + 1}$ contains all possible edges between $r + 1$ vertices, and a path of length $r$ is one such choice.
Let $n = R(P_{r+1}, c)$, $G = K_n$. Let $G$ be $(c - 1)$-edge-coloured, and extend this to a $c$-edge-colouring of $H = K_{n + \lfloor r/2 \rfloor}$, where the new complete subgraph $K_{\lfloor r/2 \rfloor}$ is $1$-edge-coloured for a previous colour used in $G$, and all of the edges linking $G$ to this subgraph are $1$-edge-coloured in a new colour. This is a graph with no monochromatic path of length $r$, so:
$$R(P_{r+1}, c) \leq R(P_{r}, c - 1) + \lfloor r/2 \rfloor$$
So, by the induction hypothesis:
$$R(P_{r+1}, c) \leq r^{c-1} + 1 + \lfloor r/2 \rfloor \leq r^c + 1$$
And this last inequality is true since:
\begin{align*}
&r^{c-1} + 1 + \lfloor r/2 \rfloor \leq r^c + 1 \\
\iff &\lfloor r/2 \rfloor \leq r^{c-1}(r - 1)
\end{align*}
If $r$ is even, then $r \geq 2$ and:
$$\frac{1}{2} \leq r^{c - 2}(r - 1)$$
This last inequality might not hold if $c = 1$, but in that case:
$$\frac{1}{2} \leq 1 - \frac{1}{r}$$
and since $r \geq 2$, this is true.
If $r$ is odd, then $r \geq 1$ and:
$$\frac{r - 1}{2} \leq r^{c - 1}(r - 1) \iff \frac{1}{2} \leq r^{c - 1}$$
Q.E.D.
Comment: Isn't this the opposite inequality?
Answer: You must prove the following claim:

Claim. Let $r$ and $c$ be two nonnegative integers. Let $n$ be an integer such that $n > r^c$. Assume that the edges of the complete graph $K_n$ have been colored with $c$ colors. Then, $K_n$ has a monochromatic path of length $r$. (A path is called monochromatic if all its edges have the same color.)

Proof. Let $1, 2, \ldots, n$ be the vertices of $K_n$. Let $V$ be the set of all these $n$ vertices. A walk $\left(v_1,v_2,\ldots,v_s\right)$ of $K_n$ will be called increasing if $v_1 < v_2 < \cdots < v_s$. Note that any increasing walk is a path.
Let $1, 2, \ldots, c$ be the $c$ colors. For each vertex $i \in V$ and each color $k \in \left\{1,2,\ldots,c\right\}$, let $f_{i,k}$ denote the maximum length of an increasing path starting at $i$ such that all edges of this path have color $k$. (This is well-defined, since the length-$0$ path $\left(i\right)$ always exists, and since a path in $K_n$ cannot have length $\geq n$.)
Now, let us assume (for contradiction) that $K_n$ has no monochromatic path of length $r$. Then, in particular, $K_n$ has no monochromatic increasing path of length $r$. Hence, any monochromatic increasing path has length $\leq r-1$. Therefore, $f_{i,k} \in \left\{0,1,\ldots,r-1\right\}$ for all $i$ and $k$. Now, for each $i \in V$, let $f_i$ be the $c$-tuple $\left(f_{i,1},f_{i,2},\ldots,f_{i,c}\right)$. This $c$-tuple belongs to the $r^c$-element set $\left\{0,1,\ldots,r-1\right\}^c$ (since $f_{i,k} \in \left\{0,1,\ldots,r-1\right\}$ for all $i$ and $k$). By the pigeonhole principle, we thus conclude that two of these $c$-tuples $f_1, f_2, \ldots, f_n$ are equal (since $n > r^c$). That is, there exist two vertices $v$ and $w$ such that $v < w$ and $f_v = f_w$. Consider these vertices $v$ and $w$. Now, let $k$ be the color of the edge $vw$, and observe that $f_v = f_w$ entails $f_{v,k} = f_{w,k}$.
Now, take a longest increasing path starting at $w$ whose edges all have color $k$. This path has length $f_{w,k}$ (by the definition of $f_{w,k}$). Let us now extend this path by inserting the vertex $v$ (and the edge $vw$) at its front. The result is a walk of length $f_{w,k}+1$ that starts at $v$ and has the property that all its edges have color $k$ (since the edge $vw$ has color $k$). This walk furthermore is increasing (since $v < w$), and thus is a path. Hence, we have found an increasing path of length $f_{w,k}+1$ that starts at $v$ and has the property that all its edges have color $k$. Therefore, $f_{v,k} \geq f_{w,k}+1 > f_{w,k}$, which contradicts $f_{v,k} = f_{w,k}$. This shows that our assumption was false, and thus the claim is proved.
Remark. This can be generalized: If $D$ is a tournament with more than $r^c$ vertices, and if the arcs of $D$ are colored with $c$ colors, then $D$ has a monochromatic path of length $r$. This is a particular case of Theorem 2 in Yannis Manoussakis, Zsolt Tuza, Ramsey numbers for tournaments, Theoretical Computer Science 263, Issues 1--2, 28 July 2001, Pages 75--85. The proof in the general case is more complicated. Note that this general result also generalizes Redei's little theorem, which says that every tournament has a Hamiltonian path. (Just take $c = 1$ to recover this.)

Ramsey number for paths


create workgroup and join the same workgroup from Linux

Question: Is it possible to create "workgroup" in  a linux machine and join the same linux machine into that workgroup?
my understanding:
smb.conf in /etc/samba/ have an entry name workgroup which can be filled with Actual work group name , say XYZ. This is for connecting with the existing workgroup XYZ?
But, I wish to create a new workgroup and same created machine(linux) to join the workgroup.?
Then I should be able to add any computer to this workgroup?
Please let me know the configuration details for the same.
Thanks!
Comment: @Massimo,@Zoredache: Thanks!. One doubt: What should be the security value? 1. can it be domain? Or it should be any other specific value?
Answer: There is not special commands to be part of a work group.  Simply adjust the workgroup setting to the name you want.
<code>#smb.conf
[global]
   workgroup = example
</code>
A workgroup by definition allows anyone to be a member.  Basically a work group is just a name that each computer will announce in addition to their computer name.  See the netbios name service.
Comment: Thanks!. One qn: What should be the security value? 1. can it be domain? Or it should be any other specific value.
Answer: You don't "create" or "join" a workgroup, even when using Windows; a workgroup exists whenever there is at least one computer on the network which says "I am in workgroup X", and ceases to exist when there are no more of them.
If you set your computer's workgroup to some name, this is all that is needed for that workgroup to come to life.


php javascript alertbox have to click 2 times before it show

Question: I'm doing php that is textbox a value empty it will open a alertbox (I'm using javascript in here )
this is my code
    <?php
    include('config.php');

        if(isset($_POST['submit'])){
        $username=$_POST['username'];

    ?>

    <?php
    }
    ?>

Member Profile

    <form action="testing.php" method="POST" onsubmit="return validate();">
    Username

    <input class="user" type="text" name="username" id="username" />

<input type="submit" name="submit" value="register" />
</form>

The problem is i have to click 2 times before the alert show
please help me to solve this problem
Answer: It's because the script is inside the php if(isset){} block, one click submits the form, which generates the script and then it works the second time.. try this setup instead:
<?php
    include ('config.php');

    if (isset($_POST['submit']))
    {
        $username = $_POST['username'];
    }
?>

                Member Profile

            <form action="testing.php" method="POST" onsubmit="return validate();">
                Username

                <input class="user" type="text" name="username" id="username" />

                <input type="submit" name="submit" value="register" />
            </form>

Edit:
I've moved the script tag inside the head tag. I'm not sure if there are any implications for having the script outside but just to be sure I've moved it.
2nd Edit: (OCD is kicking in)
I've added body tags, not sure if you copied and pasted this code but it looked weird to me :)


hadoop failed to build from source

Question: I am trying to build hadoop-2.0.4-alpha from source..in ubuntu 13.04
I have maven 3.0.5, protobuf(libprotoc 2.4.1), cmake(18.104.22.168)
i get this
<code> occured: stylesheet /home/hadoop/hadoop-2.0.4-alpha-src/hadoop-common-project/hadoop-common/${env.FINDBUGS_HOME}/src/xsl/default.xsl doesn't exist. -> [Help 1]

org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.6:run (site) on project hadoop-common: An Ant BuildException has occured: stylesheet /home/hadoop/hadoop-2.0.4-alpha-src/hadoop-common-project/hadoop-common/${env.FINDBUGS_HOME}/src/xsl/default.xsl doesn't exist.
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: An Ant BuildException has occured: stylesheet /home/hadoop/hadoop-2.0.4-alpha-src/hadoop-common-project/hadoop-common/${env.FINDBUGS_HOME}/src/xsl/default.xsl doesn't exist.
    at org.apache.maven.plugin.antrun.AntRunMojo.execute(AntRunMojo.java:283)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: /home/hadoop/hadoop-2.0.4-alpha-src/hadoop-common-project/hadoop-common/target/antrun/build-main.xml:44: stylesheet /home/hadoop/hadoop-2.0.4-alpha-src/hadoop-common-project/hadoop-common/${env.FINDBUGS_HOME}/src/xsl/default.xsl doesn't exist.
    at org.apache.tools.ant.taskdefs.XSLTProcess.handleError(XSLTProcess.java:1229)
    at org.apache.tools.ant.taskdefs.XSLTProcess.execute(XSLTProcess.java:380)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
    at sun.reflect.GeneratedMethodAccessor54.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:390)
    at org.apache.tools.ant.Target.performTasks(Target.java:411)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1397)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1366)
    at org.apache.maven.plugin.antrun.AntRunMojo.execute(AntRunMojo.java:270)
    ... 21 more
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :hadoop-common
</code>
Comment: I got the same error on hadoop-2.0.5-alpha from source in ubuntu 12.04. Did you solve the issue?
Answer: I think your environment is missing FINDBUGS_HOME. You can download and install findbugs from here.
After that, you should run following to define FINDBUGS_HOME:
<code>export FINDBUGS_HOME=/path/to/findbugs/installation
</code>
Now, your build should not fail due to missing FINDBUGS_HOME environment variable.
Answer: I have solved by following commands:
<code> mvn clean
 mvn compile -Pnative
 mvn package
 mvn compile findbugs:findbugs
 mvn install
 mvn package -Pdist,docs,src,native -Dtar
</code>
Comment: You should see the problem is pah for FINDBUGS_HOME was not set after setting that it would work fine as per hadoop installation steps
Answer: I fixed this issue using these steps.
1) open the pom.xml file inside the hadoop-xxxxx-src/hadoop-project directory and search for the "findbugs.version" xml tag
2) download and install the required findbugs version you found in Step 1)
3) create the "FINDBUGS_HOME" environment variable as suggested by others.
Answer: For an updated answer, my colleague published an article on how to compile, patch and run hadoop with the latest source code: https://www.adaltas.com/en/2020/08/04/installing-hadoop-from-source/. It makes use of Docker for reproducible builds.

hadoop failed to build from source


SAP pdf exporting

Question: I have the code below that I was using to export PDF from SAP. It was working on previous SAP version, but now it gets "runtime error 438, object doesn't support this property or method" on Browserhandle.locationURL.
Could you please give me a hint what should I change?
<code>Call SAPopen(SystemName, SystemID, TransID)
session.findById("wnd[0]").maximize

For i = 6 To lastInv

    invRef = Cells(i, 2)
    invName = Cells(i, 3)
    fileName = fPath & invName & ".pdf"
    If FileExists(fileName) = True Then fileName = fPath & invName & "i" & ".pdf"

    session.findById("wnd[0]/usr/ctxtVBRK-VBELN").Text = invRef
    session.findById("wnd[0]/mbar/menu[0]/menu[11]").Select

    If session.ActiveWindow.Name = "wnd[0]" Then
        Message = "No output exists"
        GoTo WriteMsg
    End If

    session.findById("wnd[1]/usr/tblSAPLVMSGTABCONTROL").getAbsoluteRow(0).Selected = True
    session.findById("wnd[1]/tbar[0]/btn[37]").press

    If session.ActiveWindow.Name = "wnd[1]" Then
        Message = "No output could be opened"
        GoTo WriteMsg
    End If

    session.findById("wnd[0]/tbar[0]/okcd").Text = "pdf!"
    session.findById("wnd[0]").sendVKey 0

    pdfLocL = session.findById("wnd[1]/usr/cntlHTML/shellcont/shell").Browserhandle.locationURL
    pdfLocStart = InStr(pdfLocL, "C:")
    pdfLocS = Mid(pdfLocL, pdfLocStart, 9999)

    Set FSO = CreateObject("Scripting.FileSystemObject")
    FSO.copyfile pdfLocS, fileName

    If FileExists(fileName) = True Then Message = "Invoice saved" Else Message = "Invoice not saved"

    session.findById("wnd[1]").Close
    session.findById("wnd[0]/tbar[0]/btn[3]").press
    session.findById("wnd[1]").Close
    Set FSO = Nothing
</code>
Comment: Hi Sandra, yes 7.70 and changing it back to MS IE solved the issue. Thank you! :)
Comment: So, you are talking about exporting a PDF from the `GuiHtmlViewer` object. Since SAP GUI 7.70, you have the possibility between the old MS IE and the newest Edge engines. Which SAP GUI version are you using, and if it's SAP GUI 7.70 which engine is configured?
Comment: Could you please write an answer so I can close the question? I don't want to delete, someone else may find it helpful and I can mark my own answer as solution in only 2 days.
Comment: I didn't know, I was just mentioning a few facts. Great that it solved, and I voted for your answer. You can also mark it as accepted.
Answer: Solved by changing browser control back to Internet Explorer.

SAP pdf exporting


Need help in translating English to Predicate logic

Question: I'm trying to translate English into Predicate Logic but I am not sure if I did it correctly. So I want to check it before I attempt to prove it.
Question 1

The sentence is : Everyone who loves Bella also loves either Claire or Daisy, and none of them speak French,
but at least one person who loves Daisy speaks German.
L(x, y) = x loves y,
b = Bell, c = Claire, d = Daisy
F(x) = speaks French
G(x) = speaks German

My first translation is
$$\forall x[L(x,b) \to (L(x,c) \lor L(x,d)] \land \neg\exists x[F(x)] \lor \exists x[L(x,d) \land G(x)]$$
For this one, I am unsure whether to put ¬∃x[F(x)] inside or outside the universal quantifier. Would it make a different if I put it out?
My second translation attempt :
$$\forall x\neg\exists y[ [(L(x,b) \to (L(x,c) \lor L(x,c)) \land \neg F(y) \land \neg(x = y)] ] \land \exists x[L(x,d) \land G(x)]$$
Which of these are correct? (If any)
Question 2

Sentence is : if everyone either speaks French or loves Daisy, and Bella speaks neither French nor German,
then somebody must love Daisy.

In this one I translate it as :
$$\forall x[F(x) \lor L(x,d)] \land \neg(F(b) \land G(b)) \to \exists x[L(x,d)]$$
Is the correct? and should I add rule like ¬(x = d) saying that daisy cannot love herself? is it necessary?
Answer: For 1:  this is a bit ambiguous, but it seems the 'them' in 'none of them' is referring to the people who love Bella, and so you do need to put $\neg F(x)$ inside the scope of the first quantifier. Also, the $\lor$ you have near the end should be an $\land$
For 2: Bella speaking neither French nor German translates as $\neg (F(b) \lor G(b))$
Answer: I would interpret "either ... or" as exclusive or which means you have to exclude the case that they love all three of them.
Further not speaking french is an attribute of the people who love daisy, while your first try reintroduces x with a new quantifier (which means it is a different variable). So you are saying $\neg\exists x: F(x)$ which is equivalent to $\forall x:\neg F(x)$ which means no person speaks French at all, compared to people who love daisy don't speak French.
Oh and I think the "but" would be a logical and. So there is someone who loves daisy and speaks german, AND the other stuff. Not or the other stuff.
My attempt (Spoiler):

 $$\forall x [L(x,b)\rightarrow \left((L(x,c)\vee L(x,d))\wedge\neg(L(x,c)\wedge L(x,d)\right) \wedge \neg F(x)]\wedge \exists y[L(y,d)\wedge G(y)]$$

The second one looks good besides the either or again. Why can daisy not love herself? That is not in the statement.


How to access Active Directory using C++Builder?

Question: I need to get a list of user names from Active Directory using C++Builder. I know I could shell out to batch file and run the csvde.exe command but surely there is a nicer way using a library or something, right?  Are there any C++ libraries? (hopefully with examples?)
Many thanks!
-Dan
Answer: Why not just use the SDK API for AD? Active Directory Service Interfaces Reference. There are examples for most common operations at Using Active Directory Service Interfaces


How does Cassandra partitioning work when replication factor == cluster size?

Question: Background:
I'm new to Cassandra and still trying to wrap my mind around the internal workings.
I'm thinking of using Cassandra in an application that will only ever have a limited number of nodes (less than 10, most commonly 3).  Ideally each node in my cluster would have a complete copy of all of the application data.  So, I'm considering setting replication factor to cluster size.  When additional nodes are added, I would alter the keyspace to increment the replication factor setting (nodetool repair to ensure that it gets the necessary data).
I would be using the NetworkTopologyStrategy for replication to take advantage of knowledge about datacenters.
In this situation, how does partitioning actually work?  I've read about a combination of nodes and partition keys forming a ring in Cassandra.  If all of my nodes are "responsible" for each piece of data regardless of the hash value calculated by the partitioner, do I just have a ring of one partition key?
Are there tremendous downfalls to this type of Cassandra deployment?  I'm guessing there would be lots of asynchronous replication going on in the background as data was propagated to every node, but this is one of the design goals so I'm okay with it.
The consistency level on reads would probably generally be "one" or "local_one".
The consistency level on writes would generally be "two".
Actual questions to answer:

Is replication factor == cluster size a common (or even a reasonable) deployment strategy aside from the obvious case of a cluster of one?
Do I actually have a ring of one partition where all possible values generated by the partitioner go to the one partition?
Is each node considered "responsible" for every row of data?
If I were to use a write consistency of "one" does Cassandra always write the data to the node contacted by the client?
Are there other downfalls to this strategy that I don't know about?
Answer:
Do I actually have a ring of one partition where all possible values
generated by the partitioner go to the one partition?
Is each node considered "responsible" for every row of data?
If all of my nodes are "responsible" for each piece of data regardless
of the hash value calculated by the partitioner, do I just have a ring
of one partition key?

Not exactly, C* nodes still have token ranges and c* still assigns a primary replica to the "responsible" node. But all nodes will also have a replica with RF = N (where N is number of nodes). So in essence the implication is the same as what you described.

Are there tremendous downfalls to this type of Cassandra deployment?
Are there other downfalls to this strategy that I don't know about?

Not that I can think of, I guess you might be more susceptible than average to inconsistent data so use C*'s anti-entropy mechanisms to counter this (repair, read repair, hinted handoff).
Consistency level quorum or all would start to get expensive but I see you don't intend to use them.

Is replication factor == cluster size a common (or even a reasonable)
deployment strategy aside from the obvious case of a cluster of one?

It's not common, I guess you are looking for super high availability and all your data fits on one box. I don't think I've ever seen a c* deployment with RF > 5. Far and wide RF = 3.

If I were to use a write consistency of "one" does Cassandra always
write the data to the node contacted by the client?

This depends on your load balancing policies at the driver. Often we select token aware policies (assuming you're using one of the Datastax drivers), in which case requests are routed to the primary replica automatically. You could use round robin in your case and have the same effect.
Answer: The primary downfall will be increased write costs at the coordinator level as you add nodes. The maximum number of replicas written to I've seen is around 8 (5 for other data centers and 3 for local replicas).
In practice this will mean a reduced stability while performing large or batched writes (greater than 1mb) or a lower per node write TPS.
The primary advantage is you can do a lot of things that'd normally be awful and impossible to do. Want to use secondary indexes? probably will work reasonably well (assuming cardinality and partition size doesn't become your bottleneck there). Want to add a custom UDF that does GroupBy or use very large IN queries it'll probably work.
It is as @Phact mentions not a common usage pattern and I primarily saw it used with DSE Search on low write throughput use cases that had requirements for 'single node' features from Solr, but for those same use cases with pure Cassandra you'd get some benefits on the read side and be able to do expensive queries that are normally impossible in a more distributed cluster.


Calculating expected total populations based on evolutionary advantage

Question: How to set up a spreadsheet to run scenarios based on the following:
If people A have genetics that give an $a\%$ advantage over other people $B$ of surviving to age $m$, mating age, and the average person has $p$ progeny, and the average age of death is $d$, after $g$ generations how what percentage of the population will have people $A$'s genetics?
The idea being, let's say a certain mutation gives a person a $5\%$ better chance of surviving to mating age. If the average mating age is $15$, couples have an average of $4$ children, and everyone dies at age $50$, after $1000$ generations how much better will people with that mutation do as based on their percentage of total population.
Comment: Are people A and people B strictly endogamous?
Comment: Actually if possible, it would be great to be able to run it both with and without intermarriage.
Comment: With is an *enormously* more complex case, even assuming purely Mendelian genetics.
Comment: Of course.  I guess then endogamous is the way to go, at least for starters.  Thanks for your help!
Answer: Real populations are, unfortunately, discrete, but let's slice some people in halves to make things easier. Let's just pretend those are some nuisance factors - (un-)lucky breaks, basically.
We're dealing with pairs of people multiplying, which suggests two things to me: one is that to maintain our, and our hardware's sanity, we'd better log-scale it, and that since it's pairs - let's use base-2 for that.
Now, we can model each generation separately. Let's just pretend out of the population $P$, each survivor $S$ of the attrition rate $A$ forms a single pair with the opposite-sex partner - they are conveniently always 1:1 - and together, they produce their statistical number of kids $K$.
Bearing in mind those are all $log_2$, this can be expressed as:
$$P_{n+1} = ((1-A)*P_n) + K - 1$$
The $(-1)$ corresponds to dividing by 2 to get pairs.
This is nice classically Markovian AR(1) process if the attrition rate is deterministic, so it's almost trivial to set up in Excel.
A nice feature of logs is that if you're just interested in ratios, you don't even need to exponentiate. You can just grab some groups logarithmic population and divide by the sum of the rest to get them.
This is just the baseline though. Uncertain attrition can be handled with a Beta distribution. You could get more accurate simulations at low populations by not using logarithms and doing floor division for pairs, but it quickly explodes in size at larger ones.
Pooling the generations' populations is doable if you pretend the reproduction and death ages are fixed, it's just incredibly tedious - you'd need to calculate them separately, then histogram the overlapping periods, and in the long run it's approximated by the raw generations anyway.
Comment: Oh, and just as an extra curiosity - the deterministic models tend to converge to a stable distribution.
Comment: This is fantastic!  Thanks so much - I'll start implementing it and see how it goes, and get back to you if any questions?
Comment: Interesting observation about the stable distribution.
Comment: I've struggled with putting together the spreadsheet.  Any chance you'd mind whipping one up and sending it to me?
Comment: I don't really have a direct way of sharing, so have a link: http://s000.tinyupload.com/index.php?file_id=52782445886042753078 (obviously, this may link-rot). This was thrown together for my own benefit, so it's not the prettiest worksheet ever.
Comment: Looks great - thanks so much!! :)


Theta Method for system of ODEs

Question: So here is a question about a little Matlab code writing because I've never seen "theta method"...

Consider the $θ$-method
  $$y_{n+1} = y_n + θhf_n + (1 − θ)hf_{n+1}$$
  where $0 ≤ θ ≤ 1$ and $f_n = f(t_n, y_n)$. Write a MATLAB code to implement
  the theta method for systems of ODEs. For $θ = 0$, $0.5$, $1$, use your code for solving
  \begin{aligned}
y_1' &= −y_1 \\
y_2' &= −100 \left(y_2 − \sin(t)\right) + \cos(t)
\end{aligned}
  for $0 ≤ t ≤ 1$, with initial value $y_1 = 1$, $y_2 = 2$. Try this for
  stepsizes $h = .01$ and $h = .05$.

Now I know how to do the Euler Code....
<code>h = 0.05; %step size
y1 = 1; %IC Conditions Y1
x1 = 2; %IC Condition Y2
t0 = 0; %Initial time
t1 = 1; %Final time

nsteps = (t1-t0)/h; %number of steps

y(1) = y1; %Array for euler method Y1, -I.C Y1
x(1) = x1; %Array for euler method Y2  -I.C Y2
t(1) = t0 ; %array for euler method t

%% For loop and implementation of Euler Method

for n = 1:nsteps
   t(n+1) = t(n)+h; %time stepping euler method, increment time
   yprime(n+1) = -y(n); %Right hand side of diff eqy y1' = -y1
   xprime(n+1) = -100*(x(n)-sin(t(n)))+cos(t(n)); %RHS of y2'= -100*(y2-sin(t))+cos(t)
   y(n+1) = y(n)+yprime(n+1)*h;
   x(n+1) = x(n)+xprime(n+1)*h;
end
</code>
Would I just be changing the last part of the code where I have this?
<code>   y(n+1) = y(n)+yprime(n+1)*h;
   x(n+1) = x(n)+xprime(n+1)*h;
</code>
Essentially I would think I change that part above into the theta method of,
$y_{n+1} = y_n + θhf_n + (1 − θ)hf_{n+1}$
If anyone is familiar with this method, please let me know how you would write this code, any feedback is helpful.
Thank you
Comment: I'm not familiar with it but it appears to be an implicit method, since you require $f_{n+1}$ to calculate $y_{n+1}$. But your notation is confusing me a bit. In your euler method code, $y_n$ seems to mean the $n$th approximate value for $y$, while in your mathjax it appears to be your $n$th dimension.
Comment: I don't have enough reputation to comment the good answer of EditPiAf, but I have the impression that there is a mistake in the $\theta$-scheme formula. Indeed, according to Barclay, G., Griffiths, D., & Higham, D. (2000). Theta Method Dynamics. LMS Journal of Computation and Mathematics, 3, 27-43. doi:10.1112/S146115700000019X (for example), the general form of a $\theta$-scheme for this problem is: $$
Y_{n+1} = Y_{n} + h\left(\left(1-\theta\right) F(t_n,Y_n) + \theta\, F(t_{n+1},Y_{n+1}) \right),
$$ which is equivalent to: $$
Y_{n+1} = Y_{n} + h\left(\theta\, F(t_n,Y_n) + \left(1-\theta\righ
Answer: Let us introduce the vector of unknowns $Y = (y_1,y_2)^\top$ which satisfies the ODE system $Y'(t) = F(t,Y)$. At each step, one needs to solve
$$
Y_{n+1} = Y_{n} + h\left(\theta\, F(t_n,Y_n) + \left(1-\theta\right) F(t_{n+1},Y_{n+1}) \right) ,
$$
where $t_n = nh$ and $Y_n \simeq Y(t_n)$. In general, this is a nonlinear equation for $Y_{n+1}$, which is rewritten $G(Y_{n+1}) = 0$, where
$$
G : Y \mapsto Y - h\left( \left(1-\theta\right) F(nh+h,Y) + \theta\, F(nh,Y_n) \right)  - Y_{n} \, .
$$
It is solved at each step using Newton's method
$$
Y_{n+1}^{k+1} = Y_{n+1}^{k} - \left( G'(Y_{n+1}^{k})\right)^{-1}\, G(Y_{n+1}^{k}) \, ,
$$
where
$$
G' : Y \mapsto I - \left(1-\theta\right) h\, \partial_Y F(nh+h,Y)
$$
is the Jacobian matrix of $G$, and $\partial_Y F(nh+h,\cdot)$ is the Jacobian matrix of $F(nh+h,\cdot)$. The initial guess is $Y_{n+1}^{0} = Y_n$, and the final value is $Y_{n+1}^\infty = Y_{n+1}$.
The code below performs the proposed integration:
<code>% numerical parameters
theta = 0.5;
h = 0.01;
T = 1;

% functions describing ODE system
dim = 2;
F = @(t,Y) [-Y(1); -100*(Y(2)-sin(t))+cos(t)];
Fp = @(t,Y) [-1, 0; 0, -100];

% functions for Euler method
G = @(Y,Yn,n) Y - h*( (1-theta)*F(n*h+h,Y) + theta*F(n*h,Yn) ) - Yn;
Gp = @(Y,n) eye(dim) - h*(1-theta)*Fp(n*h+h,Y);

% initialization
N = floor(T/h);
Y = zeros(2,N);
Y(:,1) = [1; 2];
k = zeros(1,N-1);

for n=1:N-1
    Yn = Y(:,n);
    Yk = Yn;
    err = 1;
    while (err>1e-14)&&(k(n)<20)
        Ykp1 = Yk - Gp(Yk,n)\G(Yk,Yn,n);
        err = norm(Ykp1-Yk);
        Yk = Ykp1;
        k(n) = k(n)+1;
    end
    Y(:,n+1) = Ykp1;
end

plot(Y(1,:),Y(2,:),'bo');

% analytical solution
hold on
t = (0:N)*h;
plot(exp(-t),2*exp(-100*t)+sin(t),'k');
</code>
A comparison of the numerical solution (blue) with the analytical solution (red) in the phase space $y_1$-$y_2$ is given in the graphics output

Theta Method for system of ODEs


Chaves estrangeiras na modelagem do banco de dados

Question: Uma chave primária pode ter duas chaves estrangeiras em tabelas diferentes? Por exemplo:
Answer: A chave primária da tabela Lucros pode ser chave estrangeira/externa de outras tabelas, neste caso tens:
Faturamento
 PK->codFaturamento
 FK->codLucro

Lucros
PK->codLucro

Despesas
PK->codDespesa

FK->codLucro

Nestes casos, um relacionamento de 1:N
Comment: Então esta correto ?
Comment: Sim está correcto!


Howto deserialize class, if class version was changed

Question: I want to write the code, that can deserialize the class even if the class was changed (but you have old class version).
The idea is simple.

Read the serialVersionUID of the serialized class
Check if that serialVersionUID is equal to the serialVersionUID of the current class version.
If not, create new ClassLoader and load the old class version into workspace.

I thought to use something like this:
FileInputStream file = new FileInputStream(filename);
ObjectInputStream o = new ObjectInputStream(file) {
    protected Class<?> resolveClass(java.io.ObjectStreamClass desc) throws IOException, ClassNotFoundException {
        //5639490496474438904L is the suid of the older version
        if (desc.getSerialVersionUID() == 5639490496474438904L) {
            Class c01 = null;
            URL eineURL = new URL("file://localhost/U:/MyJavaProj/bin/test/oldversion/");
            URL[] reiURL = new URL[] {eineURL};
            URLClassLoader clazLader = new URLClassLoader(reiURL);
            c01 = clazLader.loadClass("test.SerObj");
            return c01;
        }
        return super.resolveClass(desc);
    }
};

SerObj obj = (SerObj) o.readObject();

The problem is in the last line. My current class version is placed in U:/MyJavaProj/bin/test/SerObj.class
My old class version is placed in U:/MyJavaProj/bin/test/oldversion/test/SerObj.class
In the last line I read the old class version but cast it to the new version :(
Has anyone some idea or maby any other aproach to add the versioning support for the serialization in Java?
Comment: What exactly is the problem - can you provide an exception stack trace?
Comment: Exception in thread "main" java.lang.ClassCastException: test.SerObj cannot be cast to test.SerObj :)
Answer: i don't know if you trying to fix an existing problem, or write new functionality.  if the latter, then i would look into using the advanced functionality of java serialization.  java serialization supports various facilities for being able to handle multiple serial versions of the same class within one classloader (critically, though, you need to keep the serialVersionUID the same for all instances).
here's an example for handling an "incompatible" change, where an integer value was changed to a String value:
public class MyClass {
  private static final int CUR_VERSION = 5;
  private String _value;

  private void readObject(ObjectInputStream in) {
    // first value is always the serial version:
    int dataVersion = in.readInt();
    if(dataVersion == CUR_VERSION) {
      // _value is a String
      _value = in.readString();
    } else {
      // in older versions, _value was an int
      _value = String.valueOf(in.readInt());
    }
  }

  private void writeObject(ObjectOutputStream out) {
    // always write version first
    out.writeInt(CUR_VERSION);
    out.writeString(_value);
  }
}

Comment: Yes. I know this solution. But it would not work by some serialisation incompatibaly changes. And that is, what i want to support
Comment: not true.  you can certainly handle incompatible changes, you just need to handle the conversion in your own code.
Comment: Good example. However, i'd recommend hard coding the version into the code. Instead of "if(dataVersion == CUR_VERSION)" use "if(dataVersion >= 5)". Otherwise when you jump to version 6, it's going to deserialize v5 data improperly.
Comment: @ldkronos - i don't understand.  if you change to version 6, then you will presumably be changing the code...
Comment: @jtahlborn - Although this example is simple, in reality you are probably going to be deserializing multiple fields from the stream. While version 5 might have affected handling of the 3rd variable, version 6 might concern handling of the 7th variable. The way the example is written, when you go to add handling for variable #7 in version 6, you first have to go back and rewrite handling of variable #3 for version >= 5. So rather than make you remember to change it later (and possibly break it), just do it correctly now, then nothing gets broken in the future.
Answer: The simple answer to this is don't change the serialVersionUID.
If you think you've made a serialization-incompatible change to the class, first read the Object Versioning part of the Object Serialization Specification to double-check that, as you probably haven't, and if you really have, change/add the writeObject/readObject methods so that they can cope with the old serialization format.
And certainly don't try to mess around with two versions of the class at runtime. It won't work.
Answer: You won't be able to perform the cast in the last line, because it's of a different class (which is not castable) - you might get a confusing message such as test.SerObj is not an instance of test.SerObj.
This arises from the fact that a class is essentially a java.lang.Class instance, which critically is unique within a given classloader.  Even if you referenced the exact same *.class file, an instance of SerObj loaded by the default classloader is a different class from an instance of SerObj loaded by clazLader.  Neither class could be cast to the other one.
Thus it is not going to be possible for the method to return SerObj if you need to use multiple classloaders to deserialise.  (Besides - how could it, when the two class files could have arbitrary differences?)

One possible workaround is to define an interface that defines the behaviour which is fixed between versions of the class.  If you set up the temporary classloader such that it can only load SerObj from the oldversion class file, and that it has the right parent classloader, then your old SerObj should still implement the interface class as defined by the root classloader.
In this was, both the new SerObj and old SerObj instances would be castable to the SerObjIface interface, and so you could declare your method to return that.  And in fact if you want callers to deal with different yet similar classes (which is what different versions of "the same class" are), you should arguably be returning an interface for this anyway.
Comment: Thank you. I had the same idea with an interface, but it was interesting to know, if i could solve it another way.
Comment: But it looks, like to cast into common interface or parent class is one and only solution.
Comment: Yep - as the classes are different, they can only possibly share a parent interface or superclass (in the extreme case, all the way up to `java.lang.Object`).  I don't think it's conceptually possible to get around this limitation.
Comment: You could use reflection to read the fields from the old class and set those on an instance of the new class.


Rule to autopopulate node reference field and redirect after content creation

Question: I'm trying to make a rule so that when a node of content type X is created, a node of content type Y is also created and is automatically populated with a nodereference field to the nid of content type X that was created. Then the user should be redirected to the edit form of the node of content type Y that they just created.
My rules configuration looks like this right now:
Event: After saving new content
Condition: Content is of type X
Actions:

Create a new entity of content type Y
Set a data value: set the node reference field on new node of content type Y nid of new node of content type X
Page redirect: URL: [entity-created:edit-url]

Everything works as expected except the redirect (which I thought would be the easiest part). Both nodes get created and the node reference field is set correctly. But I get a page not found error with the following messages:

Notice: Undefined property: stdClass::$nid in node_tokens() (line 112
  of /web/xxxxxx/www/modules/node/node.tokens.inc).
"content type X" "title of new content of type x" was successfully created
The requested page "/node//edit" could not be found.

I've also tried node/[entity-created:nid]/edit for the page redirect. Same exact problem. I have no idea why it's not plugging in the nid of the new node of content type Y in between node/*/edit.
Answer: Basically you need to create another event right after "create entity" which immediately saves the new entity before you move on to the redirect rule.
See also http://groups.drupal.org/node/204558#comment-688188.
Answer: After setting the data value, also choose the action "Save entity" action and remove the page redirect action which is not yet needed.
Next
Create another rule that has:
Event "After Saving new Content"
Condition: content of type y
Action: Page redirect -> [node:edit-url]
When you are done with both rules, you can set the weights of the rules so that one runs before the other. So set your rule to weight: -2 and then set the new rule to weight: -1 and save them. At the bottom of the page click on settings and you will see a drop down of values for the weights.
Comment: Seems similar to the other answer except that it's a separate rule. Wouldn't the fact that it's a new rule though mean that this *always* happens whenever saying content of type y? That wouldn't be desirable in this case.
Comment: Yes it happens only after creating a new content of type y, not after editing a content of type y. If you want to also create a content of type y without using content type x then your better solution is to use the link above. But if you only use content type x to create content type y then then my answer should be okay too.


Why does initial hash value in GetHashCode() implementation generated for anonymous class depend on property names?

Question: When generating GetHashCode() implementation for anonymous class, Roslyn computes the initial hash value based on the property names. For example, the class generated for
var x = new { Int = 42, Text = "42" };

is going to have the following GetHashCode() method:
public override in GetHashCode()
{
   int hash = 339055328;
   hash = hash * -1521134295 + EqualityComparer<int>.Default.GetHashCode( Int );
   hash = hash * -1521134295 + EqualityComparer<string>.Default.GetHashCode( Text );
   return hash;
}

But if we change the property names, the initial value changes:
var x = new { Int2 = 42, Text2 = "42" };

public override in GetHashCode()
{
   int hash = 605502342;
   hash = hash * -1521134295 + EqualityComparer<int>.Default.GetHashCode( Int2 );
   hash = hash * -1521134295 + EqualityComparer<string>.Default.GetHashCode( Text2 );
   return hash;
}

What's the reason behind this behaviour? Is there some problem with just picking a big [prime?] number and using it for all the anonymous classes?
Comment: It seems more useful to me if you use different constants so that objects of different types are "more" different.
Answer:
Is there some problem with just picking a big [prime?] number and using it for all the anonymous classes?

There is nothing wrong with doing this, it just tends to produce a less efficient value.
The goal of a GetHashCode implementation is to return different results for values which are not equal.  This decreases the chance of collisions when the values are used in hash based collections (such as Dictionary<TKey, TValue>).
An anonymous value can never be equal to another anonymous value if they represent different types.  The type of an anonymous value is defined by the shape of the properties:

Name of properties
Type of properties
Count of properties

Two anonymous values which differ on any of these characteristics represent different types and hence can never be equal values.
Given this is true it makes sense for the compiler to generate GetHashCode implementations which tend to return different values for different types.  This is why the compiler includes the property names when computing the initial hash.
Comment: I see. I guess the hash codes with the constant initial value could blow up in your face if you put instances of different types into `HashSet` for whatever reason.
Comment: However, if differentiating hashes for the objects of different types is generally a good idea, why are the amonymous classes the only case when it's done by default? I haven't found a single example of this in BCL yet. For example, Int64, TimeSpan and DateTime basically share the implementation and `0L.GetHashCode()` == `TimeSpan.Zero.GetHashCode()` == `default( DateTime ).GetHashCode()`.
Comment: @HellBrick the differentiation is only interesting when it's likely the values will be inserted into the same hashing structure.  It's actually not uncommon for anonymous values of different types to do this.  But it's probably pretty rare, if ever, that a hashing structure will have both `DateTime` and `TimeSpan` values as keys.
Comment: Huh, I'd never expect putting anonymous values of different types into one dictionary / hashset to be popular enough =) But it explains a lot. Now I get the picture, thanks.
Comment: @HellBrick customers always do something you weren't expecting them to do ;)
Answer: Unless someone from the Roslyn team steps up we can only speculate. I would have done it the same way. Using a different seed for each anonymous type seems like a useful way to have more randomness in the hash codes. For example it causes new { a = 1 }.GetHashCode() != new { b = 1 }.GetHashCode() to be true.
I also wonder whether there are any bad seeds that cause the hash code computation to fall apart. I don't think so. Even a 0 seed would work.
The Roslyn source code can be found in AnonymousTypeGetHashCodeMethodSymbol. The initial hash code value is based on a hash of the names of the anonymous type.


Some attribute values aren't case sensitive (input[type]) some are (*[class]) - how does Html Agility Pack handle that?

Question: I am trying to select an element by its type
//input[(@type = 'checkbox' or @type = 'radio') and @name = 'BigBobMcNob']

but its not matching, because my type is capitalised
<input type='Checkbox' name='BigBobMcNob' />

How do I fix that? and if I do will it break when selecting on class, which should be case sensitive?
Answer: You could just iterate through the node collection and check each node against your conditions like this:
var allowedName = "Checkbox";
var allowedTypes = new[] { "checkbox", "radio" };
var nodes = doc.DocumentNode.DescendantNodes()
    .Where(n =>
        n.Name == "input" &&
        allowedTypes.Contains(n.GetAttributeValue("type", null), StringComparer.OrdinalIgnoreCase) &&
        n.GetAttributeValue("type", null) == allowedName
    ).ToList();

For type attribute comparison, StringComparer.OrdinalIgnoreCase comparer is used; name attribute doesn't require a special comparer.
Comment: Thanks alex, the problem here is that we are configuring selectors with xpath strings through a UI, I could use dynamic linq, but its all getting a bit too complex :(


Roll $4$ dice and probability that there exists at least one pair of dice such that the sum of faces add up to $7$.

Question: Disclaimer: This isn't a homework question. I was independently studying probability and this question randomly came up in my mind.
I was thinking of subtracting "the probability of having no pair of $(n,m)$ that adds up to $7$" from $1$.
I shall denote the probability in quotation by $P$. If four numbers are all different, then P trivially becomes 1 by pigeonhole principle. (for simplicity, let's say three holes are $\{1,6\}$, $\{2,5\}$, $\{3,4\}$) Hence, I assume that there exist at least two duplicated numbers.
Total number of ways of choosing $4$ numbers is:
$T = \binom{6}{4} + \binom{6}{3}\binom{3}{1} + \binom{6}{2}[\binom{2}{1}+1] + \binom{6}{1}$. Then, I break up into three cases to calculate $P$, where

only $2$ numbers are the same:
$ P_{1} = \binom{6}{1}\binom{2}{1}\binom{2}{1}/T$ (choose $1$ number of duplicate, choose two numbers from each hole.)
$2$ duplicates:
$ P_{2} = \binom{6}{1}\binom{4}{1}/T$
only $3$ numbers are the same:
$ P_3 = \binom{6}{1}\binom{4}{1}/T$ (choose $1$ number of duplicate, then choose $1$ last number.
all $4$ numbers are the same
$ P_4 = \binom{6}{1}/T$

$P = P_1 + P_2 + P_3 + P_4$, and the solution I am looking for is, $1-P$. Am I missing anything, or overcounting anything?
P.S.

How should I solve this problem if if we have a large number instead of 4 dice, say $n$?
Is there a more elegant way to solve this problem using inclusion and exclusion? I can't really think of a way to apply inclusion and exclusion principle. Answer to this question shall easily suffice as a solution to the previous question.
Answer: Throw $n$ dice and for $A\subseteq\left\{ 1,2,3,4,5,6\right\} $
let $E_{A}$ denote the event that all faces of the dice take a value
in $A$.
Let $E:=E_{\left\{ 1,2,3\right\} }\cup E_{\left\{ 1,2,4\right\} }\cup E_{\left\{ 1,3,5\right\} }\cup E_{\left\{ 1,4,5\right\} }\cup E_{\left\{ 2,3,6\right\} }\cup E_{\left\{ 2,4,6\right\} }\cup E_{\left\{ 3,5,6\right\} }\cup E_{\left\{ 4,5,6\right\} }$
Then to be found is $1-P\left(E\right)$.
With inclusion/exclusion and symmetry we find:
$$\begin{aligned}P\left(E\right) & =8P\left(E_{\left\{ 1,2,3\right\} }\right)-12P\left(E_{\left\{ 1,2\right\} }\right)-12P\left(E_{\left\{ 1\right\} }\right)+24P\left(E_{\left\{ 1\right\} }\right)-6P\left(E_{\left\{ 1\right\} }\right)\\
 & =8\cdot2^{-n}-12\cdot3^{-n}+6\cdot6^{-n}\\
 & =2^{3-n}-4\cdot3^{1-n}+6^{1-n}
\end{aligned}
$$
So we conclude that: $$1-P\left(E\right)=1-2^{3-n}+4\cdot3^{1-n}-6^{1-n}$$
In special case $n=4$ we find: $$1-P(E)=\frac{139}{216}$$
Comment: very elegant. Thank you!


How do I make two identical classes work differently with the same javascript function?

Question: I want to make these two circles move differently (they acquire the same direction while moving) with the same javascript function, but I am quite new using javascript and do not know how to make it.
I do not know how to make javascript differ between the same classes in html to get the same function but work differently depending on their specific class. My ideal code would make the two circles move randomly but in independent direction from one to another.

    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/stylesheet.css">

        aa

        bb

body {
    overflow: hidden;
    margin: auto;
    width: 640px;
    padding: 50px;
  }

  .wrapper {
    position:absolute;
    height:200px; width:200px;
    /* border-style:solid; */
  }

  .circle {
    position:relative;
    height:100px; width:100px;
    margin-top:50px;margin-left:50px;
    border-radius:50%;
    border-style:solid;
  }

$(document).ready(function(){
    animation();
}

function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

function new_position() {
    var newt = randomNumber(-50,50);
    var newl = randomNumber(-50,50);

    return [newt, newl]
}

function animation(){
    var newpos = new_position();
    var speed = 2000;

    $('.circle').animate({ top: newpos[0], left: newpos[1] }, speed, function(){
        animation();
      });

};

Thank you very much!
Answer: To target circle aa:
$('.circle.aa').animate({ top: newpos[0], left: newpos[1] }, speed, function(){
     // Animation for circle aa
     animation_aa();
});

To target circle bb:
$('.circle.bb').animate({ top: newpos[0], left: newpos[1] }, speed, function(){
     // Animation for circle bb
     animation_bb();
});

Comment: I still can't make it work. Both move with the same direction
Comment: Probably because you're calling the same function for both (see my edited answer).


About some patterns I've noticed in truth functions

Question: https://en.wikipedia.org/wiki/Truth_function
I was looking at the 16 truth functions to see if I notice any patterns. I've found:

There are 1 set with 4 ordered pairs, 4 sets with 3 ordered pairs, 6 sets with 2 ordered pairs, 4 sets with 1 ordered pair, and 1 set with 0 ordered pair.

If looked at as relations between P and Q, half of them are symmetric and the other half are asymmetric.

Only the Proposition Q, the Biconditional, the Exclusive Disjunction, and the Negation of Q are total functions from P to Q.

Proposition Q entails the Material Implication from P to Q. Proposition Q has less ordered pairs, 2, than the Material Implication from P to Q, 3. This seems analogous to being a member of a subset entailing being a member of that set's superset.

Is there anything wrong with the statements above? Any insight from these that are interesting?
Also, is there something non-obviously special about the Material Implication function that makes it analogous to Logical Entailment?
Comment: by "assymetric' do you mean that $r_{i,j}=$ opposite of $r(j,i)$ ; what about $r_{i,i}$ ?
Answer: All of your observations are totally correct, but some of them are phrased in confusing ways. Let's look at them one by one.

There are 1 set with 4 ordered pairs, 4 sets with 3 ordered pairs, 6 sets with 2 ordered pairs, 4 sets with 1 ordered pair, and 1 set with 0 ordered pair.

It took me a minute to realize what you were trying to say here. I think a better way to phrase your observation is as follows: "One of these functions yields 'true' on all 4 possible inputs. Four of them yield 'true' on 3 of the inputs. Six of them yield 'true' on 2 of the inputs. Four of them yield 'true' on 1 of the inputs. One of them yields 'true' on none of the inputs."
We can summarize your observation with this formula: the number of truth functions that yield "true" on precisely $k$ inputs is ${4 \choose k} = \frac{4!}{k!(4-k)!}$. The reason that the binomial coefficient comes into play is that specifying a truth function consists of choosing which of the four possible inputs to yield "true" on.
Here's a challenge for you: see if you can come up with a formula that gives the number of ternary (or $n$-ary) truth functions that yield "true" on precisely $k$ inputs.

If looked at as relations between P and Q, half of them are symmetric and the other half are asymmetric.

A binary truth function is symmetric if and only if it yields the same thing on $(T,F)$ as it does on $(F,T)$, since these are the only two inputs where switching the truth vales of $P$ and $Q$ changes anything. There are just as many truth functions that yield the same result on these inputs as there are that yield different results on these inputs.
Again, I challenge you to generalize your observation to the ternary or $n$-ary case. How many ternary truth functions are symmetric on $P$ and $Q$? How many ternary truth functions are symmetric on $P$, $Q$, and $R$? In general, how many $n$-ary truth functions are symmetric on the first $k$ arguments?

Only the Proposition Q, the Biconditional, the Exclusive Disjunction, and the Negation of Q are total functions from P to Q.

This one also took me a minute to understand. You can rephrase it as follows "The Proposition $Q$, the Biconditional, the Exclusive Disjunction, and the Negation of $Q$ are the only truth functions that can yield either true or false regardless of the value of $P$."
A truth function $f$ has this property if and only if $f(P, Q) = \neg f(P, \neg Q)$ for all possible values of $P$ and $Q$, where $\neg x$ denotes the negation of $x$. If we assume that a function has this property, we only have to specify its values at $(T,T)$ and $(F,T)$ to determine its values at all four inputs. Since there are $2 \times 2 = 4$ ways to specify the values of a two-valued function at two inputs, there are precisely four functions with this property.
Once again, I challenge you to generalize your observation to the ternary and $n$-ary cases.

Proposition Q entails the Material Implication from P to Q. Proposition Q has less ordered pairs, 2, than the Material Implication from P to Q, 3. This seems analogous to being a member of a subset entailing being a member of that set's superset.

If $Q$ is true, then every proposition, including $P$, implies $Q$. And yes, the set of inputs that make Proposition $Q$ true is a subset of the set of inputs that make Material Implication true.

Also, is there something non-obviously special about the Material Implication function that makes it analogous to Logical Entailment?

There are two ways to think about these 16 truth functions. On one hand, you can think of them as purely algebraic objects without any deeper meaning—they are just mathematical functions that take in two arguments and return either a $0$ or a $1$. On the other hand, you can think of them as linguistic/semantic objects endowed with meaning—they are ways to take two propositions that make statements about the universe and combine them into a new proposition.
What makes mathematical logic so useful is that it allows us to switch between these two perspectives depending on which is more useful/relevant. This article might be a bit advanced, but you can read about algebraic propositional logic to learn more about this duality.


Intuitively, why is multiplying a row of matrix elements with the corresponding cofactors of another row equivalent to a determinant with 2 same rows?

Question: This property was listed in my Mathematics Textbook, with a very unintuitive and hard to understand proof :
If elements of a row (or column) are multiplied with cofactors of any other row (or column), then their sum is zero.
I have attempted so far writing down matrices and testing this property out, reading and researching various answers about this property, yet I am not able to intuitively understand it.
Several answers around the Internet state that multiplying a row with corresponding cofactors of ANOTHER row is identical to calculating the determinant of matrix containing 2 identical rows. This is precisely the part I do not understand
Why intuitively is it equivalent to a determinant of a matrix containing two identical rows? I can tell that the property holds true if I test it on any matrix on paper, and that it is indeed equivalent to calculating the determinant of a matrix with two identical rows, but I can't intuitively understand WHY it is so and why such a result happens?
Is there a way to let me understand why it is like that?
Comment: When you compute the cofactors along row $i$, you are computing them by computing the determinants of submatrices that have row $i$ deleted, right? But the cofactors are computed using all of the other rows. Then, when you compute the determinant of the matrix using cofactor expansion, you use row $i$ and the cofactors computed along row $i$. If you instead used row $j$ with the cofactors computed along row $i$, that would be the same as the cofactor expansion of a matrix that had row $i$ equal to row $j$.
Comment: @Joe Sorry I'm struggling to understand what you mean. Cofactor for any specific element in a 3x3 matrix aij, does not include row i AND column j, yes? So cofactors for an entire row would not include row i and also column j for each element aij in row i

So how can we say that the submatrices ONLY consist of elements not including row i, when column j1,j2, and j3 are also missing?

'If you instead used row j with the cofactors computed along row i, that would be the same as the cofactor expansion of a matrix that had row i equal to row j'

But why is this so? This is the part I cant get
Answer: Let's consider the matrix:
$$A = \begin{bmatrix}a & b & c\\d & e & f\\g & h & i\end{bmatrix}$$
The cofactors along the first row are:
$$C_{1,1} = \begin{vmatrix}e & f\\h & i\end{vmatrix}$$
$$C_{1,2} = -\begin{vmatrix}d & f\\g & i\end{vmatrix}$$
$$C_{1,3} = \begin{vmatrix}d & e\\g & h\end{vmatrix}$$
And we have that:
$$\det(A) = aC_{1,1}  +  bC_{1,2}  +  cC_{1,3}$$
But now consider the equation:
$$dC_{1,1}  +  eC_{1,2}  +  fC_{1,3}$$
That would be the cofactor expansion of the matrix:
$$B = \begin{bmatrix}d & e & f\\d & e & f\\g & h & i\end{bmatrix}$$
Since that matrix has the same cofactors along the first row as $A$.
But since $B$ has two identical rows, we know that its determinant is zero, so:
$$\det(B) = dC_{1,1}  +  eC_{1,2}  +  fC_{1,3} = 0$$
I think the key idea is that, since the cofactors computed along a row (or column) do not use the values of that row (or column), then replacing that row (or column) does not change the cofactors computed along it.
That is why the linear combination
$$\sum_{j=1}^{n} a_{k,j} C_{i,j}$$
is the same as the determinant of matrix $A$ with row $i$ replaced with row $k$.
EDIT adding additional details.
The question was about why it is true that:
"If elements of a row (or column) are multiplied with cofactors of any other row (or column), then their sum is zero."
To show why that is true, I first chose a row for the cofactors (in the example above, row 1), then a different row to multiply them by (in the example above, row 2).
Then I showed that the product is the same as the determinant of a different matrix (matrix $B$) in which row 1 is replaced by row 2.
So $B$ was not some random matrix. It was a matrix determined by our choices of

the row (or column) along which to compute the cofactors, which I'll call $i$, and
the other row (or column) which we want to multiply those cofactors by, which I'll call $j$

Once we have chosen those two rows (or columns), we can see that the product of the cofactors for row (or column) $i$ by row (or column) $j$ is the same as the cofactor expansion of a different matrix, in which row (or column) $i$ is replace by row (or column) $j$, so that it has two copies of that row (or column): one in row (or column) $i$ and another in row (or column) $j$.
Hence, that matrix has a determinant of zero, so the equation is equal to zero.
Comment: I have a question. Why exactly is Matrix B defined such that the (in this case atleast) first two rows are identical? Sure I can see why it has the same cofactors along the same row as A, but exactly why must its first row be = to the second row of A? Why cant the first elements of B...well, be anything else?
Comment: I'll edit the answer to explain further.


How to obtain the Gaussian conditional pdf, as discussed in section 2.3.1 in Pattern Recognition and Machine Learning, Bishop?

Question: From Statistical Inference of Casella, a conditional pdf is obtained through the joint pdf by the following equation,
(1)
$$
p_a(x_a | x_b) = \frac {p(x_a, x_b)}{p_b(x_b)}
$$
In section 2.1.3 of PRML, the author did not mention explicitly the equation, but I guess he using the same approach. The author obtain the conditional mean and covariant matrix by directly manipulating the quadratic form of the exponent of the joint pdf. I understand how he obtain the conditional mean and covariant matrix, but since he does not explain how to obtain the corresponding Gaussian pdf, I have no idea if that pdf is equal to (1).
This are the derived conditional mean and covariant matrix derived from the joint pdf, and other relevant vectors and matrices
The result conditional mean of $x_a$, given $x_b$
$$
\mu_{a|b} = \mu_a - \Lambda_{aa}^{-1} \Lambda_{ab} (x_b - \mu_b) \\
$$
The resulted conditional covariant matrix
$$
\Sigma_{a|b} = \Lambda_{aa}^{-1} \\
$$
The random vector
$$
x = \binom{x_a}{x_b} \\
$$
The joint mean
$$
\mu = \binom{\mu_a}{\mu_b} \\
$$
The joint covariant matrix and its inverse
$$
\Sigma = \begin{bmatrix}
\Sigma_{aa} & \Sigma_{ab}\\
\Sigma_{ba} & \Sigma_{bb} \\
\end{bmatrix} \\
\Lambda = \Sigma^{-1} = \begin{bmatrix}
\Lambda _{aa} & \Lambda _{ab}\\
\Lambda _{ba} & \Lambda _{bb} \\
\end{bmatrix} \\
$$
The quadratic form of the exponent of the joint pdf
$$
(x - \mu)^T \Sigma (x - \mu)
$$
(2) The general multivariate Gaussian pdf on a random vector $X \in R^D$
$$
N(x | \mu, \Sigma) = \frac{1}{(2\pi)^{0.5D}} \frac{1}{|\Sigma|^{0.5}} \exp\big(-0.5(x-\mu)^T \Sigma^{-1} (x-\mu) \big)
$$
Comment: Does this answer your question? [Interpretation of multivariate conditional gaussian function form?](https://stats.stackexchange.com/questions/502699/interpretation-of-multivariate-conditional-gaussian-function-form)
Comment: Can you write your question explicitly (i.e. mention the equations in PRML) and point out where you didn't understand?
Comment: There is no equation in the section I don't understand. As I said, the author only show how to obtain the conditional mean and covariant matrix. I want to verify using the parameters to obtain the equation (1), but I failed to do so.
Comment: I still don't understand what you mean by "but he does not explain how to obtain the corresponding Gaussian pdf", w/o looking into the section you mentioned. It's better if you could elaborate your question and flow.
Comment: The author manipulated the quadratic form in the exponent of the joint pdf to find the mean and covariant matrix, but not from (1), and so I still find it difficult to verify if the parameters are actually of the conditional Gaussian distribution. Btw, I added relevant matrices and vectors.
Answer: The author (C. Bishop) intentionally doesn't use the classic relation (1) because it'd then be required to calculate the denominator by marginalising the joint PDF. This integral is quite cumbersome in may cases in bayesian literature and there are approximate ways of getting it. However, in the Gaussian case, we have a way of calculating it in an indirect way (i.e. not by marginalising the joint). The author simply exploits the form of the joint PDF to come up directly with the conditional PDF. The idea can be outlined as follows:
The conditional PDF is a function of $x_a$, and since $x_b$ is given, any expression containing $x_b$ can be regarded as a constant. Therefore, the denominator has no effect on the form of $x_a$'s conditional PDF.
Ex: If let's say $p(x_a,x_b)=g(x_b)e^{-x_a h(x_b)}$ (assume $x_a$ is not a vector for this particular case), then $p(x_a|x_b)$ is in the form of an exponential random variable's PDF because all other terms including $p(x_b)$ in the denominator don't change the form of the conditional ($Ce^{-\lambda x})$.
That's why the author manipulates the joint PDF and says that it's actually in the following form:
$$\begin{align}p(x_a,x_b)&=C\exp(-0.5(x-\mu)^T\Sigma^{-1}(x-\mu))\\&=C\exp(-0.5(x_a-b)^TS^{-1}(x_a-b)+g(x_b))\end{align}$$
where $g(.)$ is a function. And, this form is Gaussian for $x_a$. So, the conditional PDF is Gaussian. We don't worry exactly what would the denominator be or what exactly $g(x_b)$ brings us since it'd all have to satisfy the normalization property of PDFs anyway.
Noting that the form is Gaussian, it all boils down to finding what $S$ and $b$ is which are conditional covariance and the mean. Of course, there are a lot of steps between the first and the second line here, and if you have questions about specific steps, you can ask them as follow-ups.
Comment: The last equation is joint PDF, it's proportional to conditional PDF by a constant (in terms of terms other than $x_a$). The constant outside the exponent can depend on S. Since S is a constant, too, it's not a problem.
Comment: Thanks for the answer. I was ignorant a conditional pdf can be "any" function, rather than defined by the form (1). Regarding the last equation in your answer, the exponent has the same form as that in the general Gaussian pdf (2) (I included it in my question), but the constant outside of the exponent still depend on S, i.e. the square root of the determinant of S. Based on the form (2), I cannot convince myself the last equation is Gaussian with mean b and covariance matrix S. Could you clarify the point?


How can this if-statement evaluate to true?

Question: if ($opts['width'] == 'fs' || $opts['height'] == 'fs' || $opts['ratio'] == 'fs') {
    var_dump($opts); // result of this see bellow
}

Result of var_dump($opts) inside (!) if-statement:
array(3) {
   'width' => int(200)
   'height' => int(0)
   'ratio' => int(0)
}

How is this possible? None of the array's values is (stirng) fs?
Comment: Try using `===`! http://ideone.com/EpsAH2
Answer: Because 0 == 'fs'. See this conversion table.
PHP has the === operator to compare both value and type.
For a more extensive table: Type-juggling and (strict) greater/lesser-than comparisons in PHP
Comment: Thank you for the conversion table link. But in my opinion that's in someway weird. 0 should not evaluatue true to (string) 'fs'. Anyway, I've saved the link for the future!
Comment: @mcj: In PHP, if `A == B` and `B == C` it doesn't mean that `A == C`.


Can a Suslin tree squared collapse $\aleph_1$?

Question: A standard fact is that if $T$ is a Suslin tree, then $T\times T$ flipped upside down and viewed as a forcing is not ccc. But can it collapse cardinals? At the very least, the answer is not always - for instance, suppose there are Suslin trees $T_1$ and $T_2$ such that the tree theoretic product $T_1\otimes T_2$ is Suslin (as happens, for instance, under $\diamondsuit$). Then take $T$ to be a tree with two nodes $t,u$ such that the collection of nodes extending $t$ is isomorphic to $T_1$ and the nodes extending $u$ is isomorphic to $T_2$. Then $T\times T$ does not force that $\aleph_1$ is collapsed since the suborder of conditions below $(t,u)$ is ccc.
Comment: I recall that this is consistent. If the Suslin tree is rigid, I think. One can certainly force such a tree. I think it's an exercise in Jech.
Answer: Answering with the hint to look in Jech and some help from a friend. The answer is yes; relevant Jech exercise is 15.20 in constructing a homogeneous Suslin tree. Suppose there are $\langle f_\alpha\mid\alpha<\omega_1\rangle$ such that $f_\alpha\colon\alpha\to2$, for $\alpha<\beta$ we have $f_\alpha=^*f_\beta$ and $T=\{g\mid g=^*f_\alpha\text{ for some }\alpha\}$ is a Suslin tree; such objects exist under $\diamondsuit$ or can be forced. Then $T\otimes T$ collapses $\aleph_1$: let $\langle t_\alpha,u_\alpha\mid \alpha<\omega_1^V\rangle$ be the generic branch through $T\otimes T$. Then mapping $n$ to the least $\alpha$ such that $t_\alpha,u_\alpha$ disagree in at least $n$ coordinates is a function from $\omega$ to $\omega_1^V$ with cofinal range.


How to make multi record join show up in main section

Question: This is the file coming out:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soapenv:Body>
    <ns1:getDocumentByKeyResponse xmlns:ns1="http://www.taleo.com/ws/integration/toolkit/2005/07" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
      <Document xmlns="http://www.taleo.com/ws/integration/toolkit/2005/07">
        <Attributes>
          <Attribute name="count">1</Attribute>
          <Attribute name="duration">0:00:00.102</Attribute>
          <Attribute name="entity">Requisition</Attribute>
          <Attribute name="mode">T-XML</Attribute>
          <Attribute name="version">http://www.taleo.com/ws/tee800/2009/01</Attribute>
        </Attributes>
        <Content>
          <ExportTXML xmlns:e="http://www.taleo.com/ws/tee800/2009/01" xmlns="http://www.taleo.com/ws/integration/toolkit/2005/07">
            <e:Requisition>
              <e:ContestNumber>15000005</e:ContestNumber>
              <e:JobInformation>
                <e:JobInformation>
                  <e:OtherLocations>
                    <e:Location>
                      <e:ZipCode>77002</e:ZipCode>
                    </e:Location>
                    <e:Location>
                      <e:ZipCode>77050</e:ZipCode>
                    </e:Location>
                  </e:OtherLocations>
                  <e:PrimaryLocation>
                    <e:Location>
                      <e:ZipCode>77003</e:ZipCode>
                    </e:Location>
                  </e:PrimaryLocation>
                </e:JobInformation>
              </e:JobInformation>
            </e:Requisition>
          </ExportTXML>
        </Content>
      </Document>
    </ns1:getDocumentByKeyResponse>
  </soapenv:Body>
</soapenv:Envelope>

I need it to look like so:
<?xml version="1.0" encoding="UTF-8"?>
<source>
  <job>
    <job_id>
      <![CDATA[15000005]]>
    </job_id>
    <location_zipcode>
      <![CDATA[77002]]>
      <![CDATA[77050]]>
      <![CDATA[77003]]>
    </location_zipcode>
  </job>
</source>

My current xsl looks like so:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:e="http://www.taleo.com/ws/tee800/2009/01" xmlns:fct="http://www.taleo.com/xsl_functions" exclude-result-prefixes="e fct">
  <xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="no" cdata-section-elements="job_id location_zipcode other_location_zipcode"/>
  <xsl:param name="OUTBOUND_FOLDER"/>
  <xsl:template match="/">
    <source>
      <xsl:apply-templates select="//e:Requisition"/>
    </source>
  </xsl:template>
  <xsl:template match="e:Requisition">
    <xsl:variable name="location_zipcode" select="e:JobInformation/e:JobInformation/e:PrimaryLocation/e:Location/e:NetworkLocation/e:NetworkLocation/e:ZipCode"/>
    <xsl:variable name="other_location_zipcode" select="e:JobInformation/e:JobInformation/e:OtherLocation/e:Location/e:NetworkLocation/e:NetworkLocation/e:ZipCode"/>
    <xsl:variable name="job_id" select="e:ContestNumber"/>
    <job>
      <job_id>
        <xsl:value-of select="$job_id"/>
      </job_id>
      <location_zipcode>
        <xsl:value-of select="$location_zipcode"/>
        <xsl:value-of select="$other_location_zipcode"/>
      </location_zipcode>
      </job>
      </xsl:template>
      </xsl:stylesheet>

This xslt makes it fail when it comes across more than 1 other location record.  I need it to keep pulling however many there are.  Any ideas would be most appreciated!
Thanks!
Greg
Comment: Then perhaps I misunderstood; I thought "what's coming out" is your current output, and the next snippet the expected output. So, is the first XML document the input?
Comment: Your question is missing your input XML, please add it.
Comment: What is coming out is the first section of my post, is it not showing?
Comment: You won't be able to put each separate zipcode in its own CDATA section using `cdata-section-elements`, the only way to do that would be to hack it with `disable-output-escaping`.  Not that there's any point putting a zip code in CDATA anyway as it should just be digits, you might as well just leave it as normal text.
Answer: The following stylesheet:
XSLT 1.0 or 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:e="http://www.taleo.com/ws/tee800/2009/01"
exclude-result-prefixes="e">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:template match="/">
    <source>
        <xsl:apply-templates select="//e:Requisition"/>
    </source>
</xsl:template>

<xsl:template match="e:Requisition">
    <job>
        <job_id>
            <xsl:value-of select="e:ContestNumber"/>
        </job_id>
        <location_zipcode>
            <xsl:for-each select="..//e:Location">
                <xsl:text disable-output-escaping="yes"><![CDATA[</xsl:text>
                <xsl:value-of select="e:ZipCode"/>
                <xsl:text disable-output-escaping="yes">]]></xsl:text>
                <xsl:text>
</xsl:text>
            </xsl:for-each>
        </location_zipcode>
    </job>
</xsl:template>

</xsl:stylesheet>

when applied to your example input (after cleaning up the redundant hyphens!) will return:
<?xml version="1.0" encoding="UTF-8"?>
<source>
   <job>
      <job_id>15000005</job_id>
      <location_zipcode><![CDATA[77002]]>
<![CDATA[77050]]>
<![CDATA[77003]]>
</location_zipcode>
   </job>
</source>

A slightly more efficient version would replace the // shortcuts with full, explicit paths.
I was just about to add a note regarding the CDATA requirement, but Ian Roberts said it much better that I was going to: How to make multi record join show up in main section
Comment: Appreciate it guys!  I will give it a shot.  Thanks for helping out a newbie.
Comment: I am actually getting this, looks like it is not returning the primary location zipcode.  Any help is appreciated!:

-
-
15000005
-
77002
77050

Comment: Nevermind, figured out what the issue was there.  Thanks Again! G
Comment: This worked with one record but now with multiple records this xsl is placing all the zipcodes on the output for each and every job_id

15000005

77002
77050
77003
77005
77051
77006

15000006

77002
77050
77003
77005
77051
77006
Comment: Please don't post code in comments, it's unreadable. If you have a follow-up question involving a different scenario, edit your original question and add your new input, along with the expected output. Or post a new question (depending on how different the new scenario is).
Comment: Gotcha.  I actually ended up figuring it out :) Will definitely remember your comment for next time.  Thanks! G


Characterization of normal $p$-complements

Question:
Let $p$ be a prime number. $N$ is a normal $p$-complement of a finite group $G$ if and only if $O_{p'}(G)=N=O^p(G)$.

Here $O_{p'}(G)$ is the largest normal subgroup whose prime divisors lie in $\mathbb P\setminus \{p\}$ and $O^p(G)$ is the smallest normal subgroup whose factor group is a $p$-group.
My attempt: First assume that $O_{p'}(G)=N=O^p(G)$ and let $P$ be a Sylow $p$-subgroup of $G$. Then $N$ is a normal subgroup and $P\cap N=1$. Thus, $|PN|=|G|$. Also, as $PN$ is a subgroup because $N$ is normal. Thus, $G=PN$ and so $N$ is a normal $p$-complement of $G$.
Conversely, let $N$ be a normal $p$-complement of $G$. Then there exists be a Sylow $p$-subgroup  $P$ of $G$ such that $G=PN$ and $P\cap N=1$.
It is easy to see that prime divisors of $N$ lie in $\mathbb P\setminus \{p\}$. Next, let $H$ be another subgroup whose prime divisors lie in $\mathbb P\setminus \{p\}$. Then for each $h\in H$, there exists $x\in P, y\in N$ such that $h=xy$. Since orders of $x$ and $y$ are coprime, so $|h|=|x| |y|$. In particular, $|x|$ divides $|h|$ and so $x=1$. Thus, $h=y\in N$. We have thus shown that $H\subseteq N$. It follows that $O_{p'}(G)=N$.
Finally, the factor group $G/N$ is of course a $p$-group. We're left to show that if $K$ is a normal subgroup of $G$ such that $G/K$ is a $p$-group, then $N\subseteq K$.

I can't figure out how to complete this.

Edit: Since $|G/K|\leq |G/N|$, we have that $|N|\leq |K|$. But this doesn't necessarily mean that $N\subseteq K$?
Answer: If $N \not\le K$ then $NK/K$ would be a nontrivial $p'$-subgroup of the $p$-group $G/K$, contradiction.
Comment: Sorry, I meant $NK/K$.
Comment: Why is $NK/N$ a $p'$-subgroup? We have $|NK/N|= |K|/|N\cap K|$, the latter can have $p$ as a prime factor. For example, if $|G|=p^2q^2, |N|=q^2, |K|=pq^2$, then?
Comment: Oh, yes. This makes sense. Thank you!


Covariation of density process in Girsanov's Theorem

Question: I am reading a proof of the following theorem concerning Girsanov's Theorem.

Let be $M$ a continuous local $P$- martingale. Then $M-\langle M,Y\rangle$ is a continuos local $Q$ martingale.

Here $Y_t=\int_0^t\frac{1}{Z_s}dZ_s$ and $Z_t$ is the radon nikodym density $\frac{dQ}{dP}_{\mid F_t}$.
I do not understand the following part in the proof:

Why is $\int_0^t\frac{1}{Z_s}d\langle M,Z\rangle=\langle M,Y\rangle_t$ true?

Any help here is highly appreciated.
The original proof:
From $Z_t=Z_0\exp(Y_t-\frac12\langle Y\rangle_t$ we have $dZ_t=Z_tdY_t$ thus $$(\frac {1}{Z}\circ \langle M,Z\rangle)_t=\int_0^t\frac{1}{Z_s}Z_sd\langle M,Y\rangle_s=\langle M,Y\rangle$$
Comment: do you have a reference for the proof?
Comment: @RScrilli the proof is in imediate consequence of Girsanov. I edited the proof. I see why this proof works, but I do not see the equality sign. Can you help me here?
Comment: I can give you a proof for the theorem, still I wanted to see the proof you were using so I can follow the reasoning your proof is using
Comment: I just need to understand the first  equality sign. Do you understand this and could elaborate on it ?
Comment: It follows from Kunita-Watanabe characterization: $[H \bullet M,N]=H \bullet [M,N].$
Answer: Heuristically $$dZ=YdY$$
implies that $$\frac{dZ}{Z}=dY.$$
Then $$dM\frac{dZ}{Z}=dY dM$$
which is equivalent to $\frac{1}{Z} d\langle Z,M\rangle=d\langle Y,M\rangle$.
Integrating both sides gives the desired result


Python String with HTML /

Question: I'm trying a simple program to send some html down a socket to a client. 2 things are goofing me up.
The code:
c.send( str.encode("Test Page<///BODY><///HTML>") )

My python client receives:
b'Test Page<///BODY><///HTML>'

According to Beginning Python which says it covers Python 3 (I'm using 3.1.1 on Windows), there is a String.Decode function. My environment cannot find it. I assume I'll run into the errors ('strict', 'ignore', 'replace' ) next.
Obviously, the extra /// is just guessing.
1) How do I decode this in Python?
2) I use my browser and obviously the HTML code is wrong, but I can see the server sent it.  How do I make the HTML browser friendly?
Cordially,
Stephen
Answer: You want '...'.encode() and b'...'.decode(). Saying "str.encode" is shorthand for saying that all str literals have this method.
Comment: I said "encode". You said "decode". Which one would you like to talk about?
Comment: >>Saying "str.encode" is shorthand for saying that all str literals >>have this method.

My environment can't find decode.  Not quite sure what what you mean by all str literals have this method.
Answer: The extra '/' is wrong. You only need to worry about escaping for '\'
Comment: @Stephen Deetz: Can you tell the difference between / and \?  One needs escaping and one does not.  Do not escape /.  Ever.  Sometimes you need to escape \ as \\.

Python String with HTML /


Filter and Query my Products (custom post type) by their Custom Taxonomy

Question: So my WordPress CMS has come quite a long way (and I've learned quite a bit about WordPress.  I've created a custom post type called Products which is here:
add_action( 'init', 'create_product_post_type' );

function create_product_post_type()
{
    $labels = array(
        'name' => _x('Products', 'post type general name'),
        'singular_name' => _x('Product', 'post type singular name'),
        'add_new' => _x('Add New', 'product'),
        'add_new_item' => __('Add New Product'),
        'edit_item' => __('Edit Product'),
        'new_item' => __('New Product'),
        'view_item' => __('View Product'),
        'search_item' => __('Search Products'),
        'not_found' => __('No products found'),
        'not_found_in_trash' => __('No products found in Trash'),
        'parent_item_colon' => '',
        'menu_name' => 'Products'
        );

    $args = array(
        'label' => __('Products'),
        'labels' => $labels,
        'public' => true,
        'can_export' => true,
        'show_ui' => true,
        '_builtin' => false,
        'capability_type' => 'post',
        'menu_icon' => get_bloginfo('template_url').'/functions/images/product.png',
        'hierarchical' => false,
        'rewrite' => array( "slug" => "product" ),
        'supports' => array('title'), //MAYBE add thumbnail later!
        'show_in_nav_menus' => true

        );

        register_post_type( 'product', $args);
}

Then a custom taxonomy called Category which is here:
function create_productcategory_taxonomy() {
    $labels = array(
        'name' => _x( 'Categories', 'taxonomy general name' ),
        'singular_name' =>_x( 'Category', 'taxonomy singular name' ),
        'search_items' =>  __( 'Search Categories' ),
        'popular_items' => __( 'Popular Categories' ),
        'all_items' => __( 'All Categories' ),
        'parent_item' => null,
        'parent_item_colon' => null,
        'edit_item' => __( 'Edit Product Category' ),
        'update_item' => __( 'Update Product Category' ),
        'add_new_item' => __( 'Add New Product Category' ),
        'new_item_name' => __( 'New Product Category' ),
        'separate_items_with_commas' => __( 'Separate categories with commas' ),
        'add_or_remove_items' => __( 'Add or remove product categories' ),
        'choose_from_most_used' => __( 'Choose from the most used categories' )
        );

    register_taxonomy('productcategory', 'product', array (
        'label' => __('Product Category'),
        'labels' => $labels,
        'hierarchical' => true,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => array( 'slug' => 'product-category'),
        ));
}

I created a single page in the wp-admin menu called Products that has a custom template I made.  Going to http://localhost/project/products brings it up and it lists all the products post types.  I also made a page for single-products.php that displays a single product post type details.
What I'm not sure how to do is create a way to filter my products by the custom taxonomy Category that is above.  Let's say I have a product that is a Widget.  This Widget has a Category of 'Spring Loaded'.  If I wanted to view the single widget, I can just link to http://localhost/project/products/widget and it would bring up the single-product.php page and display the Widget as I formatted the page to do so.  But I would like to link to just the 'Spring Loaded' category and list all my products in that custom category.  I believe every category has it's own slug (spring-loaded for example).   If I go to http://localhost/project/product-category/spring-loaded it brings up a page but I dont' know which file it is loading, other wise I could modify the output.  Right now it loads each product as a normal post (with the date, comments, etc...).
So my question is how can I filter these categories?  Or which file do I modify in order to change the output of the page that is linked from http://localhost/project/product-category/spring-loaded ?
I hope this makes sense.  Thank you!
UPDATE:
Ahhhh.  It's making sense now.  I changed this:
 register_taxonomy('productcategory', 'product', array (
        'hierarchical' => true,
        'rewrite' => array( 'slug' => 'product-category'),
        ));

to this:
 register_taxonomy('productcategory', 'product', array (
        'hierarchical' => true,
        'rewrite' => array( 'hierarchical' => true),
        ));

Even though I'm not sure what it does exactly.
I also created a taxonomy-productcategory.php and did some quick formatting and testing but it does indeed work.  I can go to http://localhost/project/productcategory/ and it will list all of the products for that category.
Now do I need to change my rewrite rules like you did?  I honestly don't understand how htaccess works so I dont' know if I need to change it or not.  Thanks!
Comment: if it work, then you don't have to change your rewrite.
Answer: This pretty much the same problem I've few weeks ago.
It already answered on Wordpress.SE: https://wordpress.stackexchange.com/questions/14451/taxonomy-terms-and-template-files
Comment: When they say make the template page    'taxonomy-type.php' does is that literally  'taxonomy-type.php' or do I replace taxonomy with my taxonomy slug(product-category)?  Also my current custom taxonomy slug rewrite looks like this `'rewrite' => array( 'slug' => 'product-category')`.  Do I also need to change it to `'rewrite' => array( 'hierarchical' => true)`?  I'm not really sure what that does.


Flutter firebase error Receiver: "Closure: () => Map from Function 'data':"

Question: Recently I have upgraded my flutter to 2.0 and firebase packages to latest ones. After upgrading them i have refactored my deprecated firebase code to new one. In one of my functions i have got run-time error on cloud_firestore package.
Old one:
  Future popularSearch() async {
    final snapshot = await FirebaseFirestore.instance.collection('searches').getDocuments();
    final List<PopularSearch> loadedResult = [];

    snapshot.documents.forEach(
        (element) => loadedResult.add(PopularSearch.fromJson(element.data)));
    popularSearches = loadedResult;
    notifyListeners();
  }
}

New one:
  Future popularSearch() async {
    final snapshot = await FirebaseFirestore.instance.collection('searches').get();
    final List<PopularSearch> loadedResult = [];

    snapshot.docs.forEach(
        (element) => loadedResult.add(PopularSearch.fromJson(element.data)));
    popularSearches = loadedResult;
    notifyListeners();
  }

Now it is giving this error instead of fetching data:
E/flutter (12403): Receiver: Closure: () => Map<String, dynamic> from Function 'data':.
E/flutter (12403): Tried calling: []("query")
E/flutter (12403): Found: []() => Map<String, dynamic>

Answer: Add a close bracket to element.data  ===> element.data()