Can somebody explain to me NUTS in english?

Question: My understanding of the algorithm is the following:
No U-Turn Sampler (NUTS) is a Hamiltonian Monte Carlo Method. This means that it is not a Markov Chain method and thus, this algorithm avoids the random walk part, which is often deemed as inefficient and slow to converge.
Instead of doing the random walk, NUTS does jumps of length x. Each jump doubles as the algorithm continues to run. This happens until the trajectory reaches a point where it wants to return to the starting point.
My questions:
What is so special about the U-turn?
How does doubling the trajectory not skip the optimized point?
Is my above description correct?
Comment: I found this [post](http://elevanth.org/blog/2017/11/28/build-a-better-markov-chain/) and the illustrated simulations really make a difference in the explanation of the concepts.
Answer: The no U-turn bit is how proposals are generated. HMC generates a hypothetical physical system: imagine a  ball with a certain kinetic energy rolling around a landscape with valleys and hills (the analogy breaks down with more than 2 dimensions) defined by the posterior you want to sample from. Every time you want to take a new MCMC sample, you randomly pick the kinetic energy and start the ball rolling from where you are. You simulate in discrete time steps, and to make sure you explore the parameter space properly you simulate steps in one direction and the twice as many in the other direction, turn around again etc. At some point you want to stop this and a good way of doing that is when you have done a U-turn (i.e. appear to have gone all over the place).
At this point the proposed next step of your Markov Chain gets picked (with certain limitations) from the points you have visited. I.e. that whole simulation of the hypothetical physical system was "just" to get a proposal that then gets accepted (the next MCMC sample is the proposed point) or rejected (the next MCMC sample is the starting point).
The clever thing about it is that proposals are made based on the shape of the posterior and can be at the other end of the distribution. In contrast Metropolis-Hastings makes proposals within a (possibly skewed) ball, Gibbs sampling only moves along one (or at least very few) dimensions at a time.
Comment: Meaning having some indication that it has covered the distribution, which NUTS tries to judge by whether you've totally turned around. If that's the case, you hopefully can in one MCMC step go to any part of the posterior. Of course, the condition does not truly guarantee that you have explored the whole posterior, but rather gives an indication that you've explored the "current part" of it (if you have some multimodal distribution you may have trouble to get to all parts of the distribution).
Comment: Could you expand on the "*appear to have gone all over the place*" comment please?
Answer: You're incorrect that HMC is not a Markov Chain method. Per Wikipedia:

In mathematics and physics, the hybrid Monte Carlo algorithm, also known as Hamiltonian Monte Carlo, is a Markov chain Monte Carlo method for obtaining a sequence of random samples from a probability distribution for which direct sampling is difficult. This sequence can be used to approximate the distribution (i.e., to generate a histogram), or to compute an integral (such as an expected value).

For more clarity, read the arXiv paper by Betancourt, which mentions the NUTS terminating criteria:

... identify when a trajectory is long enough to yield sufficient exploration of the neighborhood around the current energy level set. In particular, we want to avoid both integrating too short, in which case we would not take full advantage of the Hamiltonian trajectories, and integrating too long, in which case we waste precious computational resources on exploration that yields only diminishing returns.

Appendix A.3 talks about something like the trajectory doubling you mention:

We can also expand faster by doubling the length of the trajectory at every iteration, yielding a sampled trajectory t ∼ T(t | z) = U T2L  with the corresponding sampled state z′ ∼ T(z′ | t). In this case both the old and new trajectory components at every iteration are equivalent to the leaves of perfect, ordered binary trees (Figure 37). This allows us to build the new trajectory components recursively, propagating a sample at each step in the recursion...

and expands on this in A.4, where it talks about a dynamic implementation (section A.3 talks about a static implementation):

Fortunately, the efficient static schemes discussed in Section A.3 can be iterated to achieve a dynamic implementation once we have chosen a criterion for determining when a trajectory has grown long enough to satisfactory explore the corresponding energy level set.

I think the key is that it doesn't do jumps that double, it calculates its next jump using a technique that doubles the proposed jump's length until a criteria is met. At least that's how I understand the paper so far.


solve $\int_0^{2} x^{2}\ e^{x^2} dx$

Question: $$\int_0^{2} x^{2}\ e^{x^2} dx$$
I tried using integral by parts: $u=x$ , $dv= e^{x^2}dx$ but the answer is: $ \frac{1}{2}xe^{x^2}$- $\frac{1}{2}\int e^{x^2}dx$ and I cant calculate $\int e^{x^2}dx$
Comment: That can't be done with "elementary" functions. One needs the error function (on the complex plane).
Comment: Any chance there is a typo and it's $\int x e^{x^2} \mathrm dx$ instead?
Comment: Or $\int x^3e^{x^2}dx$ for that matter?
Comment: Your integral by parts may be missing a factor of $\frac12$
Comment: it is weird because we are not familiar with complex plane in university
Comment: maybe he means that
Comment: Numerical methods suggest $\int_0^{2} e^{x^2} dx\approx 16.45263$  and $\int_0^{2} x^{2}\ e^{x^2} dx \approx 46.37184$.  Meanwhile $\operatorname{erfi}(2) = 18.5648024145755525987\ldots$
Comment: yes true i missed 1/2
Comment: @Soheil0098 could you please correct the answer obtained with integration by parts?
Comment: i did correct it
Comment: @Soheil0098 nevermind, the page just updated for me
Comment: haha it is a little hard for me using math jax
Comment: @Soheil0098 is the answer to the given question supposed to be $0$?
Comment: I dont know the answer it seems  there is a typo but why the answer should be 0?
Answer: The imaginary error function $\operatorname{erfi}(x)=\frac{2}{\sqrt{\pi}}\int_0^xe^{t^2}dt$ satisfies $\int_0^2e^{ax^2}dx=\frac12\sqrt{\frac{\pi}{a}}\operatorname{erfi}(\sqrt{a})$, which you can differentiate with respect to $a$ to obtain$$\int_0^2x^2e^{ax^2}dx=\frac{2e^a-2\sqrt{\pi}\operatorname{erfi}(\sqrt{a})}{4a^{3/2}}.$$Hence $\int_0^2x^2e^{x^2}dx=\frac{2e-2\sqrt{\pi}\operatorname{erfi}(1)}{4}$.
Answer: $$x^2e^{x^2}=\sum_{n=0}^{\infty}\frac{x^{2n+2}}{n!}$$
So $$\int_0^2x^2 e^{x^2}dx=\int_0^2 \sum_{n=0}^{\infty}\frac{x^{2n+2}}{n!}dx=\sum_{n=0}^{\infty}\int_0^2\frac{x^{2n+2}}{n!}dx$$ $$=8\sum_{n=0}^{\infty}\frac{4^n}{n!(2n+3)}$$
The integral and summation can be interchanged by uniform convergence of the series on the interval $[0,2]$

solve $\int_0^{2} x^{2}\ e^{x^2} dx$


nginx fails routing when slash is at the end

Question: The following nginx config serves http://alpha.mydomain/mypath/test fine, however fails on http://alpha.mydomain/mypath/test/ with 500 Internal Server Error. Notice the slash in the end of the second URL.
The app is HTML5 application therefore the intent is to serve index.html for all /mypath/ paths and let the client side handle the logic.
server {
listen *:80;
server_name alpha.mydomain.com beta.mydomain.com;

location ~ ^/mypath/.*$ {
    default_type text/html; # fix for octet stream coming back sometimes
    alias /home/ubuntu/myproject-web/index.html;
    add_header Content-Type text/html;
}

location / {
    alias /home/ubuntu/myproject-web/;
}

}

Comment: Exactly how does it "fail"?
Comment: 500 Internal Server Error
Comment: What's in nginx's error log, then?
Comment: "/home/ubuntu/myproject-web/index.htmlindex.html" is not a directory
Answer: Maybe not a fix per se, but you can work around this issue by adding the following line to your config:
rewrite (.*)/$  $1;


Tweaking the "Press this" Wordpress bookmarklet

Question: I'm using the default Wordpress "Press This" bookmarklet which is good, but I want to change a couple of things.
this is the code:
javascript:var%20d=document,w=window,e=w.getSelection,k=d.getSelection,x=d.selection,s=(e?e():(k)?k():(x?x.createRange().text:0)),f='http://superarsha.wordpress.com/wp-admin/press-this.php',l=d.location,e=encodeURIComponent,u=f+'?u='+e(l.href)+'&t='+e(d.title)+'&s='+e(s)+'&v=4';a=function(){if(!w.open(u,'t','toolbar=0,resizable=1,scrollbars=1,status=1,width=720,height=570'))l.href=u;};if%20(/Firefox/.test(navigator.userAgent))%20setTimeout(a,%200);%20else%20a();void(0)

what I want:
1: insert the URL in the first line.
2: replace the original title on the body with just "YouTube" link to the source page.
if number 2 is not clear then here's an example:
when "press this" on a youtube video, the body will come like this (video_title_here - YouTube).
what I want is just (YouTube)
Comment: actually I tried nothing, because I can't write codes !
Answer: i posted this answer elsewhere as well:
You have to modify the press-this.php file in the wp-admin folder, as well as the bookmarklet javascript.
By default, wordpress will use the same information for both the post title and the link title, so you need to modify the press-this.php file so it separates the two.
Here is a pastebin link to a modified press-this.php: http://pastebin.com/5ZaYCpJ0
Here is the modified bookmarklet javascript:
javascript:var%20d=document,w=window,e=w.getSelection,k=d.getSelection,x=d.selection,s=(e?e():(k)?k():(x?x.createRange().text:0)),f='http://superarsha.wordpress.com/wp-admin/press-this.php',l=d.location,e=encodeURIComponent,r=/youtube.com/i,t=d.title,n=(r.test(l.href)?'YouTube':d.title),u=f+'?u='+e(l.href)+'&t='+e(t)+'&n='+e(n)+'&s='+e(s)+'&v=4';a=function(){if(!w.open(u,'t','toolbar=0,resizable=1,scrollbars=1,status=1,width=720,height=570'))l.href=u;};if%20(/Firefox/.test(navigator.userAgent))%20setTimeout(a,%200);%20else%20a();void(0)


Interpretation Beta coefficient regression gamma distribution

Question: I am currently working on a panel data model of 30 companies over 10 years where the dependent variable is a score (decimal bounded between 0 and 1, continuous) while the independent are dummies and their lags.
I ran different models on Stata, but the only one fitting my data is generalized estimating equations (GEE) with family Gamma and link reciprocal, for which I get significant result.
My question is: how do I interpret the coefficients? they are very big (eg -21, 18) and I know I can't interpret them as in the linear regression.
Comment: You may request the program to exponentiate the beta coefficient in Gamma regression if your analysis program had that option, the exponentiated beta coefficient is interpreted just like a risk rate, or literally a rate intepreted just like an odds ratio.
Answer: The documentation in xtxtgee stata is quite specific as to what this is.
The reciprocal link is regression with the target (A.K.A., dependent variable linked to) being $\frac{1}{y}$, as contrasted to the usual $y$. In that software, the family(gamma) has link(reciprocal) as its default. The gamma referred to appears to be the gamma distribution PDF, which in stata has the form $$\operatorname{gammaden}(a,b,g,x)=
 \frac{(x-g)^{a-1} e^{-\frac{x-g}{b}}}{\Gamma (a)b^a}\,, \quad x>0 \,,$$ which is often used setting $g=0$ to become a two parameter distribution.
Now since $a>0$ by definition, I think $a=-21$ says something is very wrong. It might help your cause if you were to show some I/O. It would not be too unusual to write the gamma distribution parameters as $\beta$ and $\theta$ but I cannot confirms this without more information.
The reason I say that this is probably the gamma distribution is because the table in the xtxtgee file lists
<code>family                  Description
______________________________________________________________________
gaussian                Gaussian (normal); family(normal) is a synonym
igaussian               inverse Gaussian
binomial [# | varname]  Bernoulli/binomial
poisson                 Poisson
nbinomial [#]           negative binomial
gamma                   gamma
</code>
That is, everything else in the table besides "gamma" is a probability distribution.
Comment: Dear @Carl I just noticed that probably I have not presented my question in the right way: I am interested in understanding the interpretation of the Beta coefficient in a regression where I use GEE family(gamma) link(reciprocal), not in estimating the two parameters of the Gamma function. May you please help me out with that? Thank you!!
Comment: Dear @Carl , thank you very much for your answer. So, in the GEE with gamma distribution and reciprocal link all the regression beta coefficients should be greater than zero?  And what would be the interpretation? Would it be as in normal linear regression, ie. one unit increase in X1 leads to Beta1 increase in the dependent variable?  From my results my regression beta coefficients are both positive and negative and are big, they oscillate between -21 to +18 depending on the independent variable. Thank you very much in advance!
Comment: @DavideL If you show a plot of the fit, and the values in table form, it would be a lot easier to comment. Otherwise, I am just reading stata documentation, which has me somewhat at a disadvantage (although slight) since I do not use that particular program, so that I cannot test my guesses as to what they mean when the documentation is inexact.
Comment: @DavideL Can't be absolutely sure but what you have is probably not the gamma function, $\Gamma (a)$, nor is it likely to be the incomplete upper gamma function, symbolized $\Gamma (a,b)$. Rather, from the context it is likely the two parameter [gamma distribution density function](https://en.wikipedia.org/wiki/Gamma_distribution).
Comment: Thank you very much! I used in the end a simple Gaussian as my variable di not have excessive skewness to justify a gamma


Bivariate cointegration in a multiple regression error correction model

Question: I am new to cointegration and ECM.
I have two I(1) variables that I have estimated and their linear combination is I(0) as per the Engle-Granger test.
Is it then possible to use this error-correcting term in an OLS regression with additional exogenous variables? (i.e., z in the below example)
Example:
$$
y_{t} =  \alpha +   \gamma x_{t} +  u_{t}
$$
After, the above is estimated it is added as the error correction in the below ECM:
$$
\Delta y_{t} = c + \beta_{1}\Delta x_{t-1} + \beta_{2}\Delta y_{t-1} + \beta_{3}\Delta z_{t-1} + \delta( {y}_{t-1} -  \widehat{a} -  \widehat{\gamma}x_{t-1})
$$
Comment: Why is $y$ without an index but $x$ and $u$ indexed by $i$ rather than $t$? Is $\Delta y$ missing an index $_t$? Why is there a hat over $y_{t-1}$?
Comment: Sorry, corrected, still getting the hand of notation in LaTeX.
Answer: Yes, this should be possible as long as $\Delta z_{t-1}$ is I(0). Then both the left hand side and the right hand side are I(0) and thus you have a balanced regression.


Replicating Rails timezone "magic" in Postgres

Question: Is there a way I can have Postgres (I use Navicat but will demonstrate via the command line tool) behave in the same way that Rails does when it comes to timezones and UTC?
Rails seems to do some magic that makes Postgres behave in a UTC-fashion; whereas via the command line (or Navicat) it is using my system timezone.  This is confusing because results vary based on whether I am executing the query in Ruby/Rails or in the console.
I still struggle with timezones in Postgres but having Rails and the console exihibit different behavior is maddening.  Can I remedy this?
Here is one example (different output values):
-- in postgress:
# select ('2018-11-06' at time zone 'utc')::timestamptz;
        timezone
------------------------
 2018-11-06 08:00:00-08
(1 row)

-- in rails console
> ApplicationRecord.execute("select ('2018-11-06' at time zone 'utc')::timestamptz").first
   (0.5ms)  select ('2018-11-06' at time zone 'utc')::timestamptz
=> #<OpenStruct timezone="2018-11-06 00:00:00+00">

They are both formatted differently (-00 vs -08) and, even more confusing, they return actual different times.
The Postgres example is returning a result 16 hours ahead of the Rails one!
Answer: In my understanding, it is not a Rails magic, but Rails simply uses the UTC as the default.  And that is why Rails can and does use timezone as opposed to timezonetz or something for the default database type for created_at etc.
You can modify the Rails default timezone as follows if you like (see the official reference):
# application.rb:
class Application < Rails::Application
  config.time_zone = 'Eastern Time (US & Canada)'
end

As for PostgreSQL, your result is not ahead; it seems your default time zone is somewhere in the American continent (8 hours behind the UTC).  You can check it as follows:
postgres=> SET TIME ZONE 'America/New_York';
postgres=> select ('2018-11-06' at time zone 'UTC')::timestamptz;
        timezone
------------------------
 2018-11-06 05:00:00-05
(1 row)

I don't know what Navicat does.  But maybe check out your postgresql.conf.  You may reset your timezone to the UTC if you want (and restart the postgreSQL server).
See this answer to "postgres default timezone" for further detail.
Comment: Thanks for that information.  Unless I am really confused, however: `2018-11-06 08:00:00-08` *is* 16 hours ahead of `2018-11-06 00:00:00+00`.  I added a photo to the post showing how `moment()` would interpret those two timestamped values.  PS - the `SET TIME ZONE` did the trick though I think.  Thanks.
Comment: I see, I'm with you. "08:00:00-08" is 8 am at the time zone of -8hours, and so it is equivalent to 4pm at UTC. Sorry, I too was confused…


Access SQL Calculating inventory at certain date, stock results doubling when ordered twice

Question: I have an SQL Query which shows the inventory status before any orders in or out:
SELECT Query3.Products.ID, Query3.ProductName, Query3.StandardCost, Query3.OnHand,
  Nz(Sum([OrderJoin.Quantity]),0) AS Outgoing, Nz(Sum([Query1.Quantity]),0) AS Incoming,
  [OnHand]+[Outgoing]-[Incoming] AS OnHandAfter, [StandardCost]*[OnHandAfter] AS TotalCost
FROM Query3
GROUP BY Query3.Products.ID, Query3.ProductName, Query3.StandardCost, Query3.OnHand;

And then I've tried to filter it so it accepts a user-inputted date to back-track stock status to:
SELECT Q1.Products.ID,
 Q1.ProductName,
 Q1.StandardCost,
 Q1.OnHand,
 SUM([Q1.OnHand] + [Q2_sub.Outgoing] - [Q3_sub.Incoming]) AS OnHandAfter,
 ([Q1.StandardCost] * [OnHandAfter]) AS TotalCost
FROM (
 Query3 AS Q1
      LEFT JOIN (
           SELECT Q2.Products.ID,
                Q2.ProductName,
                Q2.StandardCost,
                Q2.OnHand,
                NZ(Sum([OrderJoin.Quantity]), 0) AS Outgoing
           FROM Query3 AS Q2
           WHERE (
                     (
                         (ShippedDate) > [Enter End Date]
                         OR (ShippedDate) IS NULL
                         )
                     )
           GROUP BY Q2.Products.ID,
                Q2.ProductName,
                Q2.StandardCost,
                Q2.OnHand)  AS Q2_Sub ON Q1.Products.ID = Q2_Sub.ID)
      LEFT JOIN (
                SELECT Q3.Products.ID,
                     Q3.ProductName,
                     Q3.StandardCost,
                     Q3.OnHand,
                     NZ(Sum([Query1.Quantity]), 0) AS Incoming
                FROM Query3 AS Q3
                WHERE (
                     (
                         (DateReceived) > [Enter End Date]
                         OR (DateReceived) IS NULL
                      )
                 )
                GROUP BY Q3.Products.ID,
                     Q3.ProductName,
                     Q3.StandardCost,
                     Q3.OnHand)  AS Q3_Sub ON Q1.Products.ID = Q3_Sub.ID
GROUP BY Q1.Products.ID, Q1.ProductName, Q1.StandardCost, Q1.OnHand;

It comes to mostly correct results, but there are some that are completely off,
EDIT:
After looking into it, it appears some are doubling up in the Outgoing/Incoming columns
EDIT EDIT:
The thing the products that are doubling up have in common are they've all been ordered on two occasions. (i.e. the coffee has been ordered once for 25 and once for 5, but comes up as 60.) How do I fix it from counting them both twice?
Also a couple such as Crab Meat now seem to be counting cumulatively, i.e. when I first ran it it came up as 370 OnHandAfter, and now it's coming up as 416 after adding 46 again
What it should be
| ID | Product Name | Standard Cost | On Hand | Outgoing | Incoming | OnHandAfter | TotalCost |
| 14 | Crab Meat    | £13.80        | 185     | 23       | 0        | 208         | £2,870.40

What it comes to
| ID | Product Name | Standard Cost | On Hand | Outgoing | Incoming | OnHandAfter | TotalCost
| 14 | Crab Meat    | £13.80        | 185     | 46       | 0        | 370         | £5,106.00

What it should be
| ID | Product Name | Standard Cost | On Hand | Outgoing | Incoming | OnHandAfter | TotalCost |
| 16 | Coffee       | £34.50        | 150     | 30       | 152      | 28          | £966.00

What it comes to
| ID | Product Name | Standard Cost | On Hand | Outgoing | Incoming | OnHandAfter | TotalCost
| 16 | Coffee       | £34.50        | 150     | 60       | 304      | 46          | £1,587.00

Comment: what happens if you try using `select distinct`?
Comment: @LiamH No change, the results come out in one row, just the value doubles when it's been ordered on more than one occassion
Answer: As you use Pound, you're probably from the UK, thus having dates formatted as dd/mm/yyyy.
So, in your query, you may have to specify [Enter End Date] as a Parameter of data type Date and - as the date fields can be Null - take care of that, like replacing this:
(ShippedDate) > [Enter End Date]
OR (ShippedDate) IS NULL

with:
Nz([ShippedDate], #9999/12/31#) > [Enter End Date]

Comment: Ok thank you for that, it looks like in Access the date for me automatically comes as DD/MM/YYYY, but I didn't even think of that


Chopin's Etude Op. 25, Nr. 2

Question: I am having a hard time to play this etude quietly when I increase the speed to full tempo. I play it fast and relaxed but still my right hand seems too loud at that speed. Especially the first two bars, particularly when I play the black keys with finger 3 and 4 of my right hand. What are useful ways to practice the right hand to play quietly at speed? Trying to play trills but quietly? Staccato? Both hands or hands separated?
I watched the Paul Barton tutorial on this etude on Youtube where he introduces some exercises (from Cortot) like staccato playing. But I still have a hard time to reduce my volume in the right hand at full speed, even though I did practice the exercises. So I am not even sure, if these exercises are useful to reduce loudness or if they are just for finger dexterity and endurance.
Even though the notes are not that hard to play in this etude, it seems like one of the fastest etudes of Chopin (check for example Pollini's version) which makes it for me very hard to keep quiet dynamics (It is also easy to overpedal). Thank you for help.
Comment: Do you know the studies of Godowsky? https://en.wikipedia.org/wiki/Studies_on_Chopin%27s_%C3%89tudes
Comment: @AlbrechtHügli Yes I know some pieces, but I thought they were much harder than the original Chopin pieces...?
Comment: Watch the video by Josh Wright: https://www.youtube.com/watch?v=IeHPlCcxm7E
Comment: @Haversine I know that video, but this doesn't help much. Trust me, once you play this piece. There are so many things you have to master, if you want to play it at somewhere close as for example Pollini.
Comment: That is the only video I watched and I became proficient at it.... I got second place at an international competition (first place played op 10 no.4)
Answer: What I can advise to you (I have the same problem every time when I learn a new piece) is to make sure you listen to how you're playing, try and relax your wrists and don't hit the keys. I had this problem when I was younger and my teacher always used to tell me to relax my wrists. If you're playing from you're wrists, then you have no control over the notes.
I hope this helps you and best wishes with your piece
P.S. when I say relax your wrists, I mean to loosen your wrist an make it go floppy (not too floppy so it literally flops off the piano) but to make your wrist a bit more flexible
Answer: If the Cortot-Barton video is helpful for you, great.  If not -- here's a different approach:
You can work with the piece directly, grouping the written notes in a variety of ways, repeating a given grouping several times, until fluidity is achieved.  When you've gotten comfortable with the pattern of notes in the group, your brain will be able to send one signal for each group, rather than one signal per note.  This allows one to play with gentle fluidity and no unnecessary tension.
I found the score here.
The natural grouping for these twelve notes per measure would be, initially, as follows: play the first six notes of the measure quickly, and then the next one as a half note.  This allows your hand and brain to rest.  Then play the last six notes of the measure, followed by the first note of Measure two, played as a half note.  And so on.
Note that the note you'd be playing as a half note will be repeated, as the first note in the next group of six quick notes.
After a few days with the above grouping, the next step is to play twelve notes, followed by the next note played as a half note; then the twelve notes of Measure two, in tempo, followed by the next note, as a half note; etc.  As above, the long note where you allow yourself to rest will be played again as the first note of the group of six triplets.
Proceeding in this way, you give your hand and brain a chance to rest and recover.  Also, you're training your hand to respond to one signal from the brain to produce a slew of notes.
If the above gets you to where you want to be, great.  If not, you can alter the rhythm of the original piece, to come up with different groupings.  For example, you could play four notes and the fifth note as a long note.  For the next group, begin, of course, with the fifth note; play four notes quickly and fluidly, and then the next note is your long note where you allow yourself to rest and recover.  After a couple of days practicing this way, you can make a larger grouping, and play eight quick notes and then a long, restful note; etc.
Comment: Thanks for the answer, though I am not sure how this helps me to reduce loudness. I am playing it fluently and without tension but I can not play it "piano" at full speed.
Comment: @Matriz - Okay, glad to hear you've got the desired fluency at tempo.  I'll try to explain the approach I described better.  It will be easier if I speak first about my main instrument, cello.  In earlier times, teachers and etude books told one to develop "hammer fingers."  Turns out that's actually counter-productive.  One can get better results by using arm weight, rather than trying to be *forceful*.  Now, back to the piano: when I was practice coach for my son, I noticed that grouping, allowing a beat for recovery, was also helpful for the piano.  Whatever goal you have, whatever...
Comment: ... change you're trying to effect, is easier to re-imprint (e.g. playing certain notes softer) if you allow yourself that recovery time, and if you group notes to send one instruction from the brain to get a group of notes, rather than one message for each note. (Often one isn't of sending so many instructions!  But by practicing as I outlined, you'll enable a whole group of notes to emanate from one instruction.  Side benefit of this: it frees your brain up to do other things. I can't guarantee this will help you.  (If you decide to give it a try, I hope you'll keep us posted.)

Chopin's Etude Op. 25, Nr. 2


I've changed ISP, now www access to my website is not working, but HTTP is

Question: I've inherited a company's IT position, so I was not in on the original configuration. We have recently changed our ISP (several months ago). Our Domain is hosted by Network Solutions and their A Records have been updated.
The setup is this:
We have three servers

Domain Controller (server 2008r2)
Exchange 2010 running on server 2008r2
NAV running on server 2008r2

The website is on the exchange server.
I've updated the A Records (including the www) at the Domain Host to the static IP address Cox assigned us 24.255.xxx.xxx. Mail and everything else works great. That is, except for our website using www.xxxxxx.com (that gives a 404 error) http://xxxxxx.com works fine.
When I'm outside the network and ping the www.xxxxxx.com I get the IP address Cox gave us. When I do an NSLOOKUP I get an IP address of a Cox DNS Server 68.105.xxx.xxx. If I do the same steps while on the network I get a local IP Address 192.168.xxx.xxx (same results on the NSLOOKUP).
I'm stumped and have tried everything I found on this site and many others.
Comment: I can't reproduce the problem. I get a 200 on both `xxxxxx.com` and on `www.xxxxxx.com`.
Comment: When using nslookup, you can test using an outside DNS server by specifying it as the second argument. Test this using, say, `nslookup www.xxxxxx.com 220.127.116.11` and `nslookup www.xxxxxx.com 18.104.22.168`. You can do that from inside your network. Post back whether that works correctly or not.
Answer: What does your internal network's DNS configuration look like?
Your local server seems to be giving an internal address for the web server, which would be necessary to access the web server in a hairpin NAT scenario; was the website formerly hosted inside the network?
You should:

Determine which address you need to use when inside the network to successfully connect to the web server - sounds like it should be using the public address.
Verify via hosts file that the address works as expected when it's resolved as that name
Update your internal DNS configuration to return the correct address for queries to that name
Answer: I have a feeling that this is a host header problem in IIS. But I'll get to that in a sec, for now here's a general troubleshooting guide for you to follow:

If you're using an internet facing DNS server and try to resolve www.xxxxxx.com and xxxxxx.com, make sure that both of them are forwarding to the correct static IP address of your company have.
If you're using a LAN facing DNS server, make sure that the same records above resolve to your internal IP address of the web server (in your case, the exchange one)
If you're using an application level firewall, insure that www.xxxxxx.com and xxxxxx.com are allowed in and can be routed to the internal IIS server. this vary depending on your firewall type.
Make sure that the company web site in your IIS have host headers for www.xxxxxx.com and xxxxxx.com, this is needed in order to let incoming requests for the mentioned domain names to go to the correct site since you're using multiple sites in IIS, more info can be found here: http://technet.microsoft.com/en-us/library/cc753195(v=ws.10).aspx

Hope this helps.


JsGrid Sorting not working

Question: Following is part of my JsGrid code, which I think something is missing in order for me to sort my data like any other examples on Fiddle.
autoload: true,
inserting: false,
editing: false,
paging: true,
pageIndex: 1,
pageSize: 5,
pageLoading: true,
autoload: true,
filter: true,
sorting: true,

controller: {
  loadData: function(filter) {
    return $.ajax({
      type: "GET",
      url: BASE_URL,
      data: filter,
      dataType: "json",
      cache: false
    });
  },
},

I have tried with sorting:"number".
Answer: Below logic of sorting on the basis of number

    $("#Grid2").jsGrid({
        height: "auto",
        width: "100%",

        filtering: false,
        editing: false,
        sorting: true,
        paging: true,
        autoload: true,
        inserting: false,
        pageSize: 15,
        pageButtonCount: 5,

        controller: {
            loadData: function(filter) {
                var d = $.Deferred();
                $.ajax({
                    cache: false,
                    type: 'GET',
                    url: "http://" + servername + ":" + portnumber + "/api,
                    data: filter,
                    dataType: "json",
                    success: function(data) {
                        filteredData = $.grep(data, function(item) {
                            //filtering logic
                            ;
                        });
                        d.resolve(filteredData);
                        testdata = JSON.stringify(data);
                        $("#Grid2").jsGrid("sort", 1);
                        HistoricData = data;
                    },
                    error: function(e) {
                        console.log(e);
                        console.log(e.responseText);
                        var errorMsg = e.responseText;
                        var msg = errorMsg + " for this particular combination";
                        showError(msg);
                        $("#displayingHistoryValues").hide();
                        $("#ExportGrid2").hide();
                        $("#Grid2").hide();
                        d.resolve();
                    }
                });

                return d.promise();
            }
        },
        fields: [{
            title: "Value",
            name: "MeasureValue",
            type: "number",
            width: "5%",
            css: "custom-field",
            sorting: true,
            itemTemplate: function(value, item) {

                if (item.MeasureValue != null && item.MeasureValue != '' && item.MeasureValue.trim().length > 0) {
                    var mesval = FormatValeur(item.MeasureUnit, item.MeasureValue);
                    return "
" + mesval + "
";
                }

            }
        }, {
            type: "control",
            editButton: false,
            deleteButton: false,
            width: "5%"
        }]
    })

Another way to sort, get the filteredData or loaded  data
and call onRefresing of JSGrid .

Way to sort JS grid on column after grid load :

onRefreshing: function (args) {
            fundCodeList = [];
            jsonNumLst = [];
            jsonNANLst = [];
            if(this._visibleFieldIndex(this._sortField) == -1
                    || this._visibleFieldIndex(this._sortField)==1){

                $.each(filteredData, function(inx, obj) {
                    if($.isNumeric(obj.fundCode)){
                        jsonNumLst.push(obj);
                    }else{
                        jsonNANLst.push(obj);
                    }

                });

                if(this._sortOrder == undefined || this._sortOrder == 'asc'){
                    jsonNumLst.sort(sortByNumFCAsc);
                    jsonNANLst.sort(sortByNANFCAsc);
                }else if(this._sortOrder == 'desc'){
                    jsonNANLst.sort(sortByNANFCDesc);
                    jsonNumLst.sort(sortByNumFCDesc);
                }

                if(jsonNumLst.length>0 || jsonNANLst.length>0){
                    filteredData = [];
                    if(this._sortOrder == undefined || this._sortOrder == 'asc'){
                        $.each(jsonNumLst, function(inx, obj) {
                            filteredData.push(obj);
                        });
                        if(filteredData.length == jsonNumLst.length){
                            $.each(jsonNANLst, function(inx, obj) {
                                filteredData.push(obj);
                            });
                        }
                    }else if(this._sortOrder == 'desc'){
                        $.each(jsonNANLst, function(inx, obj) {
                            filteredData.push(obj);
                        });

                        if(filteredData.length == jsonNANLst.length){
                            $.each(jsonNumLst, function(inx, obj) {
                                filteredData.push(obj);
                            });
                        }
                    }
                }

                if((filteredData.length>0) && filteredData.length==(jsonNumLst.length+jsonNANLst.length)){
                    $("#measureImportGrid3").data("JSGrid").data = filteredData;
                    //isSortGrid = false;
                    //saveEffectControlData = $('#saveEffectiveControlGrid').jsGrid('option', 'data');
                }
            }

//Ascending order numeric
function sortByNumFCAsc(x,y) {
    return x.fundCode - y.fundCode;
}

//Ascending order nonnumeric
function sortByNANFCAsc(x,y) {
    return ((x.fundCode == y.fundCode) ? 0 : ((x.fundCode > y.fundCode) ? 1 : -1 ));
}

//Descending order numeric
function sortByNANFCDesc(x,y) {
    return ((x.fundCode == y.fundCode) ? 0 : ((y.fundCode > x.fundCode) ? 1 : -1 ));
}

//Descending order non-numeric
function sortByNumFCDesc(x,y) {
    return y.fundCode - x.fundCode;
}

        }

JsGrid Sorting not working


Populating dropdowns/selection lists

Question: I'm still in the process of learning DDD. I'm writing an ASP.NET MVC Application and I have several drop downs that I need to populate from the database. I've created mapped entities for every type (status, result, etc.)
What I can't figure out is from where I should be getting the data. Creating a separate repository for each type of selection list feels like a pain when you have to inject plenty of repositories into the MVC controllers. Also, all these selection lists are read-only so a repository per selection list seems overkill. Creating a single super repository for all selection list types doesn't seem right either, since a repository should be like a collection of one entity type.
I've been reading a little about CQS and having a reporting layer, but I don't know how that would be implemented correctly.
Answer: First of all - do not even look at CQRS if You don't feel comfortable with DDD. I mean - do look, but don't try to implement real project with it. Yet.
When we aren't separating read from write sides of our application, repository gets messed up a little bit cause of mixed responsibilities.
From one point of view - it is responsible for persisting aggregate root, from other - it's responsible for reporting too.
That means - there is nothing wrong (at least in my mind), if repository contains functionality to retrieve data for presentation purposes only.
In Your case - i would just build dropdowns using data from according repositories. So - Product dropdown list would take data from ProductRepository.Find(bySomething) (or Repository<Product>(bySomething) in case I decide to use generic repository).
P.s. Be warned that DDD isn't that much about patterns. It's more about ubiquitous language and making Your domain model explicit.

Populating dropdowns/selection lists


CentOS 7 - Cannot change subnet mask

Question: I just noticed that this CentOS 7 server's subnet mask is 255.255.255.0. It should be 255.255.255.240.
<code># ip a show ens32 | grep ens32
3: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 126.96.36.199/24 brd 126.96.36.199 scope global ens32
    inet 22.214.171.124/24 brd 18.104.22.168 scope global secondary ens32
    inet 188.8.131.52/24 brd 18.104.22.168 scope global secondary ens32
    inet 220.127.116.11/24 brd 22.214.171.124 scope global secondary ens32
    inet 126.96.36.199/24 brd 22.214.171.124 scope global secondary ens32
    inet 18.104.22.168/24 brd 126.96.36.199 scope global secondary ens32
</code>
I've tried unsuccessfully to change the subnet mask. The ifcfg-ens32 file has the correct prefix (/28). Even after restarting the network and rebooting the server the subnet mask is still 255.255.255.0.
<code># cat /etc/sysconfig/network-scripts/ifcfg-ens32
TYPE=Ethernet
BOOTPROTO=none
IPV4_FAILURE_FATAL=yes
DEVICE=ens32
ONBOOT=yes
PREFIX=28
GATEWAY=188.8.131.52
IPADDR0=184.108.40.206
IPADDR1=22.214.171.124
IPADDR2=22.214.171.124
IPADDR3=126.96.36.199
IPADDR4=220.127.116.11
IPADDR5=188.8.131.52
DNS1=127.0.0.1
NM_CONTROLLED=no
</code>
The IP addresses are static and the NetworkManager is not installed.
How do I fix the subnet mask?
Answer: You need to specify the CIDR prefix for each IP address. Right now none of them have it specified.
<code>PREFIX0=28
PREFIX1=28
PREFIX2=28
PREFIX3=28
PREFIX4=28
PREFIX5=28
</code>
Comment: @EsaJokinen It's undocumented except in the network-scripts themselves. But since these files are obsolete now (and were sort of deprecated back then) I wouldn't count on having an official source.
Comment: It seems a bit difficult to find a good source for this. Can you come up with one?
Comment: It's good it's obsolete. The syntax is quite horrible!

CentOS 7 - Cannot change subnet mask


Are there different types of infinity?

Question: Today in class my professor mentioned that there are different types of infinity. This confused me at first because I always thought infinity is just infinity. What are the different types of infinity?
Comment: Take a look [here](http://math.stackexchange.com/questions/1/different-kinds-of-infinities).
Answer: Your professor was talking about the distinction between countable & uncountable sets, established by Cantor's diagonal argument. See also Aleph number, Beth number, equinumerosity, & Cantor's contributions to set theory.
Comment: There's not only different *sizes* of infinity, but indeed also different *kinds* of infinity. For example, the usage of the symbol $\infty$ in limits, series, one-point-compactifications, ... is not really about cardinalities of sets.

Are there different types of infinity?


Uncaught Error: Rendered more hooks than during the previous render. How to fix?

Question: I need to fetch data from API based on key and place the data inside a tablecell. I have tried something like the following but didn't work. It is showing an uncaught error.In that case, I know hooks shouldn't be called inside loops, conditions, or nested functions. Then how I would get the item.id?

Uncaught Error: Rendered more hooks than during the previous render.

My code is:
import React, { useState, useEffect } from 'react';
import {
  Table, TableRow, TableCell, TableHead, TableBody,
} from '@mui/material';
import makeStyles from '@mui/styles/makeStyles';
import { useEffectAsync } from '../reactHelper';
import { useTranslation } from '../common/components/LocalizationProvider';
import PageLayout from '../common/components/PageLayout';
import SettingsMenu from './components/SettingsMenu';
import CollectionFab from './components/CollectionFab';
import CollectionActions from './components/CollectionActions';
import TableShimmer from '../common/components/TableShimmer';

const useStyles = makeStyles((theme) => ({
  columnAction: {
    width: '1%',
    paddingRight: theme.spacing(1),
  },
}));

const StoppagesPage = () => {
  const classes = useStyles();
  const t = useTranslation();

  const [timestamp, setTimestamp] = useState(Date.now());
  const [items, setItems] = useState([]);
  const [geofences, setGeofences] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetch('/api/geofences')
      .then((response) => response.json())
      .then((data) => setGeofences(data))
      .catch((error) => {
        throw error;
      });
  }, []);

  useEffectAsync(async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/stoppages');
      if (response.ok) {
        setItems(await response.json());
      } else {
        throw Error(await response.text());
      }
    } finally {
      setLoading(false);
    }
  }, [timestamp]);

  return (
    <PageLayout menu={<SettingsMenu />} breadcrumbs={['settingsTitle', 'settingsStoppages']}>

        <TableHead>
          <TableRow>
            <TableCell>{t('settingsStoppage')}</TableCell>
            <TableCell>{t('settingsCoordinates')}</TableCell>
            <TableCell>{t('sharedRoutes')}</TableCell>
            <TableCell className={classes.columnAction} />
          </TableRow>
        </TableHead>
        <TableBody>
          {!loading ? items.map((item) => (
            <TableRow key={item.id}>
              <TableCell>{item.name}</TableCell>
              <TableCell>{`Latitude: ${item.latitude}, Longitude: ${item.longitude}`}</TableCell>
              <TableCell>
                {
                  geofences.map((geofence) => geofence.name).join(', ')
                }
              </TableCell>
              <TableCell className={classes.columnAction} padding="none">
                <CollectionActions itemId={item.id} editPath="/settings/stoppage" endpoint="stoppages" setTimestamp={setTimestamp} />
              </TableCell>
            </TableRow>
          )) : (<TableShimmer columns={2} endAction />)}
        </TableBody>

      <CollectionFab editPath="/settings/stoppage" />
    </PageLayout>
  );
};

export default StoppagesPage;

Comment: "I know hooks shouldn't be called inside loops" So don't do that. Instead, when you get `items`, use `const ids = items.map((item) => item.id);` to get an array of ids, (from [From an array of objects, extract value of a property as array](https://stackoverflow.com/q/19590865/215552)), then use that to create an array of promises (i.e., [Javascript push and wait for async promises in array](https://stackoverflow.com/q/72183740/215552)).
Comment: Does this answer your question? [Javascript push and wait for async promises in array](https://stackoverflow.com/questions/72183740/javascript-push-and-wait-for-async-promises-in-array)
Comment: I got ids. But I am not sure how to proceed next exactly according to suggested link. Can you be more specific on that?
Answer: Refactor the mapped JSX into an actual React component so it can use the useEffect hook (and all other React hooks).
Example:
const Item = ({ item }) => {
  const [newItems, setNewItems] = useState([]);

  useEffect(() => {
    fetch(`/api/newItems?newItemId=${item.id}`)
      .then((response) => response.json())
      .then((data) => setNewItems(data))
      .catch((error) => {
        throw error;
      });
  }, []);

  return (
    <TableRow>
      <TableCell>{item.name}</TableCell>
      <TableCell>{item.latitude}</TableCell>
      <TableCell>{item.longitude}</TableCell>
      <TableCell>
        {newItems.map((newItem) => newItem.name).join(", ")}
      </TableCell>
    <TableRow/>
  );
};

...
const StoppagesPage = () => {
  ...

  return (
    <PageLayout
      menu={<SettingsMenu />}
      breadcrumbs={['settingsTitle', 'settingsStoppages']}
    >

        <TableHead>
          <TableRow>
            <TableCell>{t('settingsStoppage')}</TableCell>
            <TableCell>{t('settingsCoordinates')}</TableCell>
            <TableCell>{t('sharedRoutes')}</TableCell>
            <TableCell className={classes.columnAction} />
          </TableRow>
        </TableHead>
        <TableBody>
          {loading
            ? <TableShimmer columns={2} endAction />
            : items.map((item) => <Item key={item.id} item={item} />)
          }
        </TableBody>

      <CollectionFab editPath="/settings/stoppage" />
    </PageLayout>
  );
};

Answer: But I need to place data inside a table and render them as well. My question was simple. Since I can't  fetch data inside the JSX, On the other hand I need item.id to fetch. So how would I fetch data by item.id and render it inside the table cell?
Example:
{!loading ? items.map((item) => (
     <TableRow key={item.id}>
       <TableCell>{item.name}</TableCell>
       <TableCell>{`Latitude: ${item.latitude}, Longitude: ${item.longitude}`}</TableCell>
       <TableCell>
         {
           # need to fetch and render data here
           geofences.map((geofence) => geofence.name).join(', ')
         }
       </TableCell>
       <TableCell className={classes.columnAction} padding="none">
         <CollectionActions itemId={item.id} editPath="/settings/stoppage" endpoint="stoppages" setTimestamp={setTimestamp} />
       </TableCell>
     </TableRow>
   )) : (<TableShimmer columns={2} endAction />)}

Comment: Are you trying to answer your own question, or trying to implement the solution I provided and have question about it?
Comment: The second one. I am saying mapped Item should be inside Table. Are you saying that All  have to be replaced by [original react component] ? or what is the last snippet of code all about? please explain a bit. Very much need to solve. - @Drew Reese
Comment: Yes, the `items.map` callback is converted to a React component so it can use the `useEffect` hook and make the GET request and store some local state and map the result to the comma-joined string list value. The last snippet is what is mapped instead, i.e. instead of mapping to the table components you now map to the new component you created when refactoring the code.
Comment: it's giving another uncaught error! can not read 'id'. May I show you the whole page of code if that helps!! - Drew reese
Comment: Did you pass `item` as a prop to the new React component like in my example, i.e. `items.map((item) => )`? Sure, you can edit your post (*not answer*) to include the new and relevant details and code example.
Comment: yes I did so far. Alright I have edited the post. Please check. @Drew Reese
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/249085/discussion-between-drew-reese-and-cosmic).


How to add action function to Disposable returned from subscribe on an Observable?

Question: You have an Observable, then you subscribe to it. The return value is a Disposable.  How do you add a function to be invoked when that Disposable instance is disposed?
clickStream.subscribe(....).dispose();

When dispose() is invoked I want to call a debug function, for example, console.log('Disposing ....').  In a real app, I would want to do some non-rxjs clean-up and UI notification actions.  Probably simple thing, but I don't see it in the API.  Thx.
Answer: I wonder if finally would work for your use case (documentation). According to the documentation, Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. Note that this is not exactly the same as a callback being called when dispose is called but I thought that might be enough for your needs, and you can use it for clean-up actions.
UPDATE
Also close to what you want, but not quite so, you could use the using operator (documentation). It allows to create an object with a dispose method which would be called when the subscription to the associated observable is disposed of.
UPDATE 2
Looking at the source code, finally actually executes the action when the subscription to its observable is disposed. This includes termination or manually calling dispose() on the subscription. That seems very close to what you want to achieve.
Best is to test. Please keep us updated of the results.
Comment: This is different than a dispose. `finally` fires either on an `error` or `complete` event. You can dispose an observable without either of those things happening.
Comment: These are the fine points of Rxjs and terminology is a bit confusing. I think you dispose only a subscription. Observables do terminate, error or emit values but they are not disposed. That being said, my answer is geared towards using `finally` to do clean-up and what-not in the absence of a better option. I agree this does not answer the question, but it could still be useful.
Comment: Fair enough. It might even cover OP's use case, depending on what he actually wants to achieve.
Comment: Though I think Peter Hall's answer is "better" in terms of the use case as I presented it, the use of the finally operator was enough for now.  I tested this by adding it to a click stream on an Exit button in a UI.   Puzzling, it is indeed invoked on dispose.   Thanks for all the feedback.
Answer: Disposables are tied to event sources. The principle is that an event source is interacting with the non-Rx world, and might need to do some clean-up when no one is subscribed any more.
If you could put a hook into the Disposable that is returned from a call to subscribe then it wouldn't be of much use: you know when you called dispose() so you could just handle the clean-up logic there, and if some other code called dispose() it might be on a Disposable further down the chain, which may not affect your subscription.
It sounds like you are trying to make use of side-effects, which isn't necessarily in the spirit of the RxJS API. If you need to close down some network connection or something like that, then maybe you should be using a custom Observable, which creates a Disposable to clean itself up.
A simple example of this (simplified implementation of Observable.fromEvent) might look like this:
function fromEvent(obj, evt){
     var subject = new Rx.Subject();
     function listener(e){
        subject.onNext( e );
     }
     return Rx.Observable.create( function( observer ){
        var disp = subject.subscribe( observer );
          obj.addEventListener( evt, listener );
          return Rx.Disposable.create(function(){
             // All the clean-up code goes here
             obj.removeEventListener( evt, listener );
             disp.dispose();
          })
     });
}

var events$ = fromEvent( button, 'click');
var count = 0;
var unsub = events$.subscribe( function(){
    console.log('click');
    count++;
    if( count > 5){
        unsub.dispose();
    }
})


How do I get the output of a single field?

Question: How do I get the output of a field of a node?
I have some weird subpage construct using entity references (one 'main' node and a few 'sub'-nodes).
Each of these nodes have a header image to be displayed above the content. What I am trying to do is for the sub-nodes to 'inherit' the header image of the main node.
I implemented hook_node_view and I have got the node, I just don't know how to build the renderable array for it.
function hook_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if($view_mode == 'full'){
    if((!isset($build['field_headerimage']) || !isset($build['field_headerimage'][0])) && $entity->hasField('field_location')){
      $location = $entity->get('field_location')->referencedEntities();
      if(is_array($location) && isset($location[0])) {
        $node = $location[0];
        dsm('yay, now what?');
        dsm($node->label());
      }
    }
  }
}

Answer: The answer to my own question seems to be like so:
$build['field_headerimage'] = $node->get('field_headerimage')->view();


Migration em varias tabelas com o mesmo prefixo

Question: É possível com o laravel gerar uma migração que altere varias tabelas com o mesmo prefixo? por exemplo: nas tabelas pesquisas_187 e pesquisas_146 (tabelas que possuem os mesmos campos)
Schema::table('pesquisas_', function (Blueprint $table) {
   $table->string('code')->after('name');
});

Answer: Não existe nada pronto no laravel para essa finalidade, mas, nada impede a codificação de um Migration com o seguinte código:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Padrao1 extends Migration
{
    public function up()
    {
        $sql = 'SELECT TABLE_NAME as name FROM information_schema.tables ';
        $sql .= 'where TABLE_SCHEMA=? and TABLE_NAME LIKE ? ';
        $result = DB::select($sql, [getenv('DB_DATABASE'), 'pesquisas_%']);
        foreach($result as $table)
        {
            Schema::table($table->name, function (Blueprint $table) {
                $table->string('code')->after('name');
            });
        }
    }

    public function down()
    {

    }
}

Nesse código é feito uma pesquisa sobre as tabelas do banco configurada no arquivo .env com a chave DB_DATABASE (getenv('DB_DATABASE')) com um filtro sobre as tabelas do prefixo pesquisas_, e seu retorno é uma lista de todas as tabelas que pertence a esse prefixo, o resto é igual utilizando Schema::table, como demostrado no código.
Referencias:

Database: Getting Started
Database: Migrations


Como ler a linha de comando?

Question: Vamos dizer que eu queira fazer uma rotina para automatizar o processo de compilação de um programa. No geral (independente da linguagem), você chama compilador pela linha de comando. Por exemplo:

javac meuPrograma.class

ou

gcc meuPrograma.c -o meuPrograma

No Windows, podemos usar system(). Mas como ler a linha de comando ? No caso de um compilador, por exemplo, como ler os possíveis erros retornados pelo compilador na linha de comando. Melhor dizendo, como as IDEs fazem isso ? Isso seria importante se desejássemos integrar qualquer programa com interface CLI ao nosso sistema, não apenas para compiladores.
Comment: A IDE do Dev-C++ é um ótimo exemplo dessa integração CLI. Ela faz uso de utilitários padrões tais como o `gcc`, o `gdb` e o `make`.
Answer: Queres obter o resultado de system() dentro do teu programa?
Usa  POSIX popen()  ou  MSDN _popen()
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *handle;
    char cmd[] = "dir";
    char line[1000];
    int n = 0;

    handle = popen(cmd, "r"); // se der erro de linker experimenta _popen
    if (!handle) {
        perror("");
        exit(EXIT_FAILURE);
    }
    while (fgets(line, sizeof line, handle)) {
        printf("%03d: %s", ++n, line); // line includes ENTER
    }
    pclose(handle); // se der erro experimenta _pclose
}

Answer: O melhor é colocar os dois processos (seus dois programas) para conversarem entre si. Pode ser de várias formas diferentes, por exemplo: arquivo, memória compartilhada, mensagens ou socket.
Como você mencionou console do Windows, uma solução possível nesse caso é redirecionar a saída do console para um arquivo e depois imprimir isso no console.
Sua chamada do sistema ficaria mais ou menos com essa cara:
gcc meuPrograma.c -o meuPrograma > arquivo.txt | type arquivo.txt

Assim, seu próximo programa poderia ler esse arquivo.txt também.

Como ler a linha de comando?


GAC Problem: Keep getting old version

Question: I've created a simple httpModule, registered it on GAC and added it to the global web.config.
I've made some changes to the module, updated the version and changed it also on the web.config.
What happens is that i keep getting the old version. I've restarted the computer, removed it from the GAC, deleted the consumer app .net temp files, but still the consumer app render the old html code from the httpModule.
Any thoughts on what the hell is happening?
Thanks,
Bruno Figueiredo
http://www.brunofigueiredo.com
Answer: Don't use the GAC.
Simple, any dependencies you have should be binary deployed to avoid versioning issues.
I blogged on this before: http://www.tigraine.at/2008/10/13/handling-dependencies/
Comment: We use GAC because the html generated by the module must be added to every application hosted by the IIS.
Answer: Is it possible you have an older version lying around in your bin folder? Another alternative is that some other code is comipled against the older version. If all else fails you can use bindingRedirect to force your new version.

GAC Problem: Keep getting old version


Why is the block template for User Login not used on user/login page?

Question: If I dpm() the theme_hook_suggestions in template_preprocess_block on a standard page with the user login block on it, I get block_user_login as a suggestion.
If I go to user/login (while logged out), I don't get any pertinent suggestions. It doesn't even seem to use block.tpl.php when renderedon user/login. I know it's actually rendering that block because it prints out the description I gave it.
Answer: The user_page() function returns the form directly (i.e. not in a block) for the user login page. As such it won't fire template_preprocess_block and your dpm() call will never run. If it wasn't called directly in this manner then the User module would inadvertently become dependent on the Block module being enabled, and this shouldn't be the case.
Also, just in case it helps: dpm() will only print out a message for users who have the correct permissions to view them. By default this doesn't include anonymous users.
If you want to change it (temporarily of course, anonymous users really shouldn't have access to variable printouts), go to http://mysite.com/admin/people/permissions and make sure the Anonymous User role has the "Access developer information" permission ticked.
Comment: Yeah I already enabled dpm for anon users. As for block templates, I guess I'm just stuck using hook_form_alter for this.
Comment: Or if you don't want to do it that way...override the page callback for `user/login` with `hook_menu_alter()`, then output the login form in a block in the callback function
Comment: Unfortunately the block won't even render if you're at user/%. I think I'm really just fighting against the current on this one. Not worth it.


How to MYSQLI Select a row that has column LIKE a string variable? Reverse MYSQLI Wildcard?

Question: I have a feeling like this could perhaps be accomplished with PHP and I am overthinking it. However, let's say I have a table that looks like below
TABLE: customer_urls
ID | URL
1  | joestire.com
2  | peterstire.com

In php I would have the URL of a site which changes like
$site_url= "https://joestire.com/about/our-team"

How would I then query my table to find the ID of the record for joestire.com? Assuming I can not write a substr or str_replace because I don't already know what the URL is and what to remove?
I would think something like
"SELECT ID FROM customer_urls WHERE URL in $site_url "

But this does not seem to work?
Comment: You can first parse the URL using [parse_url()](https://www.php.net/manual/en/function.parse-url.php) to only get the hostname. When you have the hostname, it should be pretty straight forward.
Answer: Use LIKE to match a pattern. In this case, the pattern comes from the url column, with wildcards added around it.
$sql = "SELECT id FROM customer_urls WHERE ? LIKE CONCAT('%', url, '%')"
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $site_url);
$stmt->execute();
$results = $stmt->get_result();
while ($row = $results->fetch_assoc()) {
    echo "{$row['id']}
";
}

Answer: Try with SUBSTRING_INDEX function:
SELECT *, SUBSTRING_INDEX('https://joestire.com/about/our-team', '/', 3) AS example
FROM customer_urls
WHERE
    url like CONCAT('%', SUBSTRING_INDEX('https://joestire.com/about/our-team', '/', 3), '%')

You can play with the wildcards because this solution does not remove the https or https so I would think that you should apply the wildcard only at the end url%
This work for me


Disable specific keybinding in vscode

Question: I ran into a problem with my keyboard lately, my - and = stopped working and I manually remapped the two keys to PgUp and PgDn by editing <code>/usr/share/X11/xkb/keycodes/evdev</code>. Everything works fine but the problem is that vscode  still recognizes these two keys as Page-Up and Page-Down while other editors respect my new config. The question is "How do I make vscode adapt to my new configuration"?.
Thanks in advance
Answer: I have been able to solve this problem by deleting all the keyboard shortcuts associated with the remapped keys. All I did was opened,
File > Preferences > Keyboard Shortcuts, searched for the word PageUp, right-clicked the matching words and deleted them all. I did same for PageDown and everything works fine now.

Disable specific keybinding in vscode


Avoid random number cached in preprocess hook

Question: I have a random set of images that appear on the homepage which needs to show each time the page is refreshed. My holding page was doing this comfortably in PHP, but since building the whole site and migrating the PHP into Twig I ran into issues with the cache. I tried moving the code into a preprocess hook for the content type however that too is subject to the caching.
Is there anyway around this problem by disabling caching for anonymous users in the preprocess hook, or updating the random number variable in the cache on each reload etc.?
Ideally I'd like to avoid doing this in JS as per the recommendation here Ignore cache in preprocess function
Here is my preprocess function PHP code which feeds a loop.
function freadman_white_preprocess_node__3(&$variables) {

$imageset = (rand(1,8));
$time = array(
    '01:14',
    '10:37',
    '11:16',
    '09:38',
    '04:51',
    '03:24',
    '10:39',
    '10:58'
);
$date = array(
    'pm Saturday 18.08.18',
    'am Sunday 05.08.18',
    'am Sunday 05.08.18',
    'am Wednesday 15.08.18',
    'pm Tuesday 21.08.18',
    'pm Tuesday 21.08.18',
    'am Wednesday 25.07.18',
    'am Saturday 25.08.18'
);

$variables['imageCount'] = 33;
$variables['imageSet'] = $imageset;
$variables['imageTime'] = $time[$imageset-1];
$variables['imageDate'] = $date[$imageset-1];

}

Answer: First, try to pass a render element with a '#cache' value set, maybe like so:
$variables['imageSet'] = [
  '#type' => 'value',
  '#value' => $imageset,
  '#cache' => [
    'max-age' => 0,
  ],
];

Next, you could try to completely disable the cache for this node (though that's probably not the best idea).
$variables['#cache']['max-age'] = 0;

And last – but quite advanced – you can provide a custom controller, that returns an uncached JSON response with your calculations and then use a little JS script that fetches the JSON via Ajax and inserts it into some placeholder selector in your markup (for the placeholder you could even provide a pseudo field to be placed at a desired position via the admin UI).
I used exactly the concept described above to build User Online Status. You can simply grab a copy and check its code to get an idea how that works.
Comment: Thanks for your reply @leymannx. I tried your first 2 responses however neither of those seem to have an impact. The random number returned is the same each time until I clear all caches via the performance dashboard. The 3rd option is probably a little advanced for me, but I'll try to have a look into it.


Relative importance of predictors in logistic regression

Question: I would like to calculate an estimate (even a very rough one if it is the best I could get) of the relative importance of predictors in a logistic regression, something which can let me tell a common person, not proficient in statistics (just like me), for example: these are the predictors: x1, x2, x3, x4, They are all significant statistically, but as you can see, x2 is more important than x1, x3 and x4, because the value of "unknown datum" is higher than "unknown value/other predictor".
I read Relative importance of predictors in the final model, importance of each predictor in logistic regression, How to quantify the Relative Variable Importance in Logistic Regression in terms of p?, but I did not read what I am looking for.
I use R and I know a package for it: caret (https://github.com/topepo/caret/) and its function called 'varImp', but I can not understand how the absolute value of t-statistic is used, so I can not understand how to comment values obtained through this formula.

The main question is: how can I tell, in practice, that one predictor of a logistic regression is more important than another?
Secondarily: how can I tell how much a predictor in that logistic regression is more important than another? Can you explain to me, a statistician wannabe, how the absolute value of t-statistic could be helpful?
Comment: There is no agreed upon importance measure for predictors in a model, and the t statistic is not meant to be used in this way, the use of it in this way in carat is a dubious decision. Indeed, variable importance is just a slippery and borderline undefined concept. So heres a question: if I told you a measure, what would you use it for? What kinds of decisions would you like to make or actions would you like to take as a consequence of this measurement?
Comment: I'm not the downvote, but I will say that if you cannot point to any specific and detailed reason for wanting to know such a thing, then this question is unanswerable.  "Predictor Importance" is just not a statistically meaningful thing, there is nothing the universe gives us that you are trying to estimate.  The universe tends to mix all it's effects together, and there is rarely, in any real situation, a meaningful way to decompile their effect on some other phenomena...
Comment: @statisticianwannabe Ok, so in that example, what does it mean to be "more relevant", and how would such a measure inform a consumer of the model?  I don't see any situation where saying age is more or less relevant than blood pressure solves a meaningful problem.  For example, people can not control their age, but they have some meaningful control over their blood pressure.  So a doctor can't say, "well your blood pressure is high, but research has shown age is a more important factor, so you should work on lowering that first."  Sor really, what problem are we trying to solve?
Comment: Thank you for your answer. No decision would be made basing on those results: it would be just a way to tell someone how much a predictor is more relevant than another one in a specific logistic regression. I am thinking about something shaped like variable inflation factors, that is, simply a number which is somewhat interpretable
Comment: This means that concepts like that can only be made sense of within a given context: I.e., I can take an action that looks like this, what is the most beneficial place to take this action to achieve my goals?  If you can not provide such a context, then I'm left questioning what you are really after.
Comment: Hi, @MatthewDrury, not sure why you see a problem in ranking variables in logistic regression. Please have a look at my answer and let me know your thoughts.
Comment: @DeltaIV I just don't see what problem it solves.  You can write down that formula, and name it "importance", but what applications does it have?  What actionable insights about a situation could someone use it for?
Comment: Thank you again. For example, imagine if I have to publish a research paper, in which I would like to perform a logistic regression in order to understand if age and blood pressure predict atherosclerosis. First issue: maybe age and blood pressure have some degree of collinearity? I could measure variable inflation factor and show a number: "variable inflation factor is blablablah, therefore we could say that collinearity is weak/strong blablablah". Second issue: maybe age/blood pressure is more relevant than the other factor in determining atherosclerosis? How can I say and quantify that?
Comment: @MatthewDrury hey, first of all kudos for "actionable insight" - I didn't expect to read that outside of a business environment :) (maybe you do work in corporate). Second, here's an example: you have a database of default rates for credit card owners, with predictors `student` (categorical), `income` and `credit card balance` (continuous). Fit a logistic regression model. Now you can use it to decide which predictor has a larger effect on probability of default. This helps the credit card company decide to whom they should offer credit, which categories are the more risky, and so on.
Comment: hey, one of the questions you link to actually links to a good [paper](https://www.mwsug.org/proceedings/2009/stats/MWSUG-2009-D10.pdf). The first metric is basically the same I proposed (note that I did require that predictors were standardized first: if you don't, then you have to correct for the sample standard deviations of the predictors, as illustrated by the paper). The second one is no good, as explained by @MatthewDrury, and also acknowledged in the paper (makes you wonder why they included it, then). Third one is famous, but only reliable if you use likelihood ratio and not ctd...
Comment: ctd... the chi-square statistics in the denominator (as noted by @FrankHarrell in a paper). I don't know about the other methods, but the information value seems unreliable to me because of the discretization step.
Answer: I assume all predictors have been standardized (thus, centered and scaled by the sample standard deviations).
Let $\mathbf{x}$ be the vector of predictors and $y$ the response, conditionally Bernoulli-distributed wrt $\mathbf{x}$. Then if $\mu=\mathbb{E[y|\mathbf{x}]}=p(y=1|\mathbf{x})$, then clearly
$$\frac{\partial \mu}{\partial x_i}=\beta_i \frac{\exp{(-\beta_0-\boldsymbol{\beta}^T\cdot \mathbf{x})}}{(1+\exp{(-\beta_0-\boldsymbol{\beta}^T\cdot \mathbf{x})})^2}$$
measures the effect of $x_i$ on $\mu$. This effect is a function of $\mathbf{x}$. However, the relative importance of two predictors is
$$\frac{\frac{\partial \mu}{\partial x_i}}{\frac{\partial \mu}{\partial x_j}}=\frac{\beta_i}{\beta_j}$$
which is independent of $\mathbf{x}$.
Thus, provided we have standardized all predictors, we can look at the estimates of the model coefficients as indicators of the relative importance of the predictors for what it concerns the variation of the output.
As an example application, I will adapt the case in section 4.3.4 of An Introduction to Statistical Learning, by James, Witten, Hastie
& Tibshirani. Suppose you have a database Default of default rates for credit card owners, with predictors student (categorical), income and credit card balance (continuous). Standardize the predictors and fit a logistic regression model. Now you can use the relative magnitude of the $\hat{\beta}_j$to decide which predictor has a larger effect on probability of default. This helps the credit card company decide to whom they should offer credit, which categories are the more risky, which customer segment to target with an ad campaign and so on.
Finally, this paper lists six different definitions of relative predictor importance for logistic regression.
The first one is very similar to the one I showed, with the only difference that instead of standardizing the predictors before, they standardize the $\hat{\beta}_j$ after estimation by multiplying by the ratio $\frac{s_j}{s_y}$ where $s_y$ is the response sample standard deviation, and $s_j$ is the sample standard deviation of predictor $x_j$. It's not exactly the same as my suggestion, because the estimators for the logistic regression coefficients are nonlinear functions of the data, but the idea is similar.
The second one (using the $p-$values from the Wald $\chi^2$ test) is flawed, as explained by @MatthewDrury in the comments to the OP, and shouldn't be used.
Third one (logistic pseudo partial correlation) can be a good choice as long , instead of the Wald $\chi^2$ statistic, in the numerator of the pseudo partial correlation we use the ratio of the likelihood of the model with just predictor $x_i$, to that of the full model. I cannot comment on the other approaches since I don't know enough about them.
Comment: +1.  I think your answer would be improved with a short case study of how this formula could be used in scientific or business decision making.  Like the one in the comments above!
Comment: Will do. So I can also properly acknowledge the source for that example :) I thought I already did that, but comments are not as easy to edit as answers, and the link was lost.
Comment: Thank you for your answer, very interesting and it gave me a clearer vision of the issue. Now, of course, it is a matter of studying more its theoretical bases
Comment: Can you please elaborate why the predictos must be standardized beforhand? I guess it is to make their measurement unit dimensionless, but wonder whether this particular scaling is appropriate for all distributions of  predictors (provided, they are considered as random variables). Moreover, can you please explain how to standardize categorial predictors?


Return Dictionary in SaveChanges()

Question: I am overriding the SaveChanges() method so that I can use the ChangeTracker to get the modified properties of an entity. I need to return a Dictionary<string, string> of the modified properties so that in my controller I can call the Audit Service.  So far my SaveChanges() methods looks like:
public override int SaveChanges()
{
    var changeInfo = ChangeTracker.Entries()
        .Where(t => t.State == EntityState.Modified)
        .Select(t => new {
            Original = t.OriginalValues.PropertyNames.ToDictionary(pn => pn, pn => t.OriginalValues[pn]),
            Current = t.CurrentValues.PropertyNames.ToDictionary(pn => pn, pn => t.CurrentValues[pn])
        });

    Dictionary<string, string> modifiedProperties = new Dictionary<string, string>();
    foreach (var item in changeInfo)
    {
        foreach (var origValue in item.Original)
        {
            var currValue = item.Current[origValue.Key];
            if ((origValue.Value != null && currValue != null) && !origValue.Value.Equals(currValue))
            {
                modifiedProperties.Add(origValue.Key, string.Format("Old Value: {0}, New Value: {1}", origValue.Value, currValue));
            }
        }
    }
    return base.SaveChanges();
}

Is there a way to access the modifiedProperties dictionary in my controller so I can pass that to my service?
Controller:
if (validator.IsValid())
{
    _workRequestRepo.Save(workRequest);
    _auditService.Log(UserId, modelId, "Work Order", "Edit", modifiedProperties);
}

Comment: There seems to be a mismatch of dependancies here.  It sounds like it should go Controller -> Business Layer (Audit Service) -> Data Layer.  What you have is something that only controller is aware of, and any new controllers then also have to implement the same logic, that is not very DRY.
Comment: I was thinking it would go Controller -> Data Layer to save entity, then if there weren't any problems it would go Controller -> Audit Service (Domain Layer) -> Data Layer to save Audit table.
Comment: That creates dependancies on layers that shouldn't know anything.  The controller shouldn't know if it should or shouldn't audit, that's a business desicion not a presentation desicion.
Comment: Architecture aside, could you write an extension method for your DataModel that returns the dictionary and still calls `base.SaveChanges()`?
Comment: Do you think I should call the Audit Service from SaveChanges() or in the Save() method in my repository?
Comment: @chadiusvt that may work, although I think I should try to get the architecture part correct and do that as a last resort.
Comment: `Do you think I should call the Audit Service from SaveChanges()` absolutely not.  This would definitely violate the [Single Responsibility Principle](http://en.wikipedia.org/wiki/Single_responsibility_principle).  A repository should not know anything other than data manipulation.
Comment: @ErikPhilips I have to call the `Audit Service` after `SaveChanges` so I know what values were changed.  If I don't call the service in `SaveChanges` or my repository where else would it go?  I'm going to update my post to include my controller.  My post is updated.
Comment: @ErikPhilips I don't understand why this would violate the single resposiblity principle? One of the tasks of the `SaveChanges` method would be to build the history of changes made to the entities.
Comment: Audit usually means an independant authority keeping logs of changes (key word is independant).  If tracking changes within the same scope (not independant) is usually referred to as revisioning.
Comment: `I don't understand why this would violate the single resposiblity principle?`  Because the method `SaveChanges` does not in any way denote anything other than saving changes, otherwise it should be `SaveChangesAndLogAudits()`....
Comment: @ErikPhilips I see. So let's change the name of this method, problem solved, principle happy. `public int SaveChangesAndLog() { /*.... audit procedures */; return SaveChanges(); }`
Answer: You don't have to return the modified properties, you can tackle your audit procedures inside the SaveChanges method. This is an example:
    public MyContainer(IUserProvider userProvider) {
        _userProvider = userProvider;
    }

    public override int SaveChanges() {
        var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));
        if (entities.Any()) {
            User currentUser = _userProvider.GetCurrent();
            if (currentUser == null)
                throw new Exception("Current user is undefined.");
            DateTime time = DateTime.Now;
            foreach (var entity in entities) {
                BaseEntity baseEntity = (BaseEntity)entity.Entity;
                if (entity.State == EntityState.Added) {
                    baseEntity.Created = time;
                    baseEntity.CreatedBy = currentUser;
                }
                baseEntity.Modified = time;
                baseEntity.ModifiedBy = currentUser;

                // get and store the changed properties of the entity here
                // ....
                var changeInfo = entities.Select(t => new { Original = t.OriginalValues.PropertyNames.ToDictionary(pn => pn, pn => originalValues[pn]), Current = t.CurrentValues.PropertyNames.ToDictionary(pn => pn, pn => t.CurrentValues[pn]);

            }
        }

        return base.SaveChanges();
    }

Answer: Using IOC I would imagine you have something like:
(This is assume Auditing and not Revisioning)
Presentation:
public PersonController
{
  private IPersonBL _personBL;

  public PersonController(IPersonBL personBL)
  {
    _personBL = personBL
  }

  public ActionResult SavePerson(PersonVM model)
  {
     // if ModelState etc etc
     var person = Mapper.Map<Person>(model);
     _personBL.Save(person)
  }
}

Business Layer
public PersonBL : IPersonBL
{
  private IAuditService _auditService;
  private IPersonRepo _personRepo;

  public PersonBL(IAuditService auditService,
    IPersonRepo personRepo)
  {
    _auditService = auditService;
    _personRepo = personRepo;
  }

  public void Save(Person person)
  {
    PersonDTO personDTO = Mapper.Map<PersonDTO>(person);
    var result = _personRepo.Save(personDTO);
    if (result.Count > 0)
    {
      _auditService.Audit(result);
    }
  }
}

Data Layer
public PersonDL : IPersonDL
{
  private DbContext _context;

  public PersonDL(DbContext dbContext)
  {
    _context = dbContext;
  }

  public IDictionary<string, string> Save(PersonDTO person)
  {
    var result = new Dictionary<string, string>()

    _context.Persons.Add(person);
    var saveCount = _context.SaveChanges();

    if (saveCount > 0)
    {
      // Do Object Tracking
      // Populate result;
    }

    return result;
  }
}

Comment: I'm going to give this a shot.  I don't have that business layer though so I'm going to have to add that Audit call in my controller.  I think I have to have the `ChangeTracker` in `SaveChanges` though to get the modified properties.

Return Dictionary in SaveChanges()


Find two complex roots of quadratic given it's square roots

Question: a: find square roots of $-3+4i,$
for which I got: $-1-2i,$ and $1+2i$
b: Find two complex roots of the quadratic equation $z^2 + 2(1+i)z + 3 - 2i =0.$
Had a few attempts Eg. the sum of roots but I am very confused.
Comment: Welcome at MSE. What exactly is your question? Where did you get stuck? BTW you can use LaTeX/Mathjax to typeset equations on MSE.
Comment: These questions are separate, use the quadratic formula
Comment: Not entirely separate. When you use the quadratic formula, you will find that the determinant happens to be similar to the number from the first part of the question.
Comment: Tried this - I cannot do it - Maybe I am making a mistake. Got to -1 -i +/- Root 12i -12
Answer: Use the quadratic formula exactly as you did with usual, real equations:
$$\Delta=\left[2(1+i)\right]^2-4\cdot1\cdot(3-2i)=8i-12+8i=4(-3+4i)$$
so the roots are
$$z_{1,2}=\frac{-2(1+i)\pm\sqrt\Delta}2$$
And you know the roots square roots of $\;\Delta\;$...
Comment: @boiShift Use what you did in part (a) !! Then you have that $$z_{1,2}=-(1+i)\pm(1+2i)=\begin{cases}\;\;\;\;\;i\\-2-3i\end{cases}$$ ...you just *have to write explicitly* the square roots of $\;\Delta\;$ , that's all.
Comment: So I say -1 -1 +/- Root (4(-3+4i)) - Then what?
Comment: @boiShift Then nothing: $\;z_{1,2}\;$ **are the equation's roots** ...! What else do you want?
Comment: The question requires the two complex roots: Answers are: i and 2-3i
Comment: @boiShift Well, I get $\;i\,,\,\,-2-3i\;$ , but yes: these are the roots...so??
Comment: How do I get to that final part - and yes you are right it's i2-3i. That is the final answer i need.
Comment: I see, thank you. I was confused about which square root to use - Does it not matter, will I get the same result each way?
Comment: @boiShift There are **always** two square roots for any non-zero complex number, and they differ *only* by their sign. As you have $\;\pm\sqrt\Delta\;$ in the roots' formula, you get to use both and you lose nothing.
Answer: For b just use the quadratic formula. You should find the discriminant is $-12+16i$, four times the quantity you square-rooted in a.
Comment: So I say -1 -1 +/- Root (4(-3+4i)) - Then what?


How can I port this project to Android Studio?

Question: I am completely new to Android development. Can someone please provide me steps that how can I run this code via Android Studio?
https://github.com/quangpropk/TrafficSignsDetection
Comment: Does this help you? http://stackoverflow.com/questions/27406303/opencv-in-android-studio
Answer: Unzip the github project to a folder.
Open Android Studio. Go to File->Import Project.
Then choose the specific project you want to import and then click Next->Finish. It will build the Gradle automatically and'll be ready for you to use.
OR
You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.
The github repo will be created as a new project in android studio.


How to diagnose what's causing InnoDB to run out of space?

Question: Site used to go down frequently on a near daily basis and is on Digitalocean VPS
Based on some suggestions I got on DO forum, I ran mysqltuner and increased innodb buffer pool size to 341M and innodb log file size to 64M
Since then the site goes down less but it still does every once in a while like last night.
There are plently of 'InnoDB: Cannot allocate memory for the buffer pool' in the mysql error log - pastebin
I've assigned swap space and I've ran netstat, vmstat etc too and everything seems alright.
But clearly I'm running out of memory as the logs suggest. How do I diagnose whats causing my server to run out of memory? Whether its a faulty plugin or apache or something else causing the issue instead of just upgrading the droplet?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/115513/discussion-on-question-by-sam-how-to-diagnose-whats-causing-innodb-to-run-out-o).
Answer: You may want to try MySQL Workbench which is free and quite useful for tasks like this.
Comment: Exactly what about MySQL Workbench would help in this situation?
Comment: Click on server status for infos about mem usage etc.
Answer: The issue seems like MYSQL is not getting enough memory to add to the buffer pool size. Setting up parameter need to be done with precaution if the values are too high you might have an issue with server hogging. InnoDB buffer pool size should be set to 50% of the available RAM in a low connection environment and 30% in a high connection environment. You can check more about the parameters here https://www.skynats.com/blog/mysql-server-optimization/
Comment: My InnoDB buffer pool size seems in line with your recommendations then. I'm on a 1GB memory droplet and my buffer pool size if 341mb
Answer: 2020-07-15T21:33:55.734143Z 0 [Note] InnoDB: Initializing buffer pool, total size = 384M, instances = 1, chunk size = 128M
2020-07-15T21:33:55.748097Z 0 [ERROR] InnoDB: mmap(137428992 bytes) failed; errno 12
2020-07-15T21:33:55.751593Z 0 [ERROR] InnoDB: Cannot allocate memory for the buffer pool
How much RAM do you have?  Either it is very tiny, or you have a lot of RAM taken up by other things.
Comment: I am on the $5 droplet by digital ocean with a memory of 1 GB

~# free -m

              total        used        free      shared  buff/cache   available

Mem:            985         512         105          26         366         293

Swap:          1023          88         935
Comment: @Sam - Is MySQL then only thing in the droplet?
Comment: No. It has wordpress installed on it and has a lot of content on the wordpress site. Nearly a thousand post with images. However this same droplet was easily handling around 5x the traffic it is getting now and did not go down
Comment: Something is chewing up the RAM; we need to figure that out.
Comment: Yes. Rick, any way to find that out? I turned off the performance schema too in mysqld yet the site went down again
Comment: Did you change versions recently?
Comment: No I haven't changed versions


Passing parameters in java script function ?

Question: I m new in javascript developpement
i m trying to make e function which hide or show some text in a span  after a  specific mouse event and i want to pass the id of this span in my function
this is my script which work with only a specific id which is "sp1"  in this case but i want to pass the id in my function parametres


Unable to send a POST Request using Power Query in Power BI Service

Question: I need to send a POST request to generate an access token in Power Query. In Power BI Desktop, a POST request is sent, and it works as expected. However, when I try to refresh after publishing the report to Power BI Service, a GET request is sent instead, resulting in a "Method Not Allowed" error, and a response code of 405.
This is the error I have encountered.

This is the Power Query code I'm using
let
base_url = [base_url],
client_secret = [client_secret],
Source  = Json.Document(Web.Contents(base_url&"/oauth/issueToken",
    [
      Headers = [#"Content-Type"="application/json"],
      Content=Json.FromValue([
        grant_type = "client_credentials",
        client_id = "powerbi_client",
        client_secret = client_secret
      ])
    ]
)),

token = Source[access_token],

I'm uncertain if the problem lies with the headers and content we are using. However, I was able to send the request successfully via Postman by setting the "Content-Type" to "application/json". What's the issue here? Any issue with my script?
Answer: I believe the problem might be that the url argument of Web.Contents is calculated. IIRC this is problematic authentication-wise when the report is published to Power BI service.
I would try the following to test this hypothesis: Change the url argument of Web.Contents to a static string and see if that solves the problem.


GroupAggregate for Subquery in Redshift/PostgreSQL

Question: I've noticed some strange behavior in the query optimizer for Redshift, and I'm wondering if anyone can explain it or point out a workaround.
For large group by queries, it's pretty essential to get the optimizer to plan a GroupAggregate rather than a HashAggregate, so it doesn't try to  fit the temporary results in memory. This works fine for me in general. But when I try to use that group by as a subquery, it switches to HashAggregate.
For example, consider the following query.
select install_app_version, user_id, max(platform) as plat
from dailies
group by install_app_version, user_id;

The table dailies has sortkeys (install_app_version, user_id) and distkey (user_id). Hence a GroupAggregate is possible, and the query plan looks like this, as it should.
XN GroupAggregate  (cost=0.00..184375.32 rows=1038735 width=51)
  ->  XN Seq Scan on daily_players  (cost=0.00..103873.42 rows=10387342 width=51)

In contrast, if I use the above in a subquery of any other query, I get a HashAggregate. For example, even something as simple as
select count(1) from
(   select install_app_version, user_id, max(platform) as plat
    from daily_players
    group by install_app_version, user_id
);

has the query plan
XN Aggregate  (cost=168794.32..168794.32 rows=1 width=0)
  ->  XN Subquery Scan derived_table1  (cost=155810.13..166197.48 rows=1038735 width=0)
        ->  XN HashAggregate  (cost=155810.13..155810.13 rows=1038735 width=39)
              ->  XN Seq Scan on daily_players  (cost=0.00..103873.42 rows=10387342 width=39)

The same pattern persists no matter what I do in the outer query. I can group by install_app_version and user_id, I can take aggregates, I can do no grouping at all externally. Even sorting the inner query does nothing.
In the cases I've shown it's not such a big deal, but I'm joining several subqueries with their own group by, doing aggregates over that - it quickly gets out of hand and very slow without GroupAggregate.
If anyone has wisdom about the query optimizer and can answer this, it'd be much appreciated! Thanks!
Answer: don't know if your question is still opened, but I put this here because I think others could be interested.
Redshift seems to perform GROUP BY aggregation with HashAggregate by default (even when conditions for GroupAggregate are right), and switch only to GroupAggregate when there is at least one computation made by aggregation THAT NEED TO BE RESOLVED FOR THE QUERY TO RETURN. I mean by this that, in your previous example, the "max(platform) as plat" is of no use for the final "COUNT(1)" result of the query. I believe that, in such case, the aggregate computation of MAX() function is not computed at all.
The workaround I use is to add an useless HAVING clause that does nothing but still need to be computed (for exemple "HAVING COUNT(1)"). This always return true (because each group has COUNT(1) equals to at least 1 and so is true), but enables the query plan to use GroupAggregate.
Example :
EXPLAIN SELECT COUNT(*) FROM (SELECT mycol FROM mytable GROUP BY 1);

XN Aggregate  (cost=143754365.00..143754365.00 rows=1 width=0)
   ->  XN Subquery Scan derived_table1  (cost=141398732.80..143283238.56 rows=188450576 width=0)
         ->  XN HashAggregate  (cost=141398732.80..141398732.80 rows=188450576 width=40)
               ->  XN Seq Scan on mytable  (cost=0.00..113118986.24 rows=11311898624 width=40)

EXPLAIN SELECT COUNT(*) FROM (SELECT mycol FROM mytable GROUP BY 1 HAVING COUNT(1));

XN Aggregate  (cost=171091871.18..171091871.18 rows=1 width=0)
   ->  XN Subquery Scan derived_table1  (cost=0.00..171091868.68 rows=1000 width=0)
         ->  XN GroupAggregate  (cost=0.00..171091858.68 rows=1000 width=40)
               Filter: ((count(1))::boolean = true)
                ->  XN Seq Scan on mytable  (cost=0.00..113118986.24 rows=11311898624 width=40)

This works because 'mycol' is both the distkey and the sortkey of 'mytable'.
As you can see, the query plan estimate than the query with GroupAggregate is more costly than the one with HashAggregate (which must be the thing which make the query plan choose HashAggregate). Do not trust that, in my example the second query runs up to 7 times faster than the first one ! The cool thing is that the GroupAggregate do not need much memory to be computed, and so will almost never perform 'Disk Based Aggregate'.
In fact, I realised it's even a much better option to perform COUNT(DISTINCT x) with a subquery GroupAggregate than with the standard COUNT(DISTINCT x) (in my example, 'mycol' is a NOT NULL column) :
EXPLAIN SELECT COUNT(DISTINCT mycol) FROM mytable ;

XN Aggregate  (cost=143754365.00..143754365.00 rows=1 width=72)
->  XN Subquery Scan volt_dt_0  (cost=141398732.80..143283238.56 rows=188450576 width=72)
         ->  XN HashAggregate  (cost=141398732.80..141398732.80 rows=188450576 width=40)
               ->  XN Seq Scan on mytable  (cost=0.00..113118986.24 rows=11311898624 width=40)

3 minutes 46 s
EXPLAIN SELECT COUNT(*) FROM (SELECT mycol FROM mytable GROUP BY 1 HAVING COUNT(1));

XN Aggregate  (cost=171091871.18..171091871.18 rows=1 width=0)
   ->  XN Subquery Scan derived_table1  (cost=0.00..171091868.68 rows=1000 width=0)
         ->  XN GroupAggregate  (cost=0.00..171091858.68 rows=1000 width=40)
               Filter: ((count(1))::boolean = true)
               ->  XN Seq Scan on mytable  (cost=0.00..113118986.24 rows=11311898624 width=40)

40 seconds
Hopes that helps !


Add custom security check on Sharepoint 2010 document management

Question: I want, in a document management library, to be able to add another type of security based on Web services that I will call to check if user can see this document library.
How can I do that feature?
Answer: Is your webservice call running as the user making the call?  If so, make sure the user has access to the doc library.
If the user does have permissions, and the webservice call is running as that user, the webservice should be able to access everything in the doc library that the user has permissions for.