Are there any situations when one needs to make a distinction between slurs and ties?

Question: In the comment section to a question about notating tied notes, the discussion of whether it's necessary to make a distinction between ties and slurs came up.
The reasoning goes as follows: If one would place a slur underneath two consecutive notes with the same pitch, wouldn't the most reasonable thing to do be to just play/sing one single note (meaning that the slur effectively would be reduced down to a tie)? Or would this depend on the type of instrument being used (maybe for some instruments, it would make sense to produce a sort of pulsating sound) and/or the number of voices on the same staff?
Edit: Many seems to think that I'm asking what slurs and ties are. This is not the case. I'm simply asking whether it's really necessary to have two different symbols and if one simply couldn't make do with just one, which then always is unambiguously interpreted to either a tie or a slur depending on the context.
As an analogy, you could either use the words "bachelor" (tie) and "bachelorette" (slur), or you could just use the word "unmarried" and then amend it to a man ("bachelor") or a woman ("bachelorette").
Comment: @carlWitthoft No, **slurs** are used to indicate phrasing. The only purpose of a tie is notational. Ties are used to represent a single played note which it is impossible to represent with a single note symbol (for example a duration of 5 quarter notes), or a single note that starts in one bar and ends in a later bar, or where writing a single note would be rhythmically confusing (for example in bar in 4/4 time starting containing a 16th note, a dotted half note, and a dotted 8th note, the dotted half note should be rewritten using ties to show how it relates to the beats in the bar).
Comment: @Speldosa In your link to the other question, note that in the music example the shape of the ties and the slur are slightly different even though they both "connect two G's". That difference is important, though in poor quality music engraving it can be hard to see. There are other notations to indicate "a sort of pulsating sound", by combining a slur with articulations like dots or dashes.
Comment: "The only purpose of a tie is notational" - that should essentially be the answer.
Comment: Keep in mind that a tie can be used to indicate phrasing, so there's the possibility of ambiguity.
Comment: @Speldosa Agreed with alephzero here. A slur with two notes of the same pitch signals a string player to many several notes in one bow direction. When tenuto markings, this is called *louré* bowing, with staccato, it's called *slurred staccato*.  For wind instruments, it indicates several notes to be played with breath attack - no tongue articulation. Slurs are also thicker than ties and reach to the center of the notehead.  Ties are thin and flat and begin slightly away from the interior part of the notehead. Musicians distinguish them all the time.
Comment: @CarlWitthoft I've never heard of a tie being used to indicate phrasing. A tie simply joins two notes, nothing more.
Comment: @jjmusicnotes I'll try to find an example, tho' you're probably right.  I do know of instances where a slur covers 3 or 4 notes of the same pitch as a phrasing indication, but not sure about just 2 notes.
Comment: @CarlWitthoft Well, a slur covering the same pitch is fine and normal. You said that *ties* can indicate phrasing, which they cannot.
Comment: @jjmusicnotes Please convert your comment to an answer. I think it contains valuable information, but it's formatted like a reply, and probably you can add other examples.
Comment: @CarlWitthoft - it's been nearly five years. Found any yet?!
Comment: @Tim  I"m sure I forgot all about it at some point,  like, say,  early morning Nov 12, 2016.
Comment: @CarlWitthoft - a man's word, and all that... It's never too late to make amends.
Answer: Two tied notes on a percussive instrument (including piano) have a single attack.  Two slurred notes are two strikes without dampening the first strike before placing the second between.
Two tied notes on a string instrument are a single note and thus are played on the same string.  In contrast, two slurred notes may well occur on different strings when using appropriate fingering.  The Ciaconne from the violin solo partita 2 of Bach has close to its end a passage with slurred note pairs from adjacent strings and very obviously you won't suddenly turn a two-string slur into a single-string tie just because two notes happen to coincide.
Comment: Just to make it clear - is the answer to the question "Yes"? And in your Bach example, one would need to make a distinction between slurs and ties?
Comment: When you talk about these slurred note pairs, do you mean that they have the same pitch but are played on different strings? Doesn't this require some extra explanation or is it self-explanatory? And if so, isn't the interpretation of the additional slur unambiguous, since it couldn't notate a tie (since it already have been established that different strings should be played, hence demanding some kind of attack for each note)? (I hope my follow-up question was at least semi-clear.)
Comment: It's been ages since I've played violin, but by recollection is that a slur indicates that the marked notes should be played with the same bow stroke.  Legato by default, but possibly articulated if indicated with other markings in addition to the slur, or with previous markings and a "simile" notation which is still in effect.
Answer: Ties change ONLY the RHYTHM value: notes which cannot be represented only by one symbol, must be tied. Ties can be only between two tones of the same pitch.
Slurs is an EXPRESSION: it indicates that a phrase should be played smoothly. It can connect two or more tones.
Comment: Not really correct here. A half-note tied to a quarter can easily be represented by a dotted-half, but there are many reasons to notate the music the former.  Also, slurs indicate smooth things for *some* instruments and circumstances, but not *all* instruments and circumstances.
Comment: Yes, this is all true. But it still doesn't answer my question. For example, if I read a choir score and it told me to sing legato (which is the expression I interpret from slurs in choral music) for a certain phrase, and that phrase contained consecutive notes with the same pitch, I would just sing one single, tied note, hence the same as if the notes just had been notated as ties.
Comment: @Speldosa - a sung note often has one syllable, so it would be sung to that. The line going across a barline may well indicate a tie. Now I understand the question! Yes, there could be ambiguities!
Answer: Judging from the linked question, such confusion probably involves situation when a slur only involves 2 notes, and those 2 notes are equal. Thus question arises: whether such slur is equivalent to a tie. The answer is absolutely no. There would be ways for performer to tell their difference, even when composer doesn't explicitly notate as such. Using Beethoven's 31st piano sonata as example:

Here the desired effect is grouping every two notes together, maining the legato of first note as much as possible but not as a tie (100% of note length). The effective playing would be similar to (though a bit exaggerated):

This is usually the case for 18th century keyboard music. For other instruments or vocal music, there would be other semantic meanings for slur as well, which has completely different meaning from tie. They look very similar visually, but it's the meaning that matters.
Comment: " There would be ways for performer to tell their difference, even when composer doesn't explicitly notate as such" - how *do* we tell the difference here?
Comment: @topomorto in this example, it would be simple to replace the tied notes with the desired value of a tie so it just being a tie doesn't make too much sense. Baroque composers and some classic composers wrote shorthand in notation like this and wanted you to read more in between the notation.
Answer: Ties are ALWAYS between notes at the same pitch. Either because there is no one note that will portray the length or because the long note is longer than the bar length for the piece.
Slurs are ALWAYS between notes of different pitch - two, three or more may feature. A slur could be construed as a mini-phrase, where all the notes included in the slur are played in one breath, or legato, or without a perceivable break.
Ties are always written head to head, whereas slurs can be written tail to head/ head to tail, as they include different notes, often a couple, but occasionally five or six.
The two terms are not interchangeable, and shouldn't easily get mixed up. A phrase mark, which may look similar, will ALWAYS involve notes of different pitch, so would appear similar to a slur.
Comment: Beethoven seems to disagree with you on this one...
Comment: So, if I would write a slur between two notes of the same pitch (despite what the rules say), how would you interpret it?
Comment: @Tim - this isn't quite right.  If you have three C4s in a row, and you have a tie/slur symbol connecting the first note with the third, you would have created a slur even though the only note involved is C4.
Comment: @Speldosa - your question presupposes that there is some different notation that would indicate a slur.  Your notation would just be interpreted as a tie, period.
Comment: @Choirbean - the OP asks about two consecutive notes, but you have a point.
Comment: @fdreger - to whom was the comment made?
Answer: One very important situation where you need to be completely clear whether it's a slur or a tie is when inputting to a computer notation program - particularly if you want playback.  The two are logically quite different, and are entered using different commands.  And they can have subtly different visual styles.
But that apart, I defy anyone to tell whether a handwritten line is a slur, tie or phrase mark other than by context.  And context will be sufficient.
Answer: This largely depends on the context of what is being written. Performers can usually determine what is being intended by what isn't written as well.  If a composer truly wants a sustained note while others above play moving notes, the simplest answer would be to write a longer duration note.
A written slur in most orchestral music, in a place that would be more easily written as a longer duration note, often means that other players have other notes being played to create harmonic motion.  In these circumstances, each of the notes would be played with a distinct articulation since they are parts of a different chord, so would have both different tuning tendencies, and would also probably be intended to played with the same rhythm of the other players within that chord. If this was not the intent, and provided otherwise homogenous rhythmic motion, it would be much simpler and clearer just to write a longer note.
Ties on the other hand, are used when the rhythm would be difficult to notate otherwise, such as across barlines or on weak beats within a measure. In such a case, if musicians have the same tied rhythm, it would be safer to assume that it would not be a slur, but a tie for the sake of writing a difficult rhythm.
Comment: All of this is incorrect. I don't think you understand what ties or slurs are.  You should revisit your knowledge of this subject.
Comment: Could you be a little more specific? I find it hard to believe anyone would argue that you can't have a slurred, re-articulated note that is of the same pitch class as the previous note.


How can I make an http request in the service worker chrome extension?

Question: i am trying to develope a chrome extension ,now background scripts are replaced by service workers in manifest v3, How can I make an http request in the service worker?
Comment: Use [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch).
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: Use this in your service worker:
<code>fetch('http://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data));
</code>
Don't forget to set proper permissions in the manifest file:
<code>  "host_permissions": [
    "http://example.com/"
  ],
</code>


$ \int_0^\infty \ \frac{(x\cdot\cos x - \sin x)^3}{x^6} \ dx$

Question:
What is the value of
$$
\int_0^\infty \ \frac{(x\cdot\cos x - \sin x)^3}{x^6} \ dx
$$

I have no idea how to start with this integral, any hint?
Comment: http://www.wolframalpha.com/input/?i=integral+(x*cosx-sinx)%5E3%2F(x%5E6)
Comment: Try something along the lines of $$\frac{(x\cos x-\sin x)^3}{x^6} = \left(\frac{x\cos x - \sin x}{x^2}\right)^3 = \left(\frac{d}{dx}\frac{\sin x}{x}\right)^3.$$I'm leaving this as a comment because I couldn't go further. Maybe you can.
Comment: Could be useful: https://en.wikipedia.org/wiki/Trigonometric_integral
Answer: You may use the Laplace transform:
$$\mathcal{L}^{-1}\left(\frac{1}{x^6}\right)=\frac{s^5}{120},\qquad \mathcal{L}\left((x\cos x-\sin x)^3\right) = \frac{31104-196992 s^2-94080 s^4-13440 s^6}{(s^2+1)^4(s^2+9)^4}$$
turning the original integral into
$$ \frac{1}{120}\int_{0}^{+\infty}\frac{31104s^5-196992 s^7-94080 s^9-13440 s^{11}}{(s^2+1)^4(s^2+9)^4}\,ds $$
that by partial fraction decomposition equals:

$$\color{red}{\frac{4-9\log 3}{40}}$$
Comment: Does Wolfram Alpha not know Laplace transforms?  I'm a little surprised Wolfram didn't get it.
Comment: @alphacapture: probably it is just a computation time issue. I just checked the above lines and the final outcome with my (old) version of Mathematica and it is fine with them.


Distributing 12 books to 3 children.

Question: The number of ways of distributing six identical maths books and six identical physics books among three students gets at least one maths and at least one physics book is?
My attempt:
So I have learnt to distribute objects using the multinomial technique which states that when you have $n$ different objects and $r$ different groups (when no group is empty) is :$ r^n - rC1 (r-1)^n ..... (-1)^{r-1} rCr-1$
But the problem arising here is that those books are not all different but 6 each are identical.
The problem with my application is arising because I have just taught to apply a formula on a basic type of question.
The answer can have a method different from the multinomial one. And also how do we assess these kind of problems?
Comment: Have you been taught anything about distributing identical objects to distinct boxes ?
Comment: Yes using the multinomial technique , I have been.
Comment: But here , there are two sets of identical objects , how would we resolve that
Answer: There is a difference between distributing distinct objects to distinct boxes, and (here) distributing identical objects to distinct boxes.
For this, you can use Theorem 1 of stars and bars,
e.g. for the 6 identical maths books to 3 (obviously distinct) children, $\binom52$ ways
Do a similar computation for the physics books, and multiply.
Comment: Could you explain why it's not $5\choose2$?
Comment: Sorry, typo corrected
Answer: Hint Distribute first one math book to each kid. Then you can distribute the remaining 3 books any way you want. How many ways can you do this? (if not sure, you have 3 situations: one kid gets all 3, one kid gets 2, and everyone gets one. How many possibilities are in each situation)?
Do the same for physics books.

Distributing 12 books to 3 children.


Is there a single-letter neo-Riemannian transformation between F and Cm?

Question: In Is there anything special about A♭ in a Tonnetz?, the main diagram makes very clear that there is one adjacent move on the Tonnetz that, surprisingly, doesn't have a single-letter transformation associated with it. Here is the diagram:

On the left side of the diagram, we clearly see that adjacent triangles that share two pitches (i.e., a side) can be understood as P, L, or R. Immediately above we see that, when two triangles share a single node, they can be understood as N or S.
But what about the third option, the PRL transformation that toggles between, e.g., FM and Cm? It seems odd that, in a theory so focused on smooth voice leading, a chord change that shares a common tone would not have a dedicated transformation. Is there a single-letter transformation for this switch?
Comment: ...and if not, why?
Comment: @Aaron my guess is that it has something to do with the tritone between the thirds of the two chords (e.g. A and E flat).
Answer: In David Kopp's book Chromatic Transformations in Nineteenth-Century Music, he does introduce a single-letter transformation that could address this issue.
In Chapter 7 (see specifically pp. 170ff), Kopp introduces the F transformation. F stands for "fifth-change operation," and it connects two triads with different modes related by descending perfect fifth.
Beginning with a C-major triad as stated in the question, an F transformation changes the mode from major to minor and down a perfect fifth to F minor.
But there is a caveat—and a pretty big one in my view. The transformations cited in the question (P, L, R, S, N, and H) are involutions, meaning that applying the same transformation to the resulting triad returns you to the original triad. In other words, applying the P transformation to C major takes you to C minor, and applying that same P to C minor takes you right back to C major.
The F transformation, however, is not an involution, because applying F again to the resulting F-major triad from earlier takes us not back to C minor but instead to B♭ minor (recall that the definition of F connects two triads related by descending perfect fifth). However, Kopp does address this by creating the F-1 transformation, which would move by ascending fifth to get us back to C minor.
Perhaps this is one reason why—in addition to phoog's great comment that the chordal thirds are a tritone apart—this transformation is simply not mentioned in the same breath as the other six. Nevertheless, for the sake of completeness, I think it's worth having a single-letter transformation—and one that's an involution—for this system. The only question is what to call it...


Outlier-resistant average of a set?

Question: I have a web application in which users can provide valuations for items.  These valuations are currently unrestricted, and there is no non-arbitrary criteria by which I could restrict them, since valuations are purely subjective.  For each item, I have an "average valuation", which is currently just a simple mean of all valuations for the item.  This was a naive choice that has inevitably lead to abuse, whereby a small subset of users intentionally provide extreme valuations to manipulate this "average valuation" to their benefit.
I'd like to solve this problem mathematically, without imposing arbitrary restrictions on submitted valuations.  As far as I can tell, it's very commonplace for item valuations to follow a normal distribution, but I admittedly don't remember much of my statistics from decades ago.  I have been attempting to brush up on standard deviations, but it seems like I can't exclude valuations over 2σ because these extreme outliers raise the population standard deviation (I could be misunderstanding this concept, though).  So...
What statistical approach can I take to determine the "average valuation", while remaining resistant to this kind of abuse?
For reference, here is an example set of valuations for a particular item.  The outliers here are clearly the [317, 318, 630, 630, 640, 6511] subset:
60, 63, 63, 63, 63, 63.5, 63.8, 63.8, 63.9, 63.9, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64.2, 64.5, 64.5, 64.5, 64.5, 64.5, 64.9, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66.5, 67, 67, 67, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 69, 69, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 71, 72, 74, 74, 75, 75, 75, 75, 78, 80, 85, 317, 318, 630, 630, 640, 6511
For this set of valuations, I would expect an "average valuation" somewhere around 65 or 66.
Comment: You could try asking the same question at http://stats.stackexchange.com if you don't get answers here. You could also take a look at the median of the dataset. Check out https://stats.stackexchange.com/questions/16198/what-do-you-call-an-average-that-does-not-include-outliers.
Comment: The median ($65$ in your data set) is robust to outliers. There are other [robust statistics](https://en.wikipedia.org/wiki/Robust_statistics) such as Winsorized means (about $66.4$ in your data set)
Answer: The median, as suggested by @Henry seems the simplest solution to your problem.
You might also consider a 'trimmed mean'. Below I show the mean, a 5% trimmed mean (average the middle 90% of your data after discarding the top and bottom 5%), and median. (In a sense, the median is a 50% trimmed mean.) You could
try out various degrees of trimming to see what works best in your situation.
I pasted your data into R statistical software with the following results.
 mean(x);  mean(x, tr=.05);  median(x)
 ## 107.3667   # ordinary mean
 ## 66.06368   # 5% trimmed mean
 ## 65         # median

Both the trimmed mean and the median would also provide protection if there
were users who purposely gave absurdly low values.
Another approach would be to use a 'boxplot' to detect 'outliers', ignore
the outliers, and average the rest. The default outlier-detection method
may include as outliers some values you would want to keep. (You could adjust the outlier rule to be less aggressive.)
The procedure
below ignores the possibility of low outliers, and only omits the high ones.
It has some potential of giving a result biased on the low side.
 boxplot.stats(x)$out
 ##   75   75   75   75   78   80   85  317  318  630  630  640 6511
 mean(x[x <= boxplot.stats(x)$stats[5]])  # effect is to avg values 74 or less
 ## 65.77665

My guess is that you want something simple and automatic. I would probably
use the ordinary mean, 5% trimmed mean, and median in tandem for a while
and then pick one of the latter two, depending on track record.
Comment: I think I agree.  It seems like the median might be the most resistant to abuse (requiring at least 50% of valuations to be poisoned before it can be manipulated, if I'm thinking about it correctly).  It also seems to be the only one that wouldn't discard any valid valuations, which isn't a deal-breaker, but definitely a nice perk.
Answer: In my case, the outliers are important and should influence the end result slightly, so here's a method that I decided to use:
    static double OutlierResistantMean(List<double> items)
    {
        var a = items.Average();
        var eps = (items.Max() - items.Min()) * 1e-5;
        while (eps>0)
        {
            Exponential e = new Exponential(1 / items.Average(i => Math.Abs(i - a)));

            double s1 = 0, s2 = 0;

            foreach (var i in items)
            {
                var d = 1 - e.CumulativeDistribution(Math.Abs(i - a));
                s1 += i * d;
                s2 += d;
            }

            var na = s1 / s2;
            if (Math.Abs(na - a) < eps)
            {
                break;
            }
            a = na;
        }

        return a;
    }

Where Exponential is exponential distribution taken from MathNet.Numerics package
In your case, the function returns 66.0967586215405
I suppose if you believe that the outliers are errors, you could try and use normal distribution instead
Answer: In statistics, there are three major errors: bias, variance, and contaminations. Sample mean is a consistent estimator, however, its variance and robustness is not desired in many scenarios, so historically, many attempts have made to reduce the overall errors of mean estimation. For example, trimmed mean, Winsorized mean, Hodges-Lehmann estimator, Huber M-estimator, and median of means.
Comparing the performance of these estimators is still a hot topic in statistics research. Recent advances suggested that the bias bound of Winsorized mean is better than that of the trimmed mean (Mariusz Bieniek (2016) Comparison of the bias of trimmed and Winsorized means, Communications in Statistics - Theory and Methods, 45:22, 6641-6650, DOI: 10.1080/03610926.2014.963620 )
Also, the concentration bound of median of means nears the optimum of sub-Gaussian mean estimator (Luc Devroye. Matthieu Lerasle. Gabor Lugosi. Roberto I. Oliveira. "Sub-Gaussian mean estimators." Ann. Statist. 44 (6) 2695 - 2725, December 2016. https://doi.org/10.1214/16-AOS1440 )
Statistics is undergoing a trend from nonparametrics to semiparametrics, because these research are new, so they are not emphasizing in current textbooks.
In my paper, I defined two new classes of semiparametric distributions, introduced several new mean estimators and further explain why the Winsorized mean is better than the trimmed mean in most cases. Also, the median Hodges-Lehmann mean is proposed as the optimun nonparametric robust mean estimator. If you are interested, you can watch my youtube videos or read my paper https://www.youtube.com/playlist?list=PLv12WMZUyCNCxgQdS8wguSWs60uKttHaM .

Outlier-resistant average of a set?


how to remove undefined values from array with javascript

Question: i have tried with filter method but it removes all values. i'm getting this undefined value because of this function. I want to merge these three arrays and remove only undefined.
Example Arrays values:
let arry1= ["txt", "txt2"];
let arry2= ["txt"];
let arry3= ["txt", "txt5", "txt6"]

let c =  arry1.map(function(value, index) {
        return `${value} ${arry2[index]} ${arry3[index]}` ;
      });
c =  ['txt txt txt', 'txt2 undefined undefined']

i have this
let a = ["undefined this", "that undefined ", "undefined value undefined"]

// i want this

let a = ["this", "that", "value"]
```

Comment: "_I want to merge these three arrays_": Is the actual expected output the following array: `["txt txt txt", "txt2 txt5", "txt6"]`? Please update your question to provide the expected output. The term "merge" is unclear as written.
Comment: You're reading the index from arry1 and applying it to arry2, which is why you're getting undefined in the first place.
Comment: What would be the *desired* output for the first example? Where does the array `a` come from?
Comment: @jsejcksn question has been updated
Comment: `arr.map(str => str.replaceAll('undefined', '').trim())`?
Answer: you can write it like this
  let a=arry1.map(function(value, index) {
    value=`${value} ${arry2[index]||""}`.trim();
    return `${value} ${arry3[index]||""}`.trim() ;
  });

Comment: updated the answer  this will help you to get rid of extra spaces
Answer: Map through the array and remove all occurrences of undefined, then trim the result:

let a = ["undefined this", "that undefined ", "undefined value undefined"]

const result = a.map(e => e.replaceAll("undefined", "").trim())
console.log(result)
Comment: This won't work if one of the actual values is `"undefined"` (it doesn't discriminate between missing values and the literal string `"undefined"`).
Answer: The other answers don't discriminate between the lack of a value (undefined) at an array element vs having the literal string "undefined" at an array element.
I've explained how to accommodate for that using comments in the code below:

const array1 = ["txt", "txt2"];
const array2 = ["txt"];
const array3 = ["txt", "txt5", "txt6"];

// Collect the arrays into another array so that we can iterate over them:
const arrays = [array1, array2, array3];

// Create an array of the lengths of the arrays:
const arrayLengths = arrays.map(({length}) => length);

// Get the maximum value from the lengths:
const maxLength = Math.max(...arrayLengths);

const result = [];

// One outer loop for each index of the longest array:
for (let i = 0; i < maxLength; i += 1) {
  // A placeholder string:
  let str = '';

  // One inner loop for each of the arrays:
  for (const array of arrays) {
    // The value at the current index of the current array:
    const strOrUndefined = array[i];

    // If it's actually a string, then append a space and the string
    // to the placeholder string:
    if (typeof strOrUndefined === 'string') str += ` ${strOrUndefined}`;
  }

  // Push the placeholder string into the result array,
  // but first remove the extra space created by the first iteration:
  result.push(str.trimStart());
}

console.log(result); // ["txt txt txt", "txt2 txt5", "txt6"]


Show that Kernel density estimate integrates to 1

Question: I'm trying to show that the Kernel density estimate
$$ f(x) = \frac1{nb}\sum_{i=1}^nK \left(\frac {X_i - x}b\right) $$
actually integrates to 1. The $X_i$ are iid and K is a symmetric probability density function; in particular, K integrates to 1. What I get is
$$\int_{-\infty}^{\infty} \frac1{nb}\sum_{i=1}^nK\left(\frac {X_i - x}b\right) dx$$
$$ = \frac1{nb}\int_{-\infty}^{\infty} \sum_{i=1}^nK\left(\frac {X_i - x}b\right) dx $$
$$=\frac1{nb}\sum_{i=1}^n\int_{-\infty}^{\infty} K\left(\frac {X_i - x}b\right) dx$$
$$=\frac1{b}\int_{-\infty}^{\infty} K\left(\frac {X_i - x}b\right) dx$$
Using as a substitution
$$ u = \frac {X_i - x}b$$
$$ dx = -b du$$
we get
$$=\frac1{b}\int_{-\infty}^{\infty} K(u) (-b) du $$
$$= (-b) \frac1{b}\int_{-\infty}^{\infty} K(u) du  = -1$$
Something must have gone wrong with the integration. I know that $f(x)$ is often defined differently, as
$$ f'(x) = \frac1{nb}\sum_{i=1}^nK\left(\frac {x - X_i}b\right) $$
and with this version I can show that it integrates to 1. However $f'(x)$ and $f(x)$ should be equivalent as $K$ is symmetric. So there is some flaw in my calculations (my knowledge about integration with substitution is purely heuristic).
Answer: $\require{cancel}$
\begin{align}
\int_{-\infty}^{+\infty} f(x)~{\rm d}x &= \frac{1}{nb}\sum_{i = 1}^n \int_{-\infty}^{+\infty} K\left(\frac{X_i - x}{b}\right){\rm d}x &  \text{with } ~u = \frac{X_i - x}{b},~{\rm d}u = -{\rm d}x/b \\
&= -\frac{1}{n}\sum_{i=1}^n \int_{+\infty}^{-\infty} K(u)~{\rm du} \\
&= \frac{1}{n}\sum_{i=1}^n \cancelto{1}{\int_{-\infty}^{+\infty}K(u){\rm d}u} \\
&= \frac{1}{\cancel{n}} \cancel{n} = 1
\end{align}
The part you need to pay attention to is the limits, when $x\to +\infty$ you have $u \to -\infty$ and vice versa. So the limits of the integral change of order
Comment: How do You know that You can use substitution? I mean does density function (here K) has to have an antiderivative - because that's one of the assumptions for substitution.
Comment: @strefa61 This statement is part of the question "... $K$ is a symmetric probability density function..", which means is an integrable/normalizable function
Comment: I know these are basic questions but I really can't get it.
1. Does symmetricity influences the intregability and have antiderivative?
2. I can't see in the deffinition of density anything about have antiderivative (It has to be integrable, yes, but it doesn't mean we can use substitution for it).
Comment: great answer! I cant believe someone asked this question and someone answered! very useful! thank you!


How to determine if an output is being ignored with ~

Question: In Matlab, you can ignore an output with the following syntax:
[~, ixMax] = max(foo);

I have a function, with signature
[out, out1, out2, out3] = function foo(in1, in2, in3)

out1, out2 and out3 are optional outputs, and each is only needed in very specific (unusual) circumstances.  Foo is computationally expensive, and out1/out2/out3 are all even more computationally expensive, but rely on intermediate state generated by foo.  I'd like to be able to avoid computing out1/out2/out3 if the caller is using a ~ to ignore them.  How can I  check for that in the definition of foo?
Comment: `nargout` is what you need. Not sure if it works if you do `[out,~,~,~]=` but it works if you do `[out]=`
Comment: @AnderBiguri is right with `nargout` - it will return 4 if the user has requested [out,~,~,~].  I dont think there is any (certainly documented) way to determine whether the user has specified a var name instead of `~`
Comment: @Bebs but for that he needs to determine whether an output is unused ( so whether the user used a `~`)
Comment: @m7913d, it doesn't look like a dupe. OP asks if he can save computational resources by avoiding to call an output with `~`.
Comment: @Bebs The title is clearly the same (and correctly reflects the main question). Note that part of the answer may be in the question of the duplicate.
Comment: Interestingly Octave has the function [isargout](https://www.gnu.org/software/octave/doc/v4.2.1/Ignoring-Arguments.html).
Comment: Doh!  How did I miss the dup?
Answer: It won't accelerate the process. The ~ is a way to the reader to tell him you won't need these outputs. It also saves the memory usage of this variable.
Matlab documentation says:

However, some functions return results that use much more memory. If you do not need those variables, they waste space on your system.

So it does not improve performance because these values are internally calculated anyway.
The book Accelerating MATLAB Performance: 1001 tips to speed up MATLAB programs by Yair M. Altman says (p187):

However, without using the ~, and if the first output is needed, the user will gain computational time by just removing the ~ and the brackets, and writing.
out = function foo(in1, in2, in3)

Comment: Nice answer! Just a warning: the quoted text from Altman's book says _trailing `~` signs should be removed from the code whenever they appear_. That's not always true. Some functions return a different first output when they are called with two outputs. Compare for example `a = find(1:3)` and `[a,~] = find(1:3)`
Comment: @AnderBiguri, yes indeed, my answer only focuses on the `~` part. If only the first output is needed, you are correct.
Comment: Nothing, misread some of it. It is true for the `~` operation, but one can write functions that check the amount of outputs asked, so if OP does `[out]=` then they can solve the problem
Comment: @Irreducible it answers the case the OP asks for, when the input is *asked*, but not stored, i.e. `~`. The function does not know if the output is stored, only that is being called. But yes, I think the answer shoudl more clearly state this
Comment: @Irreducible, Matlab says that with the `~` the output is still calculated, but not stored.
Comment: @LuisMendo, I agree, you have a good example of a function that has a different behaviour depending on how many outputs are asked so `~` **is** needed sometimes :-)
Comment: @LuisMendo - I stand corrected, there are indeed cases such as you describe, so I will add a cautionary note to the 2nd edition of my book.

Having said that, I venture to say that these cases are not very common and IMHO demonstrate bad programming design practice. I believe that extra output args, just as extra input args, are best used as purely optional args that have no effect on the meaning of the preceding args.
Comment: @AnderBigurin what's wrong please?
Comment: I am confused by the answer. The reason is, the OP ask how to avoid unnecessary computation by checking whether a output is used. So I dont  see how this answer addresses this question?
Comment: @AnderBiguri, I thought the OP asks to check  _if the caller is using a `~`_ . So he asks for a way to check whether an output is set to `~` and internally use this information to avoid certain computations?!? For me it seems so that the OP understands that Matlab interprets `~` as an output in general.
Comment: @Irreducible and this answer says: you can not do that.
Comment: In m7913d link it seems so that there is a way to over come this? [istilde](http://biorobots.cwru.edu/personnel/adh/stackoverflow/04/)
Comment: Sorry perhaps I am completely wrong. However, my understanding is, that the OP knows the fact that Matlab interprets `~` as an output. I am also aware of this. However, from my perspective the OP ask whether he can check if an output is set by the caller to `~`. m7913d  shared a link where someone claims he wrote a function to do so.
Comment: @Irreducible, alright, I understand your point. The code you provided is interesting.
Comment: @YairAltman I totally agree. They are not very common (the only other function I can think of right now is `size`) and they can be confusing, so it's better to avoid that as programming practice


Unit roots and order of differencing

Question: I'm studying the stationarity with unit root tests and the order of integration in time series $\ln(x)$ and $\ln(y)$ found here. I'm using Dickey-Fuller test with constant but no trend.
From what I understand, the null hypothesis for ADF test is that there is a unit root present (non-stationary, random walk) and $I(d)$ process is stationary after differenced $d$ times. I tried the test for my data:
<code>    df <- read.table(file="ts.txt", header=TRUE, sep="\t")
    x <- as.ts(log(df$x)) #ln(x)
    y <- as.ts(log(df$y)) #ln(y)

    testx <- ur.df(x,type="drift",lags=1) #drift should add constant but no trend right?
    summary(textx)

    testy <- ur.df(y,type="drift",lags=1)
    summary(texty)
</code>
What I get for $\ln(x)$
<code>    Coefficients:
                 Estimate Std. Error t value Pr(>|t|)
    (Intercept)  0.040945   0.018828   2.175   0.0300 *
    z.lag.1     -0.008988   0.004265  -2.107   0.0355 *
    z.diff.lag   0.281566   0.037438   7.521  1.8e-13 ***
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

    Residual standard error: 0.06311 on 656 degrees of freedom
    Multiple R-squared:  0.08326,   Adjusted R-squared:  0.08047
    F-statistic: 29.79 on 2 and 656 DF,  p-value: 4.133e-13

    Value of test-statistic is: -2.1074 2.434

    Critical values for test statistics:
          1pct  5pct 10pct
    tau2 -3.43 -2.86 -2.57
    phi1  6.43  4.59  3.78
</code>
And for $\ln(y)$
<code>Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.032859   0.016654   1.973   0.0489 *
z.lag.1     -0.007538   0.003989  -1.890   0.0592 .
z.diff.lag   0.288379   0.037367   7.717 4.44e-14 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.06192 on 656 degrees of freedom
Multiple R-squared:  0.08604,   Adjusted R-squared:  0.08325
F-statistic: 30.88 on 2 and 656 DF,  p-value: 1.53e-13

Value of test-statistic is: -1.8899 2.0388

Critical values for test statistics:
      1pct  5pct 10pct
tau2 -3.43 -2.86 -2.57
phi1  6.43  4.59  3.78
</code>
What values should I be looking when rejecting/accepting $H_0$? And how can I find the order of integration in this case?
Answer: Yes H0 is the hypothesis, that you have a unit root in your data.
If you type drift, there will be a constant but no trend in your model as you mentioned.
the critical values are listed at the bottom of the test. So for example for ln(x) the ur.df  function gives you the value of test- statistic which in your case is: -2.1074 since this is not smaller than the critical value of -2.86 ( I assume you use the 5% level) you can not reject H0.
For the order of integration: run the same test again, but this time using the first difference of your variable. If you can reject H0 this time your series is I(0) if not you have to take the second difference and then test again. If you can reject H0 after taking the second difference your series is I(2), and so on...
Comment: So $ln(y)$ process IS stationary because $-1.8899<-2.86$? And for that one I cannot find order of difference (the order is 0 basically).
Comment: No, in order to reject H0 the value has to be smaller than the critical value. In your case -1.8899 is biger than -2.86 so you can not reject H0. Since H0 states that there is a unit root, and you can not reject H0, ln(y) has a unit root
Comment: so take the first difference of ln(y) and then run the test again. If the value of the ADF test is smaller than -2.86 the first difference of ln(y) is stationary. Since you only had to take the first difference in order to make ln(y) stationary, ln(y) is said to be I(1)
Comment: Haha yeah I was stupid (long day). Didn't notice the negative sign and just compared the absolute values in my mind :) Thanks for clear explanation !

Unit roots and order of differencing


Colorbox responsivo

Question: Estou usando Colorbox em um projeto e preciso deixa-lo responsivo.
Consegui mudar o tamanho de todas as divs com Media Queries no CSS, mas a div #colorbox não muda o tamanho! Isso faz com que a pagina fique com rolagem horizontal.
Como posso resolver isso?

                <form action="<?php echo site_url('cadastro/redefinirSenha') ?>" method="post"
                      id="form-forgot-pass">

ESQUECI MINHA SENHA

Informe abaixo seu CPF para resetar sua senha.

                        <input type="text" class="cpf" name="cpf" id="cpf" placeholder="CPF" />

                        <input type="submit" id="botao-enviar" value=""/>

SUA SENHA FOI RESETADA

.

                </form>

@media (max-width: 376px){
    #cboxLoadedContent{
        width: 370px !important;
    }
    #cboxContent{
        width: 370px !important;
    }
    #colobox{
        width: 370px !important;
    }
    #cboxWrapper{
        width: 370px !important;
        min-height: 500px;
    }
}
@media (max-width: 321px){
    #cboxLoadedContent{
        width: 300px !important;
    }
    #cboxContent{
        width: 300px !important;
    }
    #colobox{
        width: 300px !important;
    }
    #cboxWrapper{
        width: 300px !important;
        min-height: 500px;
    }
}

A solução que achei foi identificar o tamanho da tela com JS e usar condicionais para definir o tamanho do Colorbox:

if (w < 480){cbWidth = 299;}

if(w > 480) { cbWidth = 400;}

$(".inline").colorbox({inline: true, width: cbWidth});

 $(".ajuda-open").colorbox({width: cbWidth});
Comment: Tem algum código para nos ajudar a te ajudar?
Comment: Essa parte de HTML é as Divs com o conteúdo, mas a div que tem o #colorbox é criado pelo JQuery se não me engano rs
Comment: Então você pode fazer uma variável que fica `null` ou `undefined` até o que a `#colorbox` seja criada, quando ela obtem o valor da div. Daí é só alterar a div pelo jQuery.
Comment: var w = $(window).width();
            if(w > 1600) { cbWidth = 300;}
            $(".inline").colorbox({inline: true, width: cbWidth});
Comment: A sintaxe esta correta?
Comment: No seu exemplo de CSS você escreveu `colobox`, sem o `r`, isso foi só na pergunta ou seu código real está assim também?
Answer: Amigo, ao pegar seu codigo e salvar em um .html funcionou corretamente da forma como deve funcionar em sites responsivos, onde apareceu a barra de rolagem?

                    <form action="<?php echo site_url('cadastro/redefinirSenha') ?>" method="post"
                          id="form-forgot-pass">

ESQUECI MINHA SENHA

Informe abaixo seu CPF para resetar sua senha.

                            <input type="text" class="cpf" name="cpf" id="cpf" placeholder="CPF" />

                            <input type="submit" id="botao-enviar" value=""/>

SUA SENHA FOI RESETADA

.

                    </form>

Comment: Sou menina :D
O colorbox cria uma div agrupando todo o conteudo, e ela estava com o tamanho fixo no  JS! Consegui resolver, mas obrigada pela atenção!

Colorbox responsivo


Convergence of sum $\sum_{n=2}^\infty \frac{(-1)^{n+1}}{(n+(-1)^n)^p} $

Question: I've the following sum:
$$ \sum_{n=2}^\infty \frac{(-1)^{n+1}}{(n+(-1)^n)^p} $$
I think it converges for $p>0 $ but I can't find a good way to prove it.
Answer: Hint
Try to rewrite the denominator, you should able to find that :
$$\sum_{n=2}^\infty \frac{(-1)^{n+1}}{(n+(-1)^n)^p}=\sum_{n=2}^\infty \frac{(-1)^{n}}{n^p}$$
Then apply the Dirichlet's test to conclude that the sum exist iff $p>0$
Comment: @danny11, I don't think so. Try to write the first term and you'll see ;)
Comment: Unless I'm wrong the right sum runs from 1 to infinity.

If it is the case then I found the answer. Big thanks.
Comment: Yes, my mistake. Thanks again.
Comment: @danny11, my pleasure :)
Answer: Hint
In the same spirit as Fabian, separate odd and even values of $n$ and look how is structured the sequence. You should arrive to Fabian's result.


KL Loss with a unit Gaussian

Question: I've been implementing a VAE and I've noticed two different implementations online of the simplified univariate gaussian KL divergence. The original divergence as per here is
$$
KL_{loss}=\log(\frac{\sigma_2}{\sigma_1})+\frac{\sigma_1^2+(\mu_1-\mu_2)^2}{2\sigma^2_2}-\frac{1}{2}
$$
If we assume our prior is a unit gaussian i.e. $\mu_2=0$ and $\sigma_2=1$, this simplifies down to
$$
KL_{loss}=-\log(\sigma_1)+\frac{\sigma_1^2+\mu_1^2}{2}-\frac{1}{2}
$$
$$
KL_{loss}=-\frac{1}{2}(2\log(\sigma_1)-\sigma_1^2-\mu_1^2+1)
$$
And here is where my confusion rests. Although I've found a few obscure github repos with the above implementation, what I more commonly find used is:
$$
=-\frac{1}{2}(\log(\sigma_1)-\sigma_1-\mu^2_1+1)
$$
For example in the official Keras autoencoder tutorial. My question is then, what am I missing between these two? The main difference is dropping the factor of 2 on the log term and not squaring the variance. Analytically I have used the latter with success, for what its worth. Thanks in advance for any help!
Answer: Notice that by replacing $\sigma_1$ with $\sigma_1^2$ in the last equation you recover the previous (i.e. $\log(\sigma_1) - \sigma_1 \rightarrow 2\log(\sigma_1) - \sigma_1^2$). Leading me to think that in the first case the encoder is used to predict the variance, whereas in the second it is used to predict the standard deviation.
Both formulations are equivalent and the objective is unchanged.
Comment: I don't think it can be the case that these are equivalent. Yes, they are both minimised when for zero $\mu$ and unit $\sigma$. However, in the original equation (featuring the variance), the penalty for moving $\sigma$ away from unity is far larger than in the second equation (based on the standard deviation). The penalty for variations in $\mu$ is the same for both, and the reconstruction error would be the same, so using the second version dramatically changes the relative importance of departures of $\sigma$ from unity. What am I missing?
Answer: I believe the answer is simpler. In VAE, people usually use a multivariate normal distribution, which has covariance matrix $\Sigma$ instead of variance $\sigma^2$. That looks confusing in a piece of code but has the desired form.
Here you can find the derivation of a KL divergence for multivariate normal distributions: Deriving the KL divergence loss for VAEs

KL Loss with a unit Gaussian


How to explain the logistic regression model objects from the rms::lrm() function in R?

Question: Recently I was trying to do logistic regression using the rms::lrm() function. But I had some trouble understanding the model objects from the function. Here is the example from the package:
#dataset
n            <- 1000    # define sample size
set.seed(17)            # so can reproduce the results
treat        <- factor(sample(c('a','b','c'), n,TRUE))
num.diseases <- sample(0:4, n,TRUE)
age          <- rnorm(n, 50, 10)
cholesterol  <- rnorm(n, 200, 25)
weight       <- rnorm(n, 150, 20)
sex          <- factor(sample(c('female','male'), n,TRUE))
L            <- .1*(num.diseases-2) + .045*(age-50) +
                (log(cholesterol - 10)-5.2)*(-2*(treat=='a') +
                3.5*(treat=='b')+2*(treat=='c'))
y            <- ifelse(runif(n) < plogis(L), 1, 0)
#fit model
g            <- lrm(y ~ treat*rcs(age))

> g

Logistic Regression Model

lrm(formula = y ~ treat * rcs(age))

                      Model Likelihood     Discrimination    Rank Discrim.
                         Ratio Test            Indexes          Indexes
Obs          1000    LR chi2      76.77    R2       0.099    C       0.656
 0            478    d.f.            14    g        0.665    Dxy     0.312
 1            522    Pr(> chi2) <0.0001    gr       1.945    gamma   0.314
max |deriv| 3e-06                          gp       0.156    tau-a   0.156
                                           Brier    0.231
> anova(g)
                Wald Statistics          Response: y

 Factor                                     Chi-Square d.f. P
 treat  (Factor+Higher Order Factors)        5.62      10   0.8462
  All Interactions                           1.30       8   0.9956
 age  (Factor+Higher Order Factors)         65.99      12   <.0001
  All Interactions                           1.30       8   0.9956
  Nonlinear (Factor+Higher Order Factors)    2.23       9   0.9872
 treat * age  (Factor+Higher Order Factors)  1.30       8   0.9956
  Nonlinear                                  0.99       6   0.9858
  Nonlinear Interaction : f(A,B) vs. AB      0.99       6   0.9858
 TOTAL NONLINEAR                             2.23       9   0.9872
 TOTAL NONLINEAR + INTERACTION               2.57      11   0.9953
 TOTAL                                      69.06      14   <.0001

Here are my questions:
For the object g,

What does the max |deriv| 3e-06 mean?
What do the Discrimination and Rand Discrim. Indexes suggest?

For the anova(g) object,

What's the Factor +Higher Order Factors for the treat?
Why there are two all interactions? How to explain the nonlinear parts?
Answer: Max |deriv| is the maximum (over $\beta$s) of the absolute value of the first derivative of the log-likelihood function at the apparent maximum likelihood estimates.  Being close to zero is a good indication that convergence happened.  There are a lot of background sources explaining the various indexes, especially my course notes at http://biostat.mc.vanderbilt.edu/CourseBios330.  To interpret anova, type ?print.anova.rms to see the various printing options for anova objects.  These options include printing subscripts of $\beta$s that are tested in a given row, or printing a matrix of asterisks to the right of the statistics with blank spaces for $\beta$s not included in the current test.


Criando link de um site para outro no cakephp

Question: Estou com um problema, estou criando um botão, que está em um site X, mas a controller a action do do link está no site Y. O meu problema é que quando clico no botão, ele referencia o controller a action direito, mas a base do site continua do Site X e não do Y.
 <?= (!empty($cnId)) ? $this->Html->link('Galeria', array('plugin'=>'Galeria','controller'=> 'Fotos','action' => 'index',$cnId),array('class'=>'btn btn-default')) : ''; ?>

Ele está me linkando http: X/galeria/fotos/index/$id, mas eu queria que ele me linkasse para Y/galeria/fotos/index/$id. Como faço isso?
Comment: Segundo a documentação: http://api.cakephp.org/2.1/class-HtmlHelper.html#_link  `If $url starts with "http://" this is treated as an external link. Else, it is treated as a path to controller/action and parsed with the HtmlHelper::url() method.`. Você tem que fornecer alguma localização com http:// antes, caso contrário vai apontar sempre "internamente".
Answer: Não é possível utilizar a estrutura routing array para referenciar links externos. Para isso, você deve informar toda a URL no segundo parâmetro, sendo este uma string:
echo $this->Html->link('Galeria', 'http://...', array('class'=>'btn btn-default'));

Answer: Olá, tente isto:
 <?= (!empty($cnId)) ? $this->Html->url('Galeria', array('plugin'=>'Galeria','controller'=> 'Fotos','action' => 'index',$cnId),array('class'=>'btn btn-default')) : '';?>

OU
 <?= (!empty($cnId)) ? $this->Html-link('http://', 'Galeria', array('plugin'=>'Galeria','controller'=> 'Fotos','action' => 'index',$cnId),array('class'=>'btn btn-default')) : '';?>

Comment: A sintaxe aqui dos dois métodos estão incorretas, segundo o [manual](http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html). De qualquer forma @MichelHenriq, não tem necessidade de editar sua pergunta. Basta deixar o seu problema original e marcar a resposta correta como aceita, assim poderá ajudar outros com a mesma dúvida.
Comment: Dessa maneira funcionou, muito obrigado á todos.
Pergunta editada com a resposta certa.


V6-I6 and V-vi6 chord successions

Question: Why are V6-I6 and V-vi6 inappropriate chordal successions (when harmonizing for the Common Practice Period)?
Answer: Let's take a look at the successions and see what leaps to the eye. We'll use C major for simplicity's sake.

The first one, Ex. 1, has a very nice bass for a cadential progression... in E minor. That's the essential problem with it - B isn't acting as a leading tone, it's acting as if it were a dominant root. Put the C chord in root position, and you've got both a logical bass for a move to C and a logical use of the leading tone.
The second one, Ex. 2, also has a very nice bass for a cadential progression... in C major. It makes for a deceptive progression, but maybe too deceptive?
Having said all that, though, there is nothing really objectionable in the voice leading other than that you've got a rising fourth/falling fifth in the bass that isn't a movement from root to root and that the leading tone isn't going where expected in Ex. 1.
Ex. 1 thus gives absolutely no feeling of being a perfect (authentic) cadence, and Ex. 2 undercuts the sense of a deceptive cadence (a little bit) by moving to the inversion instead of root position. The latter is less of a problem than the former in that the unexpected movement of the leading tone is part of a deceptive progression anyway.
It would not surprise me, however, to find that both of these successions have seen use as passing phenomena in the middle of phrases.
Answer: Because the V6 (first inversion) has the leading tone as the bass note. During the common practice period, if the leading tone was on the bass or the soprano voice, it would go to the tonic.
So, following V6 you would need the tonic as the bass note in the next chord; can't be any kind of inversion. Just root position.
I don't see anything wrong with V-vi6

V6-I6 and V-vi6 chord successions


Split/Parse a String after reading a Text File?

Question: I am trying to simply read in a basic text file, split each line into separate strings and rearrange/copy them onto a new text file. Is there any simple way to split and identify these strings to be added to a new file at the end of processing the lines?
My code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    FILE *pFileCust
    fPointer = fopen("Athletes.txt", "r");
    char singleLine[150];

    while (!feof(pFileCust)){
        fscanf(singleLine, 150);
        int id, name, sport;
        fprintf(%d[0,6], %s[8,15], %s[16,22], id, name, sport);
    }

    fclose(fPointer);
    return 0;
}

Example Text File to be read into the program:
88888 John Doe Tennis
99999 Jane Smith Softball

Example Output that I am trying to achieve.
Tennis 88888 John Doe
Softball 99999 Jane Smith

Comment: While this is all possible, perhaps you are using wrong language. If you used Python or Perl, it would be trivial task. E.g. solution using awk is: `awk '{print $4, $1, $2, $3}' < input.txt`
Comment: Consider refactoring the feof check. [See this question](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)
Comment: A lot of weird stuff going on here; `fPointer` is undefined, you probably want to use `pFileCust`; `fscanf` should be taking your file handle as 1st argument, then format, then your variables. `fprintf` should be either `STDOUT`. Your variable will need to be defined before `fscanf`. Finally `name` and `sport` aren't integers in your example but you're using `int` type.
Comment: What is your question?
Comment: sorry zerkms I edited the post!
Comment: Is the "example output" what you *want* to get or what you *actually* get?
Comment: the example output is what I want to get
Comment: Ok, and what do you actually get?
Comment: The program does not compile and at the beginning of my attempts it printed 0's very rapidly
Comment: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
Comment: I made a [bit of a template](https://onlinegdb.com/B1h8hSwc-) for you. This might be a better starting place for you @tx203141. Consider using `strtok`, or maybe even `sscanf` to split. Alternately, you could read using `fscanf`?
Comment: I would love to be able to use strtok effectively I have seen that all over the place for help with this task but I am not sure how to use it correctly, especially after reading in the file
Answer: Each line in your file corresponds to a record. Each series of consecutive non-whitespace characters corresponds to a field in the current record. Accordingly,
/* getrecord: read next record on fp */
char *getrecord(FILE *fp)
{
    assert(fp);

    char *line = malloc(MAXLINE);
    if (line != NULL)
        if (fgets(line, MAXLINE, fp) != NULL)
            return line;

    return NULL;
}

/* getfield: read next field in record */
char *getfield(const char *record, int *pos)
{
    assert(record && pos);

    char *record;
    int ret;

    if ((record = malloc(MAXRECORD)) != NULL) {
        ret = sscanf(record + *pos, "%s", record);
        if (ret == 1)
            return record;
    }
    return NULL;
}

While each function does not appear to do much work, separating your business logic from record/field reading has real benefits. It allows extensibility (for example you can add error handling to these routines). You can also make more sense of your code. Now you can write your main function which will use this pair of calls.
Answer: Here is a simple adaptation of your code that (a) compiles, and (b) generates the output that you desire.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  FILE *pFileCust = fopen("Athletes.txt", "r");
  char first_name[100], last_name[100], sport[100];
  int id;

  while (fscanf(pFileCust, "%d %s %s %s", &id, first_name, last_name, sport) != EOF) {
    printf("%s %d %s %s\n", sport, id, first_name, last_name);

  }

  fclose(pFileCust);
  return 0;
}

One of the key things your app was missing was anything assigning values to your variables; your fscanf was not doing anything (if it even compiled). fscanf is not a very GOOD way to parse text, it's not very robust. But for the principle of understanding how variables are assigned, please look carefully at that, and in particular understand why the id has an ampersand in front of it. Also, make sure you understand why I used both a first name and a last name.
Comment: `fscanf(pFileCust, "%d %99s %99s %99s", ...) == 4` would be more robust.


Accessing controls from other classes .net

Question: I know this has been asked a million times and Ive tried 4-5 different solutions but none of them seem to produce any results.
I have a main form entitled "QoE" and I have two classes entitled "Utils" and and "Tests"
Tests calls a public shared sub from Utils using Utils.ProgressBar()
Utils.ProgressBar() updates a progress bar control from the main form entitled QoE
The ProgressBar modifier option is set to Public but I can't access the control directly from Utils (which I thought I was able to do in the past). Option 2 was to attempt to use this in the Utils class:
Dim f1 as New QoE()
f1.ProgressBarMain.Increment(+1)
f1.ProgressPercent.Text = f1.ProgressBarMain.Value.ToString() & "%"

but it doesn't produce anything.
option 3-5 was creating a module, a public static class, and trying to put the public shared update sub on the Main form itself. With these options though I usually get the "cannot refer to an instance member of a class from within a shared method" error.
So what am I missing? I would love some help.
Thanks Guys.

Edit

You're really just splitting hairs here, this is completely valid question even without code, but here is the code non the less:
Public Class QoE
End Class

Public Class Utils
    public shared sub ProgressBar
        Dim f1 as New QoE()
        f1.ProgressBarMain.Increment(+1)
        f1.ProgressPercent.Text = f1.ProgressBarMain.Value.ToString() & "%"
        'QoE.ProgressBarMain.Increment(+1) Returns The error mentioned in the comments
    end sub
End Class

Public Class Tests
    public shared sub DoWork
        Utils.Progressbar()
    End Sub

So why cant I access the controls from the QoE form when everything is set to public?
    End Class
Comment: Read very carefully the article for the [BackgroundWorker Class](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx).  There is a complete code sample provided there that will achieve exactly what you want to do.
Comment: If "QoE" is the **startup** form as implied by your statement of, "I have a main form entitled "QoE"", then simply use `QoE` to access the controls like this: `QoE.ProgressBarMain.Increment(+1)`, and `QoE.ProgressPercent.Text = QoE.ProgressBarMain.Value.ToString() & "%"`.
Comment: Ive tried QoE.ProgressBar but I always get "reference to a non shared member requires an object reference."
Comment: And there has to be an easier way than using a background worker
Comment: Based on the above, it feels like you might not be understanding how instances of a class differ from one another.  I don't mean this nastily, but it may be worth your while having a look at some "VB Getting Started" tutorials until you understand OOP a little better.  Best of luck.
Comment: What version VB are you working in?  Is QoE the "Startup Object" in Project --> Properties?
Comment: look at my previous posts, I get OOB just fine, I actually have two other projects where calling controls from other forms is working just fine. Just for whatever reason it isnt working here.... Im in vs2010 vb.net fully updated... and yes QoE is the startup object
Comment: Its actually really frustrating, Im currently in one of those other projects and from form2 I can go form1.listbox1.add("this")... and nothing seems different between that project and this project.
Answer: In order to call controls from other classes you have to initiate the form and all the controls.
Public Class Form1
    Public Shared f as Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
       f = Me
    End Sub
End Class

Then in other classes just refer to f normally like
Form1.f.Textbox1.Text = ""

or
Form1.f.CheckBox1.Checked = True

Enjoy
For some additional reading:
http://www.vbforums.com/showthread.php?744677-RESOLVED-Struggling-with-trying-to-access-a-control-on-a-form-from-seperate-classes&p=4563273&highlight=#post4563273
Comment: Not a great solution.  `f` is null in your example.  What happens if you have two Form1s open?
Comment: Notice how your linked reading is not using a Shared variable? Big difference, actually.
Comment: Why would you have two Form1's? I actually dont think having two Form1's is possible in the same solution. And f wouldnt be null - you are setting f to encompass everything in Form1 (controls, subs, etc.). Give it a try.
Comment: f is nothing until you assign it, something like `f = Me`.  You can make lots of Form1s, too:  `Dim newForm As New Form1`, `newForm.Show()`, etc.
Answer: Another solution would be to loop through open forms :
For Each FORM_ITEM As Form In Application.OpenForms
  If FORM_ITEM.Name = "Form1" Then
    With CType(FORM_ITEM, Form1)

      'Enter your code here

    End with
  End if
Next

However, this will apply to every open "Form1". So if you plan to use multiple "Form1", you can set an identifier on Form_Load like Nefariis showed in his answer.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
   F = Me
End Sub

And use that variable in the loop.


My CSS fails my javascript dropdown-menu slide effect

Question: So if you want to see my menu go here.
Since I know you'll want my source, here's the CSS:
* {
margin: 0px;
}
#menu-container ul,
#menu-container li,
#menu-container span,
#menu-container a {
  margin: 0;
  padding: 0;
  position: relative;
}
#menu-container {
  text-align:center;
  height: 49px;
  border-radius: 0px 0px 0 0;
  -moz-border-radius: 0px 0px 0 0;
  -webkit-border-radius: 0px 0px 0 0;
  background: #141414;

  background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALElEQVQImWMwMrJi+v//PxMDw3+m//8ZoPR/qBgDEhuXGLoeYswhXg8R5gAAdVpfoJ3dB5oAAAAASUVORK5CYII=) 100% 100%;
  background: -moz-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #32323a), color-stop(100%, #141414));
  background: -webkit-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -o-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -ms-linear-gradient(top, #32323a 0%, #141414 100%);
  background: linear-gradient(to bottom, #32323a 0%, #141414 100%);
  border-bottom: 2px solid #0fa1e0;
}
#menu-container:after,
#menu-container ul:after {
  content: '';
  display: block;
  clear: both;
}
#menu-container a {
  background: #141414;
  background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALElEQVQImWMwMrJi+v//PxMDw3+m//8ZoPR/qBgDEhuXGLoeYswhXg8R5gAAdVpfoJ3dB5oAAAAASUVORK5CYII=) 100% 100%;
  background: -moz-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #32323a), color-stop(100%, #141414));
  background: -webkit-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -o-linear-gradient(top, #32323a 0%, #141414 100%);
  background: -ms-linear-gradient(top, #32323a 0%, #141414 100%);
  background: linear-gradient(to bottom, #32323a 0%, #141414 100%);
  color: #ffffff;
  display: inline-block;
  margin-right: -4px;
  font-family: Helvetica, Arial, Verdana, sans-serif;
  font-size: 12px;
  line-height: 49px;
  padding: 0 20px;
  text-decoration: none;
}
#menu-container ul {
  list-style: none;
}
#menu-container > ul > li {
  display: inline-block;
  margin-right: -4px;
}
#menu-container > ul > li:hover:after {
  content: '';
  display: block;
  width: 0;
  height: 0;
  position: absolute;
  left: 50%;
  bottom: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid #0fa1e0;
  margin-left: -10px;
}
#menu-container > ul > li:first-child > a {
  border-radius: 0px 0 0 0;
  -moz-border-radius: 0px 0 0 0;
  -webkit-border-radius: 0px 0 0 0;
}
#menu-container > ul > li:last-child > a {
  border-radius: 0 0px 0 0;
  -moz-border-radius: 0 0px 0 0;
  -webkit-border-radius: 0 0px 0 0;
}
#menu-container > ul > li.active > a {
  box-shadow: inset 0 0 3px #000000;
  -moz-box-shadow: inset 0 0 3px #000000;
  -webkit-box-shadow: inset 0 0 3px #000000;
  background: #070707;
  background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALklEQVQImWNQU9Nh+v//PxMDw3+m//8ZkNj/mRgYIHxy5f//Z0BSi18e2TwS5QG4MGB54HL+mAAAAABJRU5ErkJggg==) 100% 100%;
  background: -moz-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #26262c), color-stop(100%, #070707));
  background: -webkit-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -o-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -ms-linear-gradient(top, #26262c 0%, #070707 100%);
  background: linear-gradient(to bottom, #26262c 0%, #070707 100%);
}
#menu-container > ul > li:hover > a {
  background: #070707;
  background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALklEQVQImWNQU9Nh+v//PxMDw3+m//8ZkNj/mRgYIHxy5f//Z0BSi18e2TwS5QG4MGB54HL+mAAAAABJRU5ErkJggg==) 100% 100%;
  background: -moz-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #26262c), color-stop(100%, #070707));
  background: -webkit-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -o-linear-gradient(top, #26262c 0%, #070707 100%);
  background: -ms-linear-gradient(top, #26262c 0%, #070707 100%);
  background: linear-gradient(to bottom, #26262c 0%, #070707 100%);
  box-shadow: inset 0 0 3px #000000;
  -moz-box-shadow: inset 0 0 3px #000000;
  -webkit-box-shadow: inset 0 0 3px #000000;
}
#menu-container .has-sub {
  z-index: 1;
}
#menu-container .has-sub:hover > ul {
  display: block;
}
#menu-container .has-sub ul {
  display: none;
  position: absolute;
  width: 200px;
  top: 100%;
  left: 0;
}
#menu-container .has-sub ul li {
  *margin-bottom: -1px;
}
#menu-container .has-sub ul li a {
  background: #0fa1e0;
  border-bottom: 1px dotted #6fc7ec;
  filter: none;
  font-size: 11px;
  display: block;
  line-height: 120%;
  padding: 10px;
}
#menu-container .has-sub ul li:hover a {
  background: #0c7fb0;
}
#menu-container .has-sub .has-sub:hover > ul {
  display: block;
}
#menu-container .has-sub .has-sub ul {
  display: none;
  position: absolute;
  left: 100%;
  top: 0;
}
#menu-container .has-sub .has-sub ul li a {
  background: #0c7fb0;
  border-bottom: 1px dotted #6db2d0;
}
#menu-container .has-sub .has-sub ul li a:hover {
  background: #095c80;
}
#menu-container {
-moz-box-shadow: 0 0 10px #888;
-webkit-box-shadow: 0 0 10px #888;
box-shadow: 0 0 10px #888;
}
li {
    font-size: 0
}

And JavaScript:
    var menu=function(){
    var t=15,z=50,s=6,a;
    function dd(n){this.n=n; this.h=[]; this.c=[]}
    dd.prototype.init=function(p,c){
        a=c; var w=document.getElementById(p), s=w.getElementsByTagName('ul'), l=s.length, i=0;
        for(i;i<l;i++){
            var h=s[i].parentNode; this.h[i]=h; this.c[i]=s[i];
            h.onmouseover=new Function(this.n+'.st('+i+',true)');
            h.onmouseout=new Function(this.n+'.st('+i+')');
        }
    }
    dd.prototype.st=function(x,f){
        var c=this.c[x], h=this.h[x], p=h.getElementsByTagName('a')[0];
        clearInterval(c.t); c.style.overflow='hidden';
        if(f){
            p.className+=' '+a;
            if(!c.mh){c.style.display='block'; c.style.height=''; c.mh=c.offsetHeight; c.style.height=0}
            if(c.mh==c.offsetHeight){c.style.overflow='visible'}
            else{c.style.zIndex=z; z++; c.t=setInterval(function(){sl(c,1)},t)}
        }else{p.className=p.className.replace(a,''); c.t=setInterval(function(){sl(c,-1)},t)}
    }
    function sl(c,f){
        var h=c.offsetHeight;
        if((h<=0&&f!=1)||(h>=c.mh&&f==1)){
            if(f==1){c.style.filter=''; c.style.opacity=1; c.style.overflow='visible'}
            clearInterval(c.t); return
        }
        var d=(f==1)?Math.ceil((c.mh-h)/s):Math.ceil(h/s), o=h/c.mh;
        c.style.opacity=o; c.style.filter='alpha(opacity='+(o*100)+')';
        c.style.height=h+(d*f)+'px'
    }
    return{dd:dd}
}();

And the HTML:

Home

Games

Dota 2

CS: GO

CS: Source

Terraria

Minecraft

About Us

Our YouTube Channel

Our FAQs/Q&A List

Our RSS Feed

Our Wiki

Our Blog

Privacy Policy

Contact Us

Forums

After I added "text-align:center;" to my CSS, when I hover to the menu the slide animation goes in the down direction, but it goes to right too. How to make it go down  only?
So I want when you hover on a menu the slide to be only to the bottom NOT to the right.
Comment: When we say that we want code in questions, we dont want ALL of your code.  We want the parts that are related to the problem (which you should be able to figure out without help)
Comment: Do you mean [like this](http://matthewjamestaylor.com/blog/centered-dropdown-menus) (demo page [here](http://matthewjamestaylor.com/blog/centered-dropdown-menus.html)) or [like this](http://jsfiddle.net/gNanu/)? It's a matter of centering the children elements, not an issue with the `text-align:center`. Changing `text-align` centers it in reference to the page and doesn't change the positioning of the children at all
Comment: Well I actually mean that when you hover on one of the parent elements the child elements go down (slide down) and when they stop they go right. I don't want them going to the right - just slide down.
Comment: @PowerUser Can you be more clear? Do you mean you want it to [look like the right version?](http://imgur.com/dDQOnNW)
Answer: You have a negative margin being inherited by links in the menu [#menu-container a]. So your menu items end up 4 pixels wider than the menu. You can reset the margin to 0 by adding to the more specific selector like this:
#menu-container .has-sub ul li a { margin-right: 0 }


Elegant ways of proving: If $v_1, \ldots, v_j$ are linearly independent then $v_i \notin span(v_1, \ldots, v_{i-1}, v_{i+1}, ..., v_j)$.

Question: Elegant ways of proving: If $v_1, \ldots, v_j$ are linearly independent then $v_i \notin span(v_1, \ldots, v_{i-1}, v_{i+1}, ..., v_j)$.
Idea:
Suppose I can write $c_1v_1 + \ldots + c_{i-1}v_{i-1} + c_{i+1}v_{i+1} + \ldots c_j v_j = v_i$. Then $c_1v_1 + \ldots + c_{i-1}v_{i-1} + c_{i+1}v_{i+1} + \ldots c_j v_j -v_i= 0$ is a non-trivial relation among the vectors ($-1$ is not zero), a contradiction, since the vectors only have the trivial relation.
Could this be proven without contradiction ?
Answer: Your proof is good and contradiction is not necessary, because you can use the contrapositive.

It is not restrictive to assume $i=1$. If
$$
v_1=c_2v_2+\dots+c_nv_n
$$
then
$$
v_1-c_2v_2-\dots-c_nv_n=0
$$
so the vectors are linearly dependent.
Comment: Thanks for your answer using contraposition - I appreciate it.
Answer: This is a direct proof:
Let
$$F=\operatorname{span}(v_1,\ldots,v_{i-1},v_{i+1},\ldots,v_j)$$
and
$$E=\operatorname{span}(v_1,\ldots,v_j)$$
then
$$E=F+\operatorname{span}(v_i)\tag 1$$
and since $(v_1,\ldots,v_j)$ is linearly independant then it's basis of $E$ then
$$\dim E=j\quad\text{and}\quad\dim F=j-1$$
so
$$\dim E=\dim F+\dim\operatorname{span}(v_i)$$
hence the sum in $(1)$ is direct and then $$\operatorname{span}(v_i)\cap F=\{0\}$$
and the result follows.
Comment: We have this result: If
$$E=F+G$$
and
$$\dim E=\dim F+\dim G$$
then
$$E=F\oplus G$$
Comment: Why can you conclude the sum is direct ? (Thanks for your response)
Comment: Thank you, I will have to look this result up as it's quite useful. Does it has some special name ?
Comment: No it hasn't a special name, it's just one of characterizations of the direct sum that we study. @NicolasLykkeIversen


Java Jersey HTTP, não consigo receber parametros do browser

Question: Olá gostava de receber um parâmetro do browser e imprimir usando webservices com Jersey, entretanto o parâmetro não chega até o meu método, não esta a ser imprimido.
XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>webService</display-name>
    <listener>
        <description>
        Used to cleanup when a session is destroyed</description>
        <display-name>ZK Session cleaner</display-name>
        <listener-class>org.zkoss.zk.ui.http.HttpSessionListener</listener-class>
    </listener>

        <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
        <welcome-file>index.zul</welcome-file>
    </welcome-file-list>

<servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

Método Java que recebe o parâmetro e devia imprimir no browser:
package mz.webservice.testar;

import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;

@Path("/hellowold")
public class Testando {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/{id}")
    public  String GettingHellowold(@PathParam("id") String id) {
        String st=id;

        return "Nome: "+st;
    }

}

Resultado no browser
Answer: Olá consigui fazer a implementação, Obrigado pela ajuda.
package mz.webservice.testar;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.google.gson.Gson;

@Path("/hellowold")
public class Testando {

    //http://localhost:8080/webService/rest/hellowold/primeiro?conta=123456&codigo=00000123

    @GET
    @Path("/primeiro")
    public Response getEmployeeQueryDefault( @QueryParam("conta") String conta, @QueryParam("codigo") String codigo) {
    String response;
    Gson  g=new Gson();
    Person person=new Person();
    person.setCodigo(codigo);
    person.setConta(conta);
    response=g.toJson(person);
    try {

    } catch (Throwable e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return Response.status(200).entity(response).build();
    }

}


A guitar won't stay in tune, also dirty pickup selector

Question: My friend has an Ibanez.. something, and it's not the most expensive guitar. Nevertheless, it is a pretty good guitar for its budget. Lately there have been a few problems with it, which I told him I would do my best to fix.
First off, the pickup selector crackles when it is switched, I assume from being dirty because it hasn't done that in years past. I took a look inside of the guitar at the selector to see how to clean it, and it's a sealed unit. I have been reading online and they have suggested something like compressed air or contact (electrical) cleaner. It also said to spray the air in while working the pickup selector back and forth. I would be willing to test one of these out, but if there are additional tips that I should know I would be most appreciative.
Second, the guitar will just not stay in tune (I've learned that guitars are never truly in tune, but it isn't the same thing.) We have tuned it to a-440 with a chromatic tuner, but.. say I play a G chord, the B or another string would be a little bit out of tune..so I tune that. Then I could play an E, then it B sounds out of tune...But if I tune the B, then the G might be out.. I an thinking that this problem is due to A) incorrect action, which I can fix, or B) (my guitar doesn't have a whammy so I don't know about this one) The whammy unit / springs could have been stretched out over time and just won't stay in tune now.
Once again, any help is greatly appreciated =)
P.S. No, the strings aren't new, and they're not that old either.
Comment: Simply cleaning the nut may help. Also, if the strings gauge was recently changed, that could also be causing problems. Are the strings binding at the nut? (i.e., are the slots wide enough for the strings to freely move when tuning? They should be.) Is the nut a standard type or is it a locking nut?
Comment: The crackling isn't persistent, it is only when switching pickups, so I think I will try some compressed air or contact cleaner.                                 As for the strings, the guage HAS been changed lately, except to a lighter guage. The guitar doesn't have alocking nut and the string are able to freely fit through the saddle. The strings aren't the problem, so I think it is possible the neck warping or wear on the bridge springs. The whammy, however, is rarely used at all and shouldn't be too stretched or used. Once I get a look at it tonight I will be able to post some more details.
Answer: First for the selector.
Is the crackle sound just when switched or persistent when in one position? In the first case, compressed air and contact cleaner have always worked well for me on my near-20 years old Strat. In the second case might as well be the wires/soldering/pickups.
For the tuning part, "tremolo" bridges need always a little more work to get in tune, that's because tuning a string adds/removes some tension on the bridge so all other strings need retuning. You have to do many "passes" on all the string until the variations in tone are so small that the bridge stays stiff.
All this unless the bridge it's a Floyd Rose (or similar concept) which should "resolve", or at least reduce, those problems.
But!
If the guitar goes easily/fast out of tune after some playing, it might be a bad/deformed neck or (as you pointed out) the bridge springs need replacing.
Also, check the nut, most tuning problems originate from a bad nut, it might be worth replacing it.
Answer: Re: the tuning. It is always best to have a pro do this, but with adjustable saddle and an electric tuner, you can try doing it yourself first. The basic idea is to tune all the open strings according to the tuner, then fret the note at the 12th fret(one octave up). The 12th fret note should be in tune. If the 12th fret note is off, adjust the saddle, retune the open string, and test the 12th fret again. Repeat. Do this for each string.
This is typically referred to as "electric guitar intonation adjustment"
Answer: In regards to tuning. I guess that it has a floating bridge and a fixed nut.

Loosen the nut
set all tune knobs on the bridge to their middle position
Tune from high to low and cycle this 3 or 4 times so that the strings are pretty tuned.
Lock the nut
Now tune the strings by the tune knobs on the bridge.

This approach work fine on my Ibanez RG350 EX.
When you then make a dive bomb it should still be in tune. If its not then this could be caused by

Old strings
Wear on the bridge springs
Incorrect strings (to thick/thin)
Wear on the bridge itself.

You can check if the bridge has a sharp edge as it could have become blunt. If that is the case then you should bring it in for maintenance to get it sharpened.
You can also lock the bridge if it is rarely used.
Keep in mind that a floating bridges will always be a little out of tune when used due to the stretching of the strings.
Comment: This is a really good answer in principle, it just does not really apply to non-Floyd-Rose guitars.
Answer: A whammy has two different "modes of operation": it can either be free-floating or not. The difference is that in free-floating mode, the spring tension just compensates the string tension so that the bridge stays in a non-fixed equilibrium position, so that you can subtly move it, modify the pitch not only down- but also upwards and play actual vibratos. The price to pay is that every change in tension, every bend etc. will always move this equilibrium position a little, thereby detuning all the strings. This mode is probably default in this guitar, it has not necessarily to do with worn out springs.
But you can, and if the vibrato system is rarely used I would actually recommend it, stop this free-floating by increasing the spring tension.
The other possible problem is the saddle. Often, the grooves are not quite wide enough to allow the strings to be tuned without friction-caused causing nonequal tensions, which will then, after some time, be released, detuning the string. It sometimes helps to do some bendings on a string to release any tension differences, re-tune it, bend again etc. until it stays in tune.
Answer: For my guitars with full floating bridges my tuning method when putting on a new set of strings is to start with the low E and tune it to an F. Then I tune each string to the previous one. By the time I reach the top E it is just about in tune. You will find at this point the tension has lowered the pitch on all the strings.
Then I go back to my bottom E and tune it slightly sharp again, and once again tune the other strings to this.
Then I lock the nut and carry out a couple of divebombs and squeals.
Then a last fine tune using the bridge tuners sorts it out, and it will stay almost in tune, with minor tweaks needed from the bridge tuners, until I replace the strings.

And for the switch - try contact cleaner, as if it is dirt and dust this will sort your problem. If the problem remains, it could be worn contacts, in which case just swap in a new switch.
Answer: Re. the crackly switch, a squirt of WD-40 worked for me.
Comment: Terrible idea. WD-40 leaves a residue that attracts dirt. It fixes the problem in the short term, but makes it worse in the long term.
Comment: What might work is contact cleaner. I got rid of the noise in my headphone amp's faders this way. For more detail, see [this answer](http://avp.stackexchange.com/questions/1324/headphone-amp-sliders-are-making-noise-worth-fixing-or-not/1325#1325) on the AVP site.
Comment: People always say that, but I never hear a first hand account of Wd-40 ruining a switch. Have you had this happen to you?


Setting Billable Limits

Question: From the Google API Console: When trying to change the Billable Limits for the project under the Quota page, I keep getting the error: Your input was invalid.
The error message is not very informative, doesn't specify which input was invalid or why it was invalid.
I've experimented with this in IE, Firefox, and Chrome. I've also turned off all other APIs except for Custom Search API (which I'd like to increase the limit for) without any luck.
Has anyone else encountered this problem? how can it be solved?
Comment: This is happening to me too.  I wonder if its because the quota page is using the old console, and they're trying to move to the new one.
Comment: Ethan, I thought the same as well. I was hoping that there might be a simpler solution or that the Google API team might see this post. It is odd that a product which we pay for has a bug such as this one. I would think this would be a priority to fix.
Comment: I was able to get in contact with Google Enterprise Support, and the person I talked to agreed with me that this is a bug.  He's passed the issue on to their engineering team.  So we'll see what happens...
Comment: Hi Ethan, do you have any updates on this issue or a ticket number to track with Google?
Comment: I haven't heard anything for a while.  I might bug them again.
Comment: Just got a reply back that it should be fixed.  Tried to update billable limits and it worked!  Maybe give it a try now.
Comment: Hi Ethan, how did you contact Google about this? I am having the same problem too.
Answer: (response from a Google employee)
This can happen if a "restricted" API is enabled on the project. "Restricted" APIs can only be seen by specifically enabled users. For instance, the Google Maps Javascript API v2 has been marked "restricted" because it was retired in 2013, and no user should see this API anymore (and instead, use v3).
Work is underway to remove the Google Maps Javascript API v2 from all the existing projects. A systemic fix is being worked on (internal Google reference #12001333), but in the meantime, if you see this error, the best workaround is to use a different API project.
Comment: Not a very good solution we cannot switch everything to different project right now. Anything else, maybe?

Setting Billable Limits


NLTK, reading in word numbers to float numbers

Question: I've looked at the corpus section of NLTK, but there doesn't seem to be a numbers corpus. I want to change word numbers into text. For example:
input: one thousand two hundred forty three output: 1243
input: second output: 2
input: five percent output: 0.05
Comment: Maybe you'll find this useful: http://pastebin.com/WwFCjYtt
Answer: There isn't. What you need to do is build off this Is there a way to convert number words to Integers? or someone else you find useful/easier to work with.
To start off you'll need regex to extract those strings of interest (i.e. one, two...) then replace using the code above.
The first example you've given will be the easiest of the three, the last example is just divide that number by 100 since the output is actually an integer. The second one will be a little tricky as you'll have to modify the code or possibly create a whole new function.
AFAIK, there is no module that will parse the whole text for that.
Another possibility, as I looked further into this, is to use CD tagging from Tree Parser to help identify numbers. But you'll still need a function similar to the one mentioned above.


Combining functions

Question: I want to know how to represent functions by one formula which are defined by multiple formula.
For example:
The function $f(x)$ defined as follows
$$f(x)=x,0\leq x< 1 \text{ and } f(x)=2x-1,1\leq x\leq2$$
could be represented as $$f(x)=\frac{3}{2}(x-\frac{1}{3})+\frac{1}{2}|x-1|$$
Then, I was working on the following function
$$ f(y)=y^2-5y,0<y\leq6, \text{ and } f(y)=-y^2-5y,-6<y \leq0$$
I wanted to know is there a method using which such functions could be combined to a single formula
Answer: In that particular example
$$
f(y)=|y|(y-5).
$$
With the new formulation, we have
$$
f(y)=y\,|y|-5\,y.
$$
Comment: I am sorry I have made a correction $f(y)=-5y-y^2$

Combining functions


How to calculate YTD and MTD in mongodb?

Question: How to calculate Month-To-Date(MTD) and Year-To-Date(YTD) in mongodb in a single query? sample data below, in this data requestedOn is a date field, I want to calculate MTD & YTD, on the assumption of financial year on "1st Jan of the year"(For example financial year for year 2016 is "01-Jan-2016" :
<code>     {
  "_id": {
    "$oid": "5808578b33fa6f161c9747f8"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2000-03-01",
  "bookName": "Test6",
  "revenue": 10.0,
  "unitsSold": 1,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    },
    {
      "categoryCode": "Cooking/Beverages/Bartending"
    },
    {
      "categoryCode": "Food Receipe/Taste"
    }
  ]
}{
  "_id": {
    "$oid": "5808578b33fa6f161c9747f9"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2000-03-01",
  "bookName": "Test1",
  "revenue": 11.0,
  "unitsSold": 2,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    },
    {
      "categoryCode": "Cooking/Beverages/Bartending"
    },
    {
      "categoryCode": "Food Receipe/Taste"
    }
  ]
}{
  "_id": {
    "$oid": "5808578b33fa6f161c9747fa"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2000-06-01",
  "bookName": "Test2",
  "revenue": 12.0,
  "unitsSold": 3,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    },
    {
      "categoryCode": "Cooking/Beverages/Bartending"
    },
    {
      "categoryCode": "Food Receipe/Taste"
    }
  ]
}{
  "_id": {
    "$oid": "5808578b33fa6f161c9747fb"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2000-07-01",
  "bookName": "Test3",
  "revenue": 13.0,
  "unitsSold": 4,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    },
    {
      "categoryCode": "Cooking/Beverages/Bartending"
    },
    {
      "categoryCode": "Food Receipe/Taste"
    }
  ]
}{
  "_id": {
    "$oid": "5808578b33fa6f161c9747fc"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2009-09-01",
  "bookName": "Test4",
  "revenue": 14.0,
  "unitsSold": 5,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    },
    {
      "categoryCode": "Cooking/Beverages/Bartending"
    },
    {
      "categoryCode": "Food Receipe/Taste"
    }
  ]
}{
  "_id": {
    "$oid": "5808578b33fa6f161c9747fd"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2009-06-01",
  "bookName": "Test5",
  "revenue": 15.0,
  "unitsSold": 6,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    },
    {
      "categoryCode": "Cooking/Beverages/Bartending"
    },
    {
      "categoryCode": "Food Receipe/Taste"
    }
  ]
}{
  "_id": {
    "$oid": "5808578b33fa6f161c9747fe"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2004-06-01",
  "bookName": "Test10",
  "revenue": 16.0,
  "unitsSold": 7,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    },
    {
      "categoryCode": "Cooking/Beverages/Bartending"
    },
    {
      "categoryCode": "Food Receipe/Taste"
    }
  ]
}{
  "_id": {
    "$oid": "5808578b33fa6f161c9747ff"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2000-01-01",
  "bookName": "Test11",
  "revenue": 100.0,
  "unitsSold": 100,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    },
    {
      "categoryCode": "Cooking/Beverages/Bartending"
    },
    {
      "categoryCode": "Food Receipe/Taste"
    }
  ]
}{
  "_id": {
    "$oid": "580857b833fa6f0c3499e462"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2000-02-01",
  "bookName": "Test1",
  "revenue": 20.0,
  "unitsSold": 10,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    }
  ]
}{
  "_id": {
    "$oid": "580857b833fa6f0c3499e463"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2001-02-01",
  "bookName": "Test2",
  "revenue": 19.0,
  "unitsSold": 9,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    }
  ]
}{
  "_id": {
    "$oid": "580857b833fa6f0c3499e464"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2001-02-01",
  "bookName": "Test3",
  "revenue": 18.0,
  "unitsSold": 8,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    }
  ]
}{
  "_id": {
    "$oid": "580857b833fa6f0c3499e465"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2007-06-01",
  "bookName": "Test4",
  "revenue": 17.0,
  "unitsSold": 7,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    }
  ]
}{
  "_id": {
    "$oid": "580857b833fa6f0c3499e466"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2005-06-01",
  "bookName": "Test5",
  "revenue": 16.0,
  "unitsSold": 6,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    }
  ]
}{
  "_id": {
    "$oid": "580857b833fa6f0c3499e467"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2004-06-01",
  "bookName": "Test1",
  "revenue": 15.0,
  "unitsSold": 5,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    }
  ]
}{
  "_id": {
    "$oid": "580857b833fa6f0c3499e468"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2002-06-01",
  "bookName": "Test2",
  "revenue": 14.0,
  "unitsSold": 4,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    }
  ]
}{
  "_id": {
    "$oid": "580857b833fa6f0c3499e469"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2001-06-01",
  "bookName": "Test3",
  "revenue": 13.0,
  "unitsSold": 3,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    }
  ]
}{
  "_id": {
    "$oid": "580857b833fa6f0c3499e46a"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2000-06-01",
  "bookName": "Test4",
  "revenue": 12.0,
  "unitsSold": 2,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    }
  ]
}{
  "_id": {
    "$oid": "580857b833fa6f0c3499e46b"
  },
  "_class": "exceltest.TestBean",
  "requestedOn": "2008-06-01",
  "bookName": "Test5",
  "revenue": 11.0,
  "unitsSold": 1,
  "bookCategory": [
    {
      "categoryCode": "Cooking/"
    },
    {
      "categoryCode": "Cooking/Beverages"
    },
    {
      "categoryCode": "Food Receipe/"
    },
    {
      "categoryCode": "Food Receipe/Bartending"
    }
  ]
}
</code>
Regards
Kris
Comment: Please show us what you tried so far.
Answer: It is a good practice to keep dates in MongoDB in its native dateformat ISODate().
You can use date formats like $year,$month,$day,$hour etc.
These can be used for grouping , in your case:
<code>    db.collectionName.aggregate([
          {$group:{_id:{'Date':{$year:'$requestedOn'}},total:{$sum:'$FieldName'}}}
     ])
</code>
to convert string to ISODate , answers can be found at
<code>   - [http://stackoverflow.com/questions/15473772/how-to-convert-from-string-to-date-data-type?noredirect=1&lq=1][2]
   - [http://stackoverflow.com/questions/15473772/how-to-convert-from-string-to-date-data-type?noredirect=1&lq=1][2]
</code>