Como pegar trechos entre () de uma string

Question: Estou fazendo um programa que lê uma expressão matemática qualquer como por exemplo x^(3*x+1) + (cos x), não precisa ser necessariamente essa expressão, e gostaria de saber como faço para pegar o trecho especifico entre parenteses da string.
 Sei que com IndexOf e substring eu consigo pegar o que esta dentro do primeiro parenteses, mas quando tenho mais de 1 não sei o que fazer.
EDIT : O que eu quero fazer é pegar o trecho da string que esta entre os parenteses, no caso 3*x + 1" e "cos x, mas eu não sei como fazer para pegar o conteúdo do segundo parêntese, cos x, pois só sei fazer isso usando indexof e substring dessa forma:
        string formula = Console.ReadLine();
        string trecho;
        int pos1, pos2;
        pos1 = formula.IndexOf('(');
        pos2 = formula.IndexOf(')');

        trecho = formula.Substring(pos1 + 1 , pos2 - 1);
        Console.WriteLine($"{trecho}");

Gostaria de saber se existe alguma forma de pegar o trecho que esta no segundo parênteses também.
Comment: Muito obrigado, vou dar uma estudada nessas expressões regulares, mas era exatamente isso que eu estava procurando
Comment: Olá, Renato, bem vindo ao SOpt. O _como_ é um problema de lógica, não necessáriamente de programação... Pode compartilhar conosco que você conseguiu maginar até agora como algorítmo, pelo menos?
Comment: Editei o post com mais algumas informações
Comment: Infelizmente no momento não posso responder á sua pergunta, mas posso comentar. Amigo você pode alcançar o resultado que pretende utilizando [expressões regulares](https://pt.stackoverflow.com/questions/185301/o-que-é-uma-expressão-regular). Aqui vai um [link](https://dotnetfiddle.net/DuPvTM) com uma pequena ajuda. Pode utilizar este [site](https://regex101.com) para auxiliar na compreensão da sintaxe das expressões regulares.
Comment: Sei que sua pergunta se refere à pegar a expressão dentro dos parênteses, mas acredito que você possa resolver esse algoritmo utilizando pilhas ou algumas técnicas já conhecidas
Comment: Fala renato, pega a expressão ai: https://regex101.com/r/KRZNu1/1
Answer: Se apenas pretende obter o que está dentro de parêntesis (removendo os próprios parêntesis) pode utilizar a seguinte expressão regular:
string formula = Console.ReadLine();
string trecho = Regex.Match(formula, @"(?<=\().+?(?=\))").Value;

Console.WriteLine($"{trecho}");

Pode experimentar esta expressão regular em Regular Expressions 101.
Answer: tente isso:
        string formula = Console.ReadLine();
        List<string> trechos = new List<string>();

        int indexParenteses = formula.IndexOf('(');

        while (indexParenteses != -1)
        {
            trechos.Add(formula.Substring(indexParenteses + 1, formula.IndexOf(')', indexParenteses) - indexParenteses - 1));
            indexParenteses = formula.IndexOf('(', indexParenteses + 1);
        }

        trechos.ForEach(p => Console.WriteLine(p));
        Console.Read();


Playing a large interval with the same hand

Question: I want to play this piece, ant it has two voices. I have to play G3 and B4 with the same right hand.
Is it possible to play this bar, playing the same notes the arranger wrote?
Need to sacrifice note B4 of the first voice to be possible to play note G3 of the second voice?
How would you finger it?
Comment: Arranged*

Vika managed to include the accompaniment with two hands, and also de leading voice of the singer, playing it all together. The lower notes in the G-clef are the leading voice of the singer.
Comment: What piece is this? This looks incredibly awkward to play.
Comment: It's Toxicity. Arrenged by Vika Yermolyeva -> https://www.youtube.com/watch?v=Be-loLSUWT0
Comment: Here's an example with a stretch so large *nobody* can play it as written (just under two full octaves), though the edition displayed in the video explicitly notates the roll: https://youtu.be/tZcjDG9iPOo?t=4m8s  As you can hear, it sounds just fine at that speed.
Answer: There are some contortions you can try before throwing in the towel.  Granted, in this case they might not buy you a lot.
You can try taking the note with the left hand, but the reach is at least as large so the problem is the same: this will help only if your hand spans differ.  When the thumb skirting the A3 is the problem, you might switch hands in order to have the left (or right) pinky in place of the G3 as either Eb2 or Bb4 stick out in a manner where the thumb should not have a problem.  But you'd have to work out a good point of switching over (and this is a fast piece) and it's not clear that the pinky will fare better.
I remember some Mozart menuet(?) I played on chromatic button accordion with free bass where I asked the teacher how one note was supposed to be played at all on the piano, given that it was sort of a stretch on CBA.  After some mutual deliberation we decided that this rather isolated note definitely called for using the nose, nothing else possibly being in reach.  If you were going for that version, you'd likely also take the G4 written on the sixth note in the second hand, but the Bb3 and Ab3 in the same voice would not work that way.
So all in all, the rolling suggestion is most likely the best, short of leaving one note out altogether.  You'll have to figure out how to do it best so that the top line's grouping of three remains recognizable while the hemiola character of the central line is done justice.  When rolling upwards, quaver 5 on G4 will necessarily be short and a bit early and you'll want to do this similarly for quaver 6 on G4 in order to make for consistent voicing.
Answer: At worst, you could roll the two notes (very rapidly). With practice though, you hands will develop a longer reach. On this particular interval, I'd use the thumb and little finger (1,5).
Comment: I have already develop the maximun reach of my hand. My thumb and the little finger are on the same line.  This inteval I try to play G3-B4, I reach the notes. But I cannot play it without touching A3 with my thumb. I would try that of rolling the two notes. I didnt thing of it. The piece is very fast, maybe it wont sound that bad.
Comment: A 10th is pretty big. It's common for pianists' hands to be this large, but is absolutely not *uncommon* to have smaller hands than this. Recommending that someone try to stretch to reach an interval for which their hands are simply *too small* can cause injury.
Comment: ttw starts by suggesting a hand "roll" which is the traditional way of small hand pianists achivieng large intervals and that a longer reach can be developed, not that a 10th or any other specific interval is garanteed to be achieved. I have average hands (can do a 10th with difficulty) and was taught the "roll" approach when trying to  achieve larger stretches or a 10th with a simulatenous intermediate note (e.g. a 1-5-10 chord).
Comment: As an additional side note, I seem to remember some pieces, e.g. by Liszt, (notoriously big handed) where the arpeggio was notated in certain editions but not in others, perhaps because the editor of the former adapted the score to more average hand sized performers.


EFQ SQL error when using filedCondition on two different taxonomy terms

Question: I'm using the below code to select a 'store' content type which has two taxonomy fields: category and brand.
<code>$queryStore = new EntityFieldQuery();
$queryStore->entityCondition('entity_type', 'node')
  ->entityCondition('bundle','store', '=')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_city','tid', $city_id, '=')
  ->addMetaData('account', user_load(1))
  ->execute;

 if ($_GET['category'] != 'Choose a category'){
   $queryStore->fieldCondition('field_category','tid', $category_id, '=');
 }
 if ($_GET['brand'] != '') {
   $queryStore->fieldCondition('field_brand','tid', $brand_id, '=');
 }
</code>
However when I choose a brand like Chanel and a category like Food (naturally such node doesn't exist since Chanel doesn't do food), I get the following error:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')) AND (field_data_field_city0.deleted...
I'm using Drupal 7.
Is there a way to avoid such error?
I appreciate any help given
Thanks
Comment: Sanitize those $_GETs and check that they are an integer before passing them in.
Answer: If you check your error you will notice that your query is trying to look for a column named field_data_field_city0.deleted... , it appends a 0 to it. This problem occurs because the type of value you choose for that column in field query is not correct.
Can you check an confirm if field_city is a taxonomy type of field. If you can access your DB check the table field_data_field_city and check what is the name of last column.
Comment: Hi, thank you for the response, I can confirm that city is a taxonomy type field, term reference. I'll check what you suggested and get back to you.
Comment: Thanks a lot guys, I figured it out, it was related to another function I wrote


Finding Möbius transformations that satistfy certain conditions

Question: Problem
Find Möbius transformations that send
$(i)$ the circle $|z|=2$ to $|z+1|=1$, and $-2$ to $0$, $0$ to $i$.
$(ii)$ the upper half-plane $Im(z)>0$ to $|z|<1$ and $\lambda$ to $0$ (where $Im(\lambda)>0$)
My attempt
For $(ii)$, I've tried to find $T(z)=\dfrac{az+b}{cz+d}$ that satisfied the conditions given. If $z_1,z_2,z_3$ are distinc points, and $w_1,w_2,w_3$ are also different points in the extended complex plane, then, there is a unique Möbius transformation that sends $z_i$ to $w_i$.
As they ask for $T(-2)=0$ and $T(0)=i$, there is only one more point $z \in \overline{\mathbb C} \setminus \{-2,0\}$ to define uniquely $T$. I've chosen $2 \in \{|z|=2|\}$ and I've sent it to $-2 \in \{|z+1|=1\}$.
So, the transformation constructed is $T(z)=\dfrac{z+2}{(-1+i)z-2i}$.
I've tried to show that for all $z \in \{|z|=2\}$, $T(z) \in \{|z+1|=1\}$.
In order to prove this, I've calculated $T(z)\overline{T(z)}=|T(z)|^2$
$$T(z)\overline{T(z)}=(\dfrac{z+2}{(-1+i)z-2i}+1)(\dfrac{\overline{z}+2}{(-1-i)\overline{z}+2i}+1)=(\dfrac{iz+2-2i}{(-1+i)z-2i})(\dfrac{-i\overline{z}+2+2i}{(-1-i)\overline{z}+2i})$$
Noting that $|z|=2$ and distributing, we have $$(\dfrac{iz+2-2i}{(-1+i)z-2i})(\dfrac{-i\overline{z}+2+2i}{(-1-i)\overline{z}+2i})=\dfrac{12+2Re(iz(2+2i)}{12+2Re(iz(-2+2i)}$$.
So, from here I cannot conclude $|T(z)|^2=1$, where have I committed a mistake? If my mistake doesn't come from arithmetics, how can I conveniently choose $z$ and define $T(z)$ for the remaining $z$ so that $T$ satisfies all the conditions?
The same goes for $(ii)$, I did something analogous and to $(ii)$ but arrived nowhere.
I would appreciate suggestions, thanks in advance.
Answer: While your approach is correct in theory, finding by hand an LFT from three distinct points can prove to be quite tedious. Without the aid of a computer, us humans normally categorize LFT's into groups and then prove properties about those groups for use later. Here are the two most common types of LFT's we should know by heart, Circle to Circle and Plane to Circle.
LFT 1. If $$f(z)=\frac{z-w}{1-\bar{w}z}$$ for some $w$, then $f(z)$ maps the unit circle to itself. (Try proving this by itself as an exercise.) Occasionally you made need a constant multiple of this instead, but not for the problems you gave.
LFT 2. Given two complex numbers $w_1$ and $w_2$, then $$f(z)=\frac{z-w_1}{z-w_2}$$ maps the half plane perpendicular to the midpoint line of $w_1$ and $w_2$ onto the unit disc. For example, in $$f(z)=\frac{z-(1+i)}{z-(-1-i)}$$ $w_1$ and $w_2$ have an midpoint of zero that is perpendicular to the line of $y=-x$ (draw this out). The right side of this line would be mapped onto the unit disc. This is so, because every $z$ to the right of $y=-x$ will be closer to the number $1+i$ than it will be to the number $-1-i$. Hence, $|f(z)|<1$ for $z$ to the right of $y=-x$ and by the same reasoning, $|f(z)|>1$ for $z$ to the left of $y=-x$. All the points on $y=-x$ are the same distance from $1+i$ and $-1-i$, hence the line $y=-x$ maps to the unit circle.
With these two tricks we can create almost any LFT we are looking for.
(Problem 1) Start with $$f(z)=\frac{z-w}{1-\bar{w}z}.$$ Compose and form $$g(z)=f(z/2)-1$$ so that $g(z)$ maps the circle $|z|=2$ to the circle $|z+1|=1$. Now pick $w=-1-i$, so that $-2$ maps to $0$ and $0$ maps to $i$. Simplify, $$g(z)=\frac{z/2-(-1-i)}{1-\overline{-1-i}(z/2)}-1=\frac{(i-1)(z+2)}{2(z+1+i)}.$$ It is not obvious from the formula itself that $g(z)$ has all the properties you desire. If you tried to proof $g(z)$ has the properties you want, you might be in for a terrible headache, namely because you would be trying to prove several interchanging arguments altogether. That is, why we prove it a piece at a time, first showing LFT 1 and then composing.
(Problem 2) Given $\lambda$ ($Im(\lambda)>0$) we pick a complex number on the other side of the upper half plane, namely $\overline{\lambda}$. The midpoint of $\lambda$ and $\overline{\lambda}$ is a number on the real line $\mathbb{R}$, hence the perpendicular line to the midpoint is the real line itself. Thus, $$f(x)=\frac{z-\lambda}{z-\overline{\lambda}}$$ maps the upper half plane to the unit circle as desired. Again, this follows immediately because any $z$ in the upper half plane is closer to $\lambda$ than to $\overline{\lambda}$, hence $|f(z)|<1$ for $z$ in the upper half plane.


Django error trying to delete a file using virtualenv

Question:
File
  "/srv/xxxx/venv/lib/python2.6/site-packages/django/core/files/storage.py",
  line 193, in delete
         os.remove(name)
OSError: [Errno 13] Permission denied:

'/srv/notxxxelinq/app/xxx/site_media/xx/xxx/20101217T194905.document.pdf'

I've tried chmod +x on django-admin.py but that didn't do the trick. Any ideas?
Answer: It sounds like the permissions on your site_media directory might be wrong - what are the permissions on that directory?
Comment: Obvious. Thank you. I just needed to add write permissions for those directories. Thank you!


How to filter mysql.log whole query?

Question: Hello I have a problem with filtering mysql.log (general log). I am trying to filter whole query, but in log file lines are split by newline and using GREP shows only part of the query.
Command
tail -n 2000000 mysql.log | grep '016198498'

Produces only this - without UPDATE table SET etc. just part of the code
inm = '016198498',

Any solution to grep whole query with timestamp ?
Answer: Solution has been found. You can grep lines before and after. e.g. 10 lines before and 10 lines after which provides sufficient output for me in this case.
tail -n 3000000 mysql.log | grep -B 10 -A 10 '016198498'
Comment: If you want 10 before and after, you can directly use `-C 10` with `grep`.

How to filter mysql.log whole query?


Is it more common to score on a kickoff return or a punt return?

Question: During the Super Bowl LI last night, the FOX commentators mentioned that a punt has never been returned for a touchdown during a Super Bowl.  My first thought was of Desmond Howard in Super Bowl XXXI, but my wife reminded me that that was a kickoff return, not a punt return.  (She was absolutely right, as usual.)  That 99-yard kickoff return for a touchdown helped earn Howard the Super Bowl MVP that year.  It turns out that a Super Bowl kickoff return score has happened at least one more time, during Super Bowl XLVII (for 108 yards!).
But that got me wondering: Which happens more often: a kickoff return for a touchdown, or a punt return for a touchdown?  And why?
Comment: Don't tell me you forgot about Devin Hester so soon also?  I'd rather forget the *rest* of that game, but for the first ten seconds or so...
Comment: @Joe Of course!  Although, Devin Hester's return was only a measly 92-yards.  :)  Anyway, it's been done a few times during a Super Bowl, which is why I was surprised to hear that a punt return had never been returned for a touchdown in the Super Bowl.
Comment: With only 52 superbowls, it's not too shocking to me that some things have never happened (no overtimes prior to this year, after all)... especially with presumably better-coached teams, and the higher incentive to kick away from Devin Hester and his ilk.
Comment: @Joe My surprise came from my assumption that scoring punt returns would be more common: I had guessed that games have more punts than kickoffs (I don't know if this is true), and punts are usually caught with better field position than kickoffs are.
Comment: I think field position is nearly irrelevant; most of the time the punt returner is the fastest player on the field, so the only question is can he get past the initial kick location.  As long as it's not a punt from the end zone or close to it, the difference between a 98 yard punt return for a TD and a 58 yard punt return for a TD is pretty minimal.
Comment: While there may be more punts than kickoffs (this I'm not sure about), they did, prior to moving the kick up, have more kickoff *returns*.  That's because punts can legally be out of bounds (directional punts), and also tend to be much higher in most cases, leading to fair catches.  Off the top of my head without looking it up, I think fewer than half of punts lead to any return, and many of those lead to sub-5 yard returns.
Comment: Checked the stats: about the same number of kicks and punts, around 2400 of each.  Ballpark 75% of kicks and 50% of punts are returned (slightly over for kicks, slightly under for punts).
Comment: @Joe That's the kind of information (the *why*) that I'm looking for in an answer.  Also (back to your first comment) I only truly care about the Super Bowl when the Packers are in it.  :)
Comment: I think one reason the KR stats have fallen off recently is the change in blocking rules for KRs, which specifically forbid three or more players forming any kind of "wall" or "wedge", which was blamed for a disproportionate number of injuries.
Comment: @MontyHarder The data does not bear that out. Look at my charts; 2009 was the first illegal wedge season while 2011 was the moved up kickoff. 2009-2010 had a high number of returns for TDs.
Answer: Let's go year-by-year the past several regular seasons:
2016: 10 TDs out of 1012 (0.988%) punt returns, 7 TDs out of 1036 (0.676%) kick returns
2015: 13 TDs out of 1138 (1.142%) punt returns, 7 TDs out of 1081 (0.648%) kick returns
2014: 13 TDs out of 1036 (1.255%) punt returns, 6 TDs out of 1226 (0.489%) kick returns
2013: 13 TDs out of 1094 (1.188%) punt returns, 7 TDs out of 1289 (0.543%) kick returns
2012: 18 TDs out of 1134 (1.587%) punt returns, 13 TDs out of 1395 (0.932%) kick returns
2011: 20 TDs out of 1174 (1.704%) punt returns, 9 TDs out of 1375 (0.655%) kick returns
2010: 13 TDs out of 1149 (1.1314186%) punt returns, 23 TDs out of 2033 (1.1313330%) kick returns
2009: 13 TDs out of 1182 (1.100%) punt returns, 18 TDs out of 2004 (0.898%) kick returns
2008: 16 TDs out of 1091 (1.467%) punt returns, 13 TDs out of 2114 (0.615%) kick returns
2007: 17 TDs out of 1122 (1.515%) punt returns, 25 TDs out of 2074 (1.205%) kick returns
2006: 15 TDs out of 1216 (1.234%) punt returns, 9 TDs out of 2037 (0.442%) kick returns
Consistently, over this sample size, punt returns yield more touchdowns than kick returns in number. One thing to consider, especially with the rule changes with kick returns over the seasons in this sample (namely, the elimination of "wedge" blocking (2009), kickoffs were moved from the 30 to the 35 (2011) and touchbacks were moved up from the 20 to the 25 (2016)), is the number of opportunities for punt returns and kick returns. With this in mind, in 2010, the yield between punt returns and touchdowns vs. kick returns and touchdowns were almost identical in percentage.
Thus, from 2006-2016, taking into account rules changes to kick returns over this time frame, punt returns yield more touchdowns than kick returns at a consistently higher percentage.
Comment: You might note the significant inflection point at 2010-2011 (when they moved the kick up).  Prior to that, KR/TDs were far more common (see my answer).
Comment: also worth noting: the difference between 'punts returned' and 'punts' (and 'kicks returned' and 'kicks').
Answer: I charted the KRs and PRs returned for a touchdown since 1994 (the complete play by play era of PFR).  This data is lightly edited to remove inaccuracies due to issues in the PFR system.1  This includes all games, both regular season and playoff, so slightly higher numbers than Ed's which are only regular season as far as I can tell.
As you can see, prior to 2010 the KR and PR seemed to be similar in number; sometimes kicks (blue) and sometimes punts (red) are higher in total for that season.  However, after 2010 only one season (2012) had a number of kicks returned for touchdowns greater than 10.

Here is a second chart; the same data as above, but smoothed using an Exponential Weighted Moving Average.  This weights nearer years higher; I used an 0.3 decay exponent, which I found recommended by one of the developers of my software.
This is a bit more interesting.  Here you see for most years a similar level; there is a bit of a dropoff around 1999 that is either due to the flakiness of 1999 data or an actual year with few kick returns for touchdowns.  Beyond that, you see very similar numbers until 2010's drops start being accounted for in the moving average and the blue bars drop off dramatically.

This data is still fairly flaky; I in particular am concerned about the 1999 blip, which while I can't see any evidence of it being wrong is ... strange.  Only two valid KR-TDs seems to me to be very odd compared to the other seasons (no other season in that era under 8, and none even post-2010 under 6).  (There should probably be a third included, though I can't see a legitimate data-driven way to include it without reviewing every single return; the Music City Miracle is not included as PFR lists it as a 1 yard kick return.)
Either way, I would caution against using only recent data if you're trying to evaluate the Super Bowl history of kick returns; since post-2010 the number of touchbacks rose so dramatically, the return numbers dropped in concert for kickoffs, while punts have had no significant rule changes in recent years.
Punts are also very vulnerable to individuals bumping the numbers significantly with 2+ returns in a season: note the spike in 2002-03, the longer crest in 2006-2008 and return in 2011, for example.  This may have some impact on the Super Bowl, as punt returners can be kicked away from, but kick returners cannot.
1 Specifically, I try to account for fumbles and other returns that are not of the conventional sort.  For kicks I attempt to remove onside kicks returned for touchdowns by either team and fumbled kicks returned by the kicking team; for punts I attempt to remove muffed or fumbled punts returned by the kicking team and blocked punts returned by the receiving team.
I remove any KR that is under 60 yards in total distance, or any return that includes "fumble" in the text (though none do with >60 KRYds).
I remove any PR that is from a punt under 20 yards or any punt return that is under 30 yards but has a number in the PRYds field (as the entire 1998 season has no numbers for some reason), or any punt whose play by play includes 'fumble' or 'muff' and yields less than 30 PRYds (I checked by hand, none of the 1998 punts were caught by this).
This ultimately removes 19 KRTDs and 21 PRTDs from the data.
Comment: I does look like you may be right, though the numbers are a bit hard to measure exactly.  If we limit to 1994-present (the "good data" era at PFR), it's much more nuanced.
Comment: can you summarize how you pull such data down from PFR?  Did you just use the play index and search one season at a time and put the data into Excel to make the graphs?  Or is there somewhere I've missed to do the graphs/download the data better?  Was hoping to use it to answer another question, but extracting the data game by game is proving tedious.  Thanks
Comment: @JeopardyTempest I used the [Game Play Finder](http://pfref.com/tiny/MGjP2), specifically the query "From 1994 to 2016, any team vs. any team, play type is kickoff, on kickoff down, did not result in a turnover, resulted in a touchdown" for kickoffs, and similar for punts.  I then downloaded the data and used SAS to make the chart (I'm a professional SAS programmer, so I used what I had at hand, but you could use R or even Excel, though the latter is of course less powerful).
Comment: I think their PBP data just isn't super great. The tables you looked at isn't coming from PBP data, it's coming from box scores presumably - which are much easier to parse and integrate.  Football PBP data is _hard_.
Comment: Hmmmm, I'll take a look.  That's odd in my opinion (to have a minimum for a counting stat)...
Comment: I'm also a bit surprised that so high a percentage of punt return TDs (25%?) would have been returned by players with so few returns.  I can see some one-year-wonders who never stick, but punt returns are mostly skill, so normally you'd expect only experienced returners...
Comment: I think some of the data is just bad - I looked at a few and there were things like a guy getting credited with a 16 yard kr/td on a regular 65 yard kickoff; clearly something else happened there (perhaps a lateral).  And some on both sides kr/pr seem to be fumbles returned for TDs, even if you filter out turnovers.
Comment: @ᴍᴀsᴛᴇʀᴍɪɴᴅ_ᴇᴅ You're right, they don't list < 2 - that's something I didn't see.  Anyway, I removed that post as it's clearly not based on good data, and instead did an analysis of 1994-present in chart form.
Comment: @Joe Looking at 1999, it appears there were 13 KR TDs that regular season. http://www.pro-football-reference.com/years/1999/#all_returns http://www.nfl.com/stats/categorystats?seasonType=REG&d-447263-n=1&d-447263-o=2&d-447263-p=1&d-447263-s=KICK_RETURNS_TOUCHDOWNS&tabSeq=0&season=1999&Submit=Go&experience=&archive=true&statisticCategory=KICK_RETURNS&conference=null&qualified=false
Comment: Hmm, they must have an issue in their stats then.  I'll repull the data and see if it's just a DB glitch.
Comment: @ᴍᴀsᴛᴇʀᴍɪɴᴅ_ᴇᴅ Nope, still returns same 4 (really 2) 1999 rows.
Comment: @Joe Wow. I wonder what the discrepancy is.


How to determine solutions: $\;2^x=3^y=36^{-z}\; \implies \frac1x +\frac 1y +\frac 1{2z} = \quad ?$

Question:
If $$2^x=3^y=36^{-z}\;$$ then $$\frac1x +\frac 1y +\frac 1{2z}$$
  is equal to
  a) $\;0$  b) $\;1$ c) $\;-1$
  d) none of theses

How to solve this problemplease explain it
Comment: Are you sure they are integers? There is no integer solution to $2^x=3^y$ other than $x=y=0$ which would make your expression undefined.
Comment: There are actually infinitely many solutions to the problem as given.  Are $x, y, z$ integers?
Comment: @anorton, yes they are
Comment: @amWhy It should be $\frac{1}{2z}$ for a reasonable answer. I questioned that too.
Comment: @CalvinLin That's what I suspected, too. I took the liberty to edit. Dear user84888, please double-check the edit to ensure I have expressed what you intended.
Answer: For your expression to be valid, we need to assume that $xyz \neq 0$.
Hint: Using the rules of logarithms, we know that
$$ x \ln 2 = y \ln 3 = (2z) (- \ln 6) $$
Hint: Write $y$ and $z$ in terms of $x$ and substitute into your expression.

 $$\frac{ 1}{x} \left( 1 + \frac{ \ln 3} { \ln 2}  - \frac{ \ln 6} { \ln 2} \right) = \quad ??$$
Comment: Hope you don't mind the teeny (non-substantive) edit! Nice answer, btw ;-)
Comment: @amWhy No worries. I'm often too lazy with \left. I just discovered >! to hide stuff, and I think i'd start to write my answers as hints with things hidden, more fun for me that way.
Answer: Let $2^x=3^y=36^{-z}=k\implies x=\frac{\ln k}{\ln 2},y=\frac{\ln k}{\ln 3}$ and $z=-\frac{\ln k}{\ln 36}$
Therefore, $$\frac{1}{x}+\frac{1}{y}+\frac{1}{2z}=\frac{\ln 2}{\ln k}+\frac{\ln 3}{\ln k}-\frac{\ln 36}{2\ln k}=\frac{\ln4+\ln 9-\ln 36}{2\ln k}=\frac{\ln 36-\ln 36}{2\ln k}=0$$


Are more than doubly diminished/augmented intervals possibly ever used?

Question: Warning: this is purely a theoretical question, most likely won't have any practical uses. The reason I'm asking is because I'm trying to express musical intervals programatically. Expressing them as semitones is not an option, as I want my interval representation to carry semantic information about what the intention with the interval was.
If my understanding is correct of intervals they can be either:

Perfect (unison, 4th, 5th, octave) - these can be diminished/augmented to express an interval one semitone up or down, or doubly diminished/augmented to express an interval 2 semitones up or down.
Imperfect (2nd, 3rd, 6th, 7th) - these can be either minor/major which have one semitone difference, or diminished/augmented which further move the interval up or down.

So far the most extreme interval alteration is doubly diminished/augmented.
Can we have triple, quadruple or even more diminished/augmented intervals? Does it make any musical sense to do this? Would any musician recognize such an interval (be that classical or other)? Are there practical examples?
Comment: Makes sense musically, but lacks a common symbol set. In microtonal theory triple and higher-order accidentals are used sometimes, see for example here systems beyond the reach of the 35 notes that can be achieved by combining 7 base notes with 5 accidentals (neutral=none inclusively): https://en.xen.wiki/w/Golden_meantone
Comment: @Wolf thanks, gonna check this out, I haven't considered microtonal music, but let's see how it translates!
Comment: Nit#2: If your getting into terms like double augmented, why not use "imperfect" instead of "other intervals?" That would be the music theory term.
Comment: @MichaelCurtis haha I didn't know that's a thing, but now I do :)
Comment: F♭ to B♯ is a triply augmented fourth.
Answer: In theory, if you accept no limit to the multiplicity of chromatic alteration, there is no limit to the multiplicity of augmentation or diminution.  So, for example, C-octuple-flat to E-septuple-sharp is a quindecuply augmented third.
In practice, you're never going to see that sort of thing except if someone is trying to make a point.  Doubly augmented intervals are already fairly rare.  Does it make musical sense to exceed that?  In general, it does not, which is why you generally don't see such intervals.
As a programmer, and assuming that you're not targeting highly experimental composition, I would start with 35 possibilities as suggested by Wolf (A through G and double flat through double sharp).  If you need to support larger chromatic alteration, you can add it later.
Do note that if you're planning to map the pitches to frequency ratios, and you're not using a twelve-tone temperament, identifying the interval quality isn't sufficient to identify the frequency ratios.  For example, in 5-limit just intonation, there are two different major seconds, which implies at least three minor seconds.
So, while you may have 35 letter-plus-accidental notes, you'll have more pitches.  Even limiting yourself to C major and only the seven letters with no accidentals, you need to have two different versions of A and possibly two different versions of D.
Comment: https://music.stackexchange.com/questions/126853/is-it-correct-to-write-c%e2%99%af%e2%99%af%e2%99%af%e2%99%af%e2%99%af%e2%99%af%e2%99%af%e2%99%af%e2%99%af%e2%99%af%e2%99%af%e2%99%af-twelve-sharps-as-c My question on ridiculous numbers of accidentals.
Answer: they exist. For example the interval f-double-flat up to b-double-sharp is a 5x augmented fourth. You can't tell by listening of course, and if you had to read it it would stop you dead in your tracks. As an aside, the composer Morton Feldman used multi augmented/diminished intervals because of the awkward feel it gave to the performance (e.g. successive melody notes b-sharp c-flat a-double-flat g-sharp)
Answer: From a programming perspective, if you allow pieces to be transposed, I would allow for the possibility of creating "nonsensical" notes and intervals like triple sharps, even if one would normally want to rework them to more reasonable enharmonic equivalents before trying to perform them.  If one has a piece of music which includes a sequence of chromatic key changes from A major to Bb, Cb, C, Db, and D major, and wishes to transpose it so that it starts in Ab major, performing such a transposition while keeping the same relative keys would yield the key sequence Ab, Bbb, Cbb, Cb, Dbb, and Db.  Obviously one wouldn't want to try to perform a piece written in such keys; one would instead replace the keys with the enharmonic equivalents Ab, A, Bb, Cb, C, and Db.  If, however, one were to subsequently transpose the piece to start on E major, the enharmonically-transposed form would become E, E#, F#, G, G#, A while the transposing either the original or the "nonsensical" form would have yielded the sequence E, F, Gb, G, Ab, A.
Comment: @BalázsÉdes: If the notes Abbb and B### exist, then the interval between them will be a sextuply-augmented second, rather than a minor sixth, since the interval "number" is determined solely by the letter part of the note name.  Since A and B are consecutive, any form of B will be some kind of second away from any form of A.
Comment: @BalázsÉdes: Exactly, except that I wouldn't describe the difference as being "on the C major scale", but rather "[non-German] letter names, ignoring accidentals" (from what I understand, German terminology uses the name B to refer to what is elsewhere called Bb, and H to refer to what is elsewhere called B natural).
Comment: Hey, thanks for the answer, I modeled my notes exactly like this, they can be sharpened/flattened to taste :) But we are talking about 2 different things, I'm ok with notes, intervals are the question. If we model it with geometry, I think of notes as points and intervals as vectors to translate them with on an 1d line (not sure if I make sense).
Comment: @BalázsÉdes what precisely do you mean by "interval"?  There are three distinct ways to to express intervals, two of which supercat has mentioned (half-step count or quality-plus-degree, as in "major second").  The third is as a ratio of frequencies.  This third method is necessary because in some tuning systems, or really every tuning system other than equal temperament, any given quality-plus-degree interval can have more than one size.
Comment: @BalázsÉdes: If one regards notes as being a (letter name; half-step number) pair, then intervals can be treated a (difference in letter name; difference in half steps) pair.  For example, if one selects middle C as being letter 0, half-step 0, then the F# above middle C would be letter +3, half-step +6, and the Gb above middle C would be letter +4, half-step +6, and the C## above those would be letter +7 half-step +14.  The interval from the F# to the C## would be letter +4 half-step +8, i.e. an augmented fifth.  From the Gb to the C## would be letter +3, half-step +8, i.e. a triply-aug. 4th.
Comment: This was extremely useful info for me guys, thank you! I'm glad I asked the question. This rule that @supercat mentioned, does it work in a way that between 2 notes the interval number will be always their distance on the C major scale (on C D E F G A B, repeat)? So the interval between F and B will always be a 4th but the quality of the interval will be determined by how many accidentals the notes have? Am I understanding this correctly?
Comment: @BalázsÉdes You seem to want to describe the 'logical' intervals from Western music.  For these, next to the quality-plus-degree description ("minor sixth"), there are two alternative equivalent ways that make sense musically: number of fifths + number of octaves ("-4 fifths + 3 octaves"); and: number of (major) seconds + number of sharps (augmented primes) ("5 seconds - 2 sharps"). Each is just a pair of numbers, added/subtracted pairwise.  ('Number of fifths' relates to interval quality, see https://math.stackexchange.com/a/3627693/11994; 'number of seconds' relates to interval degree.)
Answer:
...Expressing them as semitones is not an option, as I want my interval representation to carry semantic information about what the intention with the interval was.

I'm not entire sure what you mean. But in music the difference between mere semitone count and the "semantic" meaning of an interval, the musical meaning of an interval, comes from how the interval is spelled and placed within a tonality. This is not a theoretical nit pick, it has practical application and gets to the very heart of understand an interval in a tonal context, the "semantic" meaning.
But first the answer to your question: yes, you can have double diminished and augmented intervals. There really is much to it other than you can make such intervals and they will be impractical in most cases, because they could be rewritten enharmonically as something much easier to understand. You could have a double diminished fifth C G but it is probably easier in most cases to call it a perfect fourth C F.
You can continue the concept with triple, quadruple, etc. But it will be the same situation as the doubled cases. It's not very practical.
How you account for these intervals depends what you are doing with your program. On the one hand this is all a numbers game of counting semitones and then mapping to the gamut of letters ABCDEFG using accidentals. It just a mix of counting bases, with a funny symbol set of ABCDEFG♮♯♭, otherwise it's just number and theoretically infinite.
About the "semantic" aspect and semitone count. You could have a programming object with properties or methods for expressing them, like interval.type(), interval.quality(), interval.spelling(), interval.semitones(), etc.
Possibly you could even have a function to get a kind of musical function if the interval was placed into a key. Give a key of C and an interval of A♭4 F♯5, invert it to a tertian stack of F♯ A♭ the root is an altered F, the "function" is an altered subdominant ♯iv. Such a function is tricky, for a number of reason, but it could be an interesting experiment. The important thing is something like this would be necessary to truly get the "semantic" meaning of an interval. Intervals don't have such meaning, at least in tonal music, until they are placed within a key.


KeyReleased equivalence in Android

Question: On PC I can add a onKeyListener for a JTextField to listen keyReleased event. On Android I've used addTextChangedListener.
I have two EditText fields in my Android application. Editing one will affect the other. This will cause the program to fail in stack overflow error.
How can I listen for the phone's keyboard instead of changes in the EditText field? I don't want the program to invoke the listener because of the infinite loop caused by the listener.
Comment: Perhaps there is a way to work out which EditText has focus, and ignore events on the other one to avoid infinite looping?
Comment: And did something stupid and wrote the bounty text wrong...
Answer: Attach a onFocusChangedListener and add the TextChangedListener when a EditText has focus and remove it when it loses focus.
Something like this:
 EditText1.setOnFocusChangeListener(new OnFocusChangeListener() {

                public void onFocusChange(View v, boolean hasFocus) {
                    if(hasFocus){
                        ((EditText) v).addTextChangedListener(new TextWatcher() {

                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                             //

                        }

                        public void beforeTextChanged(CharSequence s, int start, int count,
                                int after) {
                            //

                        }

                        public void afterTextChanged(Editable s) {
                            // affect EditText2

                        }
                    });

                }
                if(!hasFocus){
                    ((EditText) v).removeTextChangedListener();
                }
            }
        });

        }
    });

The same for EditText2
Comment: Thanks for your answer! It's the right solution, but I cannot see it worth the bounty points, because James.Elsey already posted the solution earlier.
Comment: No problem. The bounty is for a good answer and my answer is just one sentence. Glad I could help.
Answer: First of all, I would create one text change listener, something like SynchronizingWatcher and attach it to both EditTexts. Then, when you receive a text change event, before updating other text edits, just unregister old listeners, update text and enable listeners again:
class SynchronizingWatcher implements TextWatcher {
  Set<EditText> synchronizedViews = new HashSet<EditText>();

  public void watchView(EditText view) {
    view.addTextChangedListener(this);
    synchronizedViews.add(view);
  }

  public void afterTextChanged(Editable s) {
    for (EditText editText : synchronizedViews) {
      editText.removeTextChangeListener(this);
      editText.setText(s);  // Of course you can do something more complicated here.
      editText.addTextChangeListener(this);
    }
  }

  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    // Don't care.
  }

  public void onTextChanged(CharSequence s, int start, int before, int count) {
    // Don't care.
  }
}

...
// Somewhere in your activity:
SyncrhonizingWatcher synchronizingWatcher = new SynchronizingWatcher();
synchronizingWatcher.watchView(myEditText1);
synchronizingWatcher.watchView(myEditText1);

Another solution: provide your own KeyListener that decorates existing KeyListener (you can get existing key listener with editText.getKeyListener() and set your decorator with editText.setKeyListener(). Your decorator would also update other edit texts in onKeyUp(). But I would try to stay away from messing with that stuff.
Comment: What are you refering to with IdentityHashSet? This? http://code.google.com/p/metasyntactic/source/browse/trunk/NowPlaying/Android/src/org/metasyntactic/collections/IdentityHashSet.java?spec=svn2310&r=2310
Comment: Sorry, I confused with `IdentityHashMap`. A simple `HashSet` should work.
Comment: Well of course, because you're setting something to `height` edit text but not removing text change listener from it, it causes additional ontextchange events.
Comment: But anyway James and Yalla solutions are probably better.

KeyReleased equivalence in Android


Find the value of $\theta$ and $x$

Question: Find the value of $x$ and $\theta$ if

$$2 \sin(\theta + x) = 1\;\text{and}\;2\cos(\theta -x) = 1.$$

Comment: Expand and solve for $\sin x,\cos x$ in terms of $\theta$
Answer: For $\sin(\theta+x)=\frac 12$, we obtain $$\theta+x=\frac{\pi}6+2\pi k \\ \theta+x=\frac{5\pi}6+2\pi k$$ for all integers $k$.
For $\cos(\theta-x)=\frac 12$, we obtain $$\theta - x=\frac{\pi}3+2\pi k \\ \theta - x=\frac{4\pi}3+2\pi k$$ for all integers $k$.
Try to system solve for $x$ and $\theta$.
Answer: $\displaystyle\sin\left(\theta+x\right)=\dfrac12=\sin\dfrac\pi6\implies\theta+x=n\pi+(-1)^n\dfrac\pi6\ \ \ \ (1)$ where $n$ is any integer
and
$\displaystyle\cos\left(\theta-x\right)=\dfrac12=\cos\dfrac\pi3\implies\theta-x=2m\pi\pm\dfrac\pi3\  \ \ \ (2)$ where $m$ is any integer
Solve $(1),(2)$ for $\theta,x$
Comment: It looks like you meant $\cos(\theta - x) = \frac{1}{2} = \cos \frac{\pi}{3}$.
Comment: @N.F.Taussig, Hope the typo has been rectified
Answer: the first one says $$\theta + x = \{\pi/6, 5\pi /6\} +2k\pi \tag 1 $$ the second one says $$\theta - x = \{\pi/3, 5\pi/3\} + 2m\pi \tag 2$$ you can solve these linear equations for $\theta$ and $x.$
Answer: Note that $$2\cos \theta \sin x+2\sin \theta \cos x=1$$ and $$2\cos x \cos \theta+2\sin x \sin \theta =1$$
Multiply the first by $\cos x$ and the second by $\sin x$ and subtract $$2\sin \theta\cos^2 x-2\sin \theta \sin^2 x=\cos x-\sin x$$
Now either $\sin x=\cos x$ or $$2\sin\theta \cos x+2\sin \theta \sin x=1$$
Subtract this from the first equation $$2\cos\theta\sin x-2\sin \theta\sin x=0$$
And from this either $\sin \theta = \cos \theta$ or $\sin x =0$
Now if $\sin x =0$ it follows from the first two equations that $\sin \theta=\cos \theta$
Now it simply remains to analyse the two cases $\sin x= \cos x$ and $\sin \theta = \cos \theta$ noting that in either case the common value is $\pm\cfrac {\sqrt 2}2$, and the remaining equations involve only a single unknown angle.

Find the value of $\theta$ and $x$


changing image resolution in Python for a .bmp file

Question: I want to change the resolution of the .bmp image in python. ( i.e. the pixel/inch information) . Using PIL, for jpg image, for instance, the following code works fine
import Image
im = Image.open("myImg.jpg)
im.save("output.jpg", dpi = (75, 75) )

If you view this in some image editing software like GIMP, it shows the Pixel per inch as 75, 75.
But the above code doesn't work when the input image is a .bmp file.
Could someone tell me how to change image resolution for any image  in python?
Answer: I suspect that there aren't many programs out there that respect bmp resolution. Windows bitmaps are all 96 dpi.
Also, It looks as though PIL doesn't support a resolution parameter for bitmaps. My PIL/BmpImagePlugin.py just writes in $01000000 for the x & y resolution (i'm not sure what that translates to, but I'd guess "96 dpi").
There are docs which tell you how to write your own extension .. I'd guess it would be pretty simple to make a copy of the PIL bitmap plugin which accepted resolution as a parameter.
Answer: I think input file can be any valid format and output need to be, jpg, pcx, png, tiff, wmf for dpi parameter I think, may be I am wrong, but when I looked at PIL source files, I don't see one for BMP files.


Vectors Question?

Question: A circle can be defined by an equation $x^2+y^2+ax+by+c=0$. Find an equation of a circle that passes through $(-4,1)$, $(3,0)$, and $(5,4)$:
a. $x^2+y^2+2x-8y+5=0$
b. $x^2+y^2-2x-4=0$
c. $x^2+y^2-8y-9=0$
d. $x^2+y^2-8x+2y+5=0$
Not sure which one it is?
Comment: I think you entered the second answer choice with a typo. Also, please try to include what you've tried or some effort in your question; it'll make it more likely that someone will answer it.
Answer: Substitute in each point as $(x,y)$ into the general equation of the circle, obtaining 3 (simultaneous) equations in $a, b$ and $c$ that you must solve.
e.g. since $(-4,1)$ lies on the circle, we know that $(x,y)=(-4,1)$ satisfies $x^2+y^2+ax+by+c=0$.
i.e. $(-4)^2+1^2+a(-4)+b(1)+c=0$.
Tidying this up, we get: $-4a+b+c+17=0 \tag{1}$
Using the other two points, and doing the same think I've just done, we obtain two more equations:
$ 3a+c+9=0\tag{2}$
$ 5a+4b+c+41=0\tag{3}$
Now, solve equations $(1), (2)$ and $(3)$ (simultaneously) for $a, b$ and $c$ and you will have your equation.

 You should find that $a=0, b=-8, c=-9$.
Answer: Write the equation of the circle as follow:
$$
x^2+y^2+ax+by+c=0\Leftrightarrow (x+x_0)^2+(y+y_0)^2=r^2.
$$
$x_0=\dfrac{a}{2}$, $y_0=\dfrac{b}{2}$, and $r^2=\dfrac{a^2+b^2-4c}{4}$. Of course, $a^2+b^2-4c\geqslant0$ must holds.
Replace your points $(x, y)$ and you will see if it satisfies the circle's equation or not.

Vectors Question?


Automapper copy List to List

Question: I have these classes:
public class Person {
    public int Id{ get; set ;}
    public string FirstName{ get; set ;}
    public string LastName{ get; set ;}
}

public class PersonView {
    public int Id{ get; set ;}
    public string FirstName{ get; set ;}
    public string LastName{ get; set ;}
}

I defined this:
Mapper.CreateMap<Person, PersonView>();
Mapper.CreateMap<PersonView, Person>()
    .ForMember(person => person.Id, opt => opt.Ignore());

That's work for this:
PersonView personView = Mapper.Map<Person, PersonView>(new Person());

I'd like to make the same but for List<Person> to List<PersonView> but I don't find the right syntax.
Thanks
Answer: Once you've created the map (which you've already done, you don't need to repeat for Lists), it's as easy as:
List<PersonView> personViews =
    Mapper.Map<List<Person>, List<PersonView>>(people);

You can read more in the AutoMapper documentation for Lists and Arrays.
Comment: What's interesting to note here, is that the source template can be the most generic type, like `PersonView[]` and the output can be of any other supported type such as `IEnumerable, ICollection, IList, etc`
Answer: For AutoMapper 6< it would be:
In StartUp:
Mapper.Initialize(cfg => {
    cfg.CreateMap<Person, PersonView>();
    ...
});

Then use it like this:
List<PersonView> personViews = Mapper.Map<List<PersonView>>(people);

Answer: You can also try like this:
var personViews = personsList.Select(x=>x.ToModel<PersonView>());

where
 public static T ToModel<T>(this Person entity)
 {
      Type typeParameterType = typeof(T);

      if(typeParameterType == typeof(PersonView))
      {
          Mapper.CreateMap<Person, PersonView>();
          return Mapper.Map<T>(entity);
      }

      return default(T);
 }

Automapper copy List to List


"Destination Path Too Long" when moving an AndroidStudio project

Question: I have recently started to learn on Android application programming using Android Studio. I have my recent projects in C:/.
However, every time I want to copy or move these projects into another folder, Windows complains that the destination path is too long (the folders name are color and drawable).
So, how can I move these folder from C:/ to somewhere else?
Comment: Maybe your file names are veeeeeeeeeeeeeeeeeery long? near the limit of 255 characters?
Comment: I do not change anything. Everything is generated by the AndroidStudio.
Answer: You'll have to move them to a path where the longest path length, with file name, is less than 255 characters.  There is no other solution.
Answer: I fixed this problem by moving the project via AndroidStudio Refactoring.

Open the project that you want to move.
Change to Project view.
From there you can Refactor, Move your project to your desired directory.

AndroidStudio will take care of this path to long problem.


how to get a filename in gnuforth from user input to save it

Question: currently I try to add a save function to a code from gforth 0.7.3
currently the version I have works fine if savefile is already existing (filled or empty as no importance both use-case are OK)
here is the code I test to get filename & save it
27 constant ESC  \ to manage escape sequences used as coloration
0 value handle

: 2>str ( n1 n2--cadr u) s>d <# #s bl hold 2drop s>d #s #> ;

: wr ( cadr n--) handle write-line throw ;

: wr-slot { x y } x y sarray count ?dup if
          x y 2>str wr wr
      else drop
      then ;

: COLORIZE ESC EMIT ." [" base @ >R 0 <# #S #> type R> base ! ." m" ; \ ASCII TERMINAL

: getfname  ( --cadr n) type pad 64 accept pad swap ;

: save 31 colorize s" Save to file: " getfname  w/o open-file ?dup if
       nip ." error"
    else
      to handle 0
    then
    if exit then ['] wr-array catch if 33 colorize s" Error while writing to file." 0 colorize error then  close ;
        \ etc...*

I do not understand how I can modify it adding or not a new definition to permit saving on a file that doesn'exist yet / keeping possibility to save in an existing one.
I worked around without succes, for now.
Comment: 1) It's better if you provide a complete code fragment, which can be run and tested as is.

2) A correct stack diagram for your word `getfname` is `( c-addr1 u1 -- c-addr2 u2 )` or better `( sd.prompt -- sd.filename )`.
Answer: In fact I just had to create file empty and then open it write/open as a buffer "fd-out"
so this part of code becomes :
0 Value fd-out \ for saving file

    : getfname  ( -- addr n) type pad 64 accept pad swap ;
    : open-output ( addr u -- )  w/o create-file throw to fd-out ;
    : open ( cadr n mode--ior) open-file ?dup if  nip 31 colorize s" Cannot open file." 0 colorize error else  to handle 0  then ;
    : close-output ( -- )  fd-out close-file throw ;
    : close ( --ior) handle close-file
      if 33 colorize s" Error while closing file." 0 colorize error then ;
    \ fix unknown filename saving by creating it empty first then writing in it
    : read s" filename ? " getfname 2dup open-output close-output ;
    : save bottom 31 colorize read w/o open if exit then ['] wr-array catch 0 colorize if 33 colorize s" Error while writing to file." 0 colorize error then  close ;


How to add an event listener to entire window except for a defined donut (or annulus)

Question: I'm trying to add an event listener, specifically a selection.on("click" function() { } ), to the entirety of the browser window, except for a defined area (that is a donut or annulus). In other words, I want to execute a particular function when a user clicks anywhere in the browser window except for a defined area (here specifically a donut or annulus).
Answer: I'm not familiar with d3.js but from the code you posted it looks like you are still dealing with regular DOM events. The basic way to do what you want is to bind the events like this:

The event that should handle all the clicks is bound to the document/body.
Then you bind another event to the elements that should not cause the first handler to fire and call the stopPropagation() method of that event object. This will prevent it from bubbling to the previous handler and thus it will never execute.


Amazon EC2 instance possibly Compromised

Question: I have an EC2 instance that may have been compromised. The instance responds far too slowly as of last week and recently I've checked the httpd access_logs and they are in excess of 11Gigs, despite opening the EC2 instance only last month. Today's access_log is growing. The log file is full of sites that have nothing to do with the site I am working on.
A handful of people had ssh access, but I've revoked it. Still, the log files grow.
Ended up getting some emails from amazon about "abuse" and found that there was a jump in mail activity. Strangely, I never set up mail service on this instance but the firewall has been set to allow smtp access (amongst other things), this is even though I only set port 80 access and a few port 22's.
I'm not really much of a server guy and I don't know any.
I've changed my Amazon passwords and created new access codes. Changed the ports for ssh to different ones.
I'd really appreciate any advice on this subject. Thanks.
//********
*EDIT
*********/
I now believe that this was the result of having my server used as a proxy.
As per these guidelines http://wiki.apache.org/httpd/ProxyAbuse I've managed to stem a great
majority of the false traffic going to the site, though the requests are still piling up on the access_logs.  I've confirmed by trying to use my server as a proxy and it forces users to the site directly -- the way I guess it should -- instead of say, yahoo.com.
I don't know if this was the solution but so far it seems to be working out -- so far.
Still, the answers posted have opened my eyes.  If anyone has more to tell I would gladly hear it.
Thanks very much!
Answer: Look through the pages you serve, look for anything like spammy links or exploit code that has been inserted into your server.  Your best bet is to compare your static files with a backup and see if anything has been altered.
Close port 25 at the firewall if you aren't using it.
You can use tools like rkhunter:
http://www.rootkit.nl/projects/rootkit_hunter.html
and chkrootkit:
http://www.chkrootkit.org/
to try and detect tools that hackers use to maintain control over your system.
Use a tool like Nexpose to find vulnerabilities in your web application and OS and follow their recommendations on remediating those vulnerabilities:
http://www.rapid7.com/vulnerability-scanner.jsp
Comment: Thanks AB.  I've tried these above but found nothing out of the ordinary.  Still, it's good to have these in the arsenal.  I've taken note.  Many thanks.
Comment: Note, a negative result from these tools doesn't guaranteed there's no breach. If they've obtained root access, a sufficiently sophisticated hacker could hide their tools or replace these tools with versions that return dummy reports. The only guaranteed method is to completely reformat and reinstall the OS.
Answer: There could be one of two ways the server is being abused or got broken into. First via a software exploit and second via the web application route. I would first check that for software exploits and then check the web application.
Possible problems. In no particular order

Do you have any mailing/form which uses user input to send emails and doesn't have authentication/authorization involved.
Misconfiguration or unsecured applications. Things like phpMyadmin without password or in development applications exposed in an unsecure way.
Check the access logs and get a list of files that were accessed. If they are your files I would check for security holes in them.
Check your known good backup with current files present on your web server. If you didn't use any secure coding guidelines the there could be a problem with Remote Shell etc.

If you are not using mailing block smtp at the firewall to contain the damage.
Comment: Thanks Sameer.  I've blocked smtp and indeed most of the incoming ports except http for the moment.  I'm checking on the others right now.
Answer: If requests are still coming in, change the elastic IP address. Often public proxies are referred to by IP address, this should stop the remaining traffic.
It's worth checking any IP address assigned to you by Googling it when you get it. I had one that was listed as a proxy, so just got another.
Comment: Upon allocating a new IP address, I've searched to find that indeed it's not known as a proxy IP so I think I'll do that.  Thanks David.


Do I need to apply changes in default.settings.php to settings.php?

Question: Recent updates to Drupal 7 have included changes in default.settings.php.
Do they need to be incorporated into settings.php manually, or does the code automatically look up in default.settings.php when it can't find something in settings.php? Apologies if this is in the documentation, I couldn't find it.
Comment: I guess it depends on what the changes are. Code comment updates, or security changes.. you'd want to incorporate the latter for sure.
Comment: I am just going to say no ( I have not for over 10 years) and manny manny manny sites are just fine lol
Comment: Have your site in an isolated env and try it out yourself.
Comment: Well, it's good to know I'm not alone! Still. would be good to know what the code's expectations are.
Comment: Yes that's what I mean, but you could have setups too that generate new sites from a default settings file through a UI. Then the new site has the updates in its new settings.php file.
Answer: Speaking specifically about the last change done for the default.settings.php file: No, you do not need to apply that change to the setting.php file, except in the case you need to change the default value used for the lock expiration timeout, which is 900 and which usually sufficient for any site.
The following is the patch for the change described in [D7] Cron lock time limit is too short and does not prevent multiple, concurrent cron runs.
diff --git a/includes/common.inc b/includes/common.inc
index 0f6ced800d..094db87f54 100644
--- a/includes/common.inc
+++ b/includes/common.inc
@@ -5532,7 +5532,8 @@ function drupal_cron_run() {
   drupal_alter('cron_queue_info', $queues);

   // Try to acquire cron lock.
-  if (!lock_acquire('cron', 240.0)) {
+  $cron_lock_expiration_timeout = variable_get('cron_lock_expiration_timeout', 900.0);
+  if (!lock_acquire('cron', $cron_lock_expiration_timeout)) {
     // Cron is still running normally.
     watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
   }
diff --git a/sites/default/default.settings.php b/sites/default/default.settings.php
index c521bc3b3a..4458ee47d0 100644
--- a/sites/default/default.settings.php
+++ b/sites/default/default.settings.php
@@ -821,3 +821,15 @@
  */
 # $conf['drupal_http_request_strip_sensitive_headers_on_host_change'] = TRUE;
 # $conf['drupal_http_request_strip_sensitive_headers_on_https_downgrade'] = TRUE;
+
+/**
+ * Cron lock expiration timeout:
+ *
+ * Each time Drupal's cron is executed, it acquires a cron lock. Older releases
+ * of Drupal set the default cron lock expiration timeout to 240 seconds. This
+ * duration was considered short, because it often caused concurrent cron runs
+ * especially on busy sites heavily utilizing cron.
+ *
+ * Use this variable to set a custom cron lock expiration timeout (float).
+ */
+# $conf['cron_lock_expiration_timeout'] = 900.0;

The last comment explains exactly what the purpose of that value is and why it was introduced.

Each time Drupal's cron is executed, it acquires a cron lock. Older releases of Drupal set the default cron lock expiration timeout to 240 seconds. This duration was considered short, because it often caused concurrent cron runs especially on busy sites heavily utilizing cron.

If you do not notice any Attempting to re-run cron while it is already running. error in the Drupal log, then you do not need to add that line ($conf['cron_lock_expiration_timeout'] = 900.0;) to the settings.php file used for the site. Otherwise, you need to add it.

does the code automatically look up in default.settings.php when it can't find something in settings.php?

No, it does not. Drupal only load the settings.php file, when running. Any change done to the default.settings.php file that is relevant for you need to be copied into the settings.php file used for the site. Keep in mind that, in some cases, the copied lines could need to be adapted for your use case.


Upright Piano action problems

Question: So I've been playing the piano for about 13 years now and I've noticed the action of my piano getting worse and worse. There are actually several problems:

On some keys the amount of force needed to move the keys (& hammers) is relatively high at the beginning and then after slight movement rapidly reduces, which in turn reduces the dynamic range of that tone since it either comes out too loud or not at all.
As said, problem 1 only exists on some keys which completely messes up the general key weights. While the keys should usually just slightly increase in terms of weight towards the lower registers, on my piano you can find lots of adjacent keys where one of the two is ~40% harder to press than the other. Playing trills on two keys like this is just horrible, but even simple runs can throw you off completely when coming across* keys like these.

*
It's about every third key I'm talking about so coming across them doesn't take long.
To counteract these problems I tend to hold down the soft pedal since that kind of evens out the problematic key weights, gives me back lots of dynamic range and brings the feel of my upright much closer to the Yamaha Grand Piano I had piano lessons on until recently. But this can't be the solution in the long run.
I should say that for the time I've had this piano (~10-11 years) it has never been adjusted and I believe this might be the reason. So would a simple adjustment do the trick or is there more to it? It would also be nice if anyone could tell me what exactly in the key mechanism is causing these problems.
Comment: How old is the piano? The fact that you have been playing it for 13 years is irrelevant if it was already 50 years old when you bought it!
Comment: @alephzero It was brand new when we bought it. It's a Euterpe EU-121 M just for the record.
Answer: I tend to disagree with the general advice about "regulating" the action by tinkering with things that look like adjustment screws, without understanding what's really going on and/or what is causing the problem.
If the problem is affecting "about one in three keys", most likely there is some underlying cause that in time will affect all the keys.
I would take a guess that the cause is something affecting the various felt pads that separate parts of the action, causing them to "stick."
One cause could be a change in the humidity and/or temperature in the room. A more serious problem would be the felts themselves becoming damaged. There could be several reasons for that:

They are simply mechanically worn out - that probably shouldn't happen to a 13-year old piano, but "Euterpe" brand name is the cheapest "beginner-level" piano made by Bechstein, and though Bechstein is a very well known name, the company did go through a rough period when it was on the "wrong side" of the Berlin Wall, so you may have inadvertently bought the piano equivalent of a Trabant!
The glue between the felts and the wood is failing for some reason.
The felt has become infested with mildew or fungus for some reason.
You have rodents living in your piano!

You really need to get a piano technician to look at it and diagnose the problem.
Answer: Doubtless your piano needs 'regulating'.  Which just means adjusting the action.
If you want to try it yourself, I don't suppose you can do any harm that a piano technician can't subsequently reverse!   Here's a video
http://www.concertpitchpiano.com/WhatsRegulation.html
Comment: I'm not sure what that video is suppose to tell you - it doesn't explain *why* or *when* you should do those operations! And you could do a huge amount of irrepairable damage by "tightening every wood screw in the action" without knowing how tight is "tight enough."
Comment: There's plenty more online material.  I agree, if you don't have basic craft skills that tell you when a screw is being over-tightened, you should keep well away from this sort of job.   But a blanket 'Hands off!  Call a technician!' scare is also inappropriate.
Answer: One simple fix that you can do yourself relatively safely is to make sure the capstans are adjusted to remove any play in the key where it makes contact with the rest of the action.
The capstan is the screw at the back of the key. You may need a wrench or channel-lock pliers to turn it. Make a small asjustment (~1/4 turn) and replace the key to test; repeat if necessary.
If the problem is in the action itself, I'd advise calling in a Piano technician.
Edit: After reading alephzero's answer, I agree that it sounds more like worn-out pads, in which case adjusting the capstans is not likely to help much. You probably need a pad-check/replacement and tune-up. I leave the answer as it may be interesting or useful to others with somewhat similar problems.
Answer: This isn't really an answer but a way to start to diagnose the problem.
I have been watching YouTube videos by Roberts Pianos in Oxford UK. There is a lot of information about what they do when restoring pianos they sell and rent out, both upright and grand actions. I suggest perusing these to understand how different shortcomings manifest themselves in touch and sound.  Some of the remedies they perform require special tools, materials, spares and plain old experience.

Upright Piano action problems


Setting a value for when value isn't present

Question: Using request.POST.get you can do this:
token = request.POST.get('token', False)

Is there a way to do the same thing using
request.data['token']

Comment: Give an example of the data you are trying to access. What's wrong with the first approach that you mentioned? Is it that you don't want to use the `.get()` notation or that the data is nested?
Answer: Figured it out.
Axios was serializing the object to JSON by default while I needed to send the data in the `application/x-www-form-urlencoded' format. I used the 'qs' library to achieve this.
var qs = require('qs');

axios.post('/foo', qs.stringify({ 'bar': 123 });

Thought it was a Django issue but it was actually Axios.
Answer: The HttpRequest object doesn't have a 'data' attribute, but depending on what you are looking for there are other attributes, such as 'body', 'FILES', 'META'.  Full details in the documentation:
https://docs.djangoproject.com/en/2.2/ref/request-response/


Select records where the only exist 1 in a joined table

Question: I have the following query:
SELECT
    A.POSTCARD_ID, A.STAMP_ID, B.END_DT
FROM
    PST_VS_STAMP A
JOIN
    STAMP B ON A.POSTCARD_ID = B.POSTCARD_ID
WHERE
    B.ACCOUNT LIKE 'AA%'
    AND B.END_DT = '9999-12-31'
GROUP BY
    A.POSTCARD_ID, A.STAMP_ID, B.END_DT
HAVING
    COUNT(A.POSTCARD_ID) < 2

But I get the wrong results.
I want only the postcards ID's where there is 1 record (HAVING < 2) in the PST_VS_STAMP table. How can I query this?
Comment: Tag your database. If your `END_DT` column datatype as `date`, then better to cast it before comparison.
Comment: Add some sample table data and the expected result - all as well formatted text.
Comment: Why even a `GROUP BY` ?? There are **no aggregate** functions anywhere in your query..... makes absolutely no sense ....
Answer: Do the aggregation in the subquery, only on the table where you want one row.  Because there is one row, you can use an aggregation function to pull out the value of any column (for one row min(col) is the column's value):
select s.postcard_id, vs.stamp_id, s.end_dt
from stamp s join
     (select vs.postcard_id, min(stamp_id) as stamp_id
      from pst_vs_stamp vs
      group by vs.postcard_id
      having count(*) = 1
     ) s
     on vs.POSTCARD_ID = s.POSTCARD_ID
where s.ACCOUNT like 'AA%' and s.END_DT = '9999-12-31';


User defined logger

Question: I am quite new to the Log4j . I am having a few questions on root logger and user defined logger.

On what basis  should we create user defined logger (Project specific or class specific or any thing else)?
When to create root logger?
Answer:
At your heart's content. The common practice is to create one logger per class with the excerpt:
Logger l = Logger.getLogger(getClass());

You don't need to worry that it you'll create too many loggers, log4j creates only one per given name.
Root logger is always created by log4j.
Answer: You should create a user defined logger when you want to have:

different "additivity" level from the root logger (true/false)
different logging level (DEBUG, ERROR,...)
different appender
<logger name="my.package.Class" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="MYAPPENDER"/>

I use it this way:
private static Logger log = Logger.getLogger(YourClass.class);

If you just want a simple logging system you can use the root logger.

User defined logger


How to write overlapping lines when using 4 parts

Question: Here is an example of what I want to do. This is not a chorale hymn! But lets just use the naming conventions since I want 4 lines. The "Soprano" and "Alto" are providing an accompaniment for the tenor which is singing the melody and lyrics. They both momentarily drop below the tenor on the Dm chord at the end of the phrase. I have used a bass clef momentarily but not sure this is right. What is the best way to write something like this?
I want to use these exact pitches and just need the best way to notate them.
Comment: "Ranges are out but nevermind that": the question is about overlapping ranges.  You'll get more meaningful responses if you fix the range problems before asking the question.
Comment: There are some pretty strict rules when we're doing 4-part harmony. Writing for one voice with instrumental accompaniment lets you out of some of these rules. Maybe edit to make it more clear whether you're asking "are these good pitches to write," or "I want these pitches, what's the best way to notate them"? I agree you should not try to print the last half of m3 using treble clef; that's too many ledger lines. Also, I wouldn't describe these instrumental parts as "Soprano and Alto"; they're not in soprano and alto ranges, so it's just confusing.
Comment: Give yourself permission not to have four SATB parts. If this is, e.g., a rock song, and the top two "parts" are a single electric guitar, then they'll spend plenty of time overlapping with a tenor voice, or being even lower, and that's ok. If you're not writing a choral hymn, it might be time to explore the best way to notate for your intended ensemble.
Comment: Andy, I AM exploring! hence this post. Having 4 parts in this case has nothing to do with a chorale hymn. I just use 4 lines to get an idea and to limit myself. Anyway, I am all ears to see your idea. If they overlap, and they do, how do you notate this?
Comment: I changed the title. maybe that'll help to get some help. what I want is to add those two voices/lines to the bass and tenor and need to know how to write it. Cant be so difficult.
Answer: For me, the easiest way to understand the score overall would be to write it on three staves: top staff for the vocal part, plus a grand staff for the accompaniment.

In this specific case, though, given how low the treble staff part is, it would be most clear to write the entire part of the bass staff.

And, at least for this limited segment, the whole thing could be reduced to two staves.
Comment: Absolutely! Though when composing personally I find it useful to use more staves rather than less, as handling multiple voices is a pain in most notation programs.
Comment: The problem for me personally is that I can read the counterpoint between the vocal and bass parts easier the other way when they are on the same staff. I guess with  more practice it wont matter. Why do you use a treble clef transposed an octave higher for the melody instead of a bass clef?
Comment: @armani The treble octave clef is typical for tenor vocal parts.
Answer: F is a low note for alto, D is a very low note for alto. F is absolutely out of range for soprano.
Do you intend this to be sung by actual Singers or played on instruments of soprano/alto range? Most lines written for an instrument aligning to such a vocal range should be possible to notate without a clef change.
So if this is to be played on such an instrument or a singer you should not use a clef change but instead use a few ledger lines.
If this is to be played on an instrument of high range such as piano doing this clef change is fine.
Comment: No. The tenor is the singer and the bass is a bass guitar. I just wanted to get an idea of what other notes I could use in the voice leading. the guitar will likely play the other two notes but havent decided. If you think there is a better way to write this then I am keen to improve on it. thank you
Comment: @armani Hm, as the guitar is tenor instrument you'd notate it on octave higher anyway, so in this case everything can be treble clef. Nota bene: Guitar players are usually not used to clef changes!
Comment: but I need a solution that works in general. For example, I may not use guitar. Lets say I wanted to use non transposing instruments. How would you do it?
Comment: @armani There is no solution that works in general. Different instruments require different notation. A non transposing instrument of that range probably would be notated in bass clef. Of course you could just score the whole thing in a piano like manner and create a guitar score from that if needed. In a piano like manner having such a clef change is fine (although the whole part could be notated in bass clef).
Comment: so you mean with 2 bass clefs or just on one?
Comment: @armani Yes, I mean two bass clefs. Also may I inquire what the intended purpose of the score should be? Is a draft for you to compose the piece? Or is it something musicians should play from?
Comment: it is to be able to compose a song. The goal will be for recording the parts down in my studio. I like the idea if 2 bass clefs. And should I use a guitar then I will simply transpose up an octave. Thanks for helping
Comment: @armani If this notation is meant just to help you compose the song you can do anything you like, including clef changes. Only if you intend to create a score for publishing you should take such things into account.
Comment: @armani Sounds like this was a helpful answer. Please remember to upvote.


What happens to fixed effects when random effects are not well modeled?

Question: Considering a dataset where models do not converge to model random effects (e.g. boundary (singular) fit: see help('isSingular') in R), how confident can we be on the remaining coefficients?
To give an example, consider the following code and results (example taken from here):
library("afex")
# examples data set with both within- and between-subjects factors (see ?fhch2010)
data("fhch2010", package = "afex")
fhch <- fhch2010[ fhch2010$correct,] # remove errors
str(fhch2010) # structure of the data
#> 'data.frame':    13222 obs. of  10 variables:
#>  $ id       : Factor w/ 45 levels "N1","N12","N13",..: 1 1 1 1 1 1 1 1 1 1 ...
#>  $ task     : Factor w/ 2 levels "naming","lexdec": 1 1 1 1 1 1 1 1 1 1 ...
#>  $ stimulus : Factor w/ 2 levels "word","nonword": 1 1 1 2 2 1 2 2 1 2 ...
#>  $ density  : Factor w/ 2 levels "low","high": 2 1 1 2 1 2 1 1 1 1 ...
#>  $ frequency: Factor w/ 2 levels "low","high": 1 2 2 2 2 2 1 2 1 2 ...
#>  $ length   : Factor w/ 3 levels "4","5","6": 3 3 2 2 1 1 3 2 1 3 ...
#>  $ item     : Factor w/ 600 levels "abide","acts",..: 363 121 202 525 580 135 42 368 227 141 ...
#>  $ rt       : num  1.091 0.876 0.71 1.21 0.843 ...
#>  $ log_rt   : num  0.0871 -0.1324 -0.3425 0.1906 -0.1708 ...
#>  $ correct  : logi  TRUE TRUE TRUE TRUE TRUE TRUE ...

m2 <- mixed(log_rt ~ task * length + (length || id) + (task || item),
            fhch, expand_re = TRUE)
#> Contrasts set to contr.sum for the following variables: task, length, id, item
#> boundary (singular) fit: see help('isSingular')

Note that the model does not converge, we can see that some of the random effects are not well modeled, and in fact have variances close to 0:
summary(m2)$varcor
#>  Groups   Name        Std.Dev.
#>  item     re2.task1   1.0119e-01
#>  item.1   (Intercept) 1.0685e-01
#>  id       re1.length2 3.1129e-06 <<<<
#>  id.1     re1.length1 1.2292e-02
#>  id.2     (Intercept) 1.9340e-01
#>  Residual             3.0437e-01

My question is regarding how much we can be confident that the fixed effects have had coefficients accurately estimated.
Answer: From my understanding, a singular fit does not mean the model did not converge- actually, it could be the best representation of the data (see the links below). What would be a bigger issue is, if say, your random effects are near-perfectly correlated with each other.
If you want to see the effect your singular boundary is having on your fixed effect estimates, you could run the model a second time, removing some of the specified random effects until your model converges without the singular boundary warning (if it does). Then, call the summary and directly compare each of the estimates visually. From my personal experience, if your random effects structure is already quite minimal, I would not expect much change.
https://rpubs.com/palday/lme4-singular-convergence
https://www.sciencedirect.com/science/article/pii/S0749596X17300013


<<>> vs {} in LilyPond

Question: It's not really clear in the LilyPond documentation (or at least, I haven't found it) as to when you should use << something >> or { something }. It does seem to matter, since when I used braces for my staff group I got one part, then the other in sequence, but when I used the double arrows it engraved correctly. Is there a guide somewhere for when to use each type of container?
Answer: It's really just what these each mean in and of themselves that counts:

In LilyPond input files, music is represented by music expressions. A single note is a music expression.

(source)
Ergo, a'4 is a music expression.

Enclosing a note in braces creates a compound music expression.

(source)
Ergo, { a'4 b'4 } is a compound music expression. Everything in between those braces will be processed sequentially.

To enter music with more voices or more staves, we combine expressions in parallel. To indicate that two voices should play at the same time, simply enter a simultaneous combination of music expressions. A 'simultaneous' music expression is formed by enclosing expressions inside << and >>.

(source)
Ergo, <> is a simultaneous music expression.
The documentation in that last section usefully provides more than one example of what you can combine. You can produce multiple lines of music in parallel within a single staff.
Here are some examples of these in practice (although with practice you will find more efficient ways of implementing these):

{
   \relative { a'4 b }
   \relative { c''4 d }
}

because these two music expressions are surrounded by braces, it means, "display everything in the first music expression before moving on to the second."

<<
   \relative { a'4 b }
   \relative { c''4 d }
>>

because these two music expressions are surrounded by chevrons, it means, "display both of these at the same time."

(Note: the music expressions are only of single notes here, but you'll see that a staff, clef, key, and time signature are created automatically. LilyPond provides those as defaults if the user does not explicitly enter them.)
How you choose to combine these is entirely up to you. Some will become apparent through practice:
\new Staff <<
 \new Voice
 \new Voice
>>

\new Staff {
 \new Voice
 \new Voice
}

The first expression above is attempting to create one staff with two "Voices" (lines of music) that occur simultaneously. The second expression is attempting to create one staff with two Voices that occur one after another. There are various use cases for doing one or another. For instance, if for some reason you want to write variables of music separately that will all go together in sequence eventually, you can do something like this:
first_section = \relative c' {
 music goes here
}
second_section \relative c' {
 more music
}
\score {
 \new Staff {   <------------------- because these two Voices
  \new Voice { \first_section }      are surrounded by braces,
  \new Voice { \second_section }     they will occur sequentially.
 }   <------------------------------
}

Or, another much more common use case is multiple instruments playing together:
first_instrument = \relative c' {
 music goes here
}
second_instrument \relative c' {
 more music
}
\score {
 <<   <---------------------------- because these two Staves are
  \new Staff {                      surrounded by chevrons,
   \new Voice { \first_instrument } they will occur simultaneously.
  }
  \new Staff {
   \new Voice { \second_instrument }
  }
 >>   <----------------------------
}

You can even start to come up with more complex use cases:
monophonic_section = \relative c' {
 music goes here
}
polyphonic_section_first_voice = \relative c' {
 more music
}
polyphonic_section_second_voice = \relative c' {
 even more music
}
\score {
 \new Staff {
  \new Voice {   <------------------- This starts a sequential music expression.
   \monophonic_section   < ---------- Ergo, this comes first.
   <<   <---------------------------- This follows, which is a new simultaneous music expression...
    \polyphonic_section_first_voice <-- Which means that these two
    \polyphonic_section_second_voice <- happen simultaneously.
   >>   <---------------------------- This closes the simultaneous music expression.
  } <-------------------------------- This closes the sequential music expression.
 }
}

Answer: I've been puzzled by that too, and didn't find a reference either, but this is the way I look at it (which may be incomplete or even partially wrong):

<< and >> for things that happen simultaneously (in time)
{ and } for everything else

Examples of the first are:

two or more parts (voices, or melody + chords) in a staff, as you already noted
polyphony

Both are listed in the cheat sheet.

<<>> vs {} in LilyPond


How to change "CurrentThread.CurrentCulture.DateTimeFormat"

Question: I inherited code like following:
System.DateTime dateTimeOut;
if(DateTime.TryParse("18/06/2015", out dateTimeOut))
{
  Console.WriteLine("Good Job!");
}

"Good Job!" is never printed out. From MSDN I found that DateTime.TryParse uses the DateTime format from System.Globalization.DateTimeFormatInfo.CurrentInfo which in turn is from Thread.CurrentThread.CurrentCulture.DateTimeFormat. And in my system it is "mm/dd/yyyy" - that's why "18/06/2015" cannot be parsed.
Then I went to Control Panel and changed DateTime format to "dd/mm/yyyy" and restarted my PC. But when I run the program again,  Thread.CurrentThread.CurrentCulture.DateTimeFormat is still "mm/dd/yyyy"....I am wondering who controls this setting and where I can change it?
Comment: Or you can use `DateTime.TryParseExact` with explicit format, remember, lower case `mm` is for minutes, you need `MM` *(upper case)* for month
Comment: You'd probably have to change your current culture, not just your date time format settings, since the date time format is coming from the culture. You could always pass in an IFormatProvider to tryparse to specify what date format you want it to parse.
Comment: You can set `CurrentCulture` by code, for example: `Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("de");`
Comment: I checked and the current culture is "en-ca"
Answer: Specify your culture:
System.DateTime dateTimeOut;
var culture = CultureInfo.CreateSpecificCulture("en-GB");
var styles = DateTimeStyles.None;
if (DateTime.TryParse("18/06/2015", culture, styles, out dateTimeOut))
{
  Console.WriteLine("Good Job!");
}

Good Job is sent to the console here.
Answer: You can use the overload of DateTime.TryParse which accepts an IFormat Provider:
public static bool DateTime.TryParse(string s,
    IFormatProvider provider,
    DateTimeStyles styles,
    out DateTime result
)

Your code becomes:
System.DateTime dateTimeOut;
if(DateTime.TryParse("18/06/2015", new CultureInfo("it-IT"), DateTimeStyles.None, out dateTimeOut))
{
  Console.WriteLine("Good Job!");
}

it-IT is just an example of a culture which uses dd/MM/yyyy time format. you should use the one appropriated for you.
Or you can use the accepted answer of this question, from Austin, to change the culture of the entire App Domain:

In .NET 4.5, you can use the CultureInfo.DefaultThreadCurrentCulture
  property to change the culture of an AppDomain.
For versions prior to 4.5 you have to use reflection to manipulate the
  culture of an AppDomain. There is a private static field on
  CultureInfo (m_userDefaultCulture in .NET 2.0 mscorlib,
  s_userDefaultCulture in .NET 4.0 mscorlib) that controls what
  CurrentCulture returns if a thread has not set that property on
  itself.


PHPMyAdmin - backing up - How to ensure I am getting All of the Table Rows Accurately?

Question: I am backing up some large tables, and moving them to another server, to work on a mirror application.
When downloading the tables I notice - sometimes - I am getting a different number of rows for the same table!
I am using PHPMyAdmin's export feature:
PHPMyAdmin->Select_TABLE->EXPORT->SAVE_AS_FILE->My_Table.sql
Compression->none.
PROBLEM: It is producing an inconsistent number of rows in the downloaded file.
10 separate exports of the same table:

ROW COUNT: 93788
ROW COUNT: 93788
ROW COUNT: 92465
ROW COUNT: 90879
ROW COUNT: 92691
ROW COUNT: 93788
ROW COUNT: 93788
ROW COUNT: 93788
ROW COUNT: 93788
ROW COUNT: 93788

Obviously I would take the most consistent result - but:

What is the guaranteed method to ensure I get all the rows accurately?
How do I make an accurate comparison if the row count is different each time?
Comment: what code or command are you running to produce that output? whats it got to do with phpmyadmin? whats not working? Did you see/read: https://stackoverflow.com/questions/11926259/why-is-the-estimated-rows-count-very-different-in-phpmyadmin-results
Comment: I am using PHPMyAdmin's export feature.
PHPMyAdmin->Select_TABLE->EXPORT->SAVE_AS->My_Table.sql
Comment: With large files, I suggest using the `mysqldump` utility rather than the phpMyAdmin export feature. Using phpMyAdmin is subject to resource limits such as memory or execution time, and it's usually better to use the `mysqldump` utility because of those. Ideally, phpMyAdmin can keep track of what's been exported and pick up where it left off to work around the limits, but apparently that's not working in this case. As Mahdi mentions, you can also split your export if you're having trouble with the export as a workaround.
Answer: have you tried using a compression like zipped or gzipped?
you can also split your result to smaller chunks if there is some limit in your server. for doing this you need to check Dump some row(s) and fill the inputs.


GCM native permission prompt - can it be replaced or adjusted?

Question: Does anyone know if the GCM native notification prompt you see on Browsers such as Chrome, can be replaced or adjusted in any way so that we show a more presentable popup instead?
Here is a native prompt example:
Answer: No, you cannot customize it.
The only option would be do draw your custom dialog with HTML / CSS, then when someone clicks subscribe display the default browser dialog: I've already seen it on some websites, but I strongly recommend against it (because of the bad UX it provides).
Comment: Yes, I agree. We will stick to the default behavior. Thanks for the confirmation.


What are the smallest numbers $n$ such that $\dfrac{d(n)}{\ln(n)} \geq k$ where $d(n) = \sigma_0(n)$ is the number-of-divisors function?

Question: I have calculated $\dfrac{d(n)}{\ln(n)}$ on a few highly composite numbers up to 5040.
Here is what I got:
$\dfrac{d(120)}{\ln(120)} = 3.3420423$
$\dfrac{d(360)}{\ln(360)} = 4.0773999$
$\dfrac{d(1260)}{\ln(1260)} = 5.0428170$
$\dfrac{d(2520)}{\ln(2520)} = 6.12869166$
$\dfrac{d(5040)}{\ln(5040)} = 7.03798995$
So we have:
$k=3 : n=120$
$k=4 : n=360$
$k=5 : n=1260$
$k=6 : n=2520$
$k=7 : n=5040$
Notice how, except for $1260$, all of them are superior highly composite numbers!
Could someone calculate the next few $n$ up to $k=12$ ?
Comment: It is more useful to recognize that these are all highly composite numbers ( http://en.wikipedia.org/wiki/Highly_composite_number ) and that the argument at the cited page shows that they must be.
Comment: Which means that you may do this yourself by restricting to numbers with non-increasing exponents. Take a primorial $N$ with largest prime factor $P.$ write a multiple loop for the exponents in $2^{e_2} 3^{e_3} 5^{e_5} \cdots P^{e_P},$ with $e_2 \geq e_3 \geq \cdots.$ Easy to find your function for each of these, also easy to ensure they are no larger than $N.$ No need to actually multiply anything out, not required at first.
Answer: Let $\{p_i\}_{i=1}^{\infty}$ be the primes in the usual order: $p_1 = 2, p_2 = 3, \dots$  Let $f:\mathrm{Z} \rightarrow \mathrm{Z}: n \mapsto \frac{d(n)}{\ln n}$ be the function of interest.  Let $n$ be an integer with factorization $n = \prod_{i=1}^\infty p_i^{e_i}$.  Then we compute directly that $d(n) = \prod_{i=1}^{\infty} (e_i+1)$ and $\ln(n) = \sum_{i=1}^\infty e_i \ln p_i$.
Imagine a sequence of exponents $\{e_i\}_{i=1}^\infty$ (where only a finite number of exponents are nonzero so that the corresponding $n$ is finite).  We may permute these $e_i$ without changing the number of divisors of the corresponding $n$s.  To maximize $f$ over these corresponding $n$s we must minimize $\ln n$, which means we must assign the largest of the $e_i$ to the first several primes, then the next largest $e_i$, and so on, so that the sequence of exponents is nonincreasing.  Therefore, the only numbers that can appear in the desired list of record values of $f$ have nonincreasing sequences of exponents in their prime decompositions.
To organize the search, sequentially fix $s$ and for each value of $s$, enumerate all nonincreasing sequences of exponents summing to $s$, i.e., such that $s = \sum_{i=1}^\infty e_i$.  Then evaluate $f$ applied to each of these values and accumulate the records for each unit interval.  (That is, for each unit interval, track the least integer which produced a value in that interval.)  Applying this method, we get the sequence continuation (with corresponding approximate values of $f$ shown in parentheses):
$$..., 15120 (8.313), 27720 (9.384), 55440 (10.986), 83160 (11.299), 110880 (12.397), ... $$
$f(55440) = 10.986$ suggests, that there are larger numbers than those on our list with smaller values of $f$ in their unit intervals.  This is true, but not interesting.  The sequence of powers of $2$ produce ever decreasing values.  For instance $1.503 \dot{=} f(2^{14}) < f(2^{13}) < f(2^{12}) < \dots$
Answer: If we add the restriction $k< \frac{d(n)}{ln(n)} < k+1$ then:
k=8  n=15120
k=9  n=27720
k=10 n=55440
k=11 n=83160
k=12 n=110880
k=13 n=166320
k=14 n=277200
k=15 n=332640
k=16 n=554400
k=17 n=720720
k=18 n=1081080
k=20 n= 1441440
It seems there are no highly composite number (HCN) with $19< \frac{d(n)}{ln(n)} < 20$
but $19<\frac{d(1801800)}{ln(1801800)}<20$,
so if we consider the restriction $k< \frac{d(n)}{ln(n)} < k+1$
it's false n must be a HCN.
Comment: This fact appears again with k=24
Comment: Since HCN is an abbreviation not used in the Question itself, it would help Readers if you spell out at least once what you mean by this, presumably "highly composite number".
Comment: @hardmath, I followed your suggestion. Thank you.


Ascending and descending chord movement and its effect on harmonic function

Question: Is the cadence I to V the same regardless of its position relative to the tonic?
E.g In C major C4 E4 G4 --> G4 B4 D5 vs C4 E4 G4 --> G3 B3 D4
The thing that has made me question this is the fact that in the first example all notes ascend by a perfect 5th whereas in the second case they descend by a perfect fourth...
Does this have any impact on the harmonic function (not sure if this is the right term here) of the cadence?
Any input is much appreciated.
Thanks!
Answer: Harmonic function is specified without regard to the specific arrangements of notes within a chord or their positions relative to the previous/next chord.
All of the following are considered as I chords moving to V chords in the key of C.
X: 1
T: I → V progressions
M: none
K: C
L: 1/1
[CEG] [GBd] | [ceg] [GBd] | [CGe] [G,B,D | [Gce] [Gdb] | [E,cg'] [DBg'] ||

These progressions are distinguished in two ways:

By the spacing of the notes in each individual chord;
By the lowest pitch in each chord.

Chord spacing
When the notes in a chord are packed together such that no chord tone fits inbetween, this is termed close position. When the pitches are spaced apart, the chord is in open position.
There are a number of posts on this site relating to close and open position. A good starting place is Open/Close Position Chords: What I am missing?
Note order

Chords are identified according to the lowest pitch. When the root of a chord is lowest, the chord is in root position.
When the third is lowest, the chord is in first inversion, also identified as 6-3 position -- so named, because the other two notes in the chord will be a sixth and a third above the lowest note (corrected for octave displacement).
Having the fifth on the bottom is second inversion, or 6-4 position.

X: 1
T: I → V progressions
M: none
K: C
L: 1/1
"root position""_close position"[CEG] "root position""_close position"[GBd] | "root position""_close position"[ceg] "root position""_close position"[GBd] | "root position""_open position"[CGe] "root position""_close position"[G,B,d,] |
"second inversion""_close position"[Gce] "root position""_open position"[Gdb] | "first inversion""_open position"[E,cg'] "second inversion""_open position"[DBg'] ||

Answer: Strictly speaking harmonic function is just a matter of root movements and even more essentially pre-dominant, dominant, and tonic identities. In this regard V I - just two Roman numerals, a progression of roots - is all harmonic function cares about. Melodic matters are irrelevant. It's just a dominant to tonic progression.
However, if we are actually discussing cadences, rhythmic and melodic matters are essential. Strictly speaking a cadence should be the end of something. That may or may not be a rhythmic stop. Also, the quality of the cadence is determined my melodic factors. A cadence involving V I is classified as authentic. Melodic factors determine the type further. Perfect authentic is when the bass moves dominant to tonic and the soprano ends on the tonic. If any of those melodic factors changes, but the chords are still V I, it will be imperfect authentic.
Those different classes of cadence are important especially as formal structural elements in "classical" music. Imperfect cadences have a sense of not full and complete ends and might be used to set up subsequent, continuing phrases. Perfect cadences would be used for conclusive, final endings.

Ascending and descending chord movement and its effect on harmonic function

That wasn't really phrases as a question, but the answer is: ascending and descending melodic voice leading factors do not change harmonic function.

Does this have any impact on the harmonic function (not sure if this is the right term here) of the cadence?

It isn't really clear if you mean strictly "harmonic function" or something like "function of the cadence." But I don't think the answer needs to be either/or. Both things should be understood.
Melodic factors don't change harmonic function, but they change the quality and function of cadences.
Answer: Yes, they are the same. The octave doesn't matter. A C is a C in any octave, an E is an E in any octave. The only differences are in timbre, taste, darkness, openness. The function is the same.