Edit a merge commit with git rebase

Question: In Git when I have commits eg. A - B - C and I want to edit the B commit, I

use git rebase -i ,
in the list I write edit command in front of B commit,
git rebase stops right after B commit so I can fix anything I want using git commit --amend,
and then I continue using git rebase --continue.

As far as I know this is the best practice how to do this. With this method I can edit any commit in the past (as long as it hasn't been pushed to remote branch yet), and moreover with -p flag I can even preserve the merges. This is just great.
My current problem is: I did a mistake (typo) on one line in a merge commit (while resolving a conflict when merging two branches).
I'd like to fix it but I don't know how to make git rebase to stop at a merge commit. The git rebase -p -i <blah> list ignores merge commits, so I cannot write edit command in front of it and make the git rebase stop there to let me edit it.
Any help please?
I just want to fix this line in the merge commit while preserving all the commits (and merges) after it.
Thanks.
Answer: Updated answer for 2020:
You can force git rebase -i to stop at the merge commit via the break command (added in Git 2.20). You can then edit the merge commit as desired via git commit --amend.
Detailed steps:

Run git rebase -i --rebase-merges $ancestor_of_merge_commit
Find the merge commit you want to edit in the todo list.
Insert a new line after the merge commit that contains only break (or b).
Save your changes and exit your editor. Git rebase will check out the merge commit, print something like the following, then return you to your prompt:
Stopped at fb91fab (Merge branch 'foo' into bar)

Use git commit --amend to edit the merge commit as desired.
Run git rebase --continue when you are done editing the merge commit.

Alternative approach if you do not have any merge commits after the commit you want to edit:

Run git rebase -i $id_of_merge_commit
Insert a new line at the top of the todo list that contains only break (or b).
Save your changes and exit your editor. Git rebase will check out the merge commit, print something like the following, then return you to your prompt:
Stopped at fb91fab (Merge branch 'foo' into bar)

Use git commit --amend to edit the merge commit as desired.
Run git rebase --continue when you are done editing the merge commit.

Original answer from 2012 (pre-break):
Git does not make it easy to do interactive rebases when merges are involved.  The -p option uses the -i mechanism internally, so mixing the two doesn't really work.
However, git rebase is just an automated way to do lots of cherry-picks.  You can replicate its behavior by manually cherry-picking to get a bit more control over the process.  It's less convenient and more prone to human error, but possible.
This is the approach I suggest:

use git rebase to get to the commit after the merge (the child of the merge)
use git reset --hard HEAD^ to manually get to the merge
use git commit --amend to repair the merge
use git cherry-pick to get back to the commit after the merge
use git rebase --continue to finish

Here are the specific steps:

Note the SHA1 ID of the merge commit you want to modify.  For discussion, suppose it is deadbeef.
Note the SHA1 ID of the commit right after the merge commit you want to modify (the merge commit's child).  Suppose it is facef00d.
Run git rebase -i deadbeef.
Select facef00d for editing.
When rebase returns you to a prompt to edit facef00d, run git reset --hard HEAD^.  You should now be at deadbeef (git rev-parse HEAD should print deadbeef).
Make your edits to fix the incorrect merge conflict and use git add to stage them.
Run git commit --amend to fuse the staged fix with the bad merge commit.  The result will now have a different SHA1 (not deadbeef).
Run git cherry-pick facef00d to apply the changes made by facef00d to the fixed merge commit.
Run git rebase --continue to finish.
Comment: Nice. I don't mean the process, but the description. :D
Comment: So basically I get to the `facef00d` with `git rebase`, then I get to the `deadbeef` _manually_, fix what I need, and get back to `facef00d` to finish the rebasing.
I was googling this for a few hours and found nothing. Thanks!
Comment: @vsechnech:  Exactly.  I like your high-level description, so I modified my answer to include it.
Comment: Nice! Note that one simple way of noting the SHA1 values is to make temporary branches or tags at them.
Comment: @Cuadue: `rebase` refuses to run if there is uncommitted work, so there is no risk of destroying uncommitted work if you follow this procedure.
Comment: Can't steps 1,2 and 4 be avoided by using break before the first commit?
Basically, ``git rebase -i merge-commit-sha``, then b at the very top, then amend the merge commit and ``git rease --continue``.
Comment: `git reset --hard` carries the risk of destroying uncommitted work. Can you do this without the hard reset?
Comment: It is error-prone, but actually pretty safe: if I screwed up in any step before the last, I can always get back with `git rebase --abort` and start over. I just need to double-check (very carefully) *right before* the last step.
Comment: Great answer, when it works. I just had one (admittedly rare) scenario where this was horribly inefficient, and added an answer with an easy workaround.
Comment: Your 2020 edit is pretty much a copy of my answer.
Answer: This is much easier now with the --rebase-merges option available in Git 2.22 and above. This option preserves the merge topology, and works with interactive rebases.
It'll look something like this, assuming B is the merge commit to amend:
label onto

... some branch definitions ...

reset onto
merge -C B branch-name # Merge branch 'B' into whatever
pick C

You can now insert a b (or break) in between the merge and the pick:
merge -C B branch-name # Merge branch 'xyz' into whatever
break
pick C

At the break commit --amend the merge, and then continue the rebase.
This also works with a fixup commit. For example, lets say the commit with the fix for the merge is D. You can move your fixup commit D to immediately after the merge commit:
merge -C B branch-name # Merge branch 'xyz' into whatever
fixup D
pick C

See the Rebasing Merges section of the git-merge man page.
Answer: May be easier to create a fixup commit 'D' then use 'git rebase -p -i <blah>' to reorder 'D' right after 'B' and squash it into 'B'.
pick A
pick B  <- merge commit to ammend
fixup D
pick C

Comment: _I don't know how to make `git rebase` to stop at a merge commit_ is the OPs issue, and mine also. The method you described was my first approach, but I could not get the merge commit to show up in the list to pick.
Answer: tl;dr: Sometimes you simply shouldn't use git rebase to edit a merge commit. Another method may be more efficient.
I just lived through one such scenario: I had a merge commit which was merging in a very old branch, and there were many conflicts that were resolved in the merge commit. There were some additional commits after the merge, and then it was discovered that a mistake was made in the large merge commit during one file's conflict resolution. I setup the interactive rebase as described in the accepted answer, but when my machine locked up at 2/59 I realized it was writing a lot of files due to re-organizing my file system to match the old branch. After a few minutes I killed it, aborted the rebase, then had to delete 100K files to get back to where I started. Instead of rebase I did this instead:

Make note of the commit IDs I want to replay after I fix the merge commit.
git reset --hard [merge-commit-id]
Make the change and simply amend the HEAD commit (which is the merge commit).
Cherry pick each of the commit IDs in order after the merge commit, or use git rebase --onto with 3 arguments to cherry pick the entire range if there are more than just a few.)

This was much faster.

Edit a merge commit with git rebase


solutions of Differentially uniform mappings for cryptography

Question: Kaisa Nyberg provided a proof of number of zeros in inverse mapping in finite field ref. The proof is clear for me except the final step where  she proved that the following equation has two solution when n is odd in $GF(2^n)$ and 4 solutions when n is even:
$x(x^3 +\alpha^3)= 0$
Q1) she applied $gcd(3,2^n-1)=1$ for her proof. could you please explain how to use gcd in finding zeros in $GF(2^n)$?
Q2) I extended her approach to apply for $(x+\alpha)^{-2} - x^{-2}=\beta$ and obtained $x^{2}(x^6 +\alpha^6)= 0$  in $GF(2^n)$ . I got stuck to prove the number of zeros when n is odd and even. i took this approach to understand the mathematical motivation taken for one of the Aria cipher sbox ($x^{247}=x^{-8}$). could you please help me to continue proof number of solutions?
Answer: Q1
From the equation
$$
x(x^3+\alpha^3)=0
$$
we know that one of the roots is $x=0$, for the rest we want to solve
$$
x^3+\alpha^3=0 \Longleftrightarrow x^3 = -\alpha^3 = \alpha^3
$$
If $g$ is a generator of $GF(2^n)$, then $\alpha = g^v$ for some integer $0\leq v < 2^n-1$ (since $\alpha\neq 0$). We may also write $x=g^u$ for some integer $0\leq u<2^n-1$, so the equation becomes
$$
g^{3u} = g^{3v} \in GF(2^n) \Longleftrightarrow 3u\equiv 3v \pmod{2^n-1}
$$
Now if $3$ does not divide $2^n-1$, which is where the $\gcd(3,2^n-1)=1$ comes from, then we can multiply by inverse of $3$ to get
$$
u \equiv v \pmod{2^n-1}
$$
Since both $u,v$ are in $[0,2^n-1)$, there is only 1 distinct root possible, which is $u=v$. This is the obvious root $x=g^u=g^v = \alpha$. Hence there are only two roots in total, $0$ and $\alpha$.
I think it is quite common to shorten these type of argument like the following:

Let $G$ be a cyclic multiplicative group with order $m$ and $\alpha\in G$. Then
  $$x^k = \alpha^k$$
  has only 1 root if $\gcd(k,m)=1$".

For the other case where $3\mid 2^n-1$, let $m=2^n-1 = 3d$. The equation is now
$$
\begin{align}
3u &\equiv 3v \pmod{3d}\\
u &\equiv v \pmod d
\end{align}
$$
Let $r\equiv v \pmod d$ such that $0\leq r < d$. Then $u$ can take 3 solutions $u=r, r+d, r+2d$. Since $0\leq r,r+d,r+2d < 3d = 2^n-1$, we know that the elements $g^r,g^{r+d},g^{r+2d}$ are distinct. So we have 4 roots in total: $x=0,g^r,g^{r+d},g^{r+2d}$.
Finally: When $n$ is odd $3$ does not divide $2^n-1$ so by the first part there are two solution. Otherwise $n$ is even, $3$ divies $2^n-1$ so by the second part there are four solutions.

The text writes $d=(2^n-1)/3$ and suggests that the two other roots are $x=\alpha^{1+d}$ and $x=\alpha^{1+2d}$. Now these roots do satisfy the equation, say:
$$
x^3+\alpha^3 = (\alpha^{1+d})^3+\alpha^3 = \alpha^{3+m}+\alpha^3 = \alpha^3 + \alpha^3 = 0
$$
(Since $\alpha^m=1$ by Lagrange's Theorem.) The same happens for $x=\alpha^{1+2d}$. However I don't think it's quite right since these roots can be repeated, for example if $\alpha=1$ then following the text you get the roots $0,1,1,1$. Using the method above you first get $\alpha = 1 = g^0$, then the roots are $0,g^0,g^d,g^{2d}$. Maybe I am missing some context where repeated roots cannot happen.

Q2
Similarly, for the equation
$$
x^2(x^6 + \alpha^6)=0
$$
we see immediately a (repeated) root of $x=0$. The rest of the roots lie in
$$
x^6 + \alpha^6 = 0
$$
Since the field is characteristic two, we have
$$
(x^3+\alpha^3)^2 = x^6+\alpha^6 = 0
$$
Therefore we are reduced to
$$
x^3 + \alpha^3 = 0
$$
This has exactly the same roots as before, depending on whether $n$ is odd or even.


Drupal 8 group filter conditions using views query filter

Question: I'm facing an issue while applying filter in drupal 8 views.
I have created a view of records where i showed content using filter conditions. Basically, I want to add a filter using AND/OR conditions in views filter.
Currently, There are multiple AND/OR conditions in our views filter. If i chang any Condition from AND to OR, subsequent conditions are also getting changed to the same.
Requirement is:
Condition Between first & second group will be 'AND' . Condition from second & third will be OR.
How to do it in views?
Check screenshot for more reference:
Answer: Instead of clicking to add a new filter, click on the little arrow that brings down more options: and/Or Rearrange. Choose that one and you can set up the logic kind of like in this image below:: use highlighted area :: Create new filter group


Logistic Regression and Dataset Structure

Question: I am hoping that I can ask this question the correct way.  I have access to play-by-play data, so it's more of an issue with best approach and constructing the data properly.
What I am looking to do is to calculate the probability of winning an NHL game given the score and time remaining in regulation.  I figure I could use a logistic regression, but I am not sure what the dataset should look like.  Would I have multiple observations per game and for every slice of time I am interested in?  Would I have one observation per game and fit seperate models per slice of time? Is logisitic regression even the right way to go?
Any help you can provide will be very much appreciated!
Best regards.
Comment: Tough question! My guess is that it would help to know more than I do about counting processes (and more than Wikipedia does: http://en.wikipedia.org/wiki/Counting_process )
Comment: Do you have access to the ASA journal Chance?  Seems to me there was a relevant article appearing in the last year or so, whether about hockey or another sport.
Comment: I try to reformulate the problem (to stimulate discussion ?): Let's say we have a set of discrete states in a game (e.g. in tic-tac-toe). Now it is reasonable to create one model per state (maybe using logistic regression) to predict the outcome. Now HERE we have also a game, but with continuous states (i.e. game time). The question now of the OP is: How to a) discretize the time into finite set states or b) how to build a model whose parameters vary depending(!) on the current game-time. There must be someone who has already solved this "general" problem.
Answer: Do a logistic regression with covariates "play time" and "goals(home team) - goals(away team)". You will need an interaction effect of these terms since a 2 goal lead at half-time will have a much smaller effect than a 2 goal lead with only 1 minute left. Your response is "victory (home team)".
Don't just assume linearity for this, fit a smoothly varying coefficient model for the effect of "goals(home team) - goals(away team)", e.g. in R you could use mgcv's gam function with a model formula  like win_home ~ s(time_remaining, by=lead_home). Make
lead_home into a factor, so that you get a different effect of time_remaining for every value of lead_home.
I would create multiple observations per game, one for every slice of time you are interested in.
Comment: Be careful with the non-independence generated by including multiple time-slices. A random effects (multi-level) model could help.
Comment: @ Eduardo: I agree that the dependence is not modelled and that this is somewhat problematic, thanks for pointing it out. I'm not sure how random effects would help -- since the binary outcome `win_home` is constant at the level of grouping (i.e. for all time slices for any given match it's either 0 or 1), including, e.g. a random intercept, for the matches will just result in huge problems with separation in this context.
Comment: Great!  Thanks for the help.  I was going to use R, and was going to setup the data similar to how you suggested, interaction effects and all.  Glad to see I was on the right track, and I do really appreicate your time.
Comment: You might also want to consider including a parameter for total goals scored, as leads tend to be given away more easily in high scoring games.
Answer: I would  start simulating the data from a toy model. Something like:
n.games <- 1000
n.slices <- 90

score.away <- score.home <- matrix(0, ncol=n.slices, nrow=n.games)

for (j in 2:n.slices) {
  score.home[ ,j] <- score.home[ , j-1] + (runif(n.games)>.97)
  score.away[ ,j] <- score.away[ , j-1] + (runif(n.games)>.98)
}

Now we have something to play with. You could also use the raw data, but I find  simulating the data very helpful to think things through.
Next I would just plot the data, that is, plot time of the game versus lead home, with the color scale corresponding to the observed probability of winning.
score.dif <- score.home-score.away

windf <- data.frame(game=1:n.games, win=score.home[ , n.slices] > score.away[, n.slices])

library(reshape)
library(ggplot2)

dnow <- melt(score.dif)
names(dnow) <- c('game', 'time', 'dif')
dnow <- merge(dnow, windf)

res <- ddply(dnow, c('time', 'dif'), function(x) c(pwin=sum(x$win)/nrow(x)))

qplot(time, dif, fill=pwin, data=res, geom='tile') + scale_color_gradient2()

This will help you find the support of your data, and give you a raw idea of what the probabilities look like.
Answer: Check out the stats nerds at Football Outsiders as well as the book Mathletics for some inspiration.
The Football Outsiders guys make game predictions based on every play in a football game.
Winston in Mathletics uses some techniques such as dynamic programming as well.
You can also consider other algorithms such as SVM.


Is it possible to play a low A on a recorder

Question: I know this is a ridiculous question, but thought I'd ask anyways since I saw an article on wikihow for a low B. http://www.ehow.com/how_5210357_play-low-recorder.html
I need a lower A than the one with 2 top holes(and the bottom hole) covered. It would allow me to play a lot of songs in the lower scale
Comment: If your playing a recorder in C, that is impossible. The tutorial you linked to is for a recorder in F.
Comment: To continue along the lines of what @luserdroog is saying, I'd suggest checking out this video, begin at 2:20, http://www.youtube.com/watch?v=T4eR719RhhY
Comment: Using a sub-subcontrabass recorder you can play very low A:s. ;-P
Comment: To move it from *impossible* to *really hard*, ... You need to physically increase the length of the instrument. What about some sort of attachment? An inch or two of pipe held in a frame that you can walk up to and stick the recorder on it to produce the *trick note*. [It's 12:46AM here now: imagination time.]
Comment: @ReinaAbolofia is somehting like this available on the market?
Comment: @SomeshMukherjee no it is not. You would need to make it yourself out of pvc pipe.
Answer: The first question I would ask is which recorder are you playing on? The soprano and tenor recorders can go as low as C and the sopranino and alto recorders go down to low F. In the link you shared, I believe they are discussing an alto recorder. That being said, if you want to finger a low A on an alto recorder, cover the left hand holes as described in the link, then add the right hand index and middle fingers.
You can find a nice interactive fingering chart for C recorders and F recorders at these links. Just be sure to use the correct chart for the instrument you are playing.
If you are ever confused about which type of recorder you are playing, the difference is mostly just in the size. The most common recorder is the Soprano. If you have a tuner or piano, you can check the key of the recorder (whether it is a C or F recorder) by playing the note that covers all the holes and see which pitch comes out.
Comment: Thanks, it seems you are correct. In that case, I'd just suggest OP use an alto recorder instead of a soprano.
Comment: The only way your are going to get a low A out of a C recorder is to add more piping to the instrument. I'd highly suggest just getting an alto recorder.
Comment: I believe OP is asking for "trick fingerings", like covering the bottom hole, to produce an A below the lowest C on a C recorder (probably a soprano unless OP has extremely long fingers :-)
Comment: I have a Soprano C recorder. Trick Fingerings would be fine
Comment: I actually want something on a C recorder. Soprano. The fingering matches this one.  http://www.hrs.hampshire.org.uk/finger/cfinger.html
Comment: Okay, will give alto a try. I liked the range of C recorders. Just need two notes extra
Answer: Not on the soprano recorder, because it's tuned in C and going below it hits the physical limit of the instrument. Only low B is achievable by playing like the low C but partially covering the bottom recorder hole with your knees, but not well tuned.
Due to the limited range and cheap price, recorder players should try to learn playing on recorders of multiple sizes.
For reference, here are many examples and the note ranges:

reference: pitch of A4 has a frequency 440 Hertz (may be slightly different depending on the recorder). Lower notes have lower frequency values (ex: A3 is 220 Hz, C4 is ~261 Hz), higher notes have higher frequency values (ex: C6 is 1046 Hz).

Bass recorder: F3 to G5

Tenor recorder: C4 to D5

Alto recorder: F4 to G6

Soprano recorder: C5 to D7

Sopranino recorder: F5 to G7

Garklein recorder: C6 to D8

Restating your question using scientific pitch notation, you have the soprano recorder, with the lower note being C5 and you want to play A4. That's not possible, you'd need an alto, tenor or bass recorder.
A picture with 6 recorders follows: from left to right, the bass, tenor, alto, soprano, sopranino and garklein recorders.
The final suggestion is to acquire an alto recorder: it's cheap, has a good range for playing popular music, can be switched back and forth with the soprano, it's not too big and it's able to play the desired note (A4).

Here's a link to a video of a musician playing the alto recorder, so that you can see its size and hear the sound:

J.S.Bach : Gigue, BWV 1006, alto recorder:
Answer: I remembered that there are some exotic trick fingerings to go high, but I also had a memory of seeing a low one used by some really good players.
After a bunch of looking I found it - here is a link:
http://www.wfg.woodwind.org/recorder/rec_alt_1.html
Look for the first entry - the e on an f recorder or the b on a c recorder.
I just tried it - tricky to get it exactly in pitch. But it does work. I couldn't get it lower than a half step. You cover all holes and then partially cover the bell hole with your leg. Very useful for that darn piece of music that goes to the tonic with a leading tone at the low end! Although, of course, you look ridiculous.
Here is a link for some of the exotic high notes:
http://www.recorderhomepage.net/technique/fingering/the-third-octave
Jack
ps - thanks to Todd Wilcox for pointing out that I can edit my formerly erroneous posting.
Answer: First, be aware that recorders only transpose by the octave.  To go on a tangent for a moment, saxophones all transpose so that their standard range is (written) Bb3 to F6.  They are alternately pitched in Bb and Eb, but always read the same.  The recorder family is similar, being alternately pitched in C and F, but rather than transpose so they all play the same, they only transpose by the octave, so soprano and tenor play C4-C6 while alto and bass play F4-F6 with the same fingerings.
If your goal is to play a low (concert) A, then the obvious choice is to use a lower recorder.  I'm assuming you have a soprano; get an alto and learn the offset fingerings.
All woodwinds can artificially lower their lowest note by about a half step by blocking the bell, limited only by the practicality of doing so.  But you're not going to be able to go further than that.  Another trick is to put something (usually a rolled up piece of paper) in the bell to physically extend the instrument, but this only converts your lowest note into a lower one.  Meaning, if you added [I'm guessing about 2 inches of] paper to achieve a low A, then you wouldn't be able to play your normal low C, or B or Bb for that matter, which is probably not practical.


Difference between $\frac{x^2} {a^2}+\frac{y^2}{b^2} +\frac{z^2} {c^2} = 1$ and $\frac{x^2}{a^2} + \frac{y^2}{b^2} +\frac{z^2}{c^2}\leq 1$?

Question: Is the volume of the ellipsoid $\dfrac {x^2} {a^2} + \dfrac {y^2} {b^2} +\dfrac {z^2} {c^2} = 1$ the same as the volume of $\dfrac {x^2} {a^2} + \dfrac {y^2} {b^2} +\dfrac {z^2} {c^2} \leq 1$?
Comment: The volume of the first ellipsoid is $0$.
Answer: Strictly speaking, the equation $\frac{x^2}{a^2}+\frac{y^2}{b^2}+\frac{z^2}{c^2}=1$ defines the boundary of $\frac{x^2}{a^2}+\frac{y^2}{b^2}+\frac{z^2}{c^2}\leq 1$. The volume of the first equation is 0. You could think of the first equation as an empty ellipsoid shell and the second equation as a filled in ellipsoid.
This is similar to the unit circle being defined by $x^2+y^2=1$, but the filled in unit circle being defined by $x^2+y^2\leq 1$.


Task Scheduled Powershell Script Not Shutting Down machine

Question: I have a task running on a Hyper-V server setup as such:
schtasks /CREATE /TN AutoShutdown /RU "SYSTEM" /TR "Powershell \"C:\AutoShutdown.ps1\"" /SC ONSTART

It runs properly (as far as I can tell) however the script has a line to shutdown the computer and it never does.
start-sleep 120
while (1) {$vm = get-vm; if ($vm.state -ne "Running") {stop-computer} else {"Running..."; start-sleep 10}}

If I run the task in user space:
schtasks /CREATE /TN AutoShutdown /TR "Powershell \"C:\AutoShutdown.ps1\"" /SC ONLOGIN

It runs perfectly.
Comment: If someone is logged in, stop-computer will not execute.
Answer: stop-computer needs the -force flag to work I guess when running as a process.  Switching to stop-computer -force fixed the problem.


What methods can be used to pick the optimal kernel smoothing width parameter

Question: Kernel smoothers for a function f(x) usually have a parameter which control the width of the region which is used to smooth the value of the function, say at a point $f(x_0)$. For example, the Gaussian kernel
$$
K_\sigma(x) = e^{-\frac{{ \left( {x - x_0 } \right)^2 }}{2\sigma ^2 }}
$$
has width parameter $\sigma$ which is the standard deviation.
A choice of greater width increases bias but reduces variance with respect to the variance of the function values surrounding $f(x_0)$, where as a choice of smaller width reduces bias but increases the variance.
What methods can be used to pick the optimal value for the width parameter when using a kernel smoother?
Comment: I had decent results using AIC with smoothing splines.  The approach might be extensible to kernels.
Answer: The simplest two methods to compute the bandwidth for kernel smoothing are the following.

Silverman's rule from B.W. Silverman. "Density Estimation for Statistics and Data Analysis". Chapman and Hall/CRC, 1986.
$$
h = \left(\frac{R(k)}{\sigma_k^4}\frac{8\sqrt{\pi}}{3}\right)^{\frac{1}{5}} \hat{\sigma}_n n^{-\frac{1}{5}}.
$$
where $\hat{\sigma}_n$ is the sample standard deviation, $\sigma_k^4$ is the standard deviation of the kernel $k$, $R(k)$ is the rugosity of the kernel. This is based on the assumption that the distribution is gaussian. The previous equation comes from computing the rugosity of the second derivative of the gaussian distribution.
In  M.P. Wand and M.C. Jones. "Kernel Smoothing". Chapman and Hall/CRC, 1994, the sample standard deviation is replaced with the robust estimator
$$
\hat{\sigma}_{IQR} = \frac{IQR}{\Phi^{-1}(0.75) -\Phi^{-1}(0.25).}
$$
where $\Phi^{-1}$ is the quantile of the gaussian standard distribution and $IQR$ is the interquartile range :
$$
IQR = \hat{Q}_3 - \hat{Q}_1
$$
where
$$
\hat{Q}_3 = q(0.75), \qquad \hat{Q}_1 = q(0.25),
$$
are the empirical quantiles of level 0.25 and 0.75.

Chapter 3 of (Wand, Jones, 1994) is on this topic.
An interesting method is the "solve-the-equation" rule with two stages due to Sheather and Jones, 1991 (see page 74 in (Wand, Jones, 1994).
Answer: A variety of methods can be used and some of them are specific to your application (for instance you might be looking for some misclassification rate of a classifier using the smoothed estimated).
Nevertheless most of the time the methodology employed is CV (cross-validation) or GCV (generalized cross-validation). See  Generalized Cross-Validation as a Method for Choosing a Good Ridge Parameter (1979) by Golub et al for a first read.
You are essentially looking at hyper-parameter selection problem and this is far from solved. See for example the paper on On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation (2010) by Cawley and Talbot for a fresher look on the subject.
Comment: Thank you for your answer. Could you please elaborate on how misclassification rate is used in the context of kernel smoothing?
Comment: Sure. There are case that one uses a smoother to "smooth out" the noise from the data and then use that data for classification. In that case one might choose the smoothing parameter based on the misclassification rate the classifier using that data rather than the GCV score the smoothing matrix might command.


Language of Grammar

Question: Let $G = (V,T,S,P)$ be the phrase structure grammar with $V = \{0,1,A,S\}$, $T=\{0,1\}$, and a set of productions $P$ consisting of:
$S \to 1S$
$S \to 00A$
$A \to 0A$
$A \to 0$
What is the language generated by G?
I know how to start it by creating a derivative tree. And I have also created it. My only problem is that I don't know how to use that information to answer the question. Can someone help?
Answer: Here's a fairly systematic way to approach such problems, at least when the grammar is relatively simple. Note first that you must begin with $S\to 1S$ or $S\to 00A$. Once you apply the latter production, however, you can never apply the first. Thus, any derivation must start with some number $m\ge 0$ of applications of $S\to 1S$ followed by an application of $S\to 00A$:
$$S\overset{m}\Longrightarrow 1^mS\Longrightarrow 1^m00A\;.$$
From this point on the only productions that can be applied are $A\to 0A$ and $A\to 0$. The derivation won't terminate until you apply $A\to 0$, but before that you can apply $A\to 0A$ any number $n\ge 0$ times (and that's all that you can do):
$$S\overset{m}\Longrightarrow 1^mS\Longrightarrow 1^m00A\overset{n}\Longrightarrow 1^m000^nA\Longrightarrow 1^m000^n0\;.$$
Thus, $G$ generates $\{1^m0^{n+3}:m,n\ge 0\}$. You can easily write a regular expression for this language: $1^*0000^*$ (or $1^*0^*000$, or $1^*00^*00$, or $1^*000^*0$).
Answer: It looks like the language is $1^{*}000(0)^{*}$. Notice we can have no $1$'s present; and if we do, we can keep revisiting $S$. To terminate, we need to visit the $S \to 00A$ rule to get to the $A$ rules. Then we can keep tacking on $0$'s or terminate with one additional $0$.

Language of Grammar


Linear Transformation $T_{A}$ Is invertible $\iff$ A Is invertible

Question: Let $T_{A}$ be the linear mapping corresponding to the matrix A, and $A \in F^{n*n}$
$T_{A}$ Is invertible $\iff$ there is $T_{A}^{-1}$ so $T_{A} \circ T_{A}^{-1}=I $  $T_{A} \circ T_{A}^{-1}(v)=v$ $\iff$ the matrix $I=A*A^{-1} $ $\iff$ A must be invertible
Is this proof is valid?
Comment: Two questions: What is $T_A$ and what is your question?
Comment: I still don't understand $T_A$ (and I don't really know what $A$ is either). Is it perhaps the linear mapping corresponding to the matrix $A$, given some bases for the spaces? Are all matrices suppose to be square matrices? Can you give more detail?
Comment: @JoonasIlmavirta sorry, $T_{A}$ linear transformation represented by the matrix A, I am looking to verify my proof (Added), thanks
Comment: @JoonasIlmavirta you are right, I am really sorry, added the relevant information
Answer: If you know that matrices and linear mappings are in one-to-one correspondence, $T_I=\text{id}$ and $T_A\circ T_B=T_{AB}$ for any square matrices $A$ and $B$, then the proof is simple.
If $A$ is invertible, then $T_{A^{-1}}T_A=T_{A^{-1}A}=T_I=\text{id}$ and similarly $T_AT_{A^{-1}}=\text{id}$, so $T_A$ is invertible.
On the other hand, if $T_A$ is invertible, there is a matrix $B$ so that $T_A^{-1}=T_B$.
(This where I use the one-to-one correspondence and the fact that the inverse of a linear mapping is linear.)
Then $T_I=\text{id}=T_A\circ T_B=T_{AB}$, so (again by the correspondence) $AB=I$.
Thus $B=A^{-1}$.
(We have actually proved that $T_A^{-1}=T_{A^{-1}}$.)
About your proof:
I have hard time following your reasoning.
Writing $A^{-1}$ already implies that $A$ is invertible, so the end of the reasoning doesn't make much sense.
Also the role of $v$ is not quite clear.
To show that two things are equivalent, it very often is a good idea to do the two directions separately.
It helps make the presentation clearer, and that is very, very important.
Final words:
I don't mean to be overly harsh.
I thought you would rather hear this here now than from your exam's grader later, not only because you can easily ask for clarification here.
Answer: The proof is not correct. Hidden in there is the assumption that $(T_A)^{-1} = T_{A^{-1}}$, which you have not proved.


c++ istream operator >> expecting arbitrary input type

Question: I have a task where I expect random input of chars or ints. Is there any way I can understand what is coming next and say cin >> int, or cin >> char. I want to do it with the istream operator >>, because they told us not to do it with a parser. To be precise, I expect an input of a prefix expression. So I don't know when to read an operator, when to read a number. If you have any suggestions I'd appreciate them :)
Comment: read it in as a `std::string` and parse it from there.
Comment: Could you wack up an example to help us with the exact file format? I'm not sure what you mean by the input being a char or an int.
Comment: By `char`, do you mean "not a digit"? (Digits are characters, too.)
Comment: @molbdnilo Yes, thats exactly what I mean :D
Comment: @Bathsheba prefix example: `- * 8 5  + * 20 4 * + 5 8 10`
Comment: @user7091569 May be [this](http://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it) helps you a bit.
Comment: Aren't stacks used for the "prefix" expression?
Comment: @OmidCompSCI yes they are, but how can I understand if I read an operand or an operator?
Comment: @user7091569, it doesn't matter, because you keep pushing to the stack while checking if it is an operand. When it is an operand you pop from the stack two numbers and use the operand.
Comment: @OmidCompSCI so you tell me to push the stack with a broken input? :)
Comment: @user7091569 how is it broken all you are doing is pushing to the stack and checking if there is an operand, once there is an operand you pop the numbers and use the operation with those popped numbers. You always have to check if the number of operands and numbers are suffice to carry out the expression, else you would throw an error. Unless you are validating the users input one character at a time using some do-while or something, but that is usually not what people do.... Let the user enter what they want and carryout the operation, if can't be done print that out to the user.
Comment: @OmidCompSCI how can I predict what to read here: `+ 5 4`  ,`* + 5 4 3`
First time i have operator, operands, next time i have 2 operator, then operands
Comment: @user7091569 lets just assume it is postfix like 54+, so in a stack you put character at a time, so you check if 5 is operand if not push, so your stack has 5. You then check if 4 is operand its not, push, so your stack looks like 5 4. You check if next is operand its a + so you pop the two numbers and it is 5 4, and use the operand 5 + 4 = 9. And you can push that back on the stack if need be and have more operations.
Comment: @user7091569 This is postfix expression, I hope you can understand this and be able to implement it using prefix very similar concept. Of course you should have something where you are making sure there is enough operands or numbers.
Comment: @OmidCompSCI imagine I have a number more then 1 digit, lets say 180. Then I want to divide it by 90. If I work with chars, I would need parser. It is much simpler to use normal operations on `int` right? I think you haven't read my question carefully
Comment: @user7091569 as 'character' I meant everything up to a space correct? So if you had 180 and want to divide by 90, it would look like, 180 90 /. Push 180 push 90 pop 180 90 and use the operand 180 / 90. You would know this if you created your stack class and can change the type of stack you use, instead of character can use strings. Making a generic stack class would be the solution to this.
Comment: @OmidCompSCI then I'd have to use `atoi` for strings, which is not generally what I wanted.
Comment: @user7091569 I see, however atoi is a very reliable built in function, also not relly considered parsing, technically just a typecasting lol, but it is a solution that you can use if none other is out there. Sorry man!
Answer: You can do, without a parser:
int n;
cin >> n;

if (cin.good())
{
    // manage integer
}
else
{
    char c;
    cin.clear();
    cin >> c;

    // manage character
}

Comment: There's more to do to cleanup the stream state etc.
Comment: Upvoted. Possibly the best way, subject to the artificial no-parsing constraint.
Comment: @πάνταῥεῖ edited, is it ok now ? (thanks for remarks ;) )
Comment: Yeah, good solution, except [when you read an integer and then hit EOF](http://coliru.stacked-crooked.com/a/0e47aed78aed49b8). This is in fact a blunt instrument with more failure cases than you can shake a stick at. Don't do parsing like this! /cc @Bathsheba
Comment: @LightnessRacesinOrbit  I don't really understand when `std::cin` can reach end of file
Comment: @LightnessRacesinOrbit Also I agree with you, I always prefer `std::getline` and a parser but OP's requirements is explicitly a solution without parser, just `std::cin`
Comment: @Garf365: It has to eventually. Admittedly the testcase I presented doesn't reproduce for `std::cin` (and off the top of my head I'm actually not sure why that is).


Quadrado não aparece no meu código CSS

Question: Estou dando meus primeiros passos em html e esbarrei em meu primeiro quebra cabeça.
Nesse pequeno "portifólio" que estou fazendo tentei acrescentar a imagem de um quadrado , já tinha feito alguns testes e funcionou muito bem ,mas ao tentar acrescentar a figura no código deste exercício em específico a figura não aparece ....ja tentei colocá-lo em outras posições no código e até agora não funcionou,agradeço muito se alguém poder me dar uma força o código segue abaixo:

body {
  background-color: green;
}

.square {
  height: 20px;
  width: 20px;
  background-color: #555;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Nicolas Amad</title>

<big>Nicolas Amad</big>

Quem sou eu?

 Estudante de Engenharia Mecânica e Análise de Sistemas ,apaixonado pelo poder de criação que a tecnologia oferece, atualmente muito interesado em Desenvolvimento Web/Mobile.

Skills

    HTML

Comment: Seu *HTML* possui dois elementos [``](https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/body). O elemento `` representa o conteúdo de um documento *HTML*. è permitido apenas um `` por documento.
Comment: Muito obrigado Augusto,resolveu meu problema perfeitamente ,ainda me confundo muito em alguns detalhes.
Answer: Olá, boa noite!
Existem alguns erros no seu código que deve se atentar.
1 - O  é o corpo da página, e entre ele deve ficar todo conteúdo ao qual você quer que apareça visualmente na sua página e não pode ser repetido.

2 - Parece que o seu código em CSS está em um arquivo externo. Se estiver, você precisa inserir o link do arquivo dentro da tag .
Assim: <link type="text/css" rel="stylesheet" href="MeuArquivo.css">
Eu editei o seu arquivo, fiz algumas correções. Estude o código e veja no que você errou. São coisas simples. Bons estudos.
 <!DOCTYPE html>

      <meta charset="utf-8">
      <title>Nicolas Amad</title>

<big>Nicolas Amad</big>

Quem sou eu?

 Estudante de Engenharia Mecânica e Análise de Sistemas ,apaixonado pelo poder de criação que a tecnologia oferece, atualmente muito interesado em Desenvolvimento Web/Mobile.

Skills

        HTML

Quadrado não aparece no meu código CSS


Can someone tell me how to solve vector integral questions

Question: Hey I have the following question, but I am not sure how to solve it. Can someone please either show me how to solve this question or give me a link to websites which show me how to solve integrals of vectors and transformation please.
The question is as following:
question
Answer: This is a beginning line integral. All you need to do is plug in stuff.  $$d\mathbf{r} = dx \mathbf{\hat i}+ dy \mathbf{\hat j}$$ and $dy = 2x \; dx$, and $y= x^2$.  Plug in stuff until all the $y$'s are gone and then integrate from $x=0$ to $x=2$.
If you want to google, try "Line integral."


What's the difference between pulse and beat?

Question: Is there a difference between pulse and beat ,I've done my research, and some resources says they're the same, others says they're not,so which assumption is more acceptable?
-From what I've learned, the accentuation of certain beats is what determine the pulse of the piece ,is my assumption correct or not?
-Is the pulse = a single beat or it represent the whole distance between two accented notes?
Sorry for the messy questions,I couldn't find the words to describe what I need to perceive.
Comment: Can you explain more about where you've seen the word "pulse" used? I'm for one not familiar with that word in a musical context.
Comment: @ToddWilcox - Just dug out one of my 'bibles' - the Oxford  Companion to Music (1955), and pulse is described pretty much as I said in my answer earlier. Maybe it hasn't arrived the other side of the pond yet!
Answer: More often than not, they're synonyms. When counting the rhythm of a piece, they are the points at which you may tap your foot, or click you finger. Be aware, though, that people's perception of where a pulse is may vary. Some may clap on 1, 2, 3 and 4. others on 1 and 3, yet others on 2 and 4.
It's all pretty straightforward till we come to complex time, such as 6/8, where often two different feels or counts (call them pulses or beats if you like) are present in the same piece. 1 2 3 4 5 6 is one manifestation; 1 - - 2 - -  is another. And the difference between 2/4/and 4/4 is sometimes not easy to discern, making the pulse or beat a little muddy.
Some refer to a crotchet (quarter note) as a one beat note - I tend to - as it is the basic diet for a lot of rhythms. So in a 4/4 piece - way the most common - it could be said that there are 4 beats to the bar, or the pulse is 1 2 3 4.
Answer: A pulse is the heartbeat of the rhythm/music that you hear - and feel - when listening to music and this is what people usually tap along to when listening. The beat is the repeated note value of the time signature.
They can often (and are usually) the same thing, or at least they cross over. However I shall give some examples:

In a piece with time sig 4/4, the beat is 4 crotchet beats every bar. The pulse is most likely also going to be this however if some notes are more pronounced you may tap your foot 2 beats/bar.
In a piece with time sig 6/8, the beat is 6 quaver beats/bar whereas the pulse is usually 2 beats/notes at intervals of dotted crotchets. It will be felt as: 1-and-a-2-and-a, 1-and-a-2-and-a, etc. where '1' is where you tap your foot, the pulse.
Comment: So a beat is more of a (let's say) measuring utility.while the pulse is what you feel in a song.
Comment: @JaafarJumaa yes exactly!
Answer: The meaning of 'pulse' is fairly set (unless we're going to get silly and bring vegetables into it).  It's the 'click track' behind the music. The heartbeat. Well - the 'pulse'.
'Beat' has a variety of musical meanings.  It can mean the physical gesture made by the conductor.  In some modern 'techno' music it can mean a sampled fragment endlessly repeated. It can be used to approve the rhythmic drive of a piece - you'll hear 'That song has a great beat!' rather than 'That song has a great pulse!'  Not a term used much about 'classical' music, though some of it has an excellent 'beat'!
Comment: Had to upvote this - although it looks like you've bean taking the peas...
Answer: A good way of thinking about it is as a clockwork watch or clockwork mechanism or machine. You could have two watches keeping the same time but with different time signatures. Think of the second hand as the pulse with its tick, tock, tick, tock and the beat as the mechanism driving the second hand as 123, 123, 123, 123. Each tick or tock is supported by three beats. A beat behind the second hand pulse of 1234, 1234, 1234, 1234 would be a 16/4 time signature. A beat that is the same as the pulse 1234, 1234, e.t.c. would be in common time. An old mantelpiece clock could be imagined in cut time 2/2.
That's why trying to determine the time signature of a tune by counting foot taps as beats only works in 4/4 or if you double or half your tap interval to an 8/4 or 2/4, e.t.c. Complex time signatures can't be determined that way. For example, if you tap out a 6/8 jig, you'd fool yourself into thinking it's in 2/8 time, i.e. two beats to every bar whereas you are actually tapping out groups of three beats, 123, 123.
A common question in traditional music that might help is the difference between a jig and a reel. To real (forgive the pun) traditional musicians, who have learned by ear and never seen a musical score, the reply will be something using words; if you can say 'jiggery, jiggery,' to the music, it's a jig and if you can say 'this is how a reel goes, this is how a reel goes,' it's a reel. The jiggery is Ji Ge Ry, 123, beat on the capital letter, and this is how a reel goes is Thisis Howa Reel Goes, 1234. Therefore, a jig is in 6/8 time (usually) 123, 123, i.e. 6 X 8th notes (beats) per bar and a reel is in 4/4 time 4 X 4 notes (beats) per bar.
To understand the 123 grouping think of a waltz which is often (usually in 3/4 time, i.e. three quarter notes per bar. You'll find yourself saying 123, 123, 123, 123 while tapping out the pulse as one tap on the 1 of each 123 grouping.
Answer: Additionally pulse refers to a signal and can contain harmonics. A beat refers more to a tempo (rhythm).
Comment: Not strictly true. So -1. Wish everyone gave downvote reasons!
Answer: In essence Pulse came from/derived from our own Heart Beat. The Accented part of our Heart beat, usually the downbeat in music is the Pulse as in our "Heart beats" rhythmic pattern.
As our Heart Beat is normally constant, so is the Pulse of a piece. Otherwise we would have a chaotic rhythmic structure. Remember Music Is Beautiful, with Form and Grace, It Comes From Our Souls. In order for the Musician/Producer to communicate to the Listener/s in an orderly, clear, Conscice manner., we must have rules(Structures) and grammar(Dynamics, Beats etc.), a universal set of rules as in mathematics, "The Language of Numbers and it's Operations).
Detecting the Pulse of a piece takes practice and patients. What you'll be looking for, or I should say, listening for is the 1st. beat, "the One Beat" in any measure. As I previously mentioned, pulse to my understanding a constant attached to the Time Signature so with this exception to this rule in Mind, it is constant, now change the Time Sig., and you may have a change in the score's pulse. Back to detectng pulse. Once the one has been detected, determine, Time Sig./Meter, synonymous terms. Next listen for the Accented beats, a re-occurring pattern within each Measure. An ex. being a Waltz, it's pulse sounds like One-two-three. The Accented beat is Capitalised for a reason, it is Strong beat while the others are called weak beats, the accent gives the beat this quality. So it's sounds and danced correctly. Strong-weak-weak, and repeated from beginning to end. I like to think of pulse like the Accented beats per measure.


Get count of Options in Django ChoiceField

Question: I have a choiceField in a model and I want to get the count of each choice in my homepage. I alos want the counts to be clickable so that when it is clicked, it redirects me to a page containing all buildings related to it.
This is my models.py
class Property(models.Model):
    landlord = models.ForeignKey(User, related_name="lanlord",  on_delete=models.CASCADE)
    title = models.CharField( max_length= 500 )
    description =  models.CharField( max_length= 50000 )
    BUILDING_CHOICES = [
        ("Flat" , "Flat" ),
        ("Duplex" , "Duplex" ),
        ("Bungalow" , "Bungalow" ),
        ("Apartment" , "Apartment" ),
        ("Shop" , "Shop" ),
        ("Warehouse" , "Warehouse" ),
        ("Storey Building" , "Storey Building" ),
    ]
    buildingtype = models.CharField( max_length=20, choices=BUILDING_CHOICES, default='Bungalow' )

This is my home page

 Storey Building

Shop

Duplex

Apartment

This is my views.py
def home(request,):
    q = request.GET.get('q') if request.GET.get('q') != None else ''
    props = Property.objects.filter(
        Q(title__icontains = q) |
        Q(address__icontains = q) |
        Q(buildingtype__icontains = q)

        )
    property = Property.objects.all()

    properties = Property.objects.filter(is_approved = True)[:5]

    context = {"props":props, "property": property, "properties": properties}
    return render(request, "base/index.html", context)

Answer: Use a foreign key instead of a choice field
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


I have problem to connect oracle DB with SQL developer

Question: I try connect to my oracle db with oracle SQL developer and received that message:
pic (pictures 1 and 2)
if i try connect with sql plus, all well.
<code>command : select userenv('LANGUAGE') from dual;
result:
Connected to:
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production
SQL> select userenv('LANGUAGE') from dual;

*USERENV('LANGUAGE')
----------------------------------------------------
RUSSIAN_RUSSIA.CL8MSWIN1251*
</code>
in SQL DEVELOPER:
(picture 3)

check\uncheck "Skip NLS Settings", nothing changed.

what the issue is?
Comment: Defect to the US, the programmer's paradise where all texts are in ASCII! ;) Just kidding, it's a NLS problem but I don't know enough to help you fix it, sorry!
Answer: I've seen this problem before in an installation with Oracle 10g on AIX. The problem was that NLS files weren't accessible due to wrong file protection.
The problem is most likely not with SQL Developer but on the server side. When you log in, the server will always try to set regional settings that match the one on your client. That's when the error occurs because the required files aren't accessible.
Answer: If you haven't already I think it might be worth asking this question in the OTN SQL Developer Forum
Answer: I suspect you installed the Western European edition instead of the Universal.  If that's not the case, post the file list from the nls/data directory.


Change tint image color when pressing uibutton in Swift

Question: I have a scrollview inside a view. Inside the scrollview I create programmatically 5 buttons. Every button loads a different image with a different tag each one. I added a function that is called when pressing the buttons.
let avatarsListScrollingView = avatarsListView(CGSizeMake(70.0, 55.0), avatarCount: 5)

func avatarsListView(buttonSize:CGSize, avatarCount:Int) -> UIView {

 **CODE**

    for i in 0...(avatarCount-1)  {
        let button = UIButton(type: .Custom)

        **CODE**

        button.setImage(UIImage(named: avatarsList[i]), forState: .Normal)

        button.tag = i
        button.addTarget(self, action: "avatarListSelected:", forControlEvents: .TouchUpInside)

        avatarButtonView.addSubview(button)
    }
    return avatarButtonView

}

Then when pressing the buttons, I call to "avatarListSelected":
func avatarListSelected(sender:UIButton){

    if let image = sender.imageView?.image?.imageWithRenderingMode(.AlwaysTemplate) {
        sender.setImage(image, forState: .Normal)
        sender.tintColor = UIColor.redColor()
    }
    self.addAvatarView.reloadInputViews()
}

This function tints the image button to red, it is working fine, but the problem is that when I press some other button, I want the other one goes to the original color. Right now every button that I press gets in red.
I tried to add the call to "self.addAvatarView.reloadInputViews()" to try to "redraw" again all the buttons, but never gets called.
Do you guys know some way to do this?
Answer: Thanks to everybody!
This is the final code that solved the problem:
func avatarListSelected(sender:UIButton){
    print(sender.tag)

    if let image = sender.imageView?.image?.imageWithRenderingMode(.AlwaysTemplate) {
        sender.setImage(image, forState: .Normal)
        sender.tintColor = UIColor.redColor()
    }

    for view in self.avatarButtonView.subviews as [UIView] {
        if let btn = view as? UIButton {
            if btn.tag != sender.tag  {
                btn.setImage(UIImage(named: avatarsList[btn.tag]), forState: .Normal)
            }
        }
    }
}

Answer: Create a property selectedButton: UIButton? and keep a reference to the selected button there. Don't forget to update it in avatarListSelected method and before you change it, if it isn't nil, change its color to original (and then change it).
If the buttons have different original colors, subclass UIButton class and keep the original color there.
Answer: I don't know if is better approach or answer, but, i maybe could delivery this using this approach:
Create a method that will "fill" the color for your choice button and "clear" color to others , but its a method that loop through UIScrollView and look for each UIButton. Something like this :
func setBackgroundColorButton(color:UIColor , buttonTag:Int){
   for view in self.scrollView.subviews as [UIView] {
      if let btn = view as? UIButton {
         if btn == buttonTag  {
             btn.tintColor = color
         } else {
             btn.tintColor = UIColor.whiteColor()
         }
      }
   }
}

This is the concept, i didn't tested, but maybe just need adjust to search inside your scroll view or similar.
But with this will be work nice i believe :D
Comment: thanks Felipe! your answer was very helpful. I have posted the final code
Answer: You could do it like this
for i in 0...5 {
      let button = UIButton(type: .Custom)
      let x = 50 * i + 10
      let y = 50
      button.frame = CGRectMake(CGFloat(x), CGFloat(y), 40, 40)
      button.setTitle("\(i)", forState: .Normal)
      button.tag = i
      button.backgroundColor = UIColor.greenColor()
      button.tintColor = UIColor.blueColor()
      button.addTarget(self, action: "avatarListSelected:", forControlEvents: .TouchUpInside)

     self.view.addSubview(button)
}

func avatarListSelected(sender : UIButton){
        sender.backgroundColor = UIColor.orangeColor()

        for view in self.view.subviews{
            if(view.isKindOfClass(UIButton)){
                let button = view as! UIButton
                if button.tag != sender.tag{
                    button.backgroundColor = UIColor.greenColor()
                }
            }
        }
    }

The frame etc is just for demonstation purpose only, you should of course use your own value. The tintColor property is not valid for all button types. Read the documentation for more information.


Finally about different values of Acciaccatura (8th, 16th, 32th... grace notes)

Question: I spent several days but didn't find a clear explanation on this topic, only blurry ones.
It's logical to think that if the following note is, e.g., 16th note, then it's properly to use 16th acciaccatura. Still, as I noticed, the most common is 8th acciaccatura in any case. Also saw if there are two or more they beamed as 16ths.
Can somebody explain this: when to use 8th, 16th, 32th... acciaccaturas. What's the rule?
Good referenсe will be appreciated.
Answer: This is a very good question.
Generally speaking, the smaller the number is, the longer that acciaccatura should sustain. An 8th acciaccatura could theoretically be played as long as an 8th note, an so forth. Given in the same piece, at the same tempo, an 8th acciaccatura could sound longer and clearer, and thus more defined or more emphasized than those 16th, and 32th.
If you are trying to play those notations on piano, it's not a good idea to take those 8th, 16th, 32th acciaccatura....too pedanticly. The purpose of an acciaccatura is usually bringing out certain accent of the music. How that accent exactly should sound, is largely interpretable. Some pianists use their gut feelings some like to play that based on research of the style of that piece or even the personality and biography of the composer. I would suggest you listen to good recordings of that piece for samples of the interpretation. Knowledge of the style, the music history and the composer may also help.
More tricky than acciaccature are things like tremolo. Baroque works for harpsichord have lots of those stuff. How to play it? It's rather a matter of taste than technique. Education builds good taste. I would recommend the master classes taught by Sir András Schiff (you can find them on YouTube). Pick any of his master classes, and learn by heart. He doesn't necessarily teach you how to play an acciaccatura or tremolo, but he has very good taste, he teaches music.
I myself play another instrument (a kind of lute), but refer to Schiff's teaching when I play music.
FYI, the traditional repertoire of my instrument involves a huge amount of embellishment such as tremolo, acciaccatura, portamento, and on and on. Until I came across your question, I never really paid close attention to the notations. I just follow my teacher's demo, learn music style and history, refer to Schiff's master classes, and sometimes use imagination.
-------------- edit ----------------
The author clarified his question like this:

I'm asking from the perspective of the composer. That's why it so
  important. If I had to play somebody's music and saw such notes, I
  probably wouldn't pay much attention to it.

My answer:
If, in the same piece, a composer uses both 8th and 16th for the acciaccatura, then he may suggest there should be some difference between these two. Like I explained above, if he wants to emphasize an acciaccatura more than another, he could note that more defined one with 8th, the less dominant one with 16th. In my repertoire, many pieces have a group of pitches as an acciaccatura, it would be wise to use 16th or 32th for each pitch in the group, otherwise, this acciaccature would appear way too dominant, it would no longer be an embellishment, rather the main note. This should not happen.
If, that piece has only a few acciaccatura, and those acciaccatura are not grouped, then there's hardly any difference of using 8th or 16th or 32th. It's a quick crush, an embellishment, an accent. That's it.
Comment: Very good questions can simply be upvoted. :)
Comment: Thank you for your reply. I'm asking from the perspective of the composer. That's why it so important. If I had to play somebody's music and saw such notes, I probably wouldn't pay much attention to it.
Comment: @prstch I edited my answer.
Answer: The value of the following note is irrelevant. If they are single-note acciaccaturi I always write them as small eighth notes. If they are two-note or three-note ones, then as sixteenth notes, and four-note or more, as 32nd notes. In other words, the note-values of acciaccaturi are not related to their surroundings. They are a law unto themselves! So even if you're writing something in 3/16 time, an acciaccatura will be written as a quaver.
I think this is the convention. It's certainly a convention, and as long as you're consistent your intentions will be perfectly clear.
As you know, they're always written with a strike-out line through the stem and tail and, unless there's a danger of them colliding with something else (like an accidental), they're always written with their stems up.
Answer: There is no difference in the values.  An acciaccatura is a crushed note and therefore has practically no length, whether it is an 8th or 16th etc.  As you say, the 8th note (with a slash through it) is the most common and can be used in general.
Answer: Had you asked about an appoggiatura, then there would be a big important difference, as the notes involved there have definite values, which should be noted, so to speak.
However, as already stated, an acciaccatura has very little note value ot time of its own. It's effectively part of the main note - in fact, some players will play both at the same time and release the first immediately.
So, having basically no time value, it doesn't really matter as a writer, how you portray acciaccaturas. You may get more value out of writing appoggiaturas instead.


Does Shilov's Linear Algebra cover SVD?

Question: I'm teaching myself Georgi E. Shilov's Linear Algebra, and have just finished chapter 6 except the final two starred sections. So far, I haven't seen Singular Value Decomposition (SVD). I skimmed the rest of the book, and looked it up in the Index, but had no luck. I'd like to quit studying the book prematurely if it turns out not to cover the subject. You information is valuable. Thank you!
Comment: Looking at the table of contents, it seems unlikely. It's not in the index either. Why do you want to study the SVD? I would suggest Golub and Van Loan *"Matrix Computations"*, a well-known reference on numerical linear algebra, or Åke Björck *"Numerical Methods in Matrix Computations"*, also very good.
Comment: It's in Trefethen and Bau (https://books.google.com/books/about/Numerical_Linear_Algebra.html?id=JaPtxOytY7kC) . Lecture 4,5, and 31
Comment: @Jean-ClaudeArbaut I'm studying Goodfellow et al.'s _Deep Learning_, which introduces SVD but doesn't elaborate on it. The authors "highly recommend" Shilov's _Linear Algebra_, so I thought it should cover the subject.
Answer: No, it doesn't. SVD had yet to become a textbook topic in the English speaking world when Shilov's book was first published (1971). I think it entered the textbook scene by virtues of Gilbert Strang's Linear Algebra and Its Applications and Golub and Van Loan's Matrix Computations, which were published at later times.

Does Shilov's Linear Algebra cover SVD?


Prove $O(x)+O(x^2)=O(x^2)$ (Big O Notation)

Question: I have to prove:
$O(x)+O(x^2)=O(x^2)$ for $x\to\infty$ where "O" is the Big-O-Notation
Specific functions are no problem for me, but I have some difficulties with this general form. But nevertheless I  tried the following:
$O(x)$ means $|f_1(x)|\leq |C_1 \cdot g_1(x)|$ with $g_1(x)=x$, and $O(x^2)$ means $|f_2(x)|\leq |C_1 \cdot g_2(x)|$ with $g_2(x)=x^2$ So we get $C_1 x + C_2 x^2 \leq (C_1+C_2) x^2$, which is $O(x^2)$ with $C_3=C_1+C_2$.
Is this start ok or its a big fault? Any hint would be nice.
Comment: Assuming that all of this is as $x\to\infty$, it seems to me that you have the right idea.
Comment: When you say "$C_1 x + C_2 x^2 \leq (C_1+C_2) x^2$" I would be happier if you added "if $x \ge 1$"
Comment: @Daniel: Your proof looks good to me also.  Depending on the meticulousness of your professor, it may be necessary to explicitly state why you're allowed to write $x \leq x^2$.
Comment: As far as the last problem goes, just note that the minus sign is a distraction since you're taking absolute values.
Comment: Oh sorry, I forgot $x \to \infty$. I added it. Thanks
Comment: Ah ok thanks, I'll add it: I have aother problem to solve: $O(x)=O(x)-O(x), x \to \infty$. It's absolutly the same procedure or do I have to add some attributes for my $C_3$?
Comment: So nothing to worry about, thanks a lot :-)
Answer: $f(x) = O(g(x)) \space \leftrightarrow \exists c_1,x_0\in\mathbb{R}\space such\space that\space\forall x>x_0\space we \space have\space|f(x)| \leq C_1*|g(x)|$so if $f(x) = O(g(x))and\space for \space constant \space k\in\mathbb{R}\rightarrow O(k*f(x)) = O(g(x))$ and for $x>k$ so we have $O(g(x))\le O(x*f(x))$ so $O(g(x)) +O(x*O(g(x))) \le O(x*O(g(x)))+O(x*O(g(x))) (1)\space and\space O(x*O(g(x))) = O(2*x*O(g(x))) (2)$ from (1) and (2) : $O(g(x))+O(x*O(g(x))) = O(x*O(g(x)))$ and now put g(x) = x. the rest is prove of the following sentence and it's very easy you do it yourself as an exercise: $O(x*O(x)) = O(x^2)$


How to disable picture button after click?

Question: I'm new at Drupal CMS and programming at all, but I'm trying to find my way to solve this problem.Unfortunately unsuccesful for now.
I've installed Drupal 7.5 and Multipurpose theme which has social icons to redirect to facebook,twitter and etc.In theme settings there is an option to paste link with profile.I wanted to tweak their function a bit but I'm stuck with the code int the page.tpl.php file.
What I'm trying to do is basicly to check if the user is logged in, and if he is and a link was given in the setting of the theme to redirect to the social profile.The problem occurs when the user presses the button twice or more because the link copies over and over instead of refresh...for example: 1 click: https://www.facebook.com/user and on the 2 click becomes: https://www.facebook.com/user/user and so on.
The code:
 <?php if (!$logged_in) : ?>
      <?php if ($twitter_url): ?>

        <a title="<?php print $site_name; ?> in Twitter" href="<?php print $twitter_url; ?>"><img alt="Twitter" src="<?php print base_path() . drupal_get_path('theme', 'multipurpose') . '/images/social/twitter.png'; ?>">  <?php endif; ?>

<?php endif; ?>

So the question is how can I disable the button(become inactive not hidden) after one click or is there any other approach to solve this problem?
Thank you!
Comment: Your question mentions Facebook but the code shows Twitter. If the URL is absolute (http://...) it should work fine. What do you mean the link copies over and over instead of 'refresh'? It is an external link right?
Comment: Ok to be honest I'm trying to use this code but for calling the login page :D    The code is absolutly the same but instead of facebook link I'm using user/login and it does call the log page but before I log if I press the button  again and again the problem occurs.I know it strange method but I have alredy written code and it's easier for me due to the lack of programming skills....
Comment: The login page to what? Drupal? In that case the href is just '/user/login'.
Answer: The link needs a slash in front of it:
/user/login
instead of:
user/login
Logout would be:
/user/logout
You need to use relative paths or you will continue encountering this behavior. A better way would be to send the variables to your template(s) via the appropriate preprocess function, and use the l() function to create links.
Comment: ohhhhhh it works....is this the same logic for logout
Comment: @htopalov If it works please mark this answer as correct.
Comment: Thank you very much...I've been trying to solve this problem all day long and it is simple as that


HowTo install cURL on ISS 7, PHP5 and Win Server 03

Question: my question is in the title allready "How to install cURL on a windows server 2003 machine with ISS 7.0 and PHP 5?".
I try to read HowTos in the internet but don't get any word what todo, I have too less experience with php and command line things...
So I hope somebody here understands what to do and help me.
Answer: From what I've seen and the research I've done, the easiest way would be to boost a curling sheet (presumably folded or disassembled) into LEO, and then utilize a manned mission to retrieve the sheet and bring it to the ISS for assembly and installation.  However, insofar as I'm aware, there are no plans to provide a suitable module for incorporation of such a playing surface into the ISS's living space, so you'd be reduced to playing during EVA, which doesn't seem likely to go over well with the mission managers.
Why do you ask?

For more information:

http://en.wikipedia.org/wiki/Curling
http://en.wikipedia.org/wiki/ISS
Comment: I mean not curling, I mean http://curl.haxx.se/
Comment: Ah.  In that case, check http://serverfault.com/questions/141091/how-to-install-php-curl-on-iis .


Why am I OVER_QUERY_LIMIT when using Google's Geocoder API?

Question: I have this application that lets me put in an address and get the lat/lng via Google's Geocoding API. I use AJAX to call a PHP script which creates the Google Geocoder API call, it looks like this:
<code>    $base_url = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=";
    $address = urlencode($addy1 . ' ' . $addy2);
    $url = $base_url.$address;
</code>
where $addy1 is the street address and $addy2 is the City/State/Zip in the proper format for geocoding.
When I perform a file_get_contents on that $url, I consistently get a 'status'=>OVER_QUERY_LIMIT.
I do not come even close to reaching the 2500 query limit per day. I have tried maybe 15 different addresses so far today, and I didn't work at all yesterday.
As an aside, we have been having this issue since Monday morning. We did recently move the application to a cloud solution. Is it possible that we are receiving an OVER_QUERY_LIMIT due to the nature of shared IP's on the cloud?
I don't have any other solutions for this. Using an API Key ends with a REQUEST_DENIED response, since the Geocoding API doesn't use an API Key
Answer: We have been having this issue since Monday morning. We did recently move the application to a cloud solution. Is it possible that we are receiving an OVER_QUERY_LIMIT due to the nature of shared IP's on the cloud?
This is the most likely answer.  Can you move the geocoding to the client side?
EDIT: another option would be to see if you can get a dedicated IP address for your server that does the geocoding.
Similar query from 2011
Comment: I may have to move it client-side at this point, since Rackspace is telling me there isn't much they can do about it. Is this the only viable alternative? (It seems other geocoding services have similar limits in place.)
Comment: I will probably approach my boss with a solution that requires us to host web services, as we already have a dedicated server. It's just not the solution I had hoped for, which was to keep everything in one domain and hidden from the average user.
Comment: Oh, you're using Rackspace. Virtual IP addresses are an enormous problem: you are sharing your connection to the internet with lots of other users and sharing quotas/rate limits. Client-side is always better; there are very few occasions when server-side is entirely appropriate.
Comment: My only real issue with doing this on the client-side is that I have to do a lot of added processing, validating against the current db state, making sure i have uniqueness across the various tables involved, as well as actual processing of the data. It's simply easier to contain the bulk of the handling/retrieving in one spot. It is also less-prone to errors.


Arredondar resultado no script

Question: Nesse meu script como posso arredondar meu resultado? Estou tentando usar o (total.toFixed(2)); mais não funciona.
<input type="text" name="total" id="total" value="resultado" />

function updateValue(){
    //atualiza os valores
    inputQtd = parseFloat(document.getElementById("qtd").value);
    inputValor = parseFloat(document.getElementById("valor").value);
    inputMark = parseFloat(document.getElementById("mark").value);

    //atualiza o valor no resultado
    var total = document.getElementById("total");

    total.value = (inputQtd * inputValor ) / inputMark;
}

Answer: No teu código total é um elemento certo? então não podes fazer total.toFixed(2). Quanto muito podes fazer
total.value = total.value.toFixed(2)

Mas o melhor seria fazer antes de escrever no DOM:
 total.value = ((inputQtd * inputValor ) / inputMark).toFixed(2);

Exemplo:
var inputQtd = 145.3445;
var inputValor = 45.45;
var inputMark = 5.65;

var numero = ((inputQtd * inputValor ) / inputMark).toFixed(2);
alert(numero); // dá 1169.19

Arredondar resultado no script


Google play information

Question: I would like to know if it's possible to get any information about users who installed my application from Google play. I know I can get statistic about downloads and everything, but I need more specific information. I am developing security layer for my application which would check phone from which application is running and compare it to which phone was installed from Google play. If it's not same phone then it was copied or cracked and install to another phone.
I know that I can get a lot of information from the phone (Is there a unique Android device ID?), but what about from Google play so I can compare this informations.
Is this possible? To get enough information to be 100% sure, that this phone is the phone to which application was installed?
Comment: "I would like to know if it's possible to get any information about users who installed my application from Google play" -- AFAIK, no, but this sounds like you should be using the license verification system rather than rolling your own: http://developer.android.com/google/play/licensing/index.html
Comment: Thank you for the answer, I will try like you said.
Answer: The Android Licensing library may suit your needs. It has a flexible licensing policy that let's you decide what should happen if, for example, it finds out that the user hasn't actually purchased your app.
You can read more about it here:
http://developer.android.com/google/play/licensing/index.html
Comment: Thank you for the answer, I will try like you said.

Google play information


Handling touches inside UIWebview

Question: I have created a subclass of UIWebView , and have implemented the
touchesBegan, touchesMoved and touchesEnded methods.
but the webview subclass is not handling the touch events.
Is there any method to handle the touch events inside the UIWebView subclass ???
Comment: I would be suspect of any behavior when subclassing UIWebView.  The dev doc says that it cannot be subclassed.  I assume that the compiler, event handling, runloop, etc. will allow the subclass, but I would not trust the possible side effects.  Also, your code could stop working all together in a future release.  Can you explain what you want to do with a subclassed UIWebView?
Comment: I don't expect such comments from a developer. "Overriding touch events in a web view seems like a bad idea to me"

Watch out for "Stanza" and "Kindle" how they have subclassed/hooked the UIWebView for handling events.
Comment: I don't understand why you would ever want to override the touch events handled by UIWebView. Your user is going to want to zoom in and zoom out on the website, as well as touch to click hpyerlinks etc. The code you posted above doesn't have any implementation in the touch methods... I think it's important to know what you are trying to accomplish. Overriding touch events in a web view seems like a bad idea to me. Is there another way to accomplish the behavior you are looking for from your app?
Comment: Just looking for more information dude, relax.
Comment: The approach of substituting a custom UIWindow will not work with the new storyboarding approach. Maybe Apple should have some methods that at least return where touches are inside the UIWebView/WebView. How hard could it be (famous last words, I know)?
Answer:
No subclassing needed, just add a UITapGestureRecognizer :
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapMethod)];
[tap setNumberOfTapsRequired:1]; // Set your own number here
[tap setDelegate:self]; // Add the <UIGestureRecognizerDelegate> protocol

[self.myWebView addGestureRecognizer:tap];

Add the <UIGestureRecognizerDelegate> protocol in the header file, and add this method:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

Comment: I did all that, however in one case, this was not working until I also implemented `- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch` of the `UIGestureRecognizerDelegate`, and returned `YES`.
Comment: I needed to show and hide the navigation controller's navigation bar with a single tap on  top of a web view and this method worked perfectly for me.
Answer: If all you need is to handle gestures, while leaving the rest of the UIWebView functionality intact, you can subclass UIWebView and use this strategy:
in the init method of your UIWebView subclass, add a gesture recognizer, e.g.:
UISwipeGestureRecognizer  * swipeRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGestureRightMethod)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[self addGestureRecognizer:swipeRight];
swipeRight.delegate = self;

then, add this method to your class:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

Add and handle your designated selector to the class, in this case "handleSwipeGestureRightMethod" and you are good to go...
Comment: With gesture recognizers seems to be the cleanest way.
Answer: You could put an UIView over your UIWebView, and overide the touchesDidBegin etc, then send them to your webview. Ex:
User touches your UIView, which provokes a
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // Execute your code then send a touchesBegan to your webview like so:
[webView touchesBegan:touches withEvent:event];
return;
}

your UIView has to be over the webview.
Comment: this is an iphone app and its using UIKit framework, i guess NSView is only for developing Mac Apps and is availabel in AppKit Framework.
Answer: I'm not sure if this is what you want (it's not what you asked for, but it might work depending on what your end game is), but you could instead interpret the touches in JavaScript from inside the UIWebView, and get javascript to do
document.location='http://null/'+xCoord+'/'+yCoord; // Null is arbitrary.

Then you can catch that using the UIWebView's delegate method
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

And if the request.URL.host (or whatever it is) isEqualToString:@"null" take the relevant action (and return NO instead of YES). You can even add the JS to each page by doing something like:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
  [webView stringByEvaluatingJavaScriptFromString:@"window.ontouchstart=function(/* ... */);"];
}

Hope this helps?
Comment: Yes, though not with window.onmousedown! On touches began perhaps.
Comment: This approach does not properly work. It seems only to work with clickable html-items as images and links. It seems to have no effect when clicking on div, p, body, document tags :(
Answer: Handling gestures on a UIWebView is discussed in this Apple Developer forum thread.
Using the info given there, there will be no need for an extra view in most or all cases, and as mentioned here before, overriding UIWebView is not the way to go.
Copypaste of the most important post in the thread:

This is a known issue. The UIWebView has its own UITapGestureRecognizers, and they're on a private subview of the UIWebView itself. UIGestureRecognizer precedence defines that gestures attached to views deeper in the view hierarchy will exclude ones on superviews, so the web view's tap gestures will always win over yours.
If it's okay in your case to allow your tap to happen along with the web view's normal tap your best solution would be to implement the UIGestureRecognizerDelegate method gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer and return YES for other tap gestures. This way you'll get your tap handler called, and the web view will still get its called.
If you need to be the only one handling the tap you'll have to subclass UITapGestureRecognizer so you can use the one-way overrides in UIGestureRecognizerSubclass.h, an you can then return NO from canBePreventedByGestureRecognizer: when asked if the web view's tap gesture recognizer can prevent yours.
In any case, we know about this and hope to make it easier in the future.
Answer: I've just found that UIWebView does check whether it responds to the - (void)webViewDidNotClick: (id)webBrowserView selector, once one taps on the view area (not on hyperref, or any other area that should be handled specifically). So you may implement that selector with your handling code :)
Comment: Not at delegate, you should subclass UIWebView itself and rewrite this selector such as

`
-(void) webViewDidNotClick:(id)webBrowserView
{
    [self.superview touchesEnded:nil withEvent:nil];
}
`
Comment: For some reason I can't detect double tap using this method.
Comment: Where is this supposed to go? I added it to my UIWebView delegate but that didn't work.
Comment: I guess this has been removed now
Answer: Do you mean your sub-classed implementation is not called when touchesBegan, touchesMoved and touchesEnded are called?
It sounds like a problem with how you've created an instance of the object. More details are required I think.
(taken form comments)
Header File
#import <UIKit/UIKit.h>

@interface MyWebView : UIWebView { } @end

Implementation File
#import "MyWebView.h"

@implementation MyWebView

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) { } return self;
}

- (void)drawRect:(CGRect)rect {
    NSLog(@"MyWebView is loaded");
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
   NSLog(@"touches began");
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touches ended");
}

- (void)dealloc {
   [super dealloc];
}

@end

Comment: #import
@interface MyWebView : UIWebView {
}
@end

#import "MyWebView.h"
@implementation MyWebView
- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
    }
    return self;
}
- (void)drawRect:(CGRect)rect {
 NSLog(@"MyWebView is loaded");
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 NSLog(@"touches began");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
 NSLog(@"Touches ended");
}
- (void)dealloc {
    [super dealloc];
}
@end
Comment: Where do you call MyWebView *obj = [[MyWebView alloc] initWithFrame:CGMakeZero];
Answer: I would try overriding -sendEvent: on UIWindow, to see if you can intercept those touch events.
Answer: Following on from what Unfalkster said, you can use the hitTest method to achieve what you want, but you don't have to subclass UIWindow.  Just put this in your web view subclass.  You will get a compile time warning but it does work:
- (void)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (event.type == UIEventTypeTouches) {

        // get location info
        CGFloat x = point.x;
        CGFloat y = point.y;

        // get touches
        NSSet *touches = [event allTouches];

        // individual touches
        for (UITouch *touch in touches) {

            if (touch.phase == UITouchPhaseBegan) {
                // touches began

            } else if (touch.phase == UITouchPhaseMoved) {

            }

            // etc etc
        }
    }

    // call the super
    [super hitTest:point withEvent:event];
}

Hope that helps!
Comment: That's weird... For some reason [event allTouches] always returns an empty set
Comment: Normally the `hitTest:withEvent:` method returns a `UIView*`. Was that intentionally left out?
Comment: it crashes if you don't return a UIView from this method
Answer: If you want to detect your own taps but disable the UIWebView's taps then you can use my solution:
-(void)recursivelyDisableTapsOnView:(UIView*)v{
    for(UIView* view in v.subviews){
        for(UIGestureRecognizer* g in view.gestureRecognizers){
            if(g == self.ownTapRecognizer){
                continue;
            }
            if([g isKindOfClass:[UITapGestureRecognizer class]] ||
               [g isKindOfClass:[UILongPressGestureRecognizer class]] ||
               [g isKindOfClass:NSClassFromString(@"UITapAndAHalfRecognizer")]){
                g.enabled = NO;
            }
        }
        [self recursivelyDisableTapsOnView:view];
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [self recursivelyDisableTapsOnView:webView];

    //disable selection
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    // Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
}

Handling touches inside UIWebview


Getting 403 for static files using django-s3-storage

Question: I've set up the settings as follows:
STATIC_ROOT = BASE_DIR + '/static'

YOUR_S3_BUCKET = "tlot-static"

# DEFAULT_FILE_STORAGE = "django_s3_storage.storage.S3Storage"
STATICFILES_STORAGE = "django_s3_storage.storage.StaticS3Storage"
AWS_S3_BUCKET_NAME = AWS_S3_BUCKET_NAME_STATIC = YOUR_S3_BUCKET

# These next two lines will serve the static files directly
# from the s3 bucket
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % YOUR_S3_BUCKET
STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN

but I keep getting:
<?xml version="1.0" encoding="UTF-8"?>
<Error>AccessDenied<Message>Access Denied</Message><RequestId>9F85922419DD93C0</RequestId><HostId>5lV1ft+jAOTvnqCvOC/fMSolHXS8foJde8XP1LxtYytlZLjejA2gvjIurYwt9Fn8Jxlgvy5IjOI=</HostId></Error>

The files was deployed successfully with collectstatic, and I've set up the cors as per the docs on the bucket. What else do I need to do?
Comment: Make sure bucket policy updated for public access
Answer: You need to either grant public access to the file or folder in your s3 settings (fastest way) on Amazon, or set up security policies if you need more strict access.
Maybe this link could help:
https://www.codingforentrepreneurs.com/blog/s3-static-media-files-for-django/
Comment: Thanks, it seems to have been the first two options to untick with the permissions.


Error in ts(x) : 'ts' object must have one or more observations

Question: When I do forecast using forecast library, I noticed following code does not run as expected:
library(forecast)
library(dplyr)
df1 <- data.frame(gp=gl(20,5), dt=seq(1:100))

get <- function (df1){
  ts1 <- ts((df1%>%filter(gp==2))$dt)
  as.numeric(forecast(ar(ts1),15)$mean)
}

print(get(df1))

The error return is:

Error in ts(x) : 'ts' object must have one or more observations

May be it is caused by ar or ar.burg function. Because if you change the function to ets or something else the function works well.
What is more strange is that if you change the code to:
library(forecast)
library(dplyr)
df1 <- data.frame(gp=gl(20,5), dt=seq(1:100))
ts1 <- ts((df1%>%filter(gp==2))$dt)

get <- function (ts1){
  as.numeric(forecast(ar(ts1),15)$mean)
}

print(get(ts1))

The code is also running correctly. I think this may be a bug in ar function, and the problem is somehow related to scope. Any thoughts about this?
Answer: The problem is to do with scoping. forecast() tries to find the time series used to fit the model. The functions from the forecast package (such as ets) store this information in the model object, so it is easy for forecast() to find it. But ar() is from the stats package, and it does not store the time series used to fit the model. So forecast() goes looking for it. If you run your code outside of the get() function, it works ok because forecast() manages to find the ts1 object in the local environment. But within the get() function it causes an error.
One simple fix is to add the information to the fitted model before calling forecast:
library(forecast)
library(dplyr)
df1 <- data.frame(gp=gl(20,5), dt=seq(1:100))
ts1 <- ts((df1%>%filter(gp==2))$dt)

get <- function (ts1){
  fit <- ar(ts1)
  fit$x <- ts1
  as.numeric(forecast(fit,15)$mean)
}

print(get(ts1))

Alternatively, use predict instead of forecast:
library(dplyr)
df1 <- data.frame(gp=gl(20,5), dt=seq(1:100))
ts1 <- ts((df1%>%filter(gp==2))$dt)

get <- function (ts1){
  fit <- ar(ts1)
  as.numeric(predict(fit,n.ahead=15)$pred)
}

print(get(ts1))


Single document, multiple filetypes for download: how to manage?

Question: I want to upload/attach several documents to a book node. Each document will be offered in a number of file formats, for example:

Report2010.pdf
Report2010.rtf
Report2010.doc
Agreement11.pdf
Agreement11.rtf
Agreement11.doc

Given this, in order to:

Offer a sensible upload interface (like FileField) that allows an unlimited number of files to be uploaded.
Present these files for download, for example:

Report 2010 - Download as: pdf, rtf, doc
Agreement 11 - Download as: pdf, rtf, doc

Is there a robust way to relate the different file formats for each document to each other? By robust, I mean something that (for example) doesn't rely on the user naming the files in a particular way for it to work.
Answer: node-[type].tpl.php
<code>$fields = array('field_reports', 'field_agreements'); // you should to create 2 fields for different filenames
$items = array();
foreach($fields AS $field){
  $exts = array();
  foreach($node->{$field} AS $file){
    // delete real extension from file name
    $filename = explode('.', $file['filename']);
    $ext = array_pop($filename);
    $exts[$ext] = l($ext, $file['filepath']);
    $filename = implode('.', $filename);
  }
  ksort($exts);
  $items[] = t('!filename - download as: !links', array('!filename' => $filename, '!links' => implode(', ', $exts)));
}
print theme_item_list($items);
</code>
Hovewer, this code must be in template.php in phptemplate_preprocess_node function.
Comment: Thanks for the response, however the example file names I gave were only examples. In practice (for my requirements) the files could have any name, and can't be categorised into topics like agreements or reports (there needs to be an unlimited number of documents, each of which need to be offered in an rtf, pdf or doc file format). Sorry if this wasn't clear.
Answer: You can use
http://drupal.org/project/mimedetect
to ensure the files have the correct mime type, and then
http://drupal.org/project/filefield_paths
http://drupal.org/project/file_aliases
http://drupal.org/project/token
to rename them based on file values
Comment: How does this solve the OP's problem?
Answer: The Fieldgroup module seems to do almost everything I need: for each document, I create a group which has a filefield for each file type (PDF, DOC, RTF). It doesn't solve the requirement to allow unlimited files, but the workaround would be to create a number of groups that would reasonably cater for most scenarios.
Comment: Did you use `fieldgroup` or `field_group`?
Answer: You should make a custom CCK formatter (start with filfield_formatter.inc as example) to output the files the way you want without hacking up your template files.


Recommend items to complete a set

Question: I'm trying to predict/recommend items to add to an incomplete basket. In this case, the basket is a project — e.g., you detect a customer trying to fix the AC in their car, hence you suggest things that they might be missing.
I've currently implemented a collaborative-filtering-based approach with customer-sessioning. This means that a customer might come back within 1-2 weeks and continue the purchase, which is considered the same session. This should capture the concept of "coming back for a missing item".
Overall, the results seem to make some sense, but I'm still not able to "detect projects". Expected outcome:

User buys {item 1, item 2} in the same session.
We've observed several sets containing those items in the same session, which might be weeks-long. The sets are { item 1, item 2, item 3}, {item 1, item 2, item 4}, and {item 1, item 2, item 3, item 6, item 7}
The algorithm should rank these possible sets in terms of how likely they are, hopefully considering a vector of customer features and other covariates.

Any ideas on well-known architectures, proper performance metrics, or existing solutions available for this problem?
Thanks!
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: It looks like you are trying to recommend items to customers that they might need, based on the hidden pattern of a customer's basket might reveal.
Well, for a neural network to detect this kind of pattern is not quite efficient, most of this work should be done by your NLP co-workers. They could add tags to an item, and items with similar tags could be thus ranked with higher similarity.  Or input a pattern list to your model as a feature, and your model could detect the similar pattern of by this feature.
Generally speaking, you should not always rely on a model to automatically detect this kind of high level pattern, with not enough data. It's wise to give your model more information.
Thinking of training a model like driving a car to your destination, the input features are like the road signs which will lead your way, the more reliable signs you're given, the higher probability you will reach your final destination.

Recommend items to complete a set


Wolfram|Alpha Plotting multiple geometric objects

Question: I am trying to use WoflramAlpha to plot several gemoetries at once. It works fine up to an extent but after I add three different geometries to draw it just says it doesn't understand and picks something random from within my query to try and render.
My query is:
circle through (54,5) and (30,-5) centre (42, 0); line through (54,5) and (30,-5); x=54

It last worked before I added x=54. I tried separating each plot with semi-colons instead of commas but that didn't work either. I want to show a line through X=54 too, so I can create a triangle (I'm doing Mohr's Circles and using Wolfram to generate my graphs).
Comment: @alancalvitti: no. I've just checked with the Mathematica.SE mods, questions on Wolfram|Alpha are off-topic over there.
Comment: Unfortunately this seems to be typical for Wolfram|Alpha; even grouping things with parentheses doesn't help; it seems to be so focussed on recognizing fuzzy queries that it doesn't realize when you're giving it a perfectly structured, automatically parseable string with proper delimiters. There should be an option to turn off all the guessing and force it to pay attention to formal structure.
Comment: Yeah, generally I can convince it to parse it properly by running each query separately and then copying what it gives as the 'input query', but you're just guessing how they're going to look at your query in this case. Yes I think it is a matter of their lexical engine is too fuzzy by default and I don't think we can change this.
Comment: @deed02392, migrate to mathematica.stackexchange
Answer: I have realised that WolframAlpha does not like being asked to do multipe queries, even if you separate them properly. Instead I just had a lightbulb moment. If I derive the equations for the objects I wish to plot, I can feed them all to WolframAlpha in one query like so:
plot {x=100, x=-60, x=480, y=(83/19)x-(24070/19)}

This always seems to work and I've used up to 6 different objects to be returned in one graph. One limitation is the produced graph is pretty small, because the listing of the equations plotted shrinks the graph size, so it's not particularly useful unless you have Pro and can interactively resize it afterwards.


Retrieve synonyms list from database in Elasticsearch

Question: Is it possible to configure Elasticsearch to retrieve synonyms list from database/sql instead of file?
Comment: no, ES can't go direct to a table in a DB for synonym configuration
Comment: You can also manage them via API calls
Comment: Files is the recommended from the docs "However, it is recommended to define large synonyms set in a file using synonyms_path" https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-synonym-tokenfilter.html#_solr_synonyms
Comment: What do you mean by database? ES? or another nosql/sql?
Comment: @Gibbs I've edit the question, yes, I mean sql
Comment: @Nate so ES is working only with files for synonyms, or it could be something else?
Answer: Unfortunately it is not possible.
ES supports file or online synonyms. It supports solr synonyms format..
doc
But you can add all the synonyms along with original field as an array in ES. While querying, you can use that array field and retrieve the original field.
Comment: And I suggest you to consider @Nate's point of handling it API if it really demanded by management. You can read from sql db and query your field is one of them.


Limit of $p_n = f(a, n) + (1- f(a, n))p_{n - 1}, p_0 = a, 0 < a < 0.5$

Question: How does one compute the limit $\lim\limits_{n \rightarrow +\infty} p_n$ for the sequence $p_n = f(a, n)  + (1- f(a, n))p_{n - 1}$ with $p_0 = a$, where $0 < a < \dfrac{1}{2}$, $f(a,n)=\dfrac{a}{2^n}$?
Comment: If $u_n=\prod_{k=1}^n (1-\frac{a}{2^k})$, you can put for $n\geq 1$ $q_n=p_n/u_n$ (and $q_0=p_0$). This gives (if  i have not made a mistake) $q_n=q_{n-1}+a/(2^n u_n)$, a telescopic relation that gives $q_n$, and as $u_n$ has for limit $\prod_{k\geq 1} (1-\frac{a}{2^k})$, this gives you an expression (not simple...)  for the limit.
Answer: I worked on your problem and at last found the same thing that Kelenner said in his comment, anyway I write it to be another comment.
$p_n = p_{n - 1} + (1 - p_{n - 1})\dfrac{a}{2^n}=\dfrac{a}{2^n}+(1-\dfrac{a}{2^n})p_{n-1}=\lambda_n+(1-\lambda_n)p_{n-1}$ where $\lambda_n=\dfrac{a}{2^n}>0$.
$p_n =\lambda_n+(1-\lambda_n)p_{n-1}$ shows $a=p_0< p_1< p_2< p_3<\cdots<1$ then it's converge. Also
$$\frac{1-p_n}{1-p_{n-1}}=1-\lambda_n$$
and
$$\frac{1-p_k}{1-a}=\prod\limits_{n=0}^k\frac{1-p_n}{1-p_{n-1}}=\prod\limits_{n=0}^k(1-\lambda_n)$$
Thus
$$\lim_{k\to\infty}p_k=1-(1-a)\prod\limits_{n=0}^\infty(1-\dfrac{a}{2^n})$$
right product has simplified by Jack D'Aurizio here.