Multivariate multiple non linear regression

Question: I know there are already two questions on this topic, but neither has an answer.
I have a set of $N$ experiments. For each experiment, denoted by a vector of predictors $\mathbf{x}$, I measure $m$ values $y(f_1)\dots y(f_m)$ of a quantity $y$ at increasing frequency values. In other words, the result of each experiment is not a scalar but a function of frequency, measured at $m$ different frequencies. I thus have a total of $N\times m $ measured values of $y$.
I have a model for the results of this experiment, which is given by a computer code $g(f, \mathbf{x}, \boldsymbol{\theta})$, where the  $\boldsymbol{\theta}$ are calibration parameters. The setting is very similar to this question, with the added complication that now the output of the code is multivariate (a vector, instead than a scalar).
I would like to calibrate my code. I think I could use multivariate multiple nonlinear   least squares . However, I'm only familiar with multiple nonlinear least squares (single output). How do you calibrate on all outputs at once? Also, given a specific experiment, I'm not sure that errors at different frequencies are independent. As a matter of fact, based on past investigations I expect that (before calibration) the code results will match the trend in frequency of the measurements, but not the absolute values. What should I do in this case?
Answer: Let me change your notation just a little to make answering easier.  $y_{im}$ is the value of the outcome for experiment $i$ at frequency $m$, $i=1,\ldots,N$ and $m=1,\ldots,M$.  You have a function, $h(x,\theta)$, which outputs a $M$-dimensional vector of predicted $y$, one for each frequency, given a particular value for predictor variables, $x$, and parameter value $\theta$.  Connecting to your notation, $h(x,\theta)=g(f,x,\theta)$ (I think).  It's going to be convenient to think of a whole experiment's observations at once, so let $Y_i$ be the $M$-vector of all of experiment $i$'s $y$ for the various frequencies stacked up.
The data-generating process is then hypothesized to be:
\begin{align}
Y_i &= h(x_i,\theta)+\epsilon_i
\end{align}
Measurement error (or whatever the source of error is) for experiment $i$ is described by the random variables $\epsilon_i$.  All of the objects in the above equation are $M$-vectors.  You say that different frequencies' data are likely to be correlated.  I assume it is also the case that different frequencies' data could have different variances.  If we are safe to assume that these variances and covariances are the same across experiments (and that each experiment is independent of each other experiment), then we can assume that $V(\epsilon_i)=\Sigma$, where $\Sigma$ is an $M \times M$ variance-covariance matrix, and $V(\epsilon)=I \otimes \Sigma$, where $\epsilon$ is the "stacked-up" vector of errors ($NM$ by 1) and $\otimes$ is Kronecker product.
The above set-up is called non-linear seemingly unrelated regression.  The standard reference in Economics is Gallant, AR (1975) Seemingly unrelated nonlinear regressions. Journal of Econometrics, 3(1): 35-50.
The way you estimate the parameters (if you know $\Sigma$) is by solving:
\begin{align}
min_\theta \sum_{i=1}^N \left( Y_i-h(X_i,\theta)\right)' \Sigma^{-1} \left( Y_i-h(X_i,\theta)\right)
\end{align}
The variance of the (consistent and asymptotically normal) estimator, $\hat{\theta}$, so-defined is:
\begin{align}
V(\hat{\theta}) &= \left( \sum_{i=1}^N \frac{\partial h}{\partial \theta}' \Sigma  \frac{\partial h}{\partial \theta} \right)^{-1}
\end{align}
Normally, you don't know what $\Sigma$ is, however, so you have to estimate it.  The way you do this is by picking a trial value of $\Sigma$ (like the identity matrix).  Then you do the minimization above to get a first try at an estimator of $\theta$, call it $\tilde{\theta}$.  Then you "estimate" the $\epsilon$ by the residuals, $e_i=Y_i-h(X_i,\tilde{\theta})$ and calculate their sample variance matrix:
\begin{align}
\hat{\Sigma} &= \frac{1}{N} \sum_{i=1}^N e_i e_i'
\end{align}
Finally, you use $\hat{\Sigma}$ in place of $\Sigma$ above in the minimization and the variance-covariance matrix.  This procedure is called two-stage, non-linear seemingly unrelated regression (or words to that effect).
In R, I think the function you want is called nlsystemfit which has documentation here.
Comment: Great! This seems perfect.  Just a question about `nlsystemfit`: does it work also if I don't have an *explicit* expression for the nonlinear equations? I wrote a wrapper function around my computer code, so I can write a formula `y~h(x,theta)` (or maybe $M$ formulas, one for each frequency). Would that work?
Comment: I've never used it, so I don't know.  Sorry.


Two vectors linearly dependent on a third vector?

Question: I know how to check if a vector or a matrix is linearly dependent or independent , but how do I apply it on this problem?
Let V1 , V2 , V3 be vectors
How do I prove that the vector V3 = ( 2, 5, -5) is linearly dependent on V1 = ( 1,-2,3) and V2 = (4,1,1) ?
Will it be enough or correct if I solved the equation:
α1V1 + α2V2 - V3 = 0
and proved it has a solution?
Comment: A side note: 3 vectors in $\mathbb R^3$ are linearly dependent iff they are coplanar
Answer: To solve this you can approach with basic methodology:
Consider the equation $c_1(1,-2,3)+c_2(4,1,1)=(2,5,-5).$ Then you will have system of linear equations:
$c_1+4c_2=2, -2c_1+c_2=5, 3c_1+c_2=-5$.
Finding that whether $v_3$ is linearly dependent on $v_1$ and $v_2$ is equivalent to finding the solution of the above system.
A trivial computation shows that
$c_1=-2, c_2=1.$
Thus, the vector $v_3$ is linearly dependent on $v_1$ and $v_2$.
Answer: Yes, that will work.
Or you can check that$$\begin{vmatrix}2&1&4\\5&-2&1\\-5&3&1\end{vmatrix}=0.$$It follows from this that there are numbers $\alpha$, $\beta$ and $\gamma$ such that $\alpha v_3+\beta v_1+\gamma v_2=0$. If $\alpha=0$, then $v_1$ and $v_2$ would be linearly dependent, and therefore one of them would be the other one times a scalar. But that's clearly not the case. So, $\alpha\ne0$ and therefore$$v_3=-\frac\beta\alpha v_1-\frac\gamma\alpha v_2.$$


A question about complex manifolds

Question: Let $(M,J_{M})$ be a almost complex manifold and $(N,J_{N})$ be
a complex manifold. I want to prove that $F^{*}(\mathcal{O}_{N})\subset\mathcal{O}_{M}$
implies that $F:M\rightarrow N$ is almost complex. $\mathcal{O}_{M}$
denotes the sheaf of holomorphic functions on $M$ and similarily
for $\mathcal{O}_{N}$.
$F:M\rightarrow N$ is almost complex means that $dF\circ J_{M}=J_{N}\circ dF$.
Answer: $F$ is almost complex iff $dF$ maps the $+i$-eigenspace of $J_M$ to the $+i$-eigenspace of $J_N$, or equivalently (by dualization) iff $F^*$ maps $\Omega^{1,0}_N$ to $\Omega^{1,0}_M$. However, for any $\alpha\in\wedge^{1,0}T^*_xN$ there is a holomorphic function $f$ in a neighourhood of $x$ s.t. $\alpha=d_xf$ (it's enough to consider linear combinations of some local holomorhic coordinates around $x$). As $F^*f\in\mathcal{O}_M$,  for any $y\in M$ s.t. $F(y)=x$ we have $F^*\alpha=d_y(F^*f)\in\wedge^{1,0}T^*_xM$, hence $F^*$ maps $\Omega^{1,0}_N$ to $\Omega^{1,0}_M$.
Comment: One thing I don't understand is how to get that for any $\alpha\in\wedge^{1,0}T_{x}^{1,0}N$,
there exists a holomorphic function $f$ in a neighbourhood of $x$
such that $\alpha=d_{x}f$. Is this a general theorem or lemma?
Comment: If $z^i$ are local holomorphic coordinates and $\alpha=\sum a_i\, dz^i$, you can take $f=\sum a_i\,z^i$ (i.e. $f$ is a linear combination of the coordinates)

A question about complex manifolds


What is meant by a natural hat trick in hockey?

Question: While reading this article on NHL.com I noticed that they mentioned several times that Jori Lehtera recorded a natural hat trick.
I assume they say natural hat trick to contrast it to another type of hat trick, but I don't know of any other types of hat tricks.
I have only ever heard them say natural hat trick when talking about hockey so I assume it is specific to hockey.
What other types of hat tricks are there in hockey, and are they that different that a distinction is required?
Comment: Wikipedia has a listing of some common variations on hat tricks. The one you're most likely to hear, aside from natural hat trick, is the Gordie Howe hat track (a goal, an assist, and a fight). http://en.wikipedia.org/wiki/Hat-trick#Hockey
Comment: 3 goals scored by the same player consecutively
Answer: A natural hat trick is when the three goals are scored consecutively. That is, nobody else from either team scores in between the goals.


Why I cannot get CRON started in Docker Container

Question: I'm trying to create a Dockerfile based on Firebird SQL server.
FROM jacobalberty/firebird:2.5.8-sc
ENV ISC_PASSWORD masterkey
RUN apt-get update && apt-get -y install cron
RUN echo "* * * * * root echo "Time is: $(date)" >>/var/log/cron.log 2>&1" /etc/cron.d/backup-cron
CMD ["cron", "-f"]

But when I build and start it, it stuck in status "Starting".
If I perform a docker top I get this
> docker top my-container
root                20838               20824               2                   19:42               ?                   00:00:00            /bin/bash /usr/local/firebird/docker-entrypoint.sh cron -f
root                20891               20838               0                   19:42               ?                   00:00:00            cron -f

And if I comment the last line of my Dockerfile CMD I get this:
> docker top my-container
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                20487               20475               0                   19:40               ?                   00:00:00            /bin/bash /usr/local/firebird/docker-entrypoint.sh /usr/local/firebird/bin/fbguard
root                20542               20487               0                   19:40               ?                   00:00:00            /usr/local/firebird/bin/fbguard
root                20543               20542               0                   19:40               ?                   00:00:00            /usr/local/firebird/bin/fb_smp_server

Note that without the CMD my container starts the Firebird SQL Server process (fbguard and fb_smp_server), and with the CMD it doesn't and stuck in the cron -f.
I already tried to copy the ENTRYPOINT and the CMD of the parent image and merge with my command:
FROM jacobalberty/firebird:2.5.8-sc
ENV ISC_PASSWORD masterkey
RUN apt-get update && apt-get -y install cron
RUN echo "* * * * * root echo "Time is: $(date)" >>/var/log/cron.log 2>&1" /etc/cron.d/backup-cron
ENTRYPOINT ["/bin/bash", "-c", "/usr/local/firebird/docker-entrypoint.sh", "&&", "cron", "-f"]
CMD ["/usr/local/firebird/bin/fbguard"]

But when I start the container it exit with exitcode 0 and doesn't starts.
>docker-compose up --build
Removing meu_teste
Building app
Step 1/6 : FROM jacobalberty/firebird:2.5.8-sc
 ---> 8c7d4de934c9
Step 2/6 : ENV ISC_PASSWORD masterkey
 ---> Using cache
 ---> 86770045ded3
Step 3/6 : RUN apt-get update && apt-get -y install cron
 ---> Using cache
 ---> 3a42b5d13eb1
Step 4/6 : RUN echo "* * * * * root echo "Time is: $(date)" >>/var/log/cron.log 2>&1" /etc/cron.d/backup-cron
 ---> Using cache
 ---> ad83425e8f1e
Step 5/6 : ENTRYPOINT ["/bin/bash", "-c", "/usr/local/firebird/docker-entrypoint.sh", "&&", "cron", "-f"]
 ---> Using cache
 ---> ba029a42c670
Step 6/6 : CMD ["/usr/local/firebird/bin/fbguard"]
 ---> Using cache
 ---> ab6b289934ac

Successfully built ab6b289934ac
Successfully tagged teste:latest
Recreating 847556ee975e_847556ee975e_meu_teste ... done
Attaching to meu_teste
meu_teste exited with code 0

Comment: Possible duplicate of [How to run a cron job inside a docker container?](https://stackoverflow.com/questions/37458287/how-to-run-a-cron-job-inside-a-docker-container)
Answer: Solved.
I created a new entrypoint script called init.sh with this code:
#!/bin/bash
service cron start
# import the parent script as source of this new one
source /usr/local/firebird/docker-entrypoint.sh

And my Dockerfile now is:
FROM jacobalberty/firebird:2.5.8-sc
ENV ISC_PASSWORD masterkey
RUN apt-get update && apt-get -y install cron
RUN (crontab -l ; echo "* * * * * echo "'"Now is $(date)"'" >> /var/log/cron.log") | crontab
ADD init.sh /init.sh
RUN chmod +x /init.sh
ENTRYPOINT ["/init.sh"]
CMD ["/usr/local/firebird/bin/fbguard"]

The problem was about the parent image ENTRYPOINT and CMD. At my image I was redeclaring they and this was the cause that the container wasn't starting.
I think docker doesn't handle inheritance of CMD and ENTRYPOINT.


Interpretation of low bias and variance for train/test errors

Question: Based on the extensive discussion in this post, I understand that the goal is to achieve low bias and low variance.
Now, in terms of train and test errors, does it imply that achieving low bias and low variance is equivalent to having both high training and testing accuracy? Is it possible to acquire that from confusion matrix?
Answer: Overfitting/High Variance:
Your data fits very well on the training set, but poorly on the cross-validaton set. If you have no cross-validation set than it means that it fits poorly on the test set.
Underfitting/ High bias:
Your data fits badly on the training set and also badly on the test/CV set.
=> In both cases the model fits badly on the test. However we want our model to fit well on the test set. Testing accuracy is more important than training accuracy, because you want to now how good your model is on data is has not yet seen.
Your interpretation is correct: If you have a low bias and a low variance than the model has a good training and a good testing acccuracy.

You can also deduct this from the confusion matrix:
Few missclassifications in the training set and many in the test set:
You have high variance. You are overfitting your data.
Many missclassifications in the training set and many in the test set:
You might have high bias. You are probably underfitting your data.
Many missclassifications in the training set and few in the test set:
This should usually not appear. Maybe you made a mistake. This usually occurs due to non-random sampling of your data. Shuffle your data and fit the model again.
Few missclassification in the training set and few in the test set:
You have low bias and low variance. You reached your goal! Congratulations.


CFLOOP and SQL Update

Question: How do I use CFLOOP for updating my records on Access DB? I have tried using the code below but it seems it gives me a duplicated value instead of an increment
My code:
<cfloop index="i" from="1" to="3">
<cfquery name="query" datasource="datasource">
    update mytable
    set
    columnB = #i#
    where columnA = 'a'
   </cfquery>
</cfloop>

Output of records under columnB= all number 3, it should be 1,2,3
My table looks like this....
Column A|ColumnA1|ColumnB
A         A
A         B
A         C

Columns A and A1 is filled with a previous CFLOOP and SQL Insert.
Comment: What are the values of columnA?
Comment: A repeated string character, in this situation it is the letter 'A'
Comment: That's why @Busche's answer is correct.
Comment: @DanBracuk not sure what you're saying, the SQL needs to be more specific to update only select rows, includomg ColumnA1 in it as well for example, would make it only update one row instead of all three.
Comment: @Ace09 - *Output of records under columnB= all number 3, it should be 1,2,3*  **Why**? You need more criteria than just `WHERE columnA = 'a'`, because that matches *all* of your sample records. So every time you loop, all of the records are set to the same value.  You have not told us *why* the `ColumnB` values should be set to `1, 2 and 3`. Once you explain that, we can suggest the proper code.
Comment: Also, that kind of looping seems a little suspicious. What is the real goal, and is this a one time or recurring update? Because there may be more efficient options ..
Comment: @Leigh, I am designing a simple multiple choice application for an elearning website. I need to use SQL update since CLOOP could only loop insert one set of data at a time.
Comment: @Ace09 - Well that still does not tell us enough ;-) Are you trying to populate some "master" Q&A table or process user responses? We need to see the 1) [table ddl](http://en.wikipedia.org/wiki/Data_Definition_Language#CREATE_statements) 2) a more complete sample of the data used for the update 3) *and* the "desired" results.  That said  ... based on what little you have described, you may want to rethink your table structure. Q&A type applications usually store the data (ie questionID & related answerID) in rows, not columns, because it provides much greater flexibility.
Answer: You're updating all the records that have columnA = 'a' each time you run the update, you need more criteria in your where clause to stop updating multiples rows at once.
You can easily see how many rows were updated by using the result attribute of cfquery, similar to the code below.
<cfloop index="i" from="1" to="3">
<cfquery name="query" datasource="datasource" result='updated'>
    update mytable
    set
    columnB = #i#
    where columnA = 'a'
   </cfquery>
   <cfdump var='#updated#' />
</cfloop>

Update:
Given your updated question, an example updated query may look like so, as the combination of columnA and ColumnA1 make the row unique.
<cfloop index="i" from="1" to="3">
<cfquery name="query" datasource="datasource" result='updated'>
    update mytable
    set
    columnB = #i#
    where columnA = 'a'
    AND ColumnA1 = <cfqueryparam value='#i#' />
   </cfquery>
   <cfdump var='#updated#' />
</cfloop>

Comment: Just to clarify, the query is updating all of the records where `columnA` is equal to `a` (as opposed to all records in the table).
Comment: @Busches, I have tried your updated code, it seems to give me an array and it does not update ColumnB. Is the value of ColumnB be the same for ColumnA1 from the cfquery? They both use the variable i... Thank you for the quick reply
Comment: The updated variable will give you a struct of variables. The code I gave you is pseudo code, it won't necessarily work for your exact need without some tweaking. I used the variable I again as that's the only variable you have in the loop, again, you'll need to tweak the code to get it to work, but it should set you in the right direction.
Comment: The record didn't update, because the value of columnA1 is never 1, 2, or 3 which is the what this latest answer is saying to do.  Just change "where columnA = 'a'"  to "where columnA1 = 'a'" and Bob will be your uncle.

CFLOOP and SQL Update


The ideal of the intersection of two algebraic subsets

Question: If $V, W$ are algebraic subsets of $\mathbb A^n(k)$. Show that $I(V∩W)=\sqrt{I(V)+I(W)}$
Answer: Claim: $V(I(V)+I(W))=V \cap W$.
Prove the claim, and apply Hilbert's Nullstellensatz in the form $I(V(J)) = \sqrt{J}$ for every ideal $J$.
Comment: Thank you. To prove the Claim $V∩W⊂V(I(V)+I(W))$ follows by $V(I(V)+I(W))⊂V=V(I(V)$ the other side goes by the same way an the other one by definition.
Comment: @Miguel: I've merged your old account into your new one. I recommend that you register your account which will, among other things, allow you to accept answers and comment on your own questions and answers thereof.


Need help finishing proving this summation inequality by induction

Question: I'm having a hard time solving the following problem:
Prove by induction that $\forall\ n\in\mathbb{N} $:
$$\sum_{i=1}^{n} \frac{n+i}{i+1}\ge n$$
I checked the base case, and then made it up to here in the inductive step:
$\sum_{i=1}^{n+1} \frac{n+1+i}{i+1}\gt \frac{\sum_{i=1}^{n+1} n+1+i}{\sum_{i=1}^{n+1} i+1}\ge \frac{(\sum_{i=1}^{n} n+i)+(2n+1)+(2n+2)-(n+1)}{(\sum_{i=1}^{n} i+1)+(n+2)}$
How do I use the inductive hypothesis to get to: $$\sum_{i=1}^{n+1} \frac{n+1+i}{i+1}\gt n+1$$
Comment: But it's obvious without induction.
Answer: As Michael Rozenberg states in a question comment, it's fairly obvious without induction as each term is $\ge 1$ (since $n + i \ge i + 1$) and there are $n$ terms. However, if you wish to use induction, then here is one way to do it to prove that
$$\sum_{i=1}^n \cfrac{n + i}{i + 1} \ge n \tag{1}\label{eq1}$$
First, check the base case of $n = 1$, with both sides giving $1$, so it's true. Next, assume \eqref{eq1} is true for all $n \le k$ for some $k \ge 1$, in particular that
$$\sum_{i=1}^k \cfrac{k + i}{i + 1} \ge k \tag{2}\label{eq2}$$
For $n = k + 1$, note that $\frac{k + 1 + i}{i + 1} \gt \frac{k + i}{i + 1}$ for all $1 \le i \le k$. Thus,
$$\sum_{i=1}^{k + 1} \cfrac{k + 1 + i}{i + 1} \gt \sum_{i=1}^k \cfrac{k + i}{i + 1} + \cfrac{\left(k + 1\right) + k + 1}{k + 1 + 1} \tag{3}\label{eq3}$$
Using \eqref{eq2} and that $2k + 2 \gt k + 2$, the right side of \eqref{eq3} gives that
$$\sum_{i=1}^k \cfrac{k + i}{i + 1} + \cfrac{2k + 2}{k + 2} \gt k + 1 \tag{4}\label{eq4}$$
Putting \eqref{eq3} and \eqref{eq4} together gives that
$$\sum_{i=1}^{k + 1} \cfrac{k + 1 + i}{i + 1} \gt k + 1 \tag{5}\label{eq5}$$
This shows it's true for $n = k + 1$, thus completing the inductive steps.
Answer: Start with:
$$
n+2>2\Rightarrow 2n+2>n+2\Rightarrow\frac{2(n+1)}{n+2}>1.
$$
Then:
$$\sum_{i=1}^{n+1} \frac{n+1+i}{i+1}=
\sum_{i=1}^{n} \frac{n+1+i}{i+1}+\frac{2(n+1)}{n+2}\\
>\sum_{i=1}^{n} \frac{n+i}{i+1}+\frac{2(n+1)}{n+2}
>n+1.
$$


Angular 6 Reload page on parameter change

Question: I am using angular 6 to build an app. However I have got a page with list of events  with each event having link to its detail page as '/events/view/1'.
I am providing link to my a tag as View Detail
However, when I click on any event to view its detail, I get the EventId updated in the URL. But the contents in the page are not updated until I manually refresh the page.
Answer: Do you have <router-outlet></router-outlet> in your app-component html? What are the console errors if any?
Comment: Yes, I do have router outlet. However, i got it resolved. The problem was {{ dealinfo.OfferTitle }} was replaced by
Comment: try `{{dealinfo?.offerTitle}}` instead.


Does cold temperatures hurt my guitars if stored in a non heated place through the northeastern winter??

Question: will cold temperatures hurt my guitars if stored in a non heated place through the northeastern winter?? I'd like to know if I need to move them to the house?
Comment: What kinds of guitars? Either way, if there is room in the house, I would move them in so you don't have to wonder.
Comment: Where in the northeast? What sort of temperatures/humidity? Big daily changes?
Answer: Quick changes in temperature as well as certain levels of humidity can damage a guitar. Since you won't be able to control those changes outside, your guitar will be safer at room temperature.
Answer: Which northeast are we talking about? America? Europe? Asia? Switzerland?? I'm assuming USA because you assume that it's implicit, pardon my stereotyping.
It's usually temperature and humidity changes you need to avoid, but also beware of keeping your house too arid if you are keeping it inside. Too dry air can cause fretboards to shrink, or acoustic guitars to crack, neither of which you want!
Answer: It depends on what your guitar is made out of whether it hurts the actual instrument.  It your guitar is made of wood, you absolutely must not let it freeze or experience massive changes in temperature (it will become brittle and structurally unsound, plus start to sound much more tinny).
If your guitar is an electric guitar and relies on pickups rather than resonating itself then you only have to worry about the strings (the body may become more brittle, but this is not related to the musical quality).  You will absolutely ruin the strings on your guitar (of any kind) if you let them experience temperature variance of 35F or more - this is a simple mechanical fact rather than a musical one (true even without a winter - they will become warped and stretch beyond the ability to tune for any duration).
Comment: This whole answer seems quite dubious to me. That about the strings is pretty much just wrong (I know at least carbon fibre instruments have no difficulty whatsoever with large temperature swings, despite using the same steel strings). Wood definitely does respond to temperature and humidity, but I'd be surprised if freezing would be such a problem per se (consider that living spruce is perfectly happy at boreal conditions). As others have said, it's mostly _rapid changes_ that are an issue. Though that too is often exaggerated.
Comment: First time I've heard about strings warping and stretching due to extreme temperature swings. Where did that information come from?
Comment: From what I remember, the issue is similar to rapidly stretching your strings (pre-stretching, usually by pulling up on them to stretch them out). By not having regular tension across the length of the string you cause thin spots which causes loading, which causes a warble in the string creating tone decay as the vibrations slow down (pitch changes from when you pick it to when the string stops vibrating.) You can often hear this effect on old strings that causes difficulty in tuning well. I'm not sure the effect of a rapid temperature change could cause the same thing though.
Comment: @NickBastin much the same steel alloys are routinely used in industrial applications which experience temperature swings of _hundreds_ of Kelvins, that in some cases probably multiple times per hour, and the machinery is still supposed to last for years. Sure, there's a limit to what swings are safe, but 20 K is nowhere near it. — What do mean, about nylon now? This question seems to be about steelstring guitars. Nylon strings actually are more temperature-sensitive in my experience, albeit just with respect to tuning stability.
Comment: @leftaroundabout: wide variance in temperature applies considerable fatigue factor to wire - how much and the impact differ based on the temperature and the alloy.  This is not a musical question, it's a materials science one.  Wide swings in temperature will affect the functional lifetime of your strings, and over 30-35F it will do so significantly (at least with common alloys - if someone starts making strings out of new materials you'd have to look up the fatigue research on those materials).
Comment: To be clear, the wire in question for guitar strings is actually wound *around* a nylon (or steel, for electric usually) thread, and the effects of temperature on nylon I am not aware (although I'm sure you can find research on this topic).  The effects of temperature on the metal that is wound around the string are what affect the functional lifetime (how long it stays in tune, and how much variance exists over the length of the string).
Comment: @leftaroundabout: I'm not sure about the OP string type - they don't actually specify what kind of guitar (nylon never for electric, but common for classical).  You'd have to know the specs for a given string to be sure, but in my experience the nickel-plated steel wind used for most guitar strings is not a high temperature alloy (which is often electroless, which makes it too brittle to be used for such an application).


AD DS it doesn't show any info event

Question: In Role services in the AD DS role summary, it doesn't show any information. Previously it was showing information.
Is this good or bad? Do I need to correct something?
Comment: "What Changed?" -- It behaved one way, now it's behaving another, therefore something changed.  Computers do not change on their own, so someone must have changed something: determine what (and who) and that will tell you whether this is a good thing or bad.
Comment: i had an warning 1020, and i was searching for this error on microsoft page and i follow the instructions from there. It was a problem with an Certificate. The warning disappeared, and there after no more infos.
Answer: I realize after in the right side where is the Filter Events and it was not checked the Information box.
Since i checked that box it shows the info

AD DS it doesn't show any info event


.Net MVC verify only one checkox checked

Question: I have a model called Employee with a boolean field called OnDuty. Our business rules only allow for one employee on duty.
On the index page, I've setup the checkbox so they trigger an update call to update the employee as being "on call". However, I'm not set any other employees to off duty using my controller action below. How do I go about making sure that no other employee is on duty?
[HttpPost]
public JsonResult Update(Employee employee)
{
    IEnumerable<Employee> onCallEmployee = _db.Employees.Where(e => e.OnCall == true);
    foreach (Employee e in onCallEmployee) {
        e.OnCall = false;
        _db.Entry(e).State = EntityState.Modified;
        _db.SaveChanges();
    }
    _db.Entry(employee).State = EntityState.Modified;
    _db.SaveChanges();
    return Json("Employee updated!");
}

Comment: What exactly is the problem here. Is your code not setting other employees.oncall to false? Is the binder not binding the posted employee.oncall to true? What are you having an issue with. P.S. you might want to call SaveChanges() only at the bottom not within the foreach loop and at the bottom.
Comment: Correct, I was unable to save the all the employees. I was able to resolve the issue(s) using the code update in the answer I posted below. Thanks for the suggestion!
Answer: It appears that my error(s) were caused by the way I was trying to update the employees. I had to exclude the employee which was already being updated by the function from onCallEmployee because it would throw an error (Attaching an entity of type 'Employee' failed because another entity of the same type already has the same primary key value.) when trying to save the updates.
Also, based on @mwwallace8, suggestion, I removed the SaveChanges() call from the for loop and left a single call at the end.
[HttpPost]
public JsonResult Update(Employee employee)
{
    IEnumerable<Employee> onCallEmployee = _db.Employees.Where(e => e.OnCall == true && e.ID != employee.ID);
    foreach (Employee e in onCallEmployee) {
        e.OnCall = false;
        _db.Entry(e).State = EntityState.Modified;
    }
    _db.Entry(employee).State = EntityState.Modified;
    _db.SaveChanges();
    return Json("Employee updated!");
}


Dynamic link from a text input

Question: I have a text input and a link below it (I use Webix)
What I want to do is to enter a part of a link (IP address) to the text field and apply this address to a link.
I tried
elements:[
    { view:"text", label:'IP', name:"IPname", id:"IPid", value:"127.0.0.1" },
    { view:"template", height: 30,
     template:"Test link"
    }
],

But this notation doesn't work (actually, gives an error "IPid is undefined")
My Code Here
Is there any way to do this?
Answer: Please try this, I don't know whether this will help you or not, please correct me if i am wrong.
webix.ui({
    rows:[
        {
            id:"form1", view:"form", scroll:false,
            elements:[
                { view:"text", label:'IP', name:"IPname", id:"IPid",   value:"127.0.0.1" },
                { view:"template", height: 30,
                    template:"Test link"
                }
            ],
            width: 320,
            elementsConfig:{
                labelPosition: "top",
            }
        }
    ]
});

func1();
function func1() {
    document.getElementById("anId").setAttribute("href",$$("IPid").getValue());
    var abc = document.getElementById("anId").getAttribute("href");
}
window.onload=func1;

Comment: Solution will work with a small correstion: `setAttribute("href", "http://"+$$("IPid").getValue());`
Answer: Strange issue, I'm not very familiar with webix, but putting the window.open in a function worked. Also have in mind that the correct attribute is 'onclick' not 'click' and that a parenthesis was missing. Fixed them too, check it out:  http://webix.com/snippet/e4e236b9
webix.ui({
  rows:[
    {
      id:"form1", view:"form", scroll:false,
      elements:[
        { view:"text", label:'IP', name:"IPname", id:"IPid", value:"127.0.0.1" },
        { view:"template", height: 30,
         template:"Test link"
        }
      ],
      width: 320,
      elementsConfig:{
        labelPosition: "top",
      }
    }
  ]
});

Comment: Thank you. Taking out the function was the point. For now, I improved it a bit with `Test link` to prevent redirecting.
Answer: About you Error "IPid" is undefined occur because the declare id is not using with any control may be you do spelling mistake. If every this is fine try this code
 $("#YoutextBoxID").val();

and paste it where your request send for further activity
Like This click='"/*+window.open($("#YoutextBoxID").val()*/+"'

Dynamic link from a text input


JS multiselect images and draw them into canvas - sometimes canvas blank or same image drawn

Question: I am using JS and a multi select field.
A user can select multiple images from a folder and then each image should be drawn into a canvas. Each image has a predefined canvas and a predefined input field where then the decoded base64 dataurl is placed in.
The multiselect field:
<input id="bild" multiple="" name="bild" type="file">

In my example there are 3 different canvas elements and 3 different dataurl input fields:
$( "input#bild" ).change(function() {

  console.log("multiple");

  // from an input element
  var filesToUpload = this.files;
  //console.log(filesToUpload);

  if(typeof this.files[0] !== "undefined") {
    console.log("multiple-1");
    var img = document.createElement("img");
    img.src = window.URL.createObjectURL(this.files[0]);

    $( img ).load(function() {
      console.log("multiple-1-loaded");
      canvas = $("#uploading_canvas_image_1").get(0);

      var MAX_WIDTH = 550;
      var MAX_HEIGHT = 400;
      var width = img.width;
      var height = img.height;

      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }

      canvas.width = width;
      canvas.height = height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, width, height);

      var dataurl = canvas.toDataURL("image/jpg");

      $( "#dataurl_image_1" ).val(dataurl);

    });
  }

  if(typeof this.files[1] !== "undefined") {
    console.log("multiple-2");
    var img = document.createElement("img");
    img.src = window.URL.createObjectURL(this.files[1]);

    $( img ).load(function() {
      console.log("multiple-2-loaded");
      canvas = $("#uploading_canvas_image_2").get(0);

      var MAX_WIDTH = 550;
      var MAX_HEIGHT = 400;
      var width = img.width;
      var height = img.height;

      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }

      canvas.width = width;
      canvas.height = height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, width, height);

      var dataurl = canvas.toDataURL("image/jpg");

      $( "#dataurl_image_2" ).val(dataurl);

    });
  }

  if(typeof this.files[2] !== "undefined") {
    console.log("multiple-3");
    var img = document.createElement("img");
    img.src = window.URL.createObjectURL(this.files[2]);

    $( img ).load(function() {
      console.log("multiple-3-loaded");
      canvas = $("#uploading_canvas_image_3").get(0);

      var MAX_WIDTH = 550;
      var MAX_HEIGHT = 400;
      var width = img.width;
      var height = img.height;

      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }

      canvas.width = width;
      canvas.height = height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, width, height);

      var dataurl = canvas.toDataURL("image/jpg");

      $( "#dataurl_image_3" ).val(dataurl);

    });
  }

For each image I am checking if it is really there and not undefined. Then it is drawn into the canvas and the corresponding field for dataurl is populated with the dataurl.
The Problem is:
I do not get any errors.
The behaviour is different with different sets of images but its always the same with the same set. For example: I am marking 3 different images in the folder which I want to upload, but always all 3 canvas show the same image (3rd) one also all 3 dataurls are the same.
Sometimes some canvas are blank.
Sometimes it works

It seems like a general problem, but I havent managed to locate why this happens. My guess is it maybe has something to do with the onload function for the image and that the dataurl is created in the same steps. The dataurl itself is insanly long. I am looking at this atm. Maybe someone here has an idea.
Answer: I found the issue. The img was causing these problems. Because I always used the same img, eventhough it is in the if condition block. It seems that the function itself is stronger then the if condition?
I had to create a new img variable for every image selected, which means I needed this for image 1:
var img1 = document.createElement("img");
img1.src = window.URL.createObjectURL(this.files[0]);

$( img1 ).load(function() {

//...

ctx.drawImage(img1, 0, 0, width, height);

});

For image 2:
var img2 = document.createElement("img");
img2.src = window.URL.createObjectURL(this.files[1]);

$( img2 ).load(function() {

//...

ctx.drawImage(img2, 0, 0, width, height);

});

For image 3:
var img3 = document.createElement("img");
img3.src = window.URL.createObjectURL(this.files[2]);

$( img3 ).load(function() {

//...

ctx.drawImage(img3, 0, 0, width, height);

});


How do I use the rand crate without the standard library?

Question: I'm doing embedded game development for the Sega Megadrive with Rust and would like a random number generator to increase replayability. It can be pseudo-random: there's no security stuff required.
I've been looking at the rand crate which falls in the "No standard library" department, but I'm not sure on how to use it with this in my Crate.toml:
[dependencies]
rand = {version = "0.8.3", default-features = false}

When I disable default-features, there's no random function in the prelude anymore. There is the Rng trait but I'm too inexperienced to figure out how to use it.
Comment: I always used [fastrand](https://crates.io/crates/fastrand), I'm not sure if it works on SEGA though
Comment: SmallRNG from the rand crate seems to work without `std`. [Here's the documentation](https://docs.rs/rand/0.8.3/rand/rngs/struct.SmallRng.html)
Comment: Putting that code in a file called `Crate.toml` will have no effect as nothing care about that file. Perhaps there's a simple typo to fix your problem?
Comment: Generally, random number generators need a source of entropy — what will that be on your device?
Comment: @Misty SmallRNG is no_std. With a date or anything at seed, it should be OK for OP's stated needs. This looks like a valid answer (only need an example)
Comment: @Misty thanks for the pointers. Looks like fastrand uses stdlib, by the looks of https://github.com/smol-rs/fastrand/blob/master/src/lib.rs#L73. SmallRNG looks promising but an example of how to use this on a no_std crate would be very helpful indeed.
Answer: To use the rand crate without std you need to manually use one of the generators that work without it. Those generators are the OsRng and the SmallRng structs. As the name suggests the first one uses the operating system's generator, which requires the getrandom crate, which probably isn't supported on SEGA Megadrive.
SmallRng should work without problems though. We cannot use the random() function, we need to manually create the generator and then call its methods.
To do this we first have to create a generator, like this:
let mut small_rng = SmallRng::seed_from_u64([insert your seed here]);

You can also use the seed_from_u32, whose documentation you can find here.
Then we can use it as such:
let rand_num = small_rng.next_u64();

Importantly, we have to import the RngCore trait to use these functions, this way:
use rand::{Rng, SeedableRng};
use rand::rngs::SmallRng;
use rand::RngCore;

SmallRng relies on the small_rng crate feature, so you should import it this way (in the Cargo.toml file):
rand = { version = "0.8.3", features = ["small_rng"], default-features = false }

I should also leave a disclaimer: SmallRng's generator isn't cryptographically secure.
Comment: This looks like it's getting close! The compiler now complains that it cannot compile libc:
Comment: ```
1628 | ...                   speed: ::speed_t) -> ::c_int;
     |                                ^^^^^^^ not found in the crate root
error: aborting due to 380 previous errors

Some errors have detailed explanations: E0412, E0573.
For more information about an error, try `rustc --explain E0412`.
error: could not compile `libc`
```
libc is listed as an optional dependency, but it looks like small_rng requires it... Is there an obvious solution to this?
Comment: By the way I found no references to a `seed_from_u32` method... But it might not matter.
Comment: @Rein Try explicitly listing libc as a dependency. And make sure it's listed as a required dependency
Comment: I added: `libc = { version = "0.2.94", default-features = false, optional = false }` but it didn't make any difference. It still lists the same list of 380 errors, all ending with `not found in crate root`. But I can't add it to the root crate because it's a 'virtual' crate. Any ideas? My code is in https://github.com/reinvantveer/rust-mega-drive/tree/main/examples/megatowerdefense if you want to look into the details.
Comment: Ah I can add it to one of the libs, I'll try and report back
Comment: I tried adding it to one of the library crates, but that didn't work out either. Same result: the 380 errors. I'm beginning to think this isn't going to fly.
Comment: Hmm this is really weird, I just tried compiling a static-lib with the rand crate and it worked no problem. This must be very specific to your crate setup
Comment: I just tried compiling the megatowerdefense crate and it compiled just fine. Maybe this is an enviromental problem? What OS are you on? And during the compilation of which crate does it face problems?
Comment: I used the Dockerized setup to build the cross-compiler and the cargo-megadrive command with the examples: `docker build -t rust-m68k:latest -f Dockerfile.toolchain . && docker build -t rust-mega-drive .` from the project root. This will set you back a few hours, but then it errors out at compiling the megatowerdefense crate on the last build step of the `Dockerfile`. This is on Ubuntu 20.04 but that shouldn't matter with Docker. But maybe it's to do with the cargo-megadrive command/extension?
Comment: I checked and a default `cargo build --release` passes, so I'm accepting your answer @Misty! Thanks for all the good pointers, it's greatly appreciated.
Comment: One other thing: you need `rand = { version = "0.8.3", features = ["small_rng"], default-features = false }` for it to skip the compilation of features that pull in `libc` as a dependency. Could you update your answer @Misty?
Comment: @Rein sorry for my lack of responses, I didn't have access to my computer lately. I updated the answer. Good you figured it all out :)
Comment: You're totally fine @Misty, thanks for the helpful answers and the time you committed, it's greatly appreciated.


How do NFL players know a fair catch has been called?

Question: I know that a raised arm wave signals a fair catch.  But I can imagine gunners and such sometimes will be in the midst of fighting through blocks or at least have someone blocking their vision for a couple of seconds.  Or at the least need to be focusing on what's happening around them rather than looking way down the field early in the punt/kickoff.
How do players become aware of the fair catch?  Is there some officiating signal?  Or do teammates yell something out to aid one another?  Or is this just somehow not normally an issue?  It seems players these days rarely hit someone who has called fair catch, or instead hang back too much when it's not... so I have to think there's something.  I know officiating made sure to push a full fair catch signal, giving players a little extra chance, but is there anything more to help?
Answer: This is normally not the issue. I'd imagine part of gunners' responsibility is to look at the returner and see if they wave their hand above their head to signal a fair catch.
The returners also don't signal till the ball hits its flight apex, so they can judge where it can land. So the gunners have plenty of time to get close to the returner to see it.
From the NFL Rulebook's:

Rule 10. Opportunity to Catch a Kick, Fair Catch
SECTION 1 - OPPORTUNITY TO CATCH A KICK

ARTICLE 1. INTERFERENCE
During a scrimmage kick that crosses the line of scrimmage, or during a free kick, members of the kicking team are prohibited from interfering with any receiver making an attempt to catch the airborne kick, or from obstructing or hindering his path to the airborne kick, and regardless of whether any signal was given.

ARTICLE 3: RESTRICTIONS
...
C) If a receiver has made a fair catch, an opponent is
prohibited from blocking or tackling him, or causing a passive player
of either team to contact him. Incidental contact is not a foul.

Furthermore:

Penalty: For illegal contact with a player who has made a fair catch:
Loss of 15 yards from the dead-ball spot and disqualification if
flagrant.

So it's the kicking team's players' job - gunners - to avoid contacting the receiver. Regardless of signaling a fair catch, the receiver cannot be hit prior to the arrival of the ball. But If the fair catch is signaled, then the receiver can't be hit once the reception is made.
Comment: This makes logical sense, but I have to downvote; it's just your supposition, and not something from either your personal expertise nor documented in the rules or official commentary.  A good answer to a question of this nature needs to contain one of those.
Comment: @Joe & Nij see the edit
Comment: Yup, it's 100% the coverage team's responsibility to see a fair catch signal by the returner. Very rarely, you'll get some controversy over whether a proper fair catch signal was given, but if the officials think it was given, then it's considered signaled.


Weak convergence using characteristic functions

Question: This problem is from Billingsley's "Probability and measure" book.
Let $a_n \to a$, $b_n \to b$ and $\{X_n\}$,$X$ be a sequence of random variables such that $X_n \to^w X$ (weak convergence). Prove that
$$a_nX_n + b_n \to^w aX+b$$
using characteristic functions.
I was able to reduce the problem into proving the following:
If $a_n \to 0$ and $X_n \to^w X$ then $a_nX_n \to^w 0$.
To begin with, we have
$$|E[e^{ita_nX_n}] - 1| \leq E[|e^{ita_nX_n} - 1|] = 2E|\sin\left(\frac{ta_nX_n}{2}\right)|$$
The trouble I am having is that the sequence $X_n$ is in the way. If $X_n$ are integrable, then the proof is complete using $|\sin(x)| \leq |x|$. However since that is not given, I don't know how to proceed. Any help would be appreciated.
Edit: I just saw an answer here. However that used Skorokhod's theorem. Isn't there some simplification that could be done to RHS?
Answer: If $\phi_n$ is the characteristic function for $X_n$ and $\phi$ the characteristic function for $X$ then you know $\phi_n(t) \to \phi(t)$ for all $t$. Let $\epsilon > 0$. Choose $N_1$ large enough so that $n \geq N_1$ implies
$$
  |\phi_n(at) - \phi(at)|
< \frac{\epsilon}{2}.
$$
Since the $\phi_n$ are uniformly continuous, for each $n$ there is a $\delta_n > 0$ such that $|x-y| < \delta_n$ implies $|\phi_n(x) - \phi_n(y)| < \epsilon$. Without loss of generality, assume that $\delta_n$ is a decreasing sequence (if $\delta_n$ is not smaller than the $\delta_i$'s with $i\leq n$, taking it to be less than or equal to the preceding values does not make the condition false).
Now, since $a_n \to a$ you can choose $N_2 \in \mathbb{N}$ such that $n \geq \max\{ N_2,m\}$ implies
$|a_n - a| < \delta_m$ whence
$$
  |\phi_m(a_n t) - \phi_m(at)|
< \frac{\epsilon}{2}.
$$
Since $\delta_m$ is decreasing this means that
$|\phi_n(a_n t) - \phi_n(at)| < \frac{\epsilon}{2}$. Therefore, $n \geq \max\{N_1,N_2\}$ implies
$$
     |\phi_n(a_nt) - \phi(at)
\leq |\phi_n(a_n t) - \phi_n(at)| + |\phi_n(at) - \phi(at)|
<    \epsilon.
$$
This says that the characteristic functions for $a_nX_n$ converge to the characteristic function for $aX$.
Comment: I see. So what you did is essentially decouple $X_n$ and $a_n$ using uniform continuity. Then bring them together. Thanks. Additionally, do you think in my approach the RHS could be manipulated to give the result?
Comment: Hmmm .... at the moment I can't think of how to proceed. I'll think about it though!
Comment: Something seems off... In http://math.stackexchange.com/a/570519/35983, it was shown that uniform continuity of a sequence of functions, whose ptwise limit is also continuous does not imply $f_n(a_n) \to f(a)$. Has something additional been used here?
Comment: Hey Gautam. So I think the difference here is that each $\phi_n$, and $phi$, is uniformly continuous. That doesn't seem to be the case in the link!
Comment: Continuous functions on compact sets are UC. Moreover I think the problem is in This step: Since $\delta_m$ is decreasing, we have...


Find youtube channel name with channel id

Question: Is there a way to get a youtube channels name if you have the channel id for that channel?
Will i need to do the whole oauth thing to get it? or is there an easy way?
Answer: Channels: list has an Id parameter combined with snippet returns the title of the channel.

id    string The id parameter specifies a comma-separated list of the
  YouTube channel ID(s) for the resource(s) that are being retrieved. In
  a channel resource, the id property specifies the channel's YouTube
  channel ID.

GET https://www.googleapis.com/youtube/v3/channels?part=snippet&id=UC_x5XG1OV2P6uZZ5FSM9Ttw&key={YOUR_API_KEY}
Note: this is a public call to the api so you can do this with an API key and there is no need to use Oauth2.


How do I add dropdowns in Filter Criteria in Views module?

Question: I was at a local Drupal group meetup last week where a member ran through a presentation of the Views module. I was really excited when I saw that he was able to add dropdowns to the Filter Criteria that he was using as I need exactly that functionality for something that I am building.
The thing is: I can't find the settings at all in my build. I remember that there was a 'settings' link at the bottom of his Filter Criteria area, but I have nothing like that.
Could anyone explain where I can find this? Am I missing and additional module?
Comment: Are you talking about exposed filters to the user, or selecting a value for the filter in the views interface?
Comment: I am talking about exposed filters to the user. Allowing them to select a value for the filter from a dropdown and then filtering the view from there.
Answer: The filters in views and how they are exposed to the user reacts a bit differently depending on the type of filter that is used. The type of filter that used, is controlled by defining the data to views using hook_views_data and hook_views_data_alter. This is a bit code heave and not always something you need to do your self as many modules including views does a lot of this for you.
Two common filters used is

views_handler_filter_in_operator
views_handler_filter_string

The two are are fundamentally different because their assumptions and requirements are very different.
The first one, is the one that you would like to use. It's used when you store a value that has a defined list of possible values. An example could be content types which is the example that @Danielle used in her post. Since nodes can't have any random value for their content type, it's possible for views to display a list of checkboxes in the Admin interface when using this filter and a select list / multiple select list for the user when it is exposed.
The second one is used when a string is stored in the database. Using nodes as an example, the title field would be a good candidate for such a filter. Since titles can be any text, it doesn't make sense to expose title selection of a node as checkboxes or select lists, instead you get some other options like you are seeing in your view. You can filter by if the string contains a word (beginning /end / somewhere), it's length etc.
If the one that did the views integration didn't bother using the in_operator type of filter, and describe to views (by using a php function) which options are available, you will have to do it using hook_views_data_alter.
What you need to do is:

Create a subclass of views_handler_filter_in_operator
Implement get_value_options
Tell views about your new handler.

In code it would look like this
/**
 * Define my custom in_opeator
 */
class my_custom_in_operator extends views_handler_filter_in_operator {
  // overwrite the get_value_options function.
  function get_value_options() {
    if (isset($this->value_options)) {
      return;
    }
    $this->value_options array('option_1' => t('Option 1'), 'option_2' => t('Option 2'));
  }
}

/**
 * Implements hook_views_data_alter().
 */
function my_custom_views_data_alter(&$data) {
  $data['entity_type']['property']['filter']['handler'] = 'my_custom_in_operator';
}

And you're done. In reality it's actually quite simple. But finding out how to do is not as views is quite complex.
Comment: Googletorp ( & @Martin Duys) great answer, thanks ! I tried and placed code in MODULENAME.views.inc but got no result. With what am I suppose to replace entity_type & property in $data['entity_type']['property'] ? node and field name ?
Comment: @googletorp i did same according above with one change $this->value_options =array('option_1' => t('Option 1'), 'option_2' => t('Option 2')); but i am unable to find this in exposed view filter.
Answer: Are you allowing multiple values in your exposed filter?  If so, the selections will appear in a select box with a scroll bar by default. If you force single selection only, your exposed filter will appear in a drop-down by default.  I hope this helps!
Comment: I think you have it, but where do I allow multiple values?
Comment: Have a look at [this screenshot](http://polarityweb.com/proposal/files/select-filter.PNG) from an example exposed content type filter I have implemented for my client to manage content on the website.  Unchecking multiple yields your dropdown.
Comment: Sorry to be a pain, but where did you go to get that screenshot? Views | Select the View | Displays | Filter Criteria | and then?
Comment: No worries!  [Here is a screen](http://polarityweb.com/proposal/files/exposed-filter.PNG) of the whole Filter Criteria dialog box.  Note the "expose filter to visitors" in the upper left corner.
Comment: Weird. [My Screenshot](http://dl.dropbox.com/u/9480491/views_screenshot.png) looks totally different to yours? Where do I go to allow those multiple values? I am on version 7.x-3.0-rc1 by the way.
Comment: @Martin - that's because his field type is `Entity Reference` not `Text` like yours.


Sources for specific identities of spherical Bessel functions and spherical harmonics

Question: I need to solve the following integral:
$$\int_0^1 j_\ell(z_{n\ell}x)\:j_{\ell'}(z_{n'\ell'}x)\:x^4 \text{d}x$$
where $j_\ell$ is the $\ell$-th spherical Bessel function of the first kind, and $z_{n\ell}$ is the $n$-th root of $j_\ell$.
I'm looking for a source that can indicate a way to calculate these integrals. I cannot find them in the usual online sources (Wikipedia, Mathematica,etc).
The problem with the spherical Bessel integral is that it needs a recursive relation between the $j_\ell(z_{n\ell}x)$ and $_\ell(z_{n'\ell}x$ which is not at all trivial. Any thoughts?
Comment: I would ask this type of question in physics stack exchange. During my time at university i've never seen such integrals in math courses, but of course in physic courses for example in quantum mechanics and subsequent coourses.
Comment: @Fakemistake Ok, I'll wait, if not I'll migrate the question.
Answer: The spherical Bessel function can be defined from the Bessel function as ([1], see equation 1):
\begin{equation}
j_{n}(z)=\sqrt{\dfrac{\pi}{2z}}J_{n+\frac{1}{2}}(z)
\end{equation}
I think that from this equation one can establish a recurrence relation using the original Bessel functions. Additionally, we have the following result ([1], see equation 5):
\begin{equation}
\int_0^{2\pi}\int_0^\pi\: Y_\ell^{m}(\varphi,\theta) Y_{\ell'}^{*m'}(\varphi,\theta)\sin(\varphi)\text{d}\varphi\text{d}\theta=\delta_{ll}\delta{mm}
\end{equation}
References
[1] Baddour, N. (2010). Operational and convolution properties of three-dimensional Fourier transforms in spherical polar coordinates. JOSA A, 27(10), 2144-2155.
Comment: Yeah the relationship with Bessel functions is very useful. I can do the I integral when the argument is the same. But I need a relationship between the zeros when the argumentes are not the same.


Making a unit test (c#) in Visual Studio 2010. What I'm doing wrong? The test fails always

Question: I have one form: FormPrincipal.cs
In this form there is a public method called InsertionSort() taking 2 parameters: a int[] (representing a integer list) and a int represeting the size (number of elements) of the list.
This function simply orders the list using the algorithm "Insertion Sort"
The method doesn't return anything (because in the logic of my application the list is just ordened and as an array is a point then the original list is just modified to be in the right order).
I'm trying to test if the function order the list.
I created a Unit Test in Visual Studio (not as a separate project) but it always says "failed" without displaying any message. What I'm doing wrong?
The code is like the following:
 [TestMethod()]
    public void InsertionSortTest()
    {
        FormPrincipal target = new FormPrincipal(<some parameters>);
        target.loadData(); // function which load the list to be ordered
        int[] list1 = new int[10];
        list1 = {1,4,3,5,2,6,7,9,8,0);
        target.InsertionSort(list1,10);
        bool listaOrderedOrNot = isListOrdered(list1, 10); // isListOrder is just a function in the same file of the test where I loop the array checking if elements are growing.
        Assert.Inconclusive("A method that does not return a value cannot be verified.");
        // I tried to do the following assert command..
        Assert.AreEqual(listaOrderedOrNot, true,"ordered");
        Assert.IsTrue(listaOrderedOrNot, "ordered");
        Assert.IsFalse(listaOrdenadaOrNot, "NOT ordered");
    }

I suppose it may depends from the fact InsertionSort() doesn't return anything but Visual Studio doesn't give errors and no message (for example "ordered" or "NOT ordered") is printed.
The test just fails when I run it
Thank you for any help
Answer: Remove Assert.Inconclusive("A method that does not return a value cannot be verified.");.
This basically tells VS that you didn't implement your test.

When you have an array you can simply use array.Length to get the size of the array, there is no need to pass the size.

Your sort algorithm doesn't belong into the form class.
Comment: thank you . I've done exactly what you told me but same problem
Comment: But now you should get a "real" error message. Maybe you need to double click the failed test to see it.
Comment: what do you mean? the sort algorithm is a public method in FormPrincipal
Comment: BTW: You don't need all three of you Asserts. Use either one of the first two, the third one is wrong.
Comment: @dragonmnl: what corresponds your latest question to?
Comment: I'm looking right now the result. good suggestion. I will tell you :)
Comment: I solved my problems resolving problem with code (thank to your suggestion).


unexpected token else javascript

Question: all else statements give an unexpected token error
var men = 50;
alert("You are a Spartan warrior about to be fighting in the Trojan War, you get onto             your ship and set sail with a fleet of other ships but your ship breaks away from the others in a horrible storm! You have 50 men on your ship, do not lose more than 40 of them, or else.");
var start = confirm("are you ready to start?");
if (start = true) {
   alert("your platoon of Spartan soldiers is on a ship, headed for Troy");
}
else {
   alert("You failed in your mission and are executed in Sparta the next day (refresh the page)")
};
var hydra  = prompt("you encounter a large hydra on your journey to Troy, do you sail past it, or fight it?(fight or flee?)");
if (hydra = "fight") {
   alert("You kill the Hydra, but it has killed 8 of your men");
};
else {
   alert("You go around the Hydra, but it snatches up 6 of your men and starts to follow your ship!");
};
if (hydra = "fight") {
   men = 42
}
else {
   men = 44;
};
console.log(men);

Answer: First thing (not a syntax error, but wrong anyway): Compare using == instead of =.
Your syntax error is that you're using ; after the if blocks – remove those.
Comment: You should probably replace `=` with `===` to prevent any unexpected type conversions creeping in. See here: http://stackoverflow.com/a/359509/111219
Answer: The unexpected token error is because you end the else's with }; but should only be }
Comment: To be more accurate, he ends the ifs with them.
Answer: replace  if (start = true) with  if (start == true) instead. And }; but should only be }

unexpected token else javascript


How to Loop through the List in VB.NET

Question: I have a list which is filled with a data fetched from DB.
My Code:
 Dim lst As New List(Of MyClass)
 lst = GetData()

MyClass looks like the following:
Public Class MyClass
   Public Overridable Property Id as Integer
   Public Overridable Property Questions as String
   Public Overridable Property Comments as String
End Class

I am trying to loop the lst
 For Each item As String In lst
   'Some data manipulation
 Next

But I am unable to loop it through using the above code.It throws following error:
Value of Type 'MyClass' cannot be converted to 'String'
Whats arong here? Any Help?
Thanks in advance.
Comment: lst is a List with objects of type MyClass, and you are trying to iterate them as Strings
Comment: It's a list of `MyClass` not `String`
Answer: Try this
 For Each item As MyClass In lst
   'Some data manipulation
 Next

How to Loop through the List in VB.NET


Create lists of permutations of size N from elements of another list

Question: How do I, given a List = [(1,1),(1,2),(1,3),(1,4)], N = 2, create a list containing the multiple ordered permutations of List, size N:
permutations([(1,1),(1,2),(1,3),(1,4)],2,ListOut).
 ListOut=[[(1,1),(1,2)],[(1,1),(1,3)],[(1,1),(1,4)],[(1,2),(1,3)],[(1,2),(1,4)],[(1,3),(1,4)]]
??
Comment: What have you tried so far?
Comment: You could restrict it to the size you want by specifying a list of unknowns using `length/2`: `length(Permutation, 2), permutation(List, Permutation).` assuming you have a `permutation/2` that does what you want.
Comment: There are lots of solutions; you can look at lots of existing questions to see how you can do it, for instance [this one](https://stackoverflow.com/questions/10366638/prolog-permutation-function).
Comment: @DanielLyons I don't know how to do it in Prolog, I did it in C, which is quite easy. Prolog has permutations, but I don't know if I can/how to use it in a smaller size than the original structure. Meaning, that I could clearly use permutations on my original List and then select the first N elements of the permutated lists and that would be it, but how do I do it in Prolog?
Comment: That permutation/2 is the problem :b
Answer: First let's solve the problem of finding one permutation:
perm(_, 0, []).
perm([X|Xs], N, [X|Ys]) :- N1 is N-1, perm(Xs,N1,Ys).
perm([_|Xs], N, Y) :- N>0, perm(Xs,N,Y).

There are two recursive rules: 1) X can be the first element of the output, and find the remaining permutation of N-1 for the rest of the list; 2) skip the first element, and find the permutation over the remaining elements of the input list.
Finding all permutations is just about using findall/3:
permutations(X, N, Y) :- findall(Z, perm(X, N, Z), Y).

Test:
?- permutations([(1,1),(1,2),(1,3),(1,4)], 2, X).

X = [[(1, 1),  (1, 2)], [(1, 1),  (1, 3)], [(1, 1),  (1, 4)], [(1, 2),  (1, 3)], [(1, 2),  (1, 4)], [(1, 3),  (1, 4)]].
Comment: Why do you need the cut?
Comment: The cut is "needed" for termination because the second clause does not have a guard `N > 0`. That guard would be a better idea than the cut.
Comment: The cut was not really needed. I needed to add the condition `N>0` in the last rule to avoid generating the same result in multiple ways. (now fixed)


t test in R to see if mean 1 is lower than mean 2

Question: How do I compute a test in R to see if, in the AML group of the golub dataset, the mean expression value for gene 808 is lower than the mean expression value for gene 1042?
Answer: Assuming that the data are approximately normal and the sample sizes
are moderately large, there should be no problem using a t test to
test $H_0: \mu_{808} = \mu_{1042}$ against $H_0: \mu_{808} < \mu_{1042}.$
I will use fake data because I do not have immediate access to your real data, but
the method of doing the test in R would be the same. I would use the Welch
two-sample t test, because I have no reason to suppose that the two 'expression values' have the same variance.
<code>set.seed(1310)
x.808 = rnorm(500, 55, 7)
x.1042 = rnorm(450, 57, 8)
t.test(x.808, x.1042, alt="less")

        Welch Two Sample t-test

data:  x.808 and x.1042
t = -3.5065, df = 905.96, p-value = 0.0002382
alternative hypothesis: true difference in means is less than 0
95 percent confidence interval:
       -Inf -0.9124708
sample estimates:
mean of x mean of y
 55.11405  56.83431

boxplot(x.808, x.1042, col="skyblue2", pch=20, names=c("808","1042"))
</code>

The two boxplots look similar, but sample sizes are large enough to distinguish between the two means. Notice that the boxplots show some 'outliers', but
this is to be expected with normal samples of this size. The presence of
a few (fairly near) outliers is no contraindication for using the Welch t test.


How does an NTP host switch among the various modes?

Question: The NTPv3 RFC describes five operating modes:

Symmetric Active (1): A host operating in this mode sends periodic
  messages regardless of the reachability state or stratum of its peer. By
  operating in this mode the host announces its willingness to synchronize
  and be synchronized by the peer.
Symmetric Passive (2): This type of association is ordinarily created
  upon arrival of a message from a peer operating in the symmetric active
  mode and persists only as long as the peer is reachable and operating at
  a stratum level less than or equal to the host; otherwise, the
  association is dissolved. However, the association will always persist
  until at least one message has been sent in reply. By operating in this
  mode the host announces its willingness to synchronize and be
  synchronized by the peer.
Client (3): A host operating in this mode sends periodic messages
  regardless of the reachability state or stratum of its peer. By
  operating in this mode the host, usually a LAN workstation, announces
  its willingness to be synchronized by, but not to synchronize the peer.
Server (4): This type of association is ordinarily created upon arrival
  of a client request message and exists only in order to reply to that
  request, after which the association is dissolved. By operating in this
  mode the host, usually a LAN time server, announces its willingness to
  synchronize, but not to be synchronized by the peer.
Broadcast (5): A host operating in this mode sends periodic messages
  regardless of the reachability state or stratum of the peers. By
  operating in this mode the host, usually a LAN time server operating on
  a high-speed broadcast medium, announces its willingness to synchronize
  all of the peers, but not to be synchronized by any of them.

It seems to me, though, that any host except a leaf node would probably be in several modes. For example, I might have a local area network with three NTP servers, each in Symmetric Active (1) mode with respect to one another. They would also each be clients (3) of one of the many public stratum two time servers. Lastly, they would all server as servers (4) to the many local clients.
Is the point that they're only in a given mode for a moment during the synchronization? If so, how does a host know to switch? I'm only looking for enough depth here to discuss the issue in an educated manner, not to write a custom time server.
Comment: They are association modes, not node modes.
Answer: Operating mode does not describe how the daemon functions in general, rather it is a description of an association (normally an association between two computers).  Check the aragraph right before the modes you listed:

Except in broadcast mode, an NTP association is formed when two peers
  exchange messages and one or both of them create and maintain an
  instantiation of the protocol machine, called an association. The
  association can operate in one of five modes

For information about association modes in ntpv4 see:
http://www.eecis.udel.edu/%7Emills/ntp/html/assoc.html


What does ∇∇:Q mean?

Question: I'm reading a paper from the 1960's on Electromagnetism, and I wanted to know what the symbol ∇∇:Q (where Q is the Electric Quadrupole) means. Is this just the Laplacian? See Below .
Comment: Peraphs $\nabla^2$? Do the textbook use CGS unit?
Answer: The expression is $\nabla \nabla : Q$. I suspect that $:$ refers to the dyadic "double dot-product", so that
$$
\nabla \nabla = \pmatrix{
\frac{\partial^2}{\partial x^2}
& \frac{\partial^2}{\partial x\partial y}
& \frac{\partial^2}{\partial x\partial z}\\
\frac{\partial^2}{\partial y\partial z}
& \frac{\partial^2}{\partial y^2}
& \frac{\partial^2}{\partial y\partial z}\\
\frac{\partial^2}{\partial z\partial x}
& \frac{\partial^2}{\partial z\partial y}
& \frac{\partial^2}{\partial z^2}
},
$$
and $\nabla \nabla : Q = \sum_{i,j = 1}^3 \frac{\partial^2Q_{ij}}{\partial x_i\partial x_j}$, where $x_1 = x, x_2 = y, x_3 = z$.

What does ∇∇:Q mean?


Problema com Fast Colored TextBox (indentação)

Question: Estou modificando um projeto de código aberto criado por Pavel Torgashov, chamado Fast Colored TextBox, e estou tendo problemas com a linguagem VB no editor, pois os métodos e propriedades são indentados dentro das Interfaces...

Invés de ela ficar assim:

Está assim:

E o resto do código dentro dessa FCTB fica indentado para frente. Aqui está o código original do parágrafo VB (Em C#) (Extraído da classe SyntaxHighlighter):
    protected void VBAutoIndentNeeded(object sender, AutoIndentEventArgs args)
    {
        //end of block
        if (Regex.IsMatch(args.LineText, @"^\s*(End|EndIf|Next|Loop)\b", RegexOptions.IgnoreCase))
        {
            args.Shift = -args.TabLength;
            args.ShiftNextLines = -args.TabLength;
            return;
        }
        //start of declaration
        if (Regex.IsMatch(args.LineText,
                          @"\b(Class|Property|Enum|Structure|Sub|Function|Namespace|Interface|Get)\b|(Set\s*\()",
                          RegexOptions.IgnoreCase))
        {
            args.ShiftNextLines = args.TabLength;
            return;
        }
        // then ...
        if (Regex.IsMatch(args.LineText, @"\b(Then)\s*\S+", RegexOptions.IgnoreCase))
            return;
        //start of operator block
        if (Regex.IsMatch(args.LineText, @"^\s*(If|While|For|Do|Try|With|Using|Select)\b", RegexOptions.IgnoreCase))
        {
            args.ShiftNextLines = args.TabLength;
            return;
        }

        //Statements else, elseif, case etc
        if (Regex.IsMatch(args.LineText, @"^\s*(Else|ElseIf|Case|Catch|Finally)\b", RegexOptions.IgnoreCase))
        {
            args.Shift = -args.TabLength;
            return;
        }

        //Char _
        if (args.PrevLineText.TrimEnd().EndsWith("_"))
        {
            args.Shift = args.TabLength;
            return;
        }
    }

OK, então daí eu converti o código para VB, e agora no meu projeto se encontra desse jeito:
    'end of block
  If Regex.IsMatch(args.LineText, "(^\s*)End (Sub|Function|Property|Set|Class|Enum|Module|Structure|Namespace|Interface|Get)\b", RegexOptions.IgnoreCase) Then
     args.Shift = -args.TabLength
     args.ShiftNextLines = -args.TabLength
     Return
  ElseIf Regex.IsMatch(args.LineText, ".*(:|: |: )(End (If|While|Try|With|Using|SyncLock|Select)|EndIf|Next|Loop)\b", RegexOptions.IgnoreCase) Then
     args.ShiftNextLines = -args.TabLength
     Return
  End If
  'start of declaration
  If Regex.IsMatch(args.LineText, $"(^\s*|| )({dAttribute}) \b(Sub|Function|Property)\b ", RegexOptions.IgnoreCase) Then
     args.ShiftNextLines = args.TabLength
     Return
  End If
  If Regex.IsMatch(args.LineText, $"(^\s*|| )({dAttribute}) \b(Class|Enum|Module|Structure|Namespace|Interface|Get)\b|(Set\s*\()", RegexOptions.IgnoreCase) Then
     args.ShiftNextLines = args.TabLength
     Return
  End If
  ' then ...
  If Regex.IsMatch(args.LineText, "\b(Then)\s*\S+", RegexOptions.IgnoreCase) Then
     Return
  End If
  'start of operator block
  If Regex.IsMatch(args.LineText, "(^\s*|:|: |:  )(If|While|For|Do|Try|With|Using|SyncLock|Select)\b", RegexOptions.IgnoreCase) Then
     args.ShiftNextLines = args.TabLength
     Return
  End If

  'Statements else, elseif, case etc
  If Regex.IsMatch(args.LineText, "(^\s*|:|: |:  )(Else|ElseIf|Case|Catch|Finally)\b", RegexOptions.IgnoreCase) Then
     args.Shift = -args.TabLength
     Return
  End If

  'Char _
  If args.PrevLineText.TrimEnd().EndsWith("_") Then
     args.Shift = args.TabLength
     Return
  End If

...e o problema persiste. Lembrando que, aceito respostas em C#.
Comment: Não seria identado ao invés de indenizado?
Comment: A pergunta está confusa. No inicio você diz que está modificando o projeto original, mas depois parece que está construindo um editor que usa o componente e o seu código é para configurar o componente dentro desse editor. Pode melhorar a pergunta para deixar mais claro para que serve esse componente e em que parte você está com problema?
Comment: Corrigido.... obrigado
Comment: Qual é o editor que está usando? Visual Studio? Não é bastante claro na sua explicação.
Comment: Sim, é o Visual Studio 2015.
Comment: Desculpe @Pagotti, eu descontinuei o desenvolvimento do projeto.
Answer: Você quer apenas corrigir a identação?
Ctrl+K+D

Caso queira uma ferramenta que faça isso em várias páginas ou até no projeto inteiro, recomendo o CodeMaid, 100% free
http://www.codemaid.net/
Existe também o Resharper, mas ele é pago, e utilizar ele apenas para essa finalidade é como comprar uma Ferrari para ir na Padaria.


Got new ice skates and instantly got much worse. Why/what should I do next?

Question: I recently replaced a pair of very old, used figure skates with some inexpensive Bauer hockey skates because I heard those were better and I had the opportunity to go out on a skating "ribbon" while visiting friends.
I can normally skate on a rink in a slightly wobbly way but without falling unless a child falls in front of me or something. In the new skates, I got out on the ice and instantly felt much less in control. I only fell a few times on the more difficult "ribbon" but the afternoon ended for me with a hard wipeout onto my knees and wrist--I'm not even sure how it happened.
Skating lessons may not be practical for me where I live now and I'm trying to sort out what is different about the new skates. They don't cinch tight over the toes so I think I have less awareness of how the blade is oriented in line with my foot. Without the toe pick, I think the blade starts further back on my foot so that my wipeout may have been caused by my bringing my foot down too perpendicularly and tripping myself. Also, I think these skates may be much, much better sharpened than my old clunkers, since we got them at a real hockey shop.
My knees are still smarting and purple a week later and I don't want to start chickening out so I'd appreciate any advice on what to be aware of or look for next time I'm out.
Comment: I really do know how bad your knees must be from the same experience.  Get knee pads.  A good sporting goods store or a skating boarding store will have some.  If you don't want anyone to know you are wearing them they can be worn under sweat pants.  Consider wrist guards too.  Broken bones are waaay less cool as an adult than as a kid.
Answer: It's not surprising at all, and actually completely normal, that you had trouble with your transition from one skate to another.  Here's why:
Figure skates and hockey skates are completely different styles of skates.  Figure skate boots can have a higher heel which would put your foot at more of an incline than a hockey skate.  Figure skate blades tend to be a little flatter than hockey skate blades.  And of course there's that toe pick.  Kids who start out on figure skates, then transition to hockey skates, can find it a little difficult at first, especially if they relied on the toe pick for balance, stopping, and acceleration.  And vice versa, kids who start out on hockey skates, then transition to figure skates, can find themselves tripping over the toe pick.
You also mentioned your new skates were sharper.  This could effect your ability to stop if you are used to having dull skates.
All it will take is time on the ice to get used to your new skates.  Even going from an old figure skate to a new figure skate, or an old hockey skate to a new hockey skate, even if they are the same brand and model of boot takes a little time.  Leather is stiffer on the new skate, the new boot hasn't conformed to the shape of your foot, and blades are at their original manufactured height as opposed to thinner due to being sharpened hundreds of times.
So just get out on the ice at a local rink regularly and you'll be used to your new skates in no time.
Also, if you want to speed the break in process a little for your new skates, you can try "baking" your skates (How do I bake my Bauer skates?).  This may help soften the leather a little and help the skate conform to the shape of your foot.
Answer: I've played hockey my entire life, but can't speak with much experience about figure skating. Although, I do know the two are quite a bit different. Figure skates are designed for swift and seamless movement, while hockey skates are more rigid and designed to take more of a "beating". These fundamental differences result in changes to all aspects of the skate, from the material used for the liner, to the shape of the blade. It makes sense that you'd have trouble switching from one to the other, but with more experience, I'm sure you'll find you can skate in either.


Por que minhas páginas de erro personalizada não estão sendo chamadas?

Question: A minha página de erro personalizada não está sendo chamada.

SO: Linux Ubuntu
PHP 7 / Laravel 5.5
Já criei a pasta "resources/errors" e nela o arquivo "404.blade.php"
Já dei permissão no SO para a pasta
Já usei os comandos "php artisan cache:clear" e "php artisan view:clear".
Troquei no arquivo .env a opção "debug" para false.

Enfim, essas foram as ações que eu tomei.
Answer: Eu acho que à partida o erro está no path para a pasta errors, esta deve estar em resources/views/errors.
Exemplo para teste:
 - Cria ficheiro 404.blade.php dentro da pasta que mencionei acima
 - Aceder a um url que não esteja definida em app/HTTP/routes.php ou routes/web.php (em versões mais recentes do Laravel) e confirma se vai para esta nova pag 404.blade.php
A partir daí podes personalizá-la como quiseres.
Comment: Miguel foi exatamente isso. Eu li a documentação e não me atentei a este detalhe. Realmente o arquivo deverá ficar em "resources/views/errors".
Muito obrigado!
Comment: De nada @AlexandroSantos


How many real roots of $f(x)=x^{12}-x^9+x^4-x+1$ between $0$ and $1$?

Question: How can we know if $f(x) = x^{12} - x^9 + x^4 - x + 1$ has How many real roots between 0 and 1. ?
Okay so at both 1 and 0 the value of function is 1. So there can be no or even roots between
 them so how can we tell can we use calculus ?
Comment: Adapt your title (existence of a real root) to your text (number of roots)....
Comment: In general, you can use calculus to see where there are turning points, and then substitute point at which the function is stationary into $f(x)$, and see whether this is positive or negative. However in this example you get an 11th degree polynomial so I am not sure if this is useful.
Comment: Yeah exactly and btw Why did you write your name john doe ?
Comment: @RaghavSingal why not?
Comment: No thats correct I am sorry its none of my business.
Comment: That's ok, no worries :)
Answer: If $0<x<1$ then
$$f(x)=1-x+x^4-x^9+x^{12}=1-x+x^4(1-x^5)+x^{12}>0$$
Comment: Yeah but it is specific to this equation as it can be factorised but this is not a general method it cant work always.
Comment: @Raghav Singal Yes, of course, but it would another problem.
Comment: So isn't there like a theorem for this or like some calculus method ?
Answer: $\begin{cases}
f(x)=x^{12}-x^9+x^4-x+1 \\
f'(x)=12x^{11}-9x^8+4x^3-1 \\
f''(x)=132x^{10}-72x^7+12x^2=12x^2(11x^8-6x^5+1)=12x^2g(x) \\
g'(x)=88x^7-30x^4=x^4(88x^3-30)
\end{cases}$
And we can stop here, because we are only interested in the signs of the derivatives.
$a=\sqrt[3]{\frac{30}{88}}$
$\begin{array}{|c|ccccc|}
\hline
x & 0 && a && 1\\
\hline
g'& 0 & - & 0 & + & 58 \\
\hline
g & 1 & \searrow & \simeq 0.62 & \nearrow & 6 \\
\hline
f'' & 0 && + && 72\\
\hline
f' & -1 && \nearrow && 6 \\
\hline\end{array}$
So there exists $b\in]0,a[$ such that $f'(b)=0$.
$\begin{array}{|c|ccccc|}
\hline
x & 0 && b && 1\\
\hline
f'& -1 & - & 0 & + & 6 \\
\hline
f & 1 & \searrow & f(b) & \nearrow & 1 \\
\hline
\hline\end{array}$
From there you can calculate $b$ by dichotomy $b\simeq 0.6746$ and then compute $f(b)\simeq 0.51245>0$.
We are dealing with polynomial here, so continuity is assured and abrupt variations excluded so we can be quite confident that $f>0$ on $[0,1]$.
Now, if you want to pursue the algebraic proof, you'll have to substitute $b$ : we know that $bf'(b)=12b^{12}-9b^9+4b^4-b=0$
So $12f(b)=(9b^9-4b^4+b)+12(-b^9+b^4-b+1)=-3b^9+8b^4-11b+12$
And then carry on with this lesser degree equation until you get $f(b)>0$.
You wanted a general method without tricks, you got one.


Can be GenerationType.SEQUENCE optimized to not to perform query to sequence on every ID update?

Question: When I use
<code>@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE
)
private Long id;
</code>
Does it mean, on every entity creation ORM framework makes a query to DB to update sequence table? Can it be optimized, e.g. by chunks?
Answer: @GeneratedValue further exposes an option to define a generator :
<code>@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_generator")
@SequenceGenerator(name="id_generator", sequenceName = "id_seq", allocationSize=50)
private Long id;
</code>
Enabling this , Hibernate will allocate a batch of 50 ids per session.This batch will be then prefetch for a range of 50 which can provide better performance.
There are still some additional things to be considered , such as , if a session is closed/killed prematurely we will lose the allocated sequence ids.
The following deep-dive talks more about the caveats/soltions : https://www.jpa-buddy.com/blog/the-ultimate-guide-on-db-generated/


Trying to black out everything outside of a moveable div

Question: I wrote a hover zoom plugin and I'm trying to figure out how to dark out everything outside of the hover zoom box, and make the zoom box itself transparent, but am having a tough time trying to figure out what I need to do for it. Do I use opacity? Do I use a background image?
Right now it's just showing a white .5 opacity on top of a darker black opacity bg, but I'm kinda scratching my head trying to figure this out. Any suggestions would be super helpful.
What I'm trying to do:

Demo: jsfiddle
Comment: Sounds like a job for CSS masks, although you may have to sacrifice some browser support: http://www.webkit.org/blog/181/css-masks/
Comment: @MikeRobinson Oh wow :( this is exactly what I need but it's a bummer it's webkit only. Thanks for the info.
Answer: Here's an example of a solution, but it requires you to make a couple of changes.
If you set the zoom square to have a background image the same as the underlying image and adjust its background-position by css to be the negative of its position relative to the original image... am I explaining this correctly?
http://jsfiddle.net/moopet/Be9AA/
The important part is
var left = Math.min(Math.max(relX - 100, 0), $origImg.width() - $zoomBox.width()),
    top = Math.min(Math.max(relY  - 100, 0), $origImg.height() - $zoomBox.height());

$zoomBox.css({
    left: left,
    top: top
});

$zoomBox.css({ backgroundPosition: (-left) + "px " + (-top) + "px" });

And I've set the background of the zoom element in the CSS for the fiddle, but if you needed to do this for multiple images you could do it in JS by just copying the src attribute.
Comment: Very clever solution. I've started first to play with additional background image...


Distributing integers on a tree .

Question: We have an undirected tree with N vertices and we want to distribute integer numbers starting from 1 to N such that every parent element has smaller element than it's child .The root vertex is 1 .
In how many ways we can distribute the numbers ?
Example :
Let's say we have 3 vertices in the tree and they are connected like this .
1 2 (1 is connected with 2).
1 3 (1 is connected with 3).
So the Ans for this will be 2 . Because we can write 2 on vertex 2 and 3 on vertex 3 or we can write 3 on vertex 2 and 2 on vertex 3 . So total number of ways is 2 .
Actually the formula is n!/(s1s2...sn) . Where si is the the size of the subtree rooted at vertex i .
But I don't know how to prove it .
Can anybody provide the proof for the same .
P.S :
Let's say the tree contains 5 vertices and they are connected like this .
1 2.
1 3.
1 4.
2 5.
The no. of ways for this tree will be 5!/(5*2*1*1*1) = 12 .
Answer: You can prove this by induction on the size $n$ of the tree.
Notice that after writing $1$ on the root, we can divide the remaining $n-1$ labels among the root's immediate subtrees however we want. If these subtrees have sizes $k_1,\dots,k_m$, then the number of ways to do this is the multinomial coefficient $\binom{n-1}{k_1,\dots,k_m}=\frac{(n-1)!}{k_1!\cdots k_n!}$. After choosing this allocation, we have subtrees of sizes $k_1,\dots,k_m$ to label. By induction hypothesis, the number of ways to label a tree of size $k<n$ is $\frac{k!}{s_1\cdots s_r}$ (where the $s_i$ are the sizes of the subtrees of that tree, including $k$ itself), so the total number of ways to label our $n$-tree is
$$\frac{(n-1)!}{k_1!\cdots k_n!}\cdot\frac{k_1!}{s\cdots s}\cdots\frac{k_m!}{s\cdots s}=\frac{n!}{n\cdot s\cdots s}$$
where the "$s$" values in the denominator are the sizes of all our subtrees except $n$ itself.
Answer: This was a problem from Atcoder Programming Contest held yesterday (though actual problem needed re-rooting additionally). I actually participated in that contest, and here is my approach to this problem.
Consider a slightly different situation. We try with a random permutation of $1, 2, \dots n$ and compute probability of getting a valid one. We then multiply that probability with $n!$ since we have total $n!$ permutations.
If $a$ is a ancestor (in a tree) of $b$, we have a constraint for our permutation - that $a$ must come up before $b$.
For example, consider $a$ having $b, c, d$ in it's subtree (which order of b, c, d does not matter). Then, in our permutation, $a$ must come before $b, c, d$. Probability of being so is $\frac{1}{4}$ since all permutation of $a, b, c, d$ is equally likely and we have 6 of them sufficing $a > (b, c, d)$ (in order of permutation). This is where $ 1 / s_i$ comes up.
Then observe that for each node, this process is independent. $a$ coming up before $b$ does not change probability of $b$ coming up before $c$.
Comment: @joriki Thanks for pointing it out. I actually meant that in my mind but I wrote it in a wrong way... My argument holds because we only consider that permutation of subtree.
Comment: $+1$, nice solution. The last sentence isn't quite right – $a$ coming up before $b$ does change the probability of $b$ coming up before $c$; what you're actually using is that $a$ coming up before $b$, $c$ and $d$ doesn't change the probability of $b$ coming up before $c$.

Distributing integers on a tree .


How to avoid module specific jQuery plugin script running globally?

Question: This is my first time working with Drupal (Drupal 7).
I've created a jQuery plugin which populates a target div. The target div is added to the node via panelizer.
I only want to run the script for when it's needed. Just now it runs all the time. Even on the dashboard, this causes script errors.
I'm not sure what the best approach is for this.
EDIT (SOLUTION):
Thanks for the input. I decided to use a Javascript approach.
var elementExists = document.getElementById('target');

if (typeof(elementExists) != 'undefined' && elementExists != null) {
  // Script
} else {
    return;
}

Comment: you can write your script as block and display it when needed and exlude for admin
Answer: From my experience it's usually best to leave this check to JS and don't bother on PHP side. Of course it all depends on your definition of best, but benefits I see are:

It's easy and stable to test for div existence with $("#myid"), opposed to more mysterious tests in PHP. Now you know that this div will appear when X is true and Y == Z. Will you remember that in two months?
Sure, we have comments. But will future developer understand what you meant? Will you be disciplined enough to write them, and do it really clearly?
It's easier for caching - if you aggregate your scripts, you will use the same aggregated file for pages with and without div, so one less check / download for browser
It lessens the chance for conflict between your module and other ones.

Modules shouldn't just overwrite [#attached] array, but I encountered some that did.
If you are using drupal_add_js instead, making sure test for conditions is run when it is supposed to might be hard, if other modules will try to reorder hooks. So this isn't a sure way to avoid problem described above.
Various caching systems might miss the conditions you use. Probably nothing as severe as Boost and Mobile Tools issue, but risk is there.
Theme shouldn't need to know about blocks - if you will leave test to theme, point above will not apply, but you risk crashes whenever theme is switched or block is disabled. Testing for it on both sides will add a lot of code.
And I'm sure there are other things I simply never encountered yet.

Of course you could say most of those are bugs in other modules, and you would be right, but being right does not help if you need your site up and running.
It's easier to quickly see scripts added via .info file than to search code for drupal_add_js or attached or... you see, there are many ways to do it in code, happy hunting if you are new developer and need to find where this one script came from.
Comment: For the first point, that is why we have comments in code. :) Could you expand the point about module conflicts? I think that would be an interesting one, since most of the users would not think of that.
Comment: @kiamlaluno added some. Best I could do this evening.
Answer: In template.php add this code:
function mytheme_preprocess_html(&$variables) {
  $theme_path = path_to_theme();
  $path = drupal_get_path_alias();
  if($path == 'my/path') {
      drupal_add_js($theme_path . '/js/example.js');
    }
}

Answer: As alternative solution you may use tracking code.
That would allow you to load JS or anything else only on specific pages.
It would also give you overview what and where you run extra stuff.
Like this:


Android SMS API

Question: I know that the SMS content provider is not part of the public API (at least not documented), but if I understand correctly it's still possible to use many of the SMS features as long as you know how to use the API(?).
E.g it's pretty straightforward to insert an SMS into your inbox:
 ContentValues values = new ContentValues();
 values.put("address", "+457014921911");
 contentResolver.insert(Uri.parse("content://sms"), values);

Unfortunately this does not trigger the standard "new-SMS-in-your-inbox" notification. Is it possible to trigger this manually?
Edit: AFAIK the "standard mail application (Messaging)" in Android is listening for incoming SMSes using the android.permission.RECEIVE_SMS permission. And then, when a new SMS has arrived, a status bar notification is inserted with a "special" notification id.
So one solution to my problem (stated above) could be to find, and send the correct broadcast intent; something like "NEW SMS HAS ARRIVED"-intent.
Edit: Downloaded a third party messaging application (chompsms) from Android market. This application satisfies my needs better. When i execute the code above the chompsms notice the new sms and shows the "standard status bar notification". So I would say that the standard Android Messaging application is not detecting sms properly? Or am I wrong?
Answer: Unfortunately the code responsible for these notifications is hidden in the messaging application. The class MessagingNotification has a static method updateAllNotifications that you could call using a PathClassLoader and reflection:
PathClassLoader c = new PathClassLoader("/system/app/Mms.apk", getClassLoader());
Class.forName("com.android.mms.util.ContactInfoCache", true, c)
    .getMethod("init", Context.class).invoke(null, context);
Class.forName("com.android.mms.transaction.MessagingNotification", true, c)
    .getMethod("updateAllNotifications", Context.class).invoke(null, context);

This is obviously a very bad idea for several reasons but I can't think of another way to do what you described.
Answer: Could you trigger a PUSH notification after the SMS?
Thread: Does Android support near real time push notification?
Answer: Maybe you should replace
content://sms

with
content://sms/inbox

Comment: No difference; SMS appears in the inbox. But still no nice sms notification :) –

Android SMS API


On groups with presentations $ \langle a,b,c\mid a^2=b^2=c^2=(ab)^p=(bc)^q=(ca)^r=(abc)^s=1\rangle $...

Question: $$
\langle a,b,c\mid a^2=b^2=c^2=(ab)^p=(bc)^q=(ca)^r=1\rangle =\Delta(p,q,r)
$$
This is a presentation of a triangle group $\Delta(p,q,r)$, a special kind of Coxeter group.
EDIT In fact, these are called extended triangle groups, by G. Jones and D. Singerman in Maps, hypermaps and triangle groups...
What about the following presentation:
$$
\langle a,b,c\mid a^2=b^2=c^2=(ab)^p=(bc)^q=(ca)^r=(abc)^s=1\rangle
$$
Do these groups have a name and where are they treated?
The presentation in question are motivated by this and that...
ANOTHER EDIT
if $p=q=r$ is prime and $s=1$ this is called triangular Fuchsian group here...
Comment: Have you come across generalised triangle groups? What I call a triangle group is the group of transformations of the tiled plane (no reflections); Wikipedia calls these von Dyck groups. Such groups have presentation $\langle x, y, x; x^p, y^q, z^r, xyz\rangle$, and here $ab=x$, $bc=y$ and $ca=z$. A *generalised triangle group* is a group with presentation $\langle x, y, x; x^p, y^q, z^r, W(x, y, z)\rangle$. Fine and Rosenberger wrote a whole book motivated by these groups and their generalisations (one-relator products). Jim Howie has also written a lot about them.
Comment: @user1729 you mean $$? Do you have some explicite references or links to them?
Comment: Yes, $x, y, z$. When I google the first link is to a paper of Jim Howie (http://www.macs.hw.ac.uk/~jim/preprint27.pdf). The references look extensive. I am pretty sure he gave a talk on these at a conference in 2012 I was at. The book of Fine and Rosenberger is "Algebraic generalizations of discrete groups: a path to combinatorial group theory through one-relator products".
Comment: @user1729 why not posting this as an answer...
Comment: Instead of editing this old post again, you might be better asking a new question about your new edit. If you think Derek Holt's answer is insufficient then you could consider asking on MathOverflow.
Comment: @user1729, sorry, and I just realised that Derek points out exactly what I edited...
Comment: @user1729 but you're right. I did: https://math.stackexchange.com/q/3819674/19341
Answer: I haven't come across a name for this family in full generality, but the special case in which $p=2$ was defined and studied by Coxeter in his paper
H. S. M. Coxeter, The abstract groups $G^{ m, n, p}$, Trans. Amer. Math. Soc. 45 (1939),  73-150.
where (in your notation) the group is called $G^{q,r,s}$.
Also, when $s$ is even, your group has a subgroup of index $2$ with presentation $\langle x,y \mid x^p=y^q=(xy)^r=[x,y]^{s/2} \rangle$.
These groups were studied in the same paper by Coxeter, and denoted $(p,q,r;s/2)$.
Both of these families have been extensively studied since then, in particular concerning their finiteness. They are generally infinite for sufficiently large values of the parameters, and there is just a handful of remaining cases for which their finiteness is still unknown.
A few years ago Havas and I showed, using a big computer calculation, that $(2,3,13;4)$ is finite of order $358\,848\,921\,600$. So your group with $(p,q,r,s) = (2,3,13,8)$ has twice that order.
Comment: +1 great the paper is [available online](http://www.ams.org/journals/tran/1939-045-01/S0002-9947-1939-1501984-9/S0002-9947-1939-1501984-9.pdf) and for free
Comment: hmmm: when I replace $A,B,C$ in the definition of $G^{m,n,p}$ by $A=x/y, \; B=y/z,\; C=z/x$ and use that $x^2=y^2=z^2=1$ (so they are self-inverse) I get: $\langle (xy)^m=(yz)^n=(zx)^p=x^2=y^2=z^2=(\frac xy \frac yz \frac zx)^2=1 \rangle$, where the triple product is trivial. Now it looks just like the triangle group. What have I done (wrong)?
Comment: Maybe you are interested: The presentation in question are motivated by [this](http://math.stackexchange.com/q/1622906/19341) and [that](http://math.stackexchange.com/q/1640803/19341)...
Comment: Help you with what?