What qualities of a guitar should I seek for an 8 year old?

Question: We are looking for a guitar for my son, and have seen cheap ones at Toys R Us, et al.  He is just starting out, and we are trying to gauge his interest before spending too much.  Would it be worth starting off with what is essentially a toy, and upgrading later? If not, what things should we look for?  Nylon or steel strings? What size? 30", 1/2, 3/4? Is there anything else that would help him use the instrument?
Comment: It's not going in the answer, but I believe places like Toys R Us do sell instruments that are good enough not to be described as toys. If you're spending less than $50 on a guitar though, definitely go nylon strung.
Answer: I bought my son a 3/4 scale guitar with nylon strings when he was 5 or 6. That gave him enough interest to start learning, then I let him use one of my cheap full scale acoustics with steel strings at age 8 as his hands were big enough.
Currently he has taken up bass, so he is learning on a 5 string that my bass player had spare. It is a challenge as he is only 11, but he is gaining hand strength and stretch.
The core for me at the start was letting him enjoy what he was doing, so nylon strings meant it didn't hurt his fingers. Once he had decided he wanted to learn, he was mentally in a place where toughening his fingers up on steel strings wasn't an issue.
Comment: +1 for starting with nylon strings....I still can't stand how steel slices my finger pads up.
Comment: I have always thought Nylon string is a deal breaker and any wanna be guitarist should stick to steel string unless s/he has a very specific reason to do otherwise, am I wrong?
Comment: Why the strong steel string preference? In addition to my rock and blues I love playing classical and flamenco so I do use nylon a fair bit.
Comment: @dr-mayhem I've always played steel string with low tension on string.Then I learned that this is not standard tuning and the standard on has much higher tension. After that its really difficult for me to play it. I've always preferred low tension where the strings give me more comfort. That's why I thought starting with steel is a smarter choice. What do you suggest in my situation?
Comment: @babu Sorry, I don't mean offence. But, 'steel slices my finger pads up', really sound a bad excuse. Do you have any logic to back it up?
Comment: @iamcreasy If you want the sound that steel makes, you have to use steel. Nylon makes a different sound, neither better nor worse than steel. Nylon works at *much* lower tensions than steel, so it's easier on beginners' fingers.
Comment: @iamcreasy - steel strings will cut your hands at first, but you very quickly develop calluses on your fingertips. It only takes a few practice sessions to do this. You will lose the calluses if you stop playing for any length of time, but your body will protect itself.
Comment: @dr-mayhem I am playing guitar from an early age(not 8 of course, and I am not a very good guitarist) but I never had(or even seen) any cut from steel string. So, when I hear someone saying 'steel string cut my finger', I scratch my head. My thinking is either he is holding/doing it the wrong or there was something wrong with that string.
Comment: Perhaps he slides way too much enough to cut, but even then it doesn't sound right
Answer: I started playing  guitar at about 7 years old, I got a classical guitar, slightly smaller than the common size -but very slightly (I think it was larger that the '3/4 size', I actually played until I was 20!). The important thing for a child, I'd say, is that the guitar is confortable to play: rather low action and normal-to-low tension strings. Nylon, of course.
Comment: I still use my 3/4 size classical guitar. I've had it 20 years, and had a good bash on it last night, tuned to an open blues chord.
Answer: Consider a ukulele.
"Real" ukuleles are available cheaply (although you can spend a lot on a really lovely one). It suits small hands. It has nylon strings so it's not too difficult to fret. There are plenty of resources for learning real songs to play on the uke. Having fewer strings makes for easier chord shapes. It's a great instrument on which a child can learn the basics of fretting, strumming and plucking without having to deal with a large instrument.
One down side is that if he migrates to a guitar, he'll have to learn new shapes, to account for the extra two strings.
But to mitigate that, being adaptable to new tunings is a good skill -- and young minds adapt quickly. And of course, he could choose to stay with the uke... or the mandolin... or the banjo... or any number of other guitar-like instruments.
If you do this, do get a uke book (or learn uke yourself, and teach him). The high-tuned bottom string is counter-intuitive, so he'll need reassurance -- or with the right strings you can tune it low so it feels more like a guitar.
Whether you go for a guitar, a uke, or something else, make sure the instrument has acceptable intonation. Playing an instrument with bad intonation is really no fun whatever your standard.
If you do go for a steel strung instrument, pay special attention to the action and the string tension. You don't want to put him off by giving him an instrument that's a struggle to fret.
Comment: How far are guitar and ukulele? I've always thought they are close cousin and there is not much of a difference between them. Can anyone learn them interchangeably at the same time?
Comment: A ukulele has four strings tuned at the same intervals as the top four strings of a guitar (except the bottom string is usually an octave up). So the shapes are the same as you'd use on the EBGD strings on a guitar. It should be very straight forward (and fun) to learn both at the same time.
Comment: Whoa, interesting suggestion!
Comment: @slim I might try your suggestion, I am looking forward to buy a ukulele withing a few months. Does ukulele has instrumental sophistication like guitar?
Comment: "Sophistication" is a difficult thing to measure, but a uke has four strings that you can fret, bend, mute, pluck, strum etc. just like a guitar. YouTube is full of examples of people playing a uke in an unsophisticated manner, but a good player can do incredible things with one. http://www.youtube.com/watch?v=puSkP3uym5k
Answer: I'm not (really) a guitar player, but I have taught beginners as part of a generalist music-lesson gig.  The other answers so far are good, but I would add two essential things from my own experience:

The fretboard needs to be in tune.  Otherwise, the instrument is going to sound really bad.  If you're not sure, tune any string with an electronic chromatic tuner, then play the same string on each fret individually and notice what the tuner says.  If the guitar gets way off pitch, quickly, stay away.
It needs to be possible to set up the guitar so that the open strings (or strings when pressed down) do not arbitrarily buzz against frets.  Trying the exercise from item #1 on all the strings and noticing if there is any buzz (that comes from something other than improper finger placement) is a good way to check for this, since there is no guarantee that the frets are the same height all the way across the fretboard.

I remember teaching a very young student who clearly had a "toy" guitar, and these two issues made it almost impossible to teach her.  It was frustrating for the student and for me, and the student never really improved very much.
Comment: My first guitar got off pitch quickly, and it was frustrating.  My son plays with an old guitar of ours that has starting buzzing and that's why he wants his own. Great advice!
Answer: I agree on quality. You wouldn't want to give a child a pre-war Martin unless you're crazy and rich or he's Chris Thile in the making, but you wouldn't want to give something that pretended to be an instrument, either.
Smaller, but not too small, or else the child will rightfully think it's just a toy.
Two crucial things to note: If the child is interested in playing electric, no acoustic guitar will do, and if the child is interested in playing acoustic, no electric guitar will do. And your child, as with anyone who hasn't been taught to know better, will not know how hard to fret, and will thus oversqueeze, hurting fingertips (which makes playing uncomfortable) and pulling sharp (which makes the sound uncomfortable). Early on, teach a light touch, and this will make the rest of the process easier.
Comment: He does have a point, if the kid does want an electric guitar, an acoustic will not fulfill his wants. If you want the kid to enjoy this you would want to seek what he wants, not what you want for him. The fun factor isn't just from holding the strings right, but also what he thinks is cool. If he thinks the guitar looks stupid he's not going to want to play it at all
Comment: -1, You are far away from the curve. 1) 8 year old would be disturbed from the distortion and ultra precision/care he has to take to sound good with an electric. 2) 8 year boy would never understand the tonal difference, so quality is not the issue here. The only this that his father should be focus on is the `fun factor`, which comes form holding it light and playing it freely(without much of a pain).
Answer: This is around the same age I started playing guitar. The guitar I started on was my dads first guitar which was from the early 60s, it was a catalog guitar nothing fancy. For strings, since I had an electric I had light gauge steel strings.. The way I got hooked was just by listening to the music my dad liked, which is the same music I like now and then.. I wanted to be able to play that music that I heard. Just don't force it on him, thats is what killed it for me for about a year, yes try to get him to practice but make it fun not stern and dull, make achievements for him where he could get some sort of reward related to guitar .. like a strap that he saw that he liked, or something simple like that
Hope this can be of some help for you.
Answer: I would go against buying a toy guitar. This really kills everything from the start. Rather paying a little extra might pay a lot in the long run. For the guitar priority one should be, going for something that suits his body shape. Something he is comfortable with it.
Also go for steel string not Nylon!
Comment: Why not nylon? Some people play a classical guitar their whole life.
Comment: @slim See my comment on dr-mayhem's answer. Would you please refer to some guitarist who has played Nylon in their whole life? I want to know their play.
Comment: Pretty much any classical guitarist. http://www.youtube.com/watch?v=oPfZVflJdp0 or flamenco guitarist http://www.youtube.com/watch?v=aj1rUJ8rIiE
Comment: For me it feels its somehow pure to start with steel and taking the decision to jumping into nylon later(depending on the choice and skill of the player). If avoiding any finger tip damage is too high, then Nylon should be the way to go. Thought its just my opinion.
Comment: I don't know what you mean by "pure" but a nylon strung guitar is the closest to a traditional instrument. Nylon strings are designed to have similar properties to the catgut strings used on all stringed instruments before steel and nylon became available. Steel strung guitars need a metal bar to strengthen the neck!
Comment: I have miss used the word 'pure' here. The thing is from where/what  source most of the people play and get inspiration from. People want to play guitar cause they heard/hear/find it sound fascinating, and most of the time the source is steel string. That's what I meant.


I have a proof that " For every set $S, ∅⊈S$" BUT I cannot find anything wrong.

Question: My proof is:
Let $S$ be a set, to show that $∅⊈S$, we must show that $∃x(x∈∅\implies x∉S)$ is true. Because $x∈∅$ is false, the conditional statement $x∈∅\implies x∉S$ is always true. Therefore, $∃x(x∈∅\implies x∉S)$ is true. This completes the proof.
I cannot find anything wrong.
Comment: You misunderstood the interplay of negation and $\to$: $\subseteq$ is defined as $\forall x (x \in \emptyset \to x \in S)$. Thus, its negation $\nsubseteq$ will be $\lnot \forall x (x \in \emptyset \to x \in S)$ that is $\exists x (x \in \emptyset \land x \notin S)$.
Comment: "to show that $∅∉S$, we must show that $∃x(x∈∅\implies x∉S)$ is true": no, what you must show is $\forall x(x=∅\implies x∉S)$ (but you won't be able to show it because it is false for many $S$'s).
Comment: Because $x \in \emptyset$ is always false. The *emptyset* is .... empty, that means exactly: $\forall x \lnot (x \in \emptyset)$
Comment: This doesn't show that $\emptyset \notin S$.
Comment: If you change the $\exists$ to $\forall$ you are showing that $\emptyset$ is disjoint from every set, which is true.
Comment: $\{\{\}\}~~~~~$
Comment: @MauroALLEGRANZA Then how do you prove that ∃x(x∈∅∧x∉S) is false?
Answer: Your error is very simple. It is not true that

To show $\varnothing\not\subseteq S$ we must show that $\exists x(x\in\varnothing\implies x\notin S)$.

This is false. You have messed up the negation of "is a subset of".
Recall that $A\subseteq B$ is shorthand for
$$\forall x (x\in A\implies x\in B).$$
That means that $A\not\subseteq B$ is shorthand for:
\begin{align*}
\neg\left(\forall x(x\in A\implies x\in B)\right) &\iff \exists x\left(\neg\bigl( x\in A\implies x \in B\bigr)\right)\\
&\iff \exists x\bigl( (x\in A)\wedge \neg(x\in B)\bigr)\\
&\iff \exists x\bigl( (x\in A)\wedge (x\notin B)\bigr).
\end{align*}
This because the negation of $P\to Q$ is $P\wedge(\neg Q)$.
So what you actually should have is:

To show $\varnothing\not\subseteq S$, we must show that $\exists x\bigl((x\in\varnothing)\wedge (x\notin S)\bigr)$.

Now note that $(x\in\varnothing)\wedge (x\notin S)$ is always false, since $x\in \varnothing$ is always false.
Answer: By definition of subset, for any two sets $A,B$, we have $A \subseteq B$ if and only if
$$\forall x[x \in A \to x \in B]$$
Thus, we show $A \nsubseteq B$ by taking the negation of said formula
$
\begin{array}{11}
\neg \forall x[x \in A \to x \in B] & \\
\exists x \neg [x \in A \to x \in B] & \text{Negation Rules for Quantifiers} \\
\exists x \neg [\neg (x \in A) \vee x \in B] & \text{Implication Rule}\\
\exists x [\neg\neg (x \in A) \wedge \neg (x \in B)] & \text{DeMorgan's Law}\\
\exists x [x \in A \wedge \neg (x \in B)] & \text{Double Negation Elimination}\\
\exists x [x \in A \wedge x \notin B] & \text{Definition of $\notin$}\\
\end{array}
$
Thus, in order to show $\emptyset \nsubseteq S$ for every set $S$, you must prove
$$ \exists x [x \in \emptyset \wedge x \notin S] $$
for some arbitrary $S$. Of course, the first conjunct $x \in \emptyset$ is always false, so the formula is always false.


How can I use the Private Message module for anonymous users?

Question: I am using the Private Message module as a way of contacting the author of a node.
I have the problem that the button that says "Send author a message" only appears on the node when the user is logged in. If the user is not logged in, then the button that appears is the one that says "Log in or register to be able to post comments" (or something like that)
What I want to achieve is that the user (not logged in) can see the "Send author a message" on the node. And when this user clicks on this button he will be taken to the login form first, and then, after login, the user gets redirected to type the message to the node author.
How can I achieve this?
Comment: Have you checked any permissions for this module? Without knowing much about your business modelor technical model do you want anonymous users to send messages through your site?
Answer: The Privatemsg module CANNOT be used for anonymous users ... Unless you are ready for some "tweaks" ... as detailed below.
I'm assuming your question is about D7, if it is for D6, you might consider using what's described in Issue # 490264. But it's worth reviewing that issue to get "an idea" about a possible work around ...
So how about D7? Issue # 554238 is about D7, and Comment #7 in it refers to the issue I mentioned above (which is for D6). However Comment #8 in that issue might be the solution. It contains this code sample:
<?php
$msg = "Hello there";
$source_tag = "from {$_SERVER['REMOTE_ADDR']}";
$result = privatemsg_new_thread( array(user_load(1)), "Browser visit {$source_tag}", $msg, array('author' => user_load(1)) );
// If you wanted to show an error, uncomment the following:
if (!isset( $result['success'] ) || !$result['success'])
{
  printf( "
Failed to send: %s
\n", $result['error'] );
}
?>

Apart from what is above, there is also the (way more) recent issue # 2231795. Comment #1 in it contains a code sample also. So if the above code doesn't fit (or work), consider this as an alternative.
So by using the Privatemsg module, and some tweaks (see above) you should be able to make it work somehow for anonymous users also
Comment: Thank you for the "thanks". Also, hope you don't mind I say so, but looking at your profile I noticed that you never visited the "tour" (link within "help", upper right). So you probably are not aware either of what's written in drupal.stackexchange.com/help/someone-answers ...
Comment: I will visit this section, no problems


MCA : interpretation for contribution and correlation

Question: According to the definitions:
The correlation matrix reports the correlation of each variable with each dimension.
Contribution refers to the contribution of each category of each variable to the dimension.
I have two questions regarding the interpretation.
How to interpret these correlations and, how is it different from the usual correlation?
What does it mean that each category contributes to this dimension or that dimension?
Answer:
What does it mean that each category contributes to this dimension or that dimension?

You might find answers to your questions on this page : http://www.sthda.com/english/articles/31-principal-component-methods-in-r-practical-guide/114-mca-multiple-correspondence-analysis-in-r-essentials/
See for example:

The variable categories with the larger value, contribute the most to
the definition of the dimensions. Variable categories that contribute
the most to Dim.1 and Dim.2 are the most important in explaining the
variability in the data set.


Backup Windows Server 2008 FTP e Cloud

Question: Preciso gerar backups diários em um servidor windows server 2008 R2, os backups são de diversas pastas e aplicações instaladas neste servidor, o windows server possui ferramenta pra isso, alguma ferramenta do propio sistema?
Tenho pouca experiência com o so em questão, minha area na verdade e desenvolvimento.
Os backups precisam ser feitos para FTP e em um cloud da vida tipo dropbox e google drive.
Estive olhando algumas ferramentas de terceiros e não vi nada que se encaixe com o que preciso "custo/beneficio", estou pensando até mesmo em desenvolver eu mesmo a ferramenta.
Alguma sugestão?
Comment: Teste o Cobian Backup, talvez lhe sirva.
Answer: Você pode utilizar o robocopy do próprio Windows para otimizar seus backups de acordo com suas necessidades.
Documentação Robocopy - https://technet.microsoft.com/pt-br/library/cc733145(v=ws.10).aspx
E pode utilizar com cloud por exemplo o Google Drive, utilizando a sintaxe do tipo:
<code>    robocopy "\\Diretório\" "\\GoogleDrive\dir" /copyall /sec /mir /r:1 /w:1
</code>
Comment: Interessante esse robocopy.. Me parece a melhor opção...

Backup Windows Server 2008 FTP e Cloud


Apache  Errors

Question: I am having real trouble with this installation - Basically this is the erro that I am getting:
apache2: Syntax error on line 234 of /etc/apache2/apache2.conf: Syntax error on line 10 of /etc/apache2/conf.d/amberdms-bs.conf: Expected </Location\xc2\xa0/billing_system> but saw </Location>

and this is the code that is being used in that modules file:
#
# Amberdms Billing System is an open source accounting, service billing and time keeping web application.
#
Alias /billing_system /usr/share/amberdms/billing_system
<Location /billing_system>
Order deny,allow
Allow from all
AllowOverride all
</Location>

Please help me! I need this software to be installed, but this error has stumped me.
Answer: Sounds like the <Location> directive has a non-breaking space instead of a normal breaking space. Remove the space and retype it.
Comment: thank you so much, can't believe I fell for that! Cheers for the quick reply.
Answer: You need a closing  tag for starters, and i'd also put the path in double quotes:
<Location "/billing_system">
  Order deny, allow
  Allow from all
  AllowOverride all
</Location>

Apache  Errors


Integrating curve over a line segment

Question: I'm having some trouble understanding this question: what is $\int_C xdy - ydx$, where C is the curve composed of a straight line segment
C from $(−2, 0)$ to $(0, 0)$, a straight line segment from $(0, 0)$ to $(0, −2)$, and the part of the circle of radius 2, centered at the origin, traversed counterclockwise starting from $(0,−2)$ and ending at $(−2, 0)$. I tried breaking it down into 2 curves, and integrating separately but I'm not able to get the answer of $6\pi$. Anyone knows what's the correct way to solve this problem?
Comment: By using Green's Theorem, you can turn this into a trivial integral and simultaneously avoid parameterizing the curve.
Answer: Recall Green-Stokes's theorem: if a closed curve $C$ encloses a region $R$, going counterclockwise, then $$\int_C P \,{\rm d}x + Q\,{\rm d}y = \iint_R \left(\frac{\partial Q}{\partial x}-\frac{\partial P}{\partial y}\right)\,{\rm d}A,$$ for $\cal C^1$ functions $P$ and $Q$.
So, using Green-Stokes, we have: $$\int_C -y \,{\rm d}x + x \,{\rm d}y = \iint_R \frac{\partial x}{\partial x} - \left(\frac{\partial(-y)}{\partial y}\right) \,{\rm d}A = 2 \iint_R \,{\rm d}A = 2 \,\frac{3}{4}\,\pi \,2^2 = 6\pi,$$ where $R$ is the interior of this pacman (its eye is just me having fun, it is simply connected)

Jokes apart, $\iint_R \,{\rm d}A = \frac{3}{4}\pi r^2$, and no calculus is needed for this part.
Comment: Is a requirement of Green's theorem that the velocity field vector must not be conservative? In this case, how do we show that the vector is not conservative? Or does that not matter?
Comment: This is not important :)

Integrating curve over a line segment


Exibir um registro por quantidade e o valor que mais se repete de uma coluna

Question: Olá, estou com o seguinte problema: preciso que seja exibido as localidades, o número de envios de cada uma (ou seja, quantas vezes o nome da localidade aparece na coluna) e a doença mais comum de cada localidade (ou seja, o nome da doença que mais se repete naquela localidade específica).

POR EXEMPLO:

localidade: Croatá 1
número de envios: 4
doença mais comum: Conjutivite

Tenho essas duas query's mas elas não funcionam juntas, apenas uma ou outra
SELECT localidade, count(localidade) AS qt FROM tb_grafico group by localidade;

SELECT localidade, tipo_doenca, COUNT(tipo_doenca) as qtidade FROM tb_grafico
where localidade='Croatá 1'
GROUP BY tipo_doenca
ORDER BY COUNT(tipo_doenca) DESC
LIMIT 1;

de preferência em uma única querry sql
Comment: o que já tentou fazer? Da uma lida no [tour](https://pt.stackoverflow.com/tour) do site, a ideia é ajudarmos a resolver dúvidas mais específicas ;)
Comment: sim eu tentei e consegui com duas querry's mas quando puxava os dados php a primeira querry não funcionava mais
Answer: Minha sugestão é que crie uma VIEW que totalize a quantidade baseado na localidade e na doença:
CREATE VIEW vw_grafico AS
  SELECT localidade,
         tipo_doenca,
         COUNT(localidade) AS quantidade
    FROM tb_grafico
   GROUP BY localidade,
            tipo_doenca;

Depois disso faça a seleção da maior doença na vw_grafico:
SELECT g.*,
       (SELECT SUM(g3.quantidade)
          FROM vw_grafico g3
         WHERE g3.localidade = g.localidade) AS total
  FROM vw_grafico g
 WHERE NOT EXISTS(SELECT 1
                    FROM vw_grafico g2
                   WHERE g2.localidade = g.localidade
                     AND g2.tipo_doenca <> g.tipo_doenca
                     AND g2.quantidade > g.quantidade)

Comment: mas ele está exibindo todas as doenças do bairro, eu só queria a localidade, doença que mais se repete e a quantidade para chamar no php e exibir apenas uma vez


SSL Handshake, Cannot Pinpoint Problem

Question: When attemting to communicate with an Alfresco Server to perform a file upload  the client receives the following error in their logs.

SSLPeerUnverifiedException:
Indicates that the peer's identity has not been verified.
When the peer was not able to identify itself (for example; no
  certificate, the particular cipher suite being used does not support
  authentication, or no peer authentication was established during SSL
  handshaking) this exception is thrown.

I was attempting to break down the SSL handshake to see what is causing this error using steps around the web.
On which step does it look like the handshake is failing. I am leaning towards 3 but have no idea due to the following:

The error is only thrown during file uploads. (Downloads, browsing, etc all work fine.)
Certificates have been checked and are still valid
Certificates have been reupdated on the client
The certs were not in cacerts on the client before so they have not been put there

Is this error occuring serverside and something is misconfigured on the server? If so what could it be?
Comment: @AndreasM Thanks, there were two certificates but the client was only set to accept one. The other was added and everything is golden. If you elaborate your comment into an answer I can give you some rep.
Comment: It seems that uploading has a different ssl configuration than download/browsing. Do you have apache/another webserver in front of alfresco? Another problem could be that the browser has actually two client certificates of that host and automatically selects the wrong one. Configure the browser for manual selection.
Comment: cool, see below. It's not entirely clear to me whether we're dealing with client or server certs. The error suggests that the server wants a client cert.
Answer: It seems that uploading has a different ssl configuration than download/browsing. A problem could be that the browser has actually two client certificates for that host/domain and automatically selects the wrong one.

SSL Handshake, Cannot Pinpoint Problem


React simple useEffect infinit loop

Question: I do not understand why this code is an infinit loop. I this it is because I update my state in else if condition. But i'd like to update an array of urls when getting new api answer.
import React, { useState, useEffect } from 'react';

function getShortenUrl() {
  const [urls, setUrls] = useState([])
  const [error, setError] = useState(null);
  const [items, setItems] = useState({});

  useEffect(() => {
    fetch("https://api.shrtco.de/v2/shorten?url=https://stackoverflow.com/questions/37435334/correct-way-to-push-into-state-array")
      .then(res => res.json())
      .then(
        (result) => {
          setItems(result);
        },
        (error) => {
          setError(error);
        }
      )
  }, [])

  if (error) {
    return
Error : {error.message}
;
  } else if (!items.result) {
    return
Loading...
;
    console.log("no item");
  } else {
    setUrls([urls, items]);
    console.log("items", items);
    console.log("urls", urls);
    return
 {items.result.short_link}
;
  }
}

export default getShortenUrl;

I am kindof lost when it comes to state actually. I do not understand how I can create an array of urls and be able to use it in other components.
Comment: You shouldn't have individual return statements: instead, have one single return statement and use if/else logic inside the return statement instead for conditional rendering.
Answer: You may have some mistakes here
      .then(
        (result) => {
          setItems(result);
        },
        (error) => {
          setError(error);
        }
      )

Change it into
.then((result) => {
          setItems(result);
          setUrls([...urls, result])
})
.catch((error) => {
          setError(error);
})

And also remove the line setUrls([urls, items]);
Comment: Hey, thank you for your answer. How do I use the returned short_link to fill an array in an other component ?
Comment: With this case, you should create and use `useContext` vs `dispatch`.
Check it out with this guide and example here: https://kentcdodds.com/blog/how-to-use-react-context-effectively
Answer: Try to use a conditional rendering instead of if else statement:
import React, { useState, useEffect } from 'react';

function getShortenUrl() {
  const [urls, setUrls] = useState([])
  const [error, setError] = useState(null);
  const [items, setItems] = useState({});

  useEffect(() => {
    fetch("https://api.shrtco.de/v2/shorten?url=https://stackoverflow.com/questions/37435334/correct-way-to-push-into-state-array")
      .then(res => res.json())
      .then(
        (result) => {
          setItems(result);
        },
        (error) => {
          setError(error);
        }
      )
  }, [])

return (

         <>
             {error&&
Error : {error.message}
}
             {!items.result &&
Loading...
 }
             {items.result &&
 {items.result.short_link}
}
        </>
   )

}

export default getShortenUrl;

Comment: Hey, thank you for your answer. How do I use the returned short_link to fill an array in an other component ?
Answer: If you are new to react then we make Loading state for API Call fetch and you are setting state in else and when state updates component re-renders so on every component re-render you are updating state which is causing infinite loop. Try this
import React, { useState, useEffect } from 'react';

function getShortenUrl() {
  const [urls, setUrls] = useState([])
  const [error, setError] = useState(null);
  // const [items, setItems] = useState({}); // remove it because you are using urls and items state for same purposes
  const [loading,setLoading]=useState(false);

  useEffect(() => {
    setLoading(true);
    fetch("https://api.shrtco.de/v2/shorten?url=https://stackoverflow.com/questions/37435334/correct-way-to-push-into-state-array")
      .then(res => res.json())
      .then(
    (result) => {
      // setItems(result); // remove it
      setUrls(result);
      setLoading(false);
    },
    (error) => {
      setError(error);
      setLoading(false);
    }
      )
  }, [])
      if(loading){
           return
Loading...
;
      }
  if (error) {
    return
Error : {error.message}
;
  } else {
    return
 {urls?.result?.short_link}
;
  }
}

export default getShortenUrl;

Comment: Hey, thank you for your answer. How do I use the returned short_link to fill an array in an other component ?
Comment: You can store it globally either using Context or Redux to avoid props drilling. And you can also send to child component via props. like

React simple useEffect infinit loop


É ideal usar tipos primitivos em Java?

Question: O Java possui vários wrapper's que nos ajudam (Integer, Double, BigDecimal), e também nos dá a possibilidade de usar tipos primitivos (int, float, char).
Um professor disse à minha turma de faculdade que Java não deveria ter suporte a tipos primitivos de dados, tanto que a partir do Java 9 ficarão obsoletos (O professor disse, não sei se é verdade). Isso é fato? Por que não devo usar tipos primitivos nem mesmo em um laço de repetição?
Comment: Um ano se passou, o Java 9 foi lançado, e os tipos primitivos estão aí firmes e fortes. :)
Comment: Estranho, o que sempre ouço falar é que os primitivos, quando estes atendem a ocasião, são melhores para ser usados do que classes wrappers. Vou aguardar um esclarecimento sobre isso também. Boa pergunta +1
Comment: @diegofm sim já vi muitas discussões sobre o assunto, mas nunca ouvi uma explicação sobre se devo ou não usar, isso me deixa muito em dúvida.
Comment: Você editou a pergunta e complicou minha resposta, mas vou dar uma atualizada.
Comment: Editei apenas a explicação o contexto e a pergunta está idêntica.
Comment: `tanto que a partir do *Java 9* ficaram depreciados *(O professor disse, não sei se é verdade '~')` essa parte não tinha na original. Adicionei agora na resposta.
Comment: Desculpe, eu lembrei depois que ele tinha dito isso, achei interessante para complementar a pergunta.
Comment: @FelipePaetzold Agora que já se passaram alguns dias, o que o seu professor disse depois disso?
Comment: @VictorStafusa tive as provas finais nessa época e não consegui abordá-lo para reaver o assunto, tentarei falar com ele na minha colação de grau em fevereiro, ou por meio de facebook, porém essa é uma conversa que prefiro ter pessoalmente ^^
Answer: Ele pode ter a opinião que quiser. Ele falou o por quê? Sempre tente entender o porquê, mais do que entender o que. Se ele discorda do que todo mundo faz ele deveria justificar. Algumas pessoas podem achar que é otimização prematura, mas acho muito academicismo achar isso.

Os chamados tipos primitivos possuem melhor performance. Os tipos não primitivos são referências, possuem indireção no acesso (esse conceito muda um pouco com versões mais novas do Java). A diferença de performance é enorme. Faça um teste de laço com os dois.

Possuem uma semântica esperada pela maioria das pessoas de que seu valor possui identidade própria e nem sempre fazem o que as pessoas estão acostumadas. Uma cópia não cria nova identidade.
Integer x = 1000;
Integer y = 1000;
x == y //dá falso já que as identidades são diferentes apesar dos valores serem iguais

Coloquei no GitHub para referência futura.

Os tipos "não primitivos" alocam espaço no heap e coloca pressão no coletor de lixo. Os primitivos alocam na stack e o gerenciamento é simples e rápido. Inclusive desperdiçam muita memória por causa do overhead natural que objetos possuem. Novamente isso mudou um pouco em alguns casos.

Os tipos primitivos não terão problemas de NullPointerException.

No caso específico do Java a sintaxe dos tipos primitivos é mais conveniente do que os tipos não primitivos. Os tipos primitivos não precisam usar equals(), por exemplo, mas isso pode estar mudando, pelo menos em parte.

Tem outros problemas em não usar tipos primitivos que não estou lembrando. Provavelmente o uso de não primitivos dificultam a resolução de escolha de overload de métodos.
Então é ideal sim, sempre que possível. Inclusive C# possui uma forma de criar tipos por valor próprios - que são os primitivos - e Java tem proposta para ter o mesmo nas próximas duas versões (se já não foi implementado quando ler isso), de tão útil que é. E dará confusão quando isto acontecer, porque o termo ficará ambíguo dentro do que Java sempre usou e algumas das coisas que eu disse aqui nem serão 100% verdadeiras mais, não mudará o fato, mas a definição (por isso eu tive que editar para dizer que algumas coisas mudaram).
Use a forma encaixotada apenas quando houver um motivo para isso.
Algumas pessoas gostam de pensar de forma linear, outras são mais pragmáticas e escolhem a melhor ferramenta para o trabalho.
Se ele deu ou der uma justificativa posta aqui pra gente.
Descontinuação
Isso não tem o menor cabimento. Não sei se está expressando algo diferente do que ele realmente disse, mas se isso ocorresse praticamente 100% dos códigos escritos em Java parariam de funcionar. E sinceramente, uma afirmação dessas coloca em cheque a credibilidade da pessoa.
Não só não existe a proposta de descontinuar esse recurso da linguagem, como cogitar isso seria um completo absurdo. Ao contrário, conforme eu já disse, eles devem ser ampliados em versão futura (estava previsto no Java 10, mas mudou tudo no esquema de versões, quem sabe na 15) e você poderá criar seus próprios tipos por valor que são os tipos primitivos. Veja a proposta oficial.
Veja mais em O que é considerado primitivo em uma linguagem de programação?.
Comment: @pmargreff até entendo, mas isso inviabilizaria todas as aplicações, exceto um Hello World :)
Comment: Obrigado pela resposta, vou procurá-lo e perguntar uma justificativa.
Comment: Acredito que ele tenha se confundido com o termo depreciar, é um excelente professor e entende muito bem, talvez não estivesse em um bom dia :/
Comment: Ou você pode ter entendido um pouco diferente do que ele falou? :)
Comment: Não o termo usado foi depreciado.
Comment: Mas ele pode ter usado em outro contexto, ele pode ter falado de alguma coisa específica e não de todo o conceito de tipo primitivo.
Comment: É possível, de qualquer forma, voltarei a tocar no assunto com ele.
Comment: @bigown a questão de uma versão do java não ter recursos compatíveis com anteriores não seria uma grande surpresa.
Answer: As características novas que foram adicionadas ao Java 9 são:

Jshell - Um interpretador de comandos Java.
Javadoc com HTML 5 e busca utilizando jQuery.
Simplificação da compilação cruzada (cross-compiling) para versões mais antigas no compilador.
Anotação @Deprecated melhorada.
Melhorias no controle de processos do sistema operacional (por exemplo: suporte a kill).
StackWalker para inspecionar a pilha de execução.
Fábricas de coleções imutáveis.
Cliente HTTP2 com websocket.
Nova modularização com a introdução do conceito de módulos acima do de pacotes.
Melhorias no locking.
Arquivos de propriedades UTF-8.
Implementação do protocolo de transporte DTLS.
Unicode 7 e 8, incluindo suporte a vários novos emojis.
Descontinuação das Applets.
Logging unificado da JVM.
Suporte a imagens TIFF já incluído por padrão.
Compilação ahead-of-time.
Strings compactas. No Java 9, as Strings usam internamente um array de byte (primitivos), ao invés de um array de char.
Método privados em interfaces.
Várias outras mudanças mais internas e obscuras.

Veja aqui a lista completa de features.
Em nenhum momento, ninguém falou sobre a possibilidade de se remover os tipos primitivos.
Inclusive, veja aqui no código-fonte da classe Integer, do Java 9, na linha 1101 que a classe Integer é implementada por meio de um objeto que contém um campo final do tipo int. Isso é assim desde os primórdios do Java quando ela ainda era chamada de Oak e não mudou até agora.
Além disso, se int estivesse descontinuado, então porque que o método int parseInt(String) não foi descontinuado também? A resposta é porque int não está descontinuado coisa nenhuma.
O que foi descontinuado sim foi o construtor de Integer que recebe um int como parâmetro. O motivo é que usar tal construtor é uma má prática de programação. O recomendável é usar o método Integer.valueOf(int). Casos análogos nas demais classes empacotadoras também ocorrem.
Há sim uma coisa interna na JVM onde ela consegue otimizar e simplificar alguns casos em que classes empacotadoras são usadas e transformá-las para uso de tipos primitivos. Com isso, a diferença entre a utilização de classes empacotadoras e primitivos diminui. Mas partir disso para dizer que os tipos primitivos ficarão obsoletos é bobagem.
Comment: Estive a ver o link que você refere como [lista completa de features](http://openjdk.java.net/projects/jdk9/) e não encontrei nenhuma referência a "Método privados em interfaces". Onde posso encontrá-la?
Comment: @ramaral É uma das coisas do *Milling Project Coin*, da JEP 213: http://openjdk.java.net/jeps/213 - Veja aqui a *feature request*: https://bugs.openjdk.java.net/browse/JDK-8071453
Answer: Uma outra razão importante que deve ser levada em consideração ao utilizar ou não os boxed types (Integer, Float, etc), também conhecidos por Wrappers, é que suas classes são imutáveis (assim como a classe String). Isso significa que será instanciando um novo objeto para qualquer alteração de conteúdo que a variável sofrer (exceto para inteiros na faixa -128 a 127, ver final da resposta).  Assim, se você fizer isso:
Integer i = 0;
i++;

Então um novo objeto do tipo Integer será instanciado (quando você fizer i++), da mesma forma que ocorre com qualquer String quando você muda o conteúdo da variável. Portanto, o código acima é muito mais lento do que fazer o mesmo com um tipo primitivo.
Uma outra maneira de ver este problema da imutabilidade aplicada nesse contexto:
Execute o código abaixo:
    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000000; i++) ;
    long end = System.currentTimeMillis();
    System.out.println(end - start);

Depois execute esse:
    long start = System.currentTimeMillis();
    for (Integer i = 0; i < 1000000000; i++) ;
    long end = System.currentTimeMillis();
    System.out.println(end - start);

Note que a diferença de tempo é abismal.
Os boxed types não foram introduzidos para substituir os tipos primitivos, eles foram introduzidos como um mecanismo para facilitar que tipos primitivos sejam passados como parâmetro onde se espera sua classe correspondente. Um exemplo clássico é quando precisa-se adicionar um int em uma Collection de Integer.
@VictorStafusa fez uma observação importante. Caso o inteiro esteja na faixa entre -128 a 127, então uma nova instância não será criada, pois o Java faz cache para instâncias Integer nesse intervalo. Ver essa reposta: https://pt.stackoverflow.com/a/3381/3084
Comment: "*Isso significa que será instanciando um novo objeto para qualquer alteração de conteúdo que a variável sofrer.*" - Isso é uma meia-verdade. O java mantém uma cache para instâncias de `Integer` que por padrão vai dos números de -128 até 127. Veja mais nessa resposta: http://pt.stackoverflow.com/a/3381/132
Comment: Obrigado @VictorStafusa! Já atualizei a minha resposta.
Comment: Excelente resposta!

É ideal usar tipos primitivos em Java?


Understanding row operations on a row with $0$'s for all entries except for the $\vec b$ solution vector entries

Question: In practice reducing matrices to row echelon form, I've encountered scenarios in which I have a row like row 3 in the following matrix:
$$
        \begin{bmatrix}
        1 & -3 & 3\\
        0 & 1 & 3 \\
        0 & 0 & 3\\
        \end{bmatrix}
$$
This matrix consists of input $x$ and $y$, with the third column as the solution vector.
When trying to convert matrices to echelon form (which this is now in), I may sometimes have a row like the third. It is a funny thing, as when I try to convert the matrix to reduced echelon form, and performing the row operation, say:
$$Upon \ R2 \Rightarrow R2-R3$$
The matrix becomes
$$
        \begin{bmatrix}
        1 & -3 & 3\\
        0 & 1 & 0 \\
        0 & 0 & 3\\
        \end{bmatrix}
$$
And then, for row 1 (to put zeros above the third pivot):
$$Upon \ R1 \Rightarrow R1-R3$$
$$
        \begin{bmatrix}
        1 & -3 & 0\\
        0 & 1 & 0 \\
        0 & 0 & 3\\
        \end{bmatrix}
$$
And then to scale the third pivot to $1$ I scale the matrix $R3$ to $(1/3)R3$. This feels like cheating, allow I'm merely preforming row operations. I literally could've just drawn zeros above the third pivot and changing the $3$ to a $1$ instead of going through all that hassle. In addition, I haven't a clue what that row would mean in terms of its row picture. $0x + 0y = 3$? That seems preposterous. Is me arriving to such a row in my operations a mistake? And if not, what gives with this?
To recap, my question is this: is the condition where the third row looks like way it does still allow for its matrix to have an existing reduced echelon form for it, and why does the fact that the matrix has no solution looking the way it does explain why row operations on it to put zeros above the third pivot are so trivial?
Comment: If your calculations are correct, then the only interpretation is that the system doesn't have a solution, because there is no x and y that satisfy $0x+0y=3$
Comment: This still makes it reducible, though, right? And how does that lend to explain how putting zeros above the third pivot is so trivial?
Comment: What's the original problem? I'm not sure I understand what your question is, maybe edit your original post with the original problem.
Comment: @MatheusFernandes Sure, I edited it.
Answer: I think I understand your question now.
Let's tackle this problem piece by piece, ok? First of all, you have a system of 2 variables $x$ and $y$, but you have 3 equations in the system.
Surely you remember that you only need two equations to reach a solution for two variables, so what would be the consequence of there being three equations, not two?
One consequence would be that the third line is unnecessary to solve the problem, that it's a multiple of the other lines, a linear combination of the other two lines, like this:
$$x+y=4$$
$$2x-3y=-7$$
$$3x-2y=-3$$
You see, adding the first two equations gives you the third equation.
If you applied the Guass-Jordan method to that system, you'd get the following matrix:
\begin{bmatrix}
        1 & 0 & 1\\
        0 & 1 & 3\\
        0 & 0 & 0\\
        \end{bmatrix}
Meaning, quite rightly, that $x=1$, $y=3$ and that $0x+0y=0$, which is not really that useful to us. Now, if the system only had two equations, not three, and in the end you had $0x+0y=0$, that could only mean that there infinite solutions to this problem. You see, there would be an infinite combinations of $x$ and $y$ that fit that solution.
In the example I gave you, however, there is only one solution, and the extra line is just that: extra.
In your problem, though, you seem to be confused in two parts. One is that you could just "replace" the number above the 3 in the third row with zeros. That's not really what you're doing, you are actually multiplying the third row by -1 and adding it to other rows. The thing is, the other numbers are 0, so they don't actually change anything, which I think is source of your confusion.
The second part is that pesky $0x+0y=3$. The matrix is indeed correct, that line is fine as it is, you don't have to change it. What it means here is something impossible, how can a number times 0 plus another number times 0 equal 3? The answer is, of course, that there are no numbers that can satisfy that equation, and the only conclusion is that the system has no solutions.
That's the reason people use the Gauss-Jordan method, it lets you know if a system has no solutions, one solution, or an infinite number of solutions.
Comment: I see. So I've discovered the system has no solution. I still *could* turn it into reduced row echelon form, though right? It just seems to be very easy to create $0$'s above that pivot in the quaint third row.
Comment: It's just what the method is, the only reason it's easy is because the other numbers are all $0$. Notice that that's what happens naturally whenever you use the Gauss-Jordan method, starting top to bottom, left to right, you never interfere with what you've already done, because of the zeroes.


jQuery Scrolling Length

Question: I am working with a script to scroll an element on click. It's working properly, however it either scrolls all the way up, or all the way down. I'm new to jquery, and I'm wondering how to make it scroll a little at at time. For example, clicking to scroll down once will take you down a certain length, clicking again scrolls that length again. Also, sometimes it jitters and bugs out when scrolling back up. Any insight on how to fix this is appreciated as well!
Thanks.
Code below:

Comment: If you take out the setInterval function and leave just this line ele.scrollTop( ele.scrollTop() - scroll ); it should go down just a little bit at a time. Your setInterval might be calling that line several times before it clears since your speed is set below 1 second.
Answer: You're saying you want to scroll little at a time but your code is saying scroll UNTIL mouse leaves. If you want to scroll little at a time why would you write a mouseleave which clearly stating if it's been scrolling stop now!
If you want to scroll up/down a bit on click, you should get rid of setInterval and mouseleave.
$(function() {
    var ele   = $('#scroll');
    var speed = 25, scroll = 5;

   $('#scroll-up').click(function() {
        // Scroll the element up
        ele.scrollTop( ele.scrollTop() - scroll );
    });

    $('#scroll-down').click(function() {
        ele.scrollTop( ele.scrollTop() + scroll );
    });

    $('#scroll-up, #scroll-down').bind({
        click: function(e) {
            // Prevent the default click action
            e.preventDefault();
        }
    });
});

jsfiddle

jQuery Scrolling Length


Conditional Probability Testing

Question: Two tests are given sequentially on devices. 75% of the devices tested
pass the first test. Also, 80% of the devices that passed the second test had also passed the first one. Finally, 20% that failed the second test had passed the first one.
(a) What is the probability that a given device passed the second test?
(b) Find the probability that, for a given device, the second test contradicts the first one.
(c) Calculate the probability that a given device failed the second test, knowing that it passed the first one.
My attempt:
Given:
$\Pr(A_p) = .25 $
$\Pr(A_p | B_p) = .80$
$\Pr(A_p | B_f) = .20 $
We must find I think:
(1) $\Pr(B_p) = \Pr(B_p ∩ A_p) + \Pr(B_p ∩ A_f) =\Pr(B_p | A_p)*\Pr(A_p) + \Pr(B_p | A_f)*\Pr(A_f)$
$=(.8)(.25)+??*(.75)$
(2) ????
(3) $\Pr(B_f | A_p) =\frac{\Pr(B_f ∩ A_p)}{\Pr(A_p)} = \frac{\Pr(B_f)*\Pr(A_p | B_f)}{\Pr(A_p)} = \frac{(\text{answer to (1)})*(.20)}{(.75)}$
The Questions marks are were I need some help.
Answer: Here's an answer to the first one. The others are very similar - basically all we're doing is playing around with identities and equalities a little. I'm going to rename things a little to make it easier to see why I'm doing things:
Your $A_p$ from now on will be called $A$, and your $B_p$ from now on will be called $B$. From this we can notice that $B_f$ will be $\overline{B}$. Hopefully this will make it a bit easier to see what's going on.
Let's start off using a few basic probability expressions.
$$ P(A)  = P(A \cap \overline{B}) + P(A \cap B)\\
P(A|B)P(B)=P(A\cap B) \\
P(A | \overline{B}) P(\overline{B})= P(A\cap \overline{B})$$
Add the second equation to the third:
$$P(A|B)P(B)+P(A | \overline{B}) P(\overline{B}) = P(A\cap B) +P(A\cap \overline{B}) $$
Remember $P(\overline{B})=1-P(B)$ and expand:
$$P(A|B)P(B)+P(A | \overline{B}) (1-P(B)) = P(A\cap B) +P(A\cap \overline{B})\\
P(A|B)P(B)+P(A|\overline{B})-P(A|\overline{B})P(B)=P(A\cap B) +P(A\cap \overline{B})$$
Now notice that the right side of our expression is the right side of the first identity I mentioned. So, let's substitute the other side of that identity in:
$$
P(A|B)P(B)+P(A|\overline{B})-P(A|\overline{B})P(B)=P(A)$$
And now notice that you have all of the probabilities in the equation above except for $P(B)$! So, let's plug in some numbers and solve for $P(B)$:
$$0.2-0.2P(B)+0.8P(B)=0.25 \\
P(B)=0.0833$$
Also, as a last note, for the second question you didn't write an inital expression so I'm going to assume you're not sure what it's asking for. It's saying, what is the probability that the first and second tests give different results - that would be the value for
$$P(A\cap \overline{B})+P(\overline{A}\cap B)$$
Comment: Should my givens have been conditional probabilities in the context of the problem? I am starting to double guess my self. Maybe intersections?
Comment: @Joakim: Is there anything else you are looking for in an answer?
Comment: Nope thanks much!

Conditional Probability Testing


How many ways of a cup frozen yogurt can be dressed up?

Question:
Three of $16$ toppings can be selected for dressing up a cup of frozen yogurt.  How many ways of a cup of frozen yogurt can be dressed up?
Select one:
a. $3360$
b. $560$
c. $48$
d. $45$
Comment: Welcome to MSE.  You'll get a lot more help, and fewer votes to close, if you show that you have made a real effort to solve the problem yourself.  What are your thoughts?  What have you tried?  How far did you get?  Where are you stuck?  This question is likely to be closed if you don't add more context.  Please respond by **editing the question body.**  Many people browsing questions will vote to close without reading the comments.
Comment: $42$. Also, what does this have to do with [tag:sequences-and-series]?
Answer: Note: this is assuming that the order does matter
You have $16$ possible toppings that can be selected and you can only select $3$.
When you pick your first topping, you will have $16$ options.
As you have already chosen $1$ out of these $16$ toppings, when you pick your second topping, you will have one less  option, i.e. your second topping will have $15$ options.
With this same logic, you have $14$ options for your last topping choice.
The total number of ways is given by: $16 × 15 × 14 = 3360$ options.
If order doesn't matter (i.e. combinations), then the answer is simply $16C3 = 560$ ways.
Comment: @N.F.Taussig - true...so perhaps $16C3$ = $560$ is an alternative answer.
Comment: Agreed.  That said, you should specify that the answer would be $3360$ if the order of the toppings matters and that the answer would be $560$ if the order of the toppings does not matter.  I believe the latter interpretation was intended, but the question could have made that assumption more explicit.
Comment: You should specify that you are assuming that the order of the toppings matters, which is not clear from the question.


Is it possible to make a nested ordered list in a table of contents in Jupyter Notebook using markdown?

Question: Is it possible to make a nested ordered list in a table of contents in Jupyter Notebook using markdown?
I am converting python into .ipynb using this.
My python code:
# 1. hello
#    1.1 hello
#    1.2 hello
#        1.2.1 hello
# 1. hello
#    1. hello
#       1. hello

Here is my markdown cell:
1. hello

   1.1 hello

   1.2 hello

       1.2.1 hello

1. hello

   1. hello

      1. hello

When run it produces this:

How can I have the same effect of the second list but  with numbers?
Answer: Apparently Markdown does not support this type of list. Here is a possible workaround (based on this post):
Note that list items must be escaped with \ with the exception of the nested values. This seems to be required in the notebook but not in Stack Overflow.
* 1\. hello
   * 1.1. hello
   * 1.2. hello
       * 1.2.1. hello
* 2\. hello
   * 1\. hello
      * 1.1. hello

Which produces this:

1. hello

1.1. hello
1.2. hello

1.2.1. hello

2. hello

1. hello

1.1. hello
Answer: Yes, a nested ordered list is possible in Markdown (as a code block)
To produce a code block in Markdown, simply indent every line of the block by at least 4 spaces or 1 tab.
Here is my Markdown cell:
    1. hello
        1.1 hello
        1.2 hello
            1.2.1. hello
    2. hello
        2.1. hello
            2.1.1. hello


iOS Change background image of navigation bar cancel button

Question: I have a UIImagePickerController that pulls from the camera roll.
In the navigation bar, there is a default UIBarButtonItem to cancel selecting a photo, but it does not match my Application at all!
How can I change its appearance or even hide it and then put my own button in its place in the nav bar?
This is easily done with the Back button like so:
<code>// Change the appearance of back button
UIImage *backButtonImage = [[UIImage imageNamed:@"back_button.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 10, 0, 0)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
</code>
There does not seem to be a setCancelButtonBackgroundImage method for UIBarButtonItem.
Answer: How about this one:
<code>UIImage * cancelButtonImage = [UIImage imageNamed:@"cancel_button.png"];
UIButton * cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[cancelButton setFrame:(CGRect){CGPointZero, hamburgerImage.size}];
[cancelButton setImage:cancelButtonImage forState:UIControlStateNormal];
[cancelButton addTarget:self
                 action:@selector(cancel:)
       forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem * cancelButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
[self.navigationItem setLeftBarButtonItem:cancelButtonItem];
</code>
Comment: I suppose that would work if I were to subclass UIImagePickerController. I would have to put it as the right bar button item (this is where the cancel button shows up on an ImagePickerController). Let me give it a shot and see if it works!


How to show homomorphism of this mapping?

Question: Let $ M_{2 \times 2} ( \mathbb{R} )$ be the $ \mathbb{R}$- Algebra  of all the $ 2 \times 2$- matrices with coefficients in $ \mathbb{R}$ and $ \mathbb{R}[X] $ the polynomial ring over $\mathbb{R}$ and
 If $ \mathbf{A} \in M_{2 \times 2} (\mathbb{R})$ then show that the map
$ \phi : \mathbb{R}[X] \to M_{2 \times 2} (\mathbb{R})$ defined as
$ \sum_{i=0}^d r_i X^i  \rightarrow \sum_{i=o}^d r_i \mathbf{A}^i  $ is a homomorphism of $\mathbb{R} $- algebras ?
Comment: You can think of this as an  "evaluation" homomorphism, where $X$ acts on $V$ (in this case $\mathbb R^2$ by some endomorphism (which is a two by two matrix.) There is only one nonotrivial thing to verify, given in the answer below.
Answer: To show an $\mathbb{R}$ algebra homomorphism you need to show that
$ \forall k\in \mathbb{R}$ and $p(X),q(X) \in \mathbb{R}[X]$
A) $\phi(k\cdot p(X)) = k\phi(p(X))$
B)$\phi(p(X)+q(X)) = \phi(p(X)) + \phi(q(X))$
C)$\phi(p(X) \cdot q(X)) = \phi(p(X))\cdot\phi(q(X))$
Conditions A and B are quite easy to prove and are almost immediate, for condition C you need to multiply $p(X)$ and $q(X)$ and take care of the indices. Then you will get the result instantly. Try this, if you need help then comment below.
Comment: thank you ! i got a bit confused by several definitions. But i should handle that from here :)
Comment: Yeah, I got the drift because this is a very easy question and realized that you probably need to know what is a R-algebra homomorphism :)
Comment: one more question..if $ A= \begin{pmatrix} 0 $ 1 \\  -1 $ 0\end{matrix} $. I cant determine the nernel of $ \phi $ ? Because the determinant is not zero, right?
Comment: If, I understand correctly you want to find out $\phi^{-}(0)$. Say for $p(X), \phi(p(X)=0$. So, you get a polynomial satisfied by $A$ that is zero. To find such a polynomial you use the cayley-hamilton theorem. Are you aware of it?
Comment: i mean $ A= \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix} $ and yes, i also mean the kernel :)
Comment: Why can't you find the kernel? look at $det(A - X*I)$. Here that will be $X^2 + 1$. Any polynomials with this as a factor will map to $0$ under $\phi$


How can I use a Lambda bool method within a WHERE clause?

Question: I have a method IsMatchingRegex which will return true or false. I want to check whether the Lambda property matches against the IsMatchingRegEx. If it does match, it should be added to the validItems List. How can I make the Lambda Expression work without changing the TRUE/FALSE method?
validItems = items.Where(x => x.Sub.PropertyToCheck == IsMatchingRegex(x.Sub.PropertyToCheck))

Comment: What do you mean by *whether the Lambda property matches against the IsMatchingRegEx*? What is the type of `x.Sub.PropertyToCheck`?
Answer: Why compare equality to the property? Just:
validItems = items.Where(x => IsMatchingRegex(x.Sub.PropertyToCheck));

The Where expects a predicate that given an item of the collection returns for it true or false. If you method already does that - just call it.


Como saber o número de arquivos numa pasta usando Java?

Question: Resumindo, dado um caminho que seja uma pasta do sistema, o retorno seja a quantidade de arquivos diretamente na raiz da pasta (não deve levar em consideração arquivos em subpastas). Isso seria usado numa iteração com for para acessar os arquivos para fazer um "parseamento" (reconheça algumas informações).
Answer: Crie uma instância da classe File contendo o caminho ao qual deseja-se obter o número total de arquivos.
File pasta = new File("/caminho/do/diretorio");

Agora basta criar um array com os arquivos utilizando o método listFiles() Depois iteramos sobre esse array contando o número de arquivos, sem mais delongas ficaria assim:
int contador = 0;
File pasta = new File("/caminho/do/diretorio");
File[] lista = pasta.listFiles();

for (File file : lista) {
    if (file.isFile()) {
        contador ++;
    }
}

Desse modo você não conta as pastas do diretório, caso queira descobrir o número total de arquivos contando as pastas, basta fazer lista.length
Att.
Answer: Você pode usar a interface FileFilter pra isso:
File f = new File("/home/user/pasta");

File[] files = f.listFiles(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        return pathname.isFile();
    }
});

System.out.println(files.length);

O método accept da inteface FileFilter é chamado pra cada arquivo da pasta em questão. No caso em tela é feito um teste se o item é um arquivo (isFile()), caso seja, retorna true e o arquivo entra no vetor que será retornado.
Em Java 8 você poderia lançar mão do Lambda:
File file = new File("/home/user/pasta");

Arrays.stream(file.listFiles())
        .filter(f -> f.isFile())
        .forEach(f -> System.out.println(f.getAbsolutePath()));

Onde está sendo executado o System.out.println(f.getAbsolutePath()) você poderia chamar a rotina que faz o parser do arquivo.
Para contar os arquivos faça isso:
long quantidade = Arrays.stream(file.listFiles())
        .filter(f -> f.isFile())
        .count();

Comment: Essa solução é bem interessante,isso elimina a necessidade de ter que criar um laço somente para conter os arquivos. +1


Clustering algorithm and distance function for sets

Question: I am willing to run a clustering algorithm on data records consisting in sets each one representing the features enabled at a certain time.
Is there any clustering algorithm you would recommend me to try out? In my first tests I'm experimenting with K-means, but maybe there is something more suitable.
Is there any distance function that works well with sets? I guess that there is something better than the Euclidean distance but I don't have may clue on how the better metric could look like.
Answer: You can convert set information to binary vectors (0/1 for presence/absence of a feature), then use a binary metric (e.g. Jacard, Tanimoto, Russell-Rao, Skal-Sneath, Yule metric) to cluster your data. I would try to pick a good visualization tool to explore the results and decide which algorithm/metric is the best for the data/problem.
Comment: Thanks for your answer. Do you recommend me any visualization tool?
Comment: I would not easily discount Euclidean distance, it often works pretty well even for binary data compared to other binary metrics. Which tool is appropriate for you depends very much on your data and requirements. What kind of data sets are you dealing with? How many features and objects? Do you know how many clusters are in your data?
Answer: I would start with distances such as proposed by James Li. They are sometimes known as fingerprint distances. Then, in my experience, it can be a good idea to use graph clustering, although this may depend on the number of features that you have. If this is large and dimensionality is thus large, and if 'set intersection' models data proximity well, then graph clustering is in my opinion the best approach. If the number of features is limited, graph clustering can still work well, but one should also consider the option of comparing feature vectors directly and use an algorithm such as OPTICS - perhaps you have already done that.
Comment: You have objects described by features. Suppose you use the tanimoto coefficient. You can then make a long list of triples 'A B w' where A and B are objects, and w is the tanimoto coefficient. Such a triple represents a single edge or arc, specifying the two nodes and the edge weight. Many graph clustering software packages (such as found in igraph, networkx, or mcl) will accept this format. Most graph clustering algorithms expect a similarity (e.g. tanimoto, Pearson correlation). For very dense data it may be necessary to specify a threshold value, only allowing w larger than the threshold.
Comment: Can you please explain me how I am supposed to map my feature into a graph?
Answer: There are some problems associated with k-means here.
First of all, k-means is designed for Euclidean distance. Literally. It does not require triangle inequality, but it requires that the mean minimizes variance. Which might not hold for other distance functions.
Furthermore, the mean of a binary vector -- assuming you try to represent your sets as binary vectors -- will not be a binary vector. So it doesn't map back to a set.
And that can cause artifacts. Essentially, all the means will be somewhere in the center of the data set, much closer to each other than to the actual instances. That is not really what k-means meant to do.
There are tons of distance functions for sets, and an even larger number of clustering algorithms that do not require means to minimize the variance. Try distance based clustering methods. A good starting point is Wikipedia. Hierarchical (but note that these are often implemented in $O(n^3)$, thus slow) and density based (where density is often computed by distance based estimations)
On the scientific side, try this survey:

Hans-Peter Kriegel, Peer Kröger, Jörg Sander, Arthur Zimek (2011).Density-based Clustering. WIREs Data Mining and Knowledge Discovery 1 (3): 231–240. doi:10.1002/widm.30
Comment: Wikipedia isn't bad for that, actually.
Comment: Some of the density based are grid-based. So these probably don't make a lot of sense for you. But those that use distances for density estimation should work.
Comment: Thank you for your reply. Can you please give me some more detailed reference about something to read about distance based clustering methods?
Comment: Wikipedia calls them density based clustering methods while I was looking for distance based. Thanks for the clarification.


ViewData as a hyperlink

Question: I an ASP.NET MVC we can pass some data via a ViewData and then show it on a page:
<%: ViewData["Foo"]%>

But how to make a hyperlink out of it?
Something like following:
<%: Html.ActionLink(ViewData["Foo"], "Index", "Home") %>

Answer: Cast it to string:
Html.ActionLink((string)ViewData["Foo"], "Index", "Home")

In general, however, try to avoid using ViewData and use a strongly typed ViewModel instead. (Thus, you would have avoided the problem in this question, btw).
Comment: Thanks, it works! I'll pay attention to your remark about ViewData vs ViewModel. +1

ViewData as a hyperlink


finding a maximum of 10 variables using proc sql

Question: I am using a proc sql query to extract id and marks of 5 subjects. I would like to create a new column as maximum marks for that id. i tried to use the below query. but it is giving syntax error.
proc sql;
select id, m1, m2,m3,m4,m5, max(m1-m5) as max_marks from data1;
quit;

Comment: Edit your question and provide sample data and desired results.
Answer: I think you can use largest():
proc sql;
    select id, m1, m2, m3, m4, m5,
           largest(m1, m2, m3, m4, m5) as max_marks
    from data1;
quit;

If not in proc sql, you can definitely do this with a data step.
Comment: In SAS the `LARGEST()` function requires another parameter. `MAX(m1,m2,m3)` is the same as `LARGEST(1,m1,m2,m3)`.
Answer: As @Gordon points out, it's easier if you post the syntax error you're getting. The syntax in your post is correct, but what it is doing is subtracting m5 from m1 and taking the max of that 1 value, clearly not what is wanted.
To get the maximum value across variables using the shortcut - then you need to add the keyword of.
max(of m1-m5)
* note that this method only works in a data step, not using proc sql *
Answer: Your syntax for passing a variable list to a function is wrong. To pass a variable list to a function in SAS you need to use the of keyword.  MAX(of m1-m5).
Your code is actually calculating the difference between M1 and M5 and since MAX() only has one parameter SAS sees this as a call to the SQL aggregate function MAX() and not a call to the SAS function MAX(,) for finding the max of two or more numbers.
But you cannot use variable lists in PROC SQL, so you will need to list the individual variables.
proc sql;
select id,m1,m2,m3,m4,m5
     , max(m1,m2,m3,m4,m5) as max_marks
from data1
;
quit;


How to Import Google Drive Sub-Folder URL to Google Sheet

Question: I'm trying to import the Sub-folder's (Not Files) Name & URL which is in the Main Folder to Google Sheets

I tried working on this code but it didn't help me to achieve my task.
var SS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3");

    function getFolderArray(folderId){
      var folder = DriveApp.getFolderById(folderId);
      var Folders = folder.getFolders();
      var FolderList = [];

      //Loop though Folders and add names and urls to the array
      while (folder.hasNext()){
        var Folder = Folders.next();
        var FolderName = Folder.getName();
        var FolderUrl = Folder.getUrl();
        FolderList = FolderList.concat([[FolderName, FolderUrl]]);
      }
       //See returned FolderList in a log
      //Logger.log( FolderList ) //Preview Returned Array
      return FolderList

    }

    //Prints any 2D array to a range that starts with the selected cell
    function printArrayToSelection(twoDimArr){
      var firstCell = SS.getActiveCell();
      var lastCell = firstCell.offset(twoDimArr.length - 1, twoDimArr[0].length - 1);
      var destinationRange = SS.getActiveSheet().getRange(
        firstCell.getA1Notation() + ':' + lastCell.getA1Notation());
      destinationRange.setValues(twoDimArr);

    }

    //Print the actual data
    function printFolderArray(){
      printArrayToSelection(getFolderArray('0B4-wws2P3gUhcExqWEI0VTlrNm8'));
    }

Can I know what went wrong?
Comment: If you want to handle folders, not files, then instead of using `folder.getFiles()`, use a [`FolderIterator`](https://developers.google.com/apps-script/reference/drive/folder-iterator). For each folder you can get the URL (using [`getUrl()`](https://developers.google.com/apps-script/reference/drive/folder#getUrl())) and the name.
Comment: @andrewjames I amended as you suggested, but i'm getting a error message Exception: Invalid argument: id getFolderArray @ Code.gs:10
Comment: OK - but you understand the general point I was trying to make in my comment? You were using the wrong tool for the job. Now you tried to use the right tool - but in the wrong way. And finally, the answer shows how to use the right tool in one right way. But the starting point is to look at the [documentation](https://developers.google.com/apps-script/reference/drive/drive-app) - and to notice that there are methods for handling files - and _different_ methods for handling folders. It's perfectly OK to need help about how to use those methods, of course.
Answer: Try
function listOfFoldersByID() {
  var folderid = '_______your folder ID___________'; // change FolderID
  SpreadsheetApp.getActiveSheet().clear();
  SpreadsheetApp.getActiveSheet().appendRow(["parent","folder","URL"]);
  try {
    var parentFolder =DriveApp.getFolderById(folderid);
    listSubFolders(parentFolder,parentFolder.getName());
  } catch (e) {
    Logger.log(e.toString());
  }
}

function listSubFolders(parentFolder,parent) {
  var childFolders = parentFolder.getFolders();
  while (childFolders.hasNext()) {
    var childFolder = childFolders.next();
    SpreadsheetApp.getActiveSheet().appendRow([parent,childFolder.getName(),childFolder.getUrl()]);
    listSubFolders(childFolder,parent + "|" + childFolder.getName());
  }
}

Comment: I modified my answer. Make sure your ID is the ID of a folder
Comment: I'm not a coder but I see there is no Folder ID to recognize from which folder the SUB FOLDER should be URL should be taken from. ???
Comment: Yes, I give you all the folders ... I will introduce the ID of the parent folder
Comment: Sorry for my poor coding skills, I didn't understand what you've trying say? :(
Comment: I tried to amend the variation with DriveApp.getFolderById("0B-wws2P3gUhcExqWEI0VTl8"); but I got the error TypeError: subfolder.hasNext is not a function
listerOfFolders @ Code.gs:7


How to add a custom antispam questions in User registration Form

Question: Recently I am receiving some user registration Spams...I use reCaptcha module but I want to add a anti-spam questions while User registers registration as you see in many forum sites.
Does anybody know how to do that ?...is there any module ..?
Answer: You can also customize captcha by the CAPTCHA Pack module. Here is a quote about it (from the module's project page):

... contains several CAPTCHA types for use with the CAPTCHA module. The CAPTCHA Pack module is meant to provide lightweight, yet effective alternatives for the traditional image CAPTCHA, which is undesirable in certain situation (e.g. bandwidth restrictions, cpu restrictions, accessibility constraints, etc).
Answer: You are probably looking for http://drupal.org/project/textcaptcha but if you have human spammers, they can answer any of these questions just as easily as completing a reCaptcha.
Answer: I have found the best way is to ask a question as part of your Captcha. Either of these should work:
https://www.drupal.org/project/captcha_questions
https://www.drupal.org/project/riddler
The way you foil spambots is to ask a specific type of question that can't be solved by a Google search. If a Google search can solve your question, then a spambot will defeat it.
For example, I ask the user to select a word that doesn't fit in the pattern, such as "Which word doesn't belong? Washer, Dryer, Pony, Stove, Refrigerator."
I make it obvious for humans. I don't use any terms that could be a possible answer.
You can't stop human spammers, and that's not the intent, because you are then stopping humans. You are stopping spambots.
Human spammers reveal themselves, and you get rid of them and their content quickly.
I use this on a forum and a site, and so far zero spambots have been able to register or send me a spam e-mail. Zero. On my site, I have had 560 failed attempts and zero successful attempts to register. The first link has a tool that lets you see the failed attempts.


Does a joint distribution have a unique decomposition into a marginal and conditional distribution?

Question: I believe this is true.
The argument is that if we fix $p_{XY}$, then the marginal $p_X$ is immediately fixed. So for any $q_X\neq p_X$, there exists no conditional probability distribution $Q_{Y|X}$ such that $q_X Q_{Y|X} = p_{XY}$. This implies that every joint distribution has a unique decomposition into a marginal and conditional distributions.
Is my argument correct?
Comment: You showed that the marginal distribution is unique. However, the conditional distributions $(Y\mid X=x)$ as a function of $x$ is not uniquely determined. To see this, you can consider the special case where $(X,Y)$ are jointly continuous with the density $f_{X,Y}$. Then $f_{Y\mid X=x}(y)=f_{X,Y}(x,y)/f_X(x)$ is only well-defined when $f_X(x)>0$, and you have ultimate freedom for the choice of $f_{Y\mid X=x}$ for $f_X(x)=0$ without affecting the joint distribution.
Comment: The general situation is more complicated than that. The statement in full-generality is as follows: Let $(X, Y)$ be a random vector, and let $\mu(\cdot)=\mathbf{P}(X\in\cdot)$ denote the marginal distribution of $X$. Then the conditional distribution of $Y$, given that $X=x$, namely the transition kernel $$K(\cdot \mid x)=\mathbf{P}(Y\in\cdot\mid X=x),$$ is determined $\mu$-almost everywhere (and only in that sense). In particular, modifying $x\mapsto K(\cdot\mid x)$ on a $\mu$-null set does not affect the joint distribution.
Comment: @SangchulLee good point. So the only case where the conditional distribution is not unique is when the marginal distribution has zeroes (discrete case), yes?
Comment: Makes sense, thank you!
Answer: The answer is no.
Let $(\Omega_X, \mathcal{F}_X)$ and $(\Omega_Y, \mathcal{F}_Y)$ be measurable spaces, and let $X:\Omega_X \rightarrow \mathbb{R}$ and $Y: \Omega_Y \rightarrow \mathbb{R}$ be random variables. Let $P_X$ be a probability measure on $(\Omega_X, \mathcal{F}_X)$. The joint distribution of $X$ and $Y$ is the extension of a pre-measure on the semialgebra $\{A_X \times A_Y \subset \Omega_X \times \Omega_Y: A_X \in \mathcal{F}_X,\ A_Y \in \mathcal{F}_Y \}$ given by
$$P((X,Y) \in (A_X \times A_Y)) = \int_{A_X} K(\omega_X, A_Y) P_X(\mathrm{d}\omega_X),$$
where $K:\Omega_X \times \mathcal{F}_Y \rightarrow [0,1]$ is a transition function. In other words, $K$ satisfies
(1) for each $\omega_X \in \Omega_X,$ $K(\omega_X, \cdot)$ is a probability measure on $(\Omega_Y, \mathcal{F}_Y)$; and
(2) for each $A_Y \in \mathcal{F}_Y$, $K(\cdot, A_Y)$ is measurable with respect to $\mathcal{F}_X$, where we assume $[0,1]$ has the Borel $\sigma-$algebra generated from the standard Euclidean topology.
By Caratheodory's Extension theorem, this pre-measure extends uniquely to a probability measure on $\mathcal{F}_X \times \mathcal{F}_Y.$
The "conditional distribution" to which you refer is $K$. It then follows that $K(\cdot, A_Y)$ can take arbitrary values on sets to which  $P_X$ assigns measure $0$.
Source: A Probability Path by Sidney Resnick.
Comment: Yes. I included the background because the original poster is probably not familiar.
Comment: So, I guess your answer is essentially a rephrasing of the fact that the conditional distribution $(Y\mid X=x)$ is determined only $\mathbf{P}(X\in\mathrm{d}x)$-almost surely.


If you take a dominant 7th chord and replace the 5th for a major 6th, what do you get?

Question: I know that in dominant 7th chords the 5th is sometimes omitted but what about if you replace the 5th with a major 6th. Does that make it another chord or is it still a dominant 7 chord? Are there any other options for what chord it could possibly be?
Comment: It would be close to a 13th chord.
Answer: A 13th chord consists of the notes {1, 3, 5, b7, 9, 11, 13}, which is the entire scale in 3rds (mixolydian if you start on 1, Ionian if you start on 5).  We typically do not play all the notes and a common voicing for the 13th chord is {1, 3, b7, 13}.  The 13th is the octave of the 6th so I'd say this is a 13th chord.  You would want to look at all other ordering of these notes to see if it is another chord.  There are multiple chords with identical notes, for example C6 = {C, E, G, A} and A-7 = {A, C, E, G}.  In this case I don't see anything obvious that would make this sound like another chord.
Comment: Saying that 11 is a part of 13 chord is misleading. At best you can say that 11 is a part of chord-scale.
Comment: @user1079505 - 11 is *theoretically* part of a 13 chord - the idea is use 1,3,5,7,9,11,13, which is great in theory, rubbish in practice!
Comment: @Tim what kind of theory are you referring to? Can you point to a reputable source saying that?
Comment: @user1079505 - not checked it out, but thought that any over 7 needed the other numbers as well - in theory. Homework time..!
Comment: It is a basic definition 13th is 1, 3, 5, b7, 9, 11, 13.  And one does sometimes use the 11th.  It depends on context
Comment: @user1079505, here is a reference, Jazz Guitar Method by Mike Christiansen page 84 chord construction table.  It clearly states 1, 3, 5, b7, 9, 11, 13 as the 13th chord formula.  And I know it is not the only source (just the one on my stand right now).  Clearly without a 7 string guitar one cannot hope to play it all so we pick and choose.  I think the critical notes are (1, 3, b7, 13), maybe (1, 3, b7, 9, 13) but that does not mean the 11th is not part of the definition.
Comment: So on a 7-string guitar 11 magically starts to fit, while on 6 string guitar it doesn't? That's nonsense. Building chords as stack of thirds might look pleasing on paper, but that's not how works. 13 chord is a quite typical dominant chord sound, while adding 11 moves it to sus or quartal tonality, which is a completely different sound.
Comment: @user1079505, your vicious hostility is uncalled for.
Answer: The chord definitely still fulfills the function of a dominant, since it contains all the characteristic notes. Compare this well-known example in Chopin's first Ballade:

Whether to call this a 13th chord or not is a question of which theoretical school you adhere to. Personally I find it much easier to conceive of d + e + g# + c# as a straighforward dominant chord with a sustained appoggiatura tone.
Answer: So now, you have notes 1,3,6 and ♭7. root C - C E A B♭. It's commonly a way of playing what I call C13. That 6 becomes another 'stacked third' further up the pile.  With chords which have a number greater than 7 appended, such as C9, C11, C13, often the 9 and/or 11 is omitted (although the 7 must be retained). The 5 is usually the first to go - particularly on guitar, as there aren't enough strings, or reachable places to play all the notes anyway.
However, you ask if it's still a dominant chord. Of course (assuming the 7 is flat). That ♭7 is what gets it called dominant - although the fact that it's built using the dominant note from the key helps.However, it won't be called 'dominant seventh'. It isn't a seventh chord any more, there's a 13 in there. So it's called dominant thirteenth.
Answer: You've still got the dominant root note, the 3rd of the chord, and the 7th (those last two forming the tritone which is the main 'engine' of a functional dom7 chord).
The 5th is a relatively inactive filler which is why, as you say, it is considered optional.   A 6th will probably be heard as a 13th  (octave shifts don't change the numbering).  So we end up with a dominant 13th chord.
If the 6th/13th is just in the melody, we might still label the chord as 'G7'.   If it's considered an integral part of the harmony we would call it 'G13'.


The best way to convert List to ObservableCollection

Question: I have got List<Object> where the Object has a lot of childs List<Object> around 4-6 levels.
Now I have to bind it to WPF TreeView... :(
Which the best way to convert it into ObservableCollection<Object> is?
Comment: Why not just make them `ObservableCollection` in the first place? When working with WPF, its important to get the data layer right, and if you're ever displaying a list that can change in the UI, you should always use an `ObservableCollection` instead of a `List`
Comment: @Rachel Correct. The first place is RIA Services. I don't know if it is possible to do it...
Answer: Assuming you mean ObservableCollection<T>, if you wanted the List directly to the ObservableCollection as-is, just use the constructor:
var oc = new ObservableCollection<Object>(yourListOfObject);

Now, if you're wanting to unwind each of those, you would need to do some work to collapse them into a single ObservableCollection<T>.
Comment: If I created a public class called `Computer` and have a public string `Name` getter-setter inside there for my OC, and then I have a `List lstComputers`, it tells me I `cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.List'`.
Comment: Actually I found out how to do it.  You can't have mismatched types.
Answer: One part of the answer is to use Reactive Extensions (Rx). You can get it from NuGet and it's developed by Microsoft. With the help of it you can simply say: myListCollection.ToObservable();
If your child collections always are in a node with the same name you could use a while(item.Collection != null || item.Collection.Count == 0) and put the ToObservable() within the loop
Comment: This is such a overkill
Answer: I assume you're talking about ObservableCollection.  To answer simply, you can use the ctor:
List<Object> myList = GetList();
new ObservableCollection<Object>(myList);

However, I think there is some work left to be done in terms of organizing your information hierarchically.
Comment: List is not a common usage of generics.  Start with a review of generics here: http://stackoverflow.com/questions/155260/what-is-the-syntax-within-c-sharp
Comment: In addition, here is a good blog post I just googled that details binding hierarchical data to a WPF TreeView: http://www.mattlong.com.au/?p=37
Answer: Assuming you have a node class defined like so:
public class Node
{
    public ICollection<Node> Children { get; set; }
}

You can use recursion to convert List<Node> collections, at any level of depth:
public static ObservableCollection<Node> ToObservableRecursive(ICollection<Node> nodes)
{
    foreach (Node node in nodes)
        if (node.Children != null)
            node.Children = ToObservableRecursive(node.Children);

    return new ObservableCollection<Node>(nodes);
}

Comment: If I created a public class called `Computer` and have a public string `Name` getter-setter inside there for my OC, and then I have a `List lstComputers`, it tells me I `cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.List'`
Comment: Actually I found out how to do it.  You can't have mismatched types.
Answer: Do you mean ObservableCollection? If you want the child level Lists to be observable also then you will need to traverse the tree and change items as necessary or add each item separately to begin with.
Answer: You cannot do any of the solutions listed here until your types are the same!  If your list or ICollection or IEnumerable is of type string, for example, but your ObservableCollection needs to be of type Nodes or Computers or something else, you have to get the List into that type, first!  I wasted so much time on these other bogus, simplified "solutions" that are NOT solutions because they do not explain this or take this factor into account.
Say this is your ObservableCollection:
public class Computer
{
    public string Name { get; set; }
}

Pretty standard, right?  You'd probably end up replacing Computer with any number of things in any number of projects.
If you then get a list of computer names in a List<string> called lstComputers, you CANNOT just convert that using:
var oc = new ObservableCollection<Computer>(lstComputers);

It will say your types are mismatched and cannot be converted from one to the other because you are trying to shove a List<string> into an ObservableCollection<Computer>.  Square peg in a round hole.
Instead, in your function for getting the computer names, you have to add them all "special-like":
public static List<Computer> NetworkComputers()
{
    List<Computer> lstComputers = new List<Computer>();
    DirectoryEntry root = new DirectoryEntry("WinNT:");
    foreach (DirectoryEntry computers in root.Children)
    {
        foreach (DirectoryEntry computer in computers.Children)
        {
            if (computer.Name != "Schema" && computer.SchemaClassName == "Computer")
            {
                lstComputers.Add(new Computer() { Name = computer.Name });
            }
        }
    }
}

Only because we used that line lstComputers.Add(new Computer() { Name = computer.Name }); and are returning the List<Computer> and not List<string> can we now put it into our ObservableCollection<Computer>.
If you missed the boat and can't do it like this from the start, this thread talks about other ways you might be able to do your conversion:
convert a list of objects from one type to another using lambda expression
So once you have it in a List<Computer>, only then you can do:
List<Computer> lstComputers = NetworkComputers();
var oc = new ObservableCollection<Computer>(lstComputers);


MySQL lost connection error on mysqldump

Question: I have a 1 TB MySQL database that I'd like to dump and reload.  Most of the data is in one table.  A lot of data has been deleted, so I'm pretty sure if I dump it with mysql, rebuild the database, then reload it the total size will be smaller.
I'm dumping the data with this command:
mysqldump  -uroot -pXXX  mydb | gzip -c > data.sql.gz

I get this error
 mysqldump: Error 2013: Lost connection to MySQL server during query when dumping table `MY_TABLE` at row: 596089342

I've tried many variations, including increasing the packet size, doing single translation and going over TCP/IP instead of local socket.
mysqldump  -uroot -pXXX -h 127.0.0.1 --max-allowed-packet=1024M  --single-transaction mydb | gzip -c > data.sql.gz

Finally, I even ran the command going to /dev/null to make sure it wasn't gzip.  All permutations produce the same error.
mysqldump  -uroot -pXXX -h 127.0.0.1 mydb > /dev/null

Here's some of the settings in my.cnf
max_allowed_packet = 1G
interactive_timeout = 600
wait_timeout = 600
net_read_timeout=600
net_write_timeout=600
connect_timeout=600

One other odd thing is that the dump always stops on the same place.  Approximately 6GB of gzipped data and at approximately the same record.  When I do ls -l the file size is always identical.
I'm stumped.  Any suggestions for next steps?
For the record, this is Mysql 5.1.58 running on Ubuntu 11.10
WILL
Comment: Try: restoring `interactive_timeout` and `wait_timeout` to their default values, or using a named pipe.
Comment: Are there any errors in the server log? Did you try a dump via phpmyadmin?
Comment: This is a linux server.  What is a pipe?  (isn't that Windows only).
Comment: no errors in the log.
Comment: I tried again after restoring interactive_timeout  and wait_timeout  to their default values and got the same result.
Answer: In the end, it looks like I had a data corruption.  I had copied two volumes (EC2 ebs) that were linked with LVM.  I may not have frozen the volume properly when making the copy and I suspect they were not properly synchronized.  I started from my original volumes, ran the procedure again, carefully freezing the xfs volume before taking the EC2 snapshot, then loading the copies onto my new server and it worked fine.
Answer: Have you tried using the socket file, to bypass the TCP/IP layer e.g.
# Find the socket file e.g.
$ grep  "^socket"  /etc/my.cnf
socket      = /var/lib/mysql/mysql.sock
#
# Plug the filename into the mysqldump
$ mysqldump  --socket=/var/lib/mysql/mysql.sock -uroot mydb | gzip -c > data.sql.gz

Comment: What bug report?
Comment: "bug" is a hyperlink (techie internet term, invented in the 1980's), if you "click" the word you'll be taken to a different web page :o)
Comment: Same issue.
 mysqldump --socket=/var/run/mysqld/mysqld.sock mydb

produces

mysqldump: Got error: 2013: Lost connection to MySQL server during query when retrieving data from server
Comment: I's suggest you add your issue to the following [bug](http://bugs.mysql.com/bug.php?id=46103) report, as you've still got the issue.
Comment: Didn't notice.  They should ban hyperlinks without underlines.
Comment: SO css / styles changed. `bug` has an underline now :)
Answer: I got the same error, the server had no more ram available and no swap.
Mysqldump was eating all ram, so i decreased  memory-related parameters in my.ini as worked


fluentbit - exclude specific kubernetes annotation from exported log metadata

Question: I have some pods that contain an annotation with a very long value. I feel this is causing issues when fluentbit attempts to export the logs to elasticsearch. I don't need this particular annotation to be exported with the log metadata.
I've tried to prevent this annotation from being exported by turning off annotations in the fluentbit kubernetses filter like so:
<code>        [FILTER]
            Name                kubernetes
            Match               kube.*
            Merge_Log           On
            Keep_Log            Off
            K8S-Logging.Parser  On
            K8S-Logging.Exclude On
            Annotations         Off
</code>
However, this causes us other issues, as we need to some of the other annotations the filter is removing.
So my question is, is there a way to exclude a single/specific annotation from the metadata, rather than exclude all the annotations?
Answer: Use these filters:

lift "kubernetes" metadata one level up
remove the data that you don't need
put the remaining data back into "kubernetes"

<code>[FILTER]
    Name                nest
    Match               application.*
    Operation           lift
    Nested_under        kubernetes
    Add_prefix          Kube.

[FILTER]
    Name                modify
    Match               application.*
    Remove              Kube.annotation.<Metadata_1>
    Remove              Kube.annotation.<Metadata_2>
    Remove              Kube.annotation.<Metadata_3>

[FILTER]
    Name                nest
    Match               application.*
    Operation           nest
    Wildcard            Kube.*
    Nested_under        kubernetes
    Remove_prefix       Kube.
</code>


Fast find in list of lists

Question: Consider the following function:
import Data.List (find)
findInLists items = map $ find (`elem` items)

Which can be called like so with the following result:
findInLists [2,3] [[1,2], [1,3,2], [4, -2, 8]] -> [Just 2, Just 3, Nothing]

The first argument can be assumed to be sorted, but the second argument will not be sorted.
If n is the total number of items in all lists to be searched (in this particular case, 7, as the search stops once an item is found) and k is the number of items to search for, I believe the runtime of this function will be O(n * k). However, this is bad for large k when n is also large.
I would like the runtime to be more like O(n * log k) + O(k * log k) or better if possible. What's the best way to do this?
Comment: Please clarify:  If there are two matches, such as in `findInLists [2,3] [[1,3,2]]`, it is OK to return `[Just 2]`, or must it be `[Just 3]`?  In other words, do you require the first match, or just to find any match in the list?
Answer: Stick the items in a Set and use member.
Answer: import Data.Set (fromList,member)
import Data.List
findInLists :: Ord a => [a] -> [[a]] -> [Maybe a]
findInLists xs = map $ find $ flip member $ fromList xs

fromList xs will take O(k log k) one time and each find will take O(log k) in worst case. So total time for n elements = O(n log k) + O(k log k) worst case.

Fast find in list of lists


Rails use of httparty to parse the JSON to external URL

Question: In a Rails application, a user has to be redirected to an external site for external processing.  The controller generates a valid JSON string and a set of headers:
@result = HTTParty.post(
  "https://some-test.supertester.com/checkout",
  :verify => false,
  :body => JSON.parse(@payment).to_json,
  headers: {
    'Content-Type' => 'application/json',
    'X-TimeStamp' => "#{Time.now.to_i}",
    'X-API-ID:' => "#{@api_id}",
    'X-API-Signature:' => "#{@api_signature}"
  },
  timeout: 20
)

This action is launched by the user via:
<%= link_to t('proceed'), data_url_cart_path(id: @existing_cart.id), class: 'button' %>

whose controller action generates the above JSON string and call.
However, Rails tries to respond to this action with a view with the same action's name (even generating a blank with format.json { head :no_content }), when the goal is to redirect the user to the aforementioned URL with the defined headers and payload.
How can this be achieved?
Comment: I think the problem is your approach. If you need to send headers to this URL, you can not redirect user to it, since you are not able to send headers when redirecting.
Answer: HTTParty is making a network request with a json payload. In this situation @response will be the response from the network request. If you call puts @response.parsed_response.inspect you will see the json returned with said response in the terminal window running your Rails server.
I think you may not need to redirect the user to an external site at all, but instead check the response to see if the action you were trying to make was successful and handle it in your own application.


spring aspect being applied outside of app context (in stubbed out unit test)

Question: Here's a weird one. I've got a few tests failing because an aspect is being applied, so an autowired service is null, bad things ensue. The issue is that I can't understand how the aspect is even being applied, since in the test I construct the object under test with new.
<code>@RunWith(MockitoJUnitRunner.class)
public class TheControllerTest {

    @Spy
    private TheController controller = new TheController();

    @Mock
    private HttpServletRequest request;

    @Mock
    private ConfigService configService;
  ....

@Before
public void setup() {
    controller.setConfigService(configService);
....
    }

@Test
public void testGetAccountsList() throws Exception {
Mockito.when(accountService.getAllAccounts()).thenReturn(Arrays.asList(account1,     account2));

    Map<String, Object> result = controller.getAccountsList(request);
...
}
}
</code>
I'm obviously omitting plenty of code, but really, I just don't understand how, given how controller is instantiated, it could have had the advice applied.
Answer: One possible reason could be if you are running this in Eclipse - in a project with ajbuilder enabled, even if you are explicitly expecting Spring AOP through dynamic proxies, ajbuilder would actually perform compile team weaving, and hence you would see advice enhanced classes even using normal "new". Can you please check this, the fix would be to disable "ajbuilder" - here is one reference - JUnit weaving wrong Spring AOP Bean
Comment: I don't see any reference to ajbuilder in the properties for this project, but this is a maven project, not being built (exclusively) in eclipse. In the pom.xml for the project, I do see a dependency for the aspectjweaver. Could that be related?
Comment: No, I doubt this could be it, do you have `aspectj-maven-plugin` in your pom.xml by any chance.