Solving the differential equation $x x''(t)=\frac{1}{t^3-t}$

Question: Solve the following differential equation
$$x x''(t)=\frac{1}{t^3-t}$$
I tried to integrate both members:
$$x(t) x'(t)-\int [x'(t)]^2 dt=\frac{1}{t}+\log\left|\frac{1}{t}-1\right|$$
but the situation does not improve. At this point, I think there is a mistake in the text of exercise.
I would appreciate some help with this problem.
Thank you very much.
Comment: Neither do I. Mathematica fails to find a closed-form solution as well. Maybe you're right and there is a typo in the statement of the problem.
Comment: Does this problem have a physical background? Has it any initial condition?
Comment: No, it appeared in an old exam. I have a question: either there is a mistake in the text, or I can not seem to solve the exercise.
Answer: As stated in the comments, Mathematica doesn't give a closed form for the solution. Still, there is some information we can find anyway.
For $t\gg1$ we have
$$\frac{1}{t^3-t}\approx\frac{1}{t^3},$$
so that asymptotically a solution $x(t)$ will satisfy
$$x(t)x''(t) = \frac{1}{t^3}.$$
We can find a solution of this by assuming $x_{t\gg1}(t)=\beta t^\alpha$ for some $\alpha,\beta\in\mathbb{R}$, then
$$x(t)x''(t) = \beta^2\alpha(\alpha-1)t^\alpha t^{\alpha-2}.$$
It follows that $2\alpha - 2 = -3$, and thus $\alpha = -\tfrac{1}{2}$, and $\beta^2\frac{3}{4} = 1$, so that
$$x(t) = \pm\frac{\sqrt{3t}}{2}$$
for $t\gg1$. Maybe something more can be derived by working on perturbations of this asymptotic solution, but I'm not sure.
It would also be interesting to get some solutions for $0<t<1$.
Answer: Hint:
$xx''(t)=\dfrac{1}{t^3-t}$
$x\dfrac{d^2x}{dt^2}=\dfrac{1}{t^3-t}$
$x\dfrac{d}{dt}\left(\dfrac{dx}{dt}\right)=\dfrac{1}{t^3-t}$
$x\dfrac{d}{dx}\left(\dfrac{1}{\dfrac{dt}{dx}}\right)\dfrac{dx}{dt}=\dfrac{1}{t^3-t}$
$-x\dfrac{\dfrac{d^2t}{dx^2}}{\left(\dfrac{dt}{dx}\right)^3}=\dfrac{1}{t^3-t}$
$t(1-t^2)x\dfrac{d^2t}{dx^2}=\left(\dfrac{dt}{dx}\right)^3$


SOAP-ERROR: Encoding: object has no 'ACCION' property

Question: I have a PHP script which calls a web service created in SAP, I already validated it with soapui5 and it works fine, but PHP throws the following message:
SOAP-ERROR: Encoding: object has no 'ACCION' property

PHP code :
$url = 'https://www.ceramicaitalia.com/wssap/zwebservice1.wsdl';
        $client = new SoapClient($url);
       echo PHP_EOL;

        $xmlr = new SimpleXMLElement("<ZWS_WEBSERVICE1></ZWS_WEBSERVICE1>");
        $xmlr->addChild('login', '***');
        $xmlr->addChild('password', '******');
        $xmlr->addChild('ACCION', '/');

        $params = new stdClass();
        $params->xml = $xmlr->asXML();
         $client->ZWS_WEBSERVICE1($params);
        $result = $client->ZWS_WEBSERVICE1('RTA');
        print_r($result);

Test in soapui5 :
Request :
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
                xmlns:urn="urn:sap-com:document:sap:rfc:functions">
   <soap:Header/>
   <soap:Body>
      <urn:ZWS_WEBSERVICE1>
         <ACCION>/</ACCION>
      </urn:ZWS_WEBSERVICE1>
   </soap:Body>
</soap:Envelope>

Response :
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
   <env:Header/>
   <env:Body>
      <n0:ZWS_WEBSERVICE1Response xmlns:n0="urn:sap-com:document:sap:rfc:functions">
         <RTA>1.5</RTA>
      </n0:ZWS_WEBSERVICE1Response>
   </env:Body>
</env:Envelope>

Comment: Possible duplicate of [Soap error, Encoding: object has no 'RecordId' property](https://stackoverflow.com/questions/7269268/soap-error-encoding-object-has-no-recordid-property)
Answer: You don't need to set root element. You can to xml as array param. Library will auto set matched elements. If you have multiple element with same name but different namespace you can check SoapVar. Working sample is below.
<?php
$url = 'https://www.ceramicaitalia.com/wssap/zwebservice1.wsdl';
$client = new SoapClient($url, ['trace' => true]);
$params = ['ACCION' => '/'];
$client->ZWS_WEBSERVICE1($params);
$result = $client->ZWS_WEBSERVICE1('RTA');
print_r($result);
?>


Save new order to core data after the using the tableView:moveRowAtIndexPath:toIndexPath: method

Question: I have a tableView in a Swift iOS app that allows the user to re-order the rows. An Edit button is tapped, rows can be re-ordered or deleted, and the Edit button (which now reads Done) is re-tapped to complete the process.
If I simply use the tableView:moveRowAtIndexPath:toIndexPath: method, it works as described above and the table shows the re-ordered rows correctly when Done is tapped. But it doesn't remember the new order when returning to the table, so I added a new "position" variable (Int) in core data and I have made my table sort itself based on that.
My problem is that after a user has moved a row and clicks Done, the table immediately re-orders itself back to how it was before. So it is using the old (original) position variables in core data, before my code can properly capture the new order and re-write it to core data.
Is there a way to make this new order get captured when Done is clicked before the table reloads?
Here is my code that handles the move:
func tableView(tableView: UITableView!, moveRowAtIndexPath sourceIndexPath: NSIndexPath!, toIndexPath destinationIndexPath: NSIndexPath!) {
}

And here is my code that is called when Done is pressed. I go through each row of my table and re-assign the person's position variable in core data based on it's new row:
for currentIteration in 0..<tableView.numberOfRowsInSection(0) {
    var indexPathForCurrentIteration = NSIndexPath(forRow: currentIteration, inSection: 0)
    let personAtCurrentIndexIteration = fetchedResultsController.objectAtIndexPath(indexPathForCurrentIteration) as PersonModel
    personAtCurrentIndexIteration.position = indexPathForCurrentIteration.row
    println("\(personAtCurrentIndexIteration.name) has a position value of \(personAtCurrentIndexIteration.position)")
    (UIApplication.sharedApplication().delegate as AppDelegate).saveContext()
        tableView.reloadData();
}

The above is called when the Done button is pressed, but I also tried calling it within the moveRowAtIndexPath method without success (same result - it reloads the old order of the table when Done is pressed). I have also tried commenting out reloadData without success.
I think my problem might lie in the fact that the above is not capturing the new row order, but instead still gets the old row order. If that is the case, then I don't know the simplest way to make it "wait" to get the new row order.
A longer workaround that I started considering would be to capture the moved row's initial and final row value, and based on that update the remaining rows' values accordingly. Some of that code is below but I stopped since I figured there is likely a smarter way.
if((sourceIndexPath.row > indexPathForCurrentIteration.row) && (destinationIndexPath.row > indexPathForCurrentIteration.row)) {
    //if the moved row was ahead of this row before AND after the move, do nothing (don't change this row's position value)
    //println("\(personAtCurrentIndexIteration.name)'s position was unchnaged")
} else if((sourceIndexPath.row > indexPathForCurrentIteration.row) && (destinationIndexPath.row < indexPathForCurrentIteration.row)) {
    //if the moved row was ahead of this row before BUT behind it after the move, then this row's position value needs to be bumped up one number
    personAtCurrentIndexIteration.position = indexPathForCurrentIteration.row+1
//Etc...

Thanks in advance for any help you can provide.
Answer:
Add to CoreData "orderPosition" type Int attribute and add orderPosition to your Model file.
When you add some data to your CoreData, add also orderPosition value
  let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
  let contxt: NSManagedObjectContext = appDel.managedObjectContext!
  let en = NSEntityDescription.entityForName("MyCoreData", inManagedObjectContext: contxt)
  let freq = NSFetchRequest(entityName: "MyCoreData")
  var MyData = contxt.executeFetchRequest(freq, error: nil)!
  var newItem = Model(entity: en!, insertIntoManagedObjectContext: contxt)
  var newOrderPosition = MyData.count

  //here you add some data to your CoreData
  //and also you must add new order position
  newItem.orderPosition = orderPosition

In your TableView you must create a function that will sort an array that you will display in your TableView. Something like this:
    func RefreshCoredata()
{
    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let freq = NSFetchRequest(entityName: "MyCoreData")
    let contxt: NSManagedObjectContext = appDel.managedObjectContext!

    let sortDescriptor = NSSortDescriptor(key: "orderPosition", ascending: true)
    freq.sortDescriptors = [sortDescriptor]
    MyData = contxt.executeFetchRequest(freq, error: nil)!

}

Remember, you must always sort your array before send him to table!
What you must do when you want to reordering your table rows? :
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
 }

override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let contxt: NSManagedObjectContext = appDel.managedObjectContext!

RefreshCoredata()

if fromIndexPath.row > toIndexPath.row
{
    for i in toIndexPath.row..<fromIndexPath.row

    {
        MyData[i].setValue(i+1, forKey: "orderPosition")

    }

    MyData[fromIndexPath.row].setValue(toIndexPath.row, forKey: "orderPosition")
}
if fromIndexPath.row < toIndexPath.row
{

    for i in fromIndexPath.row + 1...toIndexPath.row

    {
        MyData[i].setValue(i-1, forKey: "orderPosition")

    }

    MyData[fromIndexPath.row].setValue(toIndexPath.row, forKey: "orderPosition")

}

contxt.save(nil)

RefreshCoredata()

}

This need to reset ordering position in your CoreData

What you must do when you want to delete some table rows?
override func tableView(tableView: UITableView, commitEditingStyle editingStyle:
UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete {
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let contxt: NSManagedObjectContext = appDel.managedObjectContext!
RefreshCoredata()
contxt.deleteObject(MyData[indexPath.row] as NSManagedObject)
for i in indexPath.row + 1..<MyData.count
        {
            MyData[i].setValue(i-1, forKey: "orderPosition")
        }
RefreshCoredata()

 tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
 contxt.save(nil)

 }

That's all!
Answer: I recently solved the problem in an app that I made that stores a list of Places in Core Data, and these places are transferred to an array Places[] to be shown in the table view.
As mentioned above, you need to create an 'orderID' attribute in your entity.
When you rearrange a row in moveRowAt, make sure you reload the table data.
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let movedObject = places[sourceIndexPath.row]
    places.remove(at: sourceIndexPath.row)
    places.insert(movedObject, at: destinationIndexPath.row)

    tableView.reloadData()
}

This will reload every cell in the table. Therefore, when you are setting the contents of each cell in the cellForRowAt function, then you can set the orderID using the
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")

    places[indexPath.row].setValue(indexPath.row, forKey: "orderID")
    cell.textLabel?.text = places[indexPath.row].value(forKey: "name") as? String

    return cell

}

Possibly inefficient reloading the data after every move but for small data sets this is fine. Also doesn't work if you need some kind of other ordering as this will just assign each value to the index of the cell where it has been placed currently.
Comment: Thank you. I think it's the most simpliest solution for saving reordering cells with core data.
Answer: I can't help with fixing your problem since I need more code for that. The way I do it in my Core Data projects is to maintain a local buffer which I use to do all my manipulations and update Core Data when it is appropriate. For example:

I update the local buffer from the Core Data in viewDidLoad of the initial controller
I work mostly in the local buffer until I do something like moving and deleting rows. At that point I update the Core Data. This is primarily a one way operation since my local buffer is up-to-date. It can be made efficient by a good algorithm.
You still need to maintain the row-order integer because Core Data does not guarantee maintaining a specific order.
I also update Core Data in the didReceiveMemoryWarning in case I get a warning.

What are the risks?
If your program is terminated as a result of didReceiveMemoryWarning there is a risk that your data can be old. If you have a large table and the user has juggled it a lot this approach may not be suitable because of delays encountered during a big update. I am sure there are others.
Comment: Thanks for quick the reply Syed, much appreciated. So you build a local buffer on initial view of the controller, use that to show the rows in the correct order, and then update that buffer when edits are made. I will try this and hopefully it will allow my new row order to be shown when Done is clicked (and then I will write the new order to Core Data afterwards).
Answer: Assuming use of core data and fetchedResultsController you also need to know that the above solutions work when there are no sections in the tableview. Once you have sections you need to be aware that the from and to row values from indexpath.row are not giving you the correct position of the row to delete & insert elsewhere.
You have to work out the positions based on which section the row is in and going to:-
       var fromIndex = fromIndexPath.row
        var toIndex = toIndexPath.row
        //      print ("from row ",fromIndexPath.row)
//work out correct row to remove at based on it's current row and section
        for sectionIndex in 0..<fromIndexPath.section
        {
            fromIndex += fetchedResultsController.sections![sectionIndex].numberOfObjects
        }
            //print ("fromIndex ",fromIndex)
// remove the row at it's old position
       toDoData.remove(at: fromIndex)
//work out the correct row to insert at based on which section it's going to & row in that section
        for sectionIndex in 0..<toIndexPath.section
        {
            toIndex += fetchedResultsController.sections![sectionIndex].numberOfObjects
            //print ("toIndex ",toIndex)
            if sectionIndex == fromIndexPath.section
            {
                toIndex -= 1 // Remember, controller still thinks this item is in the old section
                //print ("-= toIndex",toIndex)
            }
        }
// put the item back into he array at new position
         toDoData.insert(item, at: toIndex)

toDoData is the array where I have loaded the data sorted by section and order


Is there any particular historic/socio-economic reason why the distribution of car ages at an auction site follows a bell curve?

Question: Just analyzed the image names of automobiles in an auto auction sale archive and filtered the image names by the automobile's model year and counted the years' frequencies. I came up with the following plot, which I found interesting and have decided to post here for your comments on what the reason for the spike is:

x-axis: time | y-axis:frequency of vehicles with that model year
Comment: On a terminological note, many people use the phrase "bell shaped" as synonymous with the Gaussian or "normal" distribution, but (as seems to be the case in your example) the fact that a distribution is unimodal (single peak) with a smooth "hump" [doesn't necessarily make it normally distributed](http://stats.stackexchange.com/q/129417/22228)
Comment: Welcome to our site! The socio-economic aspects of this question are most likely off-topic here - see our [help/on-topic] - but I think the discussion of why the bell-shape occurs in such data in general is pertinent here.
Answer: People can't sell a car manufactured in the future, so that accounts for the right-hand tail. Moreover, you're unlikely to sell a nearly-new car as an individual, so that accounts for the drop off. And you're unlikely to sell a car that is old/decrepit/at the end of its life due to maintenance costs and the general observation that a very old car is generally only useful for scrap. That accounts for everything left of the peak.
I don't know if this is a snapshot of a single-day's distribution of model years, but if this data is collected over time, it will be necessary to account for the fact that the model year of a car is fixed, and does not change relative to today's date. If you collected these data over a period of several years, you will also be reporting the fact that there are more opportunities for 2003 model year vehicles to appear: every year since 2002.
Answer: The "spike" or "bell-shaped curve" just means that intermediate model years, from 1995 to 2000, are more likely than extreme early or later model years.  Certainly, more cars will be sold from an intermediate period where they are no longer new but still usable, than from earlier periods when they are old and unusable (low demand), as well as later periods when they are still brand new and no need to sell them (low supply).
Comment: What can be said of the peak-to-present time? For instance, if people buy new in the then present (_i.e._ the past) does this mean that they generally give up their vehicles after 17 years.
Comment: On average, roughly yes.  In fact if you calculate the mean and standard deviation, you could say that people give up their cars after (present year - mean year) +/- SD years.  However it is slightly more complex than that because more recent second hand sales may occur via other channels (e.g., back to the original garage), and some of the sales in the chart shown may be third or fourth hand sales.
Comment: The only thing you could really say without making assumptions, is that most of the sales through that auction are cars from the 1995-2000 period, but whether they are second, third or fourth hand sales we don't know.  We also don't know *when* these cars were sold, so it could be that the auction site has been in decline and losing business in recent years!


Dynamic CSS in Handlebars template?

Question: Sorry if this is a bit of a noob Q. I'm a beginner to html/js/css.
I'm trying to create a HandleBars template of a crowdfunding thermometer. My problem is that I need the dynamic value to determine the width of the progress bar inside the Handlebars template, which requires CSS. I'm confused about the concept of dynamic CSS or whether it's possible.
Effectively, the progress on the thermometer is based on an aggregated value called {{cells.percComplete}} from Google Sheets, which is plugged into HandleBars.
I need the width of the template's 'progress' div to be equal to percComplete.
Javascript
var RBITemplate = Handlebars.compile($('#team-rbi-template').html());

 $('#total').sheetrock({
   url: mySpreadsheet,
   query: "select sum(B)/100 where (A = 'Donate $2 to Test Campaign')",
   labels: ['percComplete'],
  rowTemplate: RBITemplate
});

Handlebars HTML template - here's where I'm stuck

Dynamic CSS in Handlebars template?


Difference of two binomial random variables

Question: Could anyone guide me to a document where they derive the distribution of the difference between two binomial random variables. So $X \sim \mathrm{Bin}(n_1, p_1) $ and $Y \sim \mathrm{Bin}(n_2, p_2) $, what is the distribution of $|X-Y|$.
thank you.
(Also $X$ and $Y$ are independent)
Answer: I can give you an answer for the pmf of X-Y. From there |X - Y| is straightforward.
So we start with
$X \sim Bin(n_1, p_1)$
$Y \sim Bin(n_2, p_2)$
We are looking for the probability mass function of $Z=X-Y$
First note that the min and max of the support of Z must be $(-n_2, n_1)$ since that covers the most extreme cases ($X=0$ and $Y=n_2$) and ($X=n_1$ and $Y=0$).
Then we need a modification of the binomial pmf so that it can cope with values outside of its support.
$m(k, n, p) = \binom {n} {k} p^k (1-p)^{n-k}$ when $k \leq n$ and 0 otherwise.
Then we need to define two cases

$Z \geq 0$
$Z \lt 0$

In the first case
$p(z) = \sum_{i=0}^{n_1} m(i+z, n_1, p_1) m(i, n_2, p_2)$
since this covers all the ways in which X-Y could equal z. For example when z=1 this is reached when X=1 and Y=0 and X=2 and Y=1 and X=4 and Y=3 and so on. It also deals with cases that could not happen because of the values of $n_1$ and $n_2$. For example if $n_1 = 4$ then we cannot get Z=1 as a combination of X=5 and Y=4. In this case thanks to our modified binomial pmf the probablity is zero.
For the second case we just reverse the roles. For example if z=-1 then this is reached when X=0 and Y=1, X=1 and Y=2 etc.
$p(z) = \sum_{i=0}^{n_2} m(i, n_1, p_1) m(i+z, n_2, p_2)$
Put them together and that's your pmf.
$ f(z)=
\begin{cases}
    \sum_{i=0}^{n_1} m(i+z, n_1, p_1) m(i, n_2, p_2),& \text{if } z\geq 0\\
    \sum_{i=0}^{n_2} m(i, n_1, p_1) m(i+z, n_2, p_2),              & \text{otherwise}
\end{cases}
$
Here's the function in R and a simulation to check it's right (and it does work.)
https://gist.github.com/coppeliaMLA/9681819
Comment: A great answer from Simon. Can you tell me the inverse cumulative for X - Y?
Answer: I doubt there is a special name for the distribution in general.  There is one special case of interest: $p_1 = 1 - p_2$.  Note that $n_2 - Y \sim {\text Bin}(n_2, 1-p_2)$, and so in this special  case $X - Y + n_2 \sim {\text Bin}(n_1 + n_2, p_1)$.
Comment: $P(|X-Y|=z) = P(X-Y=z) + P(X-Y=-z)$ for nonnegative integers $z$.
Comment: This explains the distribution of X−Y (in the special case). How do you get from it to the distribution of |X-Y|?
Answer: This question is more tricky than it sounds. To solve it, I will use here a combination of both manual methods and automated methods, in particular computer algebra tools [the mathStatica package (of which I am an author) for Mathematica and the latter itself].
If I may change the notation slightly:
The Problem

Let $X_1$ ~ $\text{Binomial}(n,p)$ and $X_2$ ~ $\text{Binomial}(m,q)$ be independent.
Find the pmf of $|X_1-X_2|$

Given: Due to independence, the joint pmf of $(X_1, X_2)$, say $f(x_1,x_2)$, is:

Solution
Let $Y=X_1-X_2$ and $Z=X_2$. Then, the joint pmf of $(Y,Z)$, say $g(y,z)$, is:

where Transform is a mathStatica function that derives the joint pmf using the Method of Transformations. Deriving the domain of support of $Y$ and $Z$ is a bit more tricky. To make things clearer, here is a rough plot that illustrates the (smoothed continuous version of) the domain of support:

This suggests two cases:

Case 1:  When $y \ge 0$:  $0 \le z \le n-y$
Case 2:  When $y < 0$:  $-y \le z \le m$

The density of $Y=X_1-X_2$ is then obtained by summing out $Z$ in each part of the domain:

Finally, to find the pmf of $|Y|$, the pmf for strictly positive values will be:

and when $Y=0$:

Summary
The pmf of $|X_1-X_2|$, say $\phi(y)$ is:

with domain of support $Y$ = {0, 1, ..., max$(m,n)$}.
All done.

Monte Carlo check
It is always a good idea to check ones work using Monte Carlo methods. Here, for instance, are 100,000 pseudo-random drawings from each of $X_1$ and $X_2$, given some parameter assumptions:
x1data = RandomVariate[BinomialDistribution[12, .1],  100000];
x2data = RandomVariate[BinomialDistribution[ 7, .9],  100000];

Next, compare the empirical distribution of $|X_1-X_2|$ (red triangles) to the theoretical density $\phi(y)$ (blue dots) derived above, given the same parameter assumptions:

Looks good :)
Comment: For the special case in which $p=q=1/2$ and $n=m$, we get: $Pr[Y=y] = p^{2n} \cdot \text{Binomial}[n,y] \cdot \text{Hypergeometric2F1}[-n,-n+y,1+y,1]$


Search API ItemType missing Node

Question: I am using Search API and search views to add facet blocks into my views page. It works perfect on my test site with only search/facet/views related modules.
But on my working site, when I add Search Index, the ItemType is missing "Node" selection, instead, it is showing "Content". I have updated all modules, but can't figure out why "Node" option is missing.
Anyone has ideas on this?
Comment: What version of search api are you running ?
Comment: All Newest version: search_api-7.x-1.14, facetapi-7.x-1.5, ctools-7.x-1.7, views-7.x-3.10, entity-7.x-1.6. We have near 100 modules for this site, is there any modules that limit the "Node" option?.
Comment: Why would you want to have a Node option ? What is the different between Node and Content ?
Comment: The difference is "Node" works, but "Content" doesn't work.
Comment: Matt, You need to provide more details about what you mean by "does not work". I have used all those modules for over a year (like everyday) and "it works fine to be."
Comment: For search_api, search_api_views, and related modules, do they require php 5.4 or higher? my current working site is 5.3.3, maybe this is the reason. I will have to try lower php version at my test server.
Answer: You do not need the "Node" Item type. Using the "Content" is going to index all your nodes.
Comment: Unfortunately it didn't work for me. The facet won't show up in the view page.
Comment: When using the Content option with commerce, product reference fields will not be pulled.
Comment: Same issue here.  Two environments, one has node one has content.  I'm getting different results on the two somehow.

Search API ItemType missing Node


Server.Transfer does not work?

Question: I want to redirect to another page using Server.Transfer and I have this simple code:
if (Page.IsPostBack)
   {
     try
     {
       Server.Transfer("AnotherPage.aspx");
     }
     catch (Exception)
     {
       throw ;
     }
    }

But I'm getting an error: "Error executing child request for AnotherPage.aspx.". Could not find the solution on the net.
Just to mention, Response.Redirect works flawlessly.
Comment: What happens when you go to AnotherPage.aspx in the browser? Does it work? Is it in the same folder/path ?
Comment: Are you actually just trying to redirect the user to the new page? If so, use Response.Redirect() instead of Server.Transfer(). If there are errors on AnotherPage.aspx, they will become clear after you use Response.Redirect() *or* navigate to AnotherPage.aspx directly from the browser.
Comment: What happens when you remove the try/catch block? There's no sense in eating exceptions here, then asking what's wrong.
Answer: The error is likely caused by something in AnotherPage.aspx. You may want to insert a try... catch handler in AnotherPage.aspx's Load event.

Server.Transfer does not work?


Torus integration question

Question: We have a torus whose "circle" has radius of $a$. We need to find the volume of this torus.
So what we did was that we put it into polar coordinates:
$$(x,y,z) = (a \cos(\phi), a \sin(\phi), 0) + (r \cos(\theta) \cos(\phi), r \cos(\theta) \sin(\phi), r \sin(\theta)) = ((a + r \cos(\theta) ) \cos(\phi), (a + r \cos(\theta))\sin(\phi),r \sin(\theta))$$
Where the parameters are: $0 \leq \phi \leq 2\pi$
$ 0 \leq \theta < 2\pi $
$0 \leq r \leq b$
However I don't understand how we chosen new coordinates for $(x,y,z)$ and how we got those parameters to integrate on.
My question is similar to: Torus coordinates and triple integration
However I would need more explanation on it.
Comment: $a$ is radius of torus from center of the torus to the center of the torus tube. Center of the torus is $(0, 0, 0)$ and the circle lies in xy-plane. So, $(a \cos\phi, a\sin\phi, 0)$ is the center of the torus cross sections at angle $\phi$ from positive x-axis. . The next term is the equation of the cross-sections which are circles at any given $\phi$ with radius of the torus tube being  $b$.
Comment: and how you are thinking about it is also correct
Comment: @MathLover I am just curious why can't we do it the following way:

i) We get the surface of the circle in the tube.

ii) We get the perimeter of the outside circle (that forms a torus as the circle of the tube).

iii) We multiply the area of the circle in the tube with the perimeter of the outside circle.
Comment: Sorry I did not get you. Are you trying to find the volume?
Comment: @MathLover Yes, the volume. What I was trying to say is: That we would get a perimiter/circumference of a circle, so like $2 \pi r$. Then we would multiply it by the area of the circle that would be in the tube of the torus.
Comment: @MathLover So we would get: $2\pi r_1 \cdot \pi r_2^2  $
Comment: @MathLover Where $r_1$ would be the distance from the center of the torus, to the center of the tube. And r_2 would be the distance from the tube to the center of the tube.
Comment: yes that is the correct formula for volume of torus.
Comment: @MathLover So it is alot easier than triple integration...
Answer: Let's define the radius $r$ as that of the cross section of the torus and $R$ as the radius of the donut to the center of that circle. I suggest that you use Pappus's ($2^{nd}$) Centroid Theorem: the volume of a planar area of revolution is the product of the area $A$ and the length of the path traced by its centroid $R$, i.e., $2\pi R$. The bottom line is that the volume is given simply by $V=2\pi RA$. Obliviously, the area of the cross section is $A=\pi r^2$, so the volume of the torus is $V=2\pi^2Rr^2$. And while we're here, Pappus's ($1^{st}$) Centroid Theorem: the surface area of a planar area of revolution is the product of the circumference $C$ and the length of the path traced by its centroid $R$, thus, $S=2\pi RC$. For the torus $C=2\pi r$, and thus $S=4\pi^2 Rr$.

Torus integration question


Postfix: How to use a simple script to map recipient addresses 'virtual_alias_maps'-style?

Question: I would like postfix to consult a simple (bash/python) script in order to find out (virtual_alias_maps - style) before-queue whether or not a recipient address it legitimate. E.g. i'd like to use mail addresses like
$email@example.com

to either get accepted for $USER if $EXIPRYDATE has not yet passed and if $CHECKSUM passes, or to get rejected otherwise.

If it simplifies the solution, i'd be ok with doing this for a single, constant user, so postfix would only need to observe True/False from some address check script.

I am not interested in solutions that require postfix to accept a mail first and then bounce later if the recipient address is found invalid ("after-queue"). I need postfix to reject during the initial SMTP session ("before-queue").
Comment: Maybe the simplest solution would be to use 'check_policy_service' and to implement a little policy service (like the ones used for greylisting or SPF).
Comment: You just need to use the before-queue milter, http://www.postfix.org/MILTER_README.html
Comment: I've never used a script. But you can do a lot with the reg-exp (pcre) version of the db tables. e.g. `/^(?:prvs=[\da-f]{10}=)?email@example.com$/                          OK` That example is for a back-scatter preventor that prefixed outgoing addresses with a MD5 hex pattern. Obviously it doesn't check the actual value of the hex-code (in this case the machine was 2ndary smtp). Would that help? See also: http://serverfault.com/questions/258469/how-to-configure-postfix-to-pipe-all-incoming-email-to-a-script
Comment: Thx erics, but it doesn't help my use case. I do need to actually check not just format but expiry date and checksum.

I know that i could pipe incoming mails to a script, but that would mean to accept incoming mails first and bounce later when found illegitimate, potentially producing backscatter. My aim is to let postfix reject straightaway if the address test fails.
Comment: Not sure about "that would mean to accept incoming mails first and bounce later when found illegitimate". `amavisd` for example, is attached as an in-line on incoming `smtp`: `smtp      inet  n       -       n       -       -       smtpd
    -o content_filter=smtp-amavis:localhost:10024
` It is clever enough to hold the connection open. If it has a problem, `postfix smtp` blocks incoming.
Comment: @ericx I hoped to get away with something significantly simpler than writing a Amavis plugin or a SMTP-daemon. (BTW "content_filter" is after-queue, one needs "smtpd_proxy_filter" to do it before-queue)
Comment: @NickW Thanks i will look into milter. I hope it's not too hard to plug-in a tiny shell script.
Answer: I have similar problem with yours. Pre-queue requirement left us to three option

SMTP access policy delegation
Milter program
SMTPD proxy

Because we are only checking recipient, then SMTP access policy delegation would be suffice. Milter and SMTPD Proxy was used if we need access to header and body too.
My checker script was provided by developer. The program usage was only calling ./myscript recipient_address which recipient_address by postfix. To do that, I use modified version of perl script. This perl script allows me to read stdin, split string per line and split the line with equal = sign.
Then I declare spawn daemon in master.cf
policy  unix    -       n             n     -     -      spawn  user=mydedicateduser argv=/path/to/perl/script.pl

Then define it in main.cf
smtpd_recipient_restrictions =
    ...
    reject_unauth_destination
    check_policy_service unix:private/policy
    ...

This script below can be substituted by another programming language. Here the pseudo-code to explain how it works.
while True:

    get the stdin

    if stdin = ''  # ---> the end of parameter
        call the external script with recipient parameter

        get the return code

        if recipient valid
            print "dunno"
        else if recipient not valid
            print "reject"
        else            # ---> command error
            print "defer if permit"

        break

    else
        validate the stdin, the proper format is 'parameter=value'

        if valid
            put it in array

For python code, you can modify code from this snippet. No need to set spawn daemon.
For the completeness, here the full source code of /path/to/perl/script.pl
#!/usr/bin/perl -w

use strict;
use Sys::Syslog qw(:DEFAULT setlogsock);
use Getopt::Long;

#
# Syslogging options for verbose mode and for fatal errors.
# NOTE: comment out the $syslog_socktype line if syslogging does not
# work on your system.
#
my $syslog_socktype = 'unix'; # inet, unix, stream, console
my $syslog_facility = 'mail';
my $syslog_options  = 'pid';
my $syslog_priority = 'info';

# Configuration

my $executable_path = '/my/execute/script.sh';

#
# Procedures
#

#
# Log an error and abort.
#
sub fatal_exit {
        my $first = shift @_;
        syslog "err", "fatal: $first", @_;
        exit 1;
}

# SMTPD access policy routine. The result is an action just like
# it would be specified on the right-hand side of a Postfix access
# table.    Request attributes are available via the %attr hash.
sub smtpd_access_policy() {
    system($executable_path, $attr{'recipient'});

    # -1 command error
    # 0 user isn't valid
    # else user valud
    if ( $? == -1 ) {
        # command error
        return "defer_if_permit Something error"
    }

    if ( $? == 0 ) {
        return "reject user not found";
    }

    return "dunno";
}

#
# Main program
#

#
# This process runs as a daemon, so it can't log to a terminal. Use
# syslog so that people can actually see our messages.
#
setlogsock $syslog_socktype;
openlog $0, $syslog_options, $syslog_facility;

unless(GetOptions('v:+' => \$verbose)) {
    syslog $syslog_priority, "Invalid option. Usage: %s [-v] [-v] ...", $0;
    exit 1;
}

#
# Unbuffer standard output.
#
select((select(STDOUT), $| = 1)[0]);

#
# Receive a bunch of attributes, evaluate the policy, send the result.
#
while (<STDIN>) {
    chomp;
    if (/^([^=]+)=(.*)$/) {
        $attr{substr($1, 0, 512)} = substr($2, 0, 512);
    } elsif ($_ eq '') {
        if ($verbose>2) {
            for (keys %attr) {
                syslog $syslog_priority, "Attribute: %s=%s", $_, $attr{$_};
            }
        }
        fatal_exit "unrecognized request type: '%s'", $attr{'request'}
            unless $attr{'request'} eq 'smtpd_access_policy';
        my $action = smtpd_access_policy();
        syslog $syslog_priority, "Action: %s", $action if $verbose>1;
        print STDOUT "action=$action\n\n";
        %attr = ();
    } else {
        syslog $syslog_priority, "warning: ignoring garbage: %.100s", $_;
    }
}

exit 0;

Comment: updated with pseudocode and python code for *SMTP access policy delegation*


Por que usar const depois da função?

Question: Notei em alguns códigos de outros programadores de C++ que usam funções como:
bool CClass::isRunning() const
{
    return this->_running;
}

Eu entendi que dessa maneira não é possível modificar nenhum membro da classe, apenas serve para retorno de valor. Então, por que usá-las? Existe algum benefício nisso? Não seria mais fácil e mais econômico chamar diretamente a variável do que criar uma função para isso?
Answer: Na verdade não se usa depois de uma função e sim depois de um método. Afinal o que ele faz é tornar o ponteiro para this, ou seja, para a instância atual, uma constante. Então você não pode alterar nenhum membro deste objeto. É uma forma de garantir que o método não produza efeitos colaterais no objeto.
Na verdade membros que sejam declarados como mutable podem ser alterados mesmo assim, então não é bem garantido.
Na medida do possível é útil fazer todos os métodos const. Isso facilita algumas otimizações e dá uma boa indicação para evitar que alguém altere o algoritmo de forma inapropriada e mexa no estado do objeto. Se um programador resolver criar mudança de estado no código ele terá que tirar o const para compilar. E isso é uma mudança na API da classe. Isso é uma proteção.
Vamos supor que essa classe tenha um método assim:
void CClass::Run() {
    this->_running = true;
}

Coloquei no GitHub para referência futura.
Não pode usar const porque o método está mudando o estado do objeto.
De fato pode ser melhor chamar direto a variável, se você tiver controle total sobre o código. Tem certeza que no futuro o acesso a essa variável não será só pegar o seu valor e terá um algoritmo que o manipule? Isso é feito preventivamente para depois não ter que alterar todos os códigos que vão consumir a sua classe. Feito com o método você cria uma indireção, o que flexibiliza o acesso.
Isso vale especialmente quando há linkedição dinâmica (DLL) onde você nem sabe como será chamado o código e uma indireção se faz necessária.
Comment: Ah sim. Entendi! Obrigado.

Por que usar const depois da função?


Como pegar apenas uma célula de um arquivo CSV com PHP?

Question: Como faço para pegar apenas uma linha de uma coluna específica? No código abaixo ele me mostra todas as linhas e todas as colunas que tem no arquivo CSV. Quero apenas uma célula específica.
Exemplo:
Coluna B - Carros
Linha 2 - Fox
Célula da linha e da coluna - B2
Quero pegar apenas essa célula B2 e imprimi-la na tela.
<?php
// activar Error reporting
error_reporting(E_ALL);

// carregar a classe PHPExcel
require_once 'Classes/PHPExcel.php';

// iniciar o objecto para leitura
$objReader = new PHPExcel_Reader_CSV();$objReader->setInputEncoding('CP1252');
$objReader->setDelimiter(';');
$objReader->setEnclosure('');
$objReader->setSheetIndex(0);
$objPHPExcel = $objReader->load("itens.csv");

//Pegando o total de colunas
$colunas       = $objPHPExcel->setActiveSheetIndex(0)->getHighestColumn();
$total_colunas = PHPExcel_Cell::columnIndexFromString($colunas);

//Pegando o total de linhas
$total_linhas = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();

echo "
";
// navegar na linha
for($linha=1; $linha<= $total_linhas; $linha++){
    echo "
";
    // navegar nas colunas da respactiva linha
    for($coluna=1; $coluna<= $total_colunas -1; $coluna++){
        if($linha==1){
        // escreve o cabeçalho da tabela
            echo "".utf8_decode($objPHPExcel->getActiveSheet()->getCellByColumnAndRow($coluna, $linha)->getValue())."	";
        }else{
        // escreve os dados da tabela
            echo "".utf8_decode($objPHPExcel->getActiveSheet()->getCellByColumnAndRow($coluna, $linha)->getValue())."	";
        }
    }
    echo "
";
}
echo "
";
?>

Comment: No caso, você apenas fez o `for` para gerar a tabela a partir do CSV, correto? Tem como você descrever como tentou fazer para obter somente essa célula? Pode ser só uma descrição da lógica, caso não saiba qual é o código.
Comment: Acho que não entendi. Eu não estou pegando apenas uma célula, eu peguei tudo que estava no arquivo CSV. Eu quero pegar apenas 1 célula. que no meu arquivo ela se chama AI2.
Comment: Foi o que eu disse. O seu código na pergunta está pegando todo o conteúdo e gerando uma tabela HTML, mas não possui nenhuma tentativa de encontrar apenas a célula desejada. Você chegou a tentar fazer algo nesse sentido?
Comment: Ah sim. Não, eu não sei como faz isso. Por isso vim aqui perguntar, eu não sei fazer que ele gere apenas uma célula, apenas sei gerar a tabela toda.
Answer: Desconstrua o CSV pegando o índice da coluna pela primeira linha e buscando o valor pela linha especificada, por exemplo, para a tabela:
1 | a  | b  | c  |
2 | AA | BB | CC |
3 | XX | YY | ZZ |

Queremos o valor da célula B2, então:
$csv = "a,b,c\nAA,BB,CC\nXX,YY,ZZ";
$celula = array( 'b','2' );

// Crie um array com as linhas
$linhas = explode( "\n", $csv ); // array( 'a,b,c', 'AA,BB,CC', 'XX,YY,ZZ' );

// Crie um array com as colunas da primeira linha
$header = explode( ',', $linhas[0] ); // array( 'a', 'b, 'c' );

// Crie um array com as colunas da linha que vc quer buscar
$colunas_linha = explode( ',', $linhas[ $celula[1]-1 ] ); // array( 'AA', 'BB, 'CC' );

// Pegue o índice da coluna que você quer buscar pelo nome
$indice_coluna = array_search( $celula[0], $header, true ); // 1

// Depois pegue o valor da célula buscando o índice no array da coluna
echo $colunas_linha[$indice_coluna]; // 'BB'

ps.: no exemplo a numeração não faz parte da tabela (como é comum em CSV), incluí somente pra ficar mais clara a visualização
Exemplo funcional


How to find the self-intersection point of $x^x=y^y(x,y>0)$?

Question: As the figure below shows, the graph of the implicit function $$x^x=y^y,(x,y >0)$$ composes of a straight line and an arc, which of the two have an intersection point $P$.

How to find the coordinates $(x_p,y_p)$ of $P$? Does there exist a closed-form solution?
Comment: The line in the figure is $x = y$, so $x_p = y_p$ should be true. (If there is any intersection : the answer below hints there may not be one).
Comment: @астонвіллаолофмэллбэрг That's right! And then?
Comment: I have also gotten this issue which an answer below has recorded : that of there being no intersection. But I think this is an issue of Desmos  rather than of the function. I am going to say more : I think the intersection point has $x$ (and $y$) coordinate  $\frac 1e$, which is the minimum of the function $x^x$ on the interval $[0,\infty)$. This is what the coordinates seem to indicate. I can't come up with a proof, simply because I cannot even see the explicit relation between $y$ and $x$. I may not need the explicit relation, though.
Comment: The only solution of equation $x^x=y^y$ is $x=y=1$. so the coordinates of p is $(1, 1)$.
Answer: Let's use the following theorem from multivariable calculus:

If the function $f$ is differentiable, the gradient of $f$ at a point is either zero, or perpendicular to the level set of $f$ at that point.

Taking the function $f=x^x-y^y$ we see that the gradient at the intersection point of yours must be zero (it is impossible for a nonzero planar vector to be perpendicular to two linearly independent vectors simultaneously).
Solving the system
$$\nabla f=\left(x^x(1+\log(x)),y^y(1+\log(y)) \right)= \mathbf{0} $$ gives
$$x=y=\mathrm{e}^{-1}. $$
Answer: Another Solution
Since $x^x=y^y$, hence ${\rm d}x^x={\rm d}y^y,$ i.e. $x^x(\ln x+1){\rm d}x=y^y(\ln y+1){\rm d}y.$ We obtain the derivative $$\frac{{\rm d}y}{{\rm d}x}=\frac{x^x(\ln x+1)}{y^y(\ln y+1)}=\frac{\ln x+1}{\ln y+1}.$$
Notice that $$x_p=y_p,$$ and $$\dfrac{{\rm d}y}{{\rm d}x}\bigg|_{x=x_p}=-1.$$ Thus, we can set up an equation as follows $$\frac{\ln x_p+1}{\ln x_p+1 }=-1.$$ Therefore,$$\ln x_p=-1.$$
As a result, $$x_p=\frac{1}{e}.$$ It follows that $$(x_p,y_p)=\left(\frac{1}{e},\frac{1}{e}\right).$$
Am I right? Indeed,there exists a flaw here, because the expression of $\dfrac{{\rm d}y}{{\rm d}x}=\dfrac{\ln x+1}{\ln y+1}$ has no definition at $x=y=\dfrac{1}{e}$. How to remedy the problem?


Get thumbnail image URL for Video

Question: I've got a Video field and the Video Thumbnail is uploaded by the user.
I've got a View which is generating JSON (with the views_datasource extension). I want to include the image url to the Video Thumbnail has one of the fields in my JSON. I've set the formatter on this field to be "Video Thumbnail":

However, the value shown in my JSON output is the url to the original video and not to the Thumbnail image.
So, I tried enabling Rewriting on that field in the Views configuration. I used the [field_video-thumbnail] token to try to get the URL of the Thumbnail image...

but what I get in my JSON is the fid of the Image and not the URL of the image.
  "node" : {
    "title" : "Test 6",
    "body" : "
test
\n",
    "field_image" : null,
    "path" : "/blog/test-6",
    "created" : "Monday, November, 2012",
    "field_video" : "38"
  }

How can I get the Image Thumbnail URL?
Comment: dont rewrite output and choose option "link video thumbnail" to url
Comment: When I do that it just generates a link to the Video and not the Thumbnail Image.
Comment: what options are in "link video thumbnail" ?
Comment: "Nothing" "File" and "Content". I tried them all and didn't get any good results.
Answer: You are looking for the Image URL Formatter module.
Answer: You can use php views, add php field  and put this code (change the video field name to yours) in output part
<?php
$file=file_load($data->field_field_video[0]['raw']['thumbnail']);
print file_create_url($file->uri);
?>

Get thumbnail image URL for Video


How do I install node packages on sublime text

Question: I was just wondering if it's possible to install node packages from sublime instead of the command line. And if it is how do I go about it
I don't mean package control, I mean installing npm packages e.g the twilio  helper library.
Comment: If sublime lets you open a terminal, then you can do it "from sublime". You will still need to type the command into a terminal window though.
Comment: There's no terminal on sublime that's why I had to use the command line, I was just wondering if there was a much more efficient way to do it
Answer: Yes,its possible,
First you need to install the sublime package control.
Follow the following steps to install the package controller:-

Open sublime text.
Click on the tools bar.
Select the Command Palette option.
Type the following: Install Package Control
Once the search result appears click on it or hit enter. Once the package control is installed, open the install Packages via the package control by performing the following steps.
Open sublime text again.
Click on the tools bar.
Select Command Palette.
Type Package Control: Install Package and hit enter.  Then a menu will appear showing along with search box different packages, search what you want and hit enter to install it. In your case you wanted to install node, you can do so by typing it in the search box. eg. Nodejs.
Comment: No. Package Control is for managing Sublime Text plugins, not Node packages. Installing *nodejs* that way will install a package with "nodejs snippets and bindings for Sublime Text 3" and not Node.js itself.
Comment: I guess that's what he wanted as an answer!
Comment: No I want to install node packages, like helper packages and things like that


How to get luminance of an HDR image

Question: I am currently working on a project where I have a bunch of HDR images and I need to get the median luminance of each image and plot them.
I am trying using opencv but I am unable to find a function or way to get the median luminance of an image. Is there any way to do it? I am sure there should be some ways but I am just can't see to find it.
Comment: The term "Luminance" is not well defined. Please do some research and define "Luminance". The term "HDR images" is not well defined, please do some research and define the standard and the format of the HDR images. Assuming you can't post an HDR sample image, consider posting a 10x10x3 NumPy array that represents the content of a raw HDR image (explain what the sample represents).
Comment: convert to LAB colorspace and extract the L (luminance) channel. Then get the average (mean) of the luminance channel or the median of the luminance.  See cv2.cvtColor() to change color spaces and see cv2.mean() to get the average or np.median() for the median.
Comment: @fmw42 can you please share a code example? I am finding it hard to get it work, Thanks in advance
Answer: Solved the issue thanks to the comment of @fmw42. Writing his comment as an answer so that it helps others.
@fmw42 commented -

convert to LAB colorspace and extract the L (luminance) channel. Then
get the average (mean) of the luminance channel or the median of the
luminance. See cv2.cvtColor() to change color spaces and see
cv2.mean() to get the average or np.median() for the median.

How to get luminance of an HDR image


Is there a key change in this chord progression?

Question: I found this chord progression on my guitar last night :
<code>C - Csus4 - Gsus4 - G - Gm7add(#5) - Am7add(#5) - Asus4 - A
</code>
It sounds pretty nice to me but when I look at it theoretically I just can't see why. What is especially bugging me is the G -> Gm -> Am part. Is there some kind of keys changes or modulation happening ? Is there a way to explain why this feels so right ? (if voicing of those chords is relevant I could edit them in)
Answer: Although unusual in terms of 18th-century common-practice music theory, this and any connection of harmonies doesn't need some sort of justification. As a musical concern, all that matters is you like it and have ideas about how you'd like to use it.
However, I think there's one aspect that could be a partial explanation of why the progression works for you: common tones. Between every one of the chords—including the ones that are most outside of a single key—share one or more common tones with its predecessor and successor. This is a common technique in a lot of late 19th- and early 20th century European music, and is sometimes referred to as "linear harmony." There are many passages in, for example, Liszt, of successions of chords where some notes are held while other pitches move by a step. It's possible that this is a place where your specific voicing might be significant, because, in a linear harmony passage, the more that common tones are held in the same places and the stepwise connections are truly stepwise (rather than jumping around in sevenths and ninths), the more that a listener can follow the thread.
For example, the succession of chords
Cmin – B – G – Bmin
is certainly not standard in a common practice sense, but can be, especially in smooth voicings, and quite clear connection. The move from Cmin to B holds a note common (the Eb/D#) while the other two notes slide down a half step (C to B, G to F#). Neo-Riemannian theorists call this connection P', and it's fairly common. The move from B to G is called a chromatic mediant relation—two triads of the same quality whose roots are a third apart—which always will have one common tone, one chromatic alteration and one stepwise change. The final move from G to Bmin has two common tones (B and D) and one half step move (G to F#). The Neo-Riemannians call that one L.
Your progression is more sophisticated than that, and whether any particular example appeals to you personally is subjective, but I think the proliferation of common tones throughout you example is at least part of the sauce that makes it stick together.
Comment: That P' is also SLIDE, correct?
Comment: Yes! That's Lewin's term I believe. I find P' to be a bit more useful, because it's shorter and it makes an explicit connection to the fact that it's the inverse of the Parallel operation, but SLIDE is well-known too.


Inferring parent distribution using phase of 2D discrete fourier transform of random image

Question: Suppose I have an NxM matrix with real entries $S_{n,m}$ which are iid with zero mean. Say $n \in [0, 1, ..., N-1], m \in [0, 1, ..., M-1]$.
From $S_{n,m}$ I can compute the 2D discrete fourier transform:
$$\eta_{j,l} = \sum_{n=0}^{N-1} \sum_{m=0}^{M-1} S_{n,m}~e^{-2\pi i (nj/N + ml/M)} $$
which has amplitude matrix $F_{j,l}$ and phase matrix $\Phi_{j,l}$, defined from:
$$ \eta_{j,l} = F_{j,l} e^{i\Phi_{j,l}}$$
Overall Question:
Does the phase matrix $\Phi_{j,l}$ alone contain significant information about the distribution from which the $S_{n,m}$ were drawn? I have a situation where I can only know $\Phi_{j,l}$, and want to infer something about the distribution of the $S_{n,m}$.
Concrete Example (this is the kind of thing I'd like to do):
Suppose I have two phase matrices $\Phi_{j,l}^{A}$ and $\Phi_{j,l}^{B}$. I know that one of them was generated from an $S_{n,m}$ matrix drawn from the t-distribution with high degrees-of-freedom = 1000 (so it's close to the normal distribution), while the other was drawn from a t-distribution with degrees-of-freedom = 2 (very heavy tails). I don't have the associated amplitude matrices.
Is there any hope of deriving a procedure to determine which distribution was used to produce which phase matrix, with a better than 50% success rate? If so, what kind of methods can be used?
EDIT (following some further investigation):
Experimentally the answer seems to be 'yes, at least in some cases' -- but I would appreciate an explanation of why.
Firstly, since the phase is unaffected by positive rescaling of $S_{n,m}$, we could never hope to detect differences in the scale of two distributions used to generate them. But it seems we can detect other differences.
Experimentally, say $Y_{n,m}$ is the inverse DFT of $e^{i\Phi_{j,l}}$ (like looking at the original image with all amplitudes set to 1). The code below investigates the distribution of this in the example above. It appears the Kurtosis of $Y_{n,m}$ is generally much higher for the low degrees-of-freedom t-distribution -- so for this particular problem, we would have a good chance of determining the correct parent distribution from the phase alone.
Can anyone explain why the disribution of $Y_{n,m}$ retains some information on the kurtosis of the distribution? This is not obvious to me.
<code>kurtosis<-function(x){
    n = length(x)
    n * sum((x - mean(x))^4)/(sum((x - mean(x))^2)^2)
}

N = 20
M = 20

nreps = 20

kurtosis1000_store = rep(NA, nreps)
kurtosis2_store = rep(NA, nreps)

pdf('Inverse_dft_phase_plots.pdf', width=8, height=8)
for(i in 1:nreps){
    # This S uses the t-distribution with a large df = 1000
    S_t1000 = matrix( rt(400, df=1000), ncol = M, nrow = N)

    # This S uses the t-distribution with a small df = 2 (finite mean but not
    # variance)
    S_t2 = matrix( rt(400, df=2), ncol = M, nrow = N)

    # Phase
    Phase_t1000 = Arg(fft(S_t1000))
    Phase_t2 = Arg(fft(S_t2))

    # If we only have these phase matrices, could we make a statistical test to
    # determine which came from the low-df / high-df distributions?
    par(mfrow=c(2,2))

    # Try to look at the inverse DFT exp(i*Phase)
    # There seem to be obvious differences (the one associated with df=2 has
    # heavier outliers, greater kurtosis, etc)
    t1000 = Re(fft(exp(1i*Phase_t1000), inverse=T)/(N*M))
    t2 = Re(fft(exp(1i*Phase_t2), inverse=T)/(N*M))
    image(t1000, main='df = 1000')
    image(t2, main='df = 2')
    hist(t1000, main='df = 1000')
    hist(t2, main='df = 2')

    kurtosis1000_store[i] = kurtosis(t1000)
    kurtosis2_store[i] = kurtosis(t2)
}
dev.off()
</code>
This leads to
<code>> summary(kurtosis1000_store)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  2.680   2.817   2.921   2.946   3.029   3.471

> summary(kurtosis2_store)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  5.548  19.880  56.040  86.500 120.500 310.400
</code>
Comment: Thinking about the kutosis comment.  In (my sketchy recollection of) the proof of the Central Limit Theorem you take the Fourier transform of the distribution, then show that the non-second order terms die in the limit, which leaves you a distribution determined only by its first two frequencies.  Could something similar be happening?  The frequency terms can detect the presence, but not the magnitude, of various moments?
Answer: I thought about this some.  I don't think I've figured everything out, but I may as well get my thoughts on paper.
Let me start with the case of a continuous signal, and then reason by analogy.  So let's say that for a function $f: R \rightarrow C$, I write $\hat{f}$ for its fourier transform, and $\check{f}$ for its inverse transform.
Now, I'm going to model your situation by taking two real valued functions $f_1, f_2 : R \rightarrow R$, and analyzing what the relationship must be if the phase of their fourier transforms is always equal.  That is, if:
$$ Arg(\hat{f_1}(\xi)) = Arg(\hat{f_2}(\xi)) $$
for all frequencies $\xi$.  The relationship above holds if and only if:
$$ \hat{f_1}(\xi) = r(\xi)\hat{f_2}(\xi) $$
for $r$ a real valued function.  Taking the inverse transform of this relationship, and using the convolution identity:
$$ f_1(t) = (\check{r} * f_2)(t) $$
Now, $h = \check{r}$ is the inverse transform of a real valued function, and hence must satisfy $h(-t) = \overline{h(t)}$.  It's clear that all such functions, when decomposed into their real and imaginary parts:
$$ h(t) = e(t) + o(t)i $$
must have $e$ and even function and $o$ and odd function.  But then:
$$ f_1(t) = (e * f_2)(t) + i(o * f_2)(t) $$
Since $f_1$ is real valued, the imaginary part of this expression must vanish, and hence we are led to the relationship:
$$ f_1(t) = (e * f_2)(t) $$
So $f_1$ and $f_2$ are related by convolution with an even function.  It's easy to reverse these steps, and convince yourself that this is actually an equivalence:
$$ Arg(\hat{f_1}(\xi)) = Arg(\hat{f_2}(\xi)) \iff f_1(t) = (e * f_2)(t) $$
The upside is that you can tell some things about a function $f$ from only its phase, without knowing its amplitudes.  The things you can discern are exactly those properties that are preserved when convolving with an even function.  A couple that seem geometrically evident are:

If $f$ has thick tails, so will its convolution with an even function.
If $f$ is skew, so will be its convolution with an even function.

Ok, so to the discrete case.  The two essential properties I used in the argument were the convolution property, and the fact that the transform of a real valued function is hermitian (satisfies $h(-t) = \overline{h(t)}$).  Both of these have discrete analogs.  The dft convolution property is well known, and the analog of the hermitian property is
$$ \hat{x}_{N-k} = \overline{\hat{x}_{k}} $$
for real sequences $x_k$.  Using these properties, the argument should go through, and we can conclude that sequences whose discrete fourier transforms agree up to a phase must differ by convolution with an even sequence.
Now I'll take a stab at explaining your kurtosis observation, but I'm not so sure it's correct.  When you randomly fill in elements of the array by selecting from the distribution with long tails, it is probable that there is an asymmetry in the array caused by an extreme observation on one side or another of the center.  Convolving with an "even" array preserves this asymmetry.  This is why high kurtosis measures are preserved.


change mysql table character set

Question: I have a table that data was inserted in it some time ago.  data included by php and  character set in it was utf-8 .
mysql_query("set names utf8");

now ,I need this table in another project which all data will show on php mysql default character set.
problem : my data is persian, when I set charachter set utf-8, every things is ok, but without character set data convert to the "?????" what should I do?!
I want to import all data form old table to new table on new character set !!
Comment: Use UTF-8. If the data is unicode, use unicode. There is no reason for the "other project" to leave the charset decision to MySQL.
Comment: Check this: http://www.devcha.com/2008/03/convert-existing-mysql-database-from.html and http://dev.mysql.com/doc/refman/5.0/en//charset-conversion.html
Answer: Try this might help you
<?php

   header('Content-Type: text/html; charset=utf-8');
?>
and then in the connection

<?php
 $dbLink = mysql_connect($argHost, $argUsername, $argPassword);
    mysql_query("SET character_set_results=utf8", $dbLink);
    mb_language('uni');
    mb_internal_encoding('UTF-8');
    mysql_select_db($argDB, $dbLink);
    mysql_query("set names 'utf8'",$dbLink);
?>

Comment: I dont want to set character set utf-8 , I want to convert my old table to new one that I havent to change my character set just for this table!!is it possible?!!
Answer: ///
$SERVER = "http://localhost:8084";
$db = mysql_connect('localhost','root') or die("Not Connected");
$sldb = mysql_select_db('vifarbydata',$db);

mysql_query("set names utf8");
$sql = "SELECT * FROM `region`  ";
$res = mysql_query($sql);
while($h=(mysql_fetch_array($res)))
{
    $row[] = $h;
}
mysql_close($db);
/// set another character set
$SERVER = "http://localhost:8084";
$db = mysql_connect('localhost','root') or die("Not Connected");
$sldb = mysql_select_db('vifarbydata',$db);
foreach ($row as $item)
{
    echo $sql = "insert into  `region2` (id,name,myId) values (".$item['id'].",'".$item['name']."','".$item['myId']."')  ";
    mysql_query($sql);
}

Answer: @afsane, using mysqldump, you can dump the data from old_table and then import it into the new_table which has the new character encoding.
mysqldump -u user -p --no-create-info schema old_table > old_table.dump
mysql -u user -p schema new_table < old_table.dump

This will be much faster than doing a conversion via PHP.

change mysql table character set


Enabling SSL for ASP.NET 5 project in Visual Studio 2015 Community RTM

Question: Most tutorials suggest that you can enable SSL for the website by going to properties of the project and then ticking the "Enable SSL" checkbox. However for my ASP.NET 5 projects in Visual Studio 2015 Community (Microsoft Visual Studio Community 2015 Version 14.0.23107.0 D14REL) this option doesn't exist (see the screenshot ).
I was able to workaround it by manually adding https protocol binding in applicationhost.config (following pre-RTM instruction in https://github.com/AzureADSamples/WebApp-OpenIdConnect-AspNet5), but I found out that Visual Studio is overwriting this file from time to time, which forces me to do the manual edit over and over again.
When I create a new Web application project, the "Enable SSL" is available only when I use ASP.NET 4.5 templates, but not when I use ASP.NET 5 Preview templates. Is there a way to configure this option for ASP.NET 5 projects in a way that persists?
Answer: I ran into the same problem as you. Problem is, there are two "Properties" for a project. If you right click on the project node in Solution Explorer and choose Properties, you will see the properties window that you show above, and no, it doesn't have "SSL Enabled" as an option. However, with the project node in Solution Explorer selected, if you view "Properties Window" (an option in View menu) then you will see the (normally docked) properties window which has this option. By the way, the difference between the two windows in View menu is "Properties Window" (the one you want) and "Property Pages" (the one you show above, not the right one). However once you get to Properties Window, although you'll be able to enable SSL, the port will be read-only. After much reading on that topic, I think all you have to do is edit the bindings in the applicationhost.config file that automatically gets created:
path from solution: ./.vs/config/applicationhost.config
xpath within file: /configuration/system.applicationHost/sites/site[@name="{your site name here}"]/bindings/binding[@protocol="https"]/@bindingInformation="*:{port}:localhost"
Comment: Thanks for pointing out the location of an applicationhost.config file in the .vs folder. Removing the file and clicking "Create Virtual Directory" in Property pages solved a lot of problems for me.
Answer: RTM, RC2 & RC1 Answer
You need to use launchSettings.json in the properties folder of the project. Note the sslPort setting. Note that for RC1 ASPNETCORE_ENVIRONMENT becomes Hosting:Environment.
{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:1025/",
      "sslPort": 44300
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "web": {
      "commandName": "web",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Beta 8 Answer
You can edit the .xproj file and add the SSLPort element to add it manually but this should really be available to any version of VS and I'd advise you to raise an issue on the ASP.NET Tooling GitHub page:
<PropertyGroup>
    <SchemaVersion>2.0</SchemaVersion>
    <DevelopmentServerPort>1025</DevelopmentServerPort>
    <SSLPort>44300</SSLPort>
</PropertyGroup>

The port number must be a number between 44300 and 44399.
Comment: @Blaise Updated for RC2.
Comment: Is there a RC2 answer?
Answer: Change the Project Url in the Web tab of your Project's settings to:
https://localhost:44300/
The port number can be changed, but it needs to be in the 44300-44399 range.
Answer: Check out this post
http://weblogs.asp.net/scottgu/released-today-visual-studio-2015-asp-net-4-6-asp-net-5-ef-7-previews
and read the section on SSL.
Comment: The problem is that there was/is a bug in VS properties panel, which hides it in high-DPI screens (https://github.com/aspnet/Tooling/issues/188#issuecomment-144479315). I found it's possible to access the setting by manipulating size of window / panel.


jquery bind action to alert box

Question: I want to bind a action to the box that show up use alert
like I have this code in my js file
...
alert('sss')
...
when this code run, a dialog box will show up, and a ok button within it, I want bind a action to that Ok button
is it possible?
you may curious why I need this
I can try to explain but I am not sure I will make it clear
there are one link that I will click to make some change to db use ajax, and after that will trigger another ajax to get some info from server, problem is the second ajax will not wait the first ajax to finish, so it get the old data
this problem only exist in ie, seem async: false not work in ie
when first ajax finish, it will be a alert call, so I want bind second ajax to this
Comment: did you try some code yourself...
Comment: alerts are synchronous actions, why not simply call the next ajax method after the "alert" code?
e.g.:
alert('hello');
callNextAjax();
Comment: @TheZuck, not work, even `if alert('hello') callNextAjax()`
Comment: see shweta's answer, this is what I was talking about (assuming you have an alert in the complete section.  I didn't mean to do an if, just call the two methods one after the other.
Answer: try to call the second ajax in a complete callback of first ajax,
e.g.
<code>$.ajax({
  url: '/some_url',
  complete: function(data) {
    // call your second ajax here
  }
</code>
});

jquery bind action to alert box


Como saber quando a lei de Brooks se aplica?

Question: "Acrescentar mais gente em um projeto de software atrasado resulta em um atraso ainda maior".
Porém quando sei que essa lei se aplica, para toda lei existe exceções.
As vezes um projeto realmente não está atrasado por falta de mão de obra qualificada?
Comment: Não sei se dá para responder isto. Acho mais fácil responder se o projeto vai atrasar ou não, o que já não é fácil. Pode haver sinais, mas se fossem óbvios ninguém cometeria esses erros. Mas até onde sei a questão é justamente não colocar mais gente sem qualificação e sim substituir por gente qualificada. Ou melhor ainda, começar com gente qualificada. Tem um problema em gente qualificada: ela vai dizer que não dá pra cumprir aquele prazo maluco inventado. Se toda lei tem exceções, algumas não terão :P Sei lá se essa tem ou não. Nem sei se esta pergunta pode ser considera *on-topic*.
Comment: Para cada pessoa nova no projeto, uma que já trabalha deve parar seu trabalho para explicar as dúvidas para os novatos.
Comment: Concordo com o @rray, e entendo seu ponto de vista bigown.
Porem eventualmente a pessoa contratada, deve passar por aquela curva de aprendizado e agregar valor ao desenvolvimento. e acho que essa era a discusão que queria levantar. Também não sei se é on-topic ou deveria ser feita no Project Management
Comment: Não é uma questão adequadamente classificada como **projeto-de-software** (*software design*). Remover esta marca facilitará a localização de questões.
Answer: Existem vários diferentes pontos de vista quanto a cada aspecto de um projeto de software; e muitos destes pontos são muito bem embasados. Toda esta diversidade pode trazer a noção de que este é um assunto subjetivo onde nenhuma resposta está certa, nem errada.
No livro onde Brooks propõe esta lei, ela figura em meio a várias outras sentenças curtas, sem muita explicação. Mas esta sentença em si tem uma breve explicação logo no parágrafo seguinte:

"Adicionar pessoas a um projeto de software aumenta o esforço total necessário de três maneiras: o trabalho de reparticionar o projeto e a perturbação que o reparticionamento causa, treinamento das novas pessoas, e o aumento do esforço em intercomunicação."

Sobre a comunicação em específico ele fala em outro parágrafo que quanto mais gente no projeto, maior o custo e maior a dificuldade da comunicação.
Às vezes um projeto realmente não está atrasado por falta de mão de obra qualificada?
Talvez Brooks não tenha descartado este aspecto ao formular sua lei, pois no mesmo livro ele próprio menciona:

"Programadores profissionais muito bons são dez vezes mais produtivos que programadores medianos*, com o mesmo treinamento e nível de experiência de dois anos."

*Aqui ele usa a palavra "poor", que eu acho que seria melhor traduzida neste caso para "medíocre", mas fica a seu critério.
Se ele acredita nisso, por que formulou a lei? O projeto não poderia ser salvo trazendo pessoas mais qualificadas?
O problema talvez seja identificar as pessoas qualificadas. A menção não diz "programadores mais qualificados", ela diz "programadores muito bons, com a mesma experiência e treinamento". Ou seja: a rigor, com a mesma qualificação.
Exceções à Lei de Brooks
Ora, isto só é uma lei porque ele disse que é :D Você pode aplicar as exceções que bem entender e provavelmente no próprio livro dele você vai encontrar texto que parece contradizer a lei.
Algumas exceções óbvias (fáceis de elaborar):

Em vez de adicionar pessoas, você pode substituir, não adicionando custo de comunicação nem gestão.

Você pode substituir por pessoas que já possuam o devido treinamento, sem adicionar este custo de tempo e dinheiro ao projeto.

Você pode delegar trabalho já delimitado para as novas pessoas em vez de repartir o projeto.

Pelo que tenho lido e observado, todavia, nenhum projeto é devolvido à agenda pela simples substituição ou adição de desenvolvedores. O que tenho visto é que quando um projeto muda de rumo por ter havido substituições, a primeira substituição que ocorreu foi a da gestão do projeto.
E eu te alerto que você não vai encontrar muita literatura dizendo para pôr pessoas mais qualificadas no projeto a fim de trazê-lo de volta para a agenda, pois isso seria transferir a culpa para o peão (o programador) em vez de mantê-la no âmbito da gestão, o que é politicamente mais correto.


How to interpret regression coefficients when outcome variable was transformed by Box-Cox

Question: I try to do a linear regression of a positive continuous dependent variable (outcome) with several independent variables (all of them are categorical / binary). I had many troubles to get Gaussian residuals (the distribution of my outcome variable is not Gaussian itself).
I tried a lot of transformations for the outcome: log, square root, inverse... and the best one is Box-Cox with a parameter: $\lambda = -3$. The regression is correct, the residuals are Gaussian, and homoscedastic. But I have found the Box-Cox is not the easiest thing to interpret. The original outcome represent a delay and there is no way to interpret the transformed outcome with a mix of power and inverse. And when I want to come back to my original outcome, I have cube root (or power 1/3).
My questions are:

How is the change of a given binary variable modality on my original outcome, knowing the corresponding coefficient?
Can I do the same thing with the confidence interval (2.5% and 97.5% limits) of the regression coefficients?
Answer: Why use Box-Cox here at all? Consider using a generalised linear model with power link. That way you get predictions on the scale of the original variable automatically.
Why sacrifice all on the altar of Gaussian residuals? If you use a generalised linear model, you can use other error families.
If I understand you correctly, your outcome is delay, i.e. some lapse measured in time units. Reciprocal links (or transformations) are often natural for such variables, as the reciprocal of a time is some kind of rate (e.g. a speed of processing, or some such).
I don't understand the question on "change of a given binary variable modality".
Comment: I understand for the power link with a GLM, we will try it. About using other error families, we tried Gamma regression but we didn't know anything about residuals analysis of this regression (and find few bibliography). In our Gamma regression model, the residuals are distributed like a Gamma distribution and not like a gaussian distribution. Is that correct ? Do you know more, or have references about residuals diagnosis on Gamma regression ?
Comment: It's not much different from any other error family. Best to have a quantile-quantile plot for gamma rather than for Gaussian. There are some specific comments in McCullagh and Nelder http://www.crcpress.com/product/isbn/9780412317606


Hidden Markov Model with Probabilistic Observations

Question: I have an HMM with $N$ states and $T$ possible obsevations where $A \in \mathbb{R}^{N \times N}$ is transition probability matrix and $B \in \mathbb{R}^{N \times T}$ is emission probability matrix. I follow the introductory text https://web.stanford.edu/~jurafsky/slp3/A.pdf and understand the concepts and formulas.
However, in my case observations are also probabilistic. It means instead of observing only one state, I have a probability vector of observed states at each discrete time. I can modify the likelihood and decoding algorithms by summing over the observations with probabilities as weights. So, if the probability of being in state $j$ after the first $t$ observations for a particular observation $o_i$ at time $t$ is $\alpha_t(j)$, then for a vector of observation probabilities $o_t$ I can write
$$ \bar{\alpha}_t(j) := \sum_{i=1}^T o_{ti} \alpha_t(j) $$
Hopefully that makes sense, because I'm quite new to the topic. However, I'm not sure how to do the training with this setting. Is there a name for this kind of problem? Can you suggest me a reference if there is? Alternatively, is there an easy way to modify the training formulation to be used in this problem?
Comment: Aren't probabilistic observations the same as emission probabilities? i.e. a probability distribution over possible observations?
Comment: @AdamKells as I understand given the observation sequence we try to find the hidden state sequence depending on the transition and emission probabilities. But the given observation sequence is absolute, i.e. only one state is observed at each discrete step. However, in my case observations are probabilistic, so in a sequence $o_1o_2 \dots o_n$ each $o_t$ is a vector with probabilities of observations instead of a scalar number.
Answer: I'm pretty sure you can just update the emission probability matrix to take the probablistic observations into account.
There are a lot of ways we could add probablistic "measurement error" to the observations. Let's say that $\gamma$ is the probability that the observation accurately reflects the emission, and $1 - \gamma$ the probability that the observation is a random sample from the $T$ possible observations, and $T=3$ in this example.
$B_i = [b_i^1, b_i^2, b_i^3]$ is the vector of emission probabilities from state $i$ before measurement error, and so are also the observations probabilities in cases where no measurement error occurs), and $E = [\frac{1}{3}, \frac{1}{3}, \frac{1}{3}]$ are the observation probabilities on cases where measurement error does occur. Since the probability of measurement error occurring is $1 - \gamma$, the marginal observation probabilities are therefore
$$
\hat B_i = \gamma B_i + (1-\gamma)E \\
= [
\gamma b_i^1 + (1-\gamma)\frac{1}{3}, \
\gamma b_i^2 + (1-\gamma)\frac{1}{3}, \
\gamma b_i^3 + (1-\gamma)\frac{1}{3}
] \\
= [
\gamma b_i^1 + \frac{(1-\gamma)}{3}, \
\gamma b_i^2 + \frac{(1-\gamma)}{3}, \
\gamma b_i^3 + \frac{(1-\gamma)}{3}
]
$$
Comment: So this is one way of incorporating the measurement errors into the model and there could be others. However, I'm still not clear how this can be used in the training of HMM since marginal emission probabilities are changing at each discrete time step.
Comment: I'm sorry, you've lost me. Emission/observation probabilities don't change over time, they're just the probabilities of observing each outcome if the system is in a particular state.
Comment: Yes, I meant the marginal emission probabilities, $\hat{B}_i$. Because $E$ changes over time (at each measurement).
Comment: Ah, OK. To be honest, you've gone beyond my knowledge in that case, but I suspect that if the observation probabilities change over time, this isn't a Markov model any more, and it probably can't be estimated.


Simulation of time series with R

Question: I'm new on time series. I'm trying to solve an exercise on the simulation of an ARMA process.
The problem is the following:
Generate 100 simulations, each with n=60 elements of an ARMA(1,2) process with mean $\mu=1.25$ and parameters $\phi_1=-0.5$, $\theta_1=0.5$, $\theta_2=-0.7$ and $\sigma^2=0.5$
For each simulation estimate the mean and the first two correlation coefficients and find in how many simulations they are contained in the theoretical confidence intervals.
Ok so, I think that for one simulation of the ARMA(1,2) I should do something like:
x <- arima.sim(list(order = c(1,0,2), ar = -0.5 , ma=c(0.5, -0.7)), sd=sqrt(0.5), n = 60)

And this is one simulation, right? But then, for generate the other 99 simulation what should I do? Can I construct a kind of a loop?
Thank you in advance ! Cheers
Answer: M=matrix(ncol=60,nrow=100)
for(i in 1:100){
  x = arima.sim(list(order = c(1,0,2), ar = -0.5 , ma=c(0.5, -0.7)), sd=sqrt(0.5), n = 60)
  M[i,]=x
}

note that every row of matrix $M$ contains a simulation.
See also Stephan Kolassa comment for an alternative.
Comment: Or use `replicate()`, as in `M <- replicate(100, arima.sim(list(order=c(1,0,2),ar=-0.5,ma=c(0.5,-0.7)),sd=sqrt(0.5),n=60))` (note that then every *column* of `M` will contain a time series, not every row).

Simulation of time series with R


Does enumeration imply equinumerosity (one-to-one correspondence)?

Question: I know that the definition of denumerability states that a set $A$ is denumerable IFF there exists a one-to-one correspondence of $A$ with the set of Natural Numbers, i.e. $A$ and $\mathbb N$ are equinumerous. In Cantor's proof of the Non-countability of the Continuum, he showed that the set of real numbers in $(0,1)$ cannot be enumerated and therefore denumerable. So does this mean that if I can enumerate a set, it automatically implies the existence of a one-to-one correspondence with $\mathbb N$?
Thanks!
Comment: Well, just think about what you do when you enumerate the set..
Answer: Let's say you have a set $A = \{a_1, a_2, a_3. \dots \}$. Then you can always have the function $f: A\to \Bbb{N}$ where $f(a_n)=n$. What can be said about $f$?
Answer: In the context of set theory, enumerating a set means it is denumerable, and if a set is denumerable then it can be enumerated.
In some other contexts, like computability and recursion theory, the term "enumerable set" usually means "recursively enumerable" which means that the function which enumerates is recursive. This also means that the set is a subset of $\Bbb N$, or some other fixed countable set, and not an arbitrary set.
Finally, Cantor showed that $\Bbb R$ is not denumerable.


IList search help

Question: I have a IList<Customer> and I want to find a customer whose lastname='smith'. how do i do that? The .where looks like it might work but I don't understand the predicate needed to do this. Or is there a better way to search the list?
Thanks,
rod.
Answer: Try this, assuming that your IList is the customers object:
var smiths = customers.Where(c => c.LastName == "Smith");

Answer: To expand on the other posts:
Any method such as Where() that takes a predicate needs that predicate to return a boolean. That predicate will be evaluated against each element of the collection, and for each element where the predicate returns true, that element will be included in the resulting collection.
Keep in mind that Where() returns a collection (I believe IEnumerable<Customer> in your scenario, but I don't have VS open right now to verify) that you will need to get an individual element from using First() or Single() (among others). You can also use the predicate on any of the single methods such as Single() or Last() to avoid chaining Where(x => blah).Single().
Answer: If you want the first customer which his last name is 'smith', use FirstOrDefault
var customer = customerList.FirstOrDefault(c => c.LastName == "smith");

if (customer != null)
  // do code;

And If you want all the customers which their last name is 'smith', use Where:
var customers = customerList.Where(c => c.LastName == "smith");

foreach(var customer in customers)
  // do code;

Good luck!

IList search help


How to apply a function as soon as an element appears in jQuery?

Question: I know in jQuery that there's the function live() to suscribe to events as soon as an element appears. I just want to do something to an element as soon as it appears. I tried suscribing the elements to the "load" event but it doesn't work. How do you go about that?
Comment: See this question:

http://stackoverflow.com/questions/3840149/jquery-live-event-for-added-dom-elements
Answer: you can't use load to all elements . only : Img Body Iframe.
and you can't listen via live to the load event of elements other  the ones i mentioned.
what you can do - is when you add them to the Page - Then you know when its happened and then you can call your func.
Answer: If you control the code which creates and appends elements, you could trigger a custom event and handle it in a handler later.
Example
$('#add').click(function() {
    $('#container').append($('
Hello! I am a new div
')).trigger('div-added');
});

$('#container').bind('div-added', function() {
    alert('A div has been added');
});

Answer: Use .delegate() http://api.jquery.com/delegate instead of .live()
For your specific case consider livequery http://docs.jquery.com/Plugins/livequery
Answer: You can listen to DOMNodeInserted.  I know that works in Webkit and Firefox - I don't know about IE though.
It would look something like this:
$('body').bind('DOMNodeInserted', function(evt) {
    var addedElement = evt.target;
    // do whatever with `addedElement`...
})

Comment: `DOMNodeInserted` and other DOM mutation events have been deprecated in DOM 3. See http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents.


Map from $SL(2,\mathbb C)/SU(2)$ to $SL(2,\mathbb C)$

Question: I am trying to write a map $s$, such that $s: SL(2,\mathbb{C})/SU(2) \to SL(2,\mathbb C)$.
Using Iwasawa decomposition, I see that any element $g$ in $SL(2,\mathbb{C})$ can be written as $g = su$, where $u$ is an element of $SU(2)$ and $s$ is a matrix that is a product of two matrices $a$ and $k$, where $a$ is a member of the subgroup of diagonal matrices with positive diagonal components, and $k$ is a member of the subgroup of upper triangular nilpotent matrices.
However, I don't exactly see how to formulate this map; I see that it should come from this decomposition, but I am a bit stuck after that.
Thanks
Comment: Well, I think you need to specify which properties your map needs to have. Otherwise one can probably construct many different maps, for example a trivial one: $s(g) = 1$ for $g\in SL(2,\mathbb C)/SU(2)$ and $1$ is the identity element of $SL(2,\mathbb C)$.
Comment: Try the [polar decomposition](http://en.wikipedia.org/wiki/Polar_decomposition) and identify $SL(2,\mathbb{C})/SU(2)$ with the positive definite, skew-Hermitian matrices $P$ of determinant one. This gives you an obvious map $s:P \to SL(2,\mathbb{C})$.
Comment: You have too many $s$'es. The set $P$ of positive definite skew-Hermitian matrices is a subset of the group $G = SL(2,\mathbb{C})$. By *uniqueness* of the polar decomposition every $g$ is uniquely $g= pu$ with $p = \sqrt{a^\ast a}\in P$ and $u = p^{-1}a \in SU(2)$. This gives you a unique coset representative $p$ for each $SU(2)$-coset and hence the projection $\pi:SL(2,\mathbb{C}) \to SL(2)/SU(2)$ restricts to a bijection of the set $P$ with the quotient $SL(2,\mathbb{C})/SU(2)$. Then the map is just the inclusion $s: P \to SL(2,\mathbb{C})$ which maps $p$ to $p$, so $s(p) = p$.
Comment: Which you can then compose with $(\pi|_P)^{-1}: SL(2,\mathbb{C})/SU(2) \to P$ if you wish.
Comment: tb:  I guess my problem is that I don't see the 'obvious map'.  It is just s: P -> SL(2,C) such that p -> sp for s in SU(2)?
Answer: I don't think that the Iwasawa decomposition can help you, because $B \cap SU(2) \neq \{1\}$, so you have to work with the subset of $B$, where the diagonal entries are strictly positive.
Answer: I hope it helps viewing SL2(C) as the complexification of SU(2), which is the compact real form, hence exhibiting a "doubling" construction allowing to look at a decomposition (Re & Im) and project etc.
Alternatively SL2(C) has two real forms, depending on the signature of the Killing form: SL2(R) (non-compact with signature (2,1)) and SU(2) (signature (0,2)); then it is clear the the complexification of the real non-compact form SL(2;R) is the non-compact SL(2;C) (not changing signature), helping understand why the same complexification of SU(2), with negative definite Killing form "turns into" the "same" Lie algebra and group (over complex numbers as coefficients there is only one signature).


Python Selenium - Wait until an element is visible

Question: I know about the solution with
elem = WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".reply-button"))).click()
But here you would wait 20 seconds and then it would either load the element in a variable or throw an exception.
Is there any blocking solution which stops the program until the element is visible?
Answer: First of all WebDriverWait will not wait 20 seconds.
It returns web element matching the passed locator, .reply-button css_selector in your case, at the moment Selenium detects that element presence.
It will wait for the defined timeout period only if no element found.
As about the element visibility, there is a similar expected condition waiting for element to be visible, like this:
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.reply-button')))

This will block the flow execution exactly until the element located by .reply-button css_selector is found to be visible or for the timeout, the first of the above.


Change the input class when an image is selected (But not yet uploaded)

Question: I have a simple image uploader (front end}
<input type="file" class="imgupload" name="file" />

But I made it with a padding and a background image inside a div with the overflow hidden
So the background image is visible but the form not, the form can still be used but it looks like an image
Is it possible to change the class when an image is selected, so that the background image can be changed?
If it is, how would could that be done?
If its not, is there another way to achieve something similar?
Thanks in advance
Comment: Change the class of the file input element, or of some container?  I'm guessing you are referring to a container, since you can't directly style a file input this way.  Also, are you only interested in changing the class when an image is selected, or when any file is selected?
Answer: Just bind it to a change event:
$("input[name=file]").change(function() {
    $(this).addClass("someClass");
});


The purpose of the domain and range of a relation

Question: This is just a general question regarding the way relations are defined. A relation is just a subset fn the cartesian product of two sets. More formally:
Definiton Suppose $A$ and $B$ are sets. Then a set $R \subseteq A \times B$ is called a relation from A to B. Its domain is given by $\text{Dom}(R) = \{ a \in A |\, \exists b \in B((a,b) \in R) \}$ and its range is given by $\text{Ran}(R) = \{ b \in B |\, \exists a \in A((a,b) \in R) \}$.
So in essence the Domain and the Range are just subsets of $A$ and $B$ respectively, or intuitively the values of $A$ and $B$ that "pop up" in the relation. Why not just define relations on these Dom($R$) and Ran($R$) instead of the supersets $A$ and $B$? We could theoretically also take arbitrary supersets of the domain and range. What was the motivation for defining them like this?
Comment: I think there might be a problem with circularity.  $\mathrm{Dom}(R)$ has a definition that depends on $R$, so you can't define $R$ in terms of $\mathrm{Dom}(R)$.
Answer: The definitions are there to make it easy to say things we want to say. In this particular case we're often interested in stating and using theorems of the general shape

Let $X$ and $Y$ be such-and-such sets, and let $R$ be any relation from $X$ to $Y$. Then blah blah blah.

and we then want the theorem to be useful whenever $R$ is a subset of $X\times Y$. If you insisted of defining relations only in terms of their narrow domains and ranges, our theorem would need to be

Let $X$ and $Y$ be such-and-such sets, and let $R$ be a relation whose domain is a subset of $X$ and whose range is a subset of $Y$. Then blah blah blah.

This would mean more words to write, and more words to digest and understand each time such a theorem is stated -- and for very little benefit.
It is simply more useful to have a short term for a relation between two already given sets, even if it may not use all of the sets we have at hand to speak about.


Programmatically add and edit controls

Question: I create programmatically an WPF TabItem and added it to my TabControl.
   var tabItem = new TabItem { Header = "foo" };

Now I want to do something like
   var txt1 = new TextBlock { Text = "foo" };
   var txt2 = new TextBlock { Text = "bar" };

   var tabItem = new TabItem { Header = txt1 + txt2 }; // cannot apply operator + to TextBlock and TextBlock
   // Other Idea:
   // var tabItem = new TabItem { Header = new TextBlock { Text = "foo" }.Text + new TextBlock { Name = "txt2", Text = "bar" }};
   // Maybe I could edit my TextBlock via it's name?
   ...
   txt2.Text = "editedBar"; // have to update the header of tabItem.

Is this anyway possible? I know in XAML it wouldn't be a problem. But the existing architecture forces me to try this way.
Comment: I cannot imagine of an "existing architecture" where you cannot create a proper UserControl or otherwise XAML-defined UI (which is the right way to do it), and then in any case add that to an existing stuff procedurally.
Comment: Where are these values of `txt1` and `txt2` coming from? If they're two properties in the same scope, an easy solution would be to create a third property that combines the two. (`public string MyProp { get { return Prop1 + Prop2; } }`) I'm having trouble imagining a scenario where you'd want to display them mashed together like that, especially if they're not closely linked.
Comment: To clarify, when `txt2.Text = "editedBar";` runs, the header should update to `fooeditedBar`?
Answer: I would do something like this:
StackPanel panel = new StackPanel();
panel.Children.Add(txt1);
panel.Children.Add(txt2);

var tabItem = new TabItem { Header = panel };

Comment: This worked for me. But I have to set the header each time. `tabItem.Header = stackPanel`. `txt2 = "foo"` isnt enough.
Comment: There's no need to set the Header each time.  You should access the TextBlocks like this ((TextBlock)(StackPanel)tabItem.Header).Children[0]).Text = "foo";  It's a little busy :(
Answer: The OP asked for a programmatical way to create WPF TabItems and add to the TabControl, through the adding of UserControls, but if you have a List or Collection of your objects, you can bind them to the TabControl.ItemsSource then use  DataTemplates to specify the ItemTemplate and ContentTemplate.
TabControl XAML:
<TabControl ItemsSource="{Binding MyItems}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock>
            <TextBlock.Text>
                <MultiBinding StringFormat="{} {0}{1}">
                    <Binding Path="HeaderA"/>
                    <Binding Path="HeaderB"/>
                </MultiBinding>
            </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
        <TextBlock>
            <TextBlock.Text>
            <Binding Path="MyContent"/>
            </TextBlock.Text>
        </TextBlock>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

MyItem class being used for TabControl
public class MyItem {
    public string HeaderA { get; set; }
    public string HeaderB { get; set; }
    public string MyContent { get; set; }
}

List of MyItem objects
public List<MyItem> MyItems {
    get {
        return new List<MyItem>() {
            new MyItem() {
                HeaderA = "Foo0",
                HeaderB = "Bar0",
                MyContent = "This is content."
            },
            new MyItem() {
                HeaderA = "Foo1",
                HeaderB = "Bar1",
                MyContent = "This is content."}
            };
        }
    }
}

This way, you can change MyContent into an object class, then use DataTemplates with the DataType attribute to specify what to show in ContentTemplate if they you have different objects for your content.

Programmatically add and edit controls