Bidirectional A* (A-Star) Not Returning the Shortest Path

Question: For some reason, my implementation of bidirectional A* isn't returning the shortest path in very specific initializations of the graph.
I'm running two A* searches, one from the source to the destination, and one from the destination to the source. From what I've read, when the closed sets for both of these searches intersect, then we've connected the shortest paths from both searches and have found the shortest path.
The problem is, in very specific situations, the closed sets for both searches are intersecting before the searches can actually discover the nodes which should be included in their respective shortest paths. This means A* doesn't get to explore enough nodes to find the shortest path.
Is this intersection condition the right way to go about things, or is there a different condition I should be using to figure out when to stop both searches?
You can run my code here: https://jasperhuangg.github.io/pathfinding-visualizer.
The cases where this problem occurs are certain (not all) situations when both walls and weights have been placed on the grid.
Here is the code if it helps, sorry if it is very messy!:
<code>async function bidirectionalAStar(graph, startNode, finishNode) {
  recolorGrid();
  searching = true;

  const infinity = Number.MAX_VALUE;
  var openSource = [];
  var openDest = [];
  var closedSource = [];
  var closedDest = [];

  var numSteps = -3; // -2 for both start and finish nodes + -1 for overlapping connecting node

  $("#steps-taken").html("Cells Examined: " + numSteps);

  const startX = startNode.x;
  const startY = startNode.y;

  const finishX = finishNode.x;
  const finishY = finishNode.y;

  var bidirectionalAStarGraph = shallowCopyGraph(graph, []);

  // initialize all nodes to dist infinity from the startNode
  for (let i = 0; i < bidirectionalAStarGraph.length; i++) {
    for (let j = 0; j < bidirectionalAStarGraph[i].length; j++) {
      bidirectionalAStarGraph[i][j].fSrc = infinity;
      bidirectionalAStarGraph[i][j].gSrc = infinity;
      bidirectionalAStarGraph[i][j].hSrc = infinity;
      bidirectionalAStarGraph[i][j].fDest = infinity;
      bidirectionalAStarGraph[i][j].gDest = infinity;
      bidirectionalAStarGraph[i][j].hDest = infinity;
      bidirectionalAStarGraph[i][j].setSource = "neither";
      bidirectionalAStarGraph[i][j].setDest = "neither";
    }
  }

  // initialize start/finish node distance from start/finish to 0
  bidirectionalAStarGraph[startX][startY].fSrc = 0;
  bidirectionalAStarGraph[startX][startY].gSrc = 0;
  bidirectionalAStarGraph[startX][startY].hSrc = 0;
  bidirectionalAStarGraph[startX][startY].setSource = "open";
  openSource.push(bidirectionalAStarGraph[startX][startY]);

  bidirectionalAStarGraph[finishX][finishY].fDest = 0;
  bidirectionalAStarGraph[finishX][finishY].gDest = 0;
  bidirectionalAStarGraph[finishX][finishY].hDest = 0;
  bidirectionalAStarGraph[finishX][finishY].setDest = "open";
  openDest.push(bidirectionalAStarGraph[finishX][finishY]);

  var lastNodeSource;
  var lastNodeDest;

  while (openSource.length > 0 && openDest.length > 0) {
    openSource.sort((a, b) => {
      if (a.fSrc !== b.fSrc) return a.fSrc - b.fSrc;
      else return a.hSrc - b.hSrc;
    });
    openDest.sort((a, b) => {
      if (a.fDest !== b.fDest) return a.fDest - b.fDest;
      else return a.hDest - b.hDest;
    });

    var currNodeSource = openSource.shift();
    var currNodeDest = openDest.shift();

    $(".currentNodeGray").removeClass("currentNodeGray");
    $(".currentNodeSunset").removeClass("currentNodeSunset");
    $(".currentNodeOcean").removeClass("currentNodeOcean");
    $(".currentNodeChaos").removeClass("currentNodeChaos");
    $(".currentNodeGreen").removeClass("currentNodeGreen");
    $(".currentNodeCottonCandy").removeClass("currentNodeCottonCandy");

    if (checkIntersection(closedSource, closedDest)) {
      break; // the paths have reached each other
    }
    numSteps += 2;

    $("#steps-taken").html("Cells Examined: " + numSteps);

    currNodeSource.setSource = "closed";
    currNodeDest.setDest = "closed";
    closedSource.push(currNodeSource);
    closedDest.push(currNodeDest);

    colorNode(currNodeSource, "currentNode");
    colorNode(currNodeDest, "currentNode");
    if (lastNodeSource !== undefined && currentSpeed !== "instantaneous")
      colorNode(lastNodeSource, "visited");
    if (lastNodeDest !== undefined && currentSpeed !== "instantaneous")
      colorNode(lastNodeDest, "visited");

    if (currentSpeed === "fast") await sleep(20);
    else if (currentSpeed === "medium") await sleep(180);
    else if (currentSpeed === "slow") await sleep(500);

    var validNeighborsSource = [];
    var validNeighborsDest = [];
    var left = currNodeSource.x - 1;
    var right = currNodeSource.x + 1;
    var up = currNodeSource.y - 1;
    var down = currNodeSource.y + 1;

    // consider all of the current node's (from source) valid neighbors
    if (left >= 0 && !bidirectionalAStarGraph[left][currNodeSource.y].blocked) {
      validNeighborsSource.push(
        bidirectionalAStarGraph[left][currNodeSource.y]
      );
    }
    if (
      right < grid_width &&
      !bidirectionalAStarGraph[right][currNodeSource.y].blocked
    ) {
      validNeighborsSource.push(
        bidirectionalAStarGraph[right][currNodeSource.y]
      );
    }
    if (up >= 0 && !bidirectionalAStarGraph[currNodeSource.x][up].blocked) {
      validNeighborsSource.push(bidirectionalAStarGraph[currNodeSource.x][up]);
    }
    if (
      down < grid_height &&
      !bidirectionalAStarGraph[currNodeSource.x][down].blocked
    ) {
      validNeighborsSource.push(
        bidirectionalAStarGraph[currNodeSource.x][down]
      );
    }

    left = currNodeDest.x - 1;
    right = currNodeDest.x + 1;
    up = currNodeDest.y - 1;
    down = currNodeDest.y + 1;

    // consider all of the current node's (from dest) valid neighbors
    if (left >= 0 && !bidirectionalAStarGraph[left][currNodeDest.y].blocked) {
      validNeighborsDest.push(bidirectionalAStarGraph[left][currNodeDest.y]);
    }
    if (
      right < grid_width &&
      !bidirectionalAStarGraph[right][currNodeDest.y].blocked
    ) {
      validNeighborsDest.push(bidirectionalAStarGraph[right][currNodeDest.y]);
    }
    if (up >= 0 && !bidirectionalAStarGraph[currNodeDest.x][up].blocked) {
      validNeighborsDest.push(bidirectionalAStarGraph[currNodeDest.x][up]);
    }
    if (
      down < grid_height &&
      !bidirectionalAStarGraph[currNodeDest.x][down].blocked
    ) {
      validNeighborsDest.push(bidirectionalAStarGraph[currNodeDest.x][down]);
    }

    // UPDATE NEIGHBORS FROM SOURCE
    for (let i = 0; i < validNeighborsSource.length; i++) {
      let neighbor = validNeighborsSource[i];

      if (neighbor.setSource === "closed") continue;

      let cost = 0;
      if (currNodeSource.weighted === true || neighbor.weighted === true)
        cost = currNodeSource.gSrc + 10;
      else cost = currNodeSource.gSrc + 1;

      if (neighbor.setSource === "open" && cost < neighbor.gSrc) {
        neighbor.setSource = "neither";
        neighbor.gSrc = cost;
        neighbor.fSrc = neighbor.gSrc + neighbor.hSrc;
        openSource.remove(neighbor);
      }
      if (neighbor.setSource === "neither") {
        openSource.push(neighbor);
        neighbor.setSource = "open";
        neighbor.gSrc = cost;
        neighbor.hSrc = calculateHeuristic(neighbor, finishNode);
        neighbor.fSrc = neighbor.gSrc + neighbor.hSrc;
        neighbor.predecessorSource = currNodeSource;
      }
    }
    lastNodeSource = currNodeSource;

    // UPDATE NEIGHBORS FROM DEST
    for (let i = 0; i < validNeighborsDest.length; i++) {
      let neighbor = validNeighborsDest[i];

      if (neighbor.setDest === "closed") continue;

      let cost = 0;
      if (currNodeDest.weighted === true || neighbor.weighted === true)
        cost = currNodeDest.gDest + 10;
      else cost = currNodeDest.gDest + 1;

      if (neighbor.setDest === "open" && cost < neighbor.gDest) {
        neighbor.setDest = "neither";
        neighbor.gDest = cost;
        neighbor.fDest = neighbor.gDest + neighbor.hDest;
        openDest.remove(neighbor);
      }
      if (neighbor.setDest === "neither") {
        openDest.push(neighbor);
        neighbor.setDest = "open";
        neighbor.gDest = cost;
        neighbor.hDest = calculateHeuristic(neighbor, startNode);
        neighbor.fDest = neighbor.gDest + neighbor.hDest;
        neighbor.predecessorDest = currNodeDest;
      }
    }
    lastNodeDest = currNodeDest;
  }
</code>
Answer: Without any code I can't identify any specific bugs in your algorithm but the thing about Bidirectional A* is that it is only as good as your A*.
A* is flexible in that it is capable of acting just like a dumb breadth first search and just like a dumb depth first search - usually it's somewhere in the middle, and that "middle" is defined by the quality of your heuristic.
Adding a second A* on the other side is a good way to "speed up" an A* heuristic that leans towards breadth, but, it won't "fix" a heuristic that leans towards depth.
If you want a guarantee that your Bidirectional A* search will always find the shortest possible path, then your heuristic needs to lean towards breadth.  (Usually this is done by estimating the heuristic - the imagined cost of a node to explore as the Manhattan distance to the target plus the distance traveled to that node.  Then sort the nodes and toss nodes more than 1.5x the lowest node -- 1.5 being a variable you can play with, too high and you'll do a traditional breadth first and too low and you might toss the actual lowest path, if it's a complicated one.)
Sorry for the vagueness, some code snippets might help give more direction!
Comment: I'm using the cost function that you specify: f = heuristic (Manhattan distance to finish) + g (distance to node). What I'm not doing is tossing out nodes in the closed sets; is this absolutely necessary or is it more just to save space? Also, can you confirm if finding the intersection of the closed sets is the right way to end the search?


The explanation for the need to compute (rather then optimize) the posterior of latent variables

Question: The most common usage of the variational inference looks like to be in computing the marginal distribution $P(X)$ in the denominator of the Bayes formula when computing the posterior probability of the hidden variables, $P(Z|X)$. This is likely a dumb question but I don't understand why we need to compute $P(Z|X)$. Why don't we just optimize $P(Z|X)$ instead (find $Z$ that maximizes $P(Z|X)$), in which case we don't need to exactly compute $P(X)$ since it does not depend on the value of $Z$. In that alternative way, we can just optimize the numerator $P(X|Z)P(Z)$ as in the regular MAP (maximum aposteriori) estimation of the parameters ($\theta$) when we don't have any hidden variables $Z$. What is the difference in those two problems (estimating parameters vs. hidden variables) such that one can go with optimizing through MAP while the other needs sophisticated tools for computing (or approximating) $P(Z|X)$?

Edit: After a little more search, I learned that the MAP is not really full Bayesian, since it does not learn the actual posterior distribution, but it instead gets a point estimate of the parameters through maximizing posterior probability. Then I think what variational inference does is real Bayesian. But still, I am not sure whether I understand the need for getting the distribution itself. Is it to get a better sense of the parameter space?
Comment: The process of computing the marginal distribution $P(X)$ results in a generative network. Variational Autoencoders are one of the ways of computing them using variational inference. Here, we do not have any information about the $Z$ thus we cannot do MLE for $P(Z|X)$, we assume that it's coming from a gaussian prior $\mathcal{N}(\mu,\sigma \textbf{I})$. We try to match the original posterior $P(Z|X)$ to that of the computed one $Q(Z|X)$ by reducing the KL distance between them. I am not sure how correct my thinking is though.
Answer: In many cases getting the distribution is more useful than a point estimation. Say I am an interviewer and I ask each candidate to do a list of questions, then $X$ (observed) could be the number of question the candidate answered correctly, and $Z$ (latent) is whether the candidate is qualified or not.
Candidate A has correctly answered 4 out of 5 questions, and B answered all 5 questions. If I just do a point estimation (MLE/MAP), the most probable value of $Z$ for A and B might be the same $$argmax_ZP(Z|X_A)=argmax_ZP(Z|X_B)=qualified$$
If I can know the full posterior distribution, then I get $$P(Z=qualified|X_A)<P(Z=qualified|X_B)$$

A more common situation would be there's another variable $Y$ that depends on $Z$, if we know the full distribution $p(Z|X)$ we get $$p(Y|X)=\int p(Y|Z)p(Z|X)d_Z$$
which we can't know given only a point estimation of $Z$.
For instance in the setting of recursive filtering algorithms, $Z$ is the state at time $t$, $X$ is the measurement at time $t$, and $Y$ is the state at time $t+1$.

Another example that might be interesting to illustrate the connection is the EM algorithm for Gaussian mixture models, in wich case $X$ is the observed data, $Z$ is the discrete latent variable that denotes which Gaussian component a data point belongs to.
EM itself is an optimization (point estimation) algorithm for the model parameters $\theta$. In the E step we assign each data point a probability of belonging to each component, which is to compute $p(Z|X)$. in the M step we optimize $\theta$ based on $p(Z|X)$.
If in the E step we do a point estimation (hard assignment) instead, then we are going from EM for GMM to K-means clustering (assuming the same identity covariance matrix).

I'm not much a statistics people, please correct me if I missed any important point. :]
Comment: @dontloo Thanks, the answer is very helpful. Just to note, EM example could be a little bit confusing, because EM retrieves a point estimate of the expected likelihood of data in the maximization step, while when computing the posterior P(Z|X) in the expectation step, it computes a probability rather than a point estimate, which is I think what you aimed to highlight, related to what I asked.
Comment: The main point in computing the marginal $p(y|x)$ is when comparing models.
Comment: @Xi'an Could you give an example? How would you use distributions in comparing two models? How would you decide which distribution is associated with the *better* model? What is the metric? Would you compare the sufficient statistics of the distributions?
Comment: @user5054: the notion of relevance is the Bayes factor.
Comment: The Wikipedia article says "The Bayes factor is a ratio of the likelihood probability of two competing hypotheses, usually a null and an alternative." Then Bayes factor is basically the terminology for the comparison method used in the interview example in @dontloo 's answer.
Comment: @user5054 yes you're right, I made some edits.
Comment: @Xi'an hi thank you much for the comments. I'm not quite familiar with model comparison though, I guess in this case $z$ is the parameter, but i'm not sure whether $p(z|x)$ should be interpreted as the prior given the model or the posterior given the training data?


Use z confidence interval to estimate population proportion

Question: Which of the following must be true of a sample in order for it to be appropriate to use a $z$ confidence interval to estimate the population proportion?
(A) The sample is a random sample from the population of interest.
(B) $n\hat{p}\ge10$ and $n(1-\hat{p})\ge10$
(C) The population distribution is normal.
(D) All of (A), (B), and (C) are required for appropriate use of the $z$ confidence interval to estimate the population proportion.
(E) Only (A) and (B) are required for appropriate use of the $z$ confidence interval to estimate the population proportion.
I chose (A) with the reasoning that either (B) or (C) must be true but that neither had to be true. If the population distribution is normal, the sampling distribution is normal. Likewise, if (B) is true, the sampling distribution is normal. So either (B) or (C) would independently ensure the sampling distribution to be normal.
My teacher marked it incorrect and gave the answer to be (E). Who is right?
Comment: In response to your edit, see my answer and the comment below it. The population isn't normal.
Answer: You both agree that A has to hold: you need independence to avoid bias, reduce your true standard error -- and in this case to be able to approximate using the normal distribution (see B, below).
Now to C. The population distribution isn't normal: your model is that there is a certain proportion of the population that has a characteristic. So you take an individual from the population and they have a characteristic $C=1$ or they don't $C=0$, with proportion $p$. This gives $P(C=1)=p$ which is a Bernoulli distribtion. If you take a sample from such a population you get a Binomial distribution which leads us to...
B. As a rule of thumb it is reasonable to approximate a binomial distribution $B(n,p)$ with a normal distribution $N(np, npq)$ under the conditions given, which amount to saying that you if you don't have an extremely large number or an extremely small number of individuals in the population with or without the characteristic, then the number of successes drawn from the binomial distribution can be approximated with the continuous bell curve of the normal distribution.
Comment: But the population binomial is normal when p=.5 No?
Comment: No, it's still binomial. There are several differences: notably the binomial distribution is discrete, whereas the normal distribution is continuous. And the binomial distribution is bounded at $0$ and $n$, the number of samples you take. But for $p=0.5$, you don't have to make $n$ very large to be able to approximate the binomial distribution with the normal distribution.
Comment: Also, see my edit, the _population_ definitely isn't binomial. You take an individual from the population and they either have the characteristic or they don't. E.g. you choose a student and see if they're male or female -- draw a histogram for this and it clearly isn't normal! Compare with a typical setting for the normal distribution where you for example take a student and measure their height. Do this enough and your histogram will be bell-shaped.
Comment: Thank you. This cleared things up


Is a proper morphism between projective schemes projective morphism?

Question: That is if $f :P^n_ {X} \rightarrow P^m_{Y}$ is a proper morphism, then it is a projective morphism.
Projective morphism means that it factors through projective scheme of last term and the first component is a closed immersion.
Answer: Let $f:X\to Y$ be a (not necessarily proper) morphism of projective schemes over a field $k$ (the same works over a scheme $S$). Then $f$ is projective.
Proof: $X\subseteq \mathbb{P}^n_k$ (closed immersion) for some $n$. Then consider the closed immersion $X\subseteq X\times_k Y$ in the graph, which is a closed subscheme of $\mathbb{P}^n_k\times_kY=\mathbb{P}^n_Y$ (here I am using that projective morphisms are proper, which is a standard application of the valuative criterion for properness). This gives the required factorization $X\to \mathbb{P}^n_Y\to Y$.
Comment: you are right.Every morphism $P^n_{k} \rightarrow Y$ is projective by using the graph.So using the projective morphism is proper,we can show every morphism $P^n_{X} \rightarrow Y $is projective morphism where $Y$ is arbitrary scheme.Thank you,Sonner!
Comment: Sorry ,Sonner you are right.  Every morphism $P^n_{S}\rightarrow Y$where $Y $is a $S$-scheme is a projective morphism.Y can't be arbitrary!
Comment: You are welcome! :)

Is a proper morphism between projective schemes projective morphism？


Properties of analytic function in a disc

Question: Show that a function analytic in the disc $\left | z \right |<1+\epsilon$ for some $\epsilon>0$ satisfies $\displaystyle f(z)=i Im(f(0))+\frac{1}{2\pi}\int_0^{2\pi}\frac{e^{it}+z}{e^{it}-z}Re(f(e^{it}))dt$
Suppose that the function above also satisfies $Re(f(e^{it}))\geq0, \forall t\in[0,2\pi]$, prove that:
$\displaystyle \frac{1-\left | z \right |}{1+\left | z \right |}Re(f(0))\leq Re(f(0))\leq\frac{1+\left | z \right |}{1-\left | z \right |}Re(f(0)),\forall z: \left | z \right |<1$
I don't even know where to begin ._.
Answer: The first line is the Schwarz integral formula, and it follows directly from the Poisson integral formula: The real part is the Poisson integral of the real part of $f$ on the circle, and the integral is analytic as a function of $z$, so the difference of $f$ and the integral is an imaginary constant. Evaluating both sides for $z=0$ you find that it has to be the imaginary part of $f(0)$.
In your line of inequalities the term in the middle should have argument $z$, not $0$. After that, the inequalities follow easily from $$ \frac{1-|z|}{1+|z|} \le \left|\frac{e^{it}+z}{e^{it}-z}\right| \le \frac{1+|z|}{1-|z|}$$ and $$u(0) = \frac1{2\pi} \int_0^{2\pi} u(e^{it}) \, dt,$$
where $u$ is the real part of $f$.


Transforming models in order to use linear least squares estimations

Question: As a pre-exam question, I found a question asking to consider the following three models
$$
y = \beta_{0}(x_{1})^{\beta_{1}}(x_{2})^{\beta_{2}}\epsilon
$$
$$
y = \frac{1}{\beta_{0} + \beta_{1}x + \epsilon}
$$
$$
y = \frac{1}{1+ e^{\beta_{0} + \beta_{1}x}\epsilon}
$$
and discuss how each of them might be transformed to use a linear least squares estimation.
To me the second and third models seem really simple, so simple that I may just be completely misunderstanding the purpose of the question. For the second one could simply take the inverse, and for the third one could take the inverse and then take the log. Is it as simple as stating that?
The first model, I am unsure what transformation to do.
Comment: please add the `self-study` tag and read its [tag wiki](http://stats.stackexchange.com/tags/self-study/info)
Answer: (Some edits in response to comment)
For the first, note that you want to get from
$\beta_{0}\,\cdot x_{1}^{\beta_{1}}\,\cdot x_{2}^{\beta_{2}}\,\cdot\epsilon$
-- a product of terms -- to
$\beta_{0}+\beta_{1} x^*_{1}+ \beta_{2} x^*_{2}+ \epsilon$
-- a sum of terms (where $x^*$ may be some transformed variable)
Does that wish not suggest something?
Edit: As OP has now realized, the first is a matter of taking logs.

The third one isn't quite right.  There's an extra term you didn't deal with.
You still need the reciprocal, but otherwise your suggested change solves it.
Comment: Right right for the first one it's quite simply taking the log, my mistake. For the third one, is it sufficient to take the inverse, subtract $1$ from $y$ and _then_ take the log? Also thanks for letting me know about the tag correction, edited the question.
Comment: Not quite; now you have left out a step from your original solution.


AngularJS + RequireJS + NgNestable

Question: Fala galera, tudo bem? Então estou trabalhando com RequireJS junto com AngularJS, hoje precisei trabalhar com uma lib de NgNestable
kamilkp/ng-nestable
Porém quando tento carregar a diretiva no meu app da seguinte forma:
define(['angularamd', 'angular-uirouter', 'angular-nestable'], function (angularAMD) {

    var app = angular.module('appFerramentaria', [
        'ui.router',
        'ng-nestable'
    ]);

    {...}
});

O seguinte erro é retornado:

Esse é o meu arquivo de configuração do RequireJS (main.js), acredito que o erro pode estar na ordem em que estou chamando os arquivos
require.config({
    baseUrl: '/portais/colaborador_novo/assets_novo/js',
    urlArgs: "v=" +  (new Date()).getTime(),// desenv
    paths: {
        'jquery': 'jquery.min',
        'bootstrap': 'bootstrap-rjs.min',
        'angular': 'angular1-7.min',
        'angular-uirouter': 'angular-ui-router.min',
        'angularamd': 'angularAMD.min',
        'jquery.nestable': 'jquery.nestable',
        'angular-nestable': 'angular-nestable',
        'app': '../../app/views/ferramentaria/app',
    },
    shim: {
        'angular': ['jquery', 'bootstrap'],
        'angularamd': ['angular'],
        'angular-uirouter': ['angular', 'angularamd'],
        'jquery.nestable': ['jquery'],
        'angular-nestable': ['jquery.nestable', 'angular']
    },
    deps: [
        'app'
    ]
});

Desde já agradeço, valeu :)
Answer: Olá depois de muito revirar achei uma solução:
shim: {
    'angular': {
        deps: ['jquery', 'bootstrap'],
        exports: 'angular'
    },
{...}

AngularJS + RequireJS + NgNestable


Calling external js file

Question: I am trying to call an external js file from another
js file. Here is my code:
file1.js
function func1(id){
 var NewScript= document.createElement('script')
 NewScript.src="file2.js"
 document.body.appendChild(NewScript);
 func2(id);

}

file2.js
function func2(id)
{
    alert("im here " +id);

}

But when I ran it it gives out the "func2 is not defined. "
Am i doing it right?
Can somebody help me?
Thanks
Comment: Check this: http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file
Comment: Is this a hypothetical example you're trying and it's not working or that's your real code? Because if your file is quite large you need to wait for the browser to load the new JS file.
Comment: this is not the real code, i changed the filenames and file2.js, yes is a little large..
Comment: As Mark suggested, you have to wait for the script to be loaded and parsed. To test what Marc B is saying, Try calling func2('test') in Body's onload and that will work
Comment: thanks @Sudhir!!! and thanks all for replying! you guys are great! :D its okay already. i followed the answer in the link that sudhir provided! :))
Answer: You have to wait for the script to actually be loaded/parsed. .appendChild will return immediately and your code continues on, likely LONG before the browser's had a chance to fetch the new script.
Moving from .appendChild() to func2() in the code is likely to be milli or microseconds, while fetching the script could be entire seconds, depending on how lossy/laggy the network is acting at that time.
Comment: thanks for this! you're right i should wait before its loaded.. I followed the answer of the link that Sudhir provided! thanks guys!
Answer: import1.js:
var a = function () {
    console.log( 'function a' );

    this._require(function(){
       b( 123456 );
    });
};

a.prototype._require = function (callback) {
    var xhr = new XMLHttpRequest();

    xhr.onload = function (e) {
        var script = document.createElement('script');
        script.innerHTML = e.target.responseText;
        document.getElementsByTagName('head')[0].appendChild(script);
        callback();
    };

    xhr.open('GET', 'import2.js', true);
    xhr.send();
};

new a();

import2.js:
var b = function ( id ) {
    console.log( id );
};

result:

Calling external js file


Lower bound on the norm of product of non square matrices

Question: The following inequality is known: $\parallel AB\parallel\geq\parallel A\parallel \sigma_{n}(B)$. However, it is only valid where both $A$ and $B$ are square.
Is there an analogue for rectangular matrices? Specifically, given that $A$ is of size $n \times nk$, $B$ is of size $nk \times nk$ and $C$ is of size $nk \times n$, what is the lower bound, in terms of singular values, of $\parallel ABC\parallel$?
Thank you.
Comment: Sorry, I should have used the opposite sign. Indeed, I meant the smallest singular value. In case both $A$ and $B$ have the same dimension ($n$), it is clear that the n-th singular value should be taken. I ask what should be the corresponding ineqaulity in case the matrices are rectangular.
Answer: I don't think there is any close analogue, because the singular values of $A,B,C$ can be all nonzero but $ABC=0$. For example, we have
$$\begin{pmatrix}1&0\end{pmatrix}\begin{pmatrix}0&1\\1&0\end{pmatrix}\begin{pmatrix}1\\0\end{pmatrix}=0.$$


Can the Eb alto clarinet and the Eb soprano clarinet be substituted?

Question: I am putting together a band to play the piece Variations on a Korean Folk Song by John Barnes Chance. I Was wondering if I could substitute both clarinets parts with a Alto sax seeing as they are both pitched in the same key.
https://www.jwpepper.com/Variations-on-a-Korean-Folk-Song/153544.item#.YbI2u9DMKUk
This is the piece there is a preview on the website
Comment: It sounds like a "too many saxophones, not enough clarinets" problem
Comment: How desperate are you?  :-)  .  You can substitute anything while losing intended tone/timbre,  etc, or you can make the Principal Clarinet transpose the Eb soprano part, and so on.
Comment: Probably the best idea, timbre-wise, @Carl Witthoft  I don't remember how high it goes but it shouldn't be too much for a skilled Bb player
Comment: @CarlWitthoft - from the question, I feel that OP doesn't want to use clarinets, so where would the Principal Clarinettist be?
Answer: Two instruments being pitched "in Eb" does not mean they sound in the same octave, so one Eb instrument cannot necessarily be substituted for another.

The Eb alto clarinet has a sounding range from G♭2 to B♭5. (SOURCE)
The Eb soprano clarinet sounding range is usually given as E3 to G6. (SOURCE)
The Eb alto saxophone has a sounding range from D♭3 to A♭5. (SOURCE)

This means that the lowest tritone on the Eb alto clarinet (Gb2 – C3) and the highest octave (roughly) on the Eb soprano clarinet (A5 – G6) will not be available on the Eb alto sax.
In practice, whether the substitutions will work depends on the specifics of the score and whether, for example, changing the octave of a part will sound okay.
At the most straightforward level of arranging, if those lowest and highest pitches are needed then

If no, then alto sax will be fine;
If used infrequently, you might be able to avoid them or replace them with other pitches;
If used frequently, you would have to move the part up or down an octave.
Answer: No, you should not make this substitution.  Aaron's answer illustrates how these three most common Eb band instruments have different ranges.  So some notes may already be impossible.
My answer is more from the perspective of the composer's intent.  Chance wrote for a specific timbre, and just as you wouldn't want to just go changing some of his notes arbitrarily, you shouldn't mess around with changing a bunch of timbres either.  The alto is a much stronger timbre and it doesn't blend as well as the clarinets.
Assuming you are conducting this piece, you'll have to weigh the importance of Chance's masterful orchestration against the need to balance your ensemble.  If it means that a young person might get to play in this wonderful piece ONLY if you make this substitution, does that outweigh the desires of the composer?  Maybe it does, maybe it doesn't.


Creating an XSLT Template based on XSD File (all nodes) and a dynamic client XML (with only 50 % nodes and values)

Question: In application client generates an XML and then convert it to PDF. (using FONET)
PDF has a fixed format and its displays all the possible nodes (whether data or not) in tabular format.
Each parent node in XML is a section in PDF which has a complex UI structure. In total PDF has 34 sections.
XML is dynamic and will always have 18-20 sections only. And with in each section (parent node) child nodes with no values will be missing.
Only way to know the 100 % XML structure is from an XSD file.
Question:
IS there any way to use both XML and XSD in XSLT to generate a PDF or we need something intermediate?
May be a fixed XML with all the possible nodes and then add client generated XML values to it?
Comment: The XSD schema language is rather complex, processing XSD with all its complexity is a difficult task. I think Saxonica has an schema export tool http://saxonica.com/documentation/index.html#!schema-processing/scm to alleviate that task. But I don't think your few sentences really describe which problems you have run into.
Comment: There are tools to generate an XML instance from XSD. The result can be used for writing an XSLT that handles all nodes that can possibly appear in the input. This is much easier then writing against an XSD. Note that this is assuming each node needs to be always handled the same way, regardless of the presence of other nodes.
Comment: How are different elements going to be processed? The same, or differently? What information in the schema are you going to use in order to decide how to process a particular element?
Comment: Thanks, I generated a Sample XML and will use it to create a template targetting all the nodes and sub Nodes. The only pending is, lot of XML Node use "Codes: instead of Actual text which is present in the documentation for that particular element eg Res  and

       RES - Resident
       NRI - Non Resident
       NOR - Resident but not Ordinarily resident

Answer: Regarding PDF generation from XSL, you can use xsl:fo to generate PDF.
For dynamic XML, i would say just write a generic template as an example if you have multiple sections on different level then just write a single template .
Also if you need to capture all the elements for which you have not written any template match then just write an identity template to copy all these elements in output:
<code><xsl:template match="node()|@*">
        <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>
</xsl:template>
</code>
I hope this will help you, if you need more details then please share input and output sample.
Comment: Thanks, We are using FONET for PDF generation.


Duvida quanto a criação de maps de eventos - TypeScript

Question: Sou estagiário e assumi um projeto em uma linguagem que não tenho muito conhecimento, estou tendo problemas a criar um retorno de eventos, tentei procurar erros parecidos na internet, mas sem sucesso. Segue o erro:
[![Imagem que mostra onde o erro ocorre][1]][1]
E o código:
return api.post<Response, apiEvent[]>('execute', data).then(() => {
  const events: IEvent[] = response.map((item: apiEvent): IEvent[] => {
    // ...
  });
});

Outro erro que da em events é:

Type 'IEvent[][]' is not assignable to type 'IEvent[]'.

Se algum puder tentar me explicar o motivo do erro agradeceria muito.
Answer: O callback do map não retorna um array de IEvent, mas sim um IEvent.
Troque a anotação de retorno do callback de IEvent[] para IEvent. O array de tipo IEvent[] é retornado por todo o map, de modo que cada callback só retorna um evento.

Saiba mais sobre o Array.prototype.map.

Mas ao corrigir o erro acima, um outro erro surgirá:

Function lacks ending return statement and return type does not include 'undefined'.

Isso acontece porque, quando você define uma anotação explícita de retorno de função, o TypeScript verificará se todos os code paths retornarão o tipo que você especificou explicitamente.
Pense neste exemplo:
function sum(a: number, b: number | undefined): number {
  if (b) {
    return a + b;
  }

  // O TypeScript irá reclamar, uma vez que, se `b` não estiver
  // definido, este caminho não retornará nada (no caso, um número
  // não será retornado). Desse modo, como anotamos explicitamente
  // o retorno da função como `number`, o erro ocorre.
}

Para corrigir o erro, então, você deve garantir que todos os caminhos retornem o tipo especificado por você.
Comment: eu fiz como você disse, porém o erro que aprensentei na imagem persistiu. O código está assim:

`return api.post('execute', data).then(() => { const events: IEvent[] = response.map((item: apiEvent): IEvent => { // ... }); });`
Comment: Estranho... Poderia tentar então reproduzir o **mesmo** problema no [TypeScript playground](https://www.typescriptlang.org/play) e colar o link na sua pergunta, por favor? cc: @Jonatan
Comment: Feito, @LuizFelipe


Auto incremento em R

Question: Como faço para gerar um campo ID auto incremental (1,2,3...) em um data.frame em R que em uma nova coluna?
meuDataFrase<- as_tibble(unique(tabelImportada$ColunaX))

Preciso criar uma nova coluna nesse data.frame que tenha os números da linha porque vou gravar essa informação em uma tabela dimensional no postgres.
Answer: Uma forma de fazer isso é usar a função rownames_to_column() do pacote tibble.
O exemplo abaixo inclui ids para as linhas da tabela iris. Nesse caso ele cria uma coluna chamada "rowname".
library(tidyverse)
# só para imprimir melhor
tbl_iris <- as_tibble(iris)

tbl_iris %>%
     rownames_to_column()
# A tibble: 150 x 6
   rowname Sepal.Length Sepal.Width Petal.Length Petal.Width Species
   <chr>          <dbl>       <dbl>        <dbl>       <dbl> <fct>
 1 1                5.1         3.5          1.4         0.2 setosa
 2 2                4.9         3            1.4         0.2 setosa
 3 3                4.7         3.2          1.3         0.2 setosa
 4 4                4.6         3.1          1.5         0.2 setosa
 5 5                5           3.6          1.4         0.2 setosa
 6 6                5.4         3.9          1.7         0.4 setosa
 7 7                4.6         3.4          1.4         0.3 setosa
 8 8                5           3.4          1.5         0.2 setosa
 9 9                4.4         2.9          1.4         0.2 setosa
10 10               4.9         3.1          1.5         0.1 setosa
# … with 140 more rows

Outra alterativa é criar uma coluna com o nome que você quiser usando mutate() do dplyr combinado com seq_len().
tbl_iris %>%
  mutate(id = seq_len(nrow(.)))
# A tibble: 150 x 6
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species    id
          <dbl>       <dbl>        <dbl>       <dbl> <fct>   <int>
 1          5.1         3.5          1.4         0.2 setosa      1
 2          4.9         3            1.4         0.2 setosa      2
 3          4.7         3.2          1.3         0.2 setosa      3
 4          4.6         3.1          1.5         0.2 setosa      4
 5          5           3.6          1.4         0.2 setosa      5
 6          5.4         3.9          1.7         0.4 setosa      6
 7          4.6         3.4          1.4         0.3 setosa      7
 8          5           3.4          1.5         0.2 setosa      8
 9          4.4         2.9          1.4         0.2 setosa      9
10          4.9         3.1          1.5         0.1 setosa     10
# … with 140 more rows

Comment: É melhor vc usar a função row_number()
Answer: Lembre-se sempre de trazer um exemplo reproduzível. Criei um DF simples como exemplo, mas o conceito é o mesmo para outros DF's.
Código:
x <- data.frame(z = c(51:101), y = c(50:100))

for(i in 1:nrow(x)) {

    x[i,3] <- i

}

Caso suas rownames não forem números, utilize o seguinte comando antes:
rownames(x) <- NULL

Obs.: Coloquei a coluna 3 no for(), mas você deve colocar o número da coluna que você deseja que apareça o número da linha.

Auto incremento em R


Updating SQL Server using ADODB recordset UpdateBatch method

Question: I am trying to populate a single column temporary table in SQL Server using ADO in Excel VBA.  My code is very slow, namely 145 seconds for 1,000 rows.
Is there a faster way involving maintainable elegant code that doesn't involve manipulating raw SQL strings?  I like .AddNew and .UpdateBatch...
Failing that, what is the fastest way?
Private Sub StackOverflowPopTempTable(cn As ADODB.Connection)

Dim rs As ADODB.Recordset
Dim row As Long
Dim strSql As String
Dim row_count As Long
Dim t As Single
t = Timer

Set rs = New ADODB.Recordset

'Create a temporary table
strSql = "IF OBJECT_ID('tempdb..##tbl_dummy_data', 'U') IS NOT NULL " & _
            "DROP TABLE ##tbl_dummy_data; " & _
            "CREATE TABLE ##tbl_dummy_data ( " & _
            "dummy_data VARCHAR(20) PRIMARY KEY " & _
            ");"
cn.Execute strSql

'Add masterkeys to this exclusion table
strSql = "SELECT * FROM ##tbl_dummy_data"
rs.Open strSql, cn, adOpenStatic, adLockBatchOptimistic

row_count = 1000
For row = 1 To row_count
    rs.AddNew
    rs("dummy_data") = "a" & row
Next row
Debug.Print Timer - t
rs.UpdateBatch
Set rs = Nothing

Debug.Print Timer - t

End Sub

Up to the UpdateBatch statement only takes half a second.  The remaining 2 minutes or so is the UpdateBatch statement.
Many thanks - I will update with anything I find in the meantime...
Update 1
This takes the same amount of time
cn.BeginTrans
row_count = 1000
For row = 1 To row_count
    strSql = "INSERT INTO ##tbl_dummy_data VALUES ('a" & row & "')"
    cn.Execute strSql
Next row
Debug.Print Timer - t
cn.CommitTrans
Debug.Print Timer - t`

Update 2
IF OBJECT_ID('tempdb..##tbl_dummy_data', 'U') IS NOT NULL
    DROP TABLE ##tbl_dummy_data;
CREATE TABLE ##tbl_dummy_data (
    dummy_data VARCHAR(20) PRIMARY KEY
);

Insert Into ##tbl_dummy_data
    Select Cast(rand(checksum(newid()))*1000000  as int);
go 1000

This takes 2 minutes on the server side
Update 3
This takes a fraction of a second, so I suspect VBA is doing individual transactions?  Even when I use .BeginTrans and .CommitTrans?
DECLARE @counter INT

SET @counter = 0
BEGIN TRANSACTION
WHILE @counter < 1000
BEGIN
   Insert Into ##tbl_dummy_data
    Select Cast(rand(checksum(newid()))*1000000  as int);
   SET @counter = @counter + 1
END
COMMIT TRANSACTION

Update 4
Checked that the provider supports transactions.  It apparently does!
?cn.Properties("Transaction DDL").Value
 8

Comment: The updatebatch takes  ~0.125 secs on my desktop (SQLserver express local server), even 50,000 records only  takes 6 seconds. Time it without a primary key. Note you only need 1 line `rs.AddNew "dummy_data", "a" & row`
Comment: adOpenKeyset is much slower (434 seconds)
Comment: Removing the primary key takes longer (150 secs).  I'm going to investigate how long it takes on the server side and if it's faster in pyodbc in Python
Answer: One answer (although it is v hacky) appears to be to put all the INSERTs into one string.  This takes 1 second
Private Sub StackOverflowPopTempTableRaw(cn As ADODB.Connection)
    Dim row As Long
    Dim strSql As String
    Dim row_count As Long
    Dim t As Single
    t = Timer

    'Create a temporary table
    strSql = "IF OBJECT_ID('tempdb..##tbl_dummy_data', 'U') IS NOT NULL " & _
                "DROP TABLE ##tbl_dummy_data; " & _
                "CREATE TABLE ##tbl_dummy_data ( " & _
                "dummy_data VARCHAR(20) PRIMARY KEY " & _
                ");"
    cn.Execute strSql

    'Add masterkeys to this exclusion table
    row_count = 1000
    For row = 1 To row_count
        strSql = strSql & "INSERT INTO ##tbl_dummy_data VALUES ('a" & row & "'); "
    Next row
    cn.Execute strSql
    Debug.Print Timer - t
End Sub


Display localstorage in input on load

Question: I have a small web calculator which calculates time. My mobile browser gets rid of all data when I've minimised/closed the mobile broswer for a few minutes or on a page refresh so I've made a button which can reload all previous data and displays as text.
I want to get rid of the "Get old data" button and just have the page reload with all the values displayed in the input box as they were before the page refresh.
I've been thinking an onload event in the input box would work but as i understand this is not possible.
HTML

Please enter minutes

<input type="text" id="etime">

Please enter time in 24 hour format (eg. 15:00)

<input type="text" id="stime">

<button onclick="myFunction()">Calculate</button>

<button onclick="getreload()">Get old data</button>

Javascript
function myFunction() {

function converToMinutes(s) {
    var c = s.split(':');
    return parseInt(c[0]) * 60 + parseInt(c[1]);
}

function parseTime(s) {
    var seconds = parseInt(s) % 60;
    return Math.floor(parseInt(s) / 60) + ":" + ((seconds < 10)?"0"+seconds:seconds);
}

var endTime = document.getElementById("etime").value;
var startTime = converToMinutes(document.getElementById("stime").value);
var converted = parseTime(startTime - endTime);

document.getElementById('finishtime').innerHTML = "You will finish your break at " + converted;

if (typeof(Storage) !== "undefined") {
localStorage.setItem("convertedTime", converted);
localStorage.setItem("endTimeReload", endTime);
} else {
// Sorry! No Web Storage support
}

}

function getreload()    {
var convertedTime = localStorage.getItem("convertedTime");
document.getElementById('finishtime2').innerHTML = "End of break time: " + convertedTime;

var endTimeReload = localStorage.getItem("endTimeReload");
document.getElementById('mintime2').innerHTML = "Minutes till next client: " + endTimeReload;
}

Comment: what error do you get. at a glance looks like it should work.
Comment: there's no error, it works great. I want to get rid of the "Get Old Data" button and just have the data load back in the input boxes on page refresh.
Answer: So after you've calculated a time, you want those values to be there if you refresh the page?
When you calculate, save all the values in localstorage, then when the page loads (body element's 'onload') set the input boxes values to the corresponding localstorage ones (checking to make sure those values exist first)
Answer: You are mostly there, but you are not restoring correctly and not saving the startTime.
Here is a fiddle with everything you need:
https://jsfiddle.net/22ej8scw/
Restore like this. (I also changed how it is saved)
function getreload()    {
    var startTime = localStorage.getItem("startTime");
    document.getElementById("stime").value = startTime;

    var endTimeReload = localStorage.getItem("endTimeReload");
    document.getElementById("etime").value = endTimeReload;

    if (startTime && endTimeReload)
        myFunction();
}

Comment: that worked great! thank you! is there anyway to clear all data?
Comment: don't worry, figured it out. small syntax error was stopping my clear function from working.

Display localstorage in input on load


jqGrid Mouse Drag to Resize

Question: I'm looking for a way to trigger a resize of a jqGrid by dragging the mouse.
Answer: Good news: in version 3.6 they've added a gridResize feature.
It adds the drag handle for you and everything.
<code>jQuery("#grid")
  .jqGrid('gridResize',
      {minWidth:350, maxWidth:800, minHeight:80, maxHeight:350}
      );
</code>
See the demo - it's the last item under "New in version 3.6"
http://trirand.com/blog/jqgrid/jqgrid.html
Comment: +1 as this is the "official" way. That said, the demo looks surprisingly clunky in Chrome; I hope the look & feel is improved in a future release.
Comment: this works pretty well -- except that it seems to break the collapse/expand functionality... any thoughts?
Comment: also seems really broken in opera.
Comment: That's a shame about Opera. It's a bit wonky, but I think it's good enough for me to implement. It's described as an 'experimental' feature, so hopefully it'll improve in v3.7

jqGrid Mouse Drag to Resize


Count on the same table

Question: i have got a problem with my SQL Statement:
Table structure:
CREATE TABLE "tags" (
  "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  "page_id" INTEGER NOT NULL,
  "title" TEXT NOT NULL
);

Now i want to select all the tags from one page and the frequency of this tag in the whole database. I have the following SQL statement:
SELECT title, title as t,
(SELECT COUNT(*) FROM tags WHERE title=t) as count
FROM tags WHERE page_id=42 ORDER BY count DESC, title
COLLATE NOCASE ASC;

But the error message i'm getting from SQLite3 Driver in PHP:
no such column: t

How do i have to write the SQL statement so that i get the result i want to have?
Thanks, Levu
Answer: Try this one
SELECT title,
(SELECT COUNT(*) FROM tags WHERE title=t.title) as count
FROM tags t
WHERE page_id=42
ORDER BY count DESC, title
COLLATE NOCASE ASC;

Answer: do you mean like this...
SELECT title, COUNT(*) as freq
FROM tags
WHERE page_id=42
GROUP BY title
ORDER BY freq DESC, title

Comment: what is the data in your table... are there more equal titles with page_id 42?
Answer: select title, count(*) as frequency
from tags
where page_id = 42
group by title
order by count(*) desc

If you want tags appear more than one
select title, count(*) as frequency
from tags
where page_id = 42
group by title
having count(*) > 1
order by count(*) desc

Comment: This also doesn't work, i want to have the frequency of the tags in the complete database, not just in the result...

Count on the same table


Gráfico sem imagem jsp

Question: Olá!
Estou querendo gerar gráfico pelo jsp
Tentei seguir esse tutorial
Mas só aparece um quadradinho no canto esquerdo da pagina quando executo
Arquivo Torta.jsp
<%
    try{
      DefaultPieDataset data = new DefaultPieDataset();
      while(rs.next()){
          data.setValue(rs.getString("marca"), rs.getInt("TOTAL"));
      }

      JFreeChart grafico = ChartFactory.createPieChart("Cantidad Productos", data, true, true, true);

      response.setContentType("image/JPEG");
      OutputStream sa = response.getOutputStream();

      ChartUtilities.writeChartAsJPEG(sa, grafico, 600,600 );

    }
    catch(Exception ex){
    }
%>

Arquivo conexion.jsp
<%
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/producto","root","123");
     Statement cmd= cn.createStatement();
     String sql = "SELECT MARCA, SUM(CANTIDAD) AS TOTAL FROM   PRODUCTO_CANTIDAD GROUP BY MARCA";
     ResultSet rs = cmd.executeQuery(sql);
%>

Imagem de como aparece o gráfico:

Agradeço antecipadamente.
Answer: Algumas possibilidades:

Como você está fazendo referência a essa imagem na página?
Você tentou executar essa query na base de dados pra ver se retorna dados?
Tentou colocar um ex.printStackTrace() no catch pra ver se não está ocorrendo algum erro na execução?
Comment: Tente fechar o OutputStream ( sa.close() ), caso não funcione, chame o flush antes de fechar ( sa.flush() )... Parece ser porque o navegador não recebe o fim do arquivo...
Comment: 1. Como você está fazendo referência a essa imagem na página?
Você tentou executar essa query na base de dados pra ver se retorna dados?
Tentou colocar um ex.printStackTrace() no catch pra ver se não está ocorrendo algum erro na execução?
Comment: 1Como você está fazendo referência a essa imagem na página?
    O Código só é esse

2. Você tentou executar essa query na base de dados pra ver se retorna dados?
    Sim. Retorna dados

3. Tentou colocar um ex.printStackTrace() no catch pra ver se não está ocorrendo algum erro na execução?
   Vou tentar agora
Comment: no console do chrome aparece assim:

net::ERR_INCOMPLETE_CHUNKED_ENCODING
Comment: Isso! Deu certo com sa.close();

Valeu mesmo!
Comment: Isso mesmo! Deu certíssimo! Era isso mesmo! Acrescentei o sa.close(); e funcionou. Muito obrigado!

Gráfico sem imagem jsp


2x2 code tab layout in Visual Studio 2017

Question: I wanted to change the way my workspace worked a bit today.
The way I wanted to set it up is to create a two by two tab layout so I can view and group 4 sets of (code) files. However, once I create a 1x2 or 2x1, only other option was to expand the existing layout (2x1 -> 3x1 -> 4x1 -> 5x1, etc, and vice versa).
Is there a way to create a 2x2 (or any other code tab configuration) in Visual Studio 2017?
EDIT: Seriously? You need a $50 plugin to do something so basic? There is no other way?
Answer: You may find my Task Canvas extension useful. It allows you to open code in multiple rows and, on a wide screen, additionally in multiple columns:
Comment: That's great, but that's $50 for something that should have been included from the get-go!


right click mouse to paste on a richtextbox vc++ windows forms

Question: I am searching on how to implement a mouse down right click to paste data from a buffer into a richtextbox with visual c++ windows forms. My richtextbox is working but I can only paste data from buffer using shift+insert key.
Thank you so much in advance.
Answer: Solution:
Changed the RichTextBox to TextBox and use the code:
private: System::Void button1_Click(System::Object^  sender System::EventArgs^  e) {
             String^ fileName = "output.txt";
             StreamWriter^ sw = gcnew StreamWriter(fileName);
             sw->WriteLine(textBox1->Text);
             sw->Close();

}
The "paste" option is automatically available on the textbox (multi-line in my case). I think this is not possible with RichTextBox without heavy coding?
Answer: Do you mean a right click menu which can paste the clipboard's text to the RichTextBox?
1) Add a ContextMenuStrip (contextMenuStrip1)
2) Add a ToolStripMenuItem and name it paste (pasteToolStripMenuItem)
3) Set richTextBox1's ContextMenuStrip to contextMenuStrip1
4) Double-click the pasteToolStripMenuItem
private: System::Void pasteToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e)
{
    richTextBox1->Paste();
}


Stopping the Indicator after task finished

Question: I am using the code below to upload an image to my server. The code is working good but the Indicator is not stopping. I am using Xcode 6 and Objective-c and her is my code:
-(void) uploadImage
{
    NSData *imageData = UIImageJPEGRepresentation(self.createdImage.image,0.2);

    if (imageData != nil)
    {
        NSString * filenames = [NSString stringWithFormat:@"TextLabel"];
        NSLog(@"%@", filenames);

        NSString *urlString = @"http://myWebSite/sendVideo.php";

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];

        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"filenames\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[filenames dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@%@%@%@.mov\"\r\n", toSaveVideoLink, myString, FormattedDate, FormattedTime]] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithData:imageData]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [request setHTTPBody:body];
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        NSLog(@"Response : %@",returnString);

        if([returnString isEqualToString:@"Success"])
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Image Saved Successfully" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];

            [alert show];

                [spinner stopAnimating];
               // [[UIApplication sharedApplication] endIgnoringInteractionEvents];
        }
        NSLog(@"Finish");
    }
}

I do not know where is the problem. The alert message appearing but the Indicator is not stopping. How could I stop it?
Comment: Have you tried stopping it before showing the alert? Does it stop after you dismiss the alert?
Answer: It's possible that spinner is not referencing the UIActivityIndicatorView that you think it is. Log the value of spinner and see what it contains. Also make sure it was added to the view correctly, etc. It's impossible to tell without seeing how you're instantiating the spinner, how you added it to the view, etc.
But, there's a deeper problem here, that you should not be doing a synchronous request. You are issuing your request like so:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"Response : %@",returnString);

if([returnString isEqualToString:@"Success"]) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Image Saved Successfully" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];

    [alert show];

    [spinner stopAnimating];
}

You should be doing this asynchronously:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    // this portion happens in the background

    NSString *returnString;

    if (data) {
        returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Response : %@",returnString);
        // do something with response
    } else {
        NSLog(@"Error: %@", error);
    }

    // dispatch UI update (and any model updates) back to the main queue

    dispatch_async(dispatch_get_main_queue(), ^{
        if([returnString isEqualToString:@"Success"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Image Saved Successfully" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [alert show];
        }
        NSAssert(spinner, @"Spinner is `nil`, but it should not be.");
        [spinner stopAnimating];
    });
}];
[task resume];

// do not do anything contingent upon the response here; the above runs asynchronously, so anything dependent upon the response must go in the block above

Also, if you're doing this block synchronously (which is very bad), I wonder if you're doing anything after this synchronously too (which would make it not respond to the stopping of the spinner in a timely manner). Again, it's impossible to tell without seeing the code, but that's another possible issue. Bottom line, just make sure you never do anything synchronously, and your UI will generally be more responsive.


What is the probability distribution of a web-server receiving a client connection request?

Question: An internet search for the probability distribution of a server getting a connection yielded no relevant results.
My guess is it would be be poisson or normal distribution, but I need something a bit better than a guess, so please cite a source for your answer!
Comment: Welcome to CV. It's not immediately apparent to me what you are asking. Would you please elaborate on what a "server getting a connection" is about and/or means -- in non-IT terms?
Comment: Basically it means that some remote machine is attempting to contact the server (to ask for data or to submit it).
Comment: So, it can be high frequency count data?
Answer: This question is too broad to have one answer for all circumstances.
When looking at the number of requests as a function of number of websites, you are hiding a third latent variable, which is the website type.
There are websites that do not attract any kind of user engagement (e.g. "about us" pages)  and there are websites that attract a lot of user engagement (e.g. Facebook and cross-validate (: )
The Poisson distribution assumes a memory-less behavior, this could be a good model if each web request for the website is single, and independent of each-other.
For example, I would expect that the wallmart's opening hours page would have this behavior.
But looking at an eCommerce websites (e.g. eBay, Amazon) , the behavior is much more complex, just imagine how does a black Friday would affects the number of requests.
In addition I would expect to see an underlying distribution of user types, for example "bargain seekers","compulsive buyers","feedback oriented" that would generate the observed "request distribution" in question.
To sum up, I doubt that you would find a "silver bullet" distribution for all website's request count. There are a lot of factors that depend on the website type and the user it attracts that need to be accounted for


Servidor HTTPS consulta cep dos correios

Question: Estou tentando requisitar o endereço pelo cep em um site, porém está dando o seguinte erro:

Mixed Content: The page at 'https://meusite.com.br' was loaded over HTTPS,
  but requested an insecure XMLHttpRequest endpoint
  'http://cep.correiocontrol.com.br/20040901.json'. This request has
  been blocked; the content must be served over HTTPS.

O servidor que meu site está hospedado é HTTPS então acredito que seja esse o problema... alguém conhece um site para consulta que também seja HTTPS para não dar erro de segurança?
Comment: Não é só você colocar `//:url` ao invés de `http://url`?
Comment: Quando você usa o protocolo HTTPS quando quer transitar dados eles  devem ser via protocolo HTTPS, no seu caso o seu servidor está usando o protocolo HTTPS mas o webservice do correios não, então ele não permite você fazer requisição pra um protocolo inseguro (no caso o http), faça o teste: faça a requisição através do procolo http, provavelmente irá funcionar.
Comment: @WallaceMaxters fiz isso e deu o seguinte erro: `GET https://cep.correiocontrol.com.br/20040901.json net::ERR_CONNECTION_TIMED_OUT`
Comment: É erro no servidor do correio então.
Comment: Deixa eu perguntar, você usa alguma linguagem de servidor (server-side)? Eu tenho uma solução para isso que acabou com essas dores de cabeça
Comment: @Laerte sim, isso mesmo... o problema que não posso fazer isso porque o sistema precisa estar em um servidor https
Comment: @WallaceMaxters sim, uso php framework Laravel
Comment: Cara eu dei uma olhada aqui, a única solução é ter essa URL disponível via https ou você trabalhar com HTTP, mas como você mesmo disse não será possível.
Answer: Quando você usa o protocolo HTTPS e precisa realizar requisições elas devem ser via HTTPS. Por questões de segurança.
No seu caso o seu servidor está usando o HTTPS mas o Web Service do Correios não, então ele não permite você fazer requisição pro servidor dos Correios por considera inseguro.
Mas você pode fazer requisições pro protocolo HTTPS via HTTP, exemplo: CDN.
A maioria dos browsers atuais bloqueia esse tipo de requisição, chamada de Mixed Content.

Para domínios de terceiros, use a versão HTTPS do site, se disponível. Se HTTPS não estiver disponível, você pode tentar entrar
  em contato com o domínio e perguntar se eles podem tornar o conteúdo
  disponível via HTTPS.

Fontes:
What is Mixed Content?
How to fix a website with blocked mixed content
Answer: Silvão, na boa? Já que você está usando Laravel, que tal usar um Proxinig?
Vai funcionar da seguinte forma: Você pega envia uma requisição para a url do cep pelo Laravel, e pelo jQuery, você enviar a requisição para o Laravel.
Te evitará muitas dores de cabeça, já que estará fazendo a requisição para o seu próprio domínio:
Route::get('cep/{cep}', function ($cep)
{
     $url = sprintf('http://cep.correiocontrol.com.br/%s.json', $cep);

     $json = json_decode(file_get_contents($url), true);

     return Response::json($json);
});

No seu jQuery, faça apenas isso:
$.get('/cep/' + cep, {}, function (response) { /** ... **/ });

A vantagem desse tipo de requisição é que você não precisa se preocupar com essas chatisses limitações impostas pelos navegadores.
Entenda mais sobre o assunto em:
Qual é o nome da operação quando fazemos uma requisição ajax para o servidor interno que por sua vez pega informação de externo?


Play E-Drums with Pedals only?

Question: Let me explain. We are a two-man-group. My mate is doing guitar and vocals and I am doing bass and percussion. Some time ago I build (soldering and then also really assembling) myself a set of 6 drum-pads I play with my feet and we have an old Yamaha drum computer that uses the MIDI from the drum-pads to generate drum samples. So far so good. However the build quality of these drum pads is as lousy as you would expect from someone who is mathematician by training (me) and the drum computer does not use the attack values from the MIDI signal. Hence, the drum sometimes are not triggered but if they are they always sound the same.
However, I had an idea, to buy an electric drum set and indead of connecting the toms and snare and so forth to the main component. So, I was wondering if it is possible to play an E-drum set only with, say six, pedals? This way I have all the advantages of E-drums available at my feet.
EDIT: I want to clarify, that I just want to connect another kick pad to the input for the snare. I assume that the drum-computer is fed by wires from all electric components. So I thought, why not connect another kick-drum to the input for the snare. Shouldn't I then be able to hear a snare sound, when I hit the pedal whose respective kick is connected to the snare?
Answer: A complete set of pads will only contain one drum pad, playable with a beater, as in a kick drum. The other pads are designed for hitting with sticks. So you could buy six 'bass drum' pads and six pedals, but that gets complex in playability.
Maybe the drum pads could be usable, but then you'd have to mount them and take up a fair bit of space. Then fit pedals.
I'm sure I've seen a one octave pedalboard (I built one for MIDI from an old organ set to play bass pedals) that is programmed to play all 13 notes. That could be re-programmed to make 13 drum sounds - easier to play, set up, break down, and could even be re-programmable with the right 'brain'. Or programmed for the Yamaha module.
It's very simple to plug any drum head into any input on the module. Whichever input used will produce the sound written on that input. So one drum can be inputted to make any of the sounds you want. But I still prefer my idea..!
Comment: I don't want to hit the other pads with pedals. I edit my question accordingly.
Comment: You have not edited clearly enough for me. It still says play with only 6 pedals, then you say you don't want to hit the other pads with pedals. Unclear. Header says pedals only. Read my edit.
Comment: Not really an answer to your question, but this could be an interesting alternative.
https://www.youtube.com/watch?v=m-nCJxizxvI
Comment: +1 There are definitely midi pedal controllers at different price ranges that would fit this need. Some are more modern with typical button style door pedals, others imitate the organ pedal style.

Play E-Drums with Pedals only?


(Function) Verificação de campos preenchidos retornar ação anterior

Question: Tenho uma função que verifica se os campos do meu formulário foram preenchidos ou não pegando pelo seu valor.
Caso tenha sido preenchido determinados campos e executado uma ação em que aparece a progressBar.
Nesta função tenho 4 Ifs que fazem a verificação e vai acrescentando mais um numero de campos para ver se foi preenchido ou não e então exibe a progressBar correspondente.
O problema é se todo o formulário foi preenchido ativando o quarto If e exibindo a "progressBar100", se depois disso o valor do campo "verInq1" for excluído a barra que passa a ser exibida no lugar da "progressBar100" será a "progressBar0" ao invés de ser a "progressBar75". Isso acontece em todos os Ifs.
Então eu queria fazer a verificação ao contrário também, em ordem decrescente onde se o último If não foi validado então ele retornasse o terceiro If e assim por diante.
HTML das progressBar.

25%

50%

75%

100%

Meu JS para checar o valor e executar ação.
function progressBarInq() {
            let progressBar0 = document.getElementById("InqProgress0");
            let progressBar25 = document.getElementById("InqProgress25");
            let progressBar50 = document.getElementById("InqProgress50");
            let progressBar75 = document.getElementById("InqProgress75");
            let progressBar100 = document.getElementById("InqProgress100");

            //25%
            let verInq1 = document.getElementById("InqueritoCircunscricaoPolicial");
            //50%
            let verInq5 = document.getElementById("NumeroDoIP");
            //75%
            let verInq8 = document.getElementById("DataDoRelatorio");
            //100%
            let verInq11 = document.getElementById("NumeroDoProcesso");

            if (verInq1.value) {
                progressBar0.style.display = "none";
                progressBar25.style.display = "block";
                progressBar50.style.display = "none";
                progressBar75.style.display = "none";
                progressBar100.style.display = "none";
            }
            if (verInq1.value && verInq5.value) {
                progressBar0.style.display = "none";
                progressBar25.style.display = "none";
                progressBar50.style.display = "block";
                progressBar75.style.display = "none";
                progressBar100.style.display = "none";
            }
            if (verInq1.value && verInq5.value && verInq8.value) {
                progressBar0.style.display = "none";
                progressBar25.style.display = "none";
                progressBar50.style.display = "none";
                progressBar75.style.display = "block";
                progressBar100.style.display = "none";
            }
            if (verInq1.value && verInq5.value && verInq8.value && verInq11.value) {
                progressBar0.style.display = "none";
                progressBar25.style.display = "none";
                progressBar50.style.display = "none";
                progressBar75.style.display = "none";
                progressBar100.style.display = "block";
            }

        }

        progressBarInq();

Answer: Você pode simplificar esses selects...
Além disso da pra simplificar o html para que possamos manipular somente o width ao inves de display...
Sendo assim da pra ter somente um progressbar.

// selecionado o progress bar
var progress = document.querySelector('.progress-bar');

//suas variaveis
let verInq1 = document.getElementById("InqueritoCircunscricaoPolicial");
let verInq5 = document.getElementById("NumeroDoIP");
let verInq8 = document.getElementById("DataDoRelatorio");
let verInq11 = document.getElementById("NumeroDoProcesso");

//aqui temos a definição em valor do width
//traduzindo temos ->
// total = (tem verInq1? então ja vale 25) + (tem verInq5? então soma 25)..etc..
let total = (verInq1 ? 25 : 0) +  (verInq5 ? 25 : 0) + (verInq8 ? 25 : 0) + (verInq11 ? 25 : 0);
//são expressões ternárias, vale a pena estudar.

//e aqui temos nosso width sendo setado com template string
progress.style.width = `${total}%`;

Comment: e como ficaria a verificação dos IFs?


Push Button press not detected in AVR

Question: I have written a code that detects a button press, first time the button is pressed a LED glows and when next time it is pressed , the LED should switch off, in the same way if third time it is pressed the LED should again glow.
The problem is , the controller is able to detect the button press but instead of switching on the LED for long time, it just momentarily switches it ON then it again switches OFF. And further button presses are not detected.
Below is the code:
#include <avr/io.h>
#include <avr/delay.h>

void glow();
void off();
void switchScan();

int main()
{
DDRA=0x02; // 0000 0010 --> BIT 0=connected to switch whose other pin is connected to   ground,, and BIT 1 is connected to LED with other pin of led connected to ground
PORTA=0x01; // 0000 0001---> Switch Input pulled up and LED output pulled down

while(1)
{
switchScan();
}

return 0;
}

void glow()
{
PORTA=PORTA|(1<<1);
}

void off()
{
PORTA=PORTA&(~(1<<1));
}

void switchScan()
{
 static int counter=0;
if(~(PINA & 0x01))
{
 counter++;
if(counter < 2)
glow();
else
{
counter--;
off();
}
}
}

Comment: Maybe you need to introduce a delay when you change the counter, to eliminate [contact bounce](http://en.wikipedia.org/wiki/Switch#Contact_bounce)? You might get more help on [E-Eng](http://electronics.stackexchange.com/).
Comment: What I mean is, if the switch 'bounces', the loop may record it as another 'press'. You won't see the bounce with the naked eye, but it's almost always present in any mechanical switch.
Comment: Thanks for prompt reply.. But one more problem is that first press is detected always so in that case , glow() function is called so the LED should continuously glow.. but it just glows momentarily.
Comment: ohh yes, right, thanks for your valuable comment .. i will try to fix the bouncing effect.
Answer: The logic in your switchScan() function is flawed. glow() will only be executed one single time. See code comments:
void switchScan() {
    static int counter=0;

    if (~(PINA & 0x01)) {
        counter++;
        // 1st button press: counter will be 1
        // 2nd and all following button presses: counter will be 2
        if (counter < 2)
            // can only be called once!
            glow();
        else {
            // counter will always go from 2 to 1 at this point
            counter--;
            off();
        }
    }
}

However, you should also consider the de-bouncing that Brett mentioned in the comments.
Comment: Thanks for replying .. i will correct the code and do the de-bouncing
Comment: As a starting point: Consider rewriting `switchScan()` to something like "bool IsKeyPressed()" and implement just pin check and de-bouncing logic in that function. Handle the switching between on/off by a global variable like `bool LedState;". This way you can get much cleaner code. Oh and please accept this answer if the problem is resolved.

Push Button press not detected in AVR


Prove that $f^{-1}\left(U_1\times\cdots\times U_\kappa\right)=\bigcap_{i=1}^\kappa \left(f_i\right)^{-1}\left(U_i\right)$

Question: Im working through Bloch's Proofs and Fundamentals and exercise 4.3.11 is

Let $B$ be a set, let $A_i,\cdots,A_\kappa$ be sets for some
   $k\in\mathbb{N}$ be a subset for all
   $i\in\left\{1,\cdots,\kappa\right\}$ and let $f:B\rightarrow
 A_1\times\cdots\times A_\kappa$ be a function. Prove that
   \begin{align} f^{-1}\left(U_1\times\cdots\times U_\kappa\right)=\bigcap_{i=1}^\kappa
 \left(f_i\right)^{-1}\left(U_i\right), \end{align} where $f_i$ are the
   coordinate functions of $f$.

My (perhaps poor) attempt at a short proof:
proof Suppose $b=f^{-1}\left(U_1\times\cdots\times U_\kappa\right)$ for some $b\in B$. Then \begin{align}f\left(b\right)&=f\left(f^{-1}\left(U_1\times\cdots\times U_\kappa\right)\right)\\&=U_1\times\cdots\times U_\kappa\subseteq A_1\times\cdots\times A_\kappa.\end{align}
Now suppose $b=\bigcap_{i=1}^\kappa\left(f_i\right)^{-1}\left(U_i\right)$ for some $b\in B$. Then \begin{align}f_i\left(b\right)&=f_i\left(\bigcap_{i=1}^\kappa\left(f_i\right)^{-1}\left(U_i\right)\right)\\&=\bigcap_{i=1}^\kappa f_i\left(\left(f_i\right)^{-1}\left(U_i\right)\right)\\&=\bigcap_{i=1}^\kappa U_i\\
&=?\end{align}
I'm not sure if I'm heading in the right direction or if it's wrong altogether. Constructive criticism and hints would be great.
Comment: Your notation is a bit off. $f^{-1}(U_1\times\dots\times U_k)$ is a subset of $B$, not an element of $B$. Other than that, $f(f^{-1}(U_1\times\dots\times U_k))\subset U_1\times \dots\times U_k$, but they are not quite equal. I can write out something a bit more substantial if you want.
Comment: You can prove this for $k=2$ and then use induction on $k$
Comment: @Moya Thanks! Does it appear as though I am heading in the right direction though? I feel off-track in the latter portion of the proof, i.e. considering the other side. And yes, I will make those necessary corrections.
Answer: Let $X=f^{-1}(U_1\times \dots \times U_k)$ and let $Y=\bigcap_{i=1}^k f_i^{-1}(U_i)$. We will show that $X\subset Y$ and $Y\subset X$.
Let $x\in X$. It means $f(x)\in f(X)\subset U_1\times \dots\times U_k$. Denoting $f(x)=(f_1(x),\dots, f_k(x)), f_i(x)\in A_i$, it means $f_i(x)\in U_i$ for every $i$, implying $x\in f_i^{-1}(U_i)$ for every $i$. So $x$ is in their intersection, meaning $x\in Y$. So $X\subset Y$.
Conversely, let $y\in Y$. Then $y\in f_i^{-1}(U_i)$ for every $i$. This implies $f_i(y)\in U_i$ for every $i$, so $f(y)=(f_1(y),\dots, f_k(y))\in U_1\times \dots \times U_k$. This means $y\in f^{-1}(U_1\times\dots U_k)=X$, so $Y\subset X$ and they're equal.
Comment: No worries. The basic idea to these naive set theory relations is just breaking down the definitions of both sides and making sure they line up. In this case, the definition of the intersection/product of sets as well as inverse images.
Comment: Also, Munkres' *Topology* has a good couple of chapters (the first 10 roughly) on this stuff with more challenging types of these sort of problems.
Comment: Thank you so much for your answer! I don't think I stated it in my original question, but this was not a homework problem, I'm just studying on my own time some more intricate concepts that weren't covered in my Discrete Math class (I'm an undergrad). I've worked through your solution step by step and it makes total sense.
Comment: Thanks! I just looked it up and found a copy. I will look it over tonight and the following few weeks, even try many of the problems if I can.


Equation of standard error of a sample mean

Question: In the equation of the standard error of a sample mean, it's given by: standard deviation divided by root-n.
My major concern is: is it the standard deviation of population or the sample on which this is based?
In some books, it is mentioned to be standard deviation of population while some books mentioned it is standard deviation of sample. In Wikipedia, it is the standard Deviation of the population which is impossible to know, hence standard deviation of sample is used.
Comment: The account I gave at https://stats.stackexchange.com/a/18609/919 may help you sort this out.
Answer: In the usual situation, the actual standard error of the mean is $\sigma/\sqrt{n}$, but you almost never know $\sigma$ (the population standard deviation), so you have to estimate it. Consequently, the estimated standard error of the mean is usually taken to be $s/\sqrt{n}$.
Some sources call that "the standard error of the mean", but strictly it's an estimate of that.
Comment: In this what is sigma ?Is it the standard deviation of mean of many samples taken from population ? If yes than how is is approximated by standard deviation of a sample...There might be a big difference in the two standard deviations
Comment: Following the usual convention, it's the population standard deviation. Yes, an estimate of it might be some distance from the population standard deviation (particularly with small samples). You can only use the information you have.
Answer: When you divide by n, it's the "population". But that's theoretical hogwash, you never know the SD of a population or if you did why the heck wouldn't you know the mean?
Using the sample SD is fine, but the SD/root-n estimator is biased due to using the same data to estimate two quantities. The degrees-of-freedom correction: SD / root(n-1) gives the minimum variance unbiased estimator.
Comment: Re "hogwash:" Sometimes I know the precision of a physical measurement system (and thereby its SD) but do not know the value I am measuring.
Comment: @ManojGupta sigma is the SD of the population *distribution*. The *standard deviation of [the] mean[s] of many samples taken from [the] population* is what we call the standard error. They are related but not the same.
Comment: Actually, the VARIANCE estimate is unbiased. It's difficult to get an unbiased SD; it can be done, but it's usually not worth the hassle.
Comment: In this what is sigma ?Is it the standard deviation of mean of many samples taken from population ? If yes than how is is approximated by standard deviation of a sample...There might be a big difference in the two standard deviations
Comment: @SheridanGrant you'll have to explain that one. SD is the root of variance. Both variance and SD estimates are biased when of the form SSE/n or root-SSE/n respectively. If you meant an unbiased estimate of the **standard error**, you're right: the formula is correct in either the limit when CLT applies or when the population (distribution) is normal.
Comment: @SheridanGrant Is your objection about the claim of a "minimum variance unbiased estimator"?
Comment: @AdamO yeah I just meant that s is not unbiased for sigma https://en.wikipedia.org/wiki/Standard_deviation#Unbiased_sample_standard_deviation
Comment: And wait why are you dividing again by root(n-1)--you've already done this in estimating sigma to account for estimating the mean.
Answer: It was already answered in two previous answers, but as a comment, notice that what Wikipedia says is:

Estimate
Since the population standard deviation is seldom known, the standard
  error of the mean is usually estimated as the sample standard
  deviation divided by the square root of the sample size (assuming
  statistical independence of the values in the sample).
  $$ {\sigma}_\bar{x}\ \approx \frac{s}{\sqrt{n}} $$

So the definition is given in terms of the unknown population parameter, but the estimator (function to estimate it from the data you have) is given in terms of sample estimate.
Comment: In this what is sigma ?Is it the standard deviation of mean of many samples taken from population ? If yes than how is is approximated by standard deviation of a sample...There might be a big difference in the two standard deviations
Comment: @ManojGupta what sigma? $s$ is sample standard deviation, as explained in Wikipedia. The quote is rather self-explanatory...
Comment: What is σ ? I mean what is actual standard deviation to be used in standard error equation?
Comment: @ManojGupta all the three answers answered this question, so I don't really understand what is unclear for you.


Support of density

Question: How do you determine the support of the sum of two random variables?
For example, if X,Y are independent random variables where Z=X+Y.
Im asked to find the density of Z, I use the convolution formula. But Im not sure on how you determine the support of $f_Z(z)$ after obtaining $f_Z(z)$.
Lets say that the support of X and Y is: $R_X=[a,b]$ and $R_Y=[A,B]$. What is $R_Z$ ?
Answer: We have
$$
f_Z(t) = \int_{\mathbb R}f_X(s)f_Y(t-s)\,ds = \int_a^bf_X(s)f_Y(t-s)\,ds.
$$
Now, $t$ is not in the support of $f_Z$ if $f_Y(t-s) = 0$ for all $s\in [a,b]$, right? This is the case if $t-s\notin [A,B]$ for all $s\in [a,b]$. That is, $t\notin [A+s,B+s]$ for all $s\in [a,b]$. And this holds if $t\notin [A+a,B+b]$. So, if $t\notin [A+a,B+b]$, then $f_Y(t-s) = 0$ for all $s\in [a,b]$ and thus $f_Z(t) = 0$. This implies that the support of $f_Z$ is contained in $[A+a,B+b]$.
Comment: Ah okay nice, that makes sense ;]

By the way, when carrying out the calculations in the integral. Am I doing it right when using the indicator function for $f_Y(t-s)$, and then obtaining the limits for $f_Y(t-s)$ and combining this with the integral limits?
Comment: I don't understand that. I can only say that you cannot replace $f_Y$ by an indicator function. Why should this be possible?
Comment: Think I phrased it wrong. But denote it as $(f_Y1_{\{t-s \in [A,B] \}})$, and then obtaining an inequality for $t-s$. Then obtain the values for s in that inequality, and combine it with the limits of the integral?
Comment: What we will have is that $ t-B \leq s \leq t-A$, and since we are integrating over [a,b] the ingration limits becomes: $\int_{max(a,t-b)}^{min(b,t-A)} $ ?
Comment: @fejz1234 "denote it as" Denote _what_ as? I cannot follow you.
Comment: The support of $f_Y(t-s)$ can be expressed with an indicator multiplied with $f_Y$? Or am I phrasing it completly wrong?
Comment: @fejz1234 I think you are thinking it much too complicated. If $t\notin [A+a,B+b]$, then $f_Y(t-s) = 0$ for all $s\in [a,b]$. Hence, the integrand in $f_Z(t)$ is zero. Thus, $f_Z(t) = 0$.
Comment: Okay, so I shouldnt set up the integral as this: $\int_a^b f_X(s)f_Y(t-s) ds= \int_a^b f_X(s)(f_Y(t-s)1_{\{t-B\leq s \leq t-A\}}) ds = \int_{max(a,t-B)}^{min(b,t-A)} f_X(s)f_Y(t-s) ds$  ?
Comment: You can do that. And then?
Comment: The problem for me was that I didn't know the support of Z, with the support  known $R_Z=[A+a,B+b]$ I should be able to determine the limits of the integral. Or how do you carry out the calculations for the integral? Is this the standard way?
Comment: @fejz1234 What do you mean by "Or how do you carry out the calculations for the integral?" You asked for the support of $f_Z$. Now, you know that it is contained in $[A+a,B+b]$. What you do there with max and min is fine. But for this, you don't need the support of $f_Z$.
Comment: But how do I determine $max(a,t-B)$ and $min(b,t-A)$ without the support of $f_Z$ ?
Comment: I meant if there is an easier way to calculate the integral, than the way that I set it up. Am I doing it too complicated, or is this the usual method that one does when calculating the integral of the convolution?
Comment: You cannot use the support of $f_Z$ to simplify this.
Comment: Think I am a bit confused now, what are the values of $t$ then? Isn't $t$ the values in the support of $f_Z$ ?
Comment: Why? Of course you can pick $t$ outside the support. Then the integral is zero.
Comment: Ok, Im not sure if I get this. How do you simplify $max(a,t-B)$ and $min(b,t-A)$ without the support?
Comment: I mean sure I can simplify it if I let $t\in \mathbb{R}$. But how can I know that the obtained limits $c_1=max(a,t-B)$ and $c_2=min(b,t-A)$ is in the support of $f_Z$? If not, then Im integrating zero without being aware of it?
Comment: You mix something here. The min/max limits are limits for $s$. The support of $f_Z$ is about $t$.
Comment: You can also proceed as follows: Instead of the min/max limits, you can integrate over the intersection $[a,b]\cap [t-B,t-A]$. This intersection is non-empty iff $t-B < b$ and $t-A > a$, that is, $t < B+b$ and $t > A+a$.
Comment: Ok so, $\int_{\mathbb{R}} f_X(s)f_Y(t-s)ds=\int_{A+a}^{B+b} f_X(s)f_Y(t-s) ds$ ?
Comment: No. I don't like to repeat myself. Read my comments. I wrote "You mix something here". Last time: You don't integrate over $t$ ,but over $s$!
Comment: Okay, I thought you said that I could integrate over the intersection of $[a,b]$ and $[t-B,t-A]$ instead, which was $t\in[A+a,B+b]$ ?
Comment: Ok. If you don't read and take into account what I write, I give up.

Support of density


Passing lat lng to another activity in Android

Question: I am trying to enable the user to long click on a map and, instead of creating a marker, the new activity should open. It should contain latitude and longitude, i.e. the location on which the user clicked.
I know data transfer is easy when I use dialogs, but I don't want to use dialog fragment in this part of my app.
MapActivity:
//Add marker on long click
final double finalLongitude = longitude;
final double finalLatitude = latitude;

mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
    // start SendMessageActivity need to add marker to message activity
    Intent intent = new Intent(getActivity(), DisplayLocationActivity.class);
    intent.putExtra("latitude",""+ finalLatitude);
    intent.putExtra("longitude", "" + finalLongitude);
    startActivity(intent);
}

DisplayLocationActivity:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_set_location);

    Bundle bundle = getIntent().getExtras();
    double lat = bundle.getDouble("latitude");
    double lng = bundle.getDouble("longitude");

    //display lat lng
    mLatDisplay = (TextView) findViewById(R.id.latTextViewDisplay);
    mLangDisplay = (TextView) findViewById(R.id.lngTextViewDisplay);

    mLatDisplay.setText(String.valueOf(lat));
    mLangDisplay.setText(String.valueOf(lng));
}

My problem is this - when I start the app and click on the map, the newly opened activity displays the lat and lng as 0.0 no matter where on the map I clicked.
Comment: That means your `if (myLocation != null) {` not getting called. debug and check here.
Answer: As see here LatLng:

public final class LatLng extends Object implements Parcelable

Means Latlng class implements Parcelable interface, so we can pass it direclty using Intent.putExtra like:
@Override
public void onMapLongClick(LatLng arg) {
  intent.putExtra("Latlng", arg);
  ..
}

and get it in next Activity using getExtras().getParcelable like:
LatLng objLatLng=getIntent().getExtras().getParcelable("Latlng");

Now use objLatLng to show location coordinates in TextView's.
Comment: @Kemo: it's ok. i have just posted this answer to show other and easy way to share `LatLng ` object between components.Thanks
Answer: You are passing the data as String but retrieving it as double.
Change
intent.putExtra("latitude",""+ finalLatitude);
intent.putExtra("longitude", "" + finalLongitude);

for
intent.putExtra("latitude", finalLatitude);
intent.putExtra("longitude", finalLongitude);

Comment: Althought this answer solves your issue and minimises the changes in your code for it to work, @ρяσѕρєя K 's answer is better and must be the accepted answer
Comment: Is `myLocation != null`?
Comment: Thank you for your reply Antonio, I now have the following problem - the lat/lng displays user's current location instead of the location on the map I clicked. I updated my code above.
Comment: myLocation != null is used when the device has not enabled GPS. If I set my GPS location enabled it shows my current location instead of the place on the map I clicked on.
Answer: In my case I am doing like this. First activity for sendinf intent...
LatLng center = mMap.getCameraPosition().target;
intent.putExtra("Latlng", center);

Second Activity.
Intent intent;
LatLng latlong =intent.getIntent().getExtras().getParcelable("Latlng");

Now you can get Latitude and Longitude from latlong Object
latlong.getlatitude;
latlong.getlongitude

Answer: You should write your Intent while passing data as this.
  intent.putExtra("latitude", finalLatitude);
  intent.putExtra("longitude", finalLongitude);

Comment: That means your `if (myLocation != null) {` not getting called. debug and check here.
Answer: Change the read code in the receiving activity to this:
Bundle bundle = getIntent().getExtras();
double lat = Double.valueOf(bundle.getString("latitude"));
double lng = Double.valueOf(bundle.getString("longitude"));

Or pass the Extras as doubles in the first place :-)
Answer: Try this,
intent.putExtra("lat","" finalLatitude);
intent.putExtra("lng", ""  finalLongitude);

then get like,
double lat = Double.valueOf(bundle.getString("lat"));
double lng = Double.valueOf(bundle.getString("lng"));

Thanks.


ES6: How to have a getter/setter for an object AND its properties

Question: Using JS getters and setters, I am aiming to create the following API case:
// the user should be able to write this to update thing

thing = {
   x: 1,
   y: 2
}

// OR they should be able to write this

thing.x = 1
thing.y = 2

Right now I am using code like this:
 get thing() {
   return {
     x: this._thing.x,
     y: this._thing.y
   };
 }

 set thing(value) {
   this._thing.x = value.x,
   this._thing.y = value.y
 }

This supports the first case, but not the second case.
Can this be done in any reasonably simple way?
EDIT: I will type up an example, but a use case for this might be that thing.x and thing.y should always round to an integer using Math.round().
Comment: Have you looked at how to define classes. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
Comment: `thing` returns a new object.
Comment: Yes this is part of a class. Or are you suggesting I turn _thing into a class instance? Because, in my project, it already is, actually...
Comment: Why have getters and setters at all? Unless there is a specific reason you are not mentioning, not using them would give you what you want for free.
Comment: I shortened by code for clarity purposes of the question. Please believe me that I need getters and setters here. I will try to post a fuller code example.
Comment: Yes `thing` returns a plain object literal, but if the user then alters that object literal by writing `this.thing.x = 5`, I cannot control it with a setter.
Comment: *This supports the first case* - it doesn't. There's no way to do `thing = { ... }`. Only if `thing` is a property of another object. It is possible to do with proxies, but most likely you have XY problem. The one should write code considering what language is capable of, not in the opposite way.
Comment: @estus yes `thing` is a property of a class
Answer: If you have to use getters and setters, a relatively simple solution would be define x and y as getters and setters as well.
get thing() {
  var self = this;
  return {
    get x() {
      return self._thing.x;
    }
    set x(value) {
      self._thing.x = value;
    }
    // same for y
  };
}

But you have to be aware that every time thing is accessed for reading, a new object will be created. Though you could avoid this by caching that object and reuse it.
In fact, I probably wouldn't have _thing at all. I'd just store _x and _y and generate an object once on demand:
class Foo {
  get thing() {
    if (this._thing) {
      return this._thing;
    }

    var self = this;
    return this._thing = {
      get x() {
        return self._x;
      }

      set x(value) {
        self._x = value;
      }
    };
  }

  set thing(value) {
    this._x = value.x;
    this._y = value.y;
  }
}

Comment: This looks promising! I will try it out... Would caching the object mean essentially creating it as a prior variable? Am I looking at needing `thing`, `_thing`, and `__thing`? I can see how that would get ugly but maybe useful in this specific case.
Comment: See the more complete example I added.
Comment: This is useful. It is a little tricky because for me, `_thing` is already another class instance ... but I think that the extra layer of abstraction you are describing can solve this. Returning a getter and setter w/in the getter looks right. One fix -- I think you want to use `self._x` on line 10, is that right?
Comment: Thanks this is great. As soon as I test this out, I will mark as answered.
Comment: This is exactly the case when we would want to have XY class instead of returning an object literal. It will look cleaner. And [it will be faster](http://stackoverflow.com/questions/36338289/object-descriptor-getter-setter-performance-in-recent-chrome-v8-versions).
Comment: @estus: Yeah, that seems to make sense.
Answer:
...a use case for this might be that thing.x and thing.y should always round to an integer using Math.round().

Consider using a Proxy

class Parent {
  constructor() {
    this.thing = {x: 15.6, y: 2.1};
  }

  set thing(value) {
    this._thing = new Proxy(value, {
      get: function(target, property, receiver) {
        // Catch all get access to properties on the object
        if (['x', 'y'].includes(property)) {
          // for x and y, return the real value, rounded
          return Math.round(target[property]);
        }
      }
    });
  }

  get thing() {
    return this._thing;
  }
}

var parent = new Parent();

console.log(parent.thing.x); // 16

parent.thing.x = 13.2;

console.log(parent.thing.x); // 13

parent.thing = {x: 10.1, y: 5.4};

console.log(parent.thing.y); // 5

// This works for the Jacque Goupil's conundrum
var anotherRef = parent.thing;
anotherRef.x = 5.8;
console.log(parent.thing.x); // 6

// In fact, if you wanted to dance with the devil...
var plainObj = {x: 10.1, y: 5.4};
parent.thing = plainObj;
plainObj.x = 7.2;
console.log(parent.thing.x); // 7
parent.thing.x = 22.2;
console.log(plainObj.x); // 22.2

The proxy allows you to catch a get or set operation on a property.
Caveat: IE doesn't natively support proxies for the moment. If I had a CDN for Google's Proxy polyfill I would add it to the snippet, but I don't. Also if you use Babel, there's babel-plugin-proxy
Comment: I will also try this, but it produces an Error ("Script Error") when I run the code snippet. Do you know why?
Comment: when you run it here on SO? I see 16 and 13 as the output
Comment: I ran it in Chrome and FF and it works fine, but it looks like in IE it needs a polyfill, hold on I'll see if I can find one.
Comment: answer updated to cover the points raised on the other answers
Answer: I don't think you should use this pattern, and I think you'll have trouble making it work. Consider the following cases:
// calls the position setter on foo
foo.position = {x: 10, y: 20};

// calls the position getter on foo, obtaining a simple {x:10,y:20} object
var pos = foo.position;

// calls the position getter on foo and then the x getter on position
var xx = foo.position.x;

So far, everything makes sense. Then we get to this situation:
// calls the position getter on foo and then the x setter on position
foo.position.x = 7;

Since we returned a simple map with the position getter, position.x simply assigns to the returned copy and doesn't modify foo's actual position. One way to fix this would be to have the position getter return a smarter object that has a reference to the foo instance and proper getter/setters. This would allow doing:
foo.position = bar.position;
bar.x += 10;

The bar.position getter would return an object that merely acts as a view for bar's x/y properties. Then, the foo.position setter would copy bar's x/y properties into its private storage. Makes sense. bar.x += 10 ads only to bar's position.
However, the following situation would be very confusing:
var temp = foo.position;
foo.position = bar.position;
bar.position = temp;

This creates the illusion that temp is a backup copy of foo.position but it isn't. It's a view. As soon as foo's position changes, we lose the data for good. There's no easy way to copy the position.
You could try making your position objects actually store both a copy of the data as well as a reference to the original, so that you can do both set and get... It's an endless problem.
But at this point, your sugar syntax is making everything much harder to maintain as well as much less efficient.
So instead of doing all this, I'd actually make is so that the x and y getter/setters are on the foo/bar objects themselves. I'd also make any code inside the foo/bar object treat positions as if they were immutable.