TS vs TRS cables to connect mixer to audio interface

Question: I understand that TS cables are mono and TRS cables are capable of delivering a stereo signal. However, if a jack supports TRS, could I still run a TS cable to it (and if so, what happens), and if a jack supports TS and I run a TRS cable to it, what happens?
Edit: here's my context: I have a mixing board (a yamaha mg124cx) with separate L and R channel outputs that I need to run to my audio interface (a Focusrite Scarlett 2i2), which has two TRS inputs. Should I be running TS cables from the mixer's L and R to the two different audio interface inputs, or should I merge the output of my mixing board to be run on a TRS cable?
Comment: It is important to know the specific use of the cable and the way a TRS cable reacts to a mono output will vary depending on what it is input to as well as the parameters of the specific equipment on each end. There are situations where you can use a TRS cable or a TS cable and either will work the same.  Do you have a specific application in mind?  The answer to your general question can only be "it depends ..."!
Comment: Tarun, thanks for the details; as you noted, specific music hardware is on-topic.  I've cleaned up the comments a bit (please take further scope discussion to Meta).
Answer: TRS (Tip-Ring-Sleeve) is the name often given to the connector, rather than the cable as such, though of course they would usually be used with a 3-conductor cable. This could be used for stereo purposes, but it could also be used for other things : e.g. as a mono send/mono return for an insert effect (like a compressor on one channel of a mixer), or as a balanced signal carrier.
If you had a stereo output socket (TRS) and plugged in a mono plug with only the tip and the sleeve, you'd be grounding one of the channels (probably the right, which is usually wired to the ring) which is not a great thing to do (https://sound.stackexchange.com/questions/25577/stereo-and-mono-cables-and-jacks-what-happens-when-you-cross-them), and you'd only get the left channel coming over the cable. If you were to plug a stereo (TRS) plug into a mono (TS or TR) socket, you'd get your mono signal coming down either the left or the right channel (probably the left, as this is usually the tip), but you'd leave your right input channel 'floating', which is not ideal.
When it comes to balanced or unbalanced audio, many sockets are designed so that plugging in a TS jack gives you an unbalanced connection, while a TRS allows a balanced connection to whatever's at the other end of the cable.
In summary, you're unlikely to do any harm mixing up stereo and mono cables, but it's a good idea to know the contact arrangement in the equipment you're plugging into so you can use it as designed.
EDIT re. your equipment
Yamaha mg124cx : http://www.yamahacommercialaudiosystems.com/downloads/manuals/mixers/mg/mg124cx_manual.pdf
Focusrite Scarlett 2i2 : http://d3se566zfvnmhf.cloudfront.net/sites/default/files/focusrite/downloads/7317/scarlett-2i2-user-guide-v2.pdf
The Yamaha manual says it has "TRS phone-jack type balanced outputs"; the Focusrite manual says "Set the LINE/INST switch next to the socket...to LINE if you are connecting a line level source such as the balanced output of a stage piano via a 3-pole (TRS) jack." (but for 'stage piano' there, we can read 'mixer')
So my guess is you want to get 2 TRS cables, one for left and one for right, and with a bit of luck that should give you balanced, stereo connection.
Comment: In audio interfaces, sleeve is usually grounded, so connecting ring to sleeve will ground the ring, not bridge the channels.
Comment: @BraddSzonye thanks for the heads up. Any better now? There's a similar question at http://sound.stackexchange.com/questions/25577/stereo-and-mono-cables-and-jacks-what-happens-when-you-cross-them, but I'm not sure if that's quite spot on!
Answer: As I am sure you are aware - the TRS connector tip is capable of transmitting a stereo signal (separate left and right signal) from a stereo output jack to a stereo input. The output jack must be wired as a TRS output in order to route the separate stereo channels into the appropriate wires inside the cable.  You will find this scenario on stereo headphones.
In many cases a TRS connector is used on a two core balanced cable to deliver a balanced signal which will reduce electrical interference and hum instead of an unbalanced signal form a single core cable and TS connector.  In mixer and interface applications, this is more commonly true than using the TRS tipped cable to transmit a stereo signal.
For the application you described, it sounds as if you wish to send the two individual outputs from the two channels on your mixer as a stereo (left and right) signal into your audio interface. I am sure you want the stereo signal to be routed into your interface so that it can then be routed into your computer and maintain the stereo separation selected on your mixer.
To do this properly, you will need to understand how your particular interface works and then use the appropriate cable to connect it. An audio interface will output into your computer where your DAW software can render two channels in stereo.   To input in stereo you would send each stereo channel (left and right) into a separate input on the interface.
If your interface has a mono/stereo selector switch, then you can use one channel as the left input and the other as the right by selecting stereo mode.
Merging the left and right output from your mixer into a single plug in your interface is not likely to accomplish what you want.  If your mixer has balanced TRS output jacks (like a separate balanced out for each side of a stereo output) and your interface will accept a balanced input through a TRS plug, your best bet is to use a two core balanced cable with a TRS plug on each end.
Good luck.
EDIT: The answers that were edited or added after you provided specifics on your equipment are on point and provide good information specific to your equipment.  However I am leaving my answer as a general answer for future visitors who may have different equipment.
Comment: "Many audio interface devices have two channels but each channel is a capable of processing a stereo signal if the signal is delivered through a TRS connector plug."

I think you'll need to give some examples of that!
Comment: You may be right (as you so often are).  Some interfaces will have a stereo line in jack to accept input from an mp3 player on a TRS plug, but can't find example of a dual purpose smart plug as envisioned. Edited answer to remove erroneous assumption.  Thanks again.
Answer: Now you've asked a specific question, you can have a specific answer!
Your yamaha mg124cx has its stereo main outputs arranged as a pair of balanced TRS 1/4" jacks.  (The outputs are duplicated on a pair of balanced XLR sockets, which carry an identical electrical signal.  But we don't need to worry about that for now.)
Your Focusrite Scarlett 2i2 has combo jacks, accepting a microphone signal on an XLR plug or a Line input on a TRS jack.  You will use the jack inputs.
If you use a pair of 3-conductor cables, with TRS jack plugs, you will get a balanced connection.  If you use a 2-conductor cable with TS jack plugs you will get an unbalanced one.  The balanced option has theoretical advantages.  In practice, I can confidently state there will be no discernable difference.
There is no way of using a single "stereo" cable.
(As well as the connection to the Focusrite Scarlett 2i2, you will have to decide where to attach your monitor speakers.  It may well be that you decide to use the Main Out for them, feed the audio interface from the Group sends.)
Answer: If it's a headphone cable, or a mini-jack cable connecting domestic equipment to a computer, a TRS connection may be stereo.  In a home recording setup a 1/4" TRS plug will much more likely be carrying a balanced mono signal.  In the pro world, you're probably see XLR connectors, one for mono, two for stereo.
Point being, TRS is TRS. It isn't "stereo".
Comment: Very true - TRS does not mean stereo.  Good point.  But it is capable of delivering a stereo signal to an output designed to receive or transmit a stereo signal.  Some devices will react to the TRS in a way that assumes stereo.    But not all.  You are correct as well about XLR connectors.
Comment: I edit the question based on your brilliant observation about the mis stated assumption in the question.  Good one.


Breakpoint will not be hit in silverlight running on azure dev fabric

Question: I'm building application using WCF RIA services and silverlight running on azure dev fabric. I have a solution with silverlight client projects, a Web client project and WCF projects.  I placed breakpoints in silverlight project and WCF project (in app.xaml.cs) so I can step thru the code on both side. I break in my WCF code but I can't jump in the silverlight code.  When I looked at the silverlight breakpoint while debugging, the red dot displays an exclamation mark and this message: "The breakpoint will not currently be hit".
I've done several things to solve this:

Made sure that the ClientBin folder contains the correct .xap file.
The folder contains the correct xap.
Checked the solution if it was in release mode, but apparently I was
in Debug mode
Checked if silverlight debugging is enabled in web site, yes it was
enabled. I'm able to debug the silverlight running on separate
instance (not in azure).
Deleted bin/debug and or bin/obj folder but still no good
Deleted the ClientBin folder on silverlight's web role end
point
Deleted the source codes and then retrieve them again from source
control to check if there's change in source control, still no good.
Apparently the solution in other developer's workstation works fine, I'm
the only one having this problem.
Reset the iis using iisreset, still nothing good happened
Cleared the browser's cache (I'm using IE9), nothing good
happened.

Anyone ever met this situation? Any answer other than re-installing would be appreciated.
Comment: Seems like you've already tried a lot ;) Can you try with another browser. Can you also check the output window of your Debugging VS instance.
Comment: I tried with firefox 4 (already configured for silverlight debugging), still nothing happened to the breakpoints.
Output window showed nothing when debugging instance.
Comment: I'm sure you've done it (you've done everything else already), but have you done a full reboot of the machine?
Comment: I did full reboot my workstation. Still nothing good happens.
Answer: I tried to reproduce this case on new solution with new azure, silverlight and wcf project and everything works fine. There was no problem in debugging either silverlight or wcf project.
Thus, there is nothing wrong with my VS or browser setting.
I tried to use a copy of the other developer's solution and there's no trouble in debugging. I have no idea why such thing could happens because the solution is basically the same (All of the csproj.user and suo files are not checked in to source control.)
Answer: Go to your Solution >> Properties >> Set the silverlight project as the startup project.


Samba + file/directories that end with a period

Question: I have a samba share and it shows a weird filename in windows whenever a file or directory named ends in space or period
If I do
mkdir temp.

will look like TB5AMV~R in windows.
Is there a fix for this?
UPDATE: my config:
# This is the main Samba configuration file. You should read the
# smb.conf(5) manual page in order to understand the options listed
# here. Samba has a huge number of configurable options (perhaps too
# many!) most of which are not shown in this example
#
# Any line which starts with a ; (semi-colon) or a # (hash)
# is a comment and is ignored. In this example we will use a #
# for commentry and a ; for parts of the config file that you
# may wish to enable
#
# NOTE: Whenever you modify this file you should run the command "testparm"
# to check that you have not made any basic syntactic errors.
#
#======================= Global Settings =====================================
[global]

        smb ports = 445
        workgroup = WORKGROUP
        server string =

        # There was a recent security issue in Samba (Feb 5 2010), a claimed
        # zero-day exploit that exploited an insecure default configuration.
        # According to an Ubuntu Forums post on the topic, the "wide links" option
        # now defaults to no.

        follow symlinks = yes
        wide links = yes
        unix extensions = no

        # added by roy for win7 - 2009-09-09
        client ntlmv2 auth = yes

        # added by roy for recycle bin
        vfs object = recycle
        recycle:repository = .RecycleBin
        recycle:keeptree = yes
        recycle:exclude = *.tmp, *~, *.bak

        printcap name = /etc/printcap
        load printers = no

        cups options = raw

        log file = /var/log/samba/%m.log
        max log size = 50

        security = user

        socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192

        dns proxy = no

#============================ Share Definitions ==============================
[homes]
   comment = Home Directories
   browseable = yes
   writable = yes

[printers]
   comment = All Printers
   path = /var/spool/samba
   browseable = no
   guest ok = no
   writable = no
   printable = yes

Comment: Please post your smb.conf.
Answer: Samba doesn't consider temp. to be a valid DOS filename so it is mangling it as per the name mangling rules which defaults to on. You can turn name mangling off by setting
mangled names = no
in your smb.conf file followed by restarting samba. Name mangling can be specified as a global or service specific parameter.
Comment: Thanks for the reply, it kinda worked, the directory name does show properly, but now windows explorer won't open the directory named like this.  This is the error I get: **`Location is not available`** `L:\\test. refers to a location that is unavailable. It could be on a hard drive on this computer, or on a network. Check to make sure that the disk is properly inserted, or that you are connected to the Internet or your network, and then try again. If it still cannot be located, the information might have been moved to a different location.`
Comment: @Roy Rico: Then that's a different question to which the answer is (probably) don't do it. There is a `strip dot` directive but I don't know if it will do what you want.


Suppose that $rank(x)=\alpha, rank(y)=\beta, and \alpha \leq \beta$, prove that $rank(x \cup y)=\beta$

Question: I know that from definition, rank(A)=⋃{(rank(x))+:x∈A} .So that for the $rank (x \cup y )$, it is equal to $sup\{rank(x),rank(y)\}$ which is $\beta$. But I have no idea about how to formally prove it.  I have checked another link:Proving $rank(\wp(x)) = rank(x)^+$ also on rank, but still confusing. Can anybody give me some hints or ideas?
Answer: Note $z\in\operatorname{rank}(A)\iff \exists t\in A\colon z\in\operatorname{rank}(t)^+$.
Thus
$$ \begin{align}z\in\operatorname{rank}(x\cup y)&\iff \exists t\in x\cup y\colon z\in \operatorname{rank}(t)^+\\
&\iff \exists t\in x\colon z\in \operatorname{rank}(t)^+\lor \exists t\in y\colon z\in \operatorname{rank}(t)^+\\
&\iff z\in \operatorname{rank}(x)\lor z\in \operatorname{rank}(y)\\
&\iff z\in \operatorname{rank}(x)\cup \operatorname{rank}(y)\end{align}$$
In other words, rank commutes with finite union (in fact, with arbitrary union).
We conclude
$$ \operatorname{rank}(x\cup y)=\operatorname{rank}(x)\cup \operatorname{rank}(y)=\alpha\cup \beta=\beta.$$


Make a jquery icon visible using on keyup event

Question: Stumped at this part. I have a simple html input, and a jquery ui icon. What I want to do is have the icon hidden untill a "keyup" event of some sort is fired on the html input. Currently have the css property of the icon set to  display:none;, but how would I use javascript to display this after some text is put into the html input?

--Here's my code

<input id="solo1" />

Answer: Try something like below
$("#solo1").keypress(function(){
    $("#saveButton").show();
});

Answer: You could use Javascript, or jQuery...first, a Javascript example:
<input id="solo1" onKeyUp="document.getElementById('saveButton').style.display = 'block';" />

Preferably, in jQuery, and this is all Javascript now:
$("#solo1").keyup(function(){
    $("#saveButton").show();
});


How to use WKhtmltopdf Library without using executable

Question: In ruby on rails project.
I am using PDFKit gem for generating pdf reports
PDFKit uses wkhtmltopdf executable which is to be installed on the machine .

And next step to give the path of the executable .
I dont want  to use the executable file .because if i use it how to deploy it on server .
the server will need to install it on its local and give the path.

Is it possible to use only library????
Answer: The executable is used to wrap the underlying Qt app, so it's technically possible to wrap the library in a gem (using ffi or some other similar lib) but I never heard anybody doing it.
I'm myself bundling the executable with my Rails app, to ship both at once when I deploy (even on Heroku).
To do the same, you can put the binary file in directory (you can call it bin), and configure PDFKit to get the executable where it's at using PDFKit.configure in an initializer for instance (you might wanna check the README).


$n\times n$ matrix with all eigenvalues equal to $1$ or $0$. Does a conjugated matrix with only $1$'s and $0$'s exist?

Question: Let $A$ be an $n\times n$ matrix with all eigenvalues equal to $1$ or $0$.  Is there a conjugated matrix $B = XAX^{-1}$ for some $X$ such that all the elements equal either $1$ or $0$?
My thoughts so far:
$A$ is not necessarily positive semi-definite..
Given the assumption that $A$ has only eigenvalues that are $0$ or $1$ doesn't really imply anything obvious that we can use.  I don't see why there would be a conjugated matrix with all the elements equal either to $1$ or $0$.
So I'm currently trying to come up with a counterexample...
Edit: Actually, a counterexample might be the wrong path to take.  The question is just asking for the existence of such a matrix...
Thanks in advance,
Answer: Hint: Jordan normal form. Note that since every field contains $1$ and $0$, the Jordan form of your $A$ always exists, even if the underlying field is not algebraically closed.
Comment: So, put A into Jordan form, which is to say A's eigenvalues of 1's and 0's are on the diagonal of a conjugated matrix, appearing as many times on the diagonal as their algebraic multiplicity.  Then "at most" we have some stuff above the diagonal of this conjugated matrix, namely 1's above the diagonal.  After that (and also below the diagonal), this conjugated matrix contains all zeros.  A Jordan normal form of A - or any matrix - always has this form, which is a sum of a diagonal matrix and a nilpotent matrix.  Hmm...what do you think, @user1551?  Feel to comment and correct me :)  Thanks...
Comment: @LebronJames In general, the Jordan form of a matrix $A$ will have the eigenvalues of $A$ on the diagonal, some 0s and 1s on the super-diagonal and zeros everywhere else. But there's a catch: the Jordan form always exists *over the algebraic closure of the ground field*, but not necessarily over the original field. For example, if a real matrix $A$ has some non real eigenvalues, then obviously you cannot find a real matrix $X$ such that $XAX^{-1}$ (which is real, because products of real matrices are real) is equal to the Jordan form of $A$ (which contains non real entries).
Comment: You are lucky, however, because the eigenvalues of $A$ in *your* case are members of the ground field. So, there always exist some $X$, whose entries lie in the ground field, such that $XAX^{-1}$ is the Jordan form of $A$.
Comment: That was an awesome explanation - thank you so much, @user1551! Have a great night :)
Comment: @LebronJames Thanks. Merry Christmas and a happy new year.
Comment: Merry Christmas and a Happy New Year to you too, @ user1551! :)


Almost sure pointwise inequality between conditional variance and variance or between conditional expectation and expectation

Question: I have a question about conditional expectation and conditional variance. It's a very general question. We defined conditional variance by
$$ \operatorname{Var}(X|\mathcal{F}):=E((X-E(X|\mathcal{F}))^2|\mathcal{F}) $$
For a random variable $ X $ and a $\sigma$-algebra $ \mathcal{F}$. Are there any inequalities such that
$ \operatorname{Var}(X|\mathcal{F})\le \operatorname{Var}(X)$ or $ \operatorname{Var}(X|\mathcal{F})\ge \operatorname{Var}(X)$ and the same question for the conditional expectation:
$E(X|\mathcal{F}) \le E(X)$ or $ E(X|\mathcal{F}) \ge E(X)$
Are any one of them true in general, or what further assumption have to bee assumed that a conclusion as above is true? Often such an inequality would be very usful.
Thanks in advance.
hulik
Comment: You might want to have a look at the (small and excellent) textbook *Probability with martingales* by David Williams.
Comment: @ Didier Piau: Thanks for your comment, but unfortunately the book is not free available or I didn't find it.
Comment: Which textbook do you use?
Answer: None of these inequalities are true in general.
Suppose you have

$\Pr(X=0,Y=0) = \frac{1}{5}$
$\Pr(X=0,Y=1) = \frac{1}{5}$
$\Pr(X=2,Y=1) = \frac{1}{5}$
$\Pr(X=-5,Y=2) = \frac{1}{5}$
$\Pr(X=3,Y=2) = \frac{1}{5}$

Then defining $\mathcal{F}$ on values of $Y$
we have $E[X]=0$, $E[X|Y=1]=1$, $E[X|Y=2]=-1$,
and $Var(X)=7.6$, $Var(X|Y=0)=0$, $Var(X|Y=2)=16$.
Comment: @ Henry: Thanks for your answer. Though I have an additional question. In fact I would like to bound $ Var(X|\mathcal{F}) $ by $ \operatorname{const}\cdot E(X^2)$. Is this possible?
Comment: No: you can exceed any given ratio
Comment: @ Henry: Thanks for your quick answer. As mentioned below (see comment after Didier Piau's answer) the motiviation behind this question can be found in [link](http://math.stackexchange.com/questions/90139/properties-about-a-certain-martingale). I wondered if in a more general setting something would be true. Because then I would be able to prove 4.) in the related question
Answer: All these inequalities fail in general, and for good reasons.
Assume for example that $\mathcal F$ is the sigma-algebra generated by $X$. Then $\mathrm E(X\mid\mathcal F)=X$ almost surely hence $\mathrm E(X)\leqslant \mathrm E(X\mid\mathcal F)$ almost surely or $\mathrm E(X)\geqslant \mathrm E(X\mid\mathcal F)$ almost surely are impossible unless $\mathrm E(X)= \mathrm E(X\mid\mathcal F)$ almost surely, that is, unless $X$ is almost surely constant.
Here is another example. Assume that $X=YZ$ with $Y$ and $Z$ independent, $\mathrm E(Z)=0$, $\mathrm E(Z^2)=1$, and that $\mathcal F$ is the sigma-algebra generated by $Y$. Then $\mathrm E(X\mid\mathcal F)=\mathrm E(Z)Y=0$ almost surely and $\mathrm{Var}(X\mid\mathcal F)=\mathrm E(X^2\mid\mathcal F)=E(Z^2)Y^2=Y^2$ almost surely while $\mathrm E(X)=0$ and $\mathrm E(X^2)=\mathrm E(Y^2)$ hence no almost sure comparison can hold.
Comment: Thanks for your answer. See [link](http://math.stackexchange.com/questions/90139/properties-about-a-certain-martingale) it's a related question, in fact it's 4. in the other question (see link). This was the reason for asking this question in a more general setting.


Atualizar div em tempo real com php /javascript sem atualizar página

Question: A minha dúvida é a seguinte, supondo que eu tenho uma div e nessa div tenho um código php que diz que quando alguem entra na página envia um curl. O Que quero saber basicamente é se existe alguma forma dessa div estar constantemente em atualização para mal eu mude uma coisa exiba ou de x em x milisegundos envie o curl.
Obrigado
Comment: jquery+ ajax não te ajuda?
Comment: Se soubesse aplicar
Comment: Você já fez alguma coisa pronta em código? Fica mais fácil explicar partindo de algo já feito.
Comment: Pesquise aqui na tag, vai encontrar um montão de exemplos e solução pros problemas mais básicos: http://pt.stackoverflow.com/questions/tagged/ajax?sort=frequent&pageSize=50
Answer: PHP é Server Side e Javascript é Client Side.
Não tem como rodar script php 'on the fly'.
Você precisa executar um Ajax quando quiser que essa CURL seja executada.
Veja se isso te ajuda:
<code>$("button").click(function(){
    $.ajax({
         url: "demo_test.txt",
         success: function(result){
              $("#div1").html(result);
         }
         });
});
</code>


How do train yourself to transcribe in real time?

Question: One of the things I have done is scale degree training where you play a cadence and play any note to see if you can identify that note. I can probably be as accurate as 98%. 90% if you add chromatic.
Also I train myself to hear harmonic progression, though I'm not good at it. I'm also doing interval training
Even though doing all this stuff, I can't really transcribe in real time, I have to pause over and over again, sing the melody to identify the intervals and maybe identify the scale degree.
I'm curious to see what you guys did to help you or what you did in general that helped understand the musical language more.
Answer: Although everything you've done so far is good practice, there's one big thing that's missing: singing!
When you sing (especially when you use a particular system—more on that later), you connect particular pitches with their functions. The more you do this, the more you'll hear music and recognize what the scale degrees are, and you'll be able to do this in real time.
But in order for this to work, it's best for you to use a functional singing system. If you use solfège, you'll want to sing movable-do solfège, because the syllables map onto particular functions (i.e., "do" is tonic, "sol" is scale-degree 5, etc.). You could also just sing on scale-degree numbers.
You could sing fixed-do solfège, but it will take a little more time to reach the level that you're hoping for. I'd only recommend fixed-do if you're a young child or if you're a college music student.
I'd go so far as to say you should forego your interval training and use that time for functional singing instead. Although interval training can be helpful, it's nowhere near as helpful as functional singing.

As for harmonic dictation, the best practice is playing things at the keyboard. But as you're playing them, make sure you know what harmonies you're playing at any given time. Only then will you map function onto sound.

But through it all, remember two things:

These things take time!
And perhaps more importantly, be realistic with your goals and your progress. Very few people in the world can hear a Beethoven symphony and transcribe it all. And to be honest, such a skill is not necessary to be a successful musician.
Comment: You're spot on with movable do as opposed to fixed do. Although numbers is as good as any - and reinforces intervals. Mozart was good at transcribing difficult works, but not sure he managed to transcribe any of Beethoven's stuff.
Answer: Answer given above is a good one. I have very good relative pitch and if I'm given the tonic chord, can identify the scale degree of any note (including chromatics) played afterward. This simply came by years of playing by ear and becoming familiar with the scales. So I'd say first of all, just don't give up and keep spending time, time, time listening to music and  playing along to follow what chords/notes are being played. That being said, I still can't transcribe every note of a piano piece in real time, and I don't know if that's a reasonable goal, unless you're dealing with a simple one-part melody line. Single vocal parts are doable, and perhaps two-part  harmony, but I don't think I know anybody that can perfectly reproduce every note of a complex piano score after hearing it once. And I know some people with incredible ears, even absolute (perfect) pitch. Just being able to accurately transcribe using your pause or slow speed options is a reasonable goal.


How do I change the scrolling speed?

Question: I recently installed and enabled the Back To Top module. It gives a button at right bottom of the screen to scroll back to the top of the page.
How can I increase the scrolling speed?
Answer: In the file back_to_top/js/back_to_top.js you'll find the following on line 23:
$('html,body').animate({ scrollTop: 0 }, 1200, 'easeOutQuart', function() {

The 1200 is the animation duration in milliseconds. Lower it and the animation will go faster. Optionally you could raise a feature request in the module issue queue to make this a configurable setting.

How do I change the scrolling speed?


Generalizing a function

Question: I am doing same step for different variables in my three functions.
 SumPosition_Channel *posChannel;
 bool isLoop;
 cont->GetPositionChannel(&posChannel);
 isLoop = posChannel->getChannelLoop();
 checkBoxChannelLoop->setChecked(isLoop);

SumRotation_Channel *rotChannel;
bool isLoop;
cont->GetRotationChannel(&rotChannel);
isLoop = rotChannel->getChannelLoop();
checkBoxChannelLoop->setChecked(isLoop);

SumScaling_Channel *scaChannel;
bool isLoop;
cont->GetScalingChannel(&scaChannel);
isLoop = scaChannel->getChannelLoop();
checkBoxChannelLoop->setChecked(isLoop);

Can I generalize them into one function?
Comment: Unrelated to your problem, but why don't you use references when passing the pointer to the `GetXChannel` functions? And unless there's some inheritance and polymorphism involved, why use pointers at all?
Comment: As for your problem, why not use templates? Create a templated function doing all that, and rewrite `GetXChannel` into a templated function that you can specialize (and I recommend it *returns* the object instead of passing arguments).
Comment: @Some programmer dude i have inheritance involved in this .
Comment: @Some programmer dude i tried using Templates but i am bit confused about how to write code for this situation.
Comment: Why do all three use the same checkbox?
Comment: @ Ulrich Eckhardt These are different animation channels of a object when we choose any channel  o then it updates the checkbox with the information whether it is looped or not.
Answer: Quite simple via overloaded functions, especially if you didn't design the interface for those classes.
void GetChannel(SumPosition_Channel** channel,WhateverTypeThisIs* checkBoxChannelLoop, ContType* cont);
void GetChannel(SumRotation_Channel** channel,WhateverTypeThisIs* checkBoxChannelLoop, ContType* cont);
void GetChannel(GetScalingChannel** channel,WhateverTypeThisIs* checkBoxChannelLoop, ContType* cont);

in each of those functions simply call the corresponding function.
i.e.
void GetChannel(SumPosition_Channel** channel, WhateverTypeThisIs* checkBoxChannelLoop, ContType* cont)
{
 bool isLoop;
 cont->GetPositionChannel(&channel);
 isLoop = channel->getChannelLoop();
 checkBoxChannelLoop->setChecked(isLoop);
}

If you designed the interface, I suggest overloading those functions inside the actual cont class, as then you would need to type less.
Comment: The issue here is cont->GetPositionChannel(&channel); this changes with the variable type.
Comment: For rotation it will be cont->GetRotationChannel(&channel)
Comment: Don't forget getScalingChannel too!
Comment: that should do it.
Answer: My recommendation is using templates, not only for the code shown but also for the GetXChannel function.
Something like
// In the class for "cont"
template<typename T>
T* GetChannel();

// Specialization for SumPosition_Channel
template<>
SumPosition_Channel* GetChannel()
{
    SumPosition_Channel* channel = new SumPosition_Channel;
    // Other SumPosition_Channel specific initialization...
    return channel;
}

// Same for the rest of the channels

If you don't need any channel-specific initialization then just
// In the class for "cont"
template<typename T>
T* GetChannel()
{
    return new T();
}

Then this can be called easily from a templated function for the code you have:
template<typename T>
T* foo(ContType const* cont, CheckBoxChannelLoopType* checkBoxChannelLoop)
{
    T* channel = cont->GetChannel<T>();
    checkBoxChannelLoop->setChecked(channel->getChannelLoop());
    return channel;
}

Instead of raw non-owning pointers as shown in the examples above, I would recommend using either std::unique_ptr if a "channel" can have only one single owner at a time, or std::shared_ptr if there can be multiple simultaneous owners.
Answer: Yes, you can generalize that using templates and overloading concepts.
template <typename T>
void func () { // your method Signature here
    T *channel;
    bool isLoop;
    cont->GetChannel(&channel); // overload the GetChannel() in the "cont" class type
    isLoop = rotChannel->getChannelLoop();
    checkBoxChannelLoop->setChecked(isLoop);
}

Now you can call the function with respective type.
Remember to overload the GetChannel() method in the "cont" class type for each of the template arguments type.
Hope this helps, Thanks.

Generalizing a function


How can I always have the node title display on top of a background image?

Question: With Drupal 8, the page title is available through a block now. We have several content types where we have an Image field (field_image) and we constantly have to write templates per content type to place the title on top of the image.
It would be nice if we could use the view modes of each content type or some module to do this. Basically, something that does "take the field image, set it as a background, and place the title on top."
Is there a better way to do this programmatically as we cannot find any other way to do this?
Comment: You can override node.twig.html and config hidden block title with contentent type.
Comment: I've made something like this with an override of node.twig.html (as @MrD say) and used the "twig_tweak" to load the block and "twig_field_value" to display the image as background. Hope it helps !
Comment: This can be done using Drupal Views module. See https://www.youtube.com/watch?v=FtV78ufp9Jw. There is also the [GD Header module](https://www.drupal.org/project/gd_header). "This module provides a block with the page title and a configurable image in the background".
Answer: There is several ways to solve this
1 make your own module
to do what you described
2 add theme templates
for each content type as you described
3 Use background_image module
The module is available for Drupal 8 promises to do just this (I meant to use it but have not actually)
According to the the project description provides a way to insert token values

Token - Provides a way to view which tokens are available to use when
  adding overlay text for a background image.

So you can probably use it with a field token to accomplish what you need
Answer: Background Images Formatter is another option for accomplishing this, especially when you might want different images on different pages.

This module provides an image formatter that allows you to set an
  image in background of a tag. The images are from a field of an entity
  and not from a configuration page or a custom entity or something
  else, so it's very easy to setup and manage.


How do you find the key of a dominant seventh chord

Question: How do you find the key of a dominant seventh chord?
Comment: Chords exist in many keys. In strictly diatonic terms, the root and the fourth will get major seventh chords, and the fifth chord would get the dominant, but as jazz exists, there are many contexts where every major chord would be assumed to be (at least) a dom7.
Comment: @DaveJacoby - in jazz, the subdominant and tonic are more likely to be major sevenths, leaving the dominant as a dom. seventh. In Blues, all three are likely sevenths.
Comment: Because of the lack of information and details in your question it cannot be answered accurately so I am voting to close it. Consider adding more detail to your question if you want an accurate answer. The short answer based on your question the way it is is: "You cannot."
Comment: Please edit to explain more. There's some understanding that's missing here; right now Tim's answer is right, but I wonder whether either the word "dominant" or "key" is meaning something different to you. For instance, perhaps you want to know how to look at a seventh chord and know what its "name" is, i.e. what the *root* is.
Comment: This question needs some clarification: it's been answered as best we can, with the scant information proffered, but it's not clear enough for a definitive answer.
Answer: We can answer the simplistic question 'If G is the dominant, what is the tonic?'  Find the major (or minor, come to that)  scale of which G is the 5th note.  That's the tonic.   Or, if you know your intervals, go up a perfect 4th or down a perfect 5th to find the tonic.
But 'Dominant 7th' can mean two things.   We might be saying the chord is the actual Dominant of a key, built on the 5th degree of that key's scale.   Or we might just be referring to the shape of chord which is a major triad with a minor 7th on top.  It MIGHT be acting as a functional dominant chord, but it might not.
Typical example, C7, F7, G7, C7.  A simple Blues sequence which comprises a 'dominant 7th' shape chord rooted in the tonic, one rooted on the subdominant and then (finally!) one rooted on the dominant.  All 'dominant 7th' shape chords, all in the same key (but with some chromatic notes) but only one is an actual 'dominant 7th'.
Then  there are 'secondary dominants', chromatic chords which ARE functional but don't lead to the tonic.  In the key of C (and the tonality never centres anywhere else long enough to count as a modulation) let's look at C, E7, A7, D7, G7, C.    Lots of 'dominant 7th' shape chords, only one the actual 'dominant 7th' of the key.
And there are other ways too that 'dominant 7th' shape chords are used in tonal harmony.
Answer: The dominant chord is the V of a key. So chord G7: C D E F G. Or to count backwards, C B A G (rule of 9).
The ^3 of a dominant chord is the ^7 of its key. So, with G7 again, ^3 is B. B is the ^7 of key C. And its ^7 is the ^4 of the prevalent key.
BUT - in Blues, all chords will probably be dominant sevenths, including the tonic, so this method won't stand. And there will always be secondary dominant chords. those which will by definition, contain non-diatonic notes, a bit of a clue. They ostensibly will be followed by a diatonic chord, but that's not part of the game, or the rules. For example, in key C, E7 is a sec. dom., supposedly leading to (thus dominant of) Am. Or B7, dominant of Em. The same method as above will apply to all secondary dominant seventh chords.
Comment: I thought about answering this in a similar way but it is just too vague. What about Sub V's or secondary dominants for example? There's not enough to this question to give a comprehensive answer.
Comment: @JohnBelzaguy - I did address sec. doms, but felt that maybe as OP has a score of 1, there may be a simple way to explain.
Comment: Yes, I see you did, too late to erase. Your answer is good, it's the question that is flawed. You can say where a dominant chord will likely go but that won't give you information as to what key you're in.


How do I get linux server to use local PHP.ini in a shared environment?

Question: I'm on shared server environment (Dreamhost.com uses Linux/Debian).
I followed their instructions here on setting up a local PHP5 instance on my user account so that I could use APC (php5 accelerator)
A caveat is that I don't have php5 installed on the root directory "/home/php5" as assumed by the instructions/install script.
Rather I have it in another directory "home/subdir-path/php5", so I had to change the script to address that.
I tried adding this dir to the env $PATH
but when I do phpinfo(), I see that it's not using the local php.ini settings =[
Any thoughts on how to remedy this is greatly appreciated.
==OR==
If someone could show me the right steps to set up a custom php5 instance, with fastcgi, and APC (php cache/accelerator) that'd be just as great.
Answer: I've never worked with DreamHost before but looking at the wiki page you referenced and taking into account the version difference of the php-update.php script (0.1.4 vs 0.1.7) in Step 4 it would appear they require you put your necessary INI changes in the $inimodifications array found on line 73.
// Modifications to be made to the ini file after it is updated
// - If you need to change these then you can do so here, then
//   delete your target ini files and run the script again
$inimodifications = array(
    'output_buffering = 0',
    'post_max_size = 100M',
    'upload_max_filesize = 100M'
);

Considering output_buffering, post_max_size & upload_max_filesize are all options found in the php.ini file I would start with trying to add the necessary lines you're neededing to change to this array following their examples and try again.
Answer: Revise the instructions in Step 4 as here:
touch ~/subdir-path/php5/php-update.php

And change this section of the script to include "subdir-path" (this script will be the one referenced by the touch command and should include the complete script as listed in the instructions):
// Determine the version of PHP to update (4 or 5) based on the directory
$directories = explode('/', dirname(__FILE__));
$directories = array_reverse($directories);
$directory = $directories[0];

switch ($directory) {
    case 'php':
        $php = 'php';
        break;
    case 'php5':
    default:
        $php = 'php5';
        break;
}

// The full paths to the source cgi and ini
$sourcecgi = '/dh/cgi-system/' . $php . '.cgi';
$sourceini = '/etc/' . $php . '/cgi/php.ini';

// Get the HOME environment variable
$home = $_SERVER['HOME'];

// The full paths to the target cgi and ini
$targetcgi = $home . '/' . 'subdir-path' . $php . '/' . $php . '.cgi';
$targetini = $home . '/' . 'subdir-path' . $php . '/php.ini';

Also, in Step 8, make sure you make those alias(es) to your custom directory, for example:
cd ~/example.com
ln -s ~/subdir-path/php5 .

You may also need to amend the pathnames in your .htaccess file(s).
Comment: actually this did not answer my question
Answer: To do this I had to create an fcgi wrapper..
you can pretty much name it whatever you want

touch php5-mywrapper.fcgi

make it executable

chmod +x php5-mywrapper.fcgi

write to the file =]

pico php5-mywrapper.fcgi

    #!/bin/sh
    export PHP_FCGI_CHILDREN = 3
    exec cgi-bin/php5.fcgi -c path/to/php-ini-dir/

then i added the appropriate handlers in the .htaccess file, and places the .htaccess file in the directory of the domain that is using the fcgi


Do We Really Need Third Party Extension Related Tags?

Question: We have some third party related to tags in our systems. Some examples are below:
ecomdev-phpunit fooman-extensionfishpigfiregentoultimate-module-creatoraheadworks-ajaxcartproavs-fastsimpleimport
There may be many more. Some of them are famous and highly used in Magento systems and others are not. However all questions which are related to 3rd party extensions are off-topic in this forum unless if they don't provide us with proper codes.
So in that case, tags which are clearly stands for a third party extension is not allowed in my opinion. Instead of that, OP can use some general tags such as extensions 3rd-party-modules in those cases ?
Can we completely remove such unwanted tags from our system ?

P.S : We can retain tags which are related to highly-used/Open-source third party modules. But in my personal opinion, having tags related to a company or a commercial extension kills "equality" in all means.
Comment: Same attempt for Magento2 pre-GA tags: http://meta.magento.stackexchange.com/q/907/3326
Answer: The specific tags are not needed and should be removed. The general tags should remain though.
[EDIT]
Apparently there is no way to delete a tag manually.
It is done each day for tags without questions: How can we get rid of misspelled and unused (or "zombie") tags?
I guess we have to go the long way and remove the tags from the questions.
Comment: I'm still searching for the delete tag option.
Comment: "I guess we have to go the long way and remove the tags from the questions." that's what I already do. I thought moderators could kill a tag entirely if needed, but seems like you need higher privilgees.
Comment: how can we remove that ? moderators has privilege to do that ?
Comment: See my edit....
Comment: will try this today and confirm you.. Thanks once again for your quick reply.
Answer: Below the numbers as they currently are. If you're helping out on this, you should also remove the tags from closed questions because if you are tagging your question and try to type in one of the tags you still see them appearing in the suggestions with a >0 count.

ecomdev-phpunit -> 49 questions
fooman-extension -> 0 questions
fishpig -> 0 questions
firegento -> 0 questions
ultimate-module-creator -> 0 questions
aheadworks-ajaxcartpro -> 0 questions
avs-fastsimpleimport -> 29 questions
magesetup -> 0 questions
magerun -> 1 questions


How to allow program updates without prompting UAC?

Question: We have about 15-20 users who have this software installed.
We have UAC enabled through GPO as you should, which means the software prompts for admin approval if a standard user trys to install it. Thats fine, they can call the help desk to have the software installed.
My problem is, our help desk is being bombarded every day because users can't update the software and there are updates almost every day which is prompting UAC.
Using procmon.exe to find out where it was trying to write to, I then created a GPO to allow file permission access to the program files folder for this particular software, including the program data folder, but it still prompts for admin approval. It seems as though that the software is using msiexec.exe to run a .msp patch file.
The only "ACCESS DENIED"s I can still see in procmon is things like this:

What can I possibly do to stop this software from prompting UAC with admin password credentials aside from disabling UAC?
Comment: Are the patches digitally signed? It looks like [this](http://msdn.microsoft.com/en-us/library/windows/desktop/aa372388(v=vs.85).aspx) may help.
Comment: @Guvante Yes they are and the signature is legit.
Comment: There is a link in my comment about how to bypass UAC for certain signed MSI patches.
Comment: Unfortunately, those pretty much all apply to the developer, no? I'm just the end user.
Comment: My apologies, I misread and thought the MsiPatchCertificate setting was related to the machine not the original MSI.
Answer: Unfortunately this problem of inconvenience is not easily solved, as you're really talking about misbehaving software -- not meant for the enterprise environment where workstations are locked down. You will need to choose software that can run without aggressively applying patches, then you can manage the schedule and push them out yourself after having signed them.  This is why systems administrators avoid consumer-grade software that tries to update often.
Comment: Unfortunately it wasn't an option for us. As a systems admin, I don't always get to choose which software our users use but it is my job to make sure it works. We ended up opening those systems with less aggressive group policy objects and turning off UAC. Not an ideal solution but necessary.
Comment: That's unfortunate. N.b. you can't effectively re-enable UAC once it has been off.
Comment: That's true. It messes around with the virtual store folders and other stuff. Once it's been off for a little while, turning it back on is going to cause issues.
Answer: I'm not sure why you say UAC enabled through GPO as you should.  I disagree with that statement.  Users shouldn't have admin rights, UAC problem solved.
And on the topic of side-stepping the problem, why are you having users install updates, rather than pushing them out through GPO via a startup script or software installation policy?  Sounds like it would be easier than trying to debug this with procmon, and should save the helldesk some grief, in addition to "doing it right" and ensuring a consistent environment.
Comment: Users don't have admin rights, but I'm not disabling UAC since pretty much every recommendation out there says to keep it on. As for the software deployment, the software is using UAC patching: http://msdn.microsoft.com/en-us/library/windows/desktop/aa372388(v=vs.85).aspx The software installs these data updates using that method, which means the software itself has nothing to do with the updates.
Answer: You need to sign the MSI packages and the MSP packages. It's a long list of steps that are detailed in the MSI SDK: User Account Control (UAC) Patching
Comment: I believe you're correct, I've contacted the company to see what is going on. Hopefully I get a non-canned response and when I do, I'll update this thread.
Answer: I already got this kind of issue and my work around was to run specific programm under different user account. If it is possible for your software to use the LSA account, you may have better luck.
Comment: It deserves specific tests for your scenario. The fact that your soft is ran from a different account doesn't necessary means that your users can run the LSA account for every single software if they don't have the LSA credentials. I think -but I might be wrong on this one- that if your software is updated through his own service, just run the service under the LSA account for testing purposes.
Comment: The problem is, couldn't these users now go and install unauthorized software using this secondary account's permissions?


Relative safety level of boys lacrosse

Question: How safe or dangerous is boys lacrosse, compared to other boys high school sports?
This would be a 10th grader playing JV as a defender.
My son, trying to convince me that he would not get a concussion. told me that as a defensive player, he would get to hit other people, but he would not get hit.
Answer: Lacrosse ranks below soccer in concussion rates.   The helmet is basically there so you don't get whacked with a stick - which I do not think could cause concussions at full full force (these stick are very light and literally will bend if it is that hard).   Basically if there are concussions in lacrosse it is either from clumsiness/uncoordinated kid, someone getting "checked" and head hits ground hard (very rare - one of my sons played for years), or from a colliding "accident".
From a parent standpoint I would worry about my kids psyche more than worry about concussions.   It is a hard sport because it requires speed, a lot of running and there is contact.   Kids without the right athletic ability or demeanor will get exposed quickly.   From an injury view, there are more bruises and boo-boos in lacrosse but injury... basketball way more dangerous.

Relative safety level of boys lacrosse


How to use JQuery Slider control without loading JQuery?

Question: I want a use a Dual Slider (Range) HTML control, similar to the JQuery dual Slider, without having to load a huge JavaScript framework just to use it.
Does such a dual slider control exist, that is light weight (filesize) and doesn't require me loading any JavaScript frameworks?
Comment: I don't think jquery is huge. A lot of websites take advantage of a Javascript Library (or Framework ^_^), you should too. That's my two cents...Will I take a -1 ?
Comment: Check out the answers in this thread: http://stackoverflow.com/questions/877530/javascript-range-slider-dual-slider-exist-without-using-a-framework
Comment: jquery isn't huge, and may be already downloaded by the user from google: http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/
Comment: @iKnowKungFoo, all of the answers on that linked question are for using an JS framework. So this doesn't help me. Thanks though
Comment: @BalusC, initially - it appears that it doesn't require any frameworks. But when I went to download the code and demo, it required the use of a 80kb custom framework + another 60kb slider class. So I wouldn't call that option "light weight" at all.
Answer: The simplest solution might be to use jQuery and the closure compiler.  I believe the closure compiler will actually remove code that is not used.  I have never actually tried this, so YMMV.
Comment: I mean googles closure compiler http://code.google.com/closure/compiler/.  As for how it does it, it looks at your code to see what is used and what it not, and gets rid of what is not.  I can't really give a better description than that as I have not looked into it very extensively.
Comment: what is the "closure compiler"?  Do you mean Google Closure? If so, how does it evaluate my HTML code to inspect to see what JQuery components I'm loading / not loading?
Answer: Your simplest answer is to use an interpreted language, server side construct or a framework.  No alternative to your requested solution.  Your asking html to do something it is not intended to do natively.  You are also asking that the browsers support features for which they are not natively built to support without compilations, interpretations and math services built in.
Your best bet is to link in to the jquery object from google (@ around 52kbps) your not asking for alot of your users.  Only other option is to use Flash which is twice the problem and 1/2 the fun.


React updating useState array not causing element refresh

Question: I am unable to trigger the component to update when the viaList state is changed. If anyone could help, please <3
I don't want to append these children if possible.
import React, { useEffect, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';

function BookingForm() {
  const [viaList, setViaList] = useState([]);

  function addViaLocation() {
    const arr = viaList;

    arr.push(

        Via Location

)

    setViaList(arr);
  }

  return (
    <>
      <button onClick={addViaLocation} className="button-standard primary" type="button">
        Add Additional Location
      </button>

{viaList.length > 0 && viaList.map(item => item)}

    </>
  );
}

export default BookingForm;

Separating the functionality into a separate component
Triggering the update using props
Regular DOM stuff (appending doesn't fit our use case)
Comment: Also I wouldn't store JSX in an array if you can avoid it (which you can), instead just store an object containing the information you need and then turn it to HTML/JSX in the `return` (within `viaList.map`, which currently does nothing).
Comment: Don't use `arr.push`, create a new array like this: `[...arr, newElement]`. Even better to use set state like this: `setViaList(prev => [...prev, newElement])`.
Comment: Does this answer your question? [React doesn't rerender on an array state update](https://stackoverflow.com/questions/64982593/react-doesnt-rerender-on-an-array-state-update)
Answer: You need to create a new array such that React understands it has changed. If you only push to the old viaList it will still hold that viaList === previousViaList. Instead create a new array, e.g. with the spread operator:
  function addViaLocation() {
    const newElement = (

        Via Location

)

    setViaList([...viaList, newElement]);
  }

Answer: Fixed it...
I was doing the following (just longer):
setViaList([...viaList,
STUFF
])

I had to update the state array using a callback instead:
setViaList(viaList => [...viaList,
STUFF
])

Comment: even the first one is correct
Comment: The point is that `setViaList([...viaList, ])` works because with `[...viaList, ]` you create a **new array** (thus `[...viaList, ] !== viaList`). On the other side `viaList.push(); setViaList(viaList)` won't work because you use the same array reference (`viaList === viaList`).
Answer:

import React, { useEffect, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';

function BookingForm() {
  const [viaList, setViaList] = useState([]);

  function addViaLocation() {
    const arr = [...viaList];

    arr.push(

        Via Location

)

    setViaList(arr);
  }

  return (
    <>
      <button onClick={addViaLocation} className="button-standard primary" type="button">
        Add Additional Location
      </button>

{viaList.length > 0 && viaList.map(item => item)}

    </>
  );
}

export default BookingForm;

You can Create a shallow Copy of the Array by spreading the current state array  and then pushing the new data and update state with the shallow copy


Why do ukulele players not use the G-string?

Question: Well, obviously, they do, but in solo/fingerpicking, the only time I've ever seen a note written on the G-string in tab is as part of a chord. Why do melodic  structures neglect to use the G-string? Is there an ergonomic reason, or something else? Or are there a bunch of counterexamples I'm overlooking?
(High G. On a Low G ukulele, it's obviously used way more.)
Answer: The G-string can certainly be used in fingerstyle.  The two books that I used to learn fingerstyle, Rob MacKillop's 20 Easy Fingerstyle Studies for Ukulele and John King's Famous Solos and Duets for the 'Ukulele both use the G-string extensively.
That having been said, because the High-G is tuned between the E- and A- strings, all of the notes here are duplicated on those strings.  Therefore, when you are learning scales, you don't really need it.  For example, when you are learning the C Major scale on the Ukulele, you will start on the open C-string and play the C and D there, then move to the E-string and play the E, F, and G there, and finally move to the A-string and finish with the A, B, and C.
What the G-string does do for you is make it easier to play some intervals.  For example, take a look at these measures from "Banjo Schottische" in John King's book:

There are a lot of G notes in there, and playing those notes on the open G-string allows you to play successive notes on two different strings, which is much easier than playing two back-to-back notes on the same string.


Kickstart virtual console: No 'Shell prompt' at Alt-F2

Question: I am installing Scientific Linux 6.1 via kickstart, and I am trying to debug a problem.
According to Tips and tricks for anaconda and kickstart, I should have several virtual consoles available:
What the different terminals display

Alt-F1    The installation dialog when using text or cmdline
Alt-F2    A shell prompt
Alt-F3    The install log displaying messages from install program
Alt-F4    The system log displaying messages from kernel, etc.
Alt-F5    All other messages
Alt-F7    The installation dialog when using the graphical installer

The Virtual Consoles Alt-F1, F3, F4 & F5 all work and show various logging information. However, the Virtual Console at Alt-F2 does not do anything.
I could really use access to the shell prompt (Alt-F2), however there is no Shell prompt available at the second virtual console (Alt-F2). All I have is a blinking '_'.
Can I force Alt-F2 to show me a shell prompt?
Answer: I have just tested an automated kickstart install (driven by cobbler) and it works fine for me. All I had to do is press Ctrl+Alt+F2 (virt-manager has a menu for this). The only problem is that the shell is not avaialble right away, you have to wait for the installer to reach a certain stage.
Regarding debugging, you might find the Anaconda logging page helpful.
Comment: Do you happen to know the line which cobbler passes to the kernel? I am not using cobbler, but suspect that's my problem.
Comment: It's actually koan that starts the virtual machine, but here it is: `method=nfs:myserver:/Scientific-6.1-i386-DVD/ ks=http://myserver/cblr/svc/op/ks/system/myvm ksdevice=link kssendmac lang= text`
Comment: Are you installing Enterprise Linux version 5.7 (or similar) or version 6.x?
Comment: I've tested with Scientific Linux 6.1, the distribution mentioned in your question.
Answer: Look into /etc/inittab. Maybe the entry for tty2 is disabled. If you want a login prompt, put this line into it:
2:2345:respawn:/sbin/getty 38400 tty2

For an autokgin as root, use:
2:2345:respawn:/sbin/mingetty --autologin root --noclear tty2

After editing, make init re-read this config:
telinit q

You should see something on tty2 now.
Comment: This is an installer, not an installed system.
Comment: Unfortunately I cannot access a commandline to view those files. And as a sidenote, RHEL6 has replaced  /etc/inittab with Upstart (/etc/inittab is ignored).
Comment: @StefanLasiewski: Ok, the blank tty2 means that installation hasn't progressed so far that other vt's could be opened. What's in your ks.cfg? Any idea at what stage it fails?
Comment: @ott : I should clarify. The other Virtual Terminals (Alt-F1, F3, etc.) are working. Alt-F2 is the only VT which is *not* working. I updated my question to be more clear.
Comment: @StefanLasiewski: Yes, the installation stops before it can start a shell on vt2, that's why you see nothing. I think you can't make "normal" screenshots, but could you take pictures of tty3 and tty4 to see the last steps?


python "local variable referenced before assignment" with hundreds of threads

Question: I am having a problem with a piece of code that is executed inside a thread in python. Everything works fine until I start using more than 100 or 150 threads, then I get the following error in several threads:
<code>    resp.read(1)
UnboundLocalError: local variable 'resp' referenced before assignment.
</code>
The code is the following:
<code>    try:
        resp = self.opener.open(request)
        code = 200
    except urllib2.HTTPError as e:
        code = e.code
        #print e.reason,_url
        #sys.stdout.flush()
    except urllib2.URLError as e:
        resp = None
        code = None

    try:
        if code:
            # ttfb (time to first byte)
            resp.read(1)
            ttfb = time.time() - start
            # ttlb (time to last byte)
            resp.read()
            ttlb = time.time() - start
        else:
            ttfb = 0
            ttlb = 0
    except httplib.IncompleteRead:
        pass
</code>
As you can see if "resp" is not assigned due to an exception, it should raise the exception and "code" coundn't be assigned so it couldn't enter in "resp.read(1)".
Anybody has some clue on wht it is failing? I guess it is related to scopes but I don't know how to avoid this or how to implement it differently.
Thanks and regards.
Answer: Basic python:
If there is a HttpError during the open call, resp will not be set, but code will be set to e.code in the exception handler.
Then code is tested and resp.read(1) is called.
This has nothing to do with threads directly, but maybe the high number of threads caused the HTTPError.
Comment: @user2336071 I agree with @dmeister that this is almost certainly the cause.  In particular, the only way that you can get an exception in your first `try` block is from the call to `opener.open`.  And if you do get an exception there, then `resp` will not get any value.  At any rate, it's easy enough to test -- try adding `resp=None` to the `except HTTPError` block, and see if that changes the error from `UnboundLocalError` to `AttributeError` (which you'd get when you try to access `resp.read`, where `resp==None`
Comment: I think that is not correct. The HTTPError is raised when there is a response code diferent from 200, for example a 404. It works perfectly with 404 errors. Besides, it worked perfectly with thousands of requests with and without errors and and low concurrency. The connection errors wich could cause that resp is not assigned are managed by URLError afaik as they are not HTTP errors (protocol errors).   Thanks fo your response.
Comment: @user2336071 If you are sure about that, please tell me what you think is referred to as `resp` in the case of a `HTTPError`?
Comment: @glglgl In case of HTTPError, for example a 404 Not Found, resp would be the file object containing the body and yes, a 404 can have a body.
Comment: @EdwardLoper I tried adding resp=Non inside the except HTTPError and now I get a NoneType error, so that seems to be the problem and fails with 404 HTTP Errors. But anyway I don't understand why is code=200 running when it is after an exception and mostly why with less threads the 404 HTTP Errors do not cause that behaviour.
Comment: Well, finally I found that sometimes work and sometimes not, but the propper way to get the body of an HTTPError is described here: http://www.voidspace.org.uk/python/articles/urllib2.shtml#httperror    Thanks a lot for your help!
Comment: @user2336071 No. In the case of a `HTTPError`, `resp` would **not be assigned at all**. `self.opener.open(request)` fails, the assignment to `resp` never happens and thus you exactly get the error mentionned.
Comment: @dmeister: **Please** pay attention when approving suggested edits 'improving' formatting. [This edit](http://stackoverflow.com/review/suggested-edits/4385056) introduced a syntax error and should have been rejected (the `/` operator was deleted).
Answer: Defining and using resp variable are not is same code block. One of them in a try/except, the other is in another try/except block. Try to merge them:
Edited:
<code>ttfb = 0
ttlb = 0
try:
        resp = self.opener.open(request)
        code = 200
        resp.read(1)
        ttfb = time.time() - start
        resp.read()
        ttlb = time.time() - start
     except urllib2.HTTPError as e:
        code = e.code
        #print e.reason,_url
        #sys.stdout.flush()
    except urllib2.URLError as e:
        pass
    except httplib.IncompleteRead:
        pass
</code>
Comment: But that is not a solution. I could also add another except for the UnboundLocalError in the second try. The problem is why the 'resp' variable is not assigned ?


How to randomly generate a data with an error which is not normally distributed but follows an empirical distribution $(0, \sigma^2)$

Question: I have this model AR model for multiple time series
$ Y_{it} = \phi y_{it-1} + \delta_1y_{i-1 ,t-1} + \delta_2 y_{i+1 , t-1} + \lambda_i + \epsilon_{it} $
where
$\epsilon_{it}$ is a function of nonparametric realized volatility.
$\phi$ is the  autoregressive coefficient common to all
$\lambda$ is the individual random part or the unique characteristic of the $ith$ assets/stocks
$\delta_1$ and $\delta_2$ are the some coefficient of previous and future asset/stocks the investor wanted to invest.
The $\phi$ , $\lambda$ and $\delta$ is assumed normal
The motivation for this model model is the stock market.
My problem is how to generate a random data where the error ($\epsilon$) is not normally distributed but under empirical distribution of $(0, \sigma^2)$.
How would I implement this in R to meet all the constrains and to really characterized my desired generated data which is needed for estimation part.
I really need some help.
Comment: What do you mean by "empirical distribution"? If you want to sample from empirical distribution use bootstrap.
Comment: before I go for bootstrapping, I need data first and I have to generate a data that would characterize my model. Empirical cumulative distribution function that is approaching to normal but not normal. Most of the codes I know, the error are all assumed normal or have some specific distribution that is common to us, but what if the error is not distributed normally but approaching Normal but not really normal.
I don't know how to implement this in R.
Comment: It is not clear what do you mean by "empirical distribution". Empirical distribution is the distribution of the data, so if you don't have any data, then there is no empirical distribution of it. So it seems that you need to make some distributional assumptions (e.g. normal). There is no "empirical distribution" without data.
Comment: I want to generate a data that don't have a distribution. the error term is non-parametric. ithas a $(0, \sigma^2)$ but  no distribution. not normal not any.
Comment: Would that be possible?
Comment: So you need to assume some kind of distribution. How would the distribution of no form look like? If you had to paint something "without using any particular color", what would be the color be? What is the color that doesn't have any color?
Comment: Are you just hoping for some kind of distribution that isn't actually normal but is kind of similar to a normal, to test robustness to non-normal inputs? You can do this, but then you're only testing how robust you are to that _particular_ kind of non-normality, so it might not be so useful....
Comment: Are you trying to explore the properties of an estimator under several possibly nonnormal distribution settings?
Answer: There is no empirical distribution without a data. Empirical distribution is defined in terms of some particular sample. If you want to sample from some model, then you need to assume some kind of distribution. You cannot simulate without making any assumptions about the distribution (how would the no-particular-distribution look like? how would you know that is is correct?). If you wanted to sample from empirical distribution, you would be using bootstrap, but the, you would need some kind of data to sample from.


Why do OLS and logistic regression coefficients have opposite sign?

Question: I have data $y$ which is the rate of success in $n$ trials. I also have covariates $X$ that I want to regress against $y$ to understand the relationship between them. I tried 2 different approaches. The first is to take the log of $y$ and apply OLS regression. The second is to apply logistic regression to $y$ directly.
I noticed that one theoretically important coefficient, call it $x_0$, is highly significant in both models but in OLS it is estimated as a strong negative effect and in logistic regression it is a small but positive effect.
How is this possible? The variable is binary and I am comparing the standardized coefficients from both models. My assumption is that $x_0$ either increases the rate or not and it should be of the same sign in both models.
UPDATE
When my only regressor is $x_0$ this doesn't happen, it's only when I add the other covariates (of which there is about $200$). I have pasted the output of the full models below, excluding the estimates of the other covariates.
OLS
Call:
lm(formula = fx, data = fit_data, weights = weights)

Weighted Residuals:
         Min           1Q       Median           3Q          Max
-5.044177447 -0.616615480  0.070124542  0.692928438  4.539252302

Coefficients
                 Estimate      Std. Error   t value   Pr(>|t|)
(Intercept)     -1.33734283e+04  4.75932218e+03  -2.80994 0.00495879 **
x0              -1.06636833e-01  2.63420263e-02  -4.04816 5.1773e-05 ***

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.01868241 on 25500 degrees of freedom
Multiple R-squared:  0.59443022,    Adjusted R-squared:  0.591090233
F-statistic: 177.973843 on 210 and 25500 DF,  p-value: < 2.220446e-16

GLM
Call:
glm(formula = fx, family = "binomial", data = fit_data, weights = weights)

Deviance Residuals:
          Min             1Q         Median             3Q            Max
-103.51742894    -3.06309844    -0.24575206     2.27364818   165.10350046

Coefficients:

                 Estimate      Std. Error    z value   Pr(>|z|)
(Intercept)      2.83201590e+03  1.31990079e+03    2.14563 0.03190268 *
x0               1.77428670e-02  1.90814767e-03    9.29848 < 2.22e-16 ***

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

Null deviance: 9542439.111  on 25710  degrees of freedom
Residual deviance: 2224838.019  on 25500  degrees of freedom
AIC: 2340850.46

Number of Fisher Scoring iterations: 8
```

Comment: The short answer is that these are very different models, especially when the numbers of trials vary and/or the values of $y$ approach $0$ and $1,$ so there's no *a priori* reason to expect every one of hundreds of variables to play similar roles.  We of course would like to go further and diagnose your particular case, but for that we need specific information.  You can start by looking at and reporting on *much* smaller models using subsets of your data and tiny numbers of variables (including $x_0$) to see whether you can reproduce this behavior.
Comment: Please include the output of both models. The logistic model may be reporting an odds ratio
Comment: Probably not this one, but I have to ask: you are not comparing unstandardized $\beta$ from OLS with odds ratio from logistic regression, right?
Comment: I am comparing the standardized $\beta$ coefficients from both models. My assumption is that $x_0$ either pushes $y$ up or down, so it should be of the same sign in both models.
Comment: @RobertLong the output is too long, the model contains several hundred variables. I am using R and I am looking at the summary of lm() for the OLS model and glm() for the logistic model.
Comment: What kind of information can I help you with? The number of trials varies a great deal (min 349, max 35 million) and the rates $y$ are tiny (mean 0.0016, median 0.00032). I understand the models are different but isn't it true that $x_0$ is either good or bad for the rate $y$? In that case why would it have different signs, unless it is an estimation issue?
Comment: Just show us the output of both models with $x_0$ as the only covariate.
Comment: @RobertLong This seems to only happen when the other covariates are in the model but I've added the output above.
Answer: I don't think an entire data presentation is needed to give some intuition behind this phenomenon. While we would expect that a logistic regression and OLS model will, on average, produce parameter estimates (slopes or log-odds ratios) that are similar sign, it's entirely possible they will disagree for a given dataset and analysis.
The most likely issue is the influence of observations in the tails. Supposing we have an X that follows a standard normal density, and a modest positive trend in the risk of outcome for greater values of X. The influence of a single observation at (X=5, Y=0) will be far, far greater in a logistic regression model than in a linear regression model. That is because the influence of such an observation in a logistic model can be arbitrarily high. If the fitted value in the logistic model is 0.9, then the Pearson residual will be $(0-0.9)^2/\left( 0.9*(1-0.9) \right)\approx 9$ compared to the linear model where the residual is $0.81$.
The other issue is overadjustment. Due to non-collapsibility of the odds ratio, if (as you say) "several hundreds" of variables are input to the linear model, and suppose several of those variables are unrelated to the outcome, the tendency will be for the OR of effect to attenuate with larger adjustment. Then it becomes likely that the OR will spontaneously flip effect due to random perturbations along the lines of what's pointed out above - again, in multivariate adjustment, it can be difficult to understand the contribution of a single variable, so using the DF-beta diagnostic is a prudent choice.
Comment: (+1) nice answer Adam :)  it is also noteworthy, that, based on the output added to the OP, in both models, the estimate for `x0` is around 4 orders of magnitude smaller than the intercept term.
Comment: @badmax well noted. The fitted values for the linear model do indeed exceed 0, 1. In the diagnostics I made for these kinds of models, I have typically truncated predictions at 0 or 1. The DF betas tend to reveal the truth about the real influence of outlying observations. A word of caution however: removing the outliers to make linear and logistic agree is a biased form of data cleaning because you are using statistical results to make decisions.
Comment: You got it! The most influential DF-beta points for $x_0$ were 8 times larger in the logistic model than in the linear model. Once I removed the outliers (0.5% of them) everything lined up as expected (and the estimate went up an order of magnitude in the logistic model).
Comment: Can you please clarify the part about the sum-of-squared error? Why can it be at most 1, when the target ($\log y$) is unbounded on the left? Why is the Pearson residual important for the logistic model rather than the same sum-of-squares?
Answer: This is an artifact of the model used for logistic regression, which is model for one of the two probabilities, which add to 1. If your two values are coded, eg, 0 and 1, then linear regression assigns a positive coefficient to any variable, x, that increases in value as y shifts from 0 to 1. So regression assumes that y increases from 0 to 1.
The logistic transformation can model either the probability that y = 1 or that y = 0, eg logit(P(Y=1)) = b0 + b1x or logit(P(Y=0)) = b0 + b1x.
These two models give opposite signs for b1, but they are the same in absolute value and they have the same estimated variance or standard error so they also have the same p-value. Confidence intervals also have their signs switched. The inferences you make about b1 are the same.
The choice of models, for P(y=1) or P(y=1), is arbitrary as far as the logistic method is concerned, when there are two categories.
The person who wrote the software probably wasn't concerned about whether users would want to compare linear regression with logistic regression, only with having a program that worked well.
I seem to recall that the model SAS originally programmed did just what you have noticed. For many years they refused to make any change. After a lot of complaints they included an option that permitted the user to switch the roles of the two categories that resulted in switching the signs of all the variables.


Sails.js : findOne() works but not find() in Waterline

Question: I am developing a sails.js app with MySQL. I have a model, for which create and retrieve work without any problems.
 Model.findOne({ where: { someAttribute : 'foo' }, function(err, model) {
  // some logic
});

works fine, but not
Model.find({ where: { someAttribute : 'foo' }, function(err, model) {
  // some logic
});

Model.find(...) always returns an empty array. I have multiple records on the model which satisfy the where clause condition.
Comment: This isn't even valid Javascript syntax: `find({ where: { someAttribute : 'foo' }, function` so you're obviously not posting your exact code.
Comment: It should work as expected. I would re-check or post more specific code.
Answer: Given code should cause error! It is not even in valid format. It should be
Model.findOne({ where: { someAttribute : 'foo' }}).exec(function(err, model) {
    // some logic
});

Model.find({ where: { someAttribute : 'foo' }}).exec(function(err, model) {
    // some logic
});

Update your code to clarify your question.


Commerce : products with 2 prices

Question: In a Commerce project, the customer should be able to choose between 2 options with a radio field, for some products only, with a different price for each option. When a customer selects a radio option, the unit price should be changed accordingly and with ajax, and the line item updated I guess.
We also need that the admin enter PRICE A, PRICE B in 2 commerce_price fields when he creates new products, not by rule calculation neither  +90 or -100 as in Commerce Pricing Attributes (because prices vary a lot and having to calculate each price difference would be a source of errors).
At the moment the lone idea I got to configure this is :

set a line item field with these radio options, shown in the add to cart form.
Then or a pricing rule which detects if the 2nd price exists, and is selected ; sets the 2nd price as the unit price ?

Or programmatically, with some hook ? Any suggestion would be really helpful.
Answer: Pricing rules was the right track. In order to configure 2 main prices for a single product :
Add a 2nd price field to the product type:

Add a boolean field to the corresponding line item type:

In the Add to Cart form settings of this field (admin/commerce/config/line-items/CUSTOM-line-item/fields/field_avec_aerien), check  Include this field on Add to Cart forms for line items of this type.
Finally, in admin/commerce/config/product-pricing/rules/manage/, create (or clone & edit) a new pricing rule which set the unit price to 2nd price amount, when the boolean is checked by the customer in the add to cart form.

Pricing rules are very powerful, indeed !
Comment: Nice, this puzzeled me for a while now. There is some more reading on pricing rules here (I needed Google to figure out what they were): https://drupalcommerce.org/user-guide/product-pricing-rules-screencast
Answer: Well, you should go for product attribute.
You've got a few tutorial about it on the drupalcommerce website :

https://drupalcommerce.org/user-guide/product-attributes-variations
https://drupalcommerce.org/user-guide/product-displays
https://drupalcommerce.org/user-guide/cart

Lucky you, one the commerce guys (Randy Fay) also make a video where he briefly talk about it : http://vimeo.com/user5912539 (can't remember which one :x)
Comment: Thanks. Anyway this does not answer my question. In order to change the price with an attribute, it's possible to use *pricing attributes* module, but as explained above, it doesn't fit this specific case.

Commerce : products with 2 prices


Reduction of sample space and conditional probability formula

Question: In conditional probability, we find the occurrence of an event given that another event has already occurred. So the formula of P(A|B) = P(intersection of A and B) over P(B).
My doubt is, if event B has already occurred , it would mean that our reduced sample space is the entire set of B. So shouldn't P(B) = 1 just like how we say P(S) = 1 where S is the sample space?
Answer: What you are thinking of is that it is certain that $B$ occurs when given that $B$ occurs.$$\mathsf P(B\mid B)=1$$
That says nothing about the unconditional probability that $B$ occurs (ie: when it is not given).

What is the probability that event $A$ occurs when given that event $B$ occurs?   It is the weighted measure of outcomes in event $A$ that occur within the event of $B$.   Thus, it is the measure of the intersection, $A\cap B$, divided by the measure of $B$.$$\mathsf P(A\mid B)~=~\dfrac{\mathsf P(A\cap B)}{\mathsf P(B)}$$

For example:  The roll of standard six-sided dice consists of six equally probable events $\{1,2,3,4,5,6\}$.
Let $B$ be the event of rolling an even number on a standard six sided dice.   This event consists of the three equally probable outcomes, $B=\{2,4,6\}$, so we claim the probability of this event is $1/2$.$$\mathsf P(B)=1/2$$
Let $A$ be the event of rolling a prime number.   There is only one outcome among the three equally probable outcomes of event $B$ that is also an outcome of event $A$; ie $A\cap B=\{2\}$.
Hence the conditional probability for $A$ when given $B$ is $1/3$.$$\begin{align}\mathsf P(A\mid B)&=\dfrac{\mathsf P(A\cap B)}{\mathsf P(B)}\\[2ex]&=\dfrac{1/6}{1/2}\\[2ex]&=\dfrac 13\end{align}$$
Comment: Why do we worry about the unconditional probability of B? We've already established that event B occurs, so P(B) should be 1 right
Comment: No, we haven't established that $B$ does occur; we are measuring the probability for $A$ occurring *if* $B$ occurs.  @noorav
Comment: Oh. I thought we establish B has occurred because it's a "given"


Ajax Form submit doesn't work second time

Question: I'm loading the node/edit form in a block and I add ajax on submit.
I add the Ajax in the hook_form_alter.
$form['#prefix'] = '
';
$form['#suffix'] = '
';
$form['actions']['submit']['#submit'][] = 'submitForm';
$form['actions']['submit']['#ajax'] = array(
  'callback' => 'my_ajax_callback',
  'wrapper' => $form_wrapper,
  'effect' => 'fade',
);

The SubmitForm:
function submitForm(array &$form, FormStateInterface $form_state){
  $input = $form_state->getUserInput();
  $form_state->setUserInput($input);
  $form_state->setRebuild(TRUE);
}

And the callback :
function my_ajax_callback(&$form, FormStateInterface $form_state, $form_id) {
   $form_state->setRebuild();
   return $form;
}

The first time works fine. The second time seems to work without any error but it doesn't submit my new data.
I checked this comment How can I implement AJAX form submission? but I don't know if I have to set the values to the form_state. Also i use this callback for multiple content types. Should I check and set the value for each field? Is there a better way?
Thanks for your help!
------ EDIT -----
I added the submitForm function and now the second time I submit I get 'The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved.'.
Also, should I get/set each one of my fields or $input = $form_state->getUserInput(); $form_state->setUserInput($input); are enough?
-------- UPDATE ------
I managed to make it work for forms that I need to be empty after the ajax submit using the below code :
In hook_form_alter:
$form['wrapper'] = array(
    '#type' => 'container',
    '#attributes' => array('id' => $form_wrapper),
  );

$prefix = '
';
$form['#prefix'] = $prefix;
$form['#suffix'] = '
';
$form['actions']['submit']['#submit'][] = 'Drupal\MY_MODULE\Plugin\Form\FormAlter::ajaxFormEntityFormSubmitEmptyForm';
$form['actions']['submit']['#ajax'] = array(
    'callback' => 'Drupal\MY_MODULE\Plugin\Form\FormAlter::ajaxFormEntityCallbackEmptyForm',
    'wrapper' => $form_wrapper,
    'effect' => 'fade',
);

And in the FormAlter.php :
/**
 * Rebuild the form - Empty form.
 */
 public static function ajaxFormEntityFormSubmitEmptyForm($form, &$form_state){
  $entity = $form_state->getBuildInfo()['callback_object']->getEntity();
  $entity_type = $entity->getEntityTypeId();
  $bundle = $entity->bundle();
  $new_entity = \Drupal::entityTypeManager()->getStorage($entity_type)->create(['type' => $bundle]);
  $form_state->getBuildInfo()['callback_object']->setEntity($new_entity);

  // Clear user input.
  $input = $form_state->getUserInput();
  $clean_keys = $form_state->getCleanValueKeys();
  $clean_keys[] = 'ajax_page_state';
  foreach ($input as $key => $item) {
    if (!in_array($key, $clean_keys) && substr($key, 0, 1) !== '_') {
      unset($input[$key]);
    }
  }

  $input['entity'] = $entity;
  $form_state->setUserInput($input);

  // Rebuild the form state values.
  $form_state->setRebuild();
  $form_state->setStorage([]);
}

/**
 * Ajax callback to handle just returns the form
 */
 public static function ajaxFormEntityCallbackEmptyForm(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
   if ($form_state->hasAnyErrors()) {
     return $form;
   }
   else {
     return $form;
    }
  }

Now I'm trying to do something similar but I want the form populated with the new values. So I created two new functions in FormAlter:
 /**
  * Rebuild the form.
  */
  public static function ajaxFormEntityFormSubmit($form, &$form_state) {
    $entity = $form_state->getBuildInfo()['callback_object']->getEntity();
    $entity_type = $entity->getEntityTypeId();
    $bundle = $entity->bundle();

    $new_entity = \Drupal::entityTypeManager()->getStorage($entity_type)->create(['type' => $bundle]);
    $form_state->getBuildInfo()['callback_object']->setEntity($new_entity);

    $input = $form_state->getUserInput();
    $input['entity'] = $entity;

    $form_state->setUserInput($input);
    if(!$form_state->hasValue('title')){
      $form_state->setValue('title',$entity->getTitle());
    }

    // Rebuild the form state values.
    $form_state->setRebuild(TRUE);
    $form_state->setStorage([]);
  }

 /**
  * Ajax callback to handle special ajax form entity magic.
  */
  public static function ajaxFormEntityCallback(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // If errors, returns the form with errors and messages.
  if ($form_state->hasAnyErrors()) {
    return $form;
  }
  // Else show the result.
  else {
    $userInputs = $form_state->getUserInput();
    $entity = $userInputs['entity'];
    $entity_type = $entity->getEntityTypeId();

    $response = new AjaxResponse();
    if ($entity_type == 'node') {
      $title = $entity->getTitle();
    }
    return $form;
  }
}

If I return the $form in the callback, the first time works fine but the second I'm getting two errors in the log:

Drupal\Core\Database\IntegrityConstraintViolationException:
  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title'
  cannot be null: INSERT INTO {node_field_data} (nid, vid, type,
  langcode, status, title, uid, created, changed, promote, sticky,
  revision_translation_affected, default_langcode) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4, :db_insert_placeholder_5,
  :db_insert_placeholder_6, :db_insert_placeholder_7,
  :db_insert_placeholder_8, :db_insert_placeholder_9,
  :db_insert_placeholder_10, :db_insert_placeholder_11,
  :db_insert_placeholder_12); Array ( [:db_insert_placeholder_0] => 201
  [:db_insert_placeholder_1] => 258 [:db_insert_placeholder_2] =>
  my_estate_details [:db_insert_placeholder_3] => en
  [:db_insert_placeholder_4] => 1 [:db_insert_placeholder_5] =>
  [:db_insert_placeholder_6] => 5 [:db_insert_placeholder_7] =>
  1500889059 [:db_insert_placeholder_8] => 1500889066
  [:db_insert_placeholder_9] => 0 [:db_insert_placeholder_10] => 0
  [:db_insert_placeholder_11] => 1 [:db_insert_placeholder_12] => 1 ) in
  Drupal\Core\Database\Connection->handleQueryException()

And

Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity
  constraint violation: 1048 Column 'title' cannot be null: INSERT INTO
  {node_field_data} (nid, vid, type, langcode, status, title, uid,
  created, changed, promote, sticky, revision_translation_affected,
  default_langcode) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5, :db_insert_placeholder_6,
  :db_insert_placeholder_7, :db_insert_placeholder_8,
  :db_insert_placeholder_9, :db_insert_placeholder_10,
  :db_insert_placeholder_11, :db_insert_placeholder_12); Array (
  [:db_insert_placeholder_0] => 201 [:db_insert_placeholder_1] => 258
  [:db_insert_placeholder_2] => my_estate_details
  [:db_insert_placeholder_3] => en [:db_insert_placeholder_4] => 1
  [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => 5
  [:db_insert_placeholder_7] => 1500889059 [:db_insert_placeholder_8] =>
  1500889066 [:db_insert_placeholder_9] => 0 [:db_insert_placeholder_10]
  => 0 [:db_insert_placeholder_11] => 1 [:db_insert_placeholder_12] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save()

In case I return $response (which is what I prefer in order to be able to alter the message etc), the first time works fine but the second I get the message:

The content has either been modified by another user, or you have
  already submitted modifications. As a result, your changes cannot be
  saved.'.

Apologies for the long message. Any idea/help will be helpful!
Thanks in advance.
Comment: re-read my comment(the one you linked), you've missed a lot of stuff.
Comment: Should I also add a submit handler except the callback? I think I'm pretty confused. Could you give me some more details please?
Comment: I also added $input = $form_state->getUserInput();  $form_state->setUserInput($input); in order to get the user input and set it in the $form_state. Is that correct? After that I do the $form_state->setRebuild(); and then return $form;
Answer: I managed to find the solution.
In my hook_form_alter :
$form['#attributes']['class'][] = $ajax_id;
$form['actions']['submit']['#submit'][] = 'Drupal\MY_MODULE\Plugin\Form\FormAlter::ajaxFormEntityFormSubmit';
$form['actions']['submit']['#ajax'] = array(
  'callback' => 'Drupal\MY_MODULE\Plugin\Form\FormAlter::ajaxFormEntityCallback',
  'wrapper' => $ajax_id,
  'effect' => 'fade',
);
$form['ajax_form_entity'] = [
  '#type' => 'hidden',
  '#value' => [
    'reload' => '.reload',
    'form_selector' => '.' . $ajax_id,
    'show_message' => TRUE,
  ]
];

public static function ajaxFormEntityFormSubmit($form, &$form_state) {
    $entity = $form_state->getBuildInfo()['callback_object']->getEntity();

    // Clear user input.
    $input = $form_state->getUserInput();
    // We should not clear the system items from the user input.
    $clean_keys = $form_state->getCleanValueKeys();
    $clean_keys[] = 'ajax_page_state';
    foreach ($input as $key => $item) {
      if (!in_array($key, $clean_keys) && substr($key, 0, 1) !== '_') {
        unset($input[$key]);
      }
    }

    // Store new entity for display in the AJAX callback.
    $input['entity'] = $entity;
    $form_state->setUserInput($input);

    // Rebuild the form state values.
    $form_state->setRebuild();
    $form_state->setStorage([]);
  }

And the callback:
public static function ajaxFormEntityCallback(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    // If errors, returns the form with errors and messages.
    if ($form_state->hasAnyErrors()) {
      return $form;
    }
    // Else show the result.
    else {
      $userInputs = $form_state->getUserInput();
      $entity = $userInputs['entity'];
      $entity_type = $entity->getEntityTypeId();
      $configurations = $form_state->getValue('ajax_form_entity');

      $response = new AjaxResponse();

      // Get messages even if not shown.
      $status_messages = array('#type' => 'status_messages');
      $message = \Drupal::service('renderer')->renderRoot($status_messages);

      // Reload the form.
        $response->addCommand(new ReplaceCommand($configurations['form_selector'], $form));

      return $response;
    }
  }


how to determine an integer in a string list

Question: i have a problem if i have a string list
for example :
token=[aaa,bbb,ccc,ddd,0,eee,40,ggg,5]
how can i do to check whether token[i] is an integer
i want to see if token[i] is integer
i will put it in to a new string list by i+1:number
ex if token[4]=0 i will put it into result[5]="5:0"

sorry for explain not clear
first if i have many data
ex
39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Male, 2174, 0, 40, United-States, <=50K
50, Self-emp-not-inc, 83311, Bachelors, 13, Married-civ-spouse, Exec-managerial, Husband, White, Male, 0, 0, 13, United-States, <=50K
second i need to convert those data into specific number
ex State-gov into 2:1  Self-emp-not-inc into 2:2
however i can convert string into number but i cannot convert number into number
ex if token[4]=0 i will put it into result[5]="5:0"
for line in lines:
    token=re.split(', ',line)

  for i in range(0,13,1):
    try:
        value = int(token[i])

    except ValueError:
        pass
    if (token[14] in '<=50K.'):
        result.append('1')
    if (token[14] in '>50K.'):
        result[j].append('2')
    if (value == true):
        result.append('i+1:token[i]')
    if (token[i] in '?'):
        result.append('i+1:0')
    if(token[i] in 'State-gov'):
        result.append("2:1")
    if(token[i] in 'Self-emp-not-inc'):
        result.append('2:2')

Comment: I dont think that this question is a duplicated !!!
Comment: I agreed 100%, this is a totally different question. At first I thought, "What, is it really possible that Python is so lame that all the elements of an array have to be of the same type, like original BASIC??!" That's the only way I could explain why someone would think a question asking how to determine if an array element is an integer is the same question as how to check if a string can be represented by a number. Thankfully, [it's not](http://stackoverflow.com/q/11387752/1248365). I'm voting to reopen.
Answer: the function type, returns the type of the object
>>> type(10)
<type 'int'>
>>> type("10")
<type 'str'>

Comment: The OP specifies a list of strings. Also, `isinstance` is generally preferred to `type`.
Comment: can you explain simplely i am a new come to python Q
Answer: >>> "13".isdigit()
True
>>>

Answer: You need to use isinstance if you want to check the type of entry , and if you have multitype elements in your list :
>>> token=['aaa','bbb','ccc','ddd',0,'eee',40,'ggg',5]
>>> ["{}:{}".format(i,j) for i,j in enumerate(token,1) if isinstance(j,int)]
['5:0', '7:40', '9:5']

Comment: but i stll need to convert aaa----->1:1 for example
Comment: @jackson whay ? it doesn't contain any digit ?
Comment: i am try to do data mining i have to convert some information in to number
ex: U.S.A----->10:1
Comment: so based on what logic ? also you didn't speak about string in your question 1!!!
Comment: so i do this
if(token[i] in 'State-gov'):
result.append("2:1")

if the data is string not number
Comment: based on whatever i choose the number i can set randomly
ex U.S.A---->10:1 Taipei----->10:2
Comment: @jackson randomly what ?? pleaaaaaase add a clear explain to your question !
Comment: @jackson i though your question is not duplicated and i gave you +1 , if you want get a good answer , you need to say clearly what you want , also if until now you find my answer useful you can tell this to community by voting !
Comment: @Kasra i explain again can u help me plzQQ


Get number from user input and create users based on answer

Question: I want to take two parameters and based on these parameters, to create users with email.
country = input("country shortcut").
The user will input country shortcut 'SG' as well as
users = int(input("How much users would you like to create"))
Number of users.
Taking those 2 parameters together and based on input number 2 it will create a user email such as:

firstname.lastname@example.com, firstname.lastname@example.com, firstname.lastname@example.com
Comment: What have you tried so far to solve this problem? Could you post some relevant code other than the brief variable declarations you've added?
Comment: What do you mean by create users emails? Do you mean create instances of an object or just return some strings?
Comment: I'd like to return some strings just for my own use.
Answer: you can do it with a little list comprehension:
country = 'sg'
users = 2

print(['{}{}@example.com'.format(country,i+1) for i in range(users)])

edit: rereading your question it seems that you also want a "base" email without a number, so the comprehension will look more like this:
['{}@example.com'.format(country)] + ['{}{}@example.com'.format(country,i+1) for i in range(users)]

Comment: Exactly what I was looking for, Thanks! now I'll be able to do the same for passwords as well!
Answer: text formatting is pretty simple, i recommend the python decontamination.
for you problem
user amount = range(user_amount)
email_list =  ["{firstname.lastname@example.com".format(country_shortcut, code) for code in user_amount]

Answer: country = input("country shortcut")
users = int(input("How much users would you like to create"))
emails = []
for x in range(users):
    emails.append('{}{}@example.com'.format(country, "" if (x==0) else x))
print(emails)

Output:
    ['firstname.lastname@example.com', 'firstname.lastname@example.com', 'firstname.lastname@example.com']