Was equal temperament caused by the invention of the piano, or was it inevitable?

Question: Historically, which key a piece of music was written in made a big difference. Toccata and Fugue in D minor for instance had to be played in that key or it wouldn't sound right.
But over the last couple of centuries, tonality has become less and less important in music.  Pieces are freely transcribed into different keys, whether to match a singer's range or for some other reason.
A large part of why this is possible is because the piano is tuned with equal temperament, so that it can be used to play in any key without being much out of tune.
The piano was more of a tool than an instrument, allowing practice accompaniment in any key.
It is also an excellent tool for composition, as one can almost play with one hand and write with the other.
Switching back and forth with almost any other instrument would be very awkward and tiring.
Unfortunately when one writes music on a piano, any concept of tonality is lost.
Most modern music is written without tonality, and most newer instruments are tuned with all notes based on equal 12th root of 2 frequency intervals.
This is very convenient in many ways, and very unfortunate in others.
The question is, was it inevitable that music would eventually have lost tonality, even if the piano (or some equivalent instrument) hadn't been invented?
Comment: A lot of factual errors here, to address a couple: 1) Most modern music is *not* written without tonality. 2) Tonality isn't "lost" when one writes for / using a piano. 3) Equal temperament predates the invention of the modern piano. 4) The piano *isn't* "more of a tool than an instrument.
Comment: The OP seems to be using "tonal" to mean "in just intonation as opposed to equal temperament", but the comments are mostly interpreting it to mean "in a key".
Comment: "Unfortunately when one writes music on a piano, any concept of tonality is lost." - I strongly doubt this; I've heard plenty of tonal 21st-century music for solo piano.
Comment: A v interesting question! Some [thoughts of mine](https://music.stackexchange.com/a/80270/13649) in a related vein. Also [here](https://music.stackexchange.com/a/86332/13649)
Comment: @Rusi, that's an amazing performance you provided a pointer to, [Utsav Lal performs Raga Bhairav Alap-Jod-Jhala on the Fluid Piano - YouTube](https://www.youtube.com/watch?v=X7ti6HUX5xQ&feature=youtu.be).
Comment: The question asks an interesting topic, but there are some factual errors and some opinions bundled in, which makes it hard for me to upvote it. I'm assuming that when you talk about "tonality" you mean "Just intonation". Can you explain how a D minor in JI would be different from a, say E minor in JI? I thought that you built the scale using a succession of perfect 5th interval starting from the root. The only difference is the timbre of the instruments involved
Comment: I'm voting to close this question because most of it is based on misunderstandings, and the core question is a speculative "what-if" question about the course of music history, and doesn't lend itself to a concrete objective answer.
Comment: @Dekkadeci says "*tonal 21st-century music for solo piano*".  But wouldn't that require that the piano be tuned to a specific key?
Comment: @RayButterworth no, why would it?  For centuries keyboards and other instruments have been tuned so they can play in any of several keys, even if it's only been the last couple of centuries in which they could play in *all* 24 keys.  Many instruments (particularly unfretted strings) and human voices have never been tuned to a particular key, yet they can play and sing in any key.  The key of a melody or other piece of music and the key to which an instrument are tuned are for the most part not related.
Comment: @ColinFine, right.  My intent was to compare when the key that a piece was written in was important, to now, when it mostly isn't.  The "classics" were written to take advantage of the sound/mood/atmosphere of a specific (not equal temperament) key, while most modern music sounds the same in any key.  If you can improve the wording or terminology in my question, please feel free to do so.
Comment: Glad you liked it! Addresses many of your questions re tonality. Here is a very different raga – jaijaiwanti – by the [same artist](https://youtu.be/c5mYcTB3qf8). Note the continuous play of major minor third. Not allowed in raga bhairav. Maybe more easily accessible (because less professional) in the last song (Ram Simara) of [this list](https://music.stackexchange.com/a/91956/13649). In the western tradition, one of these would willy nilly be an "accidental"
Comment: The question makes historically incorrect assumptions. Equal temperament wasn't invented for pianos but for lutes and other fretted instruments. (See Vincenzo Galilei). The answer calls for an opinion rather than a music-theoretical (using whatever definition of theory one cares to). I am also voting to close.
Comment: The question in the title is fine- but the body is all over the place, attempting to justify the question through a series of false statements.  Removing most of the body and focusing solely on the question would be a big improvement.  For that reason, I don't really want to close the question, but I also worry that editing to improve the question would not be appropriate because it is such a major edit.
Comment: @Edward, feel free to make whatever changes you think are appropriate.
Comment: @Edward, the central idea is that on an equal temperament scale, the interval between any two consecutive semitones is the 12th root of 2.
But with Pythagorean tuning, the frequency intervals are not the same.
In the key of C, do-re-me is 1.000 1.125, 1.111.
But starting on G, it is 1.000, 1.111, 1.125.
So a tune played in the key of G will sound significantly different from when it is played in the key of C.
Comment: @RayButterworth A correction, A tune played in the key of G *using the (non-EDO) tuning pitches for the key of C* will sound significantly different from when it is played in the key of C with the same pitches.  An instrument can be tuned for the key of G and played in G, and it will sound similar to an instrument tuned for C and played in C.  The piano would be "causing" equal temperament by the fact that is is wildly impractical to re-tune it for a specific key, but yet pianists wish to play in every key, so it must be tuned to sound good in every key.
Comment: @Edward, but that's my point. A piano tuned with equal temperament sounds "good" in every key, but it also means that every key sounds exactly the same, just a little higher or lower. The point of composing in a specific key, where each key has a different character, has been lost.
Answer: The earliest use of equal temperament was on fretted instruments with fixed frets. The ratio of 17:18 for the string length for successive frets is a good approximation to equal temperament. The errors were well within the tolerance of other intonation issues such as non-uniform gut strings, and the different amounts of string bending on different frets because of the height of the action.
Not all early fretted instruments had fixed frets - for example the frets on lutes were loops of gut tied around the neck and were adjustable.
It is probably safe to say that no keyboard instruments were routinely tuned in equal temperament for the first 1400 years of their history - there are mosaics depicting organs played by keyboards, and texts describing the sounds they produced, that date from 400 AD.
Equal-tempered tuning on a harpsichord certainly doesn't sound "better" for the historical style of playing. Harpsichord tone has more high harmonics than piano, which increases the difference in effect between just intonation major thirds and equal tempered. Most "serious" modern harpsichordists would use appropriate historical temperaments, and different temperaments for music of different periods. Harpsichords need much more frequent tuning than pianos, and harpsichordists learn to do it themselves, just like guitarists, string players, etc. Technically, it is much easier than piano tuning because the string tension is much lower, and a "non-expert" tuner is less likely to physically damage a harpsichord than a piano.
To answer Tim's comment, unequal temperaments did not only "sound better" in "just one key". For example, in the commonest meantone temperament used in the 16th century, where the tempered note names are C C# D Eb E F F# G G# A Bb B C, any major scale from two flats through to three sharps is "in tune", and in fact all those scales have exactly the same frequency ratios between the notes, so there is no problem with modulations within that part of the circle of fifths. But if you attempt to go outside that range and play an "Ab chord", the notes G#-C-Eb sound horrible, and so does a B chord with B-Eb-F#.
The various "well-tempered" tuning systems devised in the 18th century were useable in every key, though every key had its own slightly different sound - and it is clear that from the music that composers like Bach made deliberate use of that fact. The typical patterns of harmony and counterpoint are different in different keys. Some of those "well-temperaments" were still used by piano tuners even into the early 20th century. Much "romantic" 19th-century piano music was written in keys using many "black" notes for technical reasons, and it is probably not a coincidence that in some well-temperaments, the groups of keys on "opposite sides" of the circle of fifths (e.g. Bb-F-C-G-D compared with E-B-F#/Gb-Db-Ab) had distinctly different sound qualities.
Some modern harpsichord music is (probably) intended to be played in equal temperament - for example this:
Comment: Certainly there is a 12-key organ keyboard documented as being built in in 1361, though the keys were arranged as "8 + 4" not "7 + 5", with two "white" keys for B flat and B natural! By 1495 it had been rebuilt in the modern "7 + 5" layout. The 1361 instrument may have replaced an earlier one with just 8 "white" keys per octave, i.e. C D E F G A Bb B C - maybe the organist in 1361 didn't want the hassle of having to re-learn a keyboard with Bb in a different place.
Comment: … the early history is not very well documented, because "good" instruments were modernized, and "bad" ones were scrapped. Even in the early 18th century, there were keyboard instrument makers whose main source of income was rebuilding and modernizing harpsichords made by the Ruckers family in Antwerp (which had a quality reputation similar to that of say Stradivarius violins today) that were 100 or 150 years old. These rebuilds involved making new keyboards, extending the compass, adding more sets of strings, etc.
Comment: Indeed, in the early centuries of keyboards, they didn't have 12 keys per octave.  I wonder when the 12-key keyboard was invented.  Do you know?
Answer: Even without the piano (or even keyboard instruments), there were other forces pushing toward something close to equal temperament.
The common narrative is that chromatic music was instrumental in the use of temperaments that were more equal.  While that is a factor, it's important to look at how chromatic music could be even in the 1600s.  Frescobaldi's Fiori musicali, for one example, was an incredibly popular set of keyboard works published in 1635.  However, when the more chromatic ricerars are performed on organs in the meantone temperaments popular in that day, they sound positively awful to modern ears that are not used to such wild deviations from equal temperament.
And yet, composers wrote this music and performed it on instruments at that time.  Composers (and apparently listeners) appreciated the greater contrast provided by intervals that were more or less "in tune."  I still remember the first time I noticed the compositional use of tuning for effect, where I was looking at an aria written around 1700 that briefly modulated through A-flat minor while the text was declaring something was "horrible, horrible!"  Yes, the harpsichord accompanying that aria would likely have sounded quite "horrible" at that point in the piece with its harsh intervals that would seem very "out of tune" to modern ears.
So, strictly speaking, it wasn't necessarily chromaticism alone that drove the move toward equal temperament.  Composers had been using chromaticism and tuning for effect for centuries before keyboard instruments came to be tuned in something approaching modern equal temperament.
The main thing I'd add to other answers here so far is the role of other instruments.  Fretted instruments have already been mentioned as a very early use of equal temperament (long before keyboards approached it).  But I mean also the use of various instruments in the increasingly large ensembles of the 18th and 19th centuries.  We tend to obsess over temperaments in keyboard instruments mainly because there is the most discussion in historical treatises about how to temper keyboard instruments.  But that's simply a practical concern that grew first out of organ tuning, as organs have long sustained tones and timbres with rich sets of harmonics that makes tuning choices particularly important.  Later, temperaments became important to harpsichord and other keyboard players, as these instruments were some of the only ones that required the detailed knowledge of tuning to maintain them.  A harpsichord needs to be frequently tuned, and unlike other instruments like strings (bowed or plucked) that typically only needed a few intervals tuned, a keyboardist needed to know how to create adequate relationships between all of the 12 chromatic pitches in the octave.
My point is that our perspective is biased toward keyboard instruments in tuning discussions because practically that's one case where knowledge of tuning was important historically.
However, if one considers the practical considerations of playing in large ensembles with baroque instruments, it's easy to see how tuning compromises would generally lead to something approximating equal temperament.
Baroque wind instruments, in particular, didn't have most of the valves and keys of modern orchestral instruments.  A natural brass instrument without valves would be in-tune for some notes in its natural harmonic series, but other notes were often approximated through changes in embrochure and sometimes holes in the instrument that could be strategically used to better approximate chromatic notes or those not in the harmonic series of the fundamental of the instrument.
Meanwhile, woodwinds with few (or no) keys depended on all sorts of cross fingerings, half hole techniques, etc. to approximate chromatic notes.  These tunings could be all over the map.  Skilled wind players would learn to use different fingerings in different circumstances -- some fingerings might be higher in pitch (and appropriate for a leading tone), others might be in the middle of the chromatic range.  Some might be better for softer or louder notes, but might be more or less out of tune.
Now imagine ensembles like those seen in Bach's Brandenburg Concertos and think about the challenges inherent in having all of those instruments trying to intermingle and be in tune with each other.  You have brass pitched in one key (and in tune for most notes in that key), but woodwinds might be primarily pitched in another key and using chromatic fingerings attempting to be in tune with everyone else.  And these all needed to play well with the strings (who had more flexibility in tuning their individual notes, but mostly tended to anchor to the perfect fifths in their tuning) as well as whatever keyboard in whatever temperament that was accompanying them.
If one reflects for a moment on the disaster inherent in trying to mesh all of these tuning considerations together, it's easy to see that the larger ensembles of the 18th and 19th centuries required gradual compromises to a standard tuning across the scale.  All of the tuning debates about organ tunings and meantone and well-temperament fly out the window when you're just trying to have the flute, the oboe d'amore, the horns, and the strings sound okay when playing along with harpsichord in several keys.
So, as instrument builders started to invent and add keys and valves in the late 18th and early 19th centuries to wind instruments, the obvious choice was to approximate something like a compromise temperament where all the chromatic intervals of the scale were roughly equal.  Players of these instruments were already doing this in large ensembles, out of necessity.
 The expense of creating these more complex instruments increased, so gone were the days when a wind player might expect to have several instruments pitched in many different keys.  Instead, the new holes and keys and valves were meant to make instruments useful in just about any key.  Wind players today might choose to still have two instruments (usually one pitched in a flat key and one in a sharp key, like the B-flat vs. A clarinet) for convenience in fingering, but the new systems for chromatic scales on instruments were necessarily close to equal temperament simply to allow ensembles to play together reasonably in tune.
None of this takes away from the role that keyboard temperament theories and increasing chromaticism may have played in leading to equal temperament, but the simple fact of larger ensembles trying to play in tune in several keys was also likely to lead toward a compromise tuning for the chromatic scale anyway -- regardless of the piano or even the use of keyboard instruments generally.
Answer:
the piano is tuned with equal temperament

Not necessarily.  Pianos were in wide use by the late 18th century, but equal temperament was not until perhaps 100 years later.
The rise of equal temperament seems rather to have been driven by the expansion of modulatory possibilities as the "common practice" system of harmony was expanded, eventually to the breaking point.  The piano may have played a role in this (for example, the overtones of a piano are different from those of a harpsichord, so wide major thirds may sound more acceptable on the piano than on the harpsichord).
But did the piano's tonal profile enable equal temperament, or was it caused by equal temperament?  Pianos of the 18th century and even early to middle 19th century also have a different tone from today's pianos.  Most likely, the piano and preferences for tuning systems evolved together to keep pace with changing musical tastes.  Perhaps the tonal profile of the harpsichord would have changed over the course of the 19th century if the piano had never been invented, so equally tempered harpsichords would have sounded better.
In any event, it seems likely that the expansion of the harmonic language would have happened even without the piano, and that it would have led to increased preference for equal temperament.
Comment: Are equal temperament harpsichords the norm, now, or are they tuned to sound better in just one key?
Comment: @Tim neither. There's no such thing, really, as "tuned to sound better in just one key." Harpsichords are usually tuned in some historical temperament, usually chosen to be appropriate for the repertoire being played. For a modern piece calling for harpsichord, that might well be equal temperament, but most often, of course, harpsichords are used for baroque or renaissance music, so some other temperament will be chosen. Equally tempered major thirds tend to sound fairly bad on harpsichords, which was I think one of the reasons for the revived interest in historical temperaments.
Comment: @Tim to add: unequal temperaments sound better in some number of closely related keys. This was workable since many notes would only be used in certain keys (there was not much use for G♭ or D♭ in the Renaissance; those keys would only be used for F♯ and C♯). So older temperaments tend to sound better in keys that are close to C major in the circle of fifths (rather, the relative modes of those keys, such as D Dorian). Even other keys can be usable if you avoid specific intervals, however, or use them only fleetingly or in a functionally dissonant role. Bach even did this in the WTC.
Comment: @phoog: While tuning "to sound better in just one key" is not *practical*, I wouldn't say there is "no such thing." With 5-limit JI, one encounters a conundrum even in tuning a major scale. In C major, a I-vi-ii-V-I will run into problems tuning D (as 9:8 or 10:9). One has to make a choice or temper. As one chooses how to tune a chromatic scale, it can limit the possible use of those notes even within a piece overall in C. One could maximize the intonation for usability within one key, but most practical historical temperaments involved greater compromise to assure playability in several keys.
Comment: @Athanasius There's no such thing because there's no temperament that sounds better in only one key.  If you're tuning in C, for example, and you devise a temperament that makes both the G-D fifth and the D-A fifth usable such as a mean tone temperament, then you have a temperament that is usable in several related keys as well.  As you note, a keyboard tuned in pure just intonation cannot even play all the chords in *one* key unless you allow some Pythagorean major thirds.  This limitation arises even if you exclude chromatic pitches.
Comment: @phoog - Tuning the D to 10:9 for example would make the G-D fifth sound quite a bit flat, so (even assuming only diatonic notes) such a tuning would likely sound better in C major compared to G major (where the flat fifth would be on the tonic chord). Tuning of the "black notes" will also determine which types of common chromatic motions are useful within a particular key. Bottom line is that you can not only design a tuning (including temperaments) just for a particular key but even potentially to maximize intonation for a particular set of chromatic progressions to use within that key.
Comment: @Athanasius if the G-D fifth is unusable then the keyboard is tuned neither to be playable in G nor in C.  The only major keys that tuning could reasonably work in would be keys like A major that lack one of those notes.
Comment: @phoog: "Unusable" is a matter of preference, not an absolute condition. Look at the difference between Bach's preludes in C major and C# major from book I of WTC. Bach employs long lingering tones in the C major, as that key would be more in tune, but uses arpeggiated staccato notes in C# because those chords were less in tune. An interval might be fine for a passing chord or for a special effect, but not one to linger on. Historical composers may have viewed some intervals as completely "unusable," but they were often a lot more accepting of varied intonation than we might be today.
Comment: Anyhow, I'll stop the discussion in comments. My simple point was that one can design all sorts of tunings and temperaments to do all sorts of things and make some things more in tune and other things more out of tune. In some cases, one can privilege the exact chords and scale one wants to use. However, those tunings aren't very practical. The actual historical temperaments that tended to be used were (1) simple to tune and (2) useful in several keys. That doesn't mean one can't create a temperament that is most specifically suited to a single key.
Answer: Up until recently keyboards and fretted instruments were traditionally avoided by orchestras because their equal or quasi-equal temperaments made them out of tune with the other instruments. There is a lot of misinformation - especially in 20th century textbooks - falsely attributing the use of Equal Temperament on keyboard instruments, whereas an exact method of ET tuning was not formulated for the piano (by counting the beat rates for all intervals) until 1917 by W. B. White. The Masters always used meantone or well-temperament. It's only in the last couple of decades that the internet has facilitated the spread of accurate knowledge.
As for fretted instruments the Rule of 18 has been known in ancient Asia since prehistory. Say the scale length is 24 inches, divide by 18, gives the first fret at one and a half inches from the nut, and so on. Such fretted instruments approximate equal temperament very well and thus sound terrible with wind such as brass and fretless strings like violins etc.
Thankfully in the modern age with the simple push of a button one can dial up a faithful historical temperament on a digital piano. It is absolutely amazing to play period pieces by Beethoven, Chopin, etc using quarter-comma meantone with a root of say B flat and witness the beauty and sonority they would have heard back then. With pure major thirds in eight keys and fifths only a few cents narrow the instrument comes alive with beatless resonance.
So yes, the pianoforte is largely responsible for destroying modern music, rendering it toneless and lacking the intrinsic key colour that the great Masters employed so well. You could include the electric guitar as well although they weren't around in the day. If so, I'm sure Beethoven would have instantly smashed up any Fender or Gibson he had the misfortune of hearing.
Comment: Interesting but the last paragraph is probably very opinion based, and very subjective. Fortunately for Beethoven, deafness would have prevented that!
Comment: "Up until recently keyboards and fretted instruments were traditionally avoided by orchestras...".  What about harpsichords in baroque ensembles?  And I thought that the theorbo had frets.  Am I wrong about that?
Answer: As it has been explained in many questions and answers - look on the right edge of this site the related questions - the development of the well-tempered piano was a product of the development of the polyphony and the purpose of composers to modulate through all keys and accompany  chorals and songs in all keys with claves instruments (cembalos, harpsichords, organs, later the forte-piano and the Hammerklavier. This revolution started already in the 17th century when Werckmeister developed his ideas of the well-tempered tuning.
Werckmeister is best known today as a theorist, in particular through his writings Musicae mathematicae hodegus curiosus... (1687) and Musikalische Temperatur (1691), in which he described a system of what we would now refer to as well temperament (named after Bach's opus, "The Well-Tempered Clavier") now known as Werckmeister temperament.
These quotations show that the WTC by Bach has been composed before the first equal tempered pianowas built but his music has been played by clave instruments, harpsichords and organs.
Answer:
The piano was more of a tool than an instrument, allowing practice accompaniment in any key.

That's sort of an absurd statement except for the flimsiest of keyboards in the spinet and clavichord class. And those were generally not in equal temperament.  The whole point of the non-equal well-tempered temperament was to allow playing in any key, and both well and equal temperament came about at a rather late stage of the evolution of keyboard instruments and affected them somewhat across the board.
Fixed arbitrary notes (as opposed to fixed determined notes like that of a natural trumpet) are nothing that came about just with "modern" keyboard instruments: frets (often adjustable) were certainly in use in many instruments of Medieval times (and getting a fretboard smooth enough to enable fretless play is actually non-trivial), and something like a hurdy-gurdy also relies on fixed notes.
Comment: I edited out that last paragraph because it was unnecessary and worded somewhat harshly. Frame-challenging a question in an answer is fine, but this final sentiment could have been expressed in a more respectful manner.


Como alterar o formato da data para o between funcionar

Question: Eu tenho um form type date , que me retorna valores do tipo 2019-10-24 , contudo no meu banco está gravado como 20191024 , isso implica em que caso o usuário coloque numa busca duas datas iguais meu between não funcione . Contundo caso ele bote datas diferentes ele funciona.
<code>$query = ("SELECT * FROM TESTTE WHERE DT_EMISSAO BETWEEN '$data_inicial' AND '$data_final' ORDER BY FILIAL");
</code>
Answer: O que eu fiz e resolveu :
<code>$data_inicial = explode('-', $data_inicial);     // transforma em array
$data_inicial = implode('', $data_inicial);     // transforma em string novamente
$data_final = explode('-', $data_final);     // transforma em array
$data_final = implode('', $data_final);     // transforma em string novamente
</code>
Comment: Um link que talvez possa te ajudar: http://www.consultoriadba.com/post/2017/08/23/fun%C3%A7%C3%B5es-de-data-no-sql-server e este envolvendo com PHP http://www.devwilliam.com.br/php/10-funcoes-php-trabalhar-data-e-hora


Does it make sense to take the derivative of f(x) with respect to g(x)?

Question: Let $f(x) = \sin(x)$ and $g(x) = \cos(x)$.
Then I want to find the derivative of sin(x) with respect to cos(x).
So I have:
$$\frac{d\sin(x)}{d\cos(x)}$$
$d/dx \sin(x) = \cos(x)$, so $d\sin(x) = \cos(x)dx$.
$d/dx \cos(x) = -\sin(x)$, so $d\cos(x) = -\sin(x)dx$.
Then,
$$\frac{d\sin(x)}{d\cos(x)} = \frac{\cos(x)dx}{-\sin(x)dx} = -\cot(x)$$
Is this legit or am I doing something wrong here?
Comment: Does this answer your question? [Derivative of a function with respect to another function.](https://math.stackexchange.com/questions/954073/derivative-of-a-function-with-respect-to-another-function)
Answer: We have:$$\frac{d(\sqrt{1-\cos^2x})}{d(\cos x)}$$Substitute $u=\cos(x)$:
$$\frac{d}{du}(\sqrt{1-u^2})$$
Can you continue from here?
Comment: @Stacker it is $\frac{-\cos x}{\sqrt{1-\cos^2x}}=-\cot x$
Comment: $\frac {-2u} {2\sqrt{1-u^2}}=\frac {-\cos x}{\sqrt{1-\cos^2 x}}=-\cot x \csc x$
Comment: Ah. Thanks for pointing it out


How to delete stuck batch?

Question: What is a good way to delete a stuck batch in Drupal 7?
It is on a production server, we are using the Background Batch module so it shows us which one it is at admin/config/system/batch/overview.
I know I can just run a query and delete that row from the DB but wondering about other cleanup I should do too.
Answer: Another approach (if you don't want to run sql-statements directly) would be Queue UI:

View queues and number of items
Developers can define meta info about queues they create and process
Process queue with Batch API
Process queue during cron
Remove leases
Delete queue
Comment: batches are treated as queues, so yes.
Comment: Thanks, was looking for something quick and easy to run on a production server without committing new code. Does this delete batches though or just queues?
Comment: 4 years later, I just accepted this answer! I remember now that this worked well for that project, thanks again!
Answer: In my case the batch ID is 5166:
DELETE FROM batch WHERE bid IN (5166);
In our case we are using Better Batch and we also needed to run:
DELETE FROM better_batch WHERE bid IN (5166); otherwise we received an infinite redirect message in Chrome "too many redirects".
source: https://www.drupal.org/node/1627850#comment-6142774

How to delete stuck batch?


Problem with adding Views - they cannot be saved

Question: I have problem with creating new views (or clone old ones). All process is doing well, I choose my filtres etc; but when I'm trying to save it's an error - and they don't show in the views list (even if it's said that it "has been saved"). I've already tried several times but it doesn't work. I dont know why - before I didn't have this problem...
Answer: Have you tried running update.php? Or try clearing the Drupal cache which you can do quickly with drush using drush cc all.
I find this is always a good place to start.
Answer: It's stated in the error message. You're missing the core column in the views_view table. If this is a new install, then you can disable, uninstall and after wards re-enable the views module.
Otherwhise execute this code in SQL (PHPMyAdmin or whatever database GUI you use):
ALTER TABLE `views_view` ADD `core` int(11) DEFAULT '0' COMMENT 'Stores the drupal core version of the view.';
UPDATE `views_view` SET core = 6;

Assuming an SQL dialect, e.g. MySQL, and Drupal 6.


How to check that package is not present on server in SaltStack state file?

Question: I am trying to automate an Aerospike database installation using saltstack version 2015.5.2 on an Ubuntu machine.
The following is the process of manual installation that I want to automate. (I'll only mention the key steps to keep it simple)

Download Aerospike
wget -O aerospike.tgz
http://aerospike.com/download/server/latest/artifact/ubuntu12
extract the contents of the package
tar -xvf aerospike.tgz
Install Aerospike Server & Tools
cd aerospike-server-community-3.5.15-ubuntu12.04
./asinstall
Start Aerospike
/etc/init.d/aerospike start

Step 3 performs the actual installation which includes installation of 2 packages: aerospike-server-community and aerospike-tools.
Now in the saltstack state file I want to check if both the packages are already present on server, and in that case do not execute the ./asinstall command in step 3.
How can I involve that condition in my automated process?
Answer: I recommend you read requisites in salt before going on because you can find many interesting things there.
Furthermore,what you really need, in my opinion is: UNLESS, because if you already have these packages on your system they should not be installed. Unless can be used together with the pkg keyword, but for you the rpm -q package_name might work just as well.
It should look something like this:
start_process:
  cmd.run:
    - name: 'write here your command'
    - unless:
      - rpm -q package1,package2

Answer: I would like to provide a small comment to the answer, but my reputation does not allow me, so I apologize in advance for this.
This line:
- rpm -q package1,package2

Should actually be:
- rpm -q package1 package2


Ruby on Rails 3 gsub escapes the anchor of link_to method

Question: I want to check a string and change any @something to link. So I have a helper function which consists of something like this:
def parse(content)
  content.gsub(/@[a-zA-z0-9]+\b/, link_to("#{$1}", user_path($1)) )
end

But the result is
The problem is :

The  is a string, because somehow the < and > is escaped.
Why does "#{$1}" return nothing? Isn't it supposed to return whatever is checked upon, in this case @something?
Answer:
Rails HTML-escapes any content produced by a user-defined helper, unless you tell it not to. Try using <%= raw parse(content) %> in your view.
Quoting Pickaxe on gsub:

If a string is used as the replacement, special variables from the match (such as $& and $1)
  cannot be substituted into it, because substitution into the string occurs before the pattern match
  starts. However, the sequences \1, \2, and so on, may be used to interpolate successive numbered
  groups in the match, and \k<name> will substitute the corresponding named captures.

So you can't use #{$1} because $1 isn't set until after the command has finished. Your best bet is probably to use the block form of gsub - in which case $1 is set inside the block. Try:
def parse(content)
  content.gsub(/@[a-zA-z0-9]+\b/) {link_to($1, user_path($1))}
end

Comment: I've tried you solution, but now the anchor text and the href are the same, i mean, $1 returns the same value which is : /users/102 . Any ideas?
Comment: nevermind, i'm using block like this and it works now. { |str| link_to(str, $1)  } Thanks!


Change alpha based on factor group in ggplot

Question: dftt <- data.frame(values = runif(27, min = 0, max = 1),

                   Position_Group = c("Detroit.1-3", "Detroit.1-3", "Detroit.1-3",
                                  "Detroit.4-6",  "Detroit.4-6",  "Detroit.4-6",
                                   "Detroit.7-9",  "Detroit.7-9",  "Detroit.7-9",
                                  "Chicago.1-3", "Chicago.1-3", "Chicago.1-3",
                                  "Chicago.4-6", "Chicago.4-6", "Chicago.4-6",
                                  "Chicago.7-9","Chicago.7-9","Chicago.7-9",
                                   "Atlanta.1-3", "Atlanta.1-3", "Atlanta.1-3",
                                  "Atlanta.4-6","Atlanta.4-6","Atlanta.4-6",
                                  "Atlanta.7-9","Atlanta.7-9","Atlanta.7-9"),

                   name = c("Detroit", "Detroit", "Detroit",
                            "Detroit", "Detroit", "Detroit",
                            "Detroit","Detroit","Detroit",
                            "Chicago", "Chicago", "Chicago",
                            "Chicago", "Chicago", "Chicago",
                            "Chicago","Chicago","Chicago",
                            "Atlanta", "Atlanta", "Atlanta",
                            "Atlanta", "Atlanta", "Atlanta",
                            "Atlanta", "Atlanta", "Atlanta"),

                   x = c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3))

dftt$Position_Group <- as.factor(dftt$Position_Group)

levels <- unique(dftt$Position_Group)
dftt$Position_Group <- factor(dftt$Position_Group, levels = levels)
dftt <- dftt[order(dftt$Position_Group),]

 dataset2 <- dftt %>%
        ggplot(aes(x=x, y=values, group = Position_Group , color = name, alpha = Position_Group)) + geom_line(size = 3) +
        scale_alpha_discrete(range = c(1, 0.4, 0.1))

 dataset2

I am attempting to change the alpha value for each factor group. For example, I want Detroit.1-3 to be the darkest, Detroit.4-6 to be the second darkest, and Detroit.7-9 to be the lightest. I would like to apply this to Chicago and Atlanta as well. I've provided my code above, but unfortunately, it seems like this only works for 2 of the city names, while the third city's alpha values are unchanged. Any ideas on how I can tweak my code to achieve the desired outcome? Thanks.
Answer: Is this what you're looking for?  If so, the answer is splitting off the group values from the city names.  I did this using separate().  Then you can map alpha to this new group variables.
library(dplyr)
library(ggplot2)
library(tidyr)
dftt <- data.frame(values = runif(27, min = 0, max = 1),

                   Position_Group = c("Detroit.1-3", "Detroit.1-3", "Detroit.1-3",
                                      "Detroit.4-6",  "Detroit.4-6",  "Detroit.4-6",
                                      "Detroit.7-9",  "Detroit.7-9",  "Detroit.7-9",
                                      "Chicago.1-3", "Chicago.1-3", "Chicago.1-3",
                                      "Chicago.4-6", "Chicago.4-6", "Chicago.4-6",
                                      "Chicago.7-9","Chicago.7-9","Chicago.7-9",
                                      "Atlanta.1-3", "Atlanta.1-3", "Atlanta.1-3",
                                      "Atlanta.4-6","Atlanta.4-6","Atlanta.4-6",
                                      "Atlanta.7-9","Atlanta.7-9","Atlanta.7-9"),

                   name = c("Detroit", "Detroit", "Detroit",
                            "Detroit", "Detroit", "Detroit",
                            "Detroit","Detroit","Detroit",
                            "Chicago", "Chicago", "Chicago",
                            "Chicago", "Chicago", "Chicago",
                            "Chicago","Chicago","Chicago",
                            "Atlanta", "Atlanta", "Atlanta",
                            "Atlanta", "Atlanta", "Atlanta",
                            "Atlanta", "Atlanta", "Atlanta"),

                   x = c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3))

dftt$Position_Group <- as.factor(dftt$Position_Group)

levels <- unique(dftt$Position_Group)
dftt$Position_Group <- factor(dftt$Position_Group, levels = levels)
dftt <- dftt[order(dftt$Position_Group),]

dftt %>%
  separate(Position_Group, into=c("city", "group"), sep = "\\.") %>%
  ggplot(aes(x=x, y=values,color = name, alpha = group)) + geom_line(size = 3) +
  scale_alpha_discrete(range = c(1, 0.4, 0.1))
#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` instead.
#> Warning: Using alpha for a discrete variable is not advised.

Created on 2023-02-27 with reprex v2.0.2
Comment: This works perfectly! However, my legend isn't as clean as yours. I am actually converting my ggplot to plotly using the ggplotly function. So, my legend says (p1-3 Detroit, p1-3 Atlanta, p1-3 Chicago, p4-6 Detroit, p4-6 Chicago, etc.) -- is there any way I can make the legend look like yours in plotly if you happen to know?
Comment: Looks like it might be a bit complicated, though there is a discussion of something similar [here](https://stackoverflow.com/questions/42820823/r-plotly-preserving-appearance-of-two-legends-when-converting-ggplot2-with-ggpl).


How to test HTTPS in Flask

Question: The following simplified code is defined in my flask app.
def select_url_for():
    if request.is_secure:
        return 's3'
    return 'local'

I tried testing like this, and it works for HTTP.
def test_select_url_for(self):
    with self.app.test_request_context():
        self.assertTrue(select_url_for() == 'local')

How do I perform a similar test for the HTTPS with Flask?
I found this, but the question is unanswered. I need to run Flask in a HTTPS test mode.
Answer: request.is_secure check wsgi.url_scheme environment variable. By overriding it with https make request.is_secure returns True:
def test_select_url_for(self):
    with self.app.test_request_context(environ_overrides={
            'wsgi.url_scheme': 'https'
    }):
        self.assertEqual(select_url_for(), 'local')

BTW, instead of assertTrue(a == b), use assertEqual(a, b) which give you more readable assertion failure message.

How to test HTTPS in Flask


Activate using KMS on different domain

Question: We have a client where we have built new servers including DC,DNS servers, lets call it, 'new.com'. These servers are activated using the KMS host in our PROD domain 'main.com'.
1) Would OS license fail/deactivate if no contact is made to the KMS host atleast once in every 180 days ?
2) Would I need to connect each server in new.com atleast once every 180 days, to the KMS host in 'main.com' to renew the license ? If yes, is there any other/easier way to make sure the licenses on servers in 'new.com' do not get deactivated?
Answer: 1: as per documentation that is the whole sense of a KMS.
2: Sure, do not use a KMS - use a MAK (Multi Activation Key).
The whole sense of a KMS is to facilitate temporary activations under the condition that the machine connects to the KMS once per 180 days. Not every scenario supports a KMS nicely - if it does not fit, there are other ways to activate machines.

Activate using KMS on different domain


R ggplot How do I choose the colors of a raster with 2 values

Question: Here's a simple example of my problem. Steps are 1. create a SpatRaster (terra's version of a raster) with 10 rows, 10 columns and all cell values either 0 or 1. Step 2. Convert to a data frame and rename the columns. Step 3. Create a graph with ggplot. It uses blue and black for the colors and has a continuous legend.
library(terra)
x <- rast(nrow=10, ncol=10, xmin=0, xmax=1)
values(x) <- sample(c(0,1), replace=TRUE, size=100)
x_df <- as.data.frame(x, xy = TRUE)
names(x_df) <- c("x", "y", "value")
col1 <- c("red", "green")
g <- ggplot(data = x_df, aes(x, y,  fill = value)) +
  geom_tile()

Now I'd like to change the colors to those in col1. I have tried putting colors = col1 in the ggplot aes section and outside it, in an aes in geom_tile, and a few other options. Pretty much all return the error message  Error: Aesthetics must be either length 1 or the same as the data (100): xxx.
Converting value to a factor solves one problem (the legend is now discrete 0,1) but I still can't figure out where to add code to change the default two colors.
Answer: Try this:
g <- ggplot(data = x_df, aes(x, y)) +
  geom_tile(aes(fill = value)) +
  scale_fill_gradient(low="red", high="green")
g

Comment: This works, but hard wires the colors into scale_fill_gradient. And doesn't work if `value` is a factor. With value as a factor I tried scale_fill_discrete(type = col1). That returns the error  `Error: Continuous value supplied to discrete scale `
Comment: I'm not sure I understand. If `value` is `factor` the values will be discrete in your example (0 or 1) and so you can use `scale_fill_manual(values = c ("red", "green"))`
Comment: Yes! And I can use scale_fill_manual(values = col1)!


EF Core Relationships one-to-many-to-many FluentAPI

Question: Boa tarde,
Gostaria de tirar uma dúvida de relacionamento no Entity Core.
Tenho uma tabela pessoa e a pessoa tem um cargo (Gerente, supervisor, responsável, etc..)

public class Pessoa
{
    public int PessoaId { get; set; }
    public string Nome { get; set; }
    public int CargoId { get; set; }
    public virtual Cargo { get; set; }
}

public class Cargo
{
    public int CargoId { get; set; }
    public string Nome { get; set; }
    public virtual ICollection Pessoas { get; private set; }
}

Até o momento não tenho dúvidas.
Agora vamos supor que tenho uma tabela Sala e essa sala tem um Gerente, um supervisor e um responsável, que são Pessoas. Como ficaria o relacionamento ?
Assim:

public class Sala
{
    public int SalaId { get; set; }
    public string Nome { get; set; }
    public int ResponsavelId { get; set; }
    public virtual Pessoa Responsavel {get; set; }
    public int SupervisorId { get; set; }
    public virtual Pessoa Supervisor {get; set; }
    public int GerenteId { get; set; }
    public virtual Pessoa Gerente {get; set; }

}

E alteraria Pessoa

public class Pessoa
{
    public int PessoaId { get; set; }
    public string Nome { get; set; }
    public int CargoId { get; set; }
    public virtual Cargo { get; set; }

    public virtual ICollection Salas { get; private set; }
}

E criaria o relacionamento no de cada campo no Fluent API com a propriedade Salas ou

public class Pessoa
{
    public int PessoaId { get; set; }
    public string Nome { get; set; }
    public int CargoId { get; set; }
    public virtual Cargo { get; set; }

    public virtual ICollection SalaResponsavel { get; private set; }
    public virtual ICollection SalaSupervisor { get; private set; }
    public virtual ICollection SalaGerente { get; private set; }
}
Answer: Nessa forma que está fazendo, ficaria assim:
<code> public virtual Sala SalaResponsavel { get; private set; }
 public virtual Sala SalaSupervisor { get; private set; }
 public virtual Sala SalaGerente { get; private set; }
</code>
Mas, acho que fica um tanto bagunçado, acho que faria outra tabela contendo
<code>Sala
Pessoa
Cargo
</code>
Assim a relação ficaria de n-n
Estou pelo celular agora, a noite tento complementar mais a resposta
Comment: Acho que entendi sua ideia. Mas o que acontece é que as pessoas já possuem um cargo independente de estarem associadas a sala ou não. Por isso hoje eu tenho a tabela Pessoa e a Cargo. Na salas eu tenho que vincular pessoas que possuem determinados Cargos. Talvez eu possa criar uma tabela para fazer um n-n tipo PessoasSala mas não ficaria explicito os cargos que tenho que associar.
Comment: Acredito que https://stackoverflow.com/questions/42745465/ef-core-many-to-many-relationship-on-a-class resolva meu problema. Amanhã vou testar e retorno.
Answer: Para o meu contexto a resposta do link abaixo foi a solução.

https://stackoverflow.com/questions/42745465/ef-core-many-to-many-relationship-on-a-class

Fiz o mapeamento e a entidade carregou sem problema. Agora com o Dapper preenche os dados. Obrigado.


Which of the choices solution of the Cauchy problem?

Question: Consider the Cauchy problem of finding $u=u(x,t)$ such that $$\frac{\partial{u}}{\partial{t}}+u\frac{\partial{u}}{\partial{x}}=0\text{ for }x\in\mathbb{R},t>0\\u(x,0)=u_0(x),\;x\;\epsilon\;\mathbb{R}$$
which choice(s) of the following functions for $u_0$ yield a $C^1$ solution $u(x,\ t)$ for all $x\in\mathbb{R}$ and $t>0.$

$u_0(x)=\frac{1}{1+x^2}$
$u_0(x)=x$
$u_0(x)=1+x^2$
$u_0(x)=1+2x$

Because characteristic of the given PDE is $U=U_0(x-ut)$ from option 2, 4 only the satisfies the given PDE is i am right
Comment: @KprimeX: here for option(1): U=Uo(x-ut)=x-ut, satisfies the given PDE,
Comment: 4 is the also solution ,but how 3 can u explain me
Comment: yes 3 does't satisfies the equation
Comment: here by cauchy problem u(x,t)= Uo(x-ut) can any help me what next
Comment: how we going to proceed this problem
Comment: this question was asked in CSIR exam plz help me solve this question
Comment: @P suresh How do you conclude from the characteristics that $2$ and $4$ are correct?
Comment: @P suresh: but $3$ and $4$ also satisfies the PDE.
Comment: does not 3 also satisfies the PDE?
Comment: can you show me why $3$ does not satisfies the PDE?
Answer: Using method of characteristics, we set $t=t(r),x=x(r)$, then $u=u(r)$ along characteristic curve. Then
$$\frac{du}{dr}=\frac{\partial u}{\partial t}\frac{dt}{dr}+\frac{\partial u}{\partial y}\frac{dy}{dr}$$
Letting $\frac{dt}{dr}=1$, $\frac{dx}{dr}=u$ and thus $\frac{du}{dr}=0$.
$\frac{dt}{dr}=1\implies t=r$. Now, $u$ is constant along characteristic curve, so we have $\frac{dx}{dr}=\frac{dx}{dt}=c\implies x-ct=d$.
$\frac{du}{dr}=\frac{du}{dt}=0\implies u=F(d)=F(x-ut)$
Now, checking initial conditions one by one, only (2) and (4) gives a solution which satisfies the equation.
Comment: Can you show me why any one of $1$ and $3$ does not satisfy the given equation?
Comment: I am missing something may be, lets see, for $u(x,t)=1+(x-ut)^2$, then $\partial u/\partial x=2x-2ut$ and $\partial u/\partial t=-2xu+2u^2t=u(-2x+2ut)=-u\partial u/\partial x$ so it satisfies the equation. Where is my mistake?
Comment: @KushalBhuyan..check boundary condition for ur solution..


In Unity, how do I inject a named dependency into a constructor with other dependencies?

Question: I have a service with some dependencies but 1 of them is a named dependency. So, want to config my Unity container to inject that.
I have some like this:
Register of types in Unity container:
container.RegisterType<IOtherService, Implementation>("SpecificImp);
container.RegisterType<IOtherService, OtherImplementation>("otherImp");

container.RegisterType<IService, Service>(
    new InjectionConstructor(                  // Explicitly specify a constructor
        new ResolvedParameter<IOtherService>("SpecificImp") // Resolve parameter of type IRepository using name "Client"
    )
);

Service:
puclic class Service : IService
{
     private read-only IOtherService _otherService;
     private read-only IworkContext _workContext;

    public Service(
        IOtherService otherService,
        IworkContext workContext)
    {
        _otherService = otherService;
        _workContext = workContext;
    }
}

But the compiler show me a error,
'Implementation' dont have a contrusctor with 'IOtherService' parameter.
So, who can i config mi container to inject correct implementation?
Answer: If you are specifying any constructor parameter explicitly, then you need to specify all parameters of that constructor
container.RegisterType<IService, Service>(
    new InjectionConstructor(                  // Explicitly specify a constructor
        new ResolvedParameter<IOtherService>("SpecificImp"), // Resolve parameter of type IRepository using name "Client"
    new ResolvedParameter<IworkContext>()
)


Executar função jQuery em tabela gerada dinamicamente após um AJAX

Question: Preciso executar a função abaixo, após a requisição do AJAX ele tem que remover a linha da tabela, se eu coloco o código que remove a linha direto na função ele remove a linha normalmente, mas se eu coloco dentro do success do AJAX ele não remove a linha e  executa o alert normalmente no final.
$('#tabelaMaterial').on('click', '.icon-remove', function (event) {
    $.ajax({
        url: "/RCM/RemoveItemCarrinho",
        type: "POST",
        success: function () {
            $(this).closest('tr').remove();
            alert("Material removido!");
        }
    })
})

Answer: É uma questão de escopo, o this lá no success é outra coisa:
$('#tabelaMaterial').on('click', '.icon-remove', function (event) {
    var $this = $(this);
    $.ajax({
        url: "/RCM/RemoveItemCarrinho",
        type: "POST",
        success: function () {
            $this.closest('tr').remove();
        }
    });
});

Relacionado: Qual a diferença entre $(this) e $this e this?
Comment: Funcionou certinho, muito obrigado.
Comment: @Alan, acrescentei um link importante na resposta.


transitions property not working in safari browser

Question: Css Transition effects on my website don't work in safari (tested on latest version). And transition is working well in others browser tested in Chrome, firefox, and Opera.
My code is the following:
.navbar-inverse ul a{
     overflow: hidden;
    -webkit-transition: color 0.5s;
    -o-transition: color 0.5s;
    -moz-transition: color 0.5s;
     transition: color 0.5s;
}

.navbar-inverse  ul a::before{
    -webkit-transition: top 0.5s;
    -o-transition: top 0.5s;
    -moz-transition: top 0.5s;
     transition: top 0.5s;
}

How to fix it? After that transition works in safari too.
Comment: Questions seeking code help must include the shortest code necessary to reproduce it **in the question itself** preferably in a [**Stack Snippet**](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/).  See [**How to create a Minimal, Complete, and Verifiable example**](http://stackoverflow.com/help/mcve)
Answer: The problem is that you placed the transition property for the element with the pseudo element before. Try placing the transition property for the element itself. This is what I mean:
.navbar-inverse ul a{
   overflow: hidden;
  -webkit-transition: color,top 0.5s;
  -o-transition: color,top 0.5s;
  -moz-transition: color,top 0.5s;
   transition: color,top 0.5s;
}


Proving a limit involved in the Lagrangian inversion of $\frac{\log\sqrt{1+x}}{\sqrt{1+x}}$

Question: In my attempt to complete this answer, I hit a snag in showing that
$$\lim_{t\to 0} \dfrac{\mathrm d^{k-1}}{\mathrm dt^{k-1}}\left(\frac{t\sqrt{1+t}}{\log\sqrt{1+t}}\right)^k=2(k+2)^{k-1}$$
This shows up when trying to apply Lagrangian inversion to the function $\dfrac{\log\sqrt{1+x}}{\sqrt{1+x}}$. My sticking point here is that I am unable to find a convenient expression for the derivatives. Is there an easy proof for this?
Comment: @Asaf, sorry; I needed something to reflect my general mood, and this suited me nicely.
Comment: I can relate...
Answer: Complex analysis comes to the rescue. Using Cauchy differentiation formula:
$$
  f^{n-1}(0) = \frac{(n-1)!}{2 \pi i} \oint \frac{f(z)}{z^n} \mathrm{d} z
$$
Now
$$ \begin{eqnarray}
  \lim_{t\to 0} \dfrac{\mathrm d^{k-1}}{\mathrm dt^{k-1}}\left(\frac{t\sqrt{1+t}}{\log\sqrt{1+t}}\right)^k &=&
   \frac{(k-1)!}{2 \pi i} \oint\left(\frac{t\sqrt{1+t}}{\log\sqrt{1+t}}\right)^k \frac{\mathrm{d} t}{t^k} \\ &=&
  \frac{(k-1)!}{2 \pi i} \oint \left(\frac{\sqrt{1+t}}{\log\sqrt{1+t}}\right)^k \mathrm{d} t
  \end{eqnarray}
$$
Now performing the change of variable $t = \mathrm{e}^u-1$:
$$ \begin{eqnarray}
   \lim_{t\to 0} \dfrac{\mathrm d^{k-1}}{\mathrm dt^{k-1}}\left(\frac{t\sqrt{1+t}}{\log\sqrt{1+t}}\right)^k &=& \frac{(k-1)!}{2 \pi i} \oint \left( \frac{\exp(u/2)}{u/2} \right)^k \mathrm{e}^u \mathrm{d} u \\
  &=& 2^k \left[ \frac{(k-1)!}{2 \pi i} \oint \frac{\exp( u(k/2+1)}{u^k} \mathrm{d} u \right] \\
  &=& 2^k \lim_{u \to 0} \dfrac{\mathrm d^{k-1}}{\mathrm du^{k-1}} \mathrm{e}^{ u \left(\frac{k}{2}+1\right) } = 2^k \left(\frac{k}{2}+1\right)^{k-1} = 2 (k+2)^{k-1}
 \end{eqnarray}
$$
Comment: Thanks! Cauchy slipped my mind. This helps to justify the series expansion of $W(-x)^2$ in the answer I linked to.
Comment: @J.M.isn'tamathematician Correct if I am wrong, but, the Cauchy differentiation formula is only valid for holomorphic $f(z)$. In this case, the derivative by Cauchy is invalid since the logarithm in the denominator points to a singularity at $t=0$, thus is not holomorphic.
Comment: @Physicist, isn't the singularity at $0$ the removable kind? Looks like it to me. Alternatively, I can develop both $\log\sqrt{1+t}$ and $t\sqrt{1+t}$ as Maclaurin series, and perform series division...


Como fechar janela VSCode?

Question: Toda vez que estou codando no VSCode, ela fica aparecendo pequenas janelas de sugestões a todo momento. E não é aquela mesma do atalho "Ctrl + Espaço". Essa que estou falando é uma outra janela.
Vocês sabem como posso desabilitar isso? Pois ela entra na frente do código e atrapalha a visualização

A janela é essa em vermelho
Answer: Isso é do Intellisense vc pode ver mais opções aqui https://code.visualstudio.com/docs/editor/intellisense#_customizing-intellisense
Mas basicamente esse código vai fazer as sugestões desaparecerem enquanto vc digita, vc tem que salvar esse código no JSON dos Settings ok
  "editor.quickSuggestions": {
    "other": false,
    "comments": false,
    "strings": false
  }

Comment: Precisei adicionar "editor.parameterHints.enabled": false, esse código também, aí funcionou. Obrigado.
Answer: Coloquei na primeira linha do settings.json
"editor.hover.enabled": false,

e resolveu. Nenhuma dica é mostrada ao hover.

Como fechar janela VSCode?


What is the simplest way to transfer data between online running logs?

Question: I'm disillusioned with Nike+, where I've been logging runs for over a year, and ready to try something new (in this case, Strava). How can I export my data from Nike+ so I'm not losing it all?
Comment: This sounds more like a question for [webapps.se] than sports (although it's probably on topic both places, this is likely more technical than what we should be handling)
Comment: Also: eagerfeet.org is currently [having problems](https://twitter.com/eagerfeet/status/241625871595749376) so I think any and all tools are fair game for an answer.
Comment: I'm voting to close this question as off-topic because it's about a mobile application
Comment: Try http://eagerfeet.org/
Comment: @waxeagle, that's actually my hidden agenda for posting this question. :) Data portability in running logs has been [an issue of mine](http://www.flashesofpanic.com/panic/001457.php) for years.
Comment: There's probably an argument for closing it because its answers are mostly obsolete.
Comment: Steve Chapman (http://stephen-chapman.com/blog/2011/03/14/keeping-track-of-my-running-data/) mentions that he used Trailrunner to migrate his data into Runkeeper. You might want to check that out as well.
Comment: After running into difficulties with EagerFeat, I found this works great: https://mattstuehler.com/lab/NikePlus/
Answer: Endomondo.com works very well importing all the information from Nike+. After that you can use it to export individually to some other services, or use it as I think is pretty good.
Answer: Update:
Sorry folks for taking so long to get around to this update - I had to retire this tool in 2016 ago due to nike changing their API, and not having enough time to re-engineer the code, so this is no longer an acceptable solution.
Original Post:
I wrote a tool to help export workouts from nike+ for upload into other tools like Strava or Runkeeper: http://nikeplusexporter.rhysmccaig.com/
Answer: Trailrunnerx on osx can sync with nike+, including after Nike's recent changes to their API. From there one can export to various file formats. The gpx-tracks has worked for me for uploading to Strava and MapMyRun. Runkeeper on the other hand seemed to have trouble extracting the relevant data from these files. The Smashrun website can sync with nike+ directly. It's good for numbers, but doesn't have maps yet. MayMyRun also connects directly to Nike+, but doesn't seem to import gps data/maps and doesn't offer any graphs or statistics. It does so only when importing from files rather than through nike+.
Answer: Note that I've changed this answer several times, to keep up with current status.
TLDR: Use Smashrun, then Tapiriik
In the previous months/years Nike has been changing the way it provides data; including who it provides it to.
I'd been using the exporter by Rhys McCaig for quite some time, but he has since discontinued his tool. I've also tried Tapiriik, which is great, but the Nike+ service is still in beta (I always get the message "Some activities could not be synchronized").
Smashrun is able to import Nike+ runs directly. From there if you still want to export somewhere else (or just upload TCX files to Dropbox) you can use Tapiriik.
Answer: http://www.rungap.com/ supports a whole bunch of apps including Runkeeper, Garmin and Nike+. Unfortunately, it's doesn't provide online access. Just smartphone app access.
Update: Smashrun can import runs from Nike+ and Garmin directly. It also supports importing gpx/tcx files. I have the free membership for now. It is pretty bare bones, but from the looks of it the pro membership provides more valuable information and analytics.
Answer: The Android app SyncMyTracks can import and export from and to Nike+, Strava, RunKeeper, Endomondo, Garmin Connect and other services. I've been using it for a few months, and it works great!
Answer: I'm not sure what format the Nike files are, but the Fit File Repair Tool offers the most comprehensive options for conversion from and into the most commonly used formats (fit, tcx, and hrm). On top of that, it lets you fix faulty files, e.g. when the gps or the heart rate monitor went crazy due to interferences.
If conversion to tcx is sufficient, I found tcx creator to work quite smoothely. It's main purpose is to combine hrm files (from your heart rate monitor) with gpx files (from your gps device), but it also works if you skip the gpx files and just feed it with hrm.
So basically, what you need to do is check what file format Nike produced for you and check what your new online service can import (most likely one or more of the above). According to the tcx creator website, all of the following accept tcx files: endomondo.com, strava.com, connect.garmin.com, runkeeper.com
Answer: The (free) online app called Tapiriik provides a great way to sync between many applications. Including endomondo, strave, runkeeper, dropbox, garmin, ride with gps, motivato, and many others.
Answer: I have written as well a PHP script to export those data: https://github.com/cheesemacfly/nikeplusexport
(there is a link to a demo on the page)
The main difference I have with the other ones is that the time for each waypoint is calculated so I found it more precise.
It works only with the runs having GPS data and can export to GPX, TCX and JSON.
Answer: If you have an iOS device, you might find this app handy: https://rungap.zendesk.com/entries/45048583-Using-Endomondo-with-RunGap


How do I implement bootstrap's panel component for a specific block / block region in my bootstrap (sub) theme?

Question: I have a bootstrap sub-theme, and would like to render some of my blocks using Bootstrap's Panels components, so that the block would need to be wrapped something like this:

    {{ header }}

    {{ content }}

So far I've tried to implement this via the following series of dirty hacks:

Setting the css-class setting on the advanced settings of the view to panel panel-default
wrapping the header of the view in a
 block
setting the row-class parameter in the settings of the view's unformatted list format to panel-body

This almost works, but isn't quite right:

The issue is that the resulting classes aren't nested correctly:

If I manually modify the classes in my browser and set view-header to panel-heading and view-content to panel-body I get the desired effect:

So I know what I want, but how do I achieve this? I'm new to twig and I feel like there must be an easy solution to this out there, I just don't know what it is. Note that I don't want to make every block behave like this, just this one.
Answer: Quick-and-dirty way: Uncheck all the boxes to display default classes in Views, and then use a twig template specifically for that views block to write the CSS exactly as you want.
You can find the Views twig templates in /core/modules/views/templates.
It depends on how you configured the view, but if it's an unformatted block, you want the unformatted template, views-view-unformatted.html.twig.  Copy that file from the Views template directory into your subtheme's directory.
Next, you have to rename the file so that it only applies to the block. In Drupal 7, Views was nice and gave you the suggested theme hooks, but in Drupal 8, you have to figure them out yourself.
The rule is TEMPLATE_NAME--VIEW_MACHINE_NAME--DISPLAY_MACHINE_NAME.
If you go to edit the view in the admin UI, you can get this info from the URL.
/admin/structure/views/view/VIEW_MACHINE_NAME/edit/DISPLAY_MACHINE_NAME.
Once you rename the file, you will need to rebuild the cache to get Drupal to use it.
Sometimes you may need to customize other views templates as well (a single view can use multiple templates); you can do that in the same way as described above..
Comment: Great, that's exactly what I needed. One note; I got a better result by copying and modifying the `views-view.html.twig` file from `bootstrap/templates/views/views-view-html.twig`, but I guess your solution is more general. I found [this link](https://www.drupal.org/docs/theming-drupal/twig-in-drupal/twig-template-naming-conventions#s-views) really helpful to break down the twig naming conventions. Thanks again.


Find all group homomorphism from $(\Bbb Z_4, +_4)$ to $(S_3,\circ)$.

Question: Find all group homomorphism from $(\Bbb Z_4, +_4)$ to $(S_3,\circ)$.
Attempt:
Let $e_G$ denote the identity element in a group $G$.
The map $f(a)=e_{S_3}$ is the trivial group homomorphism.
Now, notice that $\Bbb Z_4$ is cyclic, i.e., $\Bbb Z_4 = \langle 1,3 \rangle$. Let $|a|$ be the order of an element $a$ of a group $G$. Then $|1|=|3|=4$. Next, for any $a \in G$ with $|a|=n$, we must have $|f(a)| \mid n$. Hence, $|f(a)| \mid 4$ for all $a \in \Bbb Z_4$. Now, the non-trivial elements in $S_3$, which the order divide $4$, are $(1 \ 2), (1 \ 3),$ and $(2 \ 3)$.
Hence, we found three mappings, namely, $f(a)=(1 \ 2)^a, f(a)=(1 \ 3)^a$, and $f(a)=(2 \ 3)^a$, for any $a \in \Bbb Z_4$, where $(x \ y)^k$ denotes the composition of $(x \ y)$ with itself $k$ times. It's not difficult to show that indeed these mappings are a group homomorphism.
Therefore, in total, there are $4$ group homomorphism from $\Bbb Z_4$ to $S_3$, where $1$ is the trivial group homomorphism, and the other three are non-trivial homomorphism.
Is it work? Thanks in advanced.
Comment: You mean $|f(a)|$ divides $n$
Comment: @AlexanderGruber My bad, sorry. Yes, it's.
Comment: @AlexanderGruber Is it work?
Answer: Once you solve such a problem, it's worth trying to extend it to a more general task: for an integer $n \geq 2$ and a group $G$, count the number of homomorphisms $\mathbf Z/n\mathbf Z \to G$. Show this number equals the number of $g \in G$ such that $g^n = 1$ (i.e., the order of $g$ divides $n$).
When $n = 4$ and $G = S_3$, you want to count solutions to $g^4 = 1$ in $S_3$, which amounts to counting elements of order $1$ or $2$ (other elements have order $3$), and there are $4$ of those elements in $S_3$.


Where is asp.net mvc3 controller parameter coming from?

Question: I am relatively new to MVC3 and had a question about a parameter in a controller.
I have a controller that takes an id
public ActionResult ChooseItem(string id) ...

This controller's view creates a form, and when the user submits the form it posts to this controller
[HttpPost]
        public ActionResult ChooseApp(string id, string itemID)...

The strange thing is, even though I do not have a hidden variable that stores id in the view that is POSTing to this control, the id parameter is set correctly.  This is actually a good thing, but I don't understand where the value is coming from. I have examined the POST values in Chrome dev tools and there is not an id in the form values that are POSTed.  What is setting the id value correctly?
Answer: If you have an id value in your querystring or your route is defined and it can locate an id element in the URL it will use them. This link describes how default binder works and the priority given to where values come from http://www.howmvcworks.net/OnModelsAndViewModels/TheBeautyThatIsTheModelBinder
Comment: hmmm - that could be it.  I have the first action I listed as my default controller/action for the project in the global.asax, and I pass a default id to the controller.  I am still surprised the id carriers through when the form is posted
Comment: Updated with link that explains the default binder. Hope it helps


HTML form field data in a text file

Question: I want to retrieve the HTML form field data in a text file on my desktop.
I am having a HTML page containing the HTML form field box.
Further, I want to run a bash script taking the text file as a input.The bash script contains the command :
 sed -f replacer input.txt > output.txt

I have to also include this output.txt file in another html form field.
Help me out.
Thank You.
Comment: Server side script is necessary for this case. Write a server side script with your own language like php, asp, etc. Send the content of text field to that server script, and there write code to write the data to text file. Also run your bash script using exec function(if php).
Comment: I am using PHP as a server side script.
Also the things seem a little diffcult in case of HTML form field using POST method.
Comment: what is that difficulty! Can you paste some code what you have done so far?
Answer: Have html like this:
<form id="some" name="someName" method="post" action="/ur/url/to/post">
   <input type="text" id="some1" class="someClass" value="" name="fileWrite"/>
   <iput type="submit" value="submit" class="submitClass"/>
</form>

Have a php script like this:
$myFile = "testFile.txt";
if(isset($_POST['fileWrite']) && !empty($_POST['fileWrite'])) {
      $fileWrite = $_POST['fileWrite'];
}
if($fileWrite) {
    $fh = fopen($myFile, 'a') or die("can't open file"); //Make sure you have permission
    fwrite($fh, $fileWrite);
    fclose($fh);
    exec('/your/command /dev/null 2>/dev/null &');
}

Thats it. Job is done.

HTML form field data in a text file


Transmit android sensors to pc server

Question: I am working on a project that gives notifications to a web application when some phone sensors change their values rapidly. I am new to android and even though I know how to get the sensors values in my phone, I'm not sure how to transmit them to my pc server. I will look into sockets for network/bluetooth transmitting, but is there any way to send it via the internet ?
Basically, I want my application to work like this: I connect to my android application on phone, I shake the phone a bit and then on my web application on pc I get some notifications. I was looking around and I saw working with a python server?
How should I proceed here? Which method should I use?
Answer: Use HTTP/HTTPS on the Android Client to send to your server.  As that will be the easiest to program and most reliably way to get data off the phone regardless of network type.  See HttpURLConnection for details.  Just do a POST with your data to the web address.
If you don't want to just construct a simple PHP, ASPX, or other web service on top of a readily available HTTP server, then you can use a variety of HTTP server modules for Python.  SimpleHTTPServer for example.
Comment: Thanks for your response

Transmit android sensors to pc server


Spherical geometry: Arbitrary point between two points

Question: If A and B are two points on the earth, how could I find any arbitrary point between them along the shortest distance side of their great circle path?
Points are in radians
longitude = $0$ to $2\pi$
latitude = $0$ to $\pi$, $0$ being at north pole
Points are not antipodal
I desire something where I specify a range $0.0$ to $1.0$, with $0.0$ being point A and $1.0$ being point B and $0.5$ being the midpoint between them, with all other values being their corresponding points.  Thanks!
Note:  This is not homework.  I'm 41yrs old and this is for a personal project I'm working on.
Comment: Good question.  It is an embarrassment to the site that a climate has been created where users feel they have to post detailed personal disclaimers (even about subjects that *are not taught* in today's education system -- spherical geometry!) to avoid the accusation of posting homework.
Comment: Here's an idea: you first get the spherical distance of your two points, construct an equatorial arc of that length, and then rotate the arc such that the ends coincide with the original points. I don't have the time to work out the mathematics completely, but I don't see a reason why it shouldn't work.
Answer: This aviation website has the information that you were looking for. The formula presented there returns the latitude and longitude of a point that is a fraction $f$ between points A and B except when they are antipodal just as you mentioned in the question.
Comment: Nice! Note that safe implementations couch any use of inverse trigonometric functions in terms of the two-argument arctangent.


If $f(x) =x^{x^{x^{x}}}$, determine the last two digits of $f(17) + f(18) + f(19) + f(20).$

Question: If
$$  f(x)= x^{x^{x^x}}, $$
then calculate the last two digits of $\displaystyle f(17) +  f(18) +  f(19) + f(20).$
I know that last two digits of $ f(20)$ will be $00$ and I also tried to find the last two digits by binomial coefficients,
like for $ 19^{19} ,$ we can get the last digit by : $$ {19 \choose 1} \times 20 - 1 $$ will be equal to $79$. Here I expresses $19$ as $20-1$ but for the next step I would need the value of $ 19^{19} $ and that would not be worth it !
Please help me, and tell me some good method to do  such type of questions.
Thank you in advance. Please help me out with the tags. I do not know under which section it should come.
Comment: We'd like to solve the congruence $ax\equiv b\pmod{c}$  as $x\equiv a^{-1}b\pmod{c}$, so we need $a^{-1}$.  It's defined as the number that makes the congruence $a\cdot a^{-1}\equiv1\pmod{c}$ true.
Comment: Are you familiar with Euler's theorem?
Comment: Euler's Phi function ?
Comment: modular arithmetic?
Comment: Yes, I am familiar with it
Comment: The $\phi$ ("totient") function does feature prominently in Euler's theorem, yes. But I wouldn't say that the theorem is _about_ the function, per se.
Comment: So what is the theorem ?
Comment: https://en.wikipedia.org/wiki/Euler%27s_theorem You need the Chinese remainder theorem as well, though. In particular to deal with $f(18)$, but I might suggest you use it on the others as well.
Comment: I tried to understand it but it was complicated, do you have any good source ?
Comment: What is Inverse of modulo ? Why do we define it ? In the proof of Chinese remainder theorem, it is required.
Answer: For example, let's consider $f(18)$.  It's easy to see $f(18) \equiv 0 (\mod 4)$.  What about mod $25$?  Well, $\phi(25) = 20$, so let's consider $18^{18^{18}} \mod 20$.
Again, $18^{18^{18}} \equiv 0 \mod 4$, so let's consider it mod $5$. $\phi(5) = 4$, and $18^{18} \equiv 0 \mod 4$, so $18^{18^{18}} \equiv 1 \mod 5$.  By Chinese Remainder,
$18^{18^{18}} \equiv 16 \mod 20$. So $f(18) \equiv 18^{16} \equiv 1 \mod 25$. Again by Chinese Remainder, since $f(18) \equiv 0 \mod 4$ and  $f(18) \equiv 1 \mod 25$,
$f(18) \equiv 76 \mod 100$.
Answer: Since you seem to be having trouble following the hints given in the comments, I'll give a more extensive explanation.
In order to evaluate $$19^{19^{19^{19}}}\pmod{100}$$ we first want to find the smallest exponent $e$ such that $$19^e\equiv1\pmod{100}$$  Then if $n$ is a positive integer, we can write $n=me+k$ for integers $m$ and $k$, where $0\leq k<e$, so that
$$19^n=19^{me}\cdot19^k=\left(19^e\right)^m\cdot19^k\equiv1^m\cdot19^k\equiv19^k\pmod{100}$$
We know $\phi(100)=40$, so by Euler's theorem, $19^{40}\equiv1\pmod{100}$, and the smallest exponent must divide $40$.  We find by experiment that the smallest exponent that works is $10.$  (Even though your calculator may not be able to compute $19^{10}$ directly, you only have to retain the last two digits as you compute higher powers, so this is not a problem.  You can shortcut the work by repeatedly squaring, and multiplying appropriate powers of $2$.)
Anyway, now we need to know the value of $19^{19^{19}}$ modulo $10$.  We do the same thing as before, only we work modulo $10$ instead of modulo $100$ this time.  It's clear that $19^2\equiv1\pmod{10}$ so $2$ is the smallest exponent.  Now we know $19^{19}$ is odd, so $$19^{19^{19}}\equiv19^1\equiv9\pmod{10},$$ and
$$19^{19^{19^{19}}}\equiv19^9\pmod{100}$$
If you've saved the powers of $19$ from when you figured out $19^{10}\equiv1\pmod{100}$, you can easily compute that $$19^9\equiv79\pmod{100}$$
When we try to apply this method to $18^{18^{18^{18}}}$, we run into the problem that Euler's theorem doesn't apply, since $18$ and $100$ are not relatively prime.  I see however that Robert Israel has just posted an answer explaining that case, so I'll stop here.
Comment: We know that $19^2\equiv1\pmod{10}$ so in computing power of $19$ modulo $10$ we only need to know if the exponent is even or odd.  $19^{2n+1}=19^{2n}\cdot19^1\equiv1\cdot19\equiv9\pmod{10}$
Comment: You would start out with $1000$.  There's no telling what the next moduli would be.  It happened that the exponent of $19$ was $10$.  That isn't the case for $17$.
Comment: I chose the smallest exponent $e$ such that $19^e\equiv1\pmod{100}$.  I explained why in the answer.  I could have used $40$ instead of $10$, but it's usually easier to work with smaller numbers.
Comment: There must be an edit in last third paragraph '
Comment: @NikolaAlfredi I found where I typed "modulo $0$" instead of "modulo$10$".  Was that it, or is there another mistake?
Comment: No, it's perfect, but how $ 19^{19^{19} } \equiv 9 \pmod {10}$ can we say it in general. That if $ {a^a} \equiv 1 \pmod n $ then $ a^{a^a} \equiv a \pmod n$ ?
Comment: First we tried to find modulo $10$ to determine the first digit,  then modulo $100$ for last two digits... am I right ?
Comment: If we want three digit then, for $10, 100 $ and $1000$ ?
Comment: Why you chose smallest power $10$ that would divide $19^{40}$ ? why not $2$ ?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/105092/discussion-between-nikola-alfredi-and-saulspatz).


Printing Administrative title to page

Question: Is there a function I can use or object I have access to in page.tpl.php in order to get the Administrative title of the current page or it's machine name?
Answer: The page title in Drupal doesn't have a machine name. If you want to add one, you can use Safeword module. How to do that: after installing the module, add a new field to that content type where you want to add the machine name; select field type as "Machine name from node title" and widget as "Machine name". After doing this, save the content type and you'll have the machine name for node title.

Printing Administrative title to page


How to match "one sequence of characters to an other one, that can repeat" regex?

Question: i am new to regex and i'm trying to do something :
I want an expression that matchs from one sequence of characters to an other one, that can repeat.
For example i have this :
string1 aze string2 eza string3 aze string4 eza string5

And i want to match this
aze string2 aze string4

I have read this : How to match "anything up until this sequence of characters" in a regular expression?
And when i use
aze(.*)*(?=eza)

it matchs
aze string2 eza string3 aze string4

Can someone help me with this if it's possible ?
Comment: You link to a question giving you the answer, and then do something different from what's in the stated answer. Perhaps you should do what the answers there tell you to, or if that's giving you a problem, explain what. Nothing there tells you to use `(.*)*`.
Comment: ok thanks for your participation
Answer: Here is one that will match any numer of words in between, relying on a reluctant quantifier:
aze.*?(?=\s+eza)

And the demo here.
Comment: Works fine ! Thanks !
Thanks @Mandy8055 too !
Answer: If you want to match the String following a certain word you can just do this
<word>.(\S+)*
where \S+ --> gives you the next String following your word(in your case `aze`) match.

In your case it becomes something like
aze.(\S+)*

You can test the desired result here:Your output. Also since you are a beginner to Regex for any other quantifier information you can visit in here:
Hope it helps...
Comment: Okay cool your question didn't specify that before so meant the thing which I gave. By the way you can simply use the answer mentioned above(**from @PJProudhon**). It works perfectly fine and I would have given the same too(as per your mentioned case)
Comment: My case was to simplify, but "string2" and "string4" can contain an indetermined number of word.

That's why i want all word until eza in my example
Comment: I take your output, and their is my problem

https://regex101.com/r/4klhOD/5

i want that it matchs the string "iwantit" and "iwantittoo". In my real case, i don't know the number of words. I just know that i want all words from aze to eza. Ot maybe i miss something.
Thanks anyway :)


Liszt Transcendental Étude No.1 (Prelude) -- chord progression along the Arpeggio (in the first 4 bars)

Question: Liszt Transcendental Étude No.1 (Prelude)
I am curious to know whether there is a logical reason for the "chord progression" of the Arpeggio for Liszt Transcendental Étude No.1 (Prelude).
At the naive level, I can see that there are series of

Majora 3rd (here denoted as "3" in red as 3 semitones in between the root [left-hand] and the third [right-hand lowest note])

and

minor 3rd  (here denoted as "2" in red as 2 semitones in between the root [left-hand] and the third [right-hand lowest note]).

Are there good logic behind it? Or Something else to look at?
EDIT Rephrased Question: What I am interested in knowing, maybe rephrased as this, "was why there are some minor 3rd (actually two minor 3rd; denoted as two of RED color 2) along the way of each Major 3rd's chromatic scale (those denoted as RED color 3) up?"
A chromatic scale all the way up through Major 3rd creates some interesting tensions for the music. Similarly for the chromatic scale all the way up through minor 3rd. But what is the purpose for this particular mixed use?
Answer: The logic stems from the "horizontal" (melodic) progression rather than the vertical (chords) one.
Consider the voices in this way:
Top
This is a melodic, diatonic sequence: ascending fifth, descending second, descending second.
Middle and Bottom
This is an ascending chromatic scale in thirds: G - EG# - FA - F#A# - GB - G#B - AC - (A)C# - BbD - BD# - CE
In this way, it's a "contrapuntal" passage of three voices.
However, the top voice is a diatonic sequence; whereas, the lower voices are chromatic. Thus, the intervals between the upper and lower voices are not always the same.
Comment: @wonderich I've updated to address your question. Please let me know if I've succeeded.
Comment: Thanks +1, obviously I saw myself just at the first glimpse to know there is a "horizontal" (melodic) progression via chromatic scale.
Comment: I think a chromatic scale all the way up through Major 3rd creates some interesting tensions for the music.
Comment: *Question*: What I am interested in knowing, maybe rephrased as this, "was why there are some minor 3rd (actually two minor 3rd) along the way of each chromatic scale up?"
Comment: I posted a new question: https://music.stackexchange.com/q/130534/9184 -- following up to find the violation of your "ascending fifth, descending second, descending second"
Comment: I hope this question makes more sense now -- https://music.stackexchange.com/q/130558/9184 thanks!

Liszt Transcendental Étude No.1 (Prelude) -- chord progression along the Arpeggio (in the first 4 bars)


Updating user profile to update node

Question: I currently have a user's profile set up with some extra fields and when that user obtains the role "paid user" an entity is created with a rule and a node that copies those extra fields in the profile is then published.  I'm having an issue however, that whenever I update the user's profile fields, it creates ANOTHER node and leaves the old one.
I'm looking for a solution that will either delete the duplicate node OR will update the current one.
Does anyone have any ideas for this?  I've tried the deduped module someone built for Drupal 7 but it doesn't seem to be working.
EDIT: Here is the second Rule I've created to try to unpublish the older node.
Event: Before saving a user account
Conditions: Entity exists by property(Entity type: Node, Property: Title, Value: [account:field-business-profile])

Data comparison(Parameter: Data to compare:[account:field-bus-name],Data value:[account:field-business-profile:title])

Actions: Unpublish content(Parameter:Content:[account:field-business-profile])

EDIT2: I've updated the second rule to rooby's edits.  The original content remains published though.  I've tried going back and forth between the account-business-profile:nid and account-unchanged-business-profile:nid to no avail.
Here are some pictures I've uploaded of the rule and the two pieces of content:
Comment: I would think you would need 2 rules. One for creating a node when the paid user role is obtained and another that updates the existing node when a profile is updated. For this you will need some way of linking the user to their node so that rules can load the node for a given user when the profile is saved.
Comment: And maybe a 3rd rule to unpublish the node when the user loses that role. And maybe a 4th to delete the node if that user is ever deleted.
Comment: If you have an entity reference field on the profile that links to the node, then you set that value on the profile when creating the node. Then later using rules you can load the node base on that entity reference value and update it. There has to be some way that the profile & node are linked or it will never work.
Comment: @rooby Yes I believe I do have to use two rules and have been trying to, but in the Data Selectors whenever I try to access the older Node, it does not appear in the list.
Comment: @rooby Well first let me thank you for the tip about linking profiles with entity reference.
I'm still having issues with the older content not being unpublished.  I've updated my question to show what I mean and how I have the rule set up.
Comment: @rooby While looking through the Data Selectors, I notice that I can only change the accout-field-business-profile node information such as title, nid, content-type etc.
How can I edit the fields directly?
Answer: Moving to an answer so I don't overload your question with comments.
Your second rules doesn't seem to ever load the node you want to unpublish/edit.
You need an action for "Fetch entity by property" (although I would be wary of fetching by title, I prefer the safety of node ID). For this action you can limit it to 1, so it only gets one node (there should only be 1 anyway).
Then that will fetch your node, and then you can do comparisons on that node or unpublish that node (or whatever else you may want).
The problem is though is that at this stage rules only knows it is an entity, it doesn't know what type or anything so you can't actually access its fields or do node actions like unpublish on it.
So (I think this is the only way) you have to install the http://drupal.org/project/rules_conditional module.
Then after your "Fetch entity by property" action you can add a loop and loop over entity-fetched (it will return an array even though you specified to return 1.
Then in this loop add a "Conditional".
Then in the conditional add an "If". For the if you can do entity has field, or entity is of type and content is of type. You can add multiple Ifs. If you want multiple nested ifs you have to add it like
    conditional
      if entity is of type node
        conditional
          if content is of type page
            action unpublish node
Once you have added the ifs rules will know that the fetched-entity is a node and what fields it has.
Then you can add an unpublish action and select entity-fetched (or list-item because of the loop)
So your rule might look like this:
Event: Before saving a user account
Action: Fetch entity by property(Parameter: Entity type: Node, Property: Title, Value: [account:field-business-profile], Limit result count: 1 Provides variables: Fetched entity (entity_fetched))
Action Loop: (Property: List: [entity-fetched], List item: Current list item (list_item))
  Conditional:
    If: Entity is of type (Parameter: Entity: [list-item], Entity type: Node)
      Conditional:
        If: Content is of type (Parameter: Content: [list-item], Content types: Basic page)
          Action: Unpublish content (Parameter: Content: [list-item])

Or it could look like this (without the loop, just working on the 1st entity-fetched):
Event: Before saving a user account
Action: Fetch entity by property(Parameter: Entity type: Node, Property: Title, Value: [account:field-business-profile], Limit result count: 1 Provides variables: Fetched entity (entity_fetched))
Conditional:
  If: Entity is of type (Parameter: Entity: [entity-fetched:0], Entity type: Node)
    Conditional:
      If: Content is of type (Parameter: Content: [entity-fetched:0], Content types: Basic page)
        Action: Unpublish content (Parameter: Content: [entity-fetched:0])

Comment: At the second action rules doesn't yet know what fields are on the entity. You have to wait until after the check for content is type. or instead of content is type you could use entity has field, and check that it has the field you want. - Because you are only dealing with a single node, you could also leave out the loop and do "Entity has field" on "entity-fetched:0", which will be the first result from your "Fetch entity by property" action.
Comment: I added a similar solution, but without the loop.
Comment: I just re-read your comment and realised I missed the point.
 It definitely should show entity-fetched, without anything after it.
Comment: Thank you again for your help, I'm much closer than I was before.
When I am adding the Loop in my second action on the rule, the property:list: area shows entity-fetched:author:, entity-fetched:body:, entity-fetched:source:, but nothing else.  I tried inputting just entity:fetched manually but it gave me an error that it did not meet the list requirements.
Comment: Thanks so much for all your help!  You've saved me what might have been days of searching, haha.  I haven't finished but I'm at a good place where I can rest easy and sleep.

I will be updating tomorrow on progress for those interested.
Comment: It seems as though I'm still having an issue with the rule.  I updated the question with a couple of screenshots of the current issue with it.
Answer: One approach I've used on a site in the past is to create the entity on profile creation and link it with a relation (I used the Relation module because at the time I couldn't get the rules integration of Entity Reference working).
I then used permissions (with the Revisioning module because I also needed to approve changes) to limit access to editing that profile to users with the appropriate role.
Then, when the user becomes a paid user, I simply have a rule that publishes the node by calling it through the relation, and another rule that unpublishes the node.
This approach creates one extra node in the database per user; some people may not like this but for me it was a good tradeoff for simplicity's sake.
To copy the values of the fields, since the nodes will already be created and you don't have to worry about saving the node first, you can just add an action set component to the rule that is a sequence of Set data value actions.

Updating user profile to update node


Smart contract in peer-to-peer network without existence of blockchain

Question: I need to know how can apply smart contract in a peer-to-peer network in which blockchain has not been utilized.
think two entities are interacting together in a peer-to-peer network and they have obligated pay some cost for some service that provide together ,but in this case they don't use blockchain and they should pay inside the network,can they use smart contract in this case? smart contract without blockchain? is any solution or any sample for that?
Answer: So far smart contracts have only been implemented in blockchain networks (and other distributed ledgers such as Hashgraph). Without such a platform you need some intermediary to fill the role of a smart contract.
For P2P networks, Bitcoin (and it's successors) were the first to create virtual currency in a decentralized fashion - so no, it is not possible to use digital currency without blockchain or a trusted third party.


Woocommerce API limits AND ussing less resources

Question: I was reading the documentation at:
http://woocommerce.github.io/woocommerce-rest-api-docs/
I am trying to figure out the limits for the API for the following methods

$woocommerce->get products/tags
$woocommerce->get products/categories
$woocommerce->get products/categories
$woocommerce->post products/tags
$woocommerce->post products/batch

For these methods I want to know how many items I can get or save at once. (Batch save for example I want to save 50 at a time; or for getting products I want to get 50 at a time (per page))
Also I am trying to figure out best practices to use less resources on both consumer of the API and receiver of API. Right now in development I have them both on the same machine and the fan really gets going on my laptop
The majority of work is done in products/batch. I am sending almost 4k items in batches of 50.
Comment: Since some time has passed since your question, did you tried to reach the limit and have some followup results/conclusions? This could be helpful for future visitors of the question :)
Answer: I know a service that uses WooCommerce says that their API calls are rate-limited by IP to 86400 calls per day (one per second on average).
That is their service so implies you can go same or higher for WooCommerce
Source: https://github.com/Paymium/api-documentation#rate-limiting
Comment: I didn't ask question clearly. For the methods above; how many can a send receive? for example. When getting products I get them in chunks of 50 right now. For batch save I save in chunks of 50
Comment: @donohoe Are there any other sources that support WooCommerce having this limit? I couldn't find any information related to API call limit.


How to integrate over a sphere in $\Bbb{R}^2$

Question: Let be $f:\mathbb{R}^2\to\mathbb{R}$ how I can calculate the integral $\int_{\partial B(0,1)}{f(y)}dy$?

I tried to do this: let be $p:\left[0,2\pi\right]\to\partial B(0,1)$ such that $p(x)=\left(\cos(x),\sin(x)\right)$ and:
$$\int_{\partial B(0,1)}{f(y)}dy=\int_0^{2\pi}f(p(x))dx$$ but I'm not sure if this is correct
Comment: There are some inconsistency here. Look that you say the domain of $f$ is a subset of $\mathbb{R}$, on the other hand the image of $p(x)$ is a subset of $\mathbb{R}^2$ so... What actually is $f(p(x))$ ??
Comment: @BrianBritosSimmari I'm sorry,  was a typo
Comment: Near as I can tell, with $f(y)$ denoting $f(y_1,y_2)$, you're thinking about simple polar coordinates and $\int_{\partial B} \,f(y)\, dy = \int_0^{2\pi} f(\cos\theta, \sin\theta)\,d\theta$.
Comment: $y$ is a vector?
Answer: Before we try to compute $\int_{\partial B(0,1)}{f(y)}dy$, we should be clear on what it means. One simple way to define it is as the line integral of $f$ along the curve $\partial B(0,1)$. In this case, applying the definition of a line integral, using your parameterization $p(x) = (\cos(x), \sin(x))$, we have,
$$\int_{\partial B(0,1)}{f(y)}dy = \int_{0}^{2 \pi}{f(p(x))} |p'(x)|dx = \int_{0}^{2 \pi}{f(p(x))}dx$$
because $|p'(x)| = \sqrt{(-\sin(x))^2 + \cos^2(x)} = 1$.
So in short, your formula is correct, but be careful about the "change of variables" part.


Convergence of $\sin((n+1)\times\frac \pi 2)$

Question: I am trying to find what value this series converges to without a calculator. I believe I need to convert the sin to cosine, but I'm not sure how that helps as it still leaves with the trig term alternating between $0, 1, 0,$ and $-1$. From what I read, when $n$ is even, it should be $1$, but plugging $n=2$ returns zero... is there something I'm missing?
$$
\sum_{n=0}^\infty\frac{\sin\frac{(n+1)\pi}{2}}{5^n}
$$
The correct value is $\frac{25}{26}$.
Comment: @user170231 you should write it as an answer, not in the comments
Answer: When $n$ is odd (so $n+1$ is even) the numerator vanishes since $\sin(n\pi)=0$ for $n\in\Bbb Z$. So one needs only consider even values of $n$; let $n=2k$, so the sum reduces to a geometric series:
$$\sum_{n=0}^\infty \frac{\sin\frac{(n+1)\pi}2}{5^n} = \sum_{k=0}^\infty \frac{\sin\frac{(2k+1)\pi}2}{5^{2k}} = \sum_{k=0}^\infty \frac{\sin\left(k\pi+\frac\pi2\right)}{25^k} = \sum_{k=0}^\infty \left(-\frac1{25}\right)^k$$
where we expand
$$\sin\left(k\pi+\frac\pi2\right) = \sin(k\pi)\cos\frac\pi2 + \cos(k\pi)\sin\frac{\pi}2 = 0 + (-1)^k$$
Answer: $n$ has been offset by $1$ in the $\sin$ function, so it actually goes $1,0,-1,0$. You can ignore the terms where $n$ is odd, so the sum can be expressed as:
$$\sum_{n=0}^\infty \frac{-1^n}{5^{2n}}$$
This is the same as:
$$\sum_{n=0}^\infty \frac{-1^n}{25^n}=\sum_{n=0}^\infty \left(-\frac1{25}\right)^n$$
The infinite geometric series formula is $\frac a{1-r}$, where $a$ is the first term and $r$ is the common ratio for the series $a+ar+ar^2+ar^3+ar^4...$ Plugging in the first term as $1$ and the common ratio as $-\frac1{25}$, we get:
$$\frac1{1--\frac1{25}}=\frac1{1+\frac1{25}}=\frac1{\frac{26}{25}}=\frac{25}{26}$$
That is how you get the correct answer.