Can one measure the degree of empirical data being Gaussian?

Question: I would like to inquire about a simple test I might be able to perform to determine how 'nicely Gaussian' my empirical data are. If they are 'nicely Gaussian', then I can perform some other analysis, that assumes my data are Gaussian to begin with.
I am looking for a concrete test. I have a simple 1-dimensional data vector, with $N\approx 10,000$, so I have plenty of data. I want to determine if these data are Gaussian.
What I have tried:

I understand that the Gaussian PDF has no skewness, and no kurtosis, so I have implemented those metrics and taken a measure. This works OK--I think--so as it stands, this is my plan B. Perhaps there is a better way?
I have heard the term "chi-squared" being thrown around. I understand that it is a PDF in its own right, but I am not sure how this might apply to this problem.
Although half in jest, my current way is to simply eyeball the data. Needless to say, this is OK for some cases, but it will not work when data is being run and I am sleeping...

EDIT:
It has been suggested that I talk some more about the 'other analysis' I had in mind, so here goes: If my data is Gaussian, I can readily apply a threshold developed (ex, here), but they only apply for data that is Gaussian. Now, if my test comes back "not Gaussian", then what I would like to do is determine what is the closest PDF that matches it, so that I can attempt to derive thresholds myself.
Now, thanks to everyone, I understand that there is an infinite number of PDFs, and I realize my question might have been somewhat open ended.
So to put a lot more clarity into the picture, I can say that my data is either a 'nice Gaussian' looking PDF, or, it tends to be a "Gaussian PDF with symmetric long tails". So, if my test comes back and says "Yes, your data is Gaussian", I can use one of the canned threshold tests I linked to earlier. If on the other hand my test says "No, the tails are way too long for a typical Gaussian...", then I would want to: 1) Know what type of PDF is this, 2) Estimate new thresholds on my own based on this.
I hope this clarifies some more, thanks for everyone.
Comment: The answer depends on what "other analysis" you have in mind. Even when 10,000 values very closely approximate a Normal distribution, a distribution test (like the K-S or S-W) will reject the hypothesis of Normality, even though the data are *beautifully* behaved for other analyses. Perhaps you could edit this question to indicate the nature of the follow-on analyses you have in mind. In the meantime, searching our site will turn up dozens (if not hundreds) of discussions of this issue.
Comment: You should look into the Kolmogorov Smirnov test.  It is the most commonly used procedure to test whether empirical data follows a given distribution.
Comment: +1 to @whuber and to all sceptics on tests. Specifically, note that Kolmogorov-Smirnov requires adjustment if parameters are estimated, as they usually are. With sample size $\sim 10^4$ testing is arguably not the issue, but you might still benefit from some indicator as a warning, but what indicator that will be depends on quite how your work depends on normality.
Comment: While I am also skeptical of blind use of hypothesis tests, the OP was asking for a "concrete test" to "run while he is sleeping".  I do agree with @whuber that what is approximately Gaussian depends on the type of follow up analysis to be done.  Knowing what other analysis is to be done with the data would be helpful.
Comment: I think what you do is quite sensible. Given you skewness and kurtosis appear "reasonable" (ie. within some conf. intervals you calculate based on your sample size) showing those along-side a non-pathological QQ-plot would be adequate to show your data is Gaussian. *Overkill suggestion*: I guess you could go ahead and do quantile renormalization of your data ie. map your data quantiles on Gaussian quantiles. Then you would go ahead, and compare your two set quantiles using KS-test (mapped & unmapped); if they are significantly different, then you didn't have Gaussian data to start with.
Comment: @caburke Thanks for that. [Kolmogorov Test](http://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test). From quickly skimming, it would then seem that this test is a measure of the L-1 norm deviation of the CDFs? Is that it in a nutshell?
Comment: @caburke: I never really felt comfortable with single normality test like Kolmogorov-Smirnov, Jarque–Bera, Shapiro-Wilk test etc (apparently it takes two to make a good Gaussianity test). I always find them "slightly too strong", as in my first comment, I find them a bit of an overkill.
:TheGrapeBeyond: Basically yes.
Comment: @user11852 Thank you. Yes, I would be content with just having a rough&tumble-then-go-home measure of goodness measure. Its not a HUGE deal if it is not completely fitting a gaussian, I just have to verify that it can be reasonably considered a gaussian...
Comment: @TheGrapeBeyond: It is closer to $L_{\infty}$ really than $L_1$ but yeah that's the big picture. (I can't edit a comment after 5'...)
Comment: @user11852 Oops! Yes thats what I meant - $L_{\infty}$. (Mini-max). :-)
Comment: Oh,okay, sorry. I'll delete that. And, eventually, this.
Comment: @whuber Thanks for your comment, I thought about it over the weekend, and have edited my post under 'edit'. Kindly take a look please, thank you.
Comment: @caburke Thank you, I have edited my post to clarify.
Comment: Somewhat related: http://stats.stackexchange.com/questions/2492/is-normality-testing-essentially-useless
Answer: There are an infinite number of ways of being non-Gaussian.
For example, you mentioned skewness and kurtosis - while those measures are certainly ways of identifying distributions that aren't Gaussian, and they can be combined into a single measure of deviation from Gaussian-ness* (and even form the basis of some common tests of normality), they're terrible at identifying distributions that have the same skewness and kurtosis as a normal but are distinctly non-normal.
* (see the tests by Bowman and Shenton and the better known - but less well-done, I think - work of Jarque and Bera)
Here's an example of the density of one such distribution:

It's bimodal, but has skewness 0, and kurtosis 3.00 (i.e. an excess kurtosis of 0), the same as the normal.
A measure based on skewness and kurtosis is going to be terrible at identifying distributions such as these. Of course, if you're not worried about such possibilities, this may not matter - if you mainly want to pick up cases where the skewness and kurtosis deviate from those of the normal, a test based on those two measures is relatively powerful.
(Incidentally, the Shapiro-Wilk test is fairly good at spotting this one.)
Ultimately, choosing such a measure (whether you intend to formally test it or not) is a matter of finding things that are good at distinguishing the particular kinds of non-normality you care about. (In hypothesis-test-ese, the ones that have good power against the specific alternatives of interest.)
So work out what features you want to 'see' best, and choose a measure that is good at seeing those things.
The chi-square you mention probably refers to the chi-square goodness of fit test. It's generally a very weak test of goodness of fit for anything other than distributions over nominal categories. (Alternatively, it might be a reference to the asymptotic chi-square distribution of the Jarque-Bera type test. Be warned, the asymptotics there 'kick in' very slowly - you need a very large n for the distribution of the test statistic to be close to normal -- see Bowman and Shenton's paper -- which predates the one by Jarque and Bera. My own simulations from back in the 80s suggest that n=200 is not close to adequate - at least for the sort of adherence to significance levels I'd look for - but it's generally pretty reasonable by about n=500)
Popular tests of normality would start with the Shapiro-Wilk and Shapiro-Francia. The Anderson-Darling** test can be adapted to work with parameter estimation and has good power. There's also smooth tests of goodness of fit (see the little book by Rayner and Best by that name, and their many papers, as well as the more recent book on Smooth tests in R); the smooth test for normality is quite powerful.
** With hypothesis tests that assume a completely specified distribution, such as the Kolmogorov-Smirnov and the Anderson-Darling, avoid using tests of normality based off estimated parameter values. The tests don't have the right properties, unless you account for that effect. In the case of the K-S, you end up with what's called a Lilliefors test. With the A-D it's still called an A-D test and if you check the book by D'Agostino & Stephens I mention below, there are approximations which adapt the usual test that seem to work quite well even with fairly small n.
If you don't want a formal hypothesis test, just about any of the usual test statistics can be adapted to be a measure that has some kind of interpretation or other as a measure of non-normality. For example, a Shapiro-Francia test statistic can be seen as a rescaled version of a squared correlation of observations with their normal scores (expected normal order statistics), and such a measure is an excellent accompaniment to a normal QQ plot.

I want to determine if these data are Gaussian.

I bet you a dollar they aren't Gaussian, and I bet you don't even need a test to tell that. What you really want to know is likely something else.
Note that usually the interesting question isn't 'are my data normal' (the answer is almost always 'obviously not', even before you collect any observations). The interesting question is 'how badly will the non-normality I have affect whatever I am trying to do?' ... and that's usually better judged by some measure of how non-normal it is, rather than a p-value.
Good places to start reading about goodness of fit (if you have access to a suitable library) would be the book Goodness of Fit Techniques by D'Agostino and Stephens and the aforementioned book on smooth tests by Rayner and Best; alternatively there are many papers and discussions you can find online, including many answers relating to goodness of fit here. Outside of some papers that are online, smooth tests can be hard to find information on, but one of Cosma Shalizi's courses has some excellent notes see here that serve as a (somewhat mathematical) introduction to the ideas.
[Goodness of fit is a surprisingly big area.]

For additional useful points, see also here or here or here or here
Comment: I don't think your edits allow more precise advice. You are telling us nothing about your data or even about what kinds of deviation from Gaussianity you fear. No indicator of non-Gaussianity, scalar or vector, leads ineluctably to identification of a better distribution. If the main issue were skewness, it might be that you should think of in terms of gamma distributions; or if it were fatter tails, of a family of t distributions. Both of these families have Gaussian as a limiting case. If you ask around, you would get other suggestions.
Comment: I think I see what you are getting at, but you need to sharpen up your terminology. A Gaussian with long tails is just another Gaussian, but one with a high standard deviation. I think you mean a symmetric distribution with higher kurtosis than the Gaussian; if so the family of t distributions might be a possibility for you. But as said, high SD is consistent with being Gaussian.
Comment: @user2429920 As Glen_b underlines, my comment was a reaction to the previous comment and embedded within it was a call to sharpen up terminology. I naturally agree with your remarks.
Comment: @Silverfish Indeed, I do; it's a "double Gamma" (in the same sense as 'double exponential' is to exponential), where the shape parameter of the gamma (I'll call it $a$ here) is about 2.302776. You can solve the equation explicitly - the kurtosis of this double gamma is $\mu'_4/(\mu'_2)^2$ for the original gamma i.e. $\Gamma(a+4)\Gamma(a)/\Gamma(a+2)^2$, which setting to 3 implies $(a+3)(a+2)=3a(a+1)$, or $a^2-a-3=0$. Which gives $a=\frac12(1+\sqrt{13})$. By symmetry (and existence of the raw moments of the gamma), the third moment is 0, so we have the same skewness and kurtosis as the normal.
Comment: Thank you very much Mr Glen_b I have to look over and study what you have said, I will comment back tomorrow.
Comment: Glen_B, I have edited my post to clarify based on what you have said, kindly take a look, thank you.
Comment: @NickCox I thought I made that clear in the edits: After looking at my data my data is either going to be a Gaussian in one extreme, or a Gaussian 'with long tails' in the other. That would pretty much summarize my data.
Comment: @NickCox Apologies for terminology, this is a case of where 'I dont know what I dont know', I am trying my best to keep up/learn where I can, and then use proper terminology. Yes, I mean symmetric distribution, with higher kurtosis than a Gaussian... yes, looking at Student-T-Distribution, this might be the other extreme my data goes to. Thanks for that.
Comment: @TheGrapeBeyond I bet your data aren't t-distributed either. There are an infinite number of distributions that are roughly symmetric vaguely bell-shaped but heavier-tailed than normal.
Comment: @Nic Cox - A Gaussian *never* has long tails, in the technical sense; see: http://en.wikipedia.org/wiki/Heavy-tailed_distribution#Definition_of_long-tailed_distribution
Comment: @Creatron, if your distribution has long tails, it is not Gaussian, see: http://en.wikipedia.org/wiki/Heavy-tailed_distribution#Definition_of_long-tailed_distribution
Comment: @user2429920 I strongly doubt there's any chance that NickCox was using the term in the linked sense, but was instead responding to the way the term was being used in the question.
Comment: Do you happen to remember what the distribution you plotted is? It's a handy (counter-)example.
Comment: Thanks, I thought it might be gamma but it is quite possible to misjudge by eye!
Comment: @Silverfish Yes. It's pretty easy to construct examples with other distributions though. I came up with this example a couple of decades back (actually, it must have been over 25 years ago now), originally just solving the equation in $\Gamma$'s by trial and error (in essence proceeding by something between binary section, regula falsi and guessing; it sufficed at the time I guess). It was an embarrassingly long time before I realized it was just the solution of a quadratic. Coming up with examples/counterexamples like these is fun.


How do i find the cubic inches of this shape?

Question: I can solve for the cubic inches of a pyramid or a triangle, but this shape is a bit different as all sides do not come to one point. It is a triangular bag that i need to find the cubic inch size for.
How do i find the volume of this shape? Is it similar to solving for a pyramid?
Answer: This is a prism.
The cross section is a triangle, find the area of the triangle and multiply by the depth and you get the volume.


How to read stacked chords?

Question: I'm trying to learn Laugh and a half by DAD. Everything is clear except for second line of verse 1 where there are chords on top of each other (G on top of D). How do I play them?

Em              D                      Em - Em
 I learned politeness on my mother's knee
G                  G                       D
D Dsus2 D
 I learned by uprightness my number of friends should increase.
Answer: That looks like a "wrapped" line, not stacked chords.
The 'D Dsus2 D' part is probably just after the word 'increase' but the line was too long for one of the protocols the file has traversed, and so it got wrapped to a new line.
Some common line-length limits for text data are 72, 80, 99 (common in "beginner" software because it's so easy to type buf[99] and move on to "fun" stuff).

This should also be easy to spot because D Dsus2 D is one of several common folk-guitar ornaments (others are D Dsus4 D, A Asus4 A, Am Asus2 Am, C Cadd9 C, C Cmaj7 C) which involve a single finger-change. So in a sense it belongs at the end of a line just after the lyric. That's the moment when the singing stops and the guitar naturally needs to doing something interesting. A "sus4" or "sus2" ornament adds that little bit of interest. Other options are: descending bass-line, jump to chromatic mediant, play the changes totally straight to add suspense, slide up to a different phrasing of the same chord, do a little solo...
Answer: Just as a reference, there is something called poly chords which in concept are "stacked chords".
An example would be D above C, which is written as (but should be tighter layout wise):

D
-
C

and simply refers to a C triad chord (in any inversion) with a D triad chord (in any inversion) stacked on top of it.
One might wonder what the difference of the example is from a C6/9#11 chord? Well, not much really, but in the 'D above C' case you could expect to hear the tones of the D chord as a distinguishable unit of its own and played above the tones of the C chord. A typical presentation of this could be a jazz big band where the trombones and saxophones play a C chord but the trumpets play a D chord creating a cool tension that wouldn't have been the same with a more traditional voicing of a C6/9#11 chord. Hosting the D chord in an instrument section of its own enhances the effect. If the trumpets where to also use, say, a harmon mute it would be even clearer that they were doing something different than the tromones, further establishing the 'D above C' case.
Poly chords are not to be confused with slash chords!
Answer: http://tabs.ultimate-guitar.com/d/dad/laugh_and_a_half_ver3_crd.htm
It's surely a case of wrapped line.
check out the lines
*G                 D    Dsus4  D Dsus2  D
in spite of the curves my smile was makin'.*
Comment: -1 This answer is an exact duplicate of @luser droog's answer. You didn't add anything and the same link is also found in the question.

How to read stacked chords?


What is it called when a group of vocalists or chorus sing Ooh's oh's, ah's, etc?

Question: I heard my chorus director refer to it as something sounding like dest cant or something, but since I'm hard-of-hearing, I couldn't hear all the letters.
If someone can give me the correct name for this, as well as more information and resources about it, that would be excellent.
Comment: 'Descant'? But it's not really oohs and ahs. Descant is singing another part over the top, literally, of an existing melody. Singing oohs and ahs is simply 'songs without words' - although there's probably an authorised word for that.
Comment: @Tim, maybe the teacher meant "distant" singer, not *descant*
Comment: I think I've found now the correct term (s. the edit of my answer: BV'S = **backing vocals**
Comment: There is a word "descant", which is defined in the answers below. The word for "oohs" and "aahs" is "vocalise", which you can read about here: [Is there terminology for vocals that do not use lyrics in certain parts?](https://music.stackexchange.com/questions/111019/is-there-terminology-for-vocals-that-do-not-use-lyrics-in-certain-parts)
Answer: The term would not be "descant"
The term you and your director are looking for is "vocable"
We use the term "vocable" to describe sounds singers make that are outside of intelligible language. Beyond "oohs" and "aahs" it would also include whoops, screams, pops, clicks, lip buzzes and any of the other thousands of sounds the human voice can make.
https://www.merriam-webster.com/dictionary/vocable
Comment: I'm not sure if I should post this as a separate question, but someone told me that a song I showed them had descant in it, or counterpoint or countermelody. It makes me associate it with a mashup because you have a second melody mixed in with the first. It was Joy to the World in 3/4 time, mixed with The First Noel.
Answer: A descant is a melody added above the main melody.  Common in festive arrangements of hymns.  Maybe this was the word he used to describe the oohs and ahs, though it doesn't specifically mean that.
I can't think of a word that exclusively means that sort of singing except 'oohs and ahs'.  Maybe 'vocalising' would cover, if not define it.
Comment: I don't think he said descant ...
Comment: Any other suggestions for 'something sounding like dest cant or something' ?
Comment: (The downvote is not from me.) Now I would agree with you that the leader might have  said descant. But I'm still searching for a term. As we say *humming* for consonants it should be **ooing** or **aaing**
Comment: This is so clearly the right answer. It explains descant, which we should assume the director used intentionally - unlike the accepted answer - and it explains _vocalise_ which is the point of the question in the title. The OP basically asked two questions.
Answer: In captioning, it is generally described as "vocalizing" or "harmonizing." Neither of these are exact definitions but they connote what's going on for a deaf viewer who is not a musicologist, especially when used in context. As used in this way, vocalizing and harmonizing are located on a continuum between singing and scatting.
Answer:
What is it called when a group of vocalists or chorus sing Ooh's oh's, ah's,

In my Gospel choir and school classes
I used the term "back ground"
back-ground voicing or back-ground singing
The typical arrangement of aah and oohs is that they are just homophone voicing the lead singer harmonizing the chords like an organ or guitar accompaniment.
(Of course will find  also polyphonic background voicing.)
Edit:
I've deleted the links provided as they haven't been corresponding to my text above. What I mean is not the same as backing voices or backup singers or also barbershop style.
I just  taught the children to sing the chords (triads) following the tune in half notes or whole notes e.g. the background voices in Hey Jude.
Maybe the term "background" has changed its meaning through the years, but that's what we have used in Swiss Jazz School in the late sixties. And I would still use it in Jazz arrangements where instruments are playing divided chord notes like the Aah and Oh in harmony of human voices.
Edit:
I thought that  distinguished to consonants like mm, hm, nn, ng this kind of vocal accompaniment  will be called vowel background.
But now here is the link with the correct answer:
BV's = BACKING VOCALS
https://www.soundonsound.com/techniques/crafting-perfect-pop-backing-vocals
Comment: That doesn't exclusively mean oohs and ahs though.
Comment: The term background singer is also used instead of backing singer.
Comment: Oohs and Aahs are probably 'background'.  But 'background' doesn't necessarily mean Oohs and Ahs.
Comment: yes, it can mean also all vocal parts responding or accompanying the lead-singer. But aahs and oohs mean surely background.

The question is related with some questions here like e.g.

https://music.stackexchange.com/questions/48369/what-is-the-anatomy-of-a-song/48386#48386
Comment: good information!
https://www.music-jobs.com/uk/jobtypes/backing-vocalist-jobs-402849.php


Logistic mixed model with 33% chance

Question: I have an experiment in which subject need to answer a discrimination task with 3 options (chance = 33%). Because the number of trials with this task varies between subjects I wanted to do mixed model paradigm.
The theory was to built 2 models in R:
one with 1 as intercept (meaning we don't define it) and one define as 33%, and compare the models with anova.
(I now that intercept of 0 is 50%, how do I define 33%?)
I couldn't define the second model.
Here is what I was trying to so (the second is just a blub and doesnt work)
m1<-glmer(success ~1+(1|subject),data=m1_m2_data,family=binomial) # the intercept is undefined
m2<-glmer((success) ~0.33 +(1|subject),data=m1_m2_data,family=binomial) #how do define chance as 33%?
Do you have any suggestions?
Comment: Is your response variable categorical with three categories (e.g. dog, cat, alligator)?
Comment: It is 3 sounds with different pitches. so it is not quite categorial
Answer: You could try working with an offset, i.e.,
m2 <- glmer(success ~ 0 + offset(rep(qlogis(0.33), len = subject)) +
                (1 | subject), data = m1_m2_data,
            family = binomial())

Comment: Hi, thanks for the answer.

I just changed the "length= subject" to "length= nrow(m1_m2_data)" because this is the number of observation, am I right?
Apart from this it works!
Comment: Yes, that is correct.

Logistic mixed model with 33% chance


Companion Lecture Notes to Atiyah-MacDonald?

Question: Is there a set of lecture notes that follow Atiyah-MacDonald and expand on the dense passages, point out typos and so forth?
Answer: You can try the following A. Altman and S. Kleiman: A term of commutative algebra, 2012.
You can read it for free here:
http://web.mit.edu/18.705/www/12Nts.pdf
Comment: Updated version: http://web.mit.edu/18.705/www/
Comment: WOW,these notes look terrific and exactly what the OP was looking for. I'm currently researching and compiling a list of free mathematics sources on the Web-I'm really glad you called attention to this jewel or I'd have missed it,Oliver!
Comment: Even more up-to-date: [2021 version](https://web.archive.org/web/20210703201703/https://www.researchgate.net/profile/Steven-Kleiman/publication/351211952_A_Term_of_Commutative_Algebra/links/608b6380458515d315e6bc21/A-Term-of-Commutative-Algebra.pdf)
Answer: Here are two links where you can find further links to downloads such as you are looking for:
http://math.berkeley.edu/~aboocher/research.html
http://people.brandeis.edu/~igusa/Courses.html
I myself was/am in the market for these. In passing I saw a mention of this book:
http://www.amazon.com/Commutative-Algebra-Mathematical-Society-Student/dp/0521646235
I have not looked at it, but it might be useful. The author is actually acknowledged in the preface to "A&M."
Answer: (Sorry, this post should really be a comment to the answer by Oliver E. Anderson, but I don't have enough reputation to be able to comment yet. Please someone re-post it as a comment instead of me. If you notify me, I'll delete this answer.)
The latest revision of the textbook by Altman and Kleiman can be found at this MO answer. Be sure to get at least the 2017 version or newer, which was a substantial expansion.


Format the results fetched by query for display

Question: I have the following MySQL query which fetches all the information I need.
SELECT biobank.*, organization_.name, biobankattributelists.*
FROM biobank INNER JOIN organization_ ON biobank.biobankDbId = organization_.organizationId
LEFT JOIN biobankattributelists ON biobank.biobankDbId=biobankattributelists.biobankDbId
WHERE ((organization_.name LIKE '%%' OR '' IS NULL)
OR (biobank.biobankId LIKE '%%' OR '' IS NULL)
OR (biobank.acronym LIKE '%%' OR '' IS NULL)
OR (biobankattributelists.attributeListName LIKE '%%' OR '' IS NULL)
OR (biobankattributelists.attributeListValue LIKE '%%' OR '' IS NULL))
AND (biobank.countryCode = '' OR '' = '')

The result is
The important columns to note here are biobankDbId, attributeListName, attributeListValue. Each biobank can have different attributeListName and each of that attributeListName has different attributeListValue. The combination of these three is unique across the result set. For eg in the rows 2 and 3; Available Documents for Biobank for Serum are Protocols/Procedures and Sample Catalogue.
Provided that I get the result like this:
Biobank results = BiobankLocalServiceUtil.searchBiobanks();
for(Biobank row:results){
 // To be done....

}

I want the result to be displayed like this for each biobank grouped by the attributeListName.
Name: Biobank For Serum

Automation Services:
Analysis

Available Documents:
Protocols/Procedures, Sample Catalogue

Complementary Services:
Biochemistry Laboratory, Pathology Department/Imaging

.....

I can probably get this done by fetching the results as it is and again making another query. But it will be inefficient to make multiple queries. Further more since I have everything needed fetched by this query I am looking for the solution either by modifying the query or perhaps in the front end say PHP/JSP to format the query result as I want it displayed.
P.S. Apologies for the small picture. It is much bigger if opened in the new tab.
Comment: I don't understand at all what you want : your query is strange : "LIKE '%%' OR '' IS NULL" '' will never be null! The language is php or java ? The answer will be totally different depending of the language. Maybe you can give the object Biobank...
Comment: And what is * OR '' = '' * supposed to do? Suggest bin this and start again!
Comment: Please assume the query to be correct. I am using Liferay Java EE portal framework, and the query is displayed slightly differently. And I use the mysql query log to run the query in sql workbench. As it is this is the empty query with no params which fetches me the result set in the picture.
Answer: Your query, generated by this Liferay thing you're using, is distractingly bizarre. But it does seem to be correct. Hopefully all those strange OR '' IS  NULL clauses don't ruin performance.
You seem to be dealing with a name/value schema in your biobankattributelists table.
Your problem here is one of formatting your result set for display. As you point out, all the information you need is in the result set. What you need to do, in your host language (Java? php? we can't tell from your question), is read the result set and construct your output.
If you can modify the query, I suggest you add this ORDER BY clause to its end.
ORDER BY organization_.name,
         biobankattributelists.attributeListName,
         biobankattributelists.attributeListValue

You want this so the rows of the result set will appear in the order you need them to construct your output.
Then you want to implement, in your host program, what report writing people call control break logic. That is, you want to do something special each time the value of a column changes from its previous value.  For example, each time the organization name changes, you want to display the new organization name.
With respect, it's beyond the scope of a SO answer to teach you to do that.


dd stderr output CR ( ^M / 0xD ) at the end of the lines

Question: I try to log dd's output to a file. For example:

dd if=/dev/sdc of=/dev/null status=progress 2> output.log

Then when I try to open output.log with a vim, I see one long line and ^M sign where newline should be.
2086523392 bytes (2,1 GB, 1,9 GiB) copied, 5 s, 417 MB/s^M2497234432 bytes (2,5 GB, 2,3 GiB) copied, 6 s, 416 MB/s^M

I can properly view output.log in vim only doing search&replace :%s/\%x0D/\r/g, or this :e ++ff=mac
It seems that dd uses mac's CR symbol in output for line break, instead of unix's LF. Why?
Comment: Well, I'm on a Mac and I get Line Feeds. Maybe we can swap our machines?
Answer: CR stands for "carriage return". That implies moving a carriage of your "typewriter" all the way to the left without scrolling "a sheet of paper". In other words, it works as "home" key when program outputs text on terminal. So every new "progress output" erases the previous one. Of course, it only works like that in terminal, not when redirected to file. Quite probably, you are not supposed to have status=progress and redirection at the same time.


sort key value pairs in Google Script

Question: I have the below script running on a google sheet to automatically send an email with the sheet info to a specific emails. It is working perfectly but I am trying to optimize it. The problem I am having is every-time the email is sent the order of the text (Key value pairs) is different I am trying to order the key value pair based on the way they are in the email.
    function onFormSubmit(e) {
  var values = e.namedValues;
  var sendFrom = '';
  var ccEmail = '';
  var subject = '';
  var htmlBody = '
';
  for (Key in values) {
    var label = Key;
    var data = values[Key];
    htmlBody += '
' + label + ": " + data + '
';
  };
  htmlBody += '
';
  MailApp.sendEmail(sendFrom, subject, htmlBody, {
    htmlBody: htmlBody,
    cc: ccEmail,
    name: 'Automated Email',
    noReply: true

  });
}

Thank you for help in advance
Comment: can you show log of `values`also can you share form please?
Comment: I guess you mean you are trying to order them based on the way they are in the sheet? You said based on how they are in the email but is that a typo?
Comment: Yes you are right
Answer: You can access just the values (in correct order) with e.values, then dynamically create the "keys" by accessing the header row from the destination 'Form Responses' sheet:
function onFormSubmit(e) {

  var values = e.values;
  var vlen = values.length;
//get headers from response sheet (i.e. form questions)
  var keys= SpreadsheetApp.getActive().getRange('Form Responses 1!A1:1').getValues()[0];
  var i;
  var htmlBody = '
';

  for (i=0;i<vlen;i++) {

    var label = keys[i];
    var data = values[i];
    htmlBody += '
' + label + ": " + data + '
';

  };

  htmlBody += '
';
/mail part etc.]

This way any edits the the questions in the form won't break your code.
Answer: A key value pair doesn't maintain order. So, you should create an array of keys to maintain the order instead, then iterate the array to retrieve each item in values.
example
  var orderedKeys = ['firstName', 'lastName', 'email', 'phone']

Then in your function, instead of iterating on values, you iterate on orderedKeys instead.
  for (var key of orderedKeys) {
    var data = values[Key];
    htmlBody += '
' + key + ": " + data + '
';
  }

sort key value pairs in Google Script


How do I get the highest `field_id` value that exists in content of a specific type?

Question: I have a content type which, among other things, have a field which contains a unique ID number (this number is used to connect the individual content to related information stored on paper).
When creating new entries I'd like to automatically generate this ID by finding the highest ID already present in the system, and calculating the next ID from that.
I have written a small module (using hook_menu()) which presents the user an interface for adding new content. How can I, from within this module, get the  field_id values of my already existing content? (So that I can calculate which ID a new entry should have?)
Is there any PHP command which can be made to return an array containing all the field_ids from my content type?

Worth to know here is that the system is kinda small (500–1000 entries of my content type, at most). There will also only be a single person entering data at a time. Also, I'm using Drupal 7.
Answer: The easiest sulotion I can think about is to use Computed field module and the id field will be computed field.
Then,  in the field read the last value using variable_get() and then update that value using variable_set().
Comment: Your answer led me in the right direction. – I ended up using `variable_get()` to set a `#default_value` in the render array for my form. (Though there was no need for the Computed field module.)
Comment: Great! You are right there is no need in computed field :)


Trying to get an ubuntu headless server to call home

Question: I would like to install PPTP on my remote ubuntu server, so that it will connect back to the main office, so that backups, and and also data transfer can take place.
Can anyone suggest a good guide for getting an ubuntu headless server, (or any linux for that matter) dialing PPTP on bootup
Answer: How about trying this: https://help.ubuntu.com/community/VPNClient#Manually%20configuring%20your%20connection
Answer: Not PPTP related: If you can use OpenVPN, it's support on Ubuntu is excellent. Just edit /etc/default/openvpn to default some OpenVPN tunnels to auto-start on boot. On the client configuration, use some passphrase-less certificate and keys, so OpenVPN does not stop asking for a passphrase.
Alternatively, on the PPTP side of things, investigate using /etc/network/interfaces, to define
<code> auto callhome
 iface callhome inet ppp
 provider callhomeprovider
</code>
This creates a "callhome" pseudo interface, that is auto-brought-up on boot, that in turn calls ppp's /etc/ppp/peers/callhomeprovider config-file. This does not require any graphical clients. For configuring that, check out the standard PPTP-client's docs.
Comment: I will try this and get back to you as soon as I can, thank you for the tip.
Answer: On the page here: http://pptpclient.sourceforge.net/howto-ubuntu.phtml there's a section labeled "Configuration, by hand."  This includes CLI directions for the PPTP client.
Answer: Install Ubuntu Server and the pptpd package which is a pptp server listening for connections. Then you can use windows vpn client and the linux pppoeconf or kppp to connect to your server. You can use this guide: http://poptop.sourceforge.net/dox/debian-howto.phtml , which is a guide for Debian, but works on Ubuntu.
Comment: OP is asking for client, now server :)
Answer: For a headless/non-gui setup install and configure wvdial to call home and add wvdial to the bottom of /etc/rc.local as a background process to have it start on bootup.
Comment: looking into wvdial - it seems that this is used to dial the modem? The system is already has Internet connectivity, and just needs to connect to our vpn server.


Possible to enumerate what has been web-deployed to an IIS server?

Question: Is there some way, e.g. through WMI, that I can query a box running IIS what web applications has been deployed to it using web-deploy?
Thanks in advance.
Answer: You can use web-deploy to -sync -whatif the whole server against a "standard" one, and that'll show you a list of differences.
If the Event Log shows Web Deploy deployments (does it?), and WMI can query the event logs, that might be more the level of detail you're looking for?
Comment: Thanks for your feedback. Actually, what I'm after is not a delta of what's been installed since a given time, or in a given time interval, but a snap shot of what web applications are, right now, installed on the IIS server.
Answer: You did not mention what version of IIS, but have you checked out the MSDN documentation on managing IIS via WMI?


How can I tell Drupal to add autocomplete=off to the login form

Question: I'm under pressure to close out some issues from a Qualys scan. One issue flagged was

150112 Sensitive form field has not disabled autocomplete

Suggestions include adding autocomplete="off" to the username and password fields.
What would be the best practice way to achieve this?
Comment: Any luck with the No Autocomplete module? Are you experiencing other issues?
Answer: It seems there is a module for this, No Autocomplete.
As a sidenote (copied from the module's page:

However, browsers and password managers and the like may very well not
  respect the "autocomplete=off" attribute anyway. For example, Chrome
  seems no longer to respect it and Lastpass ignores it by default.

Well, good luck with Qualys!
Comment: I wouldn't be scared off, it's a tiny module, code-wise. Basically implements a form alter call to add an extra attribute: $form['#attributes']['autocomplete'] = 'off';
Comment: This looks promising but should I be scared off by the maintenance status? `Maintenance status: Seeking new maintainer. Development status: Maintenance fixes only`
Comment: Did you get a chance to try this out?
Answer: Use hook_form_alter() in a Drupal module:
function hook_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['pass']['#attributes']['autocomplete'] = 'off';
  }
}

Or use jQuery:
$('#edit-password').attr('autocomplete', 'off');

Answer: You can set the attribute autocomplete='off' in username and password field of login page hook_form_alter()

Tested on Drupal 8 using hook_form_alter()

function hook_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_form') {
    $form['name']['#attributes']['autocomplete'] = 'off';
    $form['pass']['#attributes']['autocomplete'] = 'off';
  }
}


Erro na validação de formulário em JavaScript

Question: Estou com um erro de validação, quando aperto no botão input de submit ele não testa a function do JavaScript e vai logo para onde o action está mandando ir.

<TITLE>Cadastro</title>

<form name="form_cadastro" action="salvar_aluno.php" method="get">

                Nome completo

                <input type="text" name="NOME">

                Nome de Usuario

                <input type="text" name="NOMEUSUARIO">

                RM

                <input type="text" name="RM">

                SENHA

                <input type="password" name="SENHA">

        <input type="submit" name="botao_comando" value="CADASTRAR" onclick="return validaFormCadastro()">
</form>

Comment: Rapaz, sua função está sendo carregada, tanto em um arquivo que criei para testar, quanto nesse JsFiddle: http://jsfiddle.net/SamirChaves/asd7ddt3/1/ , teste e veja se este é realmente seu problema
Comment: Tente trocar o `d = document.form_cadastro` por `d = document.forms.id_form_cadastro`, no caso, seria um id, não o nome.
Comment: O teu formulário possui um input `type="submit"`, logo vai ignorar o js existente, e proceder com o envio do formulário. Uma das soluções seria colocar um substituir o evento `onclick` desse botão, por um `onblur`.
Comment: Aqui funcionou normalmente, provavelmente é algum outro script que está com erro e o resto do javascript não processa.
Answer: A solução é na chamada do método validaFormCadastro() voce adicionar o event.preventDefault(); para voltar o estado original. Tente assim:

    <input type="submit" name="botao_comando" value="CADASTRAR" onclick="validaFormCadastro(this)">


Register User with Services (JSON) with Custom Fields

Question: I am trying to register a new user on Drupal7 via services with JSON. Actually I am posting info from JAVA (android) with JSON format to the server with services module enabled. A sample successful JSON post is:
    {
    "name": "erfan",
    "pass": "1234",
    "mail": "firstname.lastname@example.com",
    "status": "1"
     }

URL: [siteURL]/[endpoint]/user/register

I was successful creating users with basic info such as name,email,status.
I have added custom fields like field_address, field_phone, etc to the web site and want to send them via JSON to the server.
The problem is I can not figure out how to post these data to the server and couldn't find any documentation about it. My trial and error approach was not successful too, because I am not good in PHP coding. So please help me. Thanks.
Comment: Could you edit the question and add one of the attempts? It'll be a bit easier to advise once we've seen the code. Entity fields are structured like `$account->field_name[$language][$delta][$column_name]` if that helps. An example for a text field might be `$account->field_foo[LANGUAGE_NONE][0]['value']`
Comment: I added more details about my problem. I am not a PHP expert. :)
Answer: Hope this will help you,
In Drupal 7 you can use the below JSON format to add custom fields(field_user_image)
{
    "name": "test",
    "pass": "password",
    "mail": "firstname.lastname@example.com",
    "field_user_image": {
        "und": [{
            "fid": "2"
        }]
    }
}

I have tried in my local and it is working fine.

Created new field UUID

Calling the Service using Firefox poster add-on

Code

  {
    "name": "testuser123",
    "pass": "testuser123",
    "mail": "firstname.lastname@example.com",
    "field_register_uuid":
      { "und":
        [{
          "value": "65C7DCA4-8F03-473C-9E8F-08B3F29E91AE"
        }]
      }
  }

I can able to create new user with the custom field
References

How do I POST a new node using the Services module?
Services module. How to construct the JSON data with session info for creating node?
Comment: This doesn't seem to work. I'm using UUID Field, and want to create a user with a UUID, which is just a text field, really. { "name": "test", "pass": "password", "mail": "email@example.com", "field_uuid": { "und": [{ "uuid_field": "65C7DCA4-8F03-473C-9E8F-08B3F29E91AE" }] }} https://www.drupal.org/sandbox/Mile23/1326218
Comment: I have updated my answer.
Comment: Thanks. But nope. :-) I suppose it's something to do with the way authentication is happening, or some other configuration problem.
Comment: I discovered I can create the user and then use PUT to update the field. The JSON above is correct, but it has to be a 2-step process. https://www.drupal.org/node/790416
Answer: This should be a comment, but I haven't enough reputation ...
When you create a user, you can only pass the fields that are shown in the registration form. Otherwise you'll need first to register the user and then update it with the new fields, as @paul-m said in his comment.
To show a field in the registration form go to

configuration->people->account settings-> manage fields
  click the edit
  link of the desired field and check "Display on user registration
  form."
Comment: Hi and welcome to Drupal Answers. Your answer in fact does contribute to the original question, so I would recommend you to re-format it and improve it.
Comment: At the time of writing this answer probably it was not possible to update custom fields in one go, but now https://drupal.stackexchange.com/a/156404/11058 answer works for me.
Answer: The field value may have to be "flattened" in order for the user registration to work. In the example below, the field is a List (text) field with radio buttons for the widget.

POST ?q=[my-endpoint]/user/register.json
Content-Type: application/json

JSON data to POST:
{
  "name":"bob",
  "mail":"email@example.com",
  "conf_mail":"firstname.lastname@example.com",
  "pass":"secret",
  "pass2":"secret",
  "field_choices":"2"
}

This also works for radio buttons:
"field_choices":{"und":"a"}

However, when we use a select list widget on this same field, the JSON is formed like this:
"field_choices":{"und":[{"value":"2"}]}

The JSON above will not work for radio buttons, you'll get a 406 - Not Acceptable An illegal choice has been detected. Please contact the site administrator. This is a lesson and reminder that the Services module can sometimes be dependant on your field's widget when it comes to the JSON it expects.
Comment: @Smalution Yes, use this hook: `hook_services_request_postprocess_alter()` - http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x
Comment: is it possible to modify the response. {
    "uid": "9",
    "uri": "http://example.com/food_api/user/9"
}


Laravel Jobs (Queue) do not worked

Question: I have a problem with one of my Jobs laravel. (This is the first time that i exepect this problem, i have anothers jobs who is working without problems...)
I have a listener who dispatch a job when one model is updating, so :

One model observer (Working)
One event launch by observer (Working)
One listener who listen the previous event (Working)
One Job who is dispatch by the listener (Not working ...)

The job is executed but he go to failed jobs in my database with error "ErrorException: Undefined variable: ...." ...
It is very strange because all the variable was defined, and why does it work once in two?
If someone have an idea about that, i will take it :D
Thanks in advance!
Code of the Job :
<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\Transaction;
use App\Repositories\TransactionRepository;
use App\Repositories\InvoiceModelRepository;
use App\Repositories\BalanceRepository;
use Scheme;
use Log;
use Config;
use App\Helpers\HelperNumber;
use Symfony\Component\Console\Output\ConsoleOutput;

/*
    sudo apt-get install supervisor
    https://laravel.com/docs/5.4/queues#supervisor-configuration
    php artisan queue:work --queue compute_fees --retry_after 30 --timeout 30
*/
class ComputeFees implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $id;

    /**
     * Create a new job instance.
     *
     * @param int $id
     * @return void
     */
    public function __construct($id)
    {
        $this->id = $id;
    }

    /**
     * Get the best match of invoice models
     *
     * @param \App\Models\Transaction $transaction
     * @return \App\Models\InvoiceModel
     */
     private function getFees($transaction) {
         $invoiceModelRepository = new InvoiceModelRepository();

         //Get the fees for this site and payment type (And country if needed)
         $params = [
             'sites_id' => $transaction->site->id
         ];

          return $params;
     }

    /**
     * Execute the job.
     *
     * @return boolean
     */
    public function handle()
    {
        $output = new ConsoleOutput();

        //Init repos
        $transactionRepository = new TransactionRepository();
        $balanceRepository = new BalanceRepository();

        //Get the transaction
        $transaction = $transactionRepository->getBy(['id' => $this->id]);

        $output->writeln('tx : '.$transaction->id);

        return true;
    }
}

The complete exception :
ErrorException: Undefined variable: transaction in /var/www/testproject/app/Jobs/ComputeFees.php:53
Stack trace:
#0 /var/www/testproject/app/Jobs/ComputeFees.php(53): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Undefined varia...', '/var/www/test....', 53, Array)
#1 /var/www/testproject/app/Jobs/ComputeFees.php(106): App\Jobs\ComputeFees->getFees()
#2 [internal function]: App\Jobs\ComputeFees->handle()
#3 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#4 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#5 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#6 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/Container.php(580): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#7 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container->call(Array)
#8 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Bus\Dispatcher->Illuminate\Bus\{closure}(Object(App\Jobs\ComputeFees))
#9 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(App\Jobs\ComputeFees))
#10 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#11 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(413): Illuminate\Bus\Dispatcher->dispatchNow(Object(App\Jobs\ComputeFees), false)
#12 /var/www/testproject/app/Listeners/ComputeFees.php(36): dispatch_now(Object(App\Jobs\ComputeFees))
#13 [internal function]: App\Listeners\ComputeFees->handle(Object(App\Events\TransactionChangeState))
#14 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Events/CallQueuedListener.php(86): call_user_func_array(Array, Array)
#15 [internal function]: Illuminate\Events\CallQueuedListener->handle(Object(Illuminate\Foundation\Application))
#16 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#17 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#18 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#19 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/Container.php(580): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#20 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container->call(Array)
#21 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Bus\Dispatcher->Illuminate\Bus\{closure}(Object(Illuminate\Events\CallQueuedListener))
#22 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Events\CallQueuedListener))
#23 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#24 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(49): Illuminate\Bus\Dispatcher->dispatchNow(Object(Illuminate\Events\CallQueuedListener), false)
#25 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(86): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\DatabaseJob), Array)
#26 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(327): Illuminate\Queue\Jobs\Job->fire()
#27 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(277): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))
#28 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(118): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))
#29 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(102): Illuminate\Queue\Worker->daemon('database', 'default', Object(Illuminate\Queue\WorkerOptions))
#30 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(86): Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default')
#31 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#32 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#33 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#34 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#35 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Container/Container.php(580): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#36 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
#37 /var/www/testproject/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#38 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#39 /var/www/testproject/vendor/symfony/console/Application.php(908): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#40 /var/www/testproject/vendor/symfony/console/Application.php(269): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#41 /var/www/testproject/vendor/symfony/console/Application.php(145): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#42 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Console/Application.php(90): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#43 /var/www/testproject/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#44 /var/www/testproject/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#45 {main}

Comment: We can't really help without seeing the relevant code and the full error message, but  to be honest the message seems clear enough, you're trying to access a variable that hasn't been defined.
Comment: Dunno since we can't see your code, the inputs that are being sent or anything else.
Comment: Did you change something on your code before posting it? **If not**: you should restart your worker. **If yes**, based on the log, at the line 106 you call `getFees()` and then you get `Undefined variable: transaction` in that method
Comment: Yes but why it is working sometimes ?
Comment: Post the line where the undefined variable is and all the code for the job
Comment: Hi, Please find the code and the complete error ... and now the job always go to failed jobs...
Answer: I found the problem, you always need to restart the queue when you done a modification in your job ...
So execute : php artisan queue:restart each time that you edit your job.

Laravel Jobs (Queue) do not worked


Accessing Localhost Port Over a Local Network

Question: Both localhost and 192.168.0.199 both resolve to the same page in my web browser (they both redirect to localhost/xampp/ and 192.168.0.199/xampp/ respectively).
But when I try not to access my web service, localhost:49973/BaseballWebService/Service.asmx/ resolves the web service and 192.168.0.199:49973/BaseballWebService/Service.asmx/  cannot find the webservice.
I have to access my web service using my computers ip instead of localhost because I have to access the we service remotely over a local network.  Anyone have an idea what could be going wrong?
Comment: Could XAMPP be interfering with my web service port?   The web service is launched from Visual Studio and is C# .NET?
Answer: Make sure that you aren't using 2 sites instead of 1.  It's possible that you have 2 different sites that both have a /xampp folder but don't both have the BaseballWebService folder.
If a single site has both localhost (or 127.0.0.1) and 184.108.40.206 bindings then it must be something causing a redirect in the BaseballWebService folder.  A good test is to create a test.txt or test.htm page and place it in your BaseballWebService folder to confirm that IIS is serving up that file correctly without redirecting.
I'm assuming that you're using IIS since you've tagged this as IIS.
Comment: I found my answer here: http://weblogs.asp.net/ryangaraygay/archive/2008/04/19/asp-net-development-server-cannot-be-accessed-using-non-localhost-url.aspx .  On development server localhost access only, no ip access.  So I need to fire up IIS.
Comment: Thanks a lot Scott!  I am not sure I am using IIS. I think it is the ASP.NET development server 9.0. I uninstalled XAMPP and now when I go to localhost/ I get the message: Forbidden You don't have permission to access / on this server. Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request. But I can view my web service at localhost:49973/BaseballWebService/Service.asmx/…
Comment: Good find. Glad you were able to track it down.  As a side, you can set IIS sites for debugging in Visual Studio/Visual Web Developer.  Edit the properties of the project to tie to the IIS site.


como mudar a cor em cada selectitem de um selectOneRadio jsf

Question: tenho um selectOneRadio que tem 3 opções : Acabamento, embargo e Expedição
<h:selectOneRadio value="#{solicitacaoImpressaoBean.entrega.tipoGuia}" class="tipoGuia" >
                        <f:selectItem itemValue="Acabamento" itemLabel="Acabamento" />
                        <f:selectItem itemValue="Embargo" itemLabel="Embargo" />
                        <f:selectItem itemValue="Expedicao" itemLabel="Expedição"/>
    </h:selectOneRadio>

Quero colocar no primeiro a cor preto, no segundo a cor azul e no terceiro a cor verde.
tentei com css a seguinte maneira:
.tipoGuia tr:nth-child(1) td label   {
    color : black
 }
.tipoGuia tr:nth-child(2) td label   {
   color : blue
}
.tipoGuia tr:nth-child(3) td label   {
   color : green;

}

mas não funcionou. alguém tem ideia de como fazer isso? grato.
Consegui assim:
.tipoGuia tr td:nth-of-type(1){
    color : black;
}
.tipoGuia tr td:nth-of-type(2){
    color : blue;
}
.tipoGuia tr td:nth-of-type(3){
    color : green;
}

Answer: Quando precisei fazer algo parecido fiz da seguinte forma:
peguei o seu código como exemplo, para testá-lo aqui, usei styleClass, mas pode usar somente class também
<h:selectOneRadio styleClass="tipoGuia">
             <f:selectItem itemValue="Acabamento" itemLabel="Acabamento"/>
             <f:selectItem itemValue="Embargo" itemLabel="Embargo" />
             <f:selectItem itemValue="Expedicao" itemLabel="Expedição"  >
             </f:selectItem>
</h:selectOneRadio>

O que você precisa fazer é pegar o valor definido no itemValue e levar para o css, da seguinte forma:
.tipoGuia
    input[value="Acabamento"] + label {color:black}
.tipoGuia
    input[value="Embargo"] + label {color:blue}
.tipoGuia
    input[value="Expedicao"] + label {color:green}

Se você observar, quando inspecionamos os itens do select no navegador, ele sempre nos mostra um
Acabamento

com os dados de cada item inspecionado.
Comment: Consegui assim:

    .tipoGuia tr td:nth-of-type(1){
     color : black;
    }
    .tipoGuia tr td:nth-of-type(2){
     color : blue;
    }
    .tipoGuia tr td:nth-of-type(3){
        color : green;
    }
Answer: Consegui assim:
.tipoGuia tr td:nth-of-type(1){
    color : black;
}
.tipoGuia tr td:nth-of-type(2){
    color : blue;
}
.tipoGuia tr td:nth-of-type(3){
    color : green;
}


How does one expression factor into the other?

Question: How does $$(k+1)(k^2+2k)(3k+5)$$ factor into $$(k)(k^2-1)(3k+2) + 12k(k+1)^2$$
Comment: I don't understand the question. Do you ask how to get to this result, or how it is possible to have several different factorisation, or if the two factorisation are really equal?
Comment: Is the second expression really factored?
Comment: How are these two factorizations equal @Martigan? I cannot see how I get from the LHS to the RHS.
Answer: Both terms are equal to $(3k + 5)(k + 2)(k + 1)k$, because
$$
k(k^2-1)(3k+2)+12k(k+1)^2= k(3k^3 + 14k^2 + 21k + 10)=(3k + 5)(k + 2)(k + 1)k.
$$
Comment: Since $k=-2$ is a root of $3k^2+11k+10$ you do polynomial division $(3k^2+11k+10)$ by $(k+2)$, which gives you $3k+5$.
Comment: How does $(3k+10)(k+1)$ factor into $(3k+5)(k+2)$?
Comment: It does not ! Take $k=-1$, then the LHS is zero, but the RHS is nonzero.
Comment: Oops. Thanks for that.
Comment: How do I factor $3k^2 + 11k + 10$?!
Answer: Well, $RHS=k(k^2-1)(3k+2) + 12k(k+1)^2 = k(k+1)((k-1)(3k+2)+12(k+1))=k(k+1)(3k^2+2k-3k-2+12k+12)=k(k+1)(3k^2+11k+10)=k(k+1)(k+2)(3k+5)=LHS$


How to create an ASP.NET route that redirects to a path that uses part of the route?

Question: I want to create a route that redirects all requests matching certain pattern to a location built using parts of the pattern. I want to grab some segment in the URL and treat the rest like a path to an aspx page in Web Forms application. For example
RouteTable.Routes.MapPageRoute("SomeRouteName", "{something}/{*path}", "~/pages/{*path}/Default.aspx");

Where *path could be something contain "\". The query string should be preserved as a query string.
Is it possible to create souch a route?
Answer: I don't know of any way to do it that way.
The more standard way would be to set the target as "~/pages/default.aspx" and then have that page check for the {path} argument and display the corresponding data.
If you really want it in another path, then don't use a {} placeholder. Simply hard code that section of the path (both the source and target).
Comment: The second solution would require hardcoding paths for many existing pages and I was hoping to avoid the first solution. Also there seems to be a way to pass in a route handler class that allows handling the routing with code but I was hoping for more clean solution.
Comment: @Stilgar: AFAIC, `MapPageRoute()` is primarily designed for cases where path elements represent information that is used to retrieve the target content, usually from a database. To the best of my knowledge, it simply wasn't designed to do what you want. If you have a lot of paths, then handling the route with code may be your best solution.
Answer: After looking at several ways to do this I ended up creating my own routing handler that is something like this:
public class SomethingRoutingHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        string something = (string)requestContext.RouteData.Values["something"];
        string path = (string)requestContext.RouteData.Values["path"];

        string virtualPath = "~/" + path + "Default.aspx";

        return BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(Page)) as Page;
    }
}

I then use the RouteData in the pages to access something. I found these articles helpful:
http://msdn.microsoft.com/en-us/magazine/dd347546.aspx
http://www.xdevsoftware.com/blog/post/Default-Route-in-ASPNET-4-URL-Routing.aspx


Alignment issues with spans

Question: Why does the followin HTML yield the *asdf aligned to the bottom of its parent div?

<input type='text' style='width: 40px'/>

*asdf

Sorry about the bad jsfiddle links, I havn't tried to share it before:
http://jsfiddle.net/IdeaHat/y7tLZ/
Comment: If your input is the same width as the parent, it will push everything else down. Naming the class "div" for a span is confusing...
Comment: What exactly are you trying to achieve?
Comment: @helion3 Yeah sorry about that have been playing around with it, i'll change it. However, it still "pushes everything down" if width is set to 40 for the text box.
Comment: @Karl right now, I'm trying to get that text to be centered. I did it with margins a while ago, but now this weird lower align happened.
Comment: @Paulie_D http://jsfiddle.net/IdeaHat/62AZh/
Comment: Your HTML is not valid! Please fix it.
Answer: This is because the default value of the vertical-align property on your span tag is not set, so it is defaulting to "baseline".
Answer: Please try with the below code snippet.
HTML

     <input type='text' style='width: 40px'/>

    *asdf

CSS
.tag_editor
    {
    float: none;
    width: 400px;
    height: 33px;
    border-style: solid;
    border-color: #B2B2B2;
    border-width: thin;
    display: inline-block;
    overflow: hidden;
    }

jsfiddle Demo
Comment: Hey, that does work. Makes sense with the default verical-align==basline
Comment: The question was "why does this happen" and not "how do I top align it"!
Comment: I do not have exact idea but as per my experience when we set height in textbox and button at that time one of them increase the height at the bottom/one side and another one increase the height at the top and bottom side both. In short all controls are not increases their height in same manner. That's why..

Alignment issues with spans


Highest number of own-goals scored in a game for both teams in football

Question: What is the highest number of own-goals scored in a football game for both teams combined, excluding:

Stade Olympique de L'Emyrne(SOL)'s 149 deliberate own-goals against AS Adema.
Indonesian side PSS Sleman beating PSIS Semarang 3-2 all of them being deliberate own-goals as well.

Biggest one I have found so far is Catania's 4 own-goals when losing 5-0 to Internazionale (Inter Milan) making combined 4 own-goals (Source). Youtube link.
Comment: Google doesn't find the answer to your question? It is amazing that your question is 1 month old and it got only 39 views and no comments at all except this one. I am placing a bounty of 100 of my own reputations to attract more viewers and answerers.
Answer: A deep Internet search didn't point to any match where 4 or more undeliberate own goals were scored in a single game, except Catania's 4 own-goals for Internazionale that was already mentioned in the question.

But the interesting one that I did find is during Nigeria Nation Wide League Division 3 play-offs, 2 scandalous matches ended with insane scores:

Plateau United Feeders 79 - 0 Akurba FC
Police Machine FC 67 - 0 Bubayaro FC

According to BBC:

A journalist who saw Bubayaro's defeat against Police Machine, and who
  asked not to be identified in order to protect his own safety, told
  BBC Sport: "In the second half, we started witnessing outrageous own
  goals, free-kicks and terrible goalkeeping.

Telegraph reports that one player alone has scored 3 own goals in the fixed match:

It was embarrassing that in one of the games, a player scored 11 times
  while in the other, four goals were scored within a minute and a
  player scored three own-goals in a match.

This player was identified by Gulf News as the captain of Akurba FC:

The NFF [Nigerian Football Federation] named 28 players as goal scorers — and own goal scorers —
  in the two games, responsible for a scarcely-believable 146 goals.
Akurba captain Anjide Said Timothy was identified by the NFF as one of
  the organisers of the "scandalous" results. He scored three own goals
  in Akurba's huge loss, the NFF said.

According to this article:

By half-time, Plateau United were 7-0 up, while Police Machine were
  leading by 6 goals to nil. However, things quickly got out of hand, as
  both teams' opponents began to put the ball into their own net
  following the break, with the games eventually ending 79-0 and 67-0
  respectively, earning Plateau United promotion.

As a result, players and officials of clubs involved in two Nigerian promotion play-off games have been banned for life. The four clubs have been banned from the game for 10 years. Unfortunately, none of the articles reveal the exact number of own goals, but we can guess that there were a lot.


"Already defined in object file" and "one or more multiply defined symbols found"

Question: Going through the RPC tutorial at MSDN,
I have just created a project with two .c files as following::
/* file hellop.c */
#include <stdio.h>
#include <windows.h>

void HelloProc(char * pszString)
{
    printf("%s\n", pszString);
    return ;
}

and
/* file: hello.c */
#include "hellop.c"

void main(void)
{
    char * pszString = "Hello, World";
    HelloProc(pszString);
    return ;
}

Problem:: Error LNK2005 and fatal Error LNK1169
Why and where is the compiler seeing the multiple symbol definition or declaration of HelloProc(char*) ?
EDIT:: As concluded in this SO_Question, including .h file is the best solution obviously. But does that leave us with no implementation of design where we can include a .c file into another .c file?
Weird Behavior:: First time compilation runs fine but rebuild of solution breaks with the above mentioned errors. You can check the multiple first time compilation by changing the file name from .c to .cpp and vice-versa. Why does it exhibit this behavior? (I am not sure if anybody else have also experienced this with the given example)
Answer: You compiling HelloProc twice, as you include the whole definition of of this function in hello.c file by #include "hellop.c", while you only need declaration of it. You should put function prototype in header file.
     #ifndef HELLOP_H
     #define HELLOP_H

     #include <stdio.h>
     #include <windows.h>

     void HelloProc(char * pszString);

     #endif

And include header file both in hellop.c and in hello.c
Edit: #include is not cut-paste as you said, it is more copy-paste

# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the
  source file identified by the specified sequence between the "
  delimiters

so you get to linkage with two definitions of HelloProc one in hellop.c and another one in hello.c. Another way to solve it is to compile only hello.c file, this way there is no duplicate of HelloProc. See how to do it in VisualStudio here
Comment: Appreciate your answer but I don't think that is the issue here. Also, I don't have any "main.c" file, it is "hello.c" :-) . And yet again, I know, putting the declaration in a header file would be great but I want to know as what is the reason behind this. "#include" is just like cut-paste thing (roughly saying), then this error should not have occurred.
Comment: @Abhineet i checked on my machine exactly as i expected : /home/davidbo/workarea/workspace/test/Debug/../hellop.c:4: multiple definition of `HelloProc'
Comment: Where can you see the two definitions of HelloProc? And as you have stated, #include would work like copy-paste, so the whole "hellop.c" will be replaced in hello.c and would be compiled. And in any case, I have already tried guards (they are the first ones to try whenever I am hit with LNK2005), but doesn't seems to work.
Comment: So, does the guards help? :-)
Comment: so include is copy-paste, meaning at linkage you have two definitions of `HelloProc` one in hellop.obj here it compiled for the first time, and in hello.obj here you get another definition of same function. So it compiled twice, and now it is trying to link `HelloProc` twice.
Comment: i found this [this](http://stackoverflow.com/a/672785/2549281) answer on similar question with an explanation much better then mine :) . Looks like you have no choice but to add header file.
Comment: So, it means, there is no way to include .c files into another .c file?
Comment: @Abhineet There is, but then you have to build only `hello.c` file
Comment: And, how would I do that? Also, do you experienced that, the given example builds perfectly the first time it is compiled and then breaks on "rebuild" ???
Comment: +1 for your solution. But I am not accepting it for now because I still have some doubts. :-) thanks for the long discussion and your patience to keep up with my never-ending doubts :-)
Comment: I'm on linux with gcc compiler, i got the error message directly at first build. I guess there some Microsoft workarounds so you get errors only at rebuild


distance metric for student course schedules

Question: I'm doing an exploratory clustering analysis of student course schedules at a college.  Interpretability by humans is paramount: we're trying to inform future research questions and possibly scheduling decisions.  Success for this project would include observations like "many students take classes only on Monday/Wednesday" or "hey, look, there are a bunch of students who take morning classes at the Springfield campus and go over to the Franklin campus in the afternoon".
For each student, for each class the student took, I have the start time, end time, days of the week, and campus.  I'm working with data from a single semester.
As a first pass, I'm doing agglomerative clustering in sklearn and exploring the dendrogram by hand.  The hard part so far is the question I'm posting here: what would be a reasonable distance metric between two students based on their course schedules?
My first attempt was to divide the week into 30-minute intervals and assign each student a 1 for every slot where the student was in class and a 0 elsewhere.  For example, a student with a morning MW class, an afternoon TR class, and a Friday seminar would look like this:

Then I can compute the overlap between two course schedules using the Jaccard distance. But I'm not fully satisfied with this approach:

Non-overlapping classes are all equally dissimilar.  A class that starts at 9:00 is just as different from one that starts at 11:00 as it is from one that starts at 16:00.
There's no "bonus" for classes at the same time on different days, or for classes at different times on the same day.
It's not obvious how to extend this to include online classes (although I suppose I could make a new "day" just for online classes) or the campus where the class was located.
Answer: The problem with clustering in this context is that these methods usually assume that:

All students are typical, i.e., mustnbelong to one of the clusters
Each student exhibits exactly one behavior

I doubt that these implicit assumptions are beneficial.
Instead, consider a frequent itemset mining and association rule mining approach, to find patterns such as "takes classes on Monday morning => takes classes on Tuesday morning".
This is beneficial because students may behave non-standard, and may combine multiple typical behaviors. But it also comes with challenges, such as removing trivial patterns, and filtering out the actual interesting patterns.
Comment: Thanks; frequent itemset mining does look like a better approach.  I assume each "item" would need to be a single course, or possibly course meeting, right?  In that case, is there a version of this approach that allows items to have features (e.g., "Monday" or "9:00") that it can use in constructing rules, instead of treating each item as an atom?
Comment: Make Monday an item and 9am another item?
Comment: That sounds good for a single class, but if the student is taking multiple classes, I think that would lead to ambiguity.  {"Monday", "9:00", "Tuesday", "11:00"} is compatible with a 9:00 Monday class plus an 11:00 Tuesday class, and vice versa.  All the examples of frequent itemset mining I've seen so far use the "market basket" analogy; do actual retailers use this kind of analysis?  And if they do, how do they deal with, e.g., different brands of bread or flavors of ice cream?
Comment: If you want to detect patterns such as "always at 9" you'll need this ambiguity. You can add overlapping symbols, but you'll then need to ignore trivial rules such as "Monday + at9 => Monday-9".
Comment: This rule induction approach is reminding me of similar algorithms from theoretical linguistics (e.g., the [Minimal Generalization Learner](http://www.mit.edu/~albright/mgl/) or [MaxEnt](http://roa.rutgers.edu/files/858-0806/858-HAYES-0-0.PDF)).  They explicitly treat sounds as bundles of features rather than atoms, which would be useful here.  But in other ways their architecture doesn't quite work for this particular problem.
Comment: MaxEnt etc. need sequences to make sense, as they model state transitions. There is a relationship but it is fairly universal to all probabilistic approaches.


Adding default option to ng-if

Question: In my dropdown menu, there are two options- small and large. When small is selected, a picture shows up; when large is selected, another picture shows up. I want to add a default picture for when nothing is selected (example. page just loaded). But my code below isn't working.
AngularJS, inside controller:
var urls = {
    '': '/images/Default.png', // empty string doesn't work
    Small: '/images/Small.png',
    Large: '/images/Large.png'
};

$scope.getUrl = function (name) {
    if (urls[name] !== undefined) return urls[name];
};

HTML (size is the ng-model that binds what the user selects from the dropdown):

Answer: You need to define your default value for size as default for example.
You can use this
var urls = {
  default: '/images/Default.png',
  Small: '/images/Small.png',
  Large: '/images/Large.png'
};

and define your size default value as initial value
$scope.size = 'default';

Answer: You had a typo in your $scope.getUrl function, which should be:
$scope.getUrl = function (name) {
  // you had *if (url[name]*... here
  if (urls[name] !== undefined) return urls[name];
};

Otherwise, there's no reason you cannot accomplish this with an empty string property. See snippet for example.

angular.module('app', ['ui.bootstrap'])
  .controller('MainCtrl', function($scope) {

    var urls = {
      '': 'http://placekitten.com/g/300/300', // empty string is working now
      Small: 'http://placekitten.com/g/150/200',
      Large: 'http://placekitten.com/g/500/500'
    };

    $scope.sizes = ['Small', 'Large'];

    $scope.selectedSize = '';

    $scope.selectSize = function(idx) {
      $scope.selectedSize = $scope.sizes[idx];
    };

    $scope.getUrl = function (name) {
      if (urls[name] !== undefined) return urls[name];
    };

  });

    <link data-require="email@example.com" data-semver="1.5.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <link data-require="firstname.lastname@example.com" data-semver="1.5.0" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" />

    <link rel="stylesheet" href="style.css" />

      <button type="button"
              id="choose-size"
              class="choose-size-dropdown-button btn btn-info"
              uib-dropdown-toggle
              ng-disabled="disabled">

          Select size

          {{ selectedSize }}

      </button>

              {{ size }}

EDIT: If you need a solution that doesn't take out ng-if, per your comment, you can just do this:

I took out the ng-if because it seems like that's actually what your question was asking -- how to show an image without condition, even if there was no selected size.
Comment: the key here is you took out ng-if. Can this be accomplished without taking out ng-if?

Adding default option to ng-if


O app fecha quando o usuário sai da conta

Question: Quando o usuário sai da conta o aplicativo fecha.
O problema surgiu quando eu mudei as regras do realtime disso
<code>{
  "rules": {
    ".read": true,
    ".write": true
  }
}
</code>
para isso
<code>{
  "rules": {
    ".read": "auth.uid != null",
    ".write": "auth.uid != null"
    }
}

</code>
BUTÃO QUE FAZ O LOG OUT
<code>        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseAuth.getInstance().signOut();
                Intent intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
                getActivity().finishAffinity();
            }
        });
</code>
Answer: tente assim:
<code>    button5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FirebaseAuth.getInstance().signOut(this).addOnCompleteListener(new OnCompleteListener<Void>() {
                public void onComplete(@NonNull Task<Void> task) {
                    // agora o usuário está deslogado
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivity(intent);
                    getActivity().finishAffinity();
                }
            });
        }
</code>


python simpleJSONDecoder and complex JSON issue

Question: In a unit test case that I am running, I get a KeyError exception on the 4th json object in the json text below because the piece of code responsible for decoding is looking for an object that isn't there, but should be.
I went through the sub-objects and found that it was the "cpuid" object that causes the problem.  When I remove it and run the test, it works fine.
def _make_report_entry(record):
    response = self.app.post(
      '/machinestats',
      params = dict(record = self.json_encode([{
          "type": "crash",
          "instance_id": "xxx",
          "version": "0.2.0",
          "build_id": "unknown",
          "crash_text": "Gah!"
        },
        {
          "type": "machine_info",
          "machine_info": "I'm awesome.",
          "version": "0.2.0",
          "build_id": "unknown",
          "instance_id": "yyy"
        },
        {
          "machine_info": "Soup",
          "crash_text": "boom!",
          "version": "0.2.0",
          "build_id": "unknown",
          "instance_id": "zzz",
          "type": "crash"
        },
        {
          "build_id": "unknown",
          "cpu_brand": "intel",
          "cpu_count": 4,
          "cpuid": {
            "00000000": {
              "eax": 123,
              "ebx": 456,
              "ecx": 789,
              "edx": 321
            },
            "00000001": {
              "eax": 123,
              "ebx": 456,
              "ecx": 789,
              "edx": 321
            }
          },
          "driver_installed": True,
          "instance_id": "yyy",
          "version": "0.2.0",
          "machine_info": "I'm awesome.",
          "os_version": "linux",
          "physical_memory_mib": 1024,
          "product_loaded": True,
          "type": "machine_info",
          "virtualization_advertised": True
        }
      ])))

In the piece of code being tested, I use simplejson.JSONDecoder from django.utils to decode the JSON.  When I log the decoded output for the above JSON that gets passed to my decoding function, I get this:
root: INFO: {u'instance_id': u'xxx', u'type': u'crash', u'crash_text': u'Gah!', u'version': u'0.2.0', u'build_id': u'unknown'}

root: INFO: {u'build_id': u'unknown', u'instance_id': u'yyy', u'version': u'0.2.0', u'machine_info': u"I'm awesome.", u'type': u'machine_info'}

root: INFO: {u'build_id': u'unknown', u'machine_info': u'Soup', u'version': u'0.2.0', u'instance_id': u'zzz', u'crash_text': u'boom!', u'type': u'crash'}

root: INFO: {u'eax': 123, u'edx': 321, u'ebx': 456, u'ecx': 789}

On the last JSON object, only the object within the JSON cpuid object is being passed to my decoding function.  Because my decoding function is expecting the the other objects (e.g., 'type', 'instance_id', etc.), I get a KeyError exception.
[Sorry for the earlier unnecessarily long post, I hope that this will narrow it down a bit more]
Comment: Could you paste the exact error?
Comment: What is *self*.json_encode? Something you wrote??
Comment: It's a lot of info, but not enough as what looks like a stack trace is incomplete -- and the trails in it hints at a _decoding_ situation going on, **not** an _encoding_ one (as your original Q suggested).  Maybe you're mis-using some of your own models? Can't tell, since we don't see the models' definitions.
Answer: Copying and pasting what you're passing to self.json_encode, and using it as an argument of json.dumps (after an import json in Python 2.6), works just fine.  So it seems the bug may be in the json_encode method you're not showing us: what else does it do, besides just calling json.dumps...?  (or simplejson.dumps if you're using a Python < 2.6, of course).
Edit: using json_encode = json.JSONEncoder().encode (as the OP just posted, except that's using the older simplejson as I had mentioned as a possibility) also works fine.  The incomplete stack-trace also posted as part of the Q's large edit suggests that the error comes in the decoding part, perhaps through misuse of some model (can't tell, as we don't see the models) -- as the OP mentioned he's now posted a lot more info, and yet it's still not enough to debug the problem.
This strongly suggests that it would be worthwhile for the OP to try and simplify the problem a little at a time until the last incremental simplification makes the bug disappear -- that usually strongly hints at what the bug may be, but even if it doesn't, posting the tiniest way to reproduce the bug plus the info that the bug will disappear if a miniscule epsilon of code is further removes, may help "third party observers" like us all assist in the debugging.  SO is not really a platform designed for collective debugging (works better for questions and answers, what it was designed for) but I don't think it breaks SO's rules to try and use it for this different purpose.
Comment: I just updated my question.  Formatting is horrible.  I'll see if I can fix that.
Answer: Last 2 lines in traceback:
File "...j_report/src/jreport/machinestats.py", line 77, in _make_report_entry
entry_type=record['type']

You have now TWO versions of def _make_report_entry(record):
Note that the first few lines of the traceback are muttering about decode, not encode.
What has the first/original version to do with the problem?
You now say "Because my decoding function is expecting the the other objects (e.g., 'type', 'instance_id', etc.), I get a KeyError exception."
So perhaps your decoding function is being called recursively and is expected by the caller to be able to handle ANY structure, not just ones with 'type' etc.
Comment: Your points 3&4 are a bit wayward: the dict() builtin has any keyword arguments you wish to give it. `dict(record='string')` creates a dictionary with a key `record`.
Comment: @Duncan: yeah silly me, I wasn't impressed with the key=value gimmick when it came out and forgot about it


How to build more projects with gradle while the part which they share will be build only once?

Question: I have three subprojects in my project. Each of them is executable web app. They share the same core module which also has its build.gradle script. Let's say its name is shared-core. Right now I have separate gradle.build and settings.gradle for each of them. So when I am trying to build all of them the core will get rebuilt thrice. But I would like to set up gradle script so the shared-core will get rebuilt only once.
I am really new to gradle so sorry if this is a dumb question but how can I do that ?
Thank you for any help.
Answer: root(main-project)
|
|-shared-core
|   |-build.gradle
|
|-sub-project-a
|   |-build.gradle
|
|-sub-project-b
|   |-build.gradle
|
|-sub-project-c
|   |-build.gradle
|
|-build.gradle
|-settings.gradle

Now on each subproject, you add dependency of shared-core as compile project(':shared-core'). You can find more details on multi-project builds.
Comment: Thank you for your help I will check that out :).
Comment: Those 3 subprojects each of them has complicated build.gradle and settings.gradle. It is not that trivial for me to group it under common root. Can you help me what should I put to build.gradle and settings.gradle of root project so it will work ?
Comment: The build.gradle in subprojects can be as is with minor extraction to root build,gradle. However, you can have only one settings.gradle which will include subprojects and should be as I mentioned above.
Answer: If I understand correctly (from the multiple settings.gradle files), you're building your projects as completely separate builds. Gradle has no knowledge of the relationships between these projects.
If you create a multi-project build, where each of your projects are sub-projects, and you make each webapp module depend on the shared-core, then Gradle will only build the shared-core project once in a single build.
You can still configure each webapp module as you like.
If you don't want to see all webapps in a single project, take a look at composite builds, but setting up that is a bit more difficult.
Comment: Thank you for your help I will check that out :).


Show different modules dependence on user role

Question: I uwrite app and now i have question - lets say i write app for restaurant.
And i need that this app can login chief and waiter  and restaurant owner
Now chief need see only orders.
And waiter need see orders, and table.
and owner need see orders, money tables and lets say count of people
So we have Money, orders, table, people modules.
So I don't want to write for each "player" app - I want all modules in 1 app but to do like [Attribute] for pages.
I come from .NET web - so in WebAPI I just put [Authorize(Roles="Owner")] for example
But i dont find example how i can do something like it in xamarin
Thank you
Comment: You can't magically do this. You have to program it.
Answer: There is no built in mechanism to do this in Xamarin.  You would need to code this yourself in your app based on whatever security/role mechanism that you are using.
If you are using MVVM navigation it should be fairly easy to add this sort of check into your navigation mechanism so that users are not allowed to navigate to pages they are not authorized to view.


Can I keep  in my app but make it not render twice

Question: I have my app inside a Strict Mode and it makes it difficult to run with my useEffect().
It basically logs all my values twice in the console which is not the result I want to achieve.
 useEffect(() => {
console.log('logs some data')
}, []);

It there a way to make useEffect only show the data once and keep the StrictMode inside my app component?
root.render(
<React.StrictMode>
 <App />
</React.StrictMode>
);

I did try using the useRef method but I was advised by my staff to not use this specific method and try another possible outwork.

Solution:
If you ever need to keep Strict Mode in your component but need to make your useEffect no render twice, you could use useRef :
Example:
 let shouldlog = useRef(true);

 useEffect(() => {
 if (shouldlog.current) {
  shouldlog.current = false;
  console.log("component mounted");
  }

return () => console.log("function cleaned up");
}, []);

Comment: no you can't: https://beta.reactjs.org/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development, but you can use ref approach if none of the scenarios work for you in that link
Comment: The double rendering (or render - unmount - render) is there to help people spot problems in their useEffects. But it's not doing this in production mode. My guess is that the React team wants to prepare people for future versions of React, where abusing useEffect will cause problems
Answer: We have to understand the concept of Strict mode first then only we will react the solution
<StrictMode> helps find common bugs in your components early during development.
Reference

Strict Mode enables the following development-only behaviors:

Your components will re-render an extra time to find bugs caused by impure rendering.
Your components will re-run Effects an extra time to find bugs caused by missing Effect cleanup.
Your components will be checked for usage of deprecated APIs.

So basically  is used to find the common errors or bugs during the development to build a quality React app
Answer: You can take advantage of the cleanup function to cancel the redundant work, for example using a 0 timeout:
  useEffect(() => {
    const timeout = setTimeout(() => {
        console.log('one console log ' + new Date().valueOf();
    }, 0);

    return () => {
        clearTimeout(timeout);
    }
  }, []);

The life cycle looks roughly: create component, immediately destroy it, create it again. And with effect: run effect, immediately run its cleanup function, run it again.


Adding Social counter

Question: i need to show in my site the social media counter like Facebook fans count ...
its some thing like :-
Answer: Share count statistics

Allows your Drupal site to gather statistics on how many times your
content (and other entity types) have been "shared" with
social/sharing services like Twitter, Google+, Facebook, etc. Also
provides an API for other modules to hook into and provide their own
share counts.

Social Stats

This is a statistics module. It provides data from various social media sites. The data which is saved per node. It includes data from:

Facebook : likes count, shares count, comments count & total count.
Twitter : tweets count.
LinkedIn : share count.
Google Plus : plus one count, share count & total count
Total Share Count : total across all available social networks
Comment: i install Social Stats but how can display in site ?
Comment: pls share what you have tried and what does not works..
Comment: i am now install this https://drupal.org/project/social_stats but i dont know how can show block in my site ?
Comment: any help to show this module to my site
Comment: you can try something like http://www.nextweblink.com/2015/02/11/social-share-counter-drupal/

Adding Social counter


How do I configure Windows for dual certificates, ECDSA with RSA fallback?

Question: We'd like to use an ECDSA SSL cert; however, we need to support a fairly wide variety of devices including some that are unlikely to ever support ECDSA certificates. The standard solution is to fallback to an RSA cert based on what the client supports, presumably as envisaged in this answer. On Linux with Apache 2.4 it's possible, and similarly for Nginx where wikipedia's turned it on.  How can I enable this, ECDSA+RSA, in Windows for IIS and OWIN?
The answer I expect is "Use Windows Server 2016 and then do X," but I'd like to be pleasantly surprised.
Answer: As Peter said, this isn't possible on any version of IIS currently. However you could setup nginx as an SSL proxy in front of IIS and that would do what you need.
Comment: Nginx as an SSL terminating proxy on a linux box in front I assume? I *believe* (without a firm basis) that Nginx on Windows still use SChannel (where support for dual certs would unblock IIS/OWIN even if it needed to be manually configured in the registry). We're currently using Azure's LB, and an Nginx loadbalancer/SSL termination could be something we'd do for other reasons.
Comment: @cacsar I'm not sure about nginx on Windows to be honest, I've only ever run it on linux boxes. That's the way I'd go, with a separate *nix box in front. Nginx HTTP/2 support should be out sometime in the not too distant future too, so you'll get advantages there that IIS can't offer currently (although will be able to with the next release and IIS 10).
Answer: It is my understanding that neither 2012 R2 nor Server 2016 support dual certificates.
You can only assign a single certificate to a binding.
Set up a second binding and point your legacy devices to it.
Comment: While I could believe that's the only option on Windows, it's not exactly a viable one. Time to go poke contacts.