Suppose $x$ and $y$ are unequal real numbers

Question:
Suppose $x$ and $y$ are unequal real numbers. If
$$
\sqrt[3]{\frac{x+y}{x-y}} + \sqrt[3]{\frac{x-y}{x+y}} = x+y
\qquad \text{and} \qquad
\sqrt{xy}=1
$$
then find the value of
$$
(x-y)^5 + 5(x-y)^3 - 2(x-y)^2+ 4(x-y)
$$

For the above question, I got $x$ not equal to $-1,0,1$ and $y = 1/x$.
Then, I tried finding $x-y$ using $\big((x+y)^2-4xy)\big)^{\frac{1}{2}}$ and then solving for $x$ and $y$.
I think I over complicated it and there must be some easier way. Please help me out.
Answer: Tricky one.
Let $x+y = u$, $x-y=v$.
$$ xy=1 \Rightarrow u^2-v^2 =4$$
and cubing original equation :$$ \sqrt[3]{\dfrac{u}{v}} + \sqrt[3]{\dfrac{v}{u}} = u $$
gives
$$ \dfrac{u}{v} + \dfrac{v}{u} + 3u = u^3 $$
$$ \Rightarrow u^2 + v^2 + 3u^2v = u^4v$$
Substitute $u^2=4+v^2$ ,
$$(4+v^2) + v^2 + 3(4+v^2)v = (4+v^2)^2v $$
directly yields
$$ \boxed{v^5 + 5v^3 -2v^2 + 4v =4}$$
Comment: nice .........+1
Answer: Intuitively, one should let $a=x+y$ and $b=x-y$.
Then from the condition $\sqrt {xy}=1$ one obtains $a^2-b^2=4$.
The other condition becomes
$$a = \sqrt[3]{\frac ab} + \sqrt[3]{\frac ba}$$
Cubing both sides, we have
\begin{align}a^3 &= \frac ab + 3\left(\sqrt[3]{\frac ab}\right)^2\sqrt[3]{\frac ba}+ 3\sqrt[3]{\frac ab}\left(\sqrt[3]{\frac ba}\right)^2+ \frac ba
\\&=\frac ab + \frac ba+ 3\left(\sqrt[3]{\frac ab} + \sqrt[3]{\frac ba}\right)
\\&=a\left(\frac 1b + \frac b{a^2}\right)+ 3a\end{align}
Eliminating $a$ from both sides gives
$$a^2 = \frac 1b + \frac b{a^2} + 3$$
$$4+b^2=\frac1b + \frac b{4+b^2} + 3$$
$$1+b^2=\frac {4+b^2+b^2}{b(4+b^2)}$$
$$b(4+b^2)(1+b^2)-2b^2 =4$$
Expanding $b(4+b^2)(1+b^2)-2b^2$ gives $b^5+5b^3-2b^2+4b$, which seems very familiar...
Comment: @Aqua The timestamps should prove that our solutions were discovered independently. :)
Comment: That is not the issue here.
Comment: The same solution as the other one....+1
Comment: @Aqua, then what is the issue?
Comment: There is no issue


Valid placement of pebbles on board. Graph theory problem that everyone in my class got wrong

Question: Can someone please help with this? I've worked on it for a few hours but can't come up with a proof. Thanks!
Consider a $2n\times 2n$ board (namely a board with $2n$ rows and $2n$ columns for a total of $4n^2$ squares) for $n\ge 1$. We place pebbles on squares (at most one per square). The placement of the pebbles ensures that each column and each row contains exactly $n$ pebbles. Consider the coordinates of a placed pebble to be $x : y$, with $x,y \in\{1,2,\ldots,2n\}$, where $x$ is the row number and $y$ is the column number. Show that for any possible valid placement of the pebbles, there is a subset of $2n$ pebbles such that the row numbers are not the same and the column numbers are not the same for any pair of those $2n$ pebbles.
Comment: It's not a good question if you don't provide any context. What have you tried over those several hours? What kind of class is this from? What tools have you learned in that class recently? What happens if you try to apply those tools here?
Comment: Please refer to this thread containing a similar question. https://math.stackexchange.com/questions/3635617/halls-marriage-theorem-2n-rooks-on-2n-times-2n-board?rq=1
Answer: Here's a combinatorial solution with minimal pre-requisites. Suppose that you're given a configuration $A$ of pebbles. Let the rows and columns of the grid both be numbered from $1$ to $2n$. We define the "configuration obtained by swapping columns $c_1,c_2$" as the configuration obtained on moving every pebble at  $(r,c_1)$ for some $r\in\{1,2,\ldots,2n\}$ to the coordinate $(r,c_2)$ and vice versa simultaneously. On a technical note, we don't require $c_1,c_2$ to be distinct. We define configurations obtained by swapping two rows similarly. Observe that we can find a subset of $2n$ pebbles satisfying the given conditions for the given configuration if and only if we can do the same for a configuration obtained by swapping two rows (analogously columns). Inductively, we can find a subset of $2n$ pebbles satisfying the given conditions for the given configuration if and only if we can do the same for a configuration obtained after a series of row swaps and column swaps.
Suppose that we start with an arbitrary configuration $A$ of pebbles. Let $\mathcal{T}$ denote the collection of all configurations obtained by performing series of row swaps and/or column swaps on $A$. For a configuration $B\in\mathcal{T}$, let $d(B)$ denote the greatest natural number $m\leq2n$ such that $B$ has a pebble on each coordinate in the set $\{(j,j)|j\leq m\}$. Let $A'\in \mathcal{T}$ such that $d(A')\geq d(B)$ for all $B\in \mathcal{T}$. Suppose towards contradiction that $d(A')=m<2n$. Unless otherwise mentioned, we shall henceforth work with the configuration $A'$. If there is a pebble on a coordinate in the set $\{(i,j)|m<i,j\leq2n\}$, then define the configuration obtained by swapping rows $i,m+1$ and then swapping columns $j,m+1$ to be $B_1$. Then, $B_1\in \mathcal{T}$ and $d(B_1)\geq d(A')+1$. This is a contradiction. Hence, at each point in the set $\{(i,j)|m<i,j\leq2n\}$ (Marked with a red fill in fig.), there is no pebble (wrt $A'$). Now, consider the $(m+1)^{st}$ row and column. The $n$ pebbles on the $(m+1)^{st}$ row (resp. column) are present on $n$ coordinates in the set $\{(m+1,j)|j\leq m\}$ (resp. $\{(j,m+1)|j\leq m\}$). So, by pigeon hole principle, there exists $x\in\{1,2,\ldots,m\}$ such that there is a pebble at each of the coordinates $(m+1,x),(x,x)$ and $(x,m+1)$. Define $B_2$ to be the configuration obtained by swapping rows $x,m+1$. Now, $B_2\in \mathcal{C}$ and $d(B_2)\geq d(A')+1$. This is a contradiction. Hence, we conclude that $d(A')=2n$. Then the set of pebbles on $\{(j,j)|j\leq 2n\}$ satisfies the given conditions for the configuration $A'$. Thus, a set of $2n$ pebbles satisfying the given conditions in the configuration $A$ also exists as specified earlier.
Comment: I'll add an image soon. Please add a comment if anything is unclear/incorrect.


Detecting TabMove in firefox add-on

Question: Tried out the impl. given in : https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser#Notification when a tab is added or removed
for tracking 'tabmove'. Didn't work.
Would appreciate any help in this regard.
BTW, already tried below code. Only 'TabOpen' event is received. 'TabClose' and 'TabMove' does not work:

var browserWindows = require("sdk/windows").browserWindows;
var activeWindow = browserWindows ? browserWindows.activeWindow : {};
var browserWindow = activeWindow ? require("sdk/view/core").viewFor(activeWindow) : {};
var DOMWindow = browserWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);

var exampleTabAdded = function(event) {
 var browser = DOMWindow.gBrowser.getBrowserForTab(event.target);
 console.log('tab added: '+ event.target);
};
var exampleTabMoved = function(event) {
 var browser = DOMWindow.gBrowser.getBrowserForTab(event.target);
 console.log('tab moved: '+ event.target);
};

function exampleTabRemoved(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  console.log('tab removed: '+ event.target);
}

function exampleTabSelected(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  console.log('tab selected: '+ event.target);
}

var container = DOMWindow.gBrowser.tabContainer;
container.addEventListener("TabMove", exampleTabMoved, false);
container.addEventListener("TabOpen", exampleTabAdded, false);
container.addEventListener("TabClose", exampleTabRemoved, false);
container.addEventListener("TabSelect", exampleTabSelected, false);

Thanks
Comment: That's an xul event, it won't work from sdk without tapping into the xul. Let me check if sdk has equivalent event. edit: there doesnt seem to be one, lets wait to see if the sdk experts have any input on this, otherwise ill show you how to tap into the xul
Comment: Thanks for the quick response. i wouldn't mind using xul within add-on.
Answer: This seems to work. Uses both sdk api's as well as XUL content document.
If there is a better way to handle 'tabmove', please do post the answer.

var tabs = require("sdk/tabs");
var { modelFor } = require("sdk/model/core");
var { viewFor } = require("sdk/view/core");
var tab_utils = require("sdk/tabs/utils");

var contentDocumentMap = new Map();

function mapHighLevelTabToLowLevelContentDocument(tab) {
 var lowLevelTab = viewFor(tab);
 var browser = tab_utils.getBrowserForTab(lowLevelTab);
 return browser.contentDocument;
}

function onOpen(tab) {
 tab.on("pageshow", logShow);
 tab.on("activate", logActivate);
 tab.on("deactivate", logDeactivate);
 tab.on("close", logClose);
}

function logShow(tab) {
 var contentWindow = mapHighLevelTabToLowLevelContentDocument(tab);
 if ((contentWindow.URL === 'about:newtab') || (contentWindow.URL === 'about:blank')) {
  return;
 }
 if (contentDocumentMap.has(contentWindow)) {
  return;
 }
 contentDocumentMap.set(contentWindow, tab.id.toString());
}

function logActivate(tab) {
 var contentWindow = mapHighLevelTabToLowLevelContentDocument(tab);
 if ((contentWindow.URL === 'about:newtab') || (contentWindow.URL === 'about:blank')) {
  return;
 }

 if (contentDocumentMap.has(contentWindow)) {
  return;
 }
 contentDocumentMap.set(contentWindow, tab.id.toString());
}

function logDeactivate(tab) {
 setTimeout(function() {
  var windows = require("sdk/windows").browserWindows;
  for (let window of windows) {
   var activeTabContentWindow = mapHighLevelTabToLowLevelContentDocument(window.tabs.activeTab);
   var activeTabId = window.tabs.activeTab.id.toString();
   if ((contentDocumentMap.has(activeTabContentWindow)) && (contentDocumentMap.get(activeTabContentWindow) !== activeTabId)) {
    console.log('M O V E D. url: '+ window.tabs.activeTab.url);
    console.log('from tabid: '+ contentDocumentMap.get(activeTabContentWindow) + ' to tabid: ' + activeTabId);
    contentDocumentMap.delete(activeTabContentWindow);
    contentDocumentMap.set(activeTabContentWindow, activeTabId);
   }
  }
 }, 150);
}

function logClose(tab) {
 var targetTabId = tab.id.toString();
 setTimeout(function() {
  var windows = require("sdk/windows").browserWindows;
  for (let window of windows) {
   var activeTabContentWindow = mapHighLevelTabToLowLevelContentDocument(window.tabs.activeTab);
   var activeTabId = window.tabs.activeTab.id.toString();
   if (contentDocumentMap.has(activeTabContentWindow)) {
    if (contentDocumentMap.get(activeTabContentWindow) !== activeTabId) {
     console.log('M O V E D. url: '+ window.tabs.activeTab.url);
     console.log('from tabid: '+ contentDocumentMap.get(activeTabContentWindow) + ' to tabid: ' + activeTabId);
     contentDocumentMap.delete(activeTabContentWindow);
     contentDocumentMap.set(activeTabContentWindow, activeTabId);
    }
    else if (targetTabId === activeTabId){
     contentDocumentMap.delete(activeTabContentWindow);
    }
   }
  }
 }, 150);
}

tabs.on('open', onOpen);
Comment: Awesome job there! Very interesting way to do it without using XUL.

Detecting TabMove in firefox add-on


Installing Tensorflow 1.3 (No module named tensorflow)

Question: I am initializing a new VM with Ubuntu 17 on Google Cloud Platform, I then SSH into the newly created VM, upload this script and run it...
#! /bin/bash
sudo apt-get install python-pip
sudo pip install --upgrade pip
sudo pip install https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl

Now, this works for me, when I launch a Python interactive environment
import tensorflow as tf

does not throw an error, however, if I run the same script but replace
tensorflow-0.5.0-cp27-none-linux_x86_64.whl

with
tensorflow-1.3.0-cp27-none-linux_x86_64.whl

I get:
ImportError: No module named tensorflow

... incredibly frustrating, especially since the contrib library doesn't seem to be apart of the 0.5 version... any ideas of what is going on, perhaps how I can first install 0.5 and then upgrade to 1.3 ?
Comment: Just to check -- are both installations part of the same Python? Based on your PIP seems like yes, but just double-checking. Python on GCP Ubuntu defaults to python 2.7, maybe your v1.3 gets installed into Python 3? You could try by using Python3 instead of Python?
Comment: Getting the URL from here: https://www.tensorflow.org/install/install_linux#python_27 but I suppose I can try updating python to 3 and use the other URL.  Will report what happens
Comment: After `sudo apt-get update` and `sudo apt-get install python3.6`, I'm getting this error:

_tensorflow-1.3.0-cp36-cp36m-linux_x86_64.whl is not a supported wheel on this platform._ ... btw, I'm creating an entirely new VM instance to test these configurations so there's no contamination from anything prior to the default OS...
Comment: Ok, I had to get a larger machine type, but first installing 0.5 and then doing `sudo pip install tensorflow --upgrade` and then
`sudo pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/protobuf-3.1.0-cp27-none-linux_x86_64.whl` works
Comment: No i think if you did 2.7 originally it should have been all OK. I haven't tried 1.3 yet, but with all prior versions it used to go very smoothly on GCP.
Comment: I've actually made a copy of the image as a custom image type which makes it super easy next time I create an instance since I can now just skip all of this and the image will already have an up and running version of Tensorflow.
Answer: I also get the same then i tried pip install tensorflow after worked fine


Change Ajax query dataType according to return data

Question: I have ajax method which call a method
 $.ajax({
                    url: "/DeviceUsage/Return",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'HTML',
                    data: JSON.stringify({ dev: { DeviceInstanceId: $('#DeviceInstanceId').val(), UserId: "1", StorageId: $('#StorageId').val() } }),
                    error: function (data) {
                        alert("wystąpił nieokreślony błąd " + data);
                    },
                    success: function (data) {
                        if (data.ok) {
                            $("#Modal").modal('hide');
                            window.location = data.newurl;
                        }
                        else {
                            $('.modal-body').html(data);
                        }
                    }
                })

That method can return HTML Data or JSON data according to if method ended succesfully
 return PartialView(dev)   <=== Html
 return Json(new { ok = true, newurl = Url.Action("MyDevices") });;<=== JSON

But In Ajax datatype I can set only Html or JSON. If I set first the redirect wont work. If json then PartialView wont work. Is there any possibility to dynamically set dataType?
Comment: Hi - is there any way you can tell what it'll be from the frontend before the request is made? I think impossible tbh. unless you change to use something else like a xhttprequest or seomthing there maybe possibility there.. but for $.ajax i think not..
Comment: There is no way to now that before request. The method check user data input and decide if its valid
Answer: try not giving dataType as jQuery tries to determinate correct format for you;

dataType (default: Intelligent Guess (xml, json, script, or html))

if this does not work use html (plain text) just check some keyword in the response data and use the data according to this. For example;
if (data.indexOf("html") > -1) {
   $('.modal-body').html(data);
}
else {
   var objData = JSON.parse(data);
   window.location = objData.newurl;
}


HAProxy directing connections to the correct server

Question: I have two servers behind pfsense haproxy and I need to make sure users land on the same server based on a part of the url.
http://mydomain/<location>/..../....

In my case the  is always the first slash after the domain, so all users with the same  should end up on the same server.
Any suggestions?
Comment: I've tried using Uri (HTTP backends only) hash, and that doesn't seem to work at all for me.
Comment: And just to confirm, you want to balance on the `` portion of your `http://mydomain//..../....` URL?
Comment: Yes, that is correct
Answer: There's no native way to do this, but with a little bit of tinkering it can be made to work.
You'll need to extract the URL path component that you want in the Frontend, and place it in a throwaway header, which will then be used by your Backend to select the server.
Your frontend would look sort of like this:
frontend fe_pfsense
  ...
  http-request set-header X-Location-Path %[capture.req.uri]
  http-request replace-header X-Location-Path ([^/]+)/.* \1
  use_backend be_pfsense
  ...

First we extract the URI and place it in a throwaway header called X-Location-Path.
Then we use a regex to find and capture the first path component, and overwrite it to the same header.
And your backend would look sort of like this:
backend be_pfsense
  ...
  balance hdr(X-Location-Path)
  ...

We use the hdr() balance algorithm to balance based on the path we extracted in the Frontend.
Optionally, I think you could then drop the header before it goes out to the servers with either of the following lines, but you'd want to test this to make sure the order of events works as expected.
http-request del-header X-Location-Path

reqidel ^X-Location-Path:.*

Comment: Thanks GregL, This is pretty much the way we went about this in the end.


Plane cut the cone in perpendicular generators

Question: Question :- Prove that if a plane cut the cone $$ax^2+by^2+cz^2=0$$ in perpendicular generators, it touches the cone $$\frac{x^2}{b+c}+\frac{y^2}{a+c}+\frac{z^2}{a+b}=0$$
In solution :- Consider a plane $$ux+vy+wz=0$$ Now , consider a section of cone and plane is $$\frac{x}{l}=\frac{y}{m}=\frac{z}{n}$$.
Since this lies in cone and plane so must satisfy these equation.Therefore,
$$ul+vm+wn=0, al^2+bm^2+cn^2=0-----(3)$$. These two line are perpendicular if $$u^2(b+c)+v^2(a+c)+w^2(a+b) = 0 ----(4)$$
Here, in this step i got somewhat confused :- $$$$
1.   When we satisfy the cone and plane  equation by replacing with l,m,n in (3), this should just be an equation, then why we are treating as line and work on their perpendicularity.?$$$$
2. From where it hold that if two line are perpendicular $$ul+vm+wn=0, al^2+bm^2+cn^2=0-----(3)$$ then $$u^2(b+c)+v^2(a+c)+w^2(a+b) = 0 ----(4)$$ should be true.?
I never studied such concept. Please clarify it will be a great help.
Comment: $ax^2+b^2+c^2=0$ is the equation of 0, 1, or 2 planes, not a cone.
Comment: Thanks for pointing this out, i have corrected this.
Answer:
Now , consider a section of cone and plane is $$\frac xl = \frac ym = \frac zn$$

That is the equation of a line (passing through the origin), not a section. Note that $x, y, z$ are the variables here. $l, m, n$ are fixed parameters defining which line the equation is for. Further, the values of the parameters $l, m, n$ for a given line are only unique up to a common multiple. I.e., if you multiply all three by the same value, the three new values will still determine the same line.
The same is true of the plane and cone equations: In $$ux + vy + wz = 0$$ $(x,y,z)$ are the coordinates of points on the plane, while $u, v, w$ are fixed parameters determining which plane it is, and are only determined up to a multiple. In $$ax^2 + by^2 + cz^2 = 0$$ $(x,y,z)$ are the coordinates of points on the elliptical cone (cross-sections are ellipses), while $a, b, c$ are parameters defining the cone, and again, are only unique up to a multiple.
All these multiples can be problematic, so I am going to make some additional assumptions:
$$u^2 + v^2 + w^2 = 1\\a^2 + b^2 + c^2 = 1\\l^2 + m^2 + n^2 = 1$$
As long as the parameters are not all $0$ (which would mean you don't actually have a cone, plane, or line) you can always multiply them by a value that makes these equations true. With these restrictions, the only multiplier possible is $-1$. To remove even this possibility, I will also require that $n > 0$.
Now a section of the cone by the plane is not one line, but two lines. That is, there is a line $\frac xl = \frac ym = \frac zn$, and a second line $\frac x{l'} = \frac y{m'} = \frac z{n'}$ which are both contained in the intersection of the plane and the cone. Since $(x,y,z) = (l, m, n)$ is a point on the first line and $(x,y,z) = (l', m', n')$ is a point on the second line, these two points must themselves be in both the plane and the cone:
$$ul + vm + wn = 0\\al^2+bm^2 + cn^2 = 0$$ $$ul' + vm' + wn' = 0\\al'^2+bm'^2 + cn'^2 = 0$$
We solve for $l, m, n$ first. There are three equations in these three unknowns:
$$ul + vm + wn = 0\\al^2+bm^2 + cn^2 = 0\\l^2+m^2 + n^2 = 1$$
If we solve the first for $l$ and substitute in the other two:
$$(bu^2 + av^2)m^2 + 2avwmn + (cu^2 + aw^2)n^2 = 0\\(u^2 + v^2)m^2 + 2vwmn + (u^2 + w^2)n^2 = u^2$$
Letting $r = \frac mn$, we can rewrite the equations
$$(bu^2 + av^2)r^2 + 2avwr + (cu^2 + aw^2) = 0\\(u^2 + v^2)r^2 + 2vwr + (u^2 + w^2) = u^2n^2$$
The first equation is a quadratic in $r$ with solutions
$$r = \frac{-avw \pm u\sqrt{-(bcu^2 +abw^2 + acv^2)}}{bu^2 + av^2}$$
Once $r$ is determined, we can find the values of $l, m, n$:
$$n = \sqrt{\frac{(u^2 + v^2)r^2 + 2vwr + (u^2 + w^2)}{u^2}}\\
m = rn\\
l = -\frac {vm + wn}u$$
Now there are two choices for $r$. One gives $l,m,n$, the other gives the other line $l', m', n'$

These two line are perpendicular if $$u^2(b+c)+v^2(a+c)+w^2(a+b)=0−−−−(4)$$

The two lines will be perpendicular if $$ll' + mm' + nn' = 0$$ (Since $l^2 + m^2 + n^2 = 1$ and $l'^2 + m'^2 + n'^2 = 1$, you can show that $ll' + mm' + nn'$ is the cosine of the angle between the two lines. When they are perpendicular, that angle is $\pi/2$, and the cosine is $0$.)
If you plug in the expressions for $l, m, n, l', m', n'$ above and do a lot of simplification, the claim is that the result will be
$$u^2(b+c)+v^2(a+c)+w^2(a+b)=0$$
This a condition that the plane $ux + vy + wz = 0$ and cone $ax^2 + by^2 + cz^2 = 0$ must satisfy if their intersection is going to consist of perpendicular generators, instead of generators meeting in some other angle.
(The fact that it requires so much tedious algebra means that this was not the best way to produce this result. You will find that pretty much every difficult calculation you encounter in mathematics can be reduced to something relatively trivial, if only you knew the right way to look at it. Alas, the right way to look at it usually only becomes apparent months or years after you've performed the calculation.)


Custom validation error template not respecting ZIndex

Question: I have a view defined as a DataTemplate (for an "OrderEntryViewModel") with a Menu, ContentPresenter, and Expander inside of a 3-row grid. The content of the ContentPresenter is binded to another viewModel "OrderViewModel" (for which there's another DataTemplate-defined view). The expander has a ZIndex of 99, so that when it expands UP, it expands OVER any other controls (i.e. the ContentPresenter).
This all works as expected EXCEPT when the ContentPresenter's content (the OrderViewModel) has data errors...My OrderView displays a custom validation error template around controls with invalid data. What happens is, when I expand the expander, all of controls inside the ContentPresenter are covered, but the red border and exclamation point I show are still visible through the expander! I've verified that my expander's ZIndex is 99 and the ContentPresenter's is 0. Can anyone help me with this?
Here's some images to help explain:
First Image shows what the views look like when NOT expanded.
Second Image shows what the views look like when I expand.
I define the validation error template like this:
<ControlTemplate x:Key="ValidationErrorTemplate">
    <DockPanel LastChildFill="true">
        <Border Background="Red" DockPanel.Dock="right" Margin="5,0,0,0" Width="10" Height="10" CornerRadius="5"
                ToolTip="{Binding AdornedElement.(Validation.Errors).CurrentItem.ErrorContent, ElementName=customAdorner}">
            <TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" FontWeight="Bold" Foreground="White"/>
        </Border>
        <AdornedElementPlaceholder x:Name="customAdorner" VerticalAlignment="Center">
            <Border BorderBrush="red" BorderThickness="1" />
        </AdornedElementPlaceholder>
    </DockPanel>
</ControlTemplate>

And assign it to a specific control like this (this is how I do it for my TextBox):

</Style>

Answer: This solution worked for me...just added an AdornerDecorator at the same level as my expander, so now, the controls inside of the AdornerDecorator use that layer to display instead of the top level layer in the window


Turn off the prompts of display large color blocks in emacs

Question: I am working python project on emacs and encounter such a problem

The annoying color blocks.
The flycheck, flymake and flycheck had all been turned off.
How could let the color blocks go?
It's displayed finely from vscode..
Comment: Trailing spaces highlighted?
Comment: oh, thank you, I searched just now, and it is spaces highlighted.
Comment: Could you please transmit the short comment to answer. @AlexKroll
Answer: Set the variable show-trailing-whitespace to nil.
In fact, that's the default value for that variable, so there might be a line in your init file that sets it to t.


AR(1) with known initial and terminal condition: how to draw the innovations?

Question: Suppose I have the following stationary $AR(1)$ process:
$$ y_{t}=\alpha_{0}+\alpha_{1}y_{t-1} + u_{t} $$
where $u_{t} \sim \mathbb{N}(0,\sigma^{2})$, with $\sigma^{2}$ known. Suppose I have an initial condition $y_{1}$ and terminal condition $y_{T}$ and I would like to simulate my process for the periods in the interim, i.e $t = 2,\dots,T-1$. After substituting recursively, I can write the final term $y_{T}$ as
$$ y_{T} = \alpha_{0} \left(\frac{1-\alpha_{1}^{T-1}}{1-\alpha_{1}} \right) + \alpha_{1}^{T-1}y_{1} + \sum_{t=0}^{T-2} \alpha_{1}^{t}u_{T-t}  $$
Since $y_{T}$ and $y_{1}$ are known, this suggests that the sum of the innovations should equal
$$ \sum_{t=0}^{T-2} \alpha_{1}^{t}u_{T-t} =  y_{T} - \alpha_{0} \left(\frac{1-\alpha_{1}^{T-1}}{1-\alpha_{1}} \right) - \alpha_{1}^{T-1}y_{1}    $$
Now, my question is what is the correct way to draw the sequence of $u_{t}$ knowing that they are $iid$ and unconditionally distributed as a $\mathbb{N}(0,\sigma^{2})$.
The way I am trying to approach this problem is following the comment of @soakley on this post Sample random variables conditional on their sum . However, I am not sure about the proper iterative procedure.
Clearly, I could treat the $\alpha_{1}^{t}$ as weights. But I am still confused. The way I proceed is as follows:
0) Define $z_{2}=y_{T} - \alpha_{0} \left(\frac{1-\alpha_{1}^{T-1}}{1-\alpha_{1}} \right) - \alpha_{1}^{T-1}y_{1}$
1) Draw $u_{t}\sim \mathbb{N}\left( \frac{z_{t}}{T-t+1},\frac{T-t}{T-t+1} \sigma^{2} \right)$ for $t \in [2,T-1]$
2) In each step update $z_{t}$ as follows
$$ z_{t+1} = z_{t} - \alpha^{T-t} u_{t} $$
3) Let $u_{T} = z_{T}$
I would really like to know if this procedure is correct.
Comment: Hi: are you missing a lagged $y_t$ in the first equation because, as it stands, that's not AR(1) process. If so, it's an interesting problem but I wanted to make sure of that first before I thought about it. thanks.
Comment: also, are $\alpha_0$ and $\alpha_1$ known parameters ?
Comment: @mlofton yes,  I am really sorry. It was a typo. I am assuming I know the parameters $\alpha_{0}$ and $\alpha_{1}$ as well.
Comment: This reminds me of an interpolating technique called 'Kriging', which is also often called a 'Gaussian process'. Might be interesting to look that up.
Answer: Since the overarching goal here is to generate the $\text{AR}(1)$ series values, I will show you how you can generate these directly, rather than via the error terms.  (The method of generating the error terms is very similar.)  The way to do this is to write out the multivariate normal distribution for the process and then use the rules for the conditional distribution for a multivariate normal.  I will use more standard notation by using the form:
$$Y_t = \mu + \phi (Y_{t-1} - \mu) + u_t
\quad \quad \quad
u_t \sim \text{IID N}(0, \sigma^2).$$
The stationary form of this model is for vectors of $y_i$ values to be distributed by a multivariate normal distribution, with variance matrix determined by the auto-covariance function of the process.  Thus, when you want conditional distributions, you can use standard results for conditioning in the multivariate normal distribution.

Conditional distribution given endpoints: The auto-correlation function for the $\text{AR}(1)$ process above is:
$$\rho(t) = \frac{\phi^t}{1-\phi^2}
\quad \quad \quad
\text{for } t \in \mathbb{Z}.$$
Thus, the marginal distribution of the vector $\mathbf{Y} = (Y_0,...,Y_T)$ is:
$$\mathbf{Y} \sim \text{N} \Bigg( \mu \mathbf{1}, \sigma^2 \mathbf{\Sigma}(\phi) \Bigg)
\quad \quad \quad
\mathbf{\Sigma}(\phi) \equiv \frac{1}{1-\phi^2} \begin{bmatrix}
1 & \phi & \phi^2 & \cdots & \phi^T \\
\phi & 1 & \phi & \cdots & \phi^{T-1} \\
\phi^2 & \phi & 1 & \cdots & \phi^{T-2} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
\phi^T & \phi^{T-1} & \phi^{T-2} & \cdots & 1 \\
 \end{bmatrix}.$$
To obtain the conditional distribution of interest, we decompose the random vector $\mathbf{Y}$ as:
$$\mathbf{y} = \begin{bmatrix} \mathbf{Y}_\text{INT} \\ \mathbf{Y}_\text{END} \end{bmatrix},$$
where $\mathbf{Y}_\text{INT} = (Y_1,...,Y_{T-1})$ and $\mathbf{Y}_\text{END} = (Y_0,Y_T)$.  We likewise decompose the mean vector and variance matrix as:
$$\mu \cdot \mathbf{1} = \begin{bmatrix}
\mu \cdot \mathbf{1} \\
\mu \cdot \mathbf{1}
\end{bmatrix}
\quad \quad \quad
\mathbf{\Sigma}(\phi) = \begin{bmatrix}
\mathbf{\Sigma}_\text{INT}(\phi) & \mathbf{\Sigma}_\text{CROSS}(\phi) \\
\mathbf{\Sigma}_\text{CROSS}(\phi)^\text{T} & \mathbf{\Sigma}_\text{END}(\phi)
\end{bmatrix},$$
where the mean vectors are of appropriate lengths and the variance parts are:
$$\begin{aligned}
\mathbf{\Sigma}_\text{INT}(\phi)
&\equiv \frac{1}{1-\phi^2} \begin{bmatrix}
1 & \phi & \phi^2 & \cdots & \phi^{T-2} \\
\phi & 1 & \phi & \cdots & \phi^{T-3} \\
\phi^2 & \phi & 1 & \cdots & \phi^{T-4} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
\phi^{T-2} & \phi^{T-3} & \phi^{T-4} & \cdots & 1 \\
 \end{bmatrix}, \\[30pt]
\mathbf{\Sigma}_\text{CROSS}(\phi)
&\equiv \frac{1}{1-\phi^2} \begin{bmatrix}
\phi & \phi^{T-1} \\
\phi^2 & \phi^{T-2} \\
\phi^3 & \phi^{T-3} \\
\vdots & \vdots \\
\phi^{T-1} & \phi \\
 \end{bmatrix}, \\[30pt]
\mathbf{\Sigma}_\text{END}(\phi)
&\equiv \frac{1}{1-\phi^2} \begin{bmatrix}
1 & \phi^{T} \\
\phi^{T} & 1 \\
 \end{bmatrix}. \\[6pt]
\end{aligned}$$
Now, using the conditional density rule for the multivariate normal distribution, we have:
$$p(\mathbf{y}_\text{INT}| \mathbf{y}_\text{END}) = \text{N}(\mathbf{y}_\text{INT}| \boldsymbol{\mu}_*, \boldsymbol{\Sigma}_*),$$
where:
$$\begin{equation} \begin{aligned}
\boldsymbol{\mu}_* &\equiv \mu \cdot \mathbf{1} + \boldsymbol{\Sigma}_\text{CROSS}(\phi) \boldsymbol{\Sigma}_\text{END}(\phi)^{-1} (\boldsymbol{y}_\text{END} - \mu \cdot \mathbf{1}), \\[8pt]
\boldsymbol{\Sigma}_* &\equiv \boldsymbol{\Sigma}_\text{INT}(\phi) - \boldsymbol{\Sigma}_\text{CROSS}(\phi) \boldsymbol{\Sigma}_\text{END}(\phi)^{-1} \boldsymbol{\Sigma}_\text{CROSS}(\phi)^\text{T}. \\[6pt]
\end{aligned} \end{equation}$$
This gives you the conditional distribution of the observable values in the process.  If you particularly want the error terms, you can extract them from the observed values using the recursive equation for the process.
Comment: So I think you're saying that $y_T$ will satisfy the AR(1) relationship at the top of your explanation  when using your approach. If so, then I believe you but I don't see it. That's okay ( there are many things I don't understand and live with :) ) and thanks for explaining.
Comment: I wrote an R program to simulate your solution and that really helped me to see what's going on. They can satisfy the recursive relationships because of the $\epsilon$ terms which is really where all the auto-correlation stems from in the first place. I will post the code in an "answer" in case anyone wants it. It's useful for seeing what actually happens when Ben's algorithm is used. Thanks Ben for your help and patience.
Comment: Ben: This is interesting but if he wants the terminal condition to be $Y_T$, how can there be a distribution ? Doesn't one need a deterministic condition to be sure that one ends up at $Y_T$ ? Thanks.
Comment: This method gives the conditional distribution of $\mathbf{y}_\text{INT} = (y_1,...,y_{T-1})$ conditional on $y_0$ and $y_T$.  So the latter values can be any conditioning values entered by the user.  The endpoints are fixed, but the interior points between them are still random.
Comment: It's definitely possible that I mis-interpreted the question. I took it that one has the values of $y_{0}$ and $y_{T}$ and the question is:  what do the noise terms between $t=1$ and $t=(T-1)$ need to be in order to ensure that the path of  $y$ ends up at the value $y_{T}$. My answer was generate the noise terms from $t=2$ to $t=T-1$ as $Normal(0, \sigma^2)$. Then, set $\epsilon_{T}$ to the function in the answer. This will ensure that $y$ reaches $y_T$ at time $t=T$. But what you did is pretty different and interesting. No idea whose interpretation is correct.  Thanks.
Comment: Your interpretation is correct, but unfortunately your method is wrong.  Once you condition on $y_0$ and $y_T$, the error terms between these values are no longer independent, so it is not legitimate to generate them independently.  The method I use bypasses the errors and generates $y_1,...,y_{T-1}$ directly, but you could certainly extract the error terms from the observed values if that is preferred.
Comment: But I don't see how you can ensure consistency in your model.  If $y_{T} -\mu = \phi \times (y_{T-1} - \mu) + \epsilon_{T}$ and $y_{T}$ is known and fixed, then $\epsilon_{T}$ needs to be fixed and not an RV ? Essentially, it needs to be a function of your $Y_{INT}$.
Comment: Oh, note that I am not conditioning on $Y_{T}$. I'm describing what $\epsilon_{T}$ needs to be in order to be sure that one ends up at the value $Y_{T}$. A totally different question from yours. Maybe the OP can tell us whose interpretation was correct. Thanks for interesting derivation.
Comment: But since $\mathbf{y}_\text{INT}$ is random, the error term $u_t$ is also random (since it depends on the former.
Comment: Hi Ben: Not to beat a dead-horse but if $Y_T$ is supposed to be some known value and also be consistent with your equation for the AR(1), how can that be guaranteed if $Y_{INT}$ is random. There has to be something that's deterministic in order to A) obtain the value of  $Y_T$ at time $t = T$ and B) have $Y_T$ adhere to the AR(1) relation. Essentially, if $\epsilon_T$ is random, then one can't guarantee A) and B)
Comment: That is not correct --- all of the error terms are still (marginally) random, but they are now constrained by two linear equations.  The error term $u_t$ is only determined if we condition on both $y_T$ and $y_{T-1}$.
Comment: (An analogy would be if you said you have random variables $x_1,...,x_{10}$ with known sample mean $\bar{x} = 6$.  Conditional on that information, each of the values is still random, but once you specify any nine of them, the last one becomes determined.)
Comment: I'm not saying your wrong but note that, when you do your derivation, you're only assumption is multivariate normality and the correct and derived cov matrix.  There is nothing in there that restricts the sequence of $Y_t$. By this, I mean, that the conditional mean and variance relationships are preserved  but there's nothing in there saying that the  AR(1) process itself has to be ensured at each time $t$. This is why I don't see why the AR(1) relation itself will end up holding at each  $t$. But that's okay. We don't have to discuss this anymore and I appreciate your patience.
Comment: No problem --- I think your misgivings here come from that last point.  In fact, the specification of the multivariate normal joint density does satisfy the underlying reqursive equation for AR(1) (i.e., the error terms induced by this distribution can be shown to be IID normal).  The distribution I have specified is the stationary distribution for the Gaussian AR(1) process.
Comment: It's easier if I attached the R code but I can't find the way to include an attachment. thanks for any pointers.
Comment: @mlofton: Note on your answer with the R code (presently hidden).  You can display R code properly by adding four spaces prior to each code line.  You should also add a ```#``` at the start of each comment line so that the R processor does not read it.  I have taken the liberty of editing your answer to make these changes.
Answer: Here is my revised and (hopefully) final  attempt.
Suppose we have the AR(1) process: $y_{t}= \alpha \times y_{t-1} + \epsilon_t$ and we know $y_1$ and $y_{T}$ and want to figure out the innovations that will start at $t = 2$ and bring us to $y_{T}$.
So, suppose that there is an innovation at time $t = 2$ and it is $\epsilon_{2}$ and similarly a new $\epsilon_{3}$ at $t= 3$ and
the same thing upto and including $t = {T-1}$.
Then, what will this result in as far as $y_{2}, y_{3}, \ldots y_{T-1}$.
Well, then we have ( don't ask what I was doing in my earlier attempts ):
$y_{2} = \alpha \times y_{1} + \epsilon_{2} $
$y_{3} = \alpha^2 y_{1} + \alpha \times \epsilon_{2}  +  \epsilon_{3} $
$y_{4} = \alpha^3 y_{1} + \alpha^2 \times \epsilon_{2} + \alpha \epsilon_{3} + \epsilon_{4} $
So, at time $t={T-1}$, we have
(1) $y_{(T-1)} =  \alpha^{T-1} y_{T} +  \sum_{i=2}^{T-1} \epsilon_{i} \alpha^{T-i}$
But, since $y_{T} = \alpha \times y_{T-1} + \epsilon_{T}$, this leads to
(3) $ y_{T} =  \alpha^{T} y_{1} +  \alpha \sum_{i=2}^{T-1} \epsilon_{i} \alpha^{T-i} + \epsilon_{T}$
Notice that the last term is obtained by taking the term at time t=T out
of the summation. This makes it very easy to solve for $\epsilon_{T}$ algebraically which leads to:
(4) $\epsilon_{T} = y_{T} - \alpha^{T} y_{1} -  \alpha  \sum_{i=2}^{T-1} \epsilon_{i} \alpha^{T-i}$.
Everything on the RHS of (4) is known which means that $\epsilon_{T}$ is
a function of variables whose values are all known at time $t = T$.
And my sincere apologies for all the noise and mistakes. Your expressions were totally correct so maybe the procedure that you describe and the one I desribe here are equivalent ? I would think that the values of $\epsilon_{t}$ from $t=2$ to $t=T-1$ can be anything as long as $\epsilon_{T}$ is the deterministic function of them given by (4). But I've lost all confidence in my ability to solve this problem correctly so correct me if you're thinking is different. :).
Comment: @Maney: I made another mistake during my second attempt so I'm gonna to post a new answer and then delete the other ones. Man, mistakes can really be wrong :).  My apologies.
Answer: Use the rGARMA function in the ts.extend package
(Note: This answer augments my other theory-based answer, the method for which has now been programmed into the present package.)
You can generate random vectors from the marginal or conditional distributions of any stationary Gaussian ARMA model using the ts.extend package.  This package generates random vectors directly form the multivariate normal distribution using the computed autocorrelation matrix for the random vector, so it gives random vectors from the exact distribution and does not require "burn-in" iterations.  It also allows you to impose conditioning values and in this case the package generates from the resulting conditional distribution.
Here is an example from an $\text{AR}(1)$ model where you generate values at the terminal points at either end of the process.  (Here I will use a model with parameters $\alpha_0 = 0$, $\alpha_1 = 0.4$ and $\sigma=1$.  I will generate twelve random vectors from this model each with $m=30$ points with terminal conditioning points $y_1=-3$ and $y_m=3$.)
#Load the package
library(ts.extend)

#Set parameters
AR <- 0.4
m  <- 30
y1 <- -3
ym <- 3

#Set the conditioning vector
CONDVALS    <- rep(NA, m)
CONDVALS[1] <- y1
CONDVALS[m] <- ym

#Generate n = 12 random vectors from this model
set.seed(1)
SERIES <- rGARMA(n = 12, m = m, ar = AR, condvals = CONDVALS)

#Plot the series using ggplot2 graphics
library(ggplot2)
plot(SERIES)

As you can see from the image below, each of the plots shows a time-series vector that has the stipulated starting and ending points.  The interior points are generated from the conditional distribution for the process.  As you can see in the code, the syntax for this is quite simple --- all you need to do is to create the vector CONDVALS with the stipulated conditioning values and add this as an argument for the function.


Using views to display KML of each node in respective maps for each node

Question: I have been using OpenLayers and Geofield to try display the custom data layer (KML polygon) on the. First of all I havent been successful at it despite trying out many mays. Also I realized that the views approach discussed almost everywhere would show the custom maps on a 'new' Page or a 'new' block. But what I want is to show the map with the KML data layer right at each node.
Is this ever possible using Views (Data layer) + Openlayer + geofield in first case?
If so, how do I configure the geofield's map which is displayed in each node?
Answer: If I understand you correctly, your question is how to attach a view to a node.
You can check out the EVA module:

"Eva" is short for "Entity Views Attachment;" it provides a Views
  display plugin that allows the output of a View to be attached to the
  content of any Drupal entity. The body of a node or comment, the
  profile of a user account, or the listing page for a Taxonomy term are
  all examples of entity content.

or this other question: Attach a view to a specific node
Comment: Could you expand this a little bit to explain how this would work with these modules?


Is it possible to replace html outside form with ajax?

Question: Is it possible to replace a
 outside form with ajax on select element?
I am having some difficulties, when Drupal generates new content it wraps my HTML with
 and I don't know why.
This is my form element.
$form['select_element'] = array(
'#type' => 'select',
'#title' => t(''),
'#options' => array(1 => 'Test 1', 2 => 'Test 2'),
'#ajax' => array(
  'callback' => 'ajax_callback',
  ),
);

This is my callback function.
$output = theme('custom_theme_function', array('test_param' => 11,));
$commands[] = ajax_command_replace("#div-id", $output);
return array('#type' => 'ajax', '#commands' => $commands);

Answer: This due to this part of ajax.js
// We don't know what response.data contains: it might be a string of text
// without HTML, so don't rely on jQuery correctly iterpreting
// $(response.data) as new HTML rather than a CSS selector. Also, if
// response.data contains top-level text nodes, they get lost with either
// $(response.data) or $('

').replaceWith(response.data).
var new_content_wrapped = $('

').html(response.data);
var new_content = new_content_wrapped.contents();

// For legacy reasons, the effects processing code assumes that new_content
// consists of a single top-level element. Also, it has not been
// sufficiently tested whether attachBehaviors() can be successfully called
// with a context object that includes top-level text nodes. However, to
// give developers full control of the HTML appearing in the page, and to
// enable Ajax content to be inserted in places where DIV elements are not
// allowed (e.g., within TABLE, TR, and SPAN parents), we check if the new
// content satisfies the requirement of a single top-level element, and
// only use the container DIV created above when it doesn't. For more
// information, please see http://drupal.org/node/736066.
if (new_content.length != 1 || new_content.get(0).nodeType != 1) {
  new_content = new_content_wrapped;
}

This ensures that text nodes are not lost when replacing contents. The second parts of the script checks if the data sent is a single top-level HTML node, and if not, wraps it in a

Back to your problem, the solution is to make sure that theme('custom_theme_function', array('test_param' => 11,)) returns your content in a single HTML node (div, span, ul, li... as long as it is single)


PHP, Tokenizer, find all the arguments of the function

Question: Help me find all the arguments of the function "funcname" using the function token_get_all() in the source code. It sounds simple, but there are many special options, such as arrays as parameters or call static methods as parameters. Maybe there's a simple universal solution?
UPD:
I need the function arguments passed when you call it. Get them to be at an external analysis of the file. For example, there is a php-file:
<?php
funcname('foo');
funcname(array('foo'), 'bar');

The analyzer should begin as follows:
$source = file_get_contents('source.php');
$tokens = token_get_all($source);
...

As a result, need to get a list like this:
[0] => array('foo'),
[1] => array(array('foo'), 'bar')

Comment: Hi Anton,  I have a similar issue for static analysis of localisation functions.  Did you ever find a solid solution to this?
Comment: Does PHP-Parser ( https://github.com/nikic/PHP-Parser ) can help?
Answer: Rather than using a tokenizer, use reflection. In this case, use ReflectionFunction:
function funcname ($foo, $bar) {

}

$f = new ReflectionFunction('funcname');
foreach ($f->getParameters() as $p) {
    echo $p->getName(), "\n";
}

This outputs
foo
bar

You can also use this class and related classes (such as ReflectionParameter) to find out more information about a function and its parameters, such as whether a parameter is optional and what its default value is.
Comment: Thank you. I incorrectly described the problem, updated the topic.


Methods for modelling distributions?

Question: As predictor X I have particle size distributions

and I would like to run a model y ~ X.
I.e. each trial has a response y of size N and a predictor X of size N*M.
The easy way would be to get some quartiles from each distribution and run a model y ~ X[q10] + X[q50] +X[q90].
However, I would prefer to do something with the whole distribution and not with summaries. So I was wondering what modelling methods I could try,

Functional Data Analyses ("easy" and hopefully useful model for this problem)
A Bayesian model. But in this case I don't know how to fit the distributions as data in a model.

To recap my question is,

What methods can I use to model predictors which are distributions?
In a Bayesian framework how can I feed distributions as data?

Thanks
Answer: A possible option might be to consider each of the vectors corresponding to a single observation of a distribution as independent observations coming from the same distribution f and then model, not just the mean as usual in a regression setting, but all the parameters required to characterize the assumed distributional form using something like brms, that estimates distributional models: https://cran.r-project.org/web/packages/brms/vignettes/brms_distreg.html. I guess you could have a hierarchical model to account for the fact that you are liteally estimating as many distributions as sets of observations, and you could have the parameters of a "parent" distribution being themselves characterized by distributions and you just observe the "sons" of this "parent" distribution, say. Note this could get quite complicated very quickly though! But maybe there are methods to do exactly what you want that I am not aware, since this is really not my area of expertize, what I have suggested here is to think about the problem in a different way. And... I'm not really sure whether this is cheating a bit because note it assumes you treat the data from each vector as independent observations of some distribution f while in the case of particle size distributions the data, being proportions of a total, are not really independent observations from any given family. In that case, an interesting distribution to consider might be a  Dirichelet, which has exactly that property of having K classes and the sum of the probabilities in each class adding to 1: https://builtin.com/data-science/dirichlet-distribution. An interesting plot with visualizations of a K=3 class Dirichelet distribution is here. I guess in your case you want a considerably higher K. Any way, more that a definitive answer, food for thought.

Methods for modelling distributions?


Gravar na Base de Dados ao término de leilão

Question: Eu estou a desenvolver um site de leilões em ASP.NET MVC4 e EF, neste momento já efectua licitações e tem um cronômetro de tempo.
O problema agora é: como eu faço para gravar os dados quando o tempo termina? Já pensei em fazer um trigger na BD, mas penso que não irá resultar.
Penso que terei de ter no servidor IIS um script que detecta que o tempo terminou e grava os dados na BD, mas como faço isto?
Eu tenho o temporizador em JavaScript:

Comment: Não é melhor temporizar por JavaScript e enviar uma requisição Ajax?
Comment: Eu tenho o temporizador em JavaScript.
Answer: Na documentação do jQuery Countdown, há um parâmetro chamado expiryUrl. Ele pode ser usado para fazer uma requisição Ajax para algum Controller seu.

Aí é só criar a Action no Controller:
public JsonResult ActionAposExpirarTempo(String parametro) {
    // Faça alguma coisa aqui relacionada com a sua lógica

    return Json(new { status = "Ok"}, JsonRequestBehavior.AllowGet);
}

É só um exemplo. Ela não necessariamente precisa devolver um JSON.
Comment: Entendi a sua resposta, mas como faço que esse método seja executado quando o cronometro chegue a zero sem haver uma iteração do utilizador com os site?
Comment: Ele decresce sozinho, não?


django site administration (entering fixtures data)

Question: I have a django site. a snippet of myapp/models.py looks like this:
class Continent(models.Model):
    name = models.CharField(max_length=128, db_index=True, unique=True)

class GeographicRegion(models.Model):
    continent = models.ForeignKey(Continent, null=False)
    name =  models.CharField(max_length=128, null=False)

When I am attempting to add new geographic regions, when I click the drop down list (select control) to choose a continent, the only values (options) in the drop down list are:
continent object
continent object
continent object
continent object
continent object
continent object

I was expecting to see the names of the continents instead, so I could create relevant geographic regions per continent. How do I get the name to show in the list instead of 'continent object'?
Hint: i added str(self) and repr(self) methods to my ContinentAdmin model in myapp/admin.py like this:
myapp/admin.py
 58 class ContinentAdmin(admin.ModelAdmin):
 59    def __repr__(self):
 60        return self.name
 61
 62 admin.site.register(Continent,ContinentAdmin)

, however this had no (observable) effect
Answer: You need to define __unicode__ method in model:
def __unicode__(self):
  return self.name

Comment: @skyeagle it all is documented here: http://docs.djangoproject.com/en/dev/ref/contrib/admin/ I believe youre looking for list_display option for AdminModel
Comment: Yup, that seems to have done the trick. Where is this documented? - so I can book mark it. Also, is there anyway I can display the id of the object 9as stored in the database), without having to look directly at the database?


Pandas fillna by "join" of another df?

Question: I have 2 DFs, one with IDs and one with entries. Basically:
ID    Val
1     111
2     222
3     333

And another one where some of the Vals are missing:
ID    Val   Other
1     111   123
1     NaN   3
1     111   5
2     222   3553
2     NaN   58
2     222   321
3     NaN   456

What I'd like to do is to fill the missing values in Val on the second df with the Val values in the first df. So the outcome should be:
ID    Val   Other
1     111   123
1     111   3
1     111   5
2     222   3553
2     222   58
2     222   321
3     NaN   456

How can I achieve this? I've seen a similar use case but from within the same df. When I try this, I get an error bc. the dimensions of my df are mismatched of course.
So the question is, how can I fill my NaN values by a "join"?
Comment: You don't need the first dataframe, if the values are sorted by ID in the second, just do `df.ffill()`
Comment: @Ite__ you should provide **all** information from the beginning, anyway, check my current updated answer it works with both dfs
Comment: Is `ID` index or a column?
Comment: @mozway But what if he has `NaN` in the first (or only) row of the`ID`?
Comment: @Aryerez it's a column!
Comment: @mozway yes I do, there are some cases where th Val is not present in the second df at all.
Comment: @Ite__ then `df2.groupby('ID').transform('first')`
Comment: @mozway okay for the third time:  This does not take into account the case where the first or only Val is NaN in the second df. Neither ffill nor bfill accounts for that case.
Answer: Assuming your dataframes are df1 and df2:
df2.groupby('ID').apply(lambda s: s.fillna(df1.set_index('ID')['Val'][s.name]))

output:
     Val  Other
0  111.0    123
1  111.0      3
2  111.0      5
3  222.0   3553
4  222.0     58
5  222.0    321

Comment: @ThePyGuy This still does not take into account the case where the only Val is NaN in the second df.
Comment: This does not take into account the case where the first or only Val is NaN in the second df.
Comment: I think you need both `ffill` and `bfill`
Comment: @lte__, I think this answer can still be used, all you need to do is to separate out the rows that don't meet your criteria, and then concatenate later.
Answer: Solution 1:
You can merge and use np.where:
vals = df2.merge(df1, on=['ID'], how='left', suffixes=['_',''])['Val']
df2['Val'] = np.where(df2['Val'].isna(), vals, df2['Val'])

Speed: 1.87 ms ± 29.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Solution 2:
Create a mapping-dictionary and map the values to the ID.
dct = df1.set_index('ID').to_dict()['Val']
df2.loc[df2['Val'].isna(), 'Val'] = df2['ID'].map(dct)

Speed: 1.94 ms ± 66.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Sample data:
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'ID': {0: 1, 1: 2}, 'Val': {0: 111, 1: 222}})
df2 = pd.DataFrame({'ID': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2}, 'Val': {0: 111.0, 1: np.nan, 2: 111.0, 3: 222.0, 4: np.nan, 5: 222.0}, 'Other': {0: 123, 1: 3, 2: 5, 3: 3553, 4: 58, 5: 321}})

Output:
   ID    Val  Other
0   1  111.0    123
1   1  111.0      3
2   1  111.0      5
3   2  222.0   3553
4   2  222.0     58
5   2  222.0    321

Comment: @mozway, thanks and same for your answer.
Answer: You can merge the first df into the second, and than use combine_first to fill the NaNs:
df2 = df2.merge(df1.rename({'Val': 'TrueVal'}, axis=1), how='left')
df2['Val'] = df2['Val'].combine_first(df2['TrueVal'])
df2.drop('TrueVal', inplace=True)

Answer: Test data:
import numpy as np
import pandas as pd

    a = pd.DataFrame({"ID": {0: 1, 1: 2}, "Val": {0: 111, 1: 222}})
    b = pd.DataFrame(
        {
            "ID": {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2},
            "Val": {0: 111.0, 1: np.NaN, 2: 111.0, 3: 222.0, 4: np.NaN, 5: 222.0},
            "Other": {0: 123, 1: 3, 2: 5, 3: 3553, 4: 58, 5: 321},
        }
    )

Then I just use merge:
b.merge(a, on="ID")

Output:
   ID  Val_x  Other  Val_y
0   1  111.0    123    111
1   1    NaN      3    111
2   1  111.0      5    111
3   2  222.0   3553    222
4   2    NaN     58    222
5   2  222.0    321    222

Clean up the dataframe with:
c = b.merge(a, on="ID").drop("Val_x", axis=1).rename(columns={"Val_y": "Val"})

Comment: This also works with your updated example. And I guess you expect the last row ID=3 the Val to be 333?

Pandas fillna by "join" of another df?


Why is my self-signed wildcard certificate not working?

Question: I have successfully created and used a self-signed certificate on my development machine (IIS 7.5  - Windows 7).
To do this I generated a self signed cert with a common name (CN) = app.localhost and imported it into the Trusted Root Certification Authorities store. I then imported the same cert into IIS and bound it to my site with a Host Name = app.localhost.
This worked fine.
Now I am developing an api that runs under api.localhost. This too needs SSL. So I created a new self-signed cert as before except I specifed a CN = *.localhost. The new cert was added to the Trusted Root Certification Authorities store and imported into IIS as before. Both sites (app.localhost & api.localhost) were successfully bound to the wildcard cert.
This did not work.
Chrome complains with:

You attempted to reach api.localhost, but instead you actually reached
  a server identifying itself as *.localhost.

IE makes a similar complaint.
How do I make a self-signed wildcard certificate that works?
Answer: Wildcard certificate for top-level domains aren't allowed by typical browsers for reasons that should be quite obvious if you think about it.
Comment: Use something like `*.myapp.dev`
Comment: Thanks for the advice. Can you provide any details how I would go about creating the type of wildcard certificate I need?
Answer: As mentioned by David Schwartz this doesn't work for Top Level domains. However it works for any domain below that.
To my c:\windows\system32\drivers\etc\hosts file I added
127.0.0.1 mysitename.localhost.dev

Here .dev is the top level, so I can issue a wildcard to *.localhost.dev
I haven't done this with IIS but this works fine using apache and specifying
<VirtualHost *:80>
    DocumentRoot C:/xampp/htdocs/hookd/mysite/public
    ServerName mysitename.localhost.dev
</VirtualHost>

Unfortunately you'll have to setup a new entry in hosts and in the apache config for each site but it's a lot easier than signing a new certificate.


$n! > (n/e)^{n}$ for all $n \geq 1$ by induction

Question: I am stuck on this problem at the last part of the $p = n+1$ step.
For $n = 1$ we get $1! > 1/e$, which checks out. So assuming $n=k$ for $k \geq 1$ is true, I want to show that $ (k+1)! > ((k+1)/e)^{k+1} $. So to show this I begin by expanding the expression leading to $(k+1)k! > (k+1)(k/e)^{k}$. Now im stuck, so I want to find an expression on the right side to use the fact that $ e > (1+(1/n))^{n}$ - How does this help me reach the necessary step? Insight on this would be greatly appreciated.
Answer: $$(k+1)(k/e)^k=(k+1)k^ke^{-k}\\
=(k+1)^{k+1}e^{-k-1}e^1\left(\frac k{k+1}\right)^k\\
\geq(k+1)^{k+1}e^{-k-1}e/e$$
because $e>((k+1)/k)^k\to1/e<(k/(k+1))^k$.
So the next rung of the inequality has been established.
Comment: Definition of $e = \lim_{n \rightarrow \infty} = (1 + 1/n)^n$.  And for $k >m$  we know $(1 + 1/k)^k < (1 + 1/m)^m < e$.  So it is acceptable to assume $e > ((k + 1)/k)^k$.
Comment: Perhaps I am being greedy or slow here, but a few explaining touches to that last step? Why is it what im searching for exactly?
Answer: Let's show that
$$
(k+1)\left(\frac{k}{e}\right)^{\!k}>\left(\frac{k+1}{e}\right)^{\!k+1}
$$
which is equivalent to
$$
\frac{k^k}{e^k}>\frac{(k+1)^k}{e^{k+1}}
$$
that is
$$
e>\frac{(k+1)^k}{k^k}=\left(1+\frac{1}{k}\right)^{\!k}
$$
Answer: You are assuming
$$n!>(n/e)^n$$
and you want to show
$$(n+1)!>\left ( \frac{n+1}{e} \right )^{n+1}.$$
We want to manipulate both sides to look more like the statement that we have assumed. The left side is $(n+1)n!$. The right side is $\frac{n+1}{e} \left ( \frac{n}{e} \right )^n \left ( \frac{n+1}{n} \right )^n$. By the inductive hypothesis you can replace $\left ( \frac{n}{e} \right )^n$ by $n!$, since that only makes the right side larger. This reduces the problem to showing
$$n+1>\frac{n+1}{e} \left ( \frac{n+1}{n} \right )^n.$$
Divide both sides by $n+1$, multiply both sides by $e$, and long divide in the parentheses; the result is
$$\left ( 1 + \frac{1}{n} \right )^n<e$$
which is a pretty classic problem.
Comment: Could I perhaps get some taste of the simple algebra for reaching the expanded form of the right side and last step and I would be very grateful. Other than that the answer was very satisfactory.
Comment: @Truefeel Edited.


How to plot results from analysis of different datasets into one graph

Question: I conducted the same logistic regression analysis for five different datasets. Now I would like to plot the results (the Odds-Ratios) all into one graph. Is this even possible? And how would I do it?
Answer: What to plot and how to plot are depending on the story / insights you want to tell.
I can think about many ways of showing 5 different models in one plot. But still do not know your goal. Here are two examples:

Plot five logistic curves on 5 data set, i.e, you will see 5 'S-shaped' curve, where x is the log odds and y is the probability. The goal here is you can compare the 'bias' term in different models, i.e, the red curve is centered at 1 but the green curve is centered at -1. Also you can compare the how steep / flat of different models.

Use histogram (such as stacked bar chart) to show output probably distribution of 5 models.
Answer: Using the mtcars data:
<code>mod1<- glm(vs~hp, data = mtcars, family = 'binomial')
mod2 <- glm(vs~disp, data = mtcars, family = 'binomial')
mod3 <- glm(vs~cyl, data = mtcars, family = 'binomial')

#Creating predictor dataset for each of the variables of length 100

newdata <- data.frame(hp=seq(min(mtcars$hp), max(mtcars$hp),len=100),
                      disp=seq(min(mtcars$disp), max(mtcars$disp), len=100),
                      cyl=seq(min(mtcars$cyl), max(mtcars$cyl), len=100))

#Predicting the dependent variables using each model
newdata$vs1 <- predict(mod1, newdata=newdata, type="response")
newdata$vs2 <- predict(mod2, newdata=newdata, type="response")
newdata$vs3 <- predict(mod3, newdata=newdata, type="response")

newdata[1:3]<- scale(newdata[1:3])  #scaling 3 predictor variables for standardizing x axis

plot(vs1~hp, data=newdata, type='l', col="red", xlab="Predictor (Scaled)", ylab="Predicted", lwd =2)
par(mfrow=c(1,1), new=TRUE)
plot(vs2~disp, data=newdata, type='l', col="blue", xaxt='n', yaxt='n', xlab="" , ylab="", lwd =2)
par(mfrow=c(1,1), new=TRUE)
plot(vs3~cyl, data=newdata, type='l', col="darkgreen", xaxt='n', yaxt='n',  xlab="" , ylab="", lwd =2)
</code>
Comment: Currently, we see only code and a plot.  Could you please explain *what* you are plotting and provide some interpretation?


perl.exe runs from any folder, and perldoc.bat is not. Meanwhile they both are located in the same folder

Question: I use ActiveState Perl 5.8.8 with Eclipse/EPIC. And it works fine. I'd like to use perldoc as well. But there is message in Eclipse "Documentation is not available." in Eclipse my perl interpreter is "C:\perl\bin\perlexe". Or if I type in cmd "perldoc" appears a message "Can't find perldoc on PATH." Sure, in system env variables C:\perl\bin path exists. perl.exe and perldoc.bat are located in the same folder, but perl works and perldoc is not. But is I go before to perl folder in cmd "cd C:\perl\bin" and type perldoc, then perldoc works well. I checked my environment variables again, but I couldn't detect any problem there - "C:\perl\bin" is in very beginning of variables in PATH, perl.exe and perldoc.bat are both located in this folder.
Comment: Type `where perl` and `where perldoc` and see what happens. Is the output of the first the same directory where perldoc exists (or, is it where you expect it to be)?
Comment: C:\>where perl
INFO: Could not find files for the given pattern(s).

C:\>where perldoc
INFO: Could not find files for the given pattern(s).

C:\>perl -v

This is perl, v5.8.8 built for MSWin32-x86-multi-thread
(with 18 registered patches, see perl -V for more detail)
Comment: Are you running in some kind of pseudo-unix shell, such as Cygwin, or one provided by ActiveState?
Comment: No, I'm running on cmd for now. (OS Windows 7)
Comment: It's possible that Eclipse is ignoring PATHEXT, the environment variable that tells "DOS" (don't flame me for that incorrect term!) which extensions to add on to the given program name, if the exact program name is not found.  For example, if you type `perl` in DOS, it will look for "perl", "perl.exe", "perl.bat", etc, in each dir in the PATH, until it finds a match.  If Eclipse is not using PATHEXT, then try configuring it to use (or typing) `perldoc.bat` instead of just `perldoc`.
Comment: perl interpreter works fine in Eclipse. But there no way to define perldoc path inside of Eclipse.
Answer: It's not "perldoc.bat" that couldn't be found. There should be a Perl script named "perldoc" (with no file extension) in the same directory as "perldoc.bat". The message "Can't find %s on PATH" comes from Perl itself and means (see perldiag):

You used the -S switch, but the script to execute could not be found
  in the PATH.

(It's "perldoc.bat" that runs Perl with the "-S" switch, in order to launch the "perldoc" script.)
I don't know why you were missing the "perldoc" script.


Whether to apply structural equation modelling separately to each of a set of heterogeneous correlation matrices in a meta-analysis context?

Question: I'm in the process of performing an Structural Equation Modelling (SEM) meta-analysis on some psychological data. Ultimately I want to examine a mediational model based on a set of correlation matrices. I've spent a little time reviewing the literature regarding what to do when you have heterogenous correlation matrices.  I've written up a brief review of what I've found on Cognitive Sciences SE.
To summarise what I've found:

Most researchers use a two-step approach. Step 1 involves extracting estimates of true correlations between a set of variables using a variety of meta-analytic techniques. Step 2 involves inputting the correlation into your SEM software and in general doing analyses as per normal non-meta-analytic SEM.
Despite an awareness of the problems, many researchers still use the two-step approach even though most datasets have variation in true correlations that can not merely be attributable to random sampling (i.e., a random effects model is generally more applicable).
Some researchers mention the possibility of clustering the dataset or performing SEM Meta-analysis on values of moderators in the hope that the true score variability will be removed once you divide the analysis up into groups. However, in most applications such moderators are insufficient to explain all the true score variation.

So instead of adopting a two-step approach, I thought about maybe doing the following, at least for cases where you are able to compute a full correlation matrix for each study:

"perform SEM on each sample and treat the parameters and fit
  statistics as values that vary between samples. You could then
  summarise the distribution (e.g.,mean and SD) of these SEM parameters
  and fit statistics. This would be similar to how correlations and
  other effect sizes are typically modelled as random effects. So, for
  example you could look at the variation in the indirect effect across
  samples. The challenging bit would be to tease out what is true score
  variation and what is due to random sampling."

Excluding the issue of teasing out true score from random sampling, it
would be straight forward to do such an analysis in R with any of the
SEM packages.
Questions
So, I was wondering:

Has this approach of fitting SEM to each study separately ever been applied?
What are the pros and cons of the approach?
How might you tease out what variation in SEM parameters is due to random sampling and what is due to true score variance?
Or is there some better approach to doing SEM meta-analysis on heterogenous correlation matrices?
Answer: Cheung and Cheung (2010) gave a presentation discussing two appraoches to meta-analytic Structural Equation Modelling (SEM). They label the two approaches:

Correlation matrices Meta-Analysis: An average correlation matrix is extracted from the primary studies and SEM is applied to this single correlation matrix.
Model Parameters Meta-Analysis: Model fitting is applied separately to the correlation matrix of each primary study and the variation in parameters is modelled using random effects multivariate meta-analysis (Cheung and Cheung, 2010 cite Cheung 2009, and Kalaian & Raudenbush, 1996)

Cheung and Cheung (2010) note that this is an area of research needing further development. They recommend trying both approaches especially where the full correlation matrix is available at least in a subset of studies.
Discussions of how to perform meta-analysis SEM are also closely related with general discussions of multivariate meta-analysis (e.g., see the tutorial by Van Houwelingen et al 2002).
I think that the standIndirect function in the metaSEM package in R (Cheung, 2011) implements a three variable test of mediation using the model parameters meta-analysis approach.
References

Becker, B.J. & Wu, M.J. (2007). The synthesis of regression slopes in meta-analysis. Statistical Science, 22, 414-429. PDF on arxiv
Cheung, S. F., & Cheung, M. W.-L. (2010). Random effects models for meta-analytic structural equation modeling. Presented at The 7th Conference of the International Test Commission, July 19-21, 2010, Hong Kong.
Cheung, M.W.L. (2011). metaSEM: Meta-Analysis using Structural Equation Modeling.
Cheung, M.W.L. (2009). Comparison of methods for constructing confidence intervals of standardized indirect effects. Behavior Research Methods, 41, 425-438.
Cheung, M.W.L. (2009). Constructing approximate confidence intervals for parameters with structural equation models. Structural Equation Modeling, 16, 267-294.
Kalaian, H.A. & Raudenbush, S.W. (1996). A multivariate mixed linear model for meta-analysis.. Psychological methods, 1, 227.
PDF
Van Houwelingen, H.C., Arends, L.R. & Stijnen, T. (2002). Advanced methods in meta-analysis: multivariate approach and meta-regression. Statistics in medicine, 21, 589-624. PDF


PDO Disabled in PHP... how to enable it?

Question: Sorry I'm still a bit of a novice with dedicated hosting. Anyway, we have a dedicated server running cPanel and WHM. I have full terminal access and all that.
Basically I've tried to install Chive to a user on my server's account. Unfortunately whenever I login with any details, I get the following error:

Internal Server Error

include(PDO.php) [function.include]:

failed to open stream: No such file or
  directory
An internal error occurred while the Web server was processing your

request. Please contact the webmaster
  to report this problem.
Thank you.

My research shows from  that --disable-pdo is in the Configure Command list. What I want to know is how can I change this and turn it off? I have these two lines at the end of my php.ini file:
extension=pdo.so
extension=pdo_mysql.so
(There's a linebreak between them but SF isn't showing it...)
But still it's not working. I can't find anywhere in php.ini that defines --disable-pdo - so where do I change this?
Thanks!
Jack
Answer: try this :
http://www.webhostingtalk.com/showthread.php?t=680039
Answer: That statement isn't showing PDO is not compiled (though it looks like it isn't) it is stating that some PHP script is trying to include a file called PDO.php. What line or file is given? It looks like you edited the message.
Comment: No, I didn't edit the message. It came straight out of Chive (http://chive-project.com), an Ajax-based alternative to phpMyAdmin. It used PDO but I've got the problem sorted now, thank you.


function not defined javaqscript

Question: here is my code
<!DOCTYPE html>

<link rel="stylesheet"
type="text/css"
href="style.css" />
<title>mysite</title>

<image src="images.jpg" id="img1">
<image src="images2.jpg" id="img2">

<button id="button2" onclick="namething2()">animationtest</button>
<button id="button1" onclick="namething()">click me!</button>

hello

returning namething2 not defined?
did i miss something?
please dont ask what i am doing this is just things i am testing things i am not actually trying to do something
Comment: It looks like you've got some HTML in the `` when it should be in the ``. There are other errors as well, including unclosed tags, missing semicolons, etc. Be sure to check your javascript error console. Here's this: http://jsfiddle.net/Njbst/
Answer: namething2 is not defined, because you have a syntax error in your JavaScript code. Look in the console for the error message, or use a syntax-checking editor such as the free Komodo Edit.
Komodo also includes a JavaScript beautifier that cleans up your formatting and indentation. With no indentation the way you have it in the question, it's very hard to visually notice errors like the one you have. Properly formatted and indented code makes it much easier to see problems like this.
If you load your entire HTML page into Komodo it will highlight all of the errors people have mentioned in the answers (except for the missing semicolons which are not really errors but recommended practice).
Comment: Specifically, you've got an extra `);` at the end of all your code, you're missing a `;` after the alerts, and you have an extra `;` after the first function (that last is not strictly a syntax error)
Comment: There's also a missing `;` after the `prompt()`, but that's not a syntax error - nor is the one after the `alert()`. Automatic semicolon insertion takes care of those. But it is better to put in the semicolon. Anyway, I am hoping to equip OP with the tools to find these errors on their own. Otherwise what can they do? Ask on Stack Overflow every time there's a syntax error?
Answer: Checkout what character is right after the right curly-brace that closes namething2.
Answer: Is there a terminating brace missing at the end of the function?
   function namething2() { alert("yes")
    $("div").animate({ height: 0 /*left:"250px" , opacity:"0. 5", right:"500px" */})
    });
   }
  ^^^

Answer:   function namething2() {
       alert("yes");
       $("div").animate({ height: 0 /*left:"250px" , opacity:"0. 5", right:"500px" */});
  }

Answer: From what I see you have 3 lines and 3 missing semicolons at the END after a complete statement:
namething #1:
    var name = prompt("what is your name");

namething #2:
    function namething2() { alert("yes");
    $("div").animate({ height: 0 /*left:"250px" , opacity:"0. 5", right:"500px" */});

function not defined javaqscript


Arduino I²C slave onReceive fails

Question:
I'm currently having some problems with my Arduino and my Raspberry Pi 2.
I set up a working I²C connection between the Arduino and the Pi. I configured the Arduino as slave.
Some simple tests worked. But when I keep using the Arduino for about 5 minutes (actual time is random) over I²C the function I registered with Wire.onReceive stops being called. The Arduino keeps sending values on request but seems to completly ignore any data being send to it.
What I have tested so far:

Removing all pin writes and reads on the Arduino
Increasing the delay between two requests from the Pi. This just seems to increase the time it is working. Still fails eventually
Frequently reregistering the functions

Here is the code on the Arduino:
#include <Wire.h>

const byte ADDRESS = 0x4E;
const byte FLAG_PWM = 0x80;

byte states[22] = {OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT, OUTPUT};
byte request;

void setup() {
  Wire.begin(ADDRESS);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}

void loop() {
  delay(100);
}

// At some point this function isn't called anymore. (request doesn't change)
void receiveEvent(int howMany) {
  byte byteIN = Wire.read();
  boolean pwm = byteIN & FLAG_PWM;

  byteIN &= ~FLAG_PWM;

  if (byteIN > 21)
    return;

  if (howMany == 1) {
    request = byteIN;

    if (states[byteIN] != INPUT)
      pinMode(byteIN, INPUT);
  } else if (howMany == 2) {
    if (states[byteIN] != OUTPUT)
        pinMode(byteIN, OUTPUT);

    byte value = Wire.read();

    // Disabling this does not help
    if (pwm)
      analogWrite(byteIN, value);
    else
      digitalWrite(byteIN, value);
  }
}

// This function keeps working after the other failed.
void requestEvent() {
  if (request < A0) {
    // Disabling this does not help
    byte value = digitalRead(request);

    Wire.write(&value, 1);
  } else {
    // Disabling this does not help
    int value = analogRead(request);

    Wire.write((char*)&value, 2);
  }
}

Right now I can't access the code on the Pi. But if needed I can post it here.
The Pi is requesting a single read about every 20ms.
I'm running out of ideas what might be wrong...
Comment: Can you post your part of the code that deals with i2c ? Does it start working again if you reboot both the devices ? I'm assuming that you used level shifter and everything since Rpi is a 3v3 device and arduino is 5v device.
Comment: @dastaan It already works when I reset the Arduino.
Comment: @dastaan Yes. I am using a level shifter.
Comment: @BrainStone Did you ever get anywhere? I'm also using a pi to talk to an Arduino via I2C and onReceive() stops being called after 30 seconds or so.
Comment: @Bort yes I eventually solved it. But I don't remember what I did. And I can access the code at the moment. If I remember correctly a sleep was too short or missing.
Comment: @BrainStone You mean delay()? I don't have any delay(). You're saying I need one?
Comment: @Bort yes. Try that.
Comment: @Bort do you have one in loop? There should be one for sure.
Comment: @BrainStone I can't put a large delay in my loop because my code is running servos that need to react quickly. I tried putting in `delay(200)` in my loop()  just to see what would happen and it still didn't help.
Comment: @Bort I mean something like 2-5
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/130342/discussion-between-bort-and-brainstone).
Answer: I am not an expert, but there is a function in Wire that checks if there are available something to read:
String DecodeUri()
{
  String ret = "";
  while (1 < Wire.available())
  {
     ret += (char)Wire.read();
  }
    ret += (char)Wire.read();
 return ret;
}

Apart you can check howMany to check if you can read.
And another weird thing I have is that if I use a battery with not too much power the I2C goes weird.

Arduino I²C slave onReceive fails


A problem in polynomials

Question: Let c be a fixed number.Show that a root of the equation
      x(x+1)(x+2)...(x+2009)=c
can have multiplicity at most 2.Determine the number of values of c for which the equation has a root of multiplicity 2.
I did the first part,I took f(x)=x(x+1)(x+2)...(x+2009)-c
then according to the rule I differentiated f(x) and got 2009*x^2008+(1+2+...+2009) which shows it can have a multiplicity of at most 2,as after further differentiation it wont be a polynomial any more.
But I cannot do the second part.
Comment: Your result for $f'(x)$ is not correct. Moreover, the second derivative of a polynmial is still a polynomial
Comment: I think this is a duplicate.
Answer: A triple (or higher) root of $f(x)=c$ with $f(x)=\prod_{k=0}^{2009}(x+k)$ is also a root of $f'(x)=0$ and $f''(x)=0$.
We can exclude the case $c=0$ as then we see immediately, that $f(x)=0$ has $2010$ distinct sinmple roots given by its linear factors.
Therefore assume $c\ne0$ from now on.
Especially, $f(x)=c$ implies $x\notin\{0,-1,\ldots,-2009\}$.
By the product rule and using logarithmic differentiation,
$$\tag1\frac{f'(x)}{f(x)} = \sum_{k=0}^{2009}\frac1{x+k}$$
for all $x\notin\{0,-1,\ldots,-2009\}$ and the derivative of this quotient is
$$\tag2\frac{f''(x)f(x)-f'(x)^2}{f(x)^2}=-\sum_{k=0}^{2009} \frac1{(x+k)^2}.$$
For $x\notin\{0,-1,\ldots,-2009\}$), the sum on the right is a sum of nozero squares, hence nonzero, i.e. the denominator on the left is nonzero. This implies that $f'(x)=f''(x)=0$ is not possible for such $x$.

A problem in polynomials


Ajuda para simplificar consulta sql query

Question: Tenho uma consulta sql enorme:
select
l.no_cidadao,
extract(year from l.dt_cad_individual) ano,
extract(month from l.dt_cad_individual) mes,
date_part('year',age(now(), l.dt_cad_individual)) diferenca
from
tb_unidade_saude p,
tb_cds_cidadao_resposta a,
tb_cds_prof as c,
tb_pessoa_fisica as d,
tb_equipe as e,
(SELECT *,
   ROW_NUMBER() OVER (PARTITION BY no_cidadao
   ORDER BY st_atualizacao desc) AS linha
   FROM tb_cds_cad_individual) l
WHERE LINHA = 1
AND l.co_seq_cds_cad_individual = a.co_cds_cad_individual
and c.nu_cns = d.nu_cns
and c.co_seq_cds_prof = l.co_cds_prof_cadastrante
and a.co_pergunta = 19
and a.st_resposta = 1
and c.nu_ine = e.nu_ine
and e.co_unidade_saude = p.co_ator_papel
and p.nu_cnes like '%".$cnes."%'
group by
p.nu_cnes, l.no_cidadao, l.dt_cad_individual, e.no_equipe
order by
e.no_equipe, l.no_cidadao, l.dt_cad_individual

Isso tudo para me retornar uma lista de nomes das mulheres que estão gestantes em um sistema.
Após listar todas elas, preciso fazer tudo de novo para ver quais delas tiveram uma consulta marcada em um determinado mês:
select
p.nu_cnes,
a.no_cidadao,
count(case when(extract(month from d.dt_ficha) = ".$mesAtual." and extract(year from d.dt_ficha) = ".$anoAtual." and b.co_cds_ficha_atend_individual = d.co_seq_cds_ficha_atend_indivdl) then a.no_cidadao else null end) as a2,
count(case when(extract(month from d.dt_ficha) = ".$mesAnterior." and extract(year from d.dt_ficha) = ".$anoAnterior." and b.co_cds_ficha_atend_individual = d.co_seq_cds_ficha_atend_indivdl) then a.no_cidadao else null end) as a1
from
tb_unidade_saude p,
tb_cds_cidadao_resposta e,
tb_cds_prof as g,
tb_equipe as f,
tb_cds_ficha_atend_individual d,
tb_cds_atend_individual b,
(SELECT *,
   ROW_NUMBER() OVER (PARTITION BY no_cidadao
   ORDER BY st_atualizacao desc) AS linha
   FROM tb_cds_cad_individual) a
WHERE LINHA = 1
AND a.co_seq_cds_cad_individual = e.co_cds_cad_individual
and g.co_seq_cds_prof = a.co_cds_prof_cadastrante
and e.co_pergunta = 19
and e.st_resposta = 1
and g.nu_ine = f.nu_ine
and f.co_unidade_saude = p.co_ator_papel
and a.nu_cns_cidadao = b.nu_cartao_sus
and ((extract(month from d.dt_ficha) = ".$mesAtual." and extract(year from d.dt_ficha) = ".$anoAtual.")
or (extract(month from d.dt_ficha) = ".$mesAnterior." and extract(year from d.dt_ficha) = ".$anoAnterior."))
and p.nu_cnes like '%".$cnes."%'
group by
p.nu_cnes, f.no_equipe, a.no_cidadao
order by
a.no_cidadao

Depois dessa, tem mais outras que usam a mesma lista de gestantes para pegar outras informações sobre as mesmas.
O que quero é o seguinte: uma vez que tenho a lista de gestantes na primeira consulta, como fazer a segunda consulta comparando com a primeira para economizar processamento, tipo assim:
select * from ... where no_cidadao in [lista da primeira consulta]

Answer: Você pode rodar uma consulta sobre outra consulta. Por exemplo, supondo que você tenha essas duas consultas, onde a segunda é basicamente uma cópia da primeira com mais um refinamento.
Forma bruta
Transforme:
select
    foo, bar
from
    mulheres
where
    gravida = 1
    and cadastro_ativo = 1
    and... -- 500 condicoes aqui

--------------------------------------

select
    foo, bar, ni
from
    mulheres
    inner join consultas on consultas.mulher = mulheres.id
where
    mulheres.gravida = 1
    and mulheres.cadastro_ativo = 1
    and... -- 500 condicoes aqui
    and consultas.data > getdate()

Em:
select
    foo, bar, ni
from
    mulheres inner join consultas on consultas.mulher = mulheres.id
where
    consultas.data > getdate()
    and mulheres.id in (
        select
            foo, bar
        from
            mulheres
        where
            gravida = 1
            and cadastro_ativo = 1
            and... -- 500 condicoes aqui
    )

Você ainda vai ter uma montanha de código, mas vai ser uma montanha menor do que a que você tem hoje. Desvantagem: a complexidade na melhor das hipóteses permanece a mesma, mas em geral aumenta.
Forma elegante
Siga os seguintes passos:

Transforme a primeira consulta em uma View.
Faça join dessa view com a segunda consulta, adicionando somente as condições que elas não tem em comum.
Encapsule tudo em uma stored procedure, para facilitar ao banco a otimização das consultas.
Não esqueça de indexar os campos utilizados com mais frequência para as pesquisa.
Havendo uma linguagem de programação em um nível acima na aplicação, talvez você possa transferir parte da lógica para o nível superior.
Answer: Você pode armazenar o resultado dessas queries com o With:
with gravidas as (
    select
    l.no_cidadao,
    extract(year from l.dt_cad_individual) ano,
    extract(month from l.dt_cad_individual) mes,
    date_part('year',age(now(), l.dt_cad_individual)) diferenca
    from
    tb_unidade_saude p,
    tb_cds_cidadao_resposta a,
    tb_cds_prof as c,
    tb_pessoa_fisica as d,
    tb_equipe as e,
    (SELECT *,
       ROW_NUMBER() OVER (PARTITION BY no_cidadao
       ORDER BY st_atualizacao desc) AS linha
       FROM tb_cds_cad_individual) l
    WHERE LINHA = 1
    AND l.co_seq_cds_cad_individual = a.co_cds_cad_individual
    and c.nu_cns = d.nu_cns
    and c.co_seq_cds_prof = l.co_cds_prof_cadastrante
    and a.co_pergunta = 19
    and a.st_resposta = 1
    and c.nu_ine = e.nu_ine
    and e.co_unidade_saude = p.co_ator_papel
    and p.nu_cnes like '%".$cnes."%'
    group by
    p.nu_cnes, l.no_cidadao, l.dt_cad_individual, e.no_equipe
    order by
    e.no_equipe, l.no_cidadao, l.dt_cad_individual),

atendidas as (

    select
p.nu_cnes,
a.no_cidadao,
count(case when(extract(month from d.dt_ficha) = ".$mesAtual." and extract(year from d.dt_ficha) = ".$anoAtual." and b.co_cds_ficha_atend_individual = d.co_seq_cds_ficha_atend_indivdl) then a.no_cidadao else null end) as a2,
count(case when(extract(month from d.dt_ficha) = ".$mesAnterior." and extract(year from d.dt_ficha) = ".$anoAnterior." and b.co_cds_ficha_atend_individual = d.co_seq_cds_ficha_atend_indivdl) then a.no_cidadao else null end) as a1
from
tb_unidade_saude p,
tb_cds_cidadao_resposta e,
tb_cds_prof as g,
tb_equipe as f,
tb_cds_ficha_atend_individual d,
tb_cds_atend_individual b,
(SELECT *,
   ROW_NUMBER() OVER (PARTITION BY no_cidadao
   ORDER BY st_atualizacao desc) AS linha
   FROM tb_cds_cad_individual) a
WHERE LINHA = 1
AND a.co_seq_cds_cad_individual = e.co_cds_cad_individual
and g.co_seq_cds_prof = a.co_cds_prof_cadastrante
and e.co_pergunta = 19
and e.st_resposta = 1
and g.nu_ine = f.nu_ine
and f.co_unidade_saude = p.co_ator_papel
and a.nu_cns_cidadao = b.nu_cartao_sus
and ((extract(month from d.dt_ficha) = ".$mesAtual." and extract(year from d.dt_ficha) = ".$anoAtual.")
or (extract(month from d.dt_ficha) = ".$mesAnterior." and extract(year from d.dt_ficha) = ".$anoAnterior."))
and p.nu_cnes like '%".$cnes."%'
group by
p.nu_cnes, f.no_equipe, a.no_cidadao
order by
a.no_cidadao)

select * from gravidas;

select * from atendidas;

A segunda query já poderia ser simplificada com os resultados da primeira, mas aí preciso entender todo seu select antes


Ler ficheiros JList e apresentar conteúdo numa JTextArea

Question: JTextArea caixaTexto = new JTextArea();

 try {
    String[] arrayLinhas = null;
    int i = 0;

    BufferedReader br = new BufferedReader(new FileReader(diretoriaExecucao + "/" + valorSelecionado));

    while(br.ready()){
        String linha = br.readLine();
        arrayLinhas[i] = linha;
        i++;
    }
    caixaTexto.setText(arrayLinhas.toString());  //imprimo caixa texto
    br.close();

} catch (IOException e2) {
    e2.printStackTrace();
}

Tenho uma lista da qual seleciono um ficheiro, leio esse ficheiro e imprimo o output na JTextArea caixa de texto.
Dá me um erro de null exception na linha:
arrayLinhas[i] = linha;
Answer: Adaptei o seu código pra ele funcionar. Você não precisa de um array se o único objetivo é mostrar o conteúdo numa área de texto.
try {
    caixaTexto.setText(""); // Limpar o TextArea
    BufferedReader br = new BufferedReader(new FileReader(diretoriaExecucao + "/" + valorSelecionado));

    while(br.ready()){
        String texto = br.readLine() + "\n";
        caixaTexto.append(texto);
    }

    br.close();
} catch (IOException e2) {
    e2.printStackTrace();
}

Versão antiga
Você não instanciou o array, veja esta linha
String[] arrayLinhas = null;

Deveria ser
String[] arrayLinhas = new String[tamanhoDoArray];

Se você não souber a quantidade de linhas de antemão, pode substituir o array por um ArrayList
ArrayList<String> listaLinhas = new ArrayList<String>();

//...
while(br.ready()){
    String linha = br.readLine();
    listaLinhas.add(linha);
}

Comment: Do lado esquerdo (declaração) sim, do lado direito (instanciação) não.
Comment: Sim mas agora tenho o problema de quando escrevo na caixa de texto com a 1ª solução não me aparece o texto mas sim codificado.
Comment: Isso é outro problema, jovem. Você pode abrir outra pergunta com isso.
Comment: pode ser só List em vez de array List?
Comment: No caso do append não da, isto porque sempre que carregar noutros ficheiros aparece sempre o texto que já lá está.
Comment: Limpa ele antes, ora. Editei a resposta
Comment: e como mudo de linha? /n não funciona
Comment: e vota no meu post pff para te marcar responda correta
Comment: É \n mesmo, cara.
Answer: O NullPointerException ocorre pois arrayLinhas não está inicializado.
Minha sujestão é substituir ele por uma List, como o ArrayList e usar o método add para as linhas. Depois você pode pegar um array de linhas se precisar com um list.toArray()
Outra solução para seu caso é usar o append do JTextArea diretamente:
JTextArea caixaTexto = new JTextArea();

try {
     BufferedReader br = new BufferedReader(new FileReader(diretoriaExecucao, valorSelecionado));

     while(br.ready()){
         String linha = br.readLine();
         caixaTexto.append(linha);//imprime continuamente na caixa texto
     }
 br.close();

 } catch (IOException e2) {
     e2.printStackTrace();
 }


Instant Server-Client Communication, C#?

Question: I have been doing research for a few months now on the possibility of client-server communication. I have experimented with many methods such as WebORB and FluorineFX, which are both servers designed to deal with client/server authentication.
WebORB only runs on Windows for their .NET version as far as I can tell, and I would much rather use an open source system. I have tried using FluorineFX, but I think their must be a simpler way for me to build my own simple system from the ground up.
I have been using Dropbox for a while now, and I like the way that the client-server communication is instant. As far as I can tell (from some Google searches) the client doesn't open a port of its own, and just communicates with the Dropbox server through port 80. An example of its instant communication is where you may delete a file on Dropbox on their website, and instantly the server communicates with the client telling it what has happened. I don't know how this instant communication is possible without opening a port.
I can create a system that uses fetching from the client, asking the server every 10 seconds or so to see if there are any updates, but I would like a method to be able to push the information from the server to the client.
My server runs Linux so I don't think I can use WCF, and ideally I am looking for a way to make PHP and C# communicate with each other.
I would love to hear any advice that anyone has and how they deal with the problem.
Cheers.
Answer: You CAN use WCF to communicate with any platform. Just make sure you're using an endpoint which your target machine support: http://msdn.microsoft.com/en-us/library/ms733107.aspx
Answer: Have you tried the good old .NET Remoting which runs perfectly with Mono?
You can choose between a TcpChannel (for performance) and a HttpChannel (to pass proxy/firewall easily).
For push notifications, you can open a connection to your server and wait for an answer indefinitely.
Comment: Thanks for the answer. I have decided to go with Mono and HttpChannel because of it's simplicity. It's much simpler for me to use than WCF!


Python - audiodiff can't find file that exists

Question: I'm comparing wav files, this script worked fine until I switched to LMDE Betsy.  The function that is giving me my error is:
def already_valid (arg_wav):
    for w in wavs:
         size_arg = getsize(arg_wav.src_path)
         size_w = getsize(w.src_path)
         if 0 < size_w == size_arg and w.src_path != arg_wav.src_path:
             print arg_wav.src_path, "::", w.src_path
             if audiodiff.audio_equal(arg_wav.src_path, w.src_path):
                 return True
    return False

My first thought was that it was trying to open the same file twice, but w.src_path != arg_wav.src_path should account for that.  I am getting this output:
From my function:
/home/will/Desktop/soundfiles/TITAN Recordings/6648/hold1_por.wav :: /home/will/Desktop/soundfiles/TITAN Recordings/6677/hold1_por.wav

Traceback:
Traceback (most recent call last):
  File "call_diff.py", line 145, in <module>
    verified += handle_wav(p)
  File "call_diff.py", line 73, in handle_wav
    if already_valid(curr_wav):
  File "call_diff.py", line 96, in already_valid
    if audiodiff.audio_equal(arg_wav.src_path, w.src_path):
  File "/usr/local/lib/python2.7/dist-packages/audiodiff/__init__.py", line 51, in audio_equal
    return checksum(name1, ffmpeg_bin) == checksum(name2, ffmpeg_bin)
  File "/usr/local/lib/python2.7/dist-packages/audiodiff/__init__.py", line 86, in checksum
    stderr=subprocess.PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

What's so odd is that it worked yesterday on Linux Mint 17.1 and on Windows 7.  Is this some weird Debian convention I don't know about?  Yes, I double-checked and both files exist in the path described.
Comment: There's a chance it's failing to find ffmpeg, rather than your files. Is ffmpeg in your PATH?
Comment: Of course I forgot to install ffmpeg on my new mint!  Thanks, it runs now, is there a way to tell from the traceback that it means it can't find `ffmpeg_bin` rather than one of my files?
Comment: From what's there, not really. I guessed because I saw `ffmpeg_bin`. You could open the audiodiff `__init__.py` and check around line 86 to see what it's actually doing there, though.
Answer: If you look at the source code of audiodiff, you'll see that you need to have ffmpeg installed and perhaps to have the path to ffmpeg binary set into FFMPEG_BIN environment variable.
https://github.com/clee704/audiodiff/blob/master/audiodiff/init.py