Why is bass note so important in harmonic analysis of music?

Question: In any type of harmonic analysis the bass plays a big part in determining the function of the harmony. There are even special ways to describe what note of the chord is in the bass (known as inversions) and notation for chord symbols to make sure the right note is in the bass (known as slash notation).
So why does the bass note play such a big role in harmony?
Comment: Ask Meghan Trainor. Or this lady https://www.youtube.com/watch?v=iyTTX6Wlf1Y
Answer: There is a rather more fundamental, physical reason for this than so far mentioned: the bass fills not only the bass frequency range, but its harmonics actually reach well into the midrange where all other voices have their fundamentals! In fact, since the bass has typically the strongest amplitude1 of all tuned instruments (save perhaps trumpets, lead vocals etc.), the middle voices have a hard time to really isolate themselves from these harmonics, at any time. Their harmonic function is thus always determined to a large degree by what interval they play over the bass.

1 This has again a particular reason: to make up for Fletcher-Munson, so the bass won't seem much quieter than everything else.
Answer: This is not a rigorous, scholarly answer, but a useful one: There is a simple, general principle in writing Western music that has been mentioned by many people over the centuries. It basically says that a piece of music has two important components: the melody up top, and the bass line down low. The chords are determined by filling in the spaces between the melody and the bass line to create musical effects that are pleasing. No matter how pieces of music are written, if you look at the music after it's written, you can see the sense of this.
When students study Western music theory, or "common-practice-period tonal harmony" as it is officially referred to, in the style of J. S. Bach, a frequent homework assignment they encounter is to take a short melody, then construct a bass line beneath it, then to write notes in-between to create chords to fill in the arrangement, according to the academic rules of part-writing. This is certainly not the only method of writing music, but it is fair to say that this method has been extremely common in all styles of music ever since the time of Bach.
Comment: Wheat, what is interesting to me is that there are great swaths of early Western music for which it is not true that melody is up and harmony is down, but the rule about bass notes defining the chord is *still* true for those periods, with one famous exception (the 14th/15th c English fashion for inversion chords)!
Answer: A lot of Western music falls into the broad category of primary melody on top, a lot of stuff in the middle, and bass line on bottom.  The outside lines--melody and bass--are easiest for our ears to distinguish because they are the lowest and highest boundaries of each vertical slice of harmony.  The inner voices are often (but by no means always) less important as melodic lines than they are for determining chord quality--the moment-to-moment color of a piece.
Therefore, if you know the bass, harmony, and melody of a piece of music, you know a lot about it.  You know the shape and color of each vertical slice, as well as the contours of the most prominent horizontal lines.  In fact, in many styles, there are idiomatic "good" ways to realize inner voices given a melody, bass and harmony, whether it be the figured bass notation of the Baroque or much freer jazz and pop styles.
Therefore, analyzing in terms of melody line, bass line, and harmony captures the "essential" identity of many types of music, from Baroque arias and dances to pop chord charts.  An experienced performer can satisfactorily replicate the "fundamental"  music from these sources.
Answer: I want to start my answer by saying: I don't know.  This is a very profound question.  It does not have a trivial answer.  I don't think anyone knows the answer for certain.
Because your question isn't just about how Common-Practice Era Western Music Theory Type analysis proceeds.  It's about how we think about what a chord is.  What is it about how we hear chords that makes us say that CEG is in an important sense the "same thing" as EGC?  Why do we conceptualize the various inversions of a chord as, er, "a chord"?
So this is a hypothesis: we think about music as we hear it, and individual pitches rest on a fundamental pitch because of how physics work, so perhaps we bring the same thinking to harmony.  I hypothesize our thinking about harmony proceeds from the assumption that harmony is really multiple voices making a single pitch with complicated overtones.
When you hear "EGC" (the first inversion of C major), even if produced by three separate instruments, maybe you hear it as if it were a single voice singing a single pitch with those overtones -- but we know intuitively that in nature that cannot be: no single resonant pitch can have the structure of EGC, because overtones simply don't happen in that order, so it implies to us an unheard lower C supporting that chord.
That's my guess.
Answer: The bass is so important because it imposes its presence on all the other sounding notes via three main characteristics:

Its harmonics interact with all the higher pitches.
It has a strong amplitude (see @leftaroundabout 's answer) and in practice is often doubled by many instruments in a variety of styles.
It stands out by virtue of being an outer voice. This is only true for the highest and lowest voices in a texture.
Answer: In a visceral sense, the bass is the below the other tones in the music, so it has the perceptual role of supporting them. An analogy can be made to the foundation  of the house, which supports the rest of the structure. You don't start building a house until a good foundation is laid down, and the foundation determines how the rest of the house is built.
Comment: It doesn't help me as a community member to downvote my answer and not tell me why. If I can improve I'd like to know how. Please discuss your downvote, for my benefit.


NodeJS TCP Server, onData small chunks

Question: I made a simple NodeJS TCP server which a Java Client sends an image:
encodedImage =
out.write("IMG;" + encodedImage);
out.flush();

My NodeJS server is as follows:
net.createServer(function(TCPSocket){
        TCPSocket.on("data", function(data){
            console.log("TCP Recieved: " + data.length);
        });
}).listen(5000);

However, even if I send all data and flush it immediately, the output is as follows:
TCP Recieved: 13
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1472
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344
TCP Recieved: 1344

I want it to recieve it in a simple chunk, but I assume it is happenng due to NodeJS's event handling mechanism, what is the best way to achieve single chunk of data for data sent as a single chunk? As far as I know, a TCP window can be much larger than 1344 bytes of data. I thought of using header values as  HTTP so I know the length ad construct the object I want.
Comment: This is the way tcp works. Not only in node, but everywhere. You can't control this. And you should not attempt. When writing tcp server, always assume data coming in with random sized chunks.
Comment: Yes, I am aware TCP is a streaming protocol, but I was asking to know if there is a way to trigger the event when specific amount of data was recieved, like java's socket reading, but I need to make a a buffering mechanism
Answer: You're correct, in Node the data will come in chunked.  You'll need to keep a buffer, concatenating all the blocks that come in and then when the socket is closed, write your data out to the file system.  Here is an example that was able to receive an image:
net = require('net');
fs = require('fs');

net.createServer(function(socket){
  var buffer = new Buffer(0, 'binary');

  socket.on("data", function(data){
    buffer = Buffer.concat([buffer, new Buffer(data,'binary')]);
  });

  socket.on("end", function(data) {
    fs.writeFile("image.jpg", buffer, function(err) {
      if(err) {
        console.log(err);
      } else {
        console.log("Socket[" + socket.name + "] closed, wrote data out to sinfo.data");
      }
    });

  });

}).listen(5000);

console.log('ready');

I sent an image to it using netcat:
$ netcat localhost 5000 < input.jpg

Comment: Why wouldn't you just write the chunks to disk as you receive them?  It's wasteful to buffer the entire image in memory and then write it to disk.
Comment: @josh3736: Your comment is exactly what i am trying.
I send a base64 encoded socket stream from a client to the server. The server should write an image file from the incoming chunks.
Do you know how to properly write these chunks into the writestream to save ram?
This is my question: stackoverflow.com/questions/22214267/write-base64-chunks-into-writestream
Comment: Am I missing something? Can't you just use pipe?
socket.pipe(fs.createWriteStream(filePath));
Comment: Instead of concatenating buffers do `var list = []; list.push(buffer); .... var final_buffer = Buffer.concat(list);`.
Comment: If i receive continually the buffer from tcp (with some images), how i know that it would finished ? is there a way to do it without the end event ?
Comment: I didn't know about socket.pipe() when I wrote this - you should post it as an answer.

NodeJS TCP Server, onData small chunks


Jordan Normal Form in $\mathbb F_2$ and $\mathbb F_4$

Question: I want to determine the Jordan normal form of the following matrix:
$$\begin{bmatrix}0 & 1\\1 & 1\ \end{bmatrix}$$
in $M_2(\mathbb F_2) $ and $M_2(\mathbb F_4) $.
I know how to generally determine the Jordan normal form of a matrix, but I'm somehow stuck on how to do it in $M_2(\mathbb F_2) $ or $M_2(\mathbb F_4) $.
I first wanted to show that the matrix given is diagonalisable, but then I end up with eigenvalues $\frac{-1 \pm \sqrt{-3}}{2}$. Can I simply ignore the fact that those are not $\in \mathbb F_2$ nor $\mathbb F_4$?
If someone could show me how to solve it in $\mathbb F_2$, then I think I could do the other one. I'd be happy about every help.
Comment: The quadratic formula for the roots doesn't hold. But still, the characteristic polynomial does have a root in $\mathbb F_4$.
Answer: The technique of completing the square for solving a quadratic involves multiplying by $4$ or dividing by $2$, which cannot be done in a field of characteristic $2$.
Indeed the characteristic polynomial of the matrix is
$$
\det\begin{bmatrix}-x & 1 \\ 1 & 1-x\end{bmatrix}
=-x(1-x)-1=x^2-x-1=x^2+x+1
$$
which is irreducible over $\mathbb{F}_2$, having no roots. Since it has degree $2$, it has its roots in $\mathbb{F}_4$. If $\alpha$ is one of them, then the other one is $\alpha+1=\alpha^{-1}$.
So the matrix is diagonalizable over $\mathbb{F}_4$, having distinct eigenvalues. We can also find the eigenvectors:
$$
\begin{bmatrix}1\\\alpha\end{bmatrix}
\qquad
\begin{bmatrix}\alpha\\1\end{bmatrix}
$$
so
$$
\begin{bmatrix}0 & 1 \\ 1 & 1\end{bmatrix}=
\begin{bmatrix}1 & \alpha\\\alpha & 1\end{bmatrix}
\begin{bmatrix}\alpha & 0 \\ 0 & \alpha^{-1}\end{bmatrix}
\begin{bmatrix}\alpha^{-1} & 1 \\ 1 & \alpha^{-1}\end{bmatrix}
$$
Note that $\alpha^2=\alpha^{-1}$ and $\alpha^{3}=1$, so the powers of the diagonal matrix are
$$
D^{3k}=I,\quad
D^{3k+1}=D=\begin{bmatrix}\alpha & 0 \\ 0 & \alpha^{-1}\end{bmatrix}\quad
D^{3k+2}=D^2=\begin{bmatrix}\alpha^{-1} & 0 \\ 0 & \alpha\end{bmatrix}
$$
which you can compute the powers of the original matrix from.
Answer: The matrix is diagonalizable over $\mathbf{F}_4$. Explicitly, its characteristic polynomial is (the Artin-Schreier polynomial)
$x^2 + x + 1$
whose roots are the two distinct elements $\lambda$ and $\lambda + 1$ of $\mathbf{F}_4 - \mathbf{F}_2$.
Does that help you and can you now complete the argument?


Using document.getElementById with partial ID name

Question: Hope you can help me with this problem... My code:
function showIt() {
  document.getElementById("gatewayContainerstacks_in_9_page4").style.visibility = "hidden";
}
setTimeout("showIt()", 2500); // after 2.5 sec

I want to hide a div after 2.5 sec. It is working fine but the problem is that the div I want to target is dynamic. Only the first word is always the same (gatewayContainerstacks). After that the ID is dynamic (the _in_9_page4 part). Is there a way to make the code search out the div starting with gatewayContainerstacks? I would appreciate a hint.. Thanks...
Answer: Use document.querySelector() in conjunction with the CSS attribute selector ^= to match elements with IDs starting with the desired prefix:
function showIt() {
  document.querySelector('[id^="gatewayContainerstacks"]').style.visibility = "hidden";
}
setTimeout(showIt, 2500);

Here, I also passed the function showIt as such (and not as a string) to setTimeout. See MDN on setTimeout for the reasons.
Comment: @Rodrigo You can use the [CSS attribute selector `*=`](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) to match for string containment.
Comment: What if the term searched for is in the middle, and not the beginning, of the id?
Answer: Well, first off, you should NEVER pass a string to setTimeout. In this case, you can just pass showIt (no parentheses!) and it'll work just fine.
As for your actual problem, you can try something like this:
document.querySelector("[id^=gatewayContainerstacks]").style.visibility = "hidden";

However keep in mind that this will not work in Internet Explorer before version 8, and may not work in some older mobile browsers either.
For a more general solution, I'd suggest giving a unique and known ID, and then putting other information into data-* attributes:

...

Or something like that.


Interversion of limit and summation of double-indexed sequence

Question: Assume we have a sequence $(a_{m,n}) \in [0,1]^{\mathbb{N}\times \mathbb{N}}$ such that $a_{m,n} \rightarrow a_n\in [0,1]$ when $m \rightarrow \infty$. Are there any known conditions under which
$\sum_{n=0}^{\infty} a_{m,n} \rightarrow \sum_{n=0}^{\infty} a_n$ when $m \rightarrow \infty$ ? Assume it is known that both series converge.
Answer: You can conclude that $\sum_{n=0}^{\infty} a_{m,n} \rightarrow \sum_{n=0}^{\infty} a_n$ if (but not only if) there exists $b_n \geq 0$ such that $\sum_0^{\infty}b_n < +\infty$ where $|a_{m,n}| \leq b_n$ for all $n,m \in \mathbb{N}$. This is a version of the famous dominated convergence theorem where the measure space is $(\mathbb{N},\mu)$ with $\mu(A)=\# A$.
Answer: We can translate Lebesgue's monotone and dominated convergence theorems to sequences $f_m = (a_{m, n})_{n=1}^\infty$ and $f = (a_n)_{n=1}^\infty$.
Lebesgue's monotone convergence theorem tells us that if $f_m$ is increasing then $$\int_\mathbb{N} f_m\ \mathrm{d}\mu \to \int_\mathbb{N} f\ \mathrm{d}\mu$$ where $\mu$ is the counting measure on $\mathbb{N}$. In other words, if $a_{m, n}$ is increasing in $m$ for each $n$, then $$\sum_{n=1}^\infty a_{m, n} \to \sum_{n=1}^\infty a_n.$$ But, clearly, we can just assume $a_{m, n}$ is increasing in $m$ for each big enough $n$ and $m$. And by that I mean, if there exist $N$ and $M$ such that $a_{m, n}$ is increasing in $m$ for $m>M$ and $n>N$.
Other theorem is the Lebesgue's dominated convergence theorem. It says that if there exists a function $g = (b_n)_{n=1}^\infty$ which bounds $f_m\leq g$ from above, meaning $a_{m, n}\leq b_n$ for all $m, n$, and $g$ is integrable, that is, $$\int_\mathbb{N} g\ \mathrm{d}\mu = \sum_{n=1}^\infty b_n < \infty,$$ then we can say that again $$\sum_{n=1}^\infty a_{m, n}\to \sum_{n=1}^\infty a_n.$$
Those are very important theorems in the theory of Lebesgue integrals. By treating infinite sums as integrals we can derive statements about infinite sums like above.


Strong law of large numbers for a scaled sequence of normally distributed random variables

Question: Let

$f\in C^3(\mathbb R)$ be positive
$g:=\ln f$
$d\in\mathbb N$, $$p_d(x):=\prod_{i=1}^df(x_i)\;\;\;\text{for }x\in\mathbb R^d$$ and $\lambda^d$ denote the Lebesgue measure on $\mathcal B(\mathbb R^d)$
$\ell>0$, $\sigma_d:=\ell d^{-\alpha}$ for some $\alpha\in[0,1]$ and $$Q_d(x,\;\cdot\;):=\mathcal N(x,\sigma_d^2I_d)\;\;\;\text{for }x\in\mathbb R^d$$
$X$ be a $\mathbb R^d$-valued random variable on $(\Omega,\mathcal A,\operatorname P)$ with $$X_\ast\operatorname P=p_d\lambda^d$$
$Y$ be a $\mathbb R^d$-valued random variable on $(\Omega,\mathcal A,\operatorname P)$ with $$\operatorname P\left[Y\in B\mid X\right]=Q_d(X,B)\;\;\;\text{almost surely for all }B\in\mathcal B(\mathbb R^d)\tag0$$

Note that, by $(0)$, $(X,Y)_\ast\operatorname P=X_\ast\operatorname P\otimes\:Q_d$ is the product of the distribution $X_\ast\operatorname P$ of $X$ under $\operatorname P$ and the Markov kernel $Q_d$. Moreover, there is a $\mathbb R^d$-valued random variable $Z$ on $(\Omega,\mathcal A,\operatorname P)$ with $Z_\ast\operatorname P=\mathcal N_d(0,I_d)$ and $Y=X+\sigma_dZ$. It's easy to see that $X$ and $Y-X$ are independent.
Assume $$I:=\int f|g'|^2\:{\rm d}\lambda^1<\infty.$$

Are we able to show $$S_d:=\frac1d\sum_{i=1}^dg''(X_i)(Y_i-X_i)^2\xrightarrow{d\to\infty}-I\;\;\;\text{almost surely?}\tag1$$

In this paper, at the beginning of page 3, it is claimed that $(1)$ holds "under appropriate technical conditions".
$(1)$ seems wrong to me. From the strong law of large numbers, we should obtain $$\frac1d\sum_{i=1}^d\frac{f''(X_i)}{f(X_i)}Z_i^2\xrightarrow{d\to\infty}\int f''\:{\rm d}\lambda^1\;\;\;\text{almost surely}\tag2$$ and $$\frac1d\sum_{i=1}^d{g'(X_i)}^2Z_i^2\xrightarrow{d\to\infty}I\;\;\;\text{almost surely}\tag3.$$ Noting that $$g''=\frac{f''}f-|g'|^2\tag4,$$ we should have $$S_d\xrightarrow{d\to\infty}\int f''\:{\rm d}\lambda^1-I\;\;\;\text{almost surely}\tag5$$ instead of $(1)$. What am I missing? It seems like the only "technical condition" that would yield the claim is that the integral on the right-hand side of $(2)$ is $0$.
Answer: I guess the claim is wrong in general. However, if we assume that $g'$ is Lipschitz continuous, we're able to conclude $f(x)\xrightarrow{|x|\to\infty}0$ and $f'(x)\xrightarrow{|x|\to\infty}0$. If we now further assume that $$\int|f''|\:{\rm d}\lambda^1<\infty\tag6,$$ we obtain $$\int fg''\:{\rm d}\lambda^1\xleftarrow{r\to\infty}f'(r)-f'(-r)-\int_{-r}^rf'(x)g'(x)\:{\rm d}x\xrightarrow{r\to\infty}-I\tag7$$ by Lebesgue's dominated convergence theorem and partial integration. In particular, $$\int f''\:{\rm d}\lambda^1=0\tag8.$$


Regression model similar to neuron action potential?

Question: On the wiki page for depolarization they show a plot of the action potential in a neuron exhibiting depolarization. See below.

I am actually modelling gene expression over time, and some of the genes in my data have a time-dependence similar to the plot above. The key features of this curve that interest me:

Initial baseline.
Asymmetric peak.
Drop below baseline after peak.
Monotonic increase back to baseline.

Is there a parametric model for this kind of time-dependence curve?
Answer: I am not aware of a parametric model for an action potential but using Fourier analysis you can get a decomposition in sines or cosines that may recreate your curve very accurately. To do that you need to digitize the curve you are showing and get the Fourier spectrum.The book I used  decades ago is "The FFT, Fundamentals and Concepts" by Robert W. Ramirez. It is good but I am sure there are more updated sources.


Assessing the relationship between continuous variables

Question: <code>  Age.of.Diagnosis Native.American European  African
                60             0.5      0.4      0.1
</code>
I have the ancestry data on ~100 individuals with cancer, and I would like to know how ancestry affects the age of diagnosis. Essentially I have 2 continuous predictors (ancestry) and 1 continuous response variable (age of diagnosis). What statistical method might be appropriate here?
Comment: What exactly does a record in your data set represent? Do 47.8% of all persons who were diagnosed cancer at 55y are native American? Or is it a single persons exact ancestry?
Comment: It would appear you actually have only *two* predictors: isn't each one always going to be equal to $1$ less than the sum of the other two?
Comment: @Adrian See http://www.ncbi.nlm.nih.gov/pmc/articles/PMC4069235/
Comment: perhaps survival analysis, if you know when they were monitored eg all subjects monitored from 50-60 years of age, so you know subject 1 didnt test positive for cancer between 50 and 54 years], as opposed to only went to the doctor when 55.
Comment: I agree with @seanv507; cancer detection is a time-to-event problem. Pathophysiologically, @Adrian, do you have in mind an accelerated failure time model, with ancestry as one determinant of the frailty? Spending some time considering the details of such models might scare you off concluding anything from these data without more information--which could be a good thing. Are there meaningful competing risks within the age range you're considering? Is this an indolent cancer (e.g., prostate) where intensity of surveillance (as opposed to the underlying disease process) could drive detection?
Comment: My discouraging comments above notwithstanding, it is nice to see *ancestry* treated in a continuous, multidimensional manner in your data, @Adrian, instead of the usual categorical way.
Comment: @whuber Oh yes, you are exactly right. I do have two predictors. Thanks for point that out.
Comment: @seanv507 I considered doing survival analysis, but no I don't know when they were monitored. In this case would doing survival analysis be inappropriate?
Comment: If you don't know the monitoring period then survival analysis is inappropriate
Comment: be cautions if any of the groups are immigrants, as the age-distribution among immigrant groups trend to be very different from other populations within a country. This may seriously bias the conclusions. Age-adjusted incidence rates could be considered.
Comment: i would go first with regression trees, because their results are easily interpretable (if the tree is not too deep...)
Comment: @Adrian: You deleted most of your question in an edit. I suppose it was an accident, as you've already two answers & several comments referring to the deleted contents; so I've rolled it back.
Comment: @Adrian: What's going on? The answers will become confusing to readers if you change the question like this?
Answer: There are examples of using Multiple Linear Regression for similar studies[1]
Here is an notebook example of doing this in R.
[1] Genomic ancestry and somatic alterations correlate with age at diagnosis in Hispanic children with B-cell ALL
Comment: Good ol' linear regression is a tempting choice, but we need to know the study design in order to conclude anything about these data.
Answer: Here is a somewhat simplistic (Bayesian) model for your problem. I did not complete it (I am not 100% positive I can). Let me know if this seems reasonable, it looks like a nice problem!
Imagine a human being is made of three independent parts: a native american part (1), a european part (2) and an african part (3). Thus, a person is represented as $x \in \mathbb{R}_{+}^3$ (meaning $x_1,x_2, x_3 \geq 0$) with the constraint $x_1+x_2+x_3 = 1$.
In order to get cancer, a human must get "enough" cancer in their inidividual parts. So if a person $x = (\frac{1}{3},\frac{1}{3},\frac{1}{3})^t$, then they can get cacner if each part gets cancer independently. Alternatively, they can get cancer by summing: say the european part gets cancer twice, the african part gets cancer once and the native american doesn't get cancer at all. In this context it is assumed that getting cancer and being diagnosed are the same (I know it might not hold but we can make things complicated later).
The probability for a part to get some number of cancers in time $T$ is modeled as Poisson process(very reasonable: it counts how many hits one gets in a given time) with some corresponding parameter $\lambda_i$. Consequently, for and individual $x$, the occurence of cancers until time $T$ is distributed like $ \sum_{i=1}^3 x_i N_i(T)$, where each $N_i(t)$ is a Poisson process with parameter $\lambda_i$. We are only interested in the first time the individual gets a total of 1 cancer or more. I believe this time should be exponential random variable with parameter that is a kind of average of the $\lambda_i$'s (I don't know that for sure, this is the missing part).
\begin{eqnarray}
\begin{split}
%
%
P( \text{Cancer before time } t|\lambda, x)&= P( \sum_i x_i N_i(t) \geq 1) \\
%
%
&= \sum_{k_1,k_2,k_3} \prod_{i=1}^3 \frac{e^{-\lambda_i} (\lambda_it)^{k_i}}{k_i!} \\
%
%
&= \sum_{k_1,k_2,k_3} \frac{e^{\lambda_1+\lambda_2+\lambda_3} \lambda_1^{k_1}\lambda_2^{k_2}\lambda_3^{k_3}t^{k_1+k_2+k_3}}{k_1!k_2!k_3!}
\end{split}
\end{eqnarray}
where the sum is over triplets $(k_1,k_2,k_3)$ such that $\sum_i k_i x_i \geq 1$. This seems to be the hard part. However, it looks like one can estimate it numerically, so that might just be enough.
If one has this distribution $P( \text{Cancer before time } t|\lambda, x)$, then calculating the data likelihood $p(\text{Data} | \lambda )$ should be trivial (a product of iids with the above distributions). Choose a reasonable prior for $\lambda$ and Bayes rule will allow you to get the probability $p(\lambda | \text{Data})$. For a new individual $x$, the distribution of age they get cancer is going to be the predictive distribution
$$
p( \text{Cancer} | x, \text{Data} ) = \int p( \text{Cancer} | \lambda, x) p(\lambda | \text{Data} ) d\lambda,
$$
 which can (probably) be estimated using Gibbs sampling.


Google Chrome call a JS Script Console?

Question: I'm trying basically, what is done here: Calling a Javascript Function from Console
Just in another way that I can't find out.
At reddit.com I'm trying to remove that Try the Redesign button. If you F12 using Google Chrome while in reddit.com you should be able to see Application, you click that and then go to scripts and search for OptIn using CTRL+F. Then you find the code, I'll just put some part of it in here.
    function f() {
        a("redesignbanner", "click", "r2banner_dismiss")
    }

this
e.actions.on("onboarding:redesignbetabarClose", f),
e.actions.on("onboarding:redesignbetabarClickOptIn", c),

and this
        initBanner: function() {
            var n = $(".redesignbetabar");
            if (!n.length)
                return;
            $("#redesign-beta-optin").on("click", function() {
                e.actions.trigger("onboarding:redesignbetabarClickOptIn"),
                t(function() {
                    e.onboardingBar.setDismissed(n.data(), !0),
                    window.location.reload(!0)
                }, function(t, n, i) {
                    e.warn("Error opting in to redesign", n, ";", i)
                })
            })
        }

Do you see that e.onboardingBar.setDismissed(n.data(), !0)? Basically, I tried to run this too, but I couldn't figure out how.
My point is to remove that button on the top right, which looks like this.

If you don't know how to get that button, I'll tried to figure out how and found out how to get it.
You go to the reddit account settings on the top right > scroll down and check, Use the redesign as my default experience > then you click on save
and then you go again to settings or if you are still there, just uncheck it and the button should appear, which is annoying and I can't get rid of it, seems that I didn't had this problem before also others have it but not all and thats weird.
Comment: Looks like a method (function inside an object) which you might access via objectname.initBanner() though there maybe more nestings (I didn't check the source). If all is inside $.ready you can forget it (like with a closure). Even if it works you only access a click handler.. that triggers a custom event... in other words this will get you nowhere.  You 're better off removing the element with a selector... ie try something similar to `jQuery("#header").remove()`
Comment: I tried to get rid of it permanently but its just temporary, not sure how google chrome cache thing works.
Comment: Of course it comes back when you reload the page... only way to get rid of it permanently is if reddit changes their source code
Answer: Since Reddit wraps almost all of their JavaScript code in anonymous functions, you are unable to access the variables and functions defined within them. For example, see the following code:
(function() {
  var x = 2;
})();

The variable x can not be accessed from anywhere except inside that anonymous function, and since that function has no name, there is no way to refer to it or access anything inside of it.
Reddit does the same thing with their code, meaning you can't call any of those methods. However, there is another way to hide the button using CSS. The button has the class "redesign-beta-optin", so the following CSS will hide the button:
.redesign-beta-optin { display: none }

This can be done with JavaScript like so:
document.getElementsByClassName("redesign-beta-optin")[0].style.display = "none"

EDIT
To get rid of the button permanently, you can use a Chrome extension such as Tampermonkey or Stylish that allows you to run JavaScript and CSS on certain web pages.
To do this with Tampermonkey, create a UserScript with the following contents:
// ==UserScript==
// @name Reddit Redesign Button Remover
// @description  Remove reddit redesign button
// @author       kmh
// @match        https://*.reddit.com/*
// ==/UserScript==

document.getElementsByClassName("redesign-beta-optin")[0].style.display = "none";

With Stylish, you can create a new style for the domain reddit.com with the contents:
.redesign-beta-optin { display: none }

You will notice a small period of time as the site is loading with the button there if you use Tampermonkey, since it takes some time to initialize. This does not happen with Stylish.
Comment: What is the [0] for?
Comment: document.getElementsByClassName returns an array of elements because multiple elements can share the same class name. [0] gets the first element of the array, which we know is the element we want since there is only one element with that class.
Comment: If you create a new account on reddit it will not show that thing, and not sure how, but maybe if I manipulate the cookies it will make it go away?

Google Chrome call a JS Script Console?


change class instance attribute conditionally in python

Question: I'm a newbie in python. I have a class X inheriting class Y. In class X the attribute b allways
keep constant and never change but in the class Y it must change when a given
condition is satisfied.
class X(object):

   def __init__(self,others_attributes):

       self.b = 1
       self.others_attributes = others_attributes

class Y(X):

   def __init__(self,others_attributes,variable_condition):

        super(X, self).__init__(others_attributes)

    self.b += 1

How can ensure that each simulation step any instance of the class Y will have a specific value of the attribute b? Shall I create a @classmethod or a @properties similar to something like below?
Or is there a better strategy?
if variable_condition:
    self.b = self.b + 1
else:
    self.b = self.b

return self.b

Comment: You don't need `self.b = self.b`.
Comment: Thank you @Barmar. You're right!
Answer: Not sure if you're asking about maintaining class level state or instance level state.
If you're asking about how to change class level state all you need to do is store b as a class variable:
some_condition = True

class X(object):
    count = 0

class Y(X):
    def __init__(self):
        if some_condition:
            Y.count += 1

instances = [
    X(),
    Y(),
    Y(),
    X(),
    X(),
    Y()
]

print('\n'.join([str(i.count) for i in instances]))

If you want to change the b for only certain instances of Y then you could do something like:
class X(object):
    def __init__(self):
        self.b = 0

class Y(X):
    def __init__(self, some_condition):
        super(Y, self).__init__()
        if some_condition:
            self.b += 1  # or set it to whatever else you want
        else:
            self.b = -1

instances = [
    X(),
    Y(True),
    Y(False),
    X(),
    X(),
    Y(True)
]

print('\n'.join([str(i.b) for i in instances]))

Comment: Thank you @kingkupps I wanna change the b for only certain instances of Y.
Answer: @kingkupps
considering as bellow
some_condition = True

class X(object):
    def __init__(self,a,c):
        self.b = 1
        self.a = a
        self.c = c

class Y(X):

   def __init__(self,a,c):

        super(X,self).__init__(a,c)

        def __init__(self, some_condition):
            super(Y, self).__init__()
            if some_condition:
               self.b += 1  # or set it to whatever else you want
            else:
               self.b = -1

File "C:\Users\Alexandre\Documents\PYTHON\Paper_ICESP\teste.py", line 248, in ABM
cells.myfun(a,c)
File "C:\Users\myname\firstfolder\secondfolder\thirdfolder\myscript.py", line 132, in myfun
c = Y(a,c)
File "C:\Users\myname\firstfolder\secondfolder\thirdfolder\myscript.py", line 154, in init
super(X,self).init(a,c)
TypeError: object.init() takes exactly one argument (the instance to initialize)
I suspect that creating a superclass Y inside daughter class Y is interfering in Y. What do you think?


How can I adjust the query below to show transition time into the next status in SQL?

Question: The pivot query below gathers the time spent by status only. If a status is in NEW for example (sorted in ascending order by customer_update_date - grouped by ticket number), the query will not get the transition time into the next status (as it is truly in the same status until the next update in a different status).
Say for this example is in NEW status from 8/23/16 01:00:00 PM to 8/23/16 02:00:00 PM (1 hour). BUT, from the update sequence where NEW goes to PENDING, the time stamp is 8/23/16 04:00:00 PM, which means it was still in NEW for 2 additional hours.
Is there any way possible the query below can be adjusted to add the transition time from status to status and group that additional time on whatever the status was previously shown? I hope this makes sense. Thank you so much for your time.
<code>WITH t AS (
    select
        ticket_number,
        ISNULL(status,'null') status,
        update_date,
        row_number() OVER (PARTITION BY ticket_number ORDER BY update_date) rn
    from xxx.dbo.report
), s AS (
    SELECT
        t1.ticket_number,
        t1.status,
        t1.update_date,
        t2.update_date prevdate,
        case when t2.status=t1.status then DATEDIFF(s, t2.update_date, t1.update_date) end dif
    FROM t t1
    LEFT JOIN t t2 ON t1.ticket_number=t2.ticket_number AND t1.rn=t2.rn+1
)
SELECT *
FROM (
    SELECT
        ticket_number,
        [status],
        cast(dateadd(s,sum(dif),0) as time(0)) [time]
    FROM s
    GROUP BY ticket_number,status )  src
PIVOT
(
  min([time])
  for [status] in ([Closed], [Complete], [New], [Waiting-1], [Waiting-2], [Waiting-3], [StopTime], [Research-1], [Research-2], [Resolved], [Special Request], [Opened Request], [null])
) piv
</code>
Comment: please show some sample data and expected result and explain along with it
Comment: even better, provide code that generates the sample data so all we have to do is change the query.  Also, it looks the PIVOT is not essential to the question, consider removing it and simplifying the request.
Answer: Seems like you want the minimum row for each status, then to calculate the time between those two rows.  This code below will do that, along with some sample data.
<code>--create table dbo.report (ticket_number int, status varchar(50), update_date datetime)
--delete from report
--insert into report values (1, 'New', '20160823 13:00')
--insert into report values (1, 'New', '20160823 14:00')
--insert into report values (1, 'Pending', '20160823 16:00')

WITH ticketstatus AS
(
    SELECT
        ticket_number,
        ISNULL(status,'null') status,
        update_date,
        ROW_NUMBER() OVER (PARTITION BY ticket_number,status ORDER BY update_date) statusrn  -- will provide us with minimum status rows
        ,ROW_NUMBER() OVER (PARTITION BY ticket_number ORDER BY update_date) ticketrn  -- will tell us which
    FROM
        dbo.report
),
-- get the first row for each status change
minticketstatus AS
(
    SELECT * FROM ticketstatus where statusrn = 1
)
, statuschange as
 (
    SELECT
        t1.ticket_number
        ,t1.status Status
        ,t1.update_date t1updatedate
        ,t2.status 'StatusChangedTo'
        ,t2.update_date 'StatusChangedDate'
        ,datediff(hh, t1.update_date, t2.update_date) 'time (in hours)'
    FROM minticketstatus t1
    LEFT JOIN minticketstatus t2 ON t2.ticket_number=t1.ticket_number AND t2.status <> t1.status and t2.update_date > t1.update_date
)
SELECT
*
FROM
    statuschange
</code>


Is it possible to control other physical devices via USB?

Question: I want to control a physical device which is connected to my android phone through USB. Here,physical device means any device (like camera,pc etc...) which can be connected to my android device via USB.I want to control this device from my phone.
Is it possible?
Thanks in Advance
Answer: Yes this is possible in some way. If you are able to control an RS232 to USB converter like the PL2303 (the normal ones that you get in the market) then you will be able to do many things. For this you will need a device that supports USB host, then you can check this PL2303 test project which I already tested and can say that works very good. You can use it as the start point for controlling the USB port. This solution works for RS232 compatible devices which you can easily adapt with some electronics using a micro controller.
Answer: Yes you can control the devices but via OTG cable.
see this link
Comment: Is it possible to control 'any device' which can be  connected to my phone via USB from my phone using this? I want a programmatic solution.
Comment: You mean you need to write a program for each device that can be controled?
Comment: M'am you have asked some serious question without the research. Its a research topic that leads you into the augmented reality and many more ways.
refer following links

http://stackoverflow.com/questions/2908530/external-usb-devices-to-android-phones

http://www.engadget.com/2011/04/10/sparkfun-intros-ioio-for-android-a-hack-free-breakout-box-to-ge/
Answer: run adb_win from here http://smart-dog.appspot.com/download/ADB_WIN.zip
and connect to it with tightvnc viewer.
it worked for me
Answer: <code>Yes i have this question as well i tried to find the solution,Yes it is possible
 do the following...
   1 - Android USB drivers must be installed on your desktop
   2 - USB Debugging must be enabled on your Android device
   3 - Your firewall should authorize adb.exe and BirdieSync.exe
   4 - Use the latest version of BirdieSync
   If u need more information visit this site it will help you...

   http://www.birdiesync.com/my-android-device-cannot-connect-over-usb
</code>
Comment: Is it possible to 'control any device' which can be connected to my phone via USB from my phone using this? I want a programmatic solution


How to distinguish whether the image is coming from gallery or camera in android?

Question: I am making an app in which i can pick an image from gallery or i can take image from camera and i am moving to next activity with the selected image.There I want to distinguish whether the image is coming from gallery or camera.I am not getting any idea how to do it.I am providing my code.Please help me how to do this.
My first activity is
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

  public class LauncherActivity extends Activity
   {
 private static final int CAMERA_REQUEST = 1888;
 private static int RESULT_LOAD_IMAGE = 1;
 ImageButton camera;
 ImageButton gallery;
 ImageView gallery_image;

 protected void onCreate(Bundle paramBundle)
 {
 super.onCreate(paramBundle);
 setContentView(R.layout.launcher);
 gallery = (ImageButton)findViewById(R.id.select_photo);
 camera = (ImageButton)findViewById(R.id.take_photo);

   gallery.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
            Intent gallery_intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(gallery_intent, RESULT_LOAD_IMAGE);
     }
    });

     camera.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
    }
});

  }
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)     {

      Uri selectedImage = data.getData();

      String[] filePathColumn = { MediaStore.Images.Media.DATA };

      Cursor cursor = getContentResolver().query(selectedImage,
              filePathColumn, null, null, null);
      cursor.moveToFirst();

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      String picturePath = cursor.getString(columnIndex);
      cursor.close();
      Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
      intent.putExtra("path", picturePath);
      startActivity(intent);

    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK && data!=null) {

      Bitmap photo_from_camera = (Bitmap) data.getExtras().get("data");

      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      photo_from_camera.compress(Bitmap.CompressFormat.PNG, 100, stream);
      byte[] byteArray = stream.toByteArray();
      Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
      intent.putExtra("image", byteArray);
      startActivity(intent);

    }
  }
  }

and my second activity is
   public class MainActivity extends Activity
   {
   Bitmap scaled;
 protected void onCreate(Bundle paramBundle)
  {
  super.onCreate(paramBundle);
  setContentView(R.layout.activity_main);

   if(//condition to The image coming from gallery)
   {
   Bundle extras=getIntent().getExtras();
   String picturePath=extras.getString("path");
  scaled=BitmapFactory.decodeFile(picturePath);
  //the things i have to do with bitmap that i know
   }
  if(//Condition to the image coming from camera)
  {
    Bundle extras = getIntent().getExtras();
   byte[] byteArray = extras.getByteArray("image");
   Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
  scaled = Bitmap.createScaledBitmap(bitmap, width, height, true);
  //the things i have to do with bitmap that i know
  }
  }
   }

Here I am not getting the code to write the conditions in the if statement.please help me.Thanks in advance.
Answer: startActivityForResult(cameraIntent, CAMERA_REQUEST);
startActivityForResult(gallery_intent, RESULT_LOAD_IMAGE);

regarding to your request code you can differentiate image is coming from gallery or camera
 boolean gallery;

     if(requestCode == CAMERA_REQUEST){
        //then image from camera

gallery=true;
    galleryIntent intent = new Intent(LauncherActivity.this, MainActivity.class);
          intent.putExtra("path", picturePath);
         intent.putExtra("isfrom", gallery);
    startActivity(intent);
        }
        if(requestCode == RESULT_LOAD_IMAGE){
    galleryIntent intent = new Intent(LauncherActivity.this, MainActivity.class);
          intent.putExtra("path", picturePath);
         intent.putExtra("isfrom", gallery);
    startActivity(intent);
        //then image from gallery
        }

in second activity you can get boolean from intent.if it is true image from gallery
Comment: it is used to distinguish in the same activity.I am moving to second activity with the selected image.In the second activity,I want to distinguish.This wont work there.
Comment: you can make a flag in first activity onActivityResult(),and use it in second activity
Comment: can u tell me in detail plz.
Comment: Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
      intent.putExtra("path", picturePath);
     intent.putExtra("isfrom", gallery); startActivity(intent);
Comment: @rajahsekar he won't understand because he doesn't know how to program (atleast in android). You answer is good, let it be.
Comment: there is a string for gallery image called path and for camera image called image.I think this is enough.no need of flag if i am not wrong.I do not know how to distinguish with these two strings in the second activity in the if statement.
Comment: Thanks yaar.It was helpful for me.
Answer: // try this way,hope this will help you...

launcher.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/select_photo"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Gallery"/>

        <Button
            android:id="@+id/take_photo"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Camera"/>
    </LinearLayout>
</LinearLayout>

activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"/>
</LinearLayout>

LauncherActivity.java
public class LauncherActivity extends Activity {

    private static final int CAMERA_REQUEST = 1;
    private static final int RESULT_LOAD_IMAGE = 2;
    Button camera;
    Button gallery;
    ImageView imageView;
    private String imgPath;

    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.launcher);
        gallery = (Button) findViewById(R.id.select_photo);
        camera = (Button) findViewById(R.id.take_photo);
        imageView = (ImageView) findViewById(R.id.imageView);

        gallery.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, ""), RESULT_LOAD_IMAGE);
            }
        });

        camera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                startActivityForResult(intent, CAMERA_REQUEST);
            }
        });

    }

    public Uri setImageUri() {
        // Store image in dcim
        File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
        Uri imgUri = Uri.fromFile(file);
        this.imgPath = file.getAbsolutePath();
        return imgUri;
    }

    public String getImagePath() {
        return imgPath;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == RESULT_LOAD_IMAGE) {
                imageView.setImageBitmap(decodeFile(getAbsolutePath(data.getData())));
                Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
                intent.putExtra("path", getAbsolutePath(data.getData()));
                intent.putExtra("from", "Gallery");
                startActivity(intent);
            } else if (requestCode == CAMERA_REQUEST) {
                imageView.setImageBitmap(decodeFile(getImagePath()));
                Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
                intent.putExtra("path", getImagePath());
                intent.putExtra("from", "Camera");
                startActivity(intent);
            }
        }

    }

    public String getAbsolutePath(Uri uri) {
        if(Build.VERSION.SDK_INT >= 19){
            String id = uri.getLastPathSegment().split(":")[1];
            final String[] imageColumns = {MediaStore.Images.Media.DATA };
            final String imageOrderBy = null;
            Uri tempUri = getUri();
            Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
                    MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
            if (imageCursor.moveToFirst()) {
                return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }else{
                return null;
            }
        }else{
            String[] projection = { MediaStore.MediaColumns.DATA };
            Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }

    }

    private Uri getUri() {
        String state = Environment.getExternalStorageState();
        if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
            return MediaStore.Images.Media.INTERNAL_CONTENT_URI;

        return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    }

    public Bitmap decodeFile(String path) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 1024;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeFile(path, o2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
}

MainActivity.java
public class MainActivity extends Activity {

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
        Toast.makeText(this,getIntent().getStringExtra("from"),Toast.LENGTH_SHORT)
        .show();
        imageView.setImageBitmap(decodeFile(getIntent().getStringExtra("path")));

    }

    public Bitmap decodeFile(String path) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 1024;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeFile(path, o2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;

    }
}

Note : please not forget this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


Quais são as meta tags que não devem faltar no cabeçalho de um bom site?

Question: Quais são as meta tags que não devem faltar no cabeçalho de um bom site e por que?
Obs.: Não estou perguntando o que é são meta tags, e sim quais são.
A questão O que são meta tags de  e para que serve cada uma? já explica o que são meta tags.
Comment: Não estou perguntando o que são, e sim quais são as recomendadas para adicionar em meus sites.
Comment: Guilherme, veja que a outra pergunta tinha um título semelhante a sua pergunta, mas ela foi editada porque a comunidade  havia fechado por ser "principalmente baseadas em opiniões."
Answer: Title
Não é exatamente uma meta tag, mas depois do conteúdo da página é a melhor coisa em termos de SEO. Não use mais do que 70 caracteres. É desnecessário especificar o nome do seu site aqui, use somente um texto fortemente relacionado com o conteúdo da página. Capriche aqui!
<title>O título vem aqui</title>

Meta description
A descrição da página. Útil para o SEO. Máximo de 160 caracteres.
<meta name="description" content="descrição aqui">

Meta robots
Indica aos buscadores certos procedimentos em relação à página. Valores:

index: a página deve ser indexada (default)
noindex: a página não deve ser indexada
follow: os links da página devem ser seguidos (default)
nofollow: os links da página não devem ser seguidos
none: o mesmo que noindex, nofollow
noarchive: o buscador não deve salvar a página em cache
noodp: o buscador não deve utilizar a descrição de certos diretórios de links (ex.: dmoz.org)
nosnippet: faz com que o Google exiba somente o link para a sua página na hora da busca, deixando de exibir a descrição, etc. (não recomendado)

OBS.: valores default não precisam ser especificados, ou seja, é desnecessário usar index, follow
OBS.: eu particularmente recomendo utilizar noarchive, para evitar que o Google salve sua página, porque se ele salvar uma determinada página e depois você se arrepender, é meio difícil a remoção. Algumas pessoas gostam que o Google salve em cache justamente para o caso de o site sair do ar temporariamente, assim as pessoas ainda conseguem visualizar o conteúdo da página.

Meta googlebot
O mesmo que robots, mas é específico para o Googlebot.
<meta name="googlebot" content="noindex">

Meta keywords
As palavras-chaves relacionadas com o conteúdo da página. O Google não utiliza mais essa meta tag, mas outros buscadores (como Bing, Baidu) podem utilizar.
<meta name="keywords" content="palavra1, palavra 2, outra aqui">

Meta author
O nome da pessoa que criou o conteúdo da página. Não ajuda no SEO, mas o Facebook por exemplo mostra o autor especificado nessa meta tag quando você compartilha um link.
<meta name="author" content="João Silva">

Meta google
Indica ao Google que sua página não deve ser traduzida pelo Google Translate. Isso faz com que o Google deixe de exibir o link "Traduzir esta página" ao lado do link do seu site, na página de busca.
<meta name="google" content="notranslate">

Answer: As meta tags mais básicas e que não podem deixar de existir são:
<meta name="description" content="Descrição sobre o conteúdoda página..." />
<meta name="keywords" content="palavras, chaves, sobre, seu, conteudo" />

Após estas, viriam as tags dos Robots, que configuram e guiam os robos de indexação dos sites de busca, mas estas não estão mais sendo tanto utilizadas pois os mecanismos do google já fazem o trabalho automaticamente:
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
//Não indexar e não seguir os links

<META NAME="ROBOTS" CONTENT="INDEX, NOFOLLOW">
//Indexar, mas não seguir os links

<META NAME="ROBOTS" CONTENT="NOINDEX, FOLLOW">
//Não indexar, mas seguir os links

<META NAME="ROBOTS" CONTENT="INDEX, FOLLOW">
//Indexar e seguir os links

Caso necessite, também tem alguns meta tags que controlam a navegação como por exemplo:
<meta http-equiv="refresh" content="30">
//Tempo para atualizar a pagina

<meta http-equiv="refresh" content="x_seconds; url=http://www.yourhost.com/pagetosendto.html">
//Redirecionar a pagina após x segundos

E por último mas não menos importante, as meta tags que as redes sociais utilizam pra captar informação da página quando o link é compartilhado:
//Facebook
<meta property="og:title" content="..."/>
<meta property="og:description" content="..."/>
<meta property="og:image" content="http://sua_url.com/foto-facebook.jpg"/>

//Twitter
<meta name="twitter:title" content="...">
<meta name="twitter:description" content="...">
<meta name="twitter:image" content="http://sua_url.com/foto-twitter.jpg">

Espero que tenha ajudado.
Caso fique com alguma dúvida ou queira ver mais meta tags este post do acquire é bem completo sobre o assunto.
Comment: MetaTag **keywords** já era, mano.
Comment: @GuilhermeJSantos
http://googlewebmastercentral.blogspot.com.br/2009/09/google-does-not-use-keywords-meta-tag.html e http://www.thesitewizard.com/archive/metatags.shtml
Comment: A keywords não é mais usada?
Comment: Sempre que pesquiso sobre isso vejo indicações para usar, e eu sempre uso.


Adding extra field on Main menu, similar to Amazon.com

Question: I'm building a new website on Drupal 7 and my client wants a menu that in addition to the menu items he be able to add html content, very similar to Amazon.com menu. Should I create a content type for my menu instead?
Answer: Your best option is to use the TB mega menu module add your html content to a block and add the block to the menu

TB Mega Menu is developed following Drupal standards and best
  practices. Along with those must-have functions of a mega menu:
  display not just menu items but image, slideshow, video, article and
  customize any of them upon your favour...
Answer: This module will help a lot for your requirements https://www.drupal.org/project/menu_descriptions


Can I use memchr safely with an internal UTF-8 char * returned from an NSString?

Question: I'd like to use memchr instead of strlen to find the length of a C string potentially used as the backing string of an NSString. Is this safe to do, or do I risk reading memory that I don't own, causing a crash? Let's assume that the NSString will not be released before I'm done with the internal buffer.
Comment: I see no reason why it may be unsafe as long as the pointer remains valid. But the hard question is that you can't easily tell when the pointer is freed unless you just get it from `NSString`, then you should just call `length` on it
Comment: Related: http://stackoverflow.com/questions/29473872/lifespan-of-nsstring-cstringusingencoding-return-value.
Comment: Why aren't you calling `-length` on the string directly?
Answer: memchr(s, 0, XXX) and strlen(s) should pretty much behave identically, save for mechr()'s ability to terminate after XXX bytes.   But strnlen() can do that, too.
And that behavior is probably exactly what you don't want.
Neither function accounts for any kind of unicode encoding.  Thus, the returned length will be the length-in-bytes and not the # of characters.
Use -length on the NSString if you want the string length.   Beyond that, what are you trying to do?
Comment: @meisel Sounds like what you _really_ want to be doing is accessing this via `NSMutableData` as a bag of bytes, perform the modifications that you want, then create real strings out of that...
Comment: I'd *highly* recommend you pull the data out in the encoding you need, process it as you see fit, and then put it into a new `NSString`.    I also suspect that the *I don't need to think about how UTF-8 works* will come back to haunt you, but at least if you control the encoding in/out, you'll have a known quantity.
Comment: This is just for a UTF-8 string. I've edited the question to reflect that.
Comment: @meisel `strlen()` will give you the byte length, not the character length.  So will `memchr()`.  So, again, very unlikely that this is really what you want.  If you want to treat the string as a generic buffer of bytes convert it to an `NSData` or copy the bytes out into a separate buffer in isolation from the string.
Comment: Actually, this is exactly what I want. I eventually, this string will be part of a larger string that is then used to create an NSString. My strategy is, take buffers out of Objective-C objects, do processing on them, recombine as an NSString for users of the API. It's very fast and doesn't need to think about how UTF-8 works, except that it's null-terminated.
Comment: @bbum my main concern is that I'll be accessing memory that I don't own. If you can address that, I'll accept this answer.
Comment: @meisel If you call `-UTF8String`, the returned buffer is owned by the string.  As long as the string isn't deallocated (or mutated, in case of mutable string), then that buffer pointer will remain valid.   If the string's lifespan is unknown, then you either need to hold a hard reference to it or use one of the `getBytes....` variants to copy the data.
Comment: @bbum the problem with a function like this is that it could be vectorized, so it may try to access memory past the end of the string. The question is, are there always at least, say, 32 bytes that we own after the end of the string? E.g., maybe NSString has 4+ ivars after the UTF8String pointer.
Comment: @meisel There is no way to know or guarantee any such allocation exists unless you also allocate the backing store for the `NSString` (which you can do).   If you have strict buffer requirements of that nature, you're going to have to either copy the contents of the string or control the creation in the first place.
Comment: @bbum how can you be so sure? Maybe the way things are laid out, we always have 32+ bytes after the end of any object, e.g. an NSString
Comment: @meisel I can be **absolutely sure** that there is no guarantee that such a layout will always be present because (a) there is no documented claim in the API that said behavior exists and (b) because I have the source.
Comment: @bbum can you link the source?
Comment: @meisel Much of NSString is implemented in CoreFoundation, but not all.  I believe that is on the Apple open source site.  For the rest, you'd need to join Apple (as I did 13 years ago).

But, again, I can guarantee that there isn't a 32 byte pad on these buffers;  it'd waste too much memory. Especially with constant strings (NSCFConstantString).  For non-constant strings, the buffers are *typically* going to be padded to malloc-good-size.  For a subset of strings, there'll be no buffer at all because they are implemented as *tagged pointers*.
Comment: My point is not that there's a 32-byte pad on the buffers, it's that the way the memory may be laid out, the objects may always have more than 32 bytes in between them and the end of the memory that my app owns. It just depends how Apple does things.
Comment: @meisel Again, **unless the API contract explicitly makes such a claim**, you cannot rely on it, *even if you have the source* (because it might change from release to release).  And, furthermore, I can-- you can, with a very simple bit of code-- guarantee that it is not always the case.


How to access private members of a class from it's private constructor

Question: I have following class and here i'm trying to access private members of the class from private constructor.
class House {
private:
    int len;
    int wid;
    House()
    {
    }
public:
    ~House()
    {
        std::cout << "destructor call" << std::endl;
    }
    static std::shared_ptr<House> house;
    static auto getHouse(const int length, const int width);

    void setlen(int lenth) { len = lenth; }
    void setwid(int width) { wid = width; }
    int getlen() { return len; }
    int getwid() { return wid; }
};

auto House::getHouse(const int length, const int width)
 {
    House::house = std::make_shared<House>();
    if ((House::house->getlen()==length) && (House::house->getwid()== width))
    {
        return House::house;
    }
    else
    {
        House::house->setlen(length);
        House::house->setwid(width);

        return House::house;
    }
}

I get the following error message

Severity  Code    Description Project File    Line    Suppression State
  Error   C2248   'House::House': cannot access private member declared in class 'House'  TestC++ c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory  1770
Comment: May be [the error messages from this MCVE](http://coliru.stacked-crooked.com/a/dc4f541198090f91) are clearer.
Comment: The majority of the code you've posted is not relevant to the actual problem. Why do you think `make_shared` should be able to call a private constructor?
Comment: @πάνταῥεῖ Clearly clarity is in the eye of the beholder!
Comment: See https://stackoverflow.com/q/8147027/241631
Comment: @Praetorian here i'm trying to construct the object withing  a class and use outside the class using smart pointers problem is clear with shared_ptr here.
Comment: @πάνταῥεῖ,@TypeIA thanks really helpful.
Answer: Because House does not have a public constructor, code outside the class is not allowed to construct a House. But you're trying to do exactly that, here:
House::house = std::make_shared<House>();

The implementation of std::make_shared invokes new to construct a new House, but std::make_shared cannot access the private constructor of House. To fix it, you need to construct the House yourself:
House::house.reset(new House);


Early Access to Async Action Results in ASP.NET MVC

Question: When we use async action in MVC like below example, post model data is available earlier than 10 seconds in view(here in 1 second) ? I confused, How data available in 1 seccond While fetching data take 10 seconds ???
for example:
    public async Task<ActionResult> GetPosts()
    {

        // ...
        IPost posts = await PostService.GetPosts();// assume this take 10 seconds
        // ...

        return View(model: posts);//BUT we return in 1 second! How posts model available in view for show to the user earlier than 10 seconds?
    }

Answer: You don't get to the return statement in 1 second. The method returns a Task<ActionResult> as soon as it reaches the first await expression which hasn't already completed. That task will not be completed (so you can't get its result) until your async method does reach the return statement.
But when the first thing you're awaiting completes, your async method will resume, continuing from where it left off until the next await, when it will "go to sleep" again (but without blocking a thread) until the awaitable has completed, etc.
That's the nature of async. You just need to distinguish between "the async method has returned a task" (which happens quickly) and "the async method has completed" (which often doesn't happen quickly).
It's hard to describe async thoroughly in just a few paragraphs - I suggest you read a good book, watch a video, or read a good tutorial. MSDN is a good starting point.
Comment: @user197508: It returns to the caller - but ASP.NET won't give a result to the *client* until the task has completed. The difference is that while it's waiting for data, it's not tying up a thread - so if you have 10,000 requests executing concurrently, you can still get away with very few threads.
Comment: you say "but without blocking a thread", so request not blocked current thread and we reach to return in 1 second, thats true? if your answer is no, SO what is difference between Async action and not Async action?
Comment: @Jun: So Async action benefit is when we use project in production with many users and many request in seccond which caused not blocked users when another user has a request? and we don't touch Async action benefits in development? thats true?
Comment: @user197508: It's not a matter of blocking users - it's a matter of how many threads are required at a time. But no, you would use async in development as well - it would be awful to try to change from sync to async just before deploying to production.
Comment: @Jun: Very Thanks for your attention.Asynchronous action methods are useful when an action must perform "Several Independent" long running operations, and we cannot use Async benefits where there are only "One" long running operation, like my question example. thats true?
Comment: @user197508: No, not at all. The long-running operation on the database doesn't need a thread running on your ASP.NET server, does it? So there could be thousands of database asynchronous operations running at the same time (one per request) but you wouldn't want one thread for each of those.
Comment: @Jun: we must use Async Only in non-CPU bound requests, acording to [here](http://msdn.microsoft.com/en-us/library/ee728598(v=vs.100).aspx), so benefit in using Async is this we don't block cpu for another requests, and we create a new thread and send non-CPU bound request for continue to this new thread, thats true?
Comment: @user197508: I'm not quite sure why you keep calling me "Jun", but no, using async in CPU-bound tasks is generally not a good idea... although there are hybrid workloads where it can make sense.
Comment: Excuse me,Excuse me sir.

Now problem solved for me.


To prove that $B\subset A\rightarrow A=A\cup B$ is it necessary to consider the cases $A\cup B=\emptyset$ and $A\cup B\neq \emptyset$?

Question: For what I know, to prove $B\subset A\rightarrow A=A\cup B$ it suffices to prove that $A\subset (A\cup B)$ and $(A\cup B)\subset A$.
Prove that $A\subset (A\cup B)$ is trivial, because $A\cup B=\{x:x\in A\vee x\in B\}$.
My teacher in proving that $(A\cup B)\subset A$ separated the proof into two parts: $A\cup B=\emptyset$ and $A\cup B\neq \emptyset$. But I didn't understand why the need to separate this proof in two cases since
$x\in (A\cup B)\to x\in A \vee x\in B$
We know, by hypothesis, that $B\subset A$, so we can conclude that $(x\in A\vee x\in B)\leftrightarrow(x\in A)$ is tautology(using truth table). So saying $x\in A\vee x\in B$ is equivalent to saying $x\in A$ which implies
$x\in (A\cup B)\to x\in A \vee x\in B\equiv x\in A\Rightarrow (A\cup B)\subset A$ (note: the implication $p\to q$ is true whenever $p$ is false).
In my opinion in the proof that $(A\cup B)\subset A$ there was no need to consider two cases, but as my teacher has great knowledge about set theory I feel that I am making a mistake by not considering the two cases. That is why I ask for help in this doubt.
Obs.: If I used some logical symbol wrongly let me know, please, since I still know few things about propositional logic.
Comment: I see no flaw in your reasoning.  Do keep in mind that teachers sometimes do unnecessary things in class to emphasize a point or a technique.
Comment: @ZachTeitler Later I'll ask my teacher why he did it. He was separating in cases all the problems similar to that. Because of this I ended up getting confused.
Comment: You're right. No need for dividing into empty/nonempty cases. Perhaps your teacher was just illustrating some other point, maybe about vacuous truths?
Comment: The two cases to use are x in A and x in B.
Answer: You are right, and I see no errors. We can also observe that  $A\subset B\iff \forall x\;(x\in B\implies x\in A).$ Therefore if $B\subset A$ then for all $x$ we have  $$x\in A\cup B)\implies  (x\in A\lor x\in B)\implies$$ $$\implies (x\in A\lor x\in A)\implies(x\in A)\implies$$ $$\implies(x\in A \lor x\in B)\implies(x\in A\cup B).$$
From this we infer that for all $x$ we have $x\in A\cup B\iff x\in A$.
This is in my style, which is almost never brief.
Answer: The reason you feel there is no reason to consider the two cases is because you feel that one case is trivial.   Indeed the conclusion from those premises is a vacuuously truth:
$$\begin{array}{lrcl}\because&(B\subseteq A)~,~ (A\cup B=\emptyset) &\vdash& \forall x ~\big((x\in A\cup B) \to (x\in A)\big)\\\hline\therefore&(B\subseteq A)~,~ (A\cup B=\emptyset)&\vdash&(A\cup B\subseteq A)\end{array}$$

However, not all proofs will have a trivial result from the empty case; for instance any proof involving an existance claim may well lead to an exception.   Your teacher just wants you to get into the habit of verifying a proof does not fail in the empty case.
Comment: I don't think this is correct: "The reason you feel there is no reason to consider the two cases is because you feel that one case is trivial." The OP does not omit one case from their argument, claiming it to be trivial; instead they provide a single argument which prove the statement regardless of whether $A\cup B=\emptyset$.
Comment: if $A\cup B=\varnothing$ and $B \subset A$ does it mean $A=\{\varnothing\}$??
Comment: No, but $A\cup B=\varnothing$ and $B\subseteq A$ does mean $A=\varnothing$.
Comment: @Stu. $\{\emptyset\}$ is $not$ the empty set. It has one member:  $\emptyset$ is its member.


Merge node stems of two voices in denemo

Question: I have this minimum working example generated with denemo. As you may see, there are two staff with two voices each.

Now I want to merge the note stems in each staff and I don't find how to do it. The result should look like this:

My denemo file:
<code><?xml version="1.0" encoding="UTF-8"?>
<score xmlns="http://denemo.org/xmlns/Denemo" version="8">
  <thumbnail>
    <first-staff>1</first-staff>
    <last-staff>3</last-staff>
    <first-measure>1</first-measure>
    <last-measure>3</last-measure>
    <first-obj>0</first-obj>
    <last-obj>2147483647</last-obj>
  </thumbnail>
  <lilycontrol>
    <papersize>a4</papersize>
    <lilyversion>2.22</lilyversion>
    <fontsize>18</fontsize>
    <orientation>1</orientation>
    <total-edit-time>8421</total-edit-time>
    <score-directives>
      <directive>
        <tag>ScoreIndent</tag>
        <prefix>\layout {indent = 0.0}
</prefix>
        <display>indent=0.0</display>
        <data>0.0</data>
        <override>4</override>
      </directive>
    </score-directives>
  </lilycontrol>
  <movement-number>1</movement-number>
  <movement>
    <edit-info>
      <staffno>1</staffno>
      <measureno>1</measureno>
      <cursorposition>1</cursorposition>
      <tonalcenter>0</tonalcenter>
      <zoom>100</zoom>
      <system-height>97</system-height>
      <page-zoom>50</page-zoom>
      <page-system-height>25</page-system-height>
      <page-width>1846</page-width>
      <page-height>1016</page-height>
      <measure-width>150</measure-width>
    </edit-info>
    <score-info>
      <tempo>
        <duration>
          <numerator>1</numerator>
          <denominator>4</denominator>
        </duration>
        <bpm>120</bpm>
      </tempo>
    </score-info>
    <staves>
      <staff id="id0"></staff>
      <staff id="id1"></staff>
    </staves>
    <voices>
      <voice id="id2">
        <voice-info>
          <voice-name>Part 1</voice-name>
          <first-measure-number>1</first-measure-number>
        </voice-info>
        <initial-voice-params>
          <staff-ref staff="id0"></staff-ref>
          <clef name="treble"></clef>
          <key-signature>
            <modal-key-signature note-name="D" mode="minor"></modal-key-signature>
          </key-signature>
          <time-signature>
            <simple-time-signature>
              <numerator>3</numerator>
              <denominator>4</denominator>
            </simple-time-signature>
          </time-signature>
        </initial-voice-params>
        <voice-props>
          <number-of-lines>5</number-of-lines>
          <voice-control>1</voice-control>
          <transpose>0</transpose>
          <instrument></instrument>
          <device-port>NONE</device-port>
          <volume>127</volume>
          <override_volume>0</override_volume>
          <mute>0</mute>
          <midi_prognum>0</midi_prognum>
          <midi_channel>0</midi_channel>
          <hasfigures>0</hasfigures>
          <hasfakechords>0</hasfakechords>
          <verses>
            <verse>Nimm al --  les von mir, was mich fern -- hält von dir. Gib al -- les mir, was mich hin -- führt zu dir. Le -- ben -- di -- ger Gott, nimm mich mir und gib mich ganz __ zu ei -- gen dir. Nimm</verse>
          </verses>
        </voice-props>
        <measures>
          <measure>
            <chord show="true" id="id3">
              <duration base="quarter"></duration>
              <notes>
                <note id="id4">
                  <middle-c-offset>3</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id5">
              <duration base="quarter"></duration>
              <notes>
                <note id="id6">
                  <middle-c-offset>3</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id7">
              <duration base="quarter"></duration>
              <notes>
                <note id="id8">
                  <middle-c-offset>4</middle-c-offset>
                </note>
              </notes>
            </chord>
          </measure>
          <measure>
            <chord show="true" id="id9">
              <duration base="half"></duration>
              <notes>
                <note id="id10">
                  <middle-c-offset>5</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id11">
              <duration base="eighth"></duration>
              <directives>
                <directive>
                  <tag>Beam</tag>
                  <postfix>[</postfix>
                  <display>[</display>
                  <tx>6</tx>
                </directive>
              </directives>
              <notes>
                <note id="id12">
                  <middle-c-offset>5</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id13">
              <duration base="eighth"></duration>
              <directives>
                <directive>
                  <tag>Beam</tag>
                  <postfix>]</postfix>
                  <display>]</display>
                  <tx>6</tx>
                </directive>
              </directives>
              <notes>
                <note id="id14">
                  <middle-c-offset>4</middle-c-offset>
                </note>
              </notes>
            </chord>
          </measure>
        </measures>
      </voice>
      <voice id="id15">
        <voice-info>
          <voice-name>Part 1</voice-name>
          <first-measure-number>1</first-measure-number>
        </voice-info>
        <initial-voice-params>
          <staff-ref staff="id0"></staff-ref>
          <clef name="treble"></clef>
          <key-signature>
            <modal-key-signature note-name="D" mode="minor"></modal-key-signature>
          </key-signature>
          <time-signature>
            <simple-time-signature>
              <numerator>3</numerator>
              <denominator>4</denominator>
            </simple-time-signature>
          </time-signature>
        </initial-voice-params>
        <voice-props>
          <number-of-lines>5</number-of-lines>
          <voice-control>3</voice-control>
          <transpose>0</transpose>
          <instrument></instrument>
          <device-port>NONE</device-port>
          <volume>127</volume>
          <override_volume>0</override_volume>
          <mute>0</mute>
          <midi_prognum>0</midi_prognum>
          <midi_channel>0</midi_channel>
          <hasfigures>0</hasfigures>
          <hasfakechords>0</hasfakechords>
        </voice-props>
        <measures>
          <measure>
            <chord show="true" id="id16">
              <duration base="quarter"></duration>
              <notes>
                <note id="id17">
                  <middle-c-offset>1</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id18">
              <duration base="quarter"></duration>
              <notes>
                <note id="id19">
                  <middle-c-offset>1</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id20">
              <duration base="quarter"></duration>
              <notes>
                <note id="id21">
                  <middle-c-offset>2</middle-c-offset>
                </note>
              </notes>
            </chord>
          </measure>
          <measure>
            <chord show="true" id="id22">
              <duration base="half"></duration>
              <notes>
                <note id="id23">
                  <middle-c-offset>3</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id24">
              <duration base="eighth"></duration>
              <directives>
                <directive>
                  <tag>Beam</tag>
                  <postfix>[</postfix>
                  <display>[</display>
                  <tx>6</tx>
                </directive>
              </directives>
              <notes>
                <note id="id25">
                  <middle-c-offset>2</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id26">
              <duration base="eighth"></duration>
              <directives>
                <directive>
                  <tag>Beam</tag>
                  <postfix>]</postfix>
                  <display>]</display>
                  <tx>6</tx>
                </directive>
              </directives>
              <notes>
                <note id="id27">
                  <middle-c-offset>2</middle-c-offset>
                </note>
              </notes>
            </chord>
          </measure>
        </measures>
      </voice>
      <voice id="id28">
        <voice-info>
          <voice-name>unnamed</voice-name>
          <first-measure-number>1</first-measure-number>
        </voice-info>
        <initial-voice-params>
          <staff-ref staff="id1"></staff-ref>
          <clef name="bass"></clef>
          <key-signature>
            <modal-key-signature note-name="D" mode="minor"></modal-key-signature>
          </key-signature>
          <time-signature>
            <simple-time-signature>
              <numerator>3</numerator>
              <denominator>4</denominator>
            </simple-time-signature>
          </time-signature>
        </initial-voice-params>
        <voice-props>
          <number-of-lines>5</number-of-lines>
          <voice-control>1</voice-control>
          <transpose>0</transpose>
          <instrument></instrument>
          <device-port>NONE</device-port>
          <volume>127</volume>
          <override_volume>0</override_volume>
          <mute>0</mute>
          <midi_prognum>0</midi_prognum>
          <midi_channel>1</midi_channel>
          <hasfigures>0</hasfigures>
          <hasfakechords>0</hasfakechords>
          <staff-directives>
            <directive>
              <tag>InstrumentName</tag>
              <prefix>instrumentName = \markup {  \with-url #'"scheme:(d-GoToPosition 1 2 1 1)(let ((choice (d-PopupMenu (list (cons (_ \"Change Name\") d-InstrumentName)   (cons (_ \"Change Indent\") d-ScoreIndent)))))
                            (if choice (choice)))    " "" }</prefix>
              <override>22</override>
            </directive>
          </staff-directives>
          <voice-directives>
            <directive>
              <tag>InitialVoice</tag>
              <postfix>\voiceFour</postfix>
              <display>Voice Four</display>
              <override>4</override>
            </directive>
          </voice-directives>
        </voice-props>
        <measures>
          <measure>
            <chord show="true" id="id29">
              <duration base="quarter"></duration>
              <notes>
                <note id="id30">
                  <middle-c-offset>-2</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id31">
              <duration base="quarter"></duration>
              <notes>
                <note id="id32">
                  <middle-c-offset>-2</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id33">
              <duration base="quarter"></duration>
              <notes>
                <note id="id34">
                  <middle-c-offset>0</middle-c-offset>
                </note>
              </notes>
            </chord>
          </measure>
          <measure>
            <chord show="true" id="id35">
              <duration base="half"></duration>
              <notes>
                <note id="id36">
                  <middle-c-offset>0</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id37">
              <duration base="eighth"></duration>
              <notes>
                <note id="id38">
                  <middle-c-offset>0</middle-c-offset>
                  <accidental name="sharp" show="true"></accidental>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id39">
              <duration base="eighth"></duration>
              <notes>
                <note id="id40">
                  <middle-c-offset>0</middle-c-offset>
                  <accidental name="sharp" show="false"></accidental>
                </note>
              </notes>
            </chord>
          </measure>
        </measures>
      </voice>
      <voice id="id41">
        <voice-info>
          <voice-name>unnamed</voice-name>
          <first-measure-number>1</first-measure-number>
        </voice-info>
        <initial-voice-params>
          <staff-ref staff="id1"></staff-ref>
          <clef name="bass"></clef>
          <key-signature>
            <modal-key-signature note-name="D" mode="minor"></modal-key-signature>
          </key-signature>
          <time-signature>
            <simple-time-signature>
              <numerator>3</numerator>
              <denominator>4</denominator>
            </simple-time-signature>
          </time-signature>
        </initial-voice-params>
        <voice-props>
          <number-of-lines>5</number-of-lines>
          <voice-control>3</voice-control>
          <transpose>0</transpose>
          <instrument></instrument>
          <device-port>NONE</device-port>
          <volume>127</volume>
          <override_volume>0</override_volume>
          <mute>0</mute>
          <midi_prognum>0</midi_prognum>
          <midi_channel>1</midi_channel>
          <hasfigures>0</hasfigures>
          <hasfakechords>0</hasfakechords>
        </voice-props>
        <measures>
          <measure>
            <chord show="true" id="id42">
              <duration base="quarter"></duration>
              <notes>
                <note id="id43">
                  <middle-c-offset>-6</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id44">
              <duration base="quarter"></duration>
              <notes>
                <note id="id45">
                  <middle-c-offset>-6</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id46">
              <duration base="quarter"></duration>
              <notes>
                <note id="id47">
                  <middle-c-offset>-7</middle-c-offset>
                </note>
              </notes>
            </chord>
          </measure>
          <measure>
            <chord show="true" id="id48">
              <duration base="half"></duration>
              <notes>
                <note id="id49">
                  <middle-c-offset>-4</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id50">
              <duration base="eighth"></duration>
              <notes>
                <note id="id51">
                  <middle-c-offset>-9</middle-c-offset>
                </note>
              </notes>
            </chord>
            <chord show="true" id="id52">
              <duration base="eighth"></duration>
              <notes>
                <note id="id53">
                  <middle-c-offset>-9</middle-c-offset>
                </note>
              </notes>
            </chord>
          </measure>
        </measures>
      </voice>
    </voices>
  </movement>
</score>
</code>
I would appreciate any help. Since denemo has no own tag I used LilyPond.
Update 1
The command from rshann worked only if I run it on every voice. The result comes close, but on the seconds staff is still something wrong.
Comment: Wouldn't you prefer to differentiate voices by the stem direction, i.e., soprano up, alto down, tenor up, bass down?
Answer: After a little time of trial and error I set the first and second voice via Object Menu ▶ Staffs/Voices ▶ Initial Voice One and the third and fourth voice as Voice Forth. This is not 100 percent what I wanted, but comes close to it.
Answer: Those aren't really voices, they are chords. A voice

is always notated with stems separated from the other voices,
can have different rhythms than the other voices.

Chords

join notes from the same voice
are written with shared stems.

Therefore, using a single voice on both staves is conceptually correct, not something of a workaround.
Comment: In LilyPond, \partCombine would be ideal for that, but I don't know if Denemo has an interface to it.
Comment: This was only a short MWE. Later on, there will be notes with different rhythms. So it's like a mixing between separate voices and chords.
The full song you can find [here](http://hansruedi-vetsch.blogspot.com/2017/12/taize-gib-mich-ganz-zu-eigen-dir.html).
Answer: Command: No Horizontal Shifts
Turns off horizontal displacement of notes (which avoid collisions between parts)
Location: Object Menu ▶ Staffs/Voices ▶ Voices
Internal Name: ShiftOff
email email@example.com for questions like this!


Unable to access value of HTML Input box written by .html() jQuery function?

Question: I am having trouble accessing the value of an HTML Input element using jQuery, this input element was written initially using .html() function in an earlier function.
THIS IS MY CODE THAT CREATES THE INPUT ELEMENT - NO ISSUES WITH THIS

Now I want to grab the value in #input1 and set a different input box (#new_input) to that value, using this code:

UPDATE: SOLVED, Thanks @Dragon
Comment: are you binding the .change event before or after you create the inputs?
Comment: The change event is coming after the initial function that creates the element
Answer: You're calling change on $("#input1") on $(document).ready but $("#input1") hasn't been created yet. Use jQuery's on() function to bind the change event to it so that once it does exist it will fire.
$(document).on("change", "#input1", function(event){
    var text = $("#input1").val();
    $("#new_input").val(text);
});

Comment: I don't think this will work, since you'll face the same problem -- `#input1` does not exist, so when you call `.on()`, it will do nothing. `.live()` would have worked in this case, but it's deprecated in favor on `.on()`.
Comment: @dragon - You just answered your own question. .live() was deprecated in favor of .on() as of jQuery 1.7, and you can create input1 after the DOM is ready and bind to it just as I've shown in my example.
Comment: @j086901 I understand, but how is your usage of `.on()` different from `.click()` used in the original question? Both would do the same if the handler were being attached after creating the element -- but I believe that's not the case here.
Comment: @dragon - I misunderstood your point. You're right, the use of .on() here needs to be tied to an existing document element. Code updated.
Answer: No, what's going on is that your jQuery code is getting executed when the page loads. At that point, #input1 and #new_input don't exist.
You want something like
$('#containingDiv').on('change', '#input1') function()
{
}

Or else maybe register the $('#input1').change() after the fields are written - maybe as a callback at the end of your $('#model').change?
Comment: Small type in your function but still helped, thanks for the help!
Answer: Like others pointed out, you're binding the event handler to '#input1' element before it's created. Either bind it after it's created, or bind it to the document with '#input1' as the context. Alternatively, you can bind it to any parent element that lives long enough to see the complete cycle of binding the handler and invoking it.
$(document).ready(function() {
$(document).on('change', "#input1", function()
        {
    var text = $("#input1").val();
    $("#new_input").val(text);
        });
});

That's all. For more info, http://api.jquery.com/on/


Delete JNLP file after it's get executed

Question: Is there anyway to delete the JNLP file after it's get executed.
When my application opens in a browser, a JNLP file is downloaded. So I don't want to keep the duplicate JNLP files so for that I want to delete the JNLP file after it's get executed
Answer: The jnlp downloads a jar with a Java application. That application could delete the jnlp file.
Comment: Right.. I tried the same.. Let's say the jnlp file is downloaded in users download folder.. That java application can find the users download folder and delete the file. But if user when downloads the jnlp file keep in different folder other than download folder then how the java application knows the path.


What are the ways to model bi-modal target distribution

Question: The target i am trying to regress is clearly a bi-modal distribution, currently one standalone model is giving results which are satisfactory.
As I am seeking improvement on my present model, I want to know whether there are specific ways in which we can learn a bi-modal target distribution.
Answer: What about fiting a mixture? E.g. mixture of two gaussians? You may want to look at our tags mixture and gaussian-mixture.


profile2 image field not show images

Question: I tested my profile2 image field at upload moment and the file upload successfully and unexpectedly after save changes the image fid appears like 0 but the image don't show.
What I do?
Thanks!
Comment: I see that profile2 image field don't save on field_data_field_name with fid. I see that the image is saved on file_managed also. Why happend?
Answer: Finally I found that I have an module conflict, if you decide to use DDF (Dynamic Dependent Fields) you must think before make tests with profile2 fields.

profile2 image field not show images


Finding a locally bounded real-valued function on $(0,1)$ whose integral is not easily computed on $(0,1)$.

Question: I need to find a locally bounded (continuous implies locally bounded) real valued function $f$ on $(0,1)$ such that the following conditions are met:

for every small $\epsilon > 0$, f is bounded and integrable on $[\epsilon , 1 - \epsilon]$
$\lim_{\epsilon\to 0} \int_{\epsilon}^{1 - \epsilon} f$ exists
the upper and lower sum, with respect to any partition $P$ of $(0,1)$ is not defined.

I've thought about the problem but I'm not sure if I'm on the right track. The function I initially considered was $sin(\frac{2\pi}{x})$ since it satisfies the first condition. With regard to the third condition, I can see that the sup of the first subinterval of any partition of $(0,1)$ would be $1$, and the inf would be $-1$. I'm not sure in what cases the upper and lower sums are undefined. I'm not sure how to check the second condition for this function.
For context, I have studied Darboux integration in a previous intro to analysis course, and I am currently studying the use of partitions of unity to define integration over arbitrary open sets in $\mathbb{R}^n$. I believe the purpose of this exercise is to motivate the necessity of using partitions of unity to evaluate certain integrals.
Any guidance would be greatly appreciated.
Answer: $f(x)=\frac 1 {\sqrt x} -\frac 1 {\sqrt {1-x}}$ is such a function. (I am sure you meant $\epsilon \to 0$ not  $\epsilon \to \infty$)
Comment: Thank you! I made the edit. I was able to check the conditions.