Objective C class from a Swift class

Question: I have a base class written in Swift that is provided to me. My job is to write additional functionality around the base class.
I am considering the swift class as super class and deriving from it. However, it isn't working.
Answer: You cannot subclass a swift class in Objective-C.
Comment: I did not know that, thanks!
Answer:
Because you can't subclass Swift classes in Objective-C, it's best to
  choose a class in your app that doesn't have any subclasses.

Excerpt from Apple's guide about using Swift with Cocoa and Objective-C.
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/Migration.html#//apple_ref/doc/uid/TP40014216-CH12-XID_67

Objective C class from a Swift class


CouchDB like replication for MySQL?

Question: Is it possible to setup CouchDB like replication for MySQL?

Replication to be initiated from an web application.
Replication should be a two way process. i.e. Synchronization
If there is a failure in network connection, replication should take over where it left.
Schronization should be incremental.
The kind of data stored is Invoice.
Syncronization should be atomic. Either it should copy the whole invoice OR nothing.

Should I go for an custom synchronization logic here? I am planning to use Hibernate for data storage.
Answer: You can configure MySQL in Master-Master mode in an active-passive configuration. One server will serve as the master while the other one stays in sync as a slave of the master (plain MySQL Replication is asynchronous in nature, btw). The secondary acts as the master of the primary, but since it's not being written to, nothing actually gets written back to the master in this case. If the primary fails, you can start using the secondary one as the main master (ie: point your app to it). Eventually when you fix the master, assuming all the data and configuration was intact, you can re-establish replication and it can pick up where it left off.
Check out the Multi-Master Replication Manager project that can help you achieve this:
http://mysql-mmm.org/
Good luck!
Comment: My goal is to use it for offline distributed application. Will Multi-Master replication help?
Comment: No, MySQL does not support distributed configurations. You can always shard your data, but this is extremely complex and generally not recommended. MySQL is much more like a RDBMS that CouchDB is.
Comment: And also, MySQL Replication can't be setup from a web interface. It needs to be configured on the server directly.

CouchDB like replication for MySQL?


How to maximize scalar product under constrains?

Question: I have a multidimensional unitary vector $\vec n$. I need to find another unitary vector $\vec r$ which maximizes the scalar product:
\begin{equation}
(\vec r, \vec n) = r_1 \cdot n_1 + r_2 \cdot n_2 + \dots r_k \cdot n_k
\end{equation}
Obviously, without constrains $\vec r$ should be equal to $\vec n$. However, I have two types of constrains.
First, every component has an (component-specific) upper and lower bound:
\begin{equation}
l_i \geq r_i \geq u_i
\end{equation}
Second, there are several (overlapping) groups of components for which sum of components should sum up to 1. For example:
\begin{align}
r_1 + r_7 + r_9 + r_{11} = 1 \\
r_3 + r_7 + r_9 + r_{12} = 1
\end{align}
How can I find my vector $\vec r$. This is not a homework. I need to solve this problem since I run a gradient based constrained optimization. Vector $\vec n$ is my gradient.
Comment: @Korf, I guess that the difference with the linear program is that my vector should be unitary. So, it looks like a quadratic constrain (sum of squares of its components should be equal to 1).
Comment: @Roman you can somehow by-pass quadratic by putting $\bf r \cdot \bf n = \cos \alpha = c$ and adding the constrain $ -1 \le c \le 1$ as indicated in my answer
Comment: suppose you intend $-1 \le l_i \le r_i \le u_i \le 1$
Comment: @Roman Thanks, I missed that, deleting the original comment.
Answer: Hint
The set of equations $r_{k_1}+r_{k_2} + \cdots =1$ plus the $\bf r \cdot \bf n = \cos \alpha$ represent a set of hyperplanes.
Their intersection will lead to express $r_k$ , unless degenerations, as a linear combination of $\lambda _1 , \lambda _2 , \cdots \lambda _m$ and
$c = \cos \alpha$.
Then you are left with a set of constrains for linear combinations of $\lambda _k $ and $c$,  including $-1 \le c \le 1$,
to maximize for $c$.
Comment: @Korf : you  solve $ q $ equations in $q < n$ unknowns in terms of $n-q$ independent variables (call them $\lambda$), so actually read the above as $ \lambda _1 , \cdots , \lambda_{m=n-q}$
Comment: What are $\lambda_i$ and $m$ in $\lambda_m$?


Consulta LIKE em tabela relacionada

Question: Tenho uma query que faz a pesquisa por CHAMADOS TÉCNICOS e nessa pesquisa eu faço alguns JOINS pra trazer informações relacionadas.
Eu preciso que o LIKE também funcione para o nome do CLIENTE (que está numa outra tabela)
A query que tenho é essa:
SELECT *,
       `t1`.`usuario` AS nome_usuario_responsavel,
       `t1`.`id_usuario` AS id_usuario_responsavel,
       `t3`.`usuario` AS usuario_criador_chamado
FROM (
       `usuarios` t1,
       `usuarios` t3,
       `chamados`
)
INNER JOIN `clientes` ON `chamados`.`fk_cliente_chamado` = `clientes`.`id_cliente`
LEFT JOIN `ativos_cliente` ON `chamados`.`fk_ativo_chamado` = `ativos_cliente`.`id_ativo`
INNER JOIN `categorias` ON `chamados`.`fk_categoria_chamado` = `categorias`.`id_categoria`
INNER JOIN `assuntos` ON `chamados`.`fk_assunto_chamado` = `assuntos`.`id_assunto`
WHERE `t1`.`id_usuario` = `chamados`.`fk_usuario_responsavel_chamado`
AND NOT EXISTS (
    SELECT *,
            MAX(id_atividade) AS id_ultima_atividade
    FROM atividades
    WHERE atividades.fk_chamado = chamados.id_chamado
    AND (atividades.status = 3 OR atividades.status = 5)
    GROUP BY fk_chamado
)
AND `t3`.`id_usuario` = `chamados`.`fk_usuario_criador_chamado`
AND(resumo_chamado LIKE '%teste%' OR texto_chamado LIKE '%teste%' OR id_chamado LIKE '%teste%')
ORDER BY chamados.`data_criacao_chamado` ASC
LIMIT 0,15;

Answer: É interessante identificar cada elemento da sua sentença com um prefixo, para evitar ambiguidades. A sentença, a início, está correta. Falta apenas alguns ajustes, indicados abaixo:
SELECT *,
       t1.usuario AS nome_usuario_responsavel,
       t1.id_usuario AS id_usuario_responsavel,
       t3.usuario AS usuario_criador_chamado
FROM   chamados c
INNER JOIN usuarios t1 ON t1.id_usuario = c.fk_usuario_responsavel_chamado
INNER JOIN usuarios t3 ON t3.id_usuario = c.fk_usuario_criador_chamado
INNER JOIN clientes cl ON c.fk_cliente_chamado = cl.id_cliente
LEFT JOIN ativos_cliente ac ON c.fk_ativo_chamado = ac.id_ativo
INNER JOIN categorias cat ON c.fk_categoria_chamado = cat.id_categoria
INNER JOIN assuntos ass ON c.fk_assunto_chamado = ass.id_assunto
WHERE NOT EXISTS (
    SELECT *,
            MAX(id_atividade) AS id_ultima_atividade
    FROM atividades
    WHERE atividades.fk_chamado = c.id_chamado
    AND (atividades.status = 3 OR atividades.status = 5)
    GROUP BY fk_chamado
)
AND (c.resumo_chamado LIKE '%teste%' OR c.texto_chamado LIKE '%teste%' OR c.id_chamado LIKE '%teste%' OR cl.nome_cliente like '%teste%')
ORDER BY c.data_criacao_chamado ASC
LIMIT 0,15;

Comment: Com uma ou outra alteração a sua solução se encaixou perfeitamente.
Comment: @EdnaldoNeimeg Fique à vontade para editar minha resposta da maneira que ficou.

Consulta LIKE em tabela relacionada


Achieve samplepad/keyboard synth sound with a bass guitar for playing live?

Question: I play bass in a pop band and for a new song we want to add a synth bass similar to the one in this song:

The estudio recording part is easy, so the question is if it's posible to achieve that kind of sound playing live with a bass, using a pedal of some sort, to avoid buying a keyboard synth or samplepad for a single song.
I watched several demos of synth bass pedals and they all sound more like overdrive pedals, funky wah-wah style ones or too sci-fi like, but not the simple electronic sound we want that fits more that kind of indie-electropop or whatever you call that style.
Any recommendations?
Comment: Some people have voted to close this question. I personally disagree. I opened a meta thread about it: http://meta.music.stackexchange.com/questions/965/should-this-question-be-closed
Comment: You are right Kevin, the question is not about how that particular bass/synth was recorded (you can easily watch any live video for this) but how to imitate or get that kind of sound with an actual bass guitar.
Answer: To me it sounds like a bass guitar with distortion or a fuzz effect. Also since it's a rock band with a bassist it might not be a synth part. Edit: Looking at live videos, it seems he does use a synth [at least in the live version], but I still think you can replicate this with a bass guitar + distortion/fuzz
Most of the fuzz pedals I have used with bass tend to kill some of the low end, so to replicate this track I would use one amp for the clean bass signal and one amp running a distorted or fuzz effect. This way you can hear the attack and the "thump" of the clean bass and still get the fuzz on top. You can probably get close with one amp by keeping the "fuzz" or "gain" levels at or below 50% on your pedal and keep the "tone" knob low so it doesn't kill the lower frequencies.
Some specific info on his bass tone and gear: link 1, link 2
From link 2:

In November 2011, on Twitter a fan asks Kevin Baird: "...a hugh [sic] fan of TDCC and your bass lines,just wanna know which [sic] pedals do u use to get that cool synthy sound :)"
Kevin Baird replies: "gallien and kreuger 1001 head, ampeg 4x10HE, sansamp rb1 rack effect and an mxr bass octave pedal."
"sansamp rb1 rack effect" most closely matches the Tech 21 Sansamp RBI Rackmount Bass Tube Amp Emulator.

So he is probably just using his amp's or the Tech 21 RBI's built-in distortion on this song. The RBI emulates tube distortion, so that likely plays a part in his overdriven tone. It looks like he uses an octave pedal too sometimes, but that's less important to this particular sound. Again, you can replicate it (or come close) with a decent distortion or fuzz pedal. Go to the shop and try some pedals out with your bass, that's the best way to find out.
As far as synth bass guitar goes, have you looked at the EHX Bass Micro Synth?
Comment: You don't need it for this song, but if you are interested in playing actual synth parts with your bass, check out the [Roland GK-3B](http://www.rolandus.com/products/details/648) which essentially turns your bass into a MIDI source so you can trigger real synths (instead of using a pedal to just modify the bass signal so it *sounds* like a synth). [Video Example](https://www.youtube.com/watch?v=QS2IFL9jn9c)
Comment: Thanks for your helpful answer and research, I reviewed all your recommendations and now I'm pretty sure you can get very close to the tone I'm looking for. However I think it'd still lack the most characteristic (IMO) and probably hardest to replicate feature, the "oscillation" you can hear in long notes (for ex. at 2:40). Being totally new to this world of effects I guess you could do that by programming an envelope filter, or maybe with some pedal with variable oscillation timing like delay ones. Am I asking the impossible?
Edit: That Roland GK-3B looks awesome.
Comment: @Wesker All I hear around 2:40 is sidechain compression, which lowers the volume of the bass every time the kick drum hits. Very common tool in electronic/EDM when you are using only drum machines and synths and are in a studio, but it's hard to replicate live with real instruments. Example: http://youtu.be/5mFu6UYTDhM?t=4m25s
Comment: @Wesker and after watching the video for [I Can Talk](https://www.youtube.com/watch?v=bJDCMth8poM) I'm pretty convinced he is using bass guitar with his amp's overdrive for this sound. He is playing a bass in the video and he gets a similar sound to the song you posted, but on I Can Talk there's slightly less distortion and you can tell it's definitely a bass guitar.
Answer: You can use an Electro Harmonix Bass Micro Synthesizer to get this effect and many others.  This EH pedal is relatively inexpensive and can be used to good effect (ha!) in other songs.  Click on the link for a demo and specs.


Relationship between Gamma and chi squared distributions

Question: What is the relationship between the Gamma distribution and the chi-squared distribution?
Answer: If a Chi-Squared distribution has $p$ degrees of freedom, then this is identical to a Gamma$(\frac{p}{2},2)$ distribution.


Tag out of a forced runner to end the inning, does the run still score?

Question: Bases loaded with 2 outs, ground ball hit towards 3B/SS hole fielded by 3B. The third-basemen elects to try and tag the runner advancing from 2nd to 3rd, but the runner sees the decision and stops running (while staying inside the legal base path) forcing the 3B to continue chasing him to apply the tag. Meanwhile the runner at 3rd base was blazing home and crossed the plate decisively before the 3rd out was made by a tag.  Umpire calls the runner safe at home because the 3rd out was not made by a FORCE out but instead a TAG out....  We realize that this 3rd basemen had a mental lapse as a force play is much easier even he has to go to second with it instead of touching 3rd....
I came up with another scenario which I think might happen more commonly in MLB, hopefully making it easier to find a record of this being called by a MLB umpire....
Bases loaded with one out, ground ball hit to SS, the short-stop fields clean and tosses it to the Second-basemen covering second who touches the base and throws on to first to complete the double play. The throw from the second-basemen is off the mark causing the first-basemen to come down the line toward home, he scoops it up and tags the runner for the 3rd out. However, the runner from third easily scored prior to the TAG being applied the batter/runner forced to first base.
EDIT - In this case the batter/runner did not reach first safely so the run does not count according to According to MLB rules: 4.09 HOW A TEAM SCORES.
(a) One run shall be scored each time a runner legally advances to and touches first, second, third and home base before three men are put out to end the inning. EXCEPTION: A run is not scored if the runner advances to home base during a play in which the third out is made (1) by the batter-runner before he touches first base; (2) by any runner being forced out; or (3) by a preceding runner who is declared out because he failed to touch one of the bases.
However, I still can't find any specific wording in MLB rule book that states a tag applied to a forced runner still counts as a FORCE-OUT.  Can anyone verify this claim??
Comment: Does [Does a run score if the batter is tagged for the 3rd out before he reaches first?](https://sports.stackexchange.com/questions/5552/does-a-run-score-if-the-batter-is-tagged-for-the-3rd-out-before-he-reaches-first) answer your question?
Comment: The comment regarding the fourth out rule on the linked question seems relevant as well, in that the ability to record a fourth out would seem to imply that the run counts. (Especially see [this example](https://en.wikipedia.org/wiki/Fourth_out#Example:_A_quick_fourth_out))
Answer: Page 143 of the Official Baseball Rules defines a force play as:

...a play in which a runner legally loses his right to occupy a base by reason of the batter becoming a runner.

Rule 5.09(b)(6), on retiring a runner (page 43 at above link) says that a runner is retired if:

He or the next base is tagged before he touches the next base, after he has been forced to advance by reason of the batter becoming a runner. However, if a following runner is put out on a force play, the force is removed and the runner must be tagged to be put out.

Since "He" can be tagged, after he has been forced to advance, then I would say yes - a tagged forced runner is a force out. The language describes how a forced play happens, but does not differentiate between the methods of getting the forced runner out for it to be a force out.


Directory/file permissions for web pages on Ubuntu web server

Question: I'm setting up a web server at work, with Ubuntu 14.04 and apache. It hosts 3 webpages (can be more in the future), managed by different developers.
I have concerns on how to setup the public web directories and contents permissions.
The developers are contractors but the web pages are owned by the company, so they might change and I'd not like to change all the file permissions when this happens
At the moment I have the following scheme:
Each developer logins with their personal id.
Each web page is owned by a application id (eg. /var/www/app1 is owned by app1user), which has ssh login disabled. (to keep accountability)
Devopers can access the server with ssh, and upload files with sftp. But then they have to "sudo su - appXuser" and move the files to the web page directory.
Developers are arguing they cannot upload directly with winscp to the web app. Is there an alternative, better scheme?
Sorry if this is a duplicate, I found related questions, but nothing exactly like this one.
Answer: You can setup vsFTPd server. Then you can link users to multiple folders, and multiple users to the same folder. So several developers can work on the same application. You should not use FTP but sftp or ftps, as it's more secure.
Using this configuration, users can upload directly to the server.
Another option is to use Git. Let the developers commit their work to Git, and then you update the production site via SSH. The developers don't need to use FTP in this situation.
Answer: Depends what the requirements are.
For doing reproducible deployments, you can restrict the sudo rules to some deploy script. Developer stages their changes in some way. Whoever does the deploy then calls  sudo -u app1user deploy. The script transfers files, updates databases, emails people, tags something in source control, does a backup, whatever.
Or, grant access to groups. app1grp can write to app1, and there are multiple users in this group. You could then allow direct scp transfers by individual users. Individuals owning files is not a big deal if the server process can read them.


"'WebForm_DoCallback' não está definido" - IE 11

Question: Tive um problema num site que estou programando ao executá-lo no IE11.
Após colocar a tag  dentro da minha  para que o código seja emulado no como IE 9:

<meta http-equiv="x-ua-compatible" content="IE=9" />

Estava tudo funcionando até chegar na função de Callback:
function CallServer(arg, context) {WebForm_DoCallback('__Page',arg,retornoCallback,"",erroCallback,true); }

E é exibida a mensagem:'WebForm_DoCallback' não está definido
Como fazer que o código execute normalmente?
Comment: Onde você está declarando a função `WebForm_DoCallback()` ? poderia mostrar o código dela? Provavelmente há erros de sintaxe nela, ou ela não está sendo declarada.
Comment: @bigown o interessante é que rodando localmente ele funciona perfeitamente mas não no serivdor. E notei também que se trocar o user-agent do IE 11 para IE 9 (além do document type) ele funciona sem problemas. Infelizmente não posso mostrar trecho de código. OBS: essa função roda sem problemas em outros navegadores.
Answer: É possível que seja um problema já conhecido com o IIS/Asp.Net do servidor, onde a Microsoft fornece alguns hotfixes (download aqui) que afetam o servidor de maneira geral e todas as aplicações, ou uma package do Nuget (App_BrowsersUpdate) para resolução do problema em uma única aplicação.
O Scott Hanselman tem um excelente artigo explicando melhor sobre essas soluções (no caso dele o problema ocorria na função __doPostback(), mas a idéia é a mesma)
Comment: instalei a atualização no servidor e nada aconteceu.


what will be the excel vba code to get the values from .INI file?

Question: I have an INI file. Now i want to parse that file in excel vba. the code must be worked in excel 2010 or higher version. I tried on google to get the code for this problem but no one can understand full functionality of that code. So please tell me the code to parse the INI file and also give me overview what is actually happening in the code.
Thanks
Comment: Welcome! Please read the [how-to-ask](https://stackoverflow.com/help/how-to-ask) article to help us help you. Your question is too broad.
Comment: please show us what you have tried?
Answer: Parsing files in VBA is not a beginner's task.  If you'd like to learn to code there are a lot websites with basic tutorials to get you started.
Whatever it is that you need to get out a .INI file, you can do with Excel, about eight different ways, any of which are going to easier on you.
To open the INI file in Excel, just:

Right Click the file → Open With → Excel.

If you need any "parsing" beyond Find (CTRL+F), Copy (CTRL+C) and Paste (CTRL+V) for such a basic filetype, Google "Excel text functions" for some ideas.
Good luck!
Comment: I want to parse the values and used that keyvalues in my excel code in different modules.
Comment: `used that keyvalues in my excel code in different modules`  In different modules?  Did you mean different _workbooks_?  Can you provide an example of how you need the data parsed?  Is this for only one INI, or multiple from multiple applications?  What is the purpose? Is it a one time parse job or would it be executed regularly?   Are there any similar existing utilities (or code) that are suitable or that could be adapted?


Number of combinations to exactly sum to a value of 200

Question: You have coins of 1, 2, 5, 10, 20, 50, 100 and 200 pennies.
One combination could be 1*10 + 5*18 + 10*5 + 1*50 = 200. The order doesn't matter.
Does anyone knows a way to solve this problem by using combinatorial analysis?
Comment: Presumably, by "exactly sum 200 pennies" you mean "sum to a value of 200," because you want to contemplate combinations that include non-pennies.
Answer: It should be the coefficient of $x^{200}$ in the following expression. [Update: Thanks to the tip from @whuber, it can be simplified using partial fractions. I will try to add more steps later today after work.]
$$\frac{1}{(1-x)(1-x^2)(1-x^5)(1-x^{10})(1-x^{20})(1-x^{50})(1-x^{200})}$$
Comment: It can be simplified tremendously, using (for instance) partial fractions.  The ultimate simplification is 51809.
Comment: Right on Sir ! Totally had forgotten about partial fractions.


Configure ReSharper to differenciate between string and String

Question: As asked here What is the difference between String and string in C#? you can use string and String in the code.
To have a common code style, we decided to use string when we create objects:
string name="Elvis";

and String when we use a static method:
String.Concat("Elvis", " lives");

I wanted to configure ReSharper in order to recognize this but I just find that I can configure it to use either the first or the second way:
Comment: Why would you decide to be inconsistent when referring to the same thing?
Comment: I don't find it inconsistent as I refer with string to an instance of string and with String to a static class (or to its static methods).

But anyway, my question is not about the consistent of these decision, I just wanna know if it is possible to configure ReSharper to do it.
Answer: Based on the documentation, I don't believe this is currently possible. I agree it's a logical thing to want to do though, that's exactly how I'd like to configure it too. Resharper only recently added the ability to choose how to reference built-in type names though. Support for any control was apparently only added in 9.1. Here's the ticket requesting it:
https://youtrack.jetbrains.com/issue/RSRP-5662
Note that despite someone else asking for exactly what you want in the comments, there was no reply to his comment from the development team, and it doesn't look like this ability was added when they implemented the feature.
For completeness, here's the relevant page of the documentation describing this option:
https://www.jetbrains.com/resharper/help/Built_In_Type_Naming.html


How to explain the coefficient plotting as pre-trend stability testing for generalized Difference-in-Differences?

Question: Proving the pre-trend parallel is hard in generalized DiD.
From this post, Thomas Bilach suggests me a very excellent way to do so which is called "coefficient plotting"
In short, it can be achieved by running this equation
$$y_{kt} = \alpha_k + \lambda_t + \delta_{-2} d_{k,t-2} + \delta_{-1} d_{k,t-1} + \delta d_{kt} + \delta_{+1} d_{k,t+1} + \delta_{+2} d_{k,t+2} + \delta_{+\bar{3}} d_{k,t+\bar{3}} + \epsilon_{kt}$$
And then, we will see "how close the $\delta$ to 0" for pre-trend periods if I understand correctly. Some examples can be seen in the answer of @Thomas Bilach above.
My effort is that I try to mimic what @Thomas Bilach suggests, along with adding some more covariates (independent variables). However, my result is as below, which make me feel hard in explaining regarding "how close to 0"
For example, I run such regression for two different dependent variables called $y1_{kt}$ $y2_{kt}$
The results for  is $y1_{kt}$

While dkt_4 is $d_{k,t-4}$, dkt4 is $d_{k,t+4}$
As can be seen, p-value of dkt1 is higher than 0.1, insignificant, so whether we still plot the coefficient even it is insignificant.
Apart from that, from the result above, is there any conclusion about the impact of laws on the dependent variable $y1_{kt}$ why the lead indicators seem to be smaller than that of lad indicators?
The result for $y2_{kt}$

How can we explain the stability trend in this case?
Answer: A quick word with respect to the "naming" of your variables. First, the only thing separating the lead variables from the lag variables is an underscore (e.g., _). This makes reviewing your output very confusing. I would imagine it's difficult for you as well, especially when returning to your project after a brief hiatus. Thus, I recommend generating 'event study' variables that you can easily recognize (e.g., lead_3, lead_2, lead_1). The same applies to your lags (e.g., lag_0, lag_1, lag_2). In short, I should be able to distinguish the pre/post epoch instantaneously.
Second, what is dkt_0 denote? Is it the last pre-treatment period or the immediate adoption period (i.e., year of change)? The _ suggests it's a lead, however the numeric value appended to it suggests it's the first adoption year. Going forward I will assume dkt_0 is the immediate adoption year, with dkt1 serving as the first lag.
In the first table, the lead coefficients suggest a deviation from a common trend. The difference appears to stabilize by the second lag, but not for long. Thus, your set of coefficients for the outcome $y^{1}_{kt}$ suggest rather strong pre-trends, which casts doubt on the assumption of trend equivalence before policy adoption. On the other hand, the second table is bit closer to what we would expect to see in a traditional 'event study' framework. The leads suggest a stability of the trends across units in the epoch before the policy change, with a positive treatment effect emerging in the year of change. Effects persist in subsequent periods.
Lastly, ignoring the early post-treatment effects simply because they bound zero is very suspicious. If we don't discover punctual change, it could be that effects emerge with a lag! A discovery of a delayed effect may be of substantive interest. Conversely, dropping insignificant downstream effects may fail to show when the effects of a policy dissipate. In sum, we can't reliably exploit when policy effects phase-in (phase-out) if you only report a subset of highly significant post-treatment effects. Thus, never do this.
Remember, we typically plot the coefficients to show their evolution over time, so it's important that we preserve the chronology of effects within the event window—regardless of their significance. A finding of an insignificant program/policy effect may be, in and of itself, a significant discovery.


How would one interpret this simple chord progression? and what scales to use for improvisation?

Question: So, I come across this progression fairly often:
e.g: G - A - C
I was wondering if this progression has a name since its used often in pop songs.
I interpret it as V - VImajor - I.
Scales to use vary from Gminor pentatonic, to G lydian dominant - A mixolydian - C mixolydian. I am not that familiar with chord scale theory and was wondering how one would fit chord scale theory over this kind of progression?
Edit: after some comments I want to re-evaluate my previous statement about the interpretation of the progression. The progression drwas heavily to G, making it plausible that G is the I chord, making the progression I, IImajor, IV. Either case, the A is the odd one out. How does the A fit in this progression?
Comment: Do you have an example of a song that uses this progression? A more common progression would include Am, instead of A, and that would be in the key of A minor.
Comment: What key feels like the tonal center? G?
Comment: by asking "fit in" are you asking for a functional harmony analysis?
Comment: Can't really see how Gm pent notes fit well, or Mixolydian on either of the other two. Unless it has a blues tinge.
Comment: Hi Peter, I understand that Am is diatonic, but thats why I ask this question: how would one interpret thís progression.
An example is the chorus from let love rule by Lenny Kravitz.
Comment: Tim, thanks for the analysis but its not contributing to an answer. If you want, you could play lydian dominant over each chord in the progression, but it would sound a bit odd.
Comment: Yes, strong pull to G, even from C.
Comment: @Tim, since the progression is not diatonic why not throw in more out notes?  G- pent will give it a bluesy tinge.
Comment: In fact the G blues scale has the maj 3rd of A and works great.  I'm trying G --> A --> C --> C-->  repeat.  Also, @TomvanHeusden, are you just playing power chords or full voicing?  The former allows for some key ambiguity.
Comment: @ggcg, triads, so no powerchords. G blues works great indeed, but what is the essence of this progression? How does the A fit in the progression?
Comment: @ michael curtis: Yes. With a relation to chord scale theory.
Comment: I didn't expect to 'contribute to an answer' That's why it's a comment!
Comment: It may not lend itself to analysis.
Comment: The sequence I II IV should be mentioned in the title of the question to find easily the link by related or similar questions.
Answer: This link names it the Pop-Rock Lydian II progression: I - II - IV - I.
Musicologist Allan W. Pollack attributed to The Beatles its first use in popular music (Eight Days a Week verse) and analyzed it as I - VofV - IV - I.
Comment: I have seen that description/analysis before, and I understand a `II` symbol can be used to show a major triad on the second scale degree, but `V/V` I don't really like. What dominant function is that chord fulfilling?
Comment: Thanks a lot. This was what I was looking for. It also solidifies my initial lydian-feel with this progression. Thanks for the link and the explanation.
Comment: @TomvanHeusden, yeah, I guess I'm picky with _functional_ descriptions. When something is non-functional (like I believe this `II` is) then a functional `V/V` seems inappropriate. Of course that doesn't change the actual music, just chord labels.
Comment: It's outside the scope of this question, but the composer Debussy used lots of non functional triads and seventh chords. Trying to label such chords with Roman numeral analysis functions wouldn't make much sense. I think this is a similar situation but in the pop music genre
Comment: @michael curtis: thanks for the contribution. I agree. I have seen many attempts ramming songs into the nashvile numbering system that, to me, (though correct) don't make much sense. Giant steps, or Stella by Starlight for example.
Comment: @MichaelCurtis I understand your rejection of the use of the V/V label in these cases. Alan Pollack did it all the time in his analysis of Beatles songs, though. For instance, talking about Yesterday: "The chord progression in which V-of-V is followed by IV, with its concomitant cross-relation and implied ethos of deferred gratification makes a somewhat surprising appearance here at the end of the verse." I think he was interested in highlighting this "deferred gratification" function. But I agree, use of Roman numerals in pop-rock is often loose.
Comment: @MichaelCurtis - if V/V isn't followed by V, you're right, it can hardly be labelled as such. II sort of works, but often pop type music defies RNA. NNS works slightly better, but that's more for practical use than being an analytical tool.


want to "avoid" animation effects of UIView subclass

Question: I want to create "rounded" "semi-transparent" UIView (or anything does similar)
my code below results in animation effects, gradually change transparent density.
What I want is to avoid this effects and draw the resulting image straight from the beginning.
Can anyone know how to do?
Thank you.
- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        // Initialization code
        super.opaque = NO;
        self.alpha = 1.0f;
        self.strokeColor = kDefaultStrokeColor;
        super.backgroundColor = [UIColor clearColor];
        self.rectColor = kDefaultRectColor;
        self.strokeWidth = kDefaultStrokeWidth;
        self.cornerRadius = kDefaultCornerRadius;
        self.contentMode = UIViewContentModeRedraw;
        self.clearsContextBeforeDrawing = NO;
    }
    return self;
}
- (void)setBackgroundColor:(UIColor *)newBGColor
{
    // Ignore attempt to set backgroundColor
}
- (void)setOpaque:(BOOL)newIsOpaque
{
    // Ignore attempt to set opaque to YES.
}
- (void)drawRect:(CGRect)rect {
    BOOL areEnabled = [UIView areAnimationsEnabled];

    // with or without setAnimationsEnabled:NO gives me the same result
    [UIView setAnimationsEnabled:NO];

        // with or without beginAnimations and commitAnimations gives me the same result
    [UIView beginAnimations:@"test" context:nil];

    [UIView setAnimationRepeatCount:1];
//  [UIView setAnimationBeginsFromCurrentState:YES];

    // With or without setAnimationDelay gives me the same result
    //[UIView setAnimationDelay:0.0f];
        // With or without setAnimationDuration gives me the same result
        // passing 0.0f the same
    //[UIView setAnimationDuration:0.1f];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);

    CGContextSetLineWidth(context, strokeWidth);
    CGContextSetStrokeColorWithColor(context, self.strokeColor.CGColor);
    CGContextSetFillColorWithColor(context, self.rectColor.CGColor);

    CGRect rrect = self.bounds;

    CGFloat radius = cornerRadius;
    CGFloat width = CGRectGetWidth(rrect);
    CGFloat height = CGRectGetHeight(rrect);

    // Make sure corner radius isn't larger than half the shorter side
    if (radius > width/2.0)
        radius = width/2.0;
    if (radius > height/2.0)
        radius = height/2.0;

    CGFloat minx = CGRectGetMinX(rrect);
    CGFloat midx = CGRectGetMidX(rrect);
    CGFloat maxx = CGRectGetMaxX(rrect);
    CGFloat miny = CGRectGetMinY(rrect);
    CGFloat midy = CGRectGetMidY(rrect);
    CGFloat maxy = CGRectGetMaxY(rrect);
    CGContextMoveToPoint(context, minx, midy);
    CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
    CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
    CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
    CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke);
    CGContextClip(context);

   [UIView commitAnimations];

   [UIView setAnimationsEnabled:areEnabled];

   // I am stacked...
}

Answer: Here's how I've done it in a Cocoa Touch application that I've been working on:
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
// Change opacity (or whatever) here.
[CATransaction commit];

Not sure if this is the best way to do it (or if it'll even work outside the iPhone environment), as I'm a bit of a Cocoa novice myself. Could be worth a try, though.
Comment: still gives me animated effects (gradually change transparency)
The point is that I don't change alpha(or opacity) value, the effects do...
Is this because I use CG functions to draw rectangle?
Comment: David, it was my mistake in other class, the class which does Open GL things (I needed to have dashed lines with width smaller than UIKit provides)
then in that draw method I created this UIView (I was experimenting how I can add "semi-transparent" "rounded" UIView subclass...didn't think too much where to put experimenting codes...)
Anyway, thank you for your comment.
I know know CATransaction basics
Thank you again!
Answer: Using UIView animations from within drawRect is pointless. Also, it's not possible to disable animations by overwriting UIView properties since CoreAnimation animates layer—not view—properties. If the alpha fades when using one of you views, the problem is not in your classe's implementation, but from where it is called. Some surrounding code did [UIView beginAnimations] before setting your view's or superview's alpha.
Do disable all animations, you can use the method proposed by David.
Comment: David, thank you for your comment.
I got your point.
Now, I see many "Calendar applications" showing event(or todo) showing with some transparency (and even with shadow)
I wonder how those are done, setting up animation disable and only set up animation when needed would cause the same problem right?

Katsumi (if I ask too primitive questions, excuse me I'm first year objective-c programmer)
Comment: Ops, the message above is for "Nikolai"
Thank you both!
Comment: Nikolai
I finally got it.
It was very simple mistakes I had in other class, the class which draw OpenGL ES codes.
As I experimenting the way to draw "semi-transparent, rounded view" I put the code in that draw method...
so each time adding new semi-transparent UIView inifinitly...

Thank you very much anyway, I'll remember your point as I will need those techs in the future.
Answer: As of 3.0, you can have any view round corners easily:
1) Set clipsToBounds to YES.
2) set view.layer.cornerRadius to some value (5.0 is pretty good, but you can play with values). This also requires you to #import <QuartzCore/QuartzCore.h> in the file where you are setting this property.
All done!
If you are using IB to define views, you can set the subview clipping in IB but you can't modify the layer properties, so you'll have to add that part in viewDidLoad or somewhere similar.
Comment: Kendall,
Thank you for your comment!
I couldn't find "clipsSubviews" but did find "clipsToBounds"
So instead of doing overwriting drawRect, in initialization method of my UIView subclass, I did the followings:

  self.clipsToBounds = YES;
  self.layer.cornerRadius = 5.0f;

I got rounded view!

Thank you!
Comment: I think it's "Clip Subviews" in IB, but the actual property (that you found) is clipsToBounds.  I corrected my code here so that others would not have to hunt for it... thanks for the response.


Is there a fundamental theorem of calculus for improper integrals?

Question: Let $f\,\,$ be a continuous function on $[a,\infty)$ such that $\int_a^\infty f(t)\,dt$ converges. Define the function $F\,$ on $[a,\infty)$ with
$$F(x) := -\int_x^\infty f(t)\,dt \qquad\text{for all}\quad x\in[a,\infty).$$
Can we somehow deduce from this—using the regular fundamental theorem of calculus—that $F\,\,$ is continuous and differentiable on $(a,\infty)$, and that $F\,\,'(x) = f(x)$ for all $x\in(a,\infty)$? If so, how? Are such "improper" versions of the fundamental theorem to be found in some book out there that I can reference?
Comment: Like [this](http://books.google.com/books?id=ECU9AAAAIAAJ&pg=PA387)?
Answer: $$F(x) := -\int_x^\infty f(t)\,dt = -\int_x^c f(t)\;dt + \int_c^\infty f(t)\;dt$$
The derivative of the first term of this sum with respect to $x$ is $f(x)$, and that of the second term is $0.$ You have some leeway as to what $c$ is; you could just choose $a.$
Comment: @mavavilj : No $\text{"} x \text{''}$ appears in the second integral, so that does not change as $x$ changes. These are derivatives with respect to $x,$ and the derivative with respect to $x$, of a quantity that _does not change_ as $x$ changes is $0. \qquad$
Comment: You could also say that the second term, if it converges, is just a constant, and derivative of a constant is just a zero.
Comment: @TheCoolDrop : The frequency with which students ask how to tell whether something is a constant is a reason to think that an answer phrased like yours may fail to be understood, whereas my comment explains what a "constant" is.
Comment: Why is the second one 0?


Find the orthogonal trajectories of a function

Question: The function which I need to find the orthogonal trajectories to is: $\quad y = x^3 + c$
So I derive the function:
$$y'= 3x^2$$
Then I get from the original equation:
$$y' = \frac{3(y-C)}{x}$$
The DE of the orthogonal function:
$$y' = \frac{-x}{3(y-C)}$$
the separable equation is
$$(y-C)\,dy = \frac{-x}{3}\,dx$$
after integration
$$\frac{y^2}{2} - C y = \frac{-x^2}{6}$$
Explaining $y$ from this equation:
$$y = \sqrt{C^2 - \frac{x^2}{3}} + c^2$$
Plotting this equation and the original using the parameter of $\,c=3\,$ I can't see the orthogonality. What did do I wrong? Can anybody help me?
Answer: Immediately take the negative reciprocal without substituting anything:
$$
y = x^3 + C \implies y' = 3x^2 ~~\xrightarrow{\textsf{negative reciprocal}}~~ y' = \frac{-1}{3x^2} \implies y =\frac{1}{3x} + D
$$
Comment: But there is one thing I can't understand. Value of D should be the C from the original equation. But how can I determine this exactly?


How to edit an old commit and push editions to the server?

Question: I have 3 commits in master branch:

third
second
first

I need to get first commit (I did it using checkout command), edit it and push commit to remote repo. I've already made the following steps:

git checkout  (my branch is "(detached
from ...)")
some editions
git commit --amend

But how I can push my commits to the master branch? Thanks in advance.
Answer: just using git push origin master. Be sure you are at master branch.
Answer: git checkout master

And then
git merge 'other_branch_name'
Answer: use rebase :
git rebase first^ --interactive

then replace pick by edit in the editor, then save and run. You will be able to edit things, then commit by git commit --amend
Then, to push on your server where your private repo is located:
git push origin master -f

-f is required and means "force" : because it's usually a bad idea to rebase something published (that's why I put private repo in bold : don't do that if the repository is used by other people, or warn them first they will have to rebase or reset their local repo)
Answer: It seems you haven't been working on master branch but on detached HEAD. It is a bit dangerous since you can lose commits until there is a reference to them (branch, tag). So use:
git branch temp

Then you can put your commits to local master:
git checkout master
git merge temp

The temporary branch is useless anymore, so delete it:
git branch -d temp

Your commits are on local master now and you can push them.
(You could also make a notice of the SHA1 of the detached HEAD, skip git branch commands I mentioned and use the git merge with that SHA1 instead of a branch name. However, I find the way using branch more git-aware.)


ANOVA with missing cells and multi-level analysis

Question: I'm about to analyse some data (hypothesis testing) and would like some feedback on my approach as I have never seen this situation (missing cells in an ANOVA-like table). I would also like to know if a multi-level approach would be better (I have no experience with it, just curious to learn more). The data have the following repeated measures design:
    A1       A2
B1  A1B1    A2B1
B2  A1B2     .
B3  A1B3     .

(Sorry about formatting). As you can see, A2B2 and A2B3 do not exist (were not tested).
The first hypothesis is that  y(A1B3) > y(A1B2) > y(A1B1), while the second is that y(A2B1) > y(A1B1). I would also like to compare y(A2B1) with y(A1B2) & y(A1B3), though these will be exploratory. The main reason for including this A2B1 was to verify that something did not go wrong as there is a well established effect (hence the hypothesis y(A2B1) > y(A1B1)). So I think that this is rather a separate question and, once verified, does not require further consideration (e.g. comparison with the other factors). That is the reason for the missing cells.
I am thinking about running a one-way ANOVA (effect of B holding A1 constant) for hypothesis 1 and a t-test (effect of A holding B1 constant) for hypothesis 2. As for the exploratory tests I was going to run two further t-tests. I think this is all ok but would like some feedback on it in case there is a problem with it.
As for the multi-level approach, the study involved a sample of participants all carrying out the same task. So it is hierarchical because there is a "single subject" level (each with ~30 trials in each condition/level), and then a "group" level on which I was planning to test the hypotheses on just the aggregated (means) single-subject data. So I wonder if multi-level is the way to go instead of ANOVA + t-tests?
Edit for clarification: there are 48 participants. By group level I just meant taking each subject's summary statistics and analysing those as in a typical ANOVA. As for the design, it is repeated measures and all subjects carry out the same task with the same conditions. Each trial is defined by belonging to one of the cells in the table.
Edit 2 for an example: Each trial of the experiment began with information about the upcoming target stimulus location, and this was either correct (A1) or incorrect (A2)*. When the target stimulus appeared in either the correct/incorrect location, it was either presented on its own (B1), with a distractor that was similar to the target (B2), or with one that was highly dissimilar (B3). The thing that makes it a bit strange is that *when a distrctor was presented, the preceding information was always correct (A1), hence the missing cells. So the factor A1/A2 was only "relevant" when there was no distractor, otherwise it was always just A1.
Comment: How many participants do you have? Can you explain the design a bit more ? What is the "group" level ? Aggregating the data will lose information.
Comment: Hi @RobertLong I have edited the post to answer your questions. I am not sure how else I can explain the design.
Comment: OK thanks. Just so I am clear, A and B are both factors with 2 and 3 levels respectively. The combinations A2B2 and A2B3 were not applied, and you are interested in a model that includes the interaction between A and B ?
Comment: Yes exactly. Although I was under the impression an interaction wouldn't be possible since I can't compare across all levels of A with all those of B. But I am not sure, if it is possible to somehow do this that would be great.
Comment: @RobertLong just in case an example would be better than speaking abstractly then I have edited in a more detailed description of the setup
Answer: It might suffice to do a one-way ANOVA, examining all 4 groups not just the 3 you seem to have been considering. That uses all of the information you have to get a better pooled estimate of the within-cell variance. Test that the overall model is significant.
Then examine your pre-specified comparisons. You "verify that something did not go wrong" based on your comparison of A1B1 against A2B1. Then you can proceed with the other tests of interest among the levels of B within A1. Use appropriate correction for multiple comparisons.


BadMethodCallException in Macroable.php line 74: Method specialization does not exist

Question: I am getting this small issue. Below is the source code
Doctor Model:
class Doctor extends Model {
......
....
     public function specialization() {
        return $this->HasMany('App\Specialization');
    }
}

Specialization Model:
class Specialization extends Model {
......
....
     public function doctor () {
        return $this->belongsTo('App\Doctor', 'id');
     }
}

Specialization Model:
Here the spec_id is a foreign key
class DoctorController extends Controller
{
......
....
 //Create a Doctor
    public function createDoctor(Request $request) {
    $doctor = new Doctor();
    $doctor->doctor_id = $request->input('doctor_id');
    // $doctor->spec_id = $request->input('spec_id');
    $doctor->spec_id = $request->specialization()->id;
    $doctor->dob = $request->input('dob');
    $doctor->age = $request->input('age');
    $doctor->gender = $request->input('gender');
    $doctor->qualification = $request->input('qualification');
    $doctor->experience = $request->input('experience');
    $doctor->phone_number = $request->input('phone_number');
    // $doctor->email = $request->user()->email;
    $doctor->email = $request->input('email');
    // $doctor->user_id = $request->user()->user_id;
    $doctor->user_id = $request->input('user_id');
    $doctor->save();
    return response()->json(['doctor' => $doctor], 201);
    }
}

Please let me know how do I fix it.
Answer: The error is most probably from ... = $request->specialization()->id; where the specialization() method doesn't exist. The error message also mentions Macroable, which makes me believe that you are type-hinting the Request facade in the method signature, not the correct Illuminate\Http\Request type.
Check your use-statements at the top of the file.
Answer: I think in the request does not have specialization, you to try to use Log, to find out what the request has
Answer: Request $request is not an eloquent model.
Try using $doctor instead of $request
$doctor->specialization->id and am sure you'll be able to get the id.
Also, the HasMany is spelled wrongly. Change the 'H' -> 'h'


Closed-form for Floor Sum 3 - With knowledge of inner expression

Question: Consider the following sum:
$$\sum_{k=0}^{n}\left\lfloor\sqrt{k^2+N}\right\rfloor$$
Assume we know the factorization of $N$, in other words, we know for which $k$, $k^2+N$ will be square, according to Fermat's Factorization Method.
$N$ in this case is a positive odd integer.
Can we use this knowledge to get a closed-form for the sum?
Thanks a lot
Answer: How large is $n$ compared to $N$? Is $n\approx\sqrt{N}$? You are counting the lattice points in a region bounded by a hyperbola, and $\sqrt{x^2+N}$ behaves like $x$ for large values of $x$. Additionally, it is not likely that your expression has a nice closed form, but it is for sure pretty close to
$$ \int_{0}^{n}\sqrt{x^2+N}\,dx = \frac{1}{4} \left(2 n \sqrt{n^2+N}-N \log N+2 N\log\left(n+\sqrt{n^2+N}\right)\right)$$
which if $n=\sqrt{N}$ behaves like $\left(\sqrt{2}+\log(1+\sqrt{2})\right)\frac{N}{2}\approx\frac{7}{6}N$ for large values of $N$.
Also notice that the problem of finding the first two terms of the asymptotic expansion of
$$ \sum_{k=0}^{\sqrt{N}}\left\lfloor\sqrt{N\color{red}{-}k^2}\right\rfloor $$
as $N\to +\infty$ is exactly the Gauss circle problem. In this case the first term of the asymptotic expansion is $\frac{\pi}{4}N$ for similar reasons.


I need to fix this loop

Question: plt.show()

CC = []

fig, ax = plt.subplots(4,4,figsize=(8,8))
tau = 130

for n,img in enumerate(ls2):
    sel = img <= tau
    img[sel] = 0
    visited = img==0.0
    i_1 = n % 4
    j_1 = n//4
    if i_1<4 and j_1<4:
        img = ls2[i_1+ax.shape[0]*j_1]
        ax[i_1,j_1].imshow(img,cmap='gray')
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            if visited[i,j]:
                continue # skip visited pixels
            ## for a grayscale image, this will be img[i,j,0]
            todo = set()
            todo.add((i,j))
            visited[i,j]=True
            # append a new connected component at i,j, maximum 0
            CC.append( (i,j,img[i,j]) )
            # inner loop(s): visit neighborhood
            while len(todo)>0:
                r,c = todo.pop() # get an element from the set
                # compute the valid "limits" of the neighborhood (edges of the graph)
                rl, rr = max(0,r-1), min(img.shape[0],r+2)
                cl, cr = max(0,c-1), min(img.shape[1],c+2)
                for this_row in range(rl,rr):
                    for this_col in range(cl,cr):
                        if visited[this_row,this_col]:
                            continue
                        todo.add((this_row,this_col))
                        visited[this_row,this_col]=True
                        if img[this_row,this_col]>CC[-1][2]:
                            # found a new maximum
                            CC[-1] = (this_row,this_col,img[this_row,this_col])

x = [r for r,c,val in CC]
y = [c for r,c,val in CC]
vals = [val for r,c,val in CC]
plt.scatter(y,x)

plt.show()

In the given image, I am trying to find the maxima and put a point on each of them (the white spots). But all of the dots get put on the last image. Can someone help?
x = [r for r,c,val in CC]
y = [c for r,c,val in CC]
vals = [val for r,c,val in CC]
plt.scatter(y,x)

I tried to indent this block inside the loop. But it doesn't work.
Answer: You have created a subplot but are not plotting in the correct subplots. Use something like the following to plot the graphs in appropriate subplots.
ax[r][c].scatter(y, x)
See documentation for more information

I need to fix this loop


Identificar versão do Android por algum método

Question: Existe algum método para identificar a versão do Android do usuário assim que ele entrar no aplicativo?
Será útil para o aplicativo executar ou não animações entre transições de telas, caso o usuário tiver uma versão mais antiga, não executará, caso tiver uma versão mais atualizada, executara a transição animada.
Answer: Sim, você pode verificar pelas constantes de versão.
Em geral, para tratamento de incompatibilidade de algumas funções da API é comum usar a constante Build.VERSION.SDK_INT, que possui a informação de qual versão o dispositivo esta rodando.
E junto com os valores dos SDK's, disponível na classe Build.VERSION_CODES você consegue executar código condicionado a versão em que o aplicativo irá rodar.
Um exemplo seria:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    ViewPropertyAnimator vpa = view.animate();

    // Restante do código usando ViewPropertyAnimator

} else {
    Animation an = new AlphaAnimation(0f, 1f);

    // Restante do código usando a API View Animation
}

Esse código não irá funcionar para dispositivos com versão menor que o SDK 4 (Android 1.6 Donut), essas constantes foram adicionadas nessa versão.


How to speed up Drupal 7 calls to _theme_process_registry?

Question: Using xhprof php profiler I can see there is much more then 100000 calls to function_exists
each time user accesses a Drupal 7.8 page, mostly from _theme_process_registry.
What to do to limit the number of or cache these calls ?
Comment: I found there is already an issue related to this on drupal.org http://drupal.org/node/519940 Performance: optimize building theme registry by using get_defined_functions() instead of function_exists()
Answer: I found there is already an issue related to this on drupal.org: Performance: optimize building theme registry by using get_defined_functions() instead of function_exists()


php 7.2 is preventing insert record without adding all the table's fields

Question: I upgraded my php version from 7.1 to 7.2.
In my phpmyadmin I have a table like this one :
CREATE TABLE `images` (
  `image_id` int(11) NOT NULL,
  `image_name` varchar(255) CHARACTER SET utf8 NOT NULL,
  `image_title` varchar(255) CHARACTER SET utf8 NOT NULL ,
  `image_alternative` varchar(255) CHARACTER SET utf8 NOT NULL ,
  `image_folder` varchar(255) CHARACTER SET utf8 NOT NULL ,
  `image_status` int(11) NOT NULL ,
  `date` datetime DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

image_id is the only required field. The rest, all optional and can be empty.
When I'm trying to insert a record :
INSERT INTO `images`(`image_name`,`image_status`) VALUES ("new image",1);

I'm getting this error
 MySQL said: Documentation #1364 - Field 'image_title' doesn't have a default value

To solve this issue I had to add in the table a predefined value for all fields or in my query to mention all fields even if they are empty.
INSERT INTO `images`(`image_name`, `image_title`, `image_alternative`, `image_folder`, `image_status`)
VALUES ("new image,"","","",0)

I understand that php 7.x is more secure from the old versions, and they are trying to make better with time. But how can I solve this issue without the need to change all my tables or my queries. Thank you
Comment: This has nothing to do with PHP or any specific version of it. All those columns that are defined as **`NOT NULL`**… well, they are *not optional*. Your assumption *"the rest all optional"* is wrong.
Comment: I fail to see how PHP is related here
Comment: The error message is generated by MySQL. PHP doesn't change your query. The query doesn't provide a value for the fields `image_title` and because it doesn't have a default value, the query fails no matter how you run it. Try to execute it using a MySQL client (the command line `mysql`, [HeidiSQL](https://www.heidisql.com/), `phpMyAdmin` or whatever program you use to check the content of the database). It will fail with the same error.
Comment: Guess: the query has always failed, but your new PHP installation has `display_errors` on by default…?
Comment: The 'image_title' has definition "NOT NULL", meaning you need to provide a value in insert or define a default one.
Comment: the codes were working perfectly in the php 7.1 version. nothing has changed except updating the php version to 7.2
Comment: My query was always successful. i never had any errors before. display errors was on aswell. Fields with NOT NULL will allow me to save records with empty fields. If i had a field as NULL and i save a record with empty field, this field will be replaced with NULL which i don't wont.
Answer: For future reference, here are some tips to remember:

To make columns optional, simply replace the NOT keyword with the DEFAULT keyword. Remember: "Default Null" is optional. "Not Null" is required.
The image_id column should be an AUTO_INCREMENT field. Adding it prevents allowing INSERT INTO ... SQL statements from failing, whenever the image_id column name & its value aren't explicitly inserted in a query. (Both of the INSERT INTO queries in the OP are missing those items.)
The image_id column is also the PRIMARY KEY for this table. That should be added.

The table should look like this after those simple edits:
CREATE TABLE `images` (
`image_id` int(11) NOT NULL AUTO_INCREMENT,
`image_name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`image_title` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`image_alternative` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`image_folder` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`image_status` int(11) DEFAULT NULL,
`date` datetime DEFAULT current_timestamp(),
 PRIMARY KEY (`image_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

Answer: The only possible explanation I can find for this would be connected to the removal of the sql.safe_mode ini setting:

sql.safe_mode boolean
If turned on, database connection functions that
  specify default values will use those values in place of any
  user-supplied arguments. For details on the default values, see the
  documentation for the relevant connection functions.

If that was on in your previous PHP version and somehow caused your chosen database function to set SQL strict mode to off, meaning your SQL session operated in non-strict mode, then that would explain the difference:

For data entry into a NOT NULL column that has no explicit DEFAULT
  clause, if an INSERT or REPLACE statement includes no value for the
  column, or an UPDATE statement sets the column to NULL, MySQL handles
  the column according to the SQL mode in effect at the time:

If strict SQL mode is enabled, an error occurs for transactional    tables and the statement is rolled back. For nontransactional tables,
  an error occurs, but if this happens for the second or subsequent row
  of a multiple-row statement, the preceding rows will have been
  inserted.
If strict mode is not enabled, MySQL sets the column to the implicit    default value for the column data type.

https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html

Either way, you should explicitly choose which SQL mode you want to operate in and not leave it up to implicit defaults. And you should prefer to run in strict mode and either make your columns nullable, or provide explicit default values for them.
Comment: Thank you @deceze. It seems this is a strict_mode issue. When i changed it worked like a charm.


How to override theme for quicktabs which actually renders a view

Question: In D8, I want to display a view through quicktabs. For this, at first I have created a view file and call the view through QT. The view is displays well through QT. Now, I want to change the look & feel of the view. Please look into the screen of view which I've created before.
Now, based on the below theme suggestions I created the file block--quicktabs-block--gallery-tab.html.twig to override and place it under the "templates" folder in my theme.

When I write something fixed like "Hello Test" in the block--quicktabs-block--gallery-tab.html.twig, its showing well. However, when I tried to do something dynamic coding like below, nothing appeared.
{% if title %}

{{ title }}

{% endif %}
{% for key, row in rows %}
  {% if key in rows_with_tabs %}
    {{ tabs }}

  {% endif %}
  {% if key in rows_with_page_starts %}
    {% for page_key, page in rows_with_page_starts %}
      {% if key == page %}

 0 ? ' quicktabs-hide' : '' }}" id="quicktabs-tabpage-{{ quicktab_id }}-{{ page_key }}">
        {% set page_number = page_key %}
      {% endif %}
    {% endfor %}
  {% endif %}
  {{ row.content }}
  {% if key in rows_with_page_endings %}
    {# close .quicktabs-tabpage #}

  {% endif %}
  {% if key == last_index %}
    {# close .quicktabs-main #}

  {% endif %}
{% endfor %}

Am I overriding the correct file? Any suggestion?
PS:
after implementing the template file as said above, the suggestions looks like:

Comment: Seems correct, is your twig template called ? did you rebuild cache ? is the `FILE NAME SUGGESTIONS:` changed with x next to your template ?
Comment: Yes, I saw that anything fixed like "XYX or TEST" within the view gets printed. I re-build the cache too. I can't understand about "changed with x next to your template". I just created a file named - `block--quicktabs-block--gallery-tab.html.twig` as said above.
Comment: Than the `FILE NAME SUGGESTIONS` should have a line like this
`x block--quicktabs-block--gallery-tab.html.twig`
the x should be on the line of your template, meaning it is using this template
Comment: Im new to drupal 8. Can you send me sample code for it? Means how to write it?
Comment: I am not telling you how to write something.  I am asking you to observe in your HTML code.  In you sample `FILE NAME SUGGESTIONS:` above the x is next to `block.html.twig`.  Did it change place after you included your template and cleared cache ? Its an indicator of which twig template is used.
Comment: I understood now. I have updated the question.
Answer: As Sunil says you are probably using view variables in your block template
Perhaps look for another template to override further down in order to find a views template to override and use your html/twig code

Here is what I would do.
Find the first template inside views-view.html.twig in my case it is views-view-unformatted.html.twig (red arrow above) and copy it in your theme templates folder.  Clear cache and make sure it is used and than explore the possibility of renaming it to be specific and used only for the quicktabs block.
See here for more info on how to name your templates
Comment: Yes, I'm using View in QT as said in my question title. Should I first template the view like `views-view--gallery--block-1.html.twig` ?
Comment: I can't know which template name you have to use without looking at the html comments of you code, find the first template inside `views-view.html.twig` as I show in my red arrow above and copy it in your theme.  Make sure it is used (after clear cache) than explore renaming it to be specific to your quicktabs.


How is the Order By working in this query

Question: SELECT * FROM TT
ORDER BY (SELECT AGE
          FROM TTT
          WHERE NAME='TANDEL'
          );

Result is,
JOHN    2
PRAVEEN 2
KUMAR   2
RAKESH  2
WASIB   2
GURUNG  2
DAYALAN 5
DEEPAK  2
TANDEL  5
RAGHU   5
GIGA    5
DEEPA   5
DEVARAJ 2

Note: Table TT and TTT both have same data.
Answer: Quite simply, it's not working. Order By requires a column or columns, if random data is passed into it instead of column names, it does nothing.
Answer: Order By requires a column or some columns
ORDER BY CLAUSE
SELECT *
FROM TT
ORDER BY colname

Answer: In the order by clause we can add two thing:

Column names
Select * from TTT order by age;

Coulmn number to filter
Select * from TTT order by 2;//if age is the second column in the table
            or
Select name,age from TTT order by 2; // this will order by age

In the following case the inner query
  SELECT AGE
      FROM TTT
      WHERE NAME='TANDEL'

will return 5
and the parent query
  SELECT * FROM TT
   ORDER BY 5


I am importing a module from home.module import contacts but its showing error no module named home

Question: enter image description hereenter image description here
So what can I do here cause I have tried everything but nothing happened please help
pip install home is also showing error so that's a big problem
kindly help
Comment: Welcome to the site. [Please do not post pictures of your code or errors.](//meta.stackoverflow.com/q/285551)
Answer: Try in you VS Code: Pip install home. After that you can import the module in your python file and use it.
Comment: Pip install home is also showing error
Comment: What is the error that it gives?


90,8 by 30,1 egyptian division

Question: I am having trouble using the Egyptian method of division.
So far I have
1    30,1
2    60,2

90,8 - 90,3 -> need 5 additional units.
I know at this point I need to take parts of 30,1 but I am not sure which direction I should go from here.
I tried the 2/3 part.
1                  30,1
2/3                20, 2/3
1/3, 1/9           13, 2/3, 1/9

I am not sure where to go from here.
Answer: I have figured this out on my own. All lines that are used in the final answer are denoted by a "\" placed in front of that line.
Continuing after 2
\      1       30,1
\      2       60,2

As I stated earlier we need 5 additional units to reach 90,8 but we can decrease this by taking other parts
\      1/8      3, 1/2, 1/4, 1/8
\      1/31     1

From here we only need an 1/8 more to reach 90,8. However the Egyptians never repeated unit fractions in their notation (1/8 was used when taking the 1/8 part). So we must change 1/8 into other unit fractions. 1/8 = .125 = .1, .025 = 1/10, 1/40
       1        30,1
\      10       300,10
\      40       1000, 200, 40

We now take the numbers on the right and reciprocate them. These form the unit fractions that sum to 1/8.
Our final answer is 3, 1/8, 1/31, 1/310, 1/1240.  Checking this with your simplest method for division you will find that this equates to 98/31 or 3.161290323....

90,8 by 30,1 egyptian division


Joint cdf of extreme values

Question: A die is rolled twice,

$X_1$ : the minimum value to appear in the two rolls
$X_2$ : the maximum

I would like to derive $\ F_{X_1,X_2}(x_1,x_2)$.
I know that that the CDF of $\ X_1 $     = $\ 1- [1-{F(x)]}  ^  n   $,   CDF  of $\ X_2  $   $\ = $    $ \  [{F(x)]}  ^  n $
 and     $\ F_{X_1,X_2}(x_1,x_2)  = P(X_1<x_1|X_2<x_2)F_{X_2}(x_2)  $
The solution seems to be :
$\ F_{X_1,X_2}(x_1,x_2) = 2F(\min[{x_1,x_2}])F(x_2) - F(\min[{x_1,x_2}])^2 $
I want to understand how such solution can be obtained.
Comment: What is $n$ here? 2? And $F$ is the cdf?
Comment: Please supply more details, is this self-study?
Comment: the example is taken from the paper "coping with copula"
Answer: Let's work out the general answer: we have independent identically distributed random variables $X_i$, and a sample of $n$ instantiations of these RVs. I'll denote the sample maximum by $X_{max}$ and the sample minimum by $X_{min}$. Let the $X_i$ have the cdf $F$. Then we have the following:
$$ P(X_{max} \leq x \cap X_{min}> y) = (F(x) - F(y))^n \textbf{1}_{\{x \geq y\}} $$
where the $\textbf{1}$ is the indicator function. This holds because for $x\geq y$, the probability that the sample maximum and minimum are in the interval $(y, x]$ is equal to the probability that each of the $n$ random variables is in this interval.
Then to get the joint density, use:
$$ P(X_{max} \leq x \cap X_{min}\leq y) = P(X_{max} \leq x) - P(X_{max} \leq x \cap X_{min}> y) $$
$$P(X_{max} \leq x \cap X_{min}\leq y) = F(x)^n- (F(x) - F(y))^n \textbf{1}_{\{x \geq y\}}$$
If you work out what this is for $n=2$, and look at the cases $x \geq y$ and $x < y$, this is equivalent to the expression you gave.
Answer: This is a problem in which working from first principles is better than specializing from poorly-understood general formulas. If $X$ and $Y$ are
the outcome on the two dice, then their joint mass function $p_{X,Y}(i,j)$ has value
$\frac{1}{36}$ for all $i,j \in \{1, 2, \dots, 6\}$ and so $p_{X_1,X_2}(i,j)$ has value $\frac{2}{36}$ if $1 \leq i < j \leq 6$, and value $\frac{1}{36}$ if $1 \leq i=j \leq 6$. The CDF can be worked out from this, but writing it out explicitly
gives a long multi-case expression that I will leave to the OP to figure out.

Joint cdf of extreme values


Stop YouTube Video on Back Button of Windows Metro App 8.1

Question: I have a page on which i am showing multiple youtube videos as webviews. When i play any video, then correspoding video starts playing. But When I click on the back button of the App i should be stop then but its running in background(can hear voice of video).
here is the code of back button:
protected void GoBack(object sender, RoutedEventArgs e)
{
        ((Frame)Window.Current.Content).GoBack();
}

Tell me how i can dispose of this webview or can stop video.
Thanks
Answer: First make sure that the page is finalized; most probably by detaching all the event handlers you manually attached before. Then (sooner or later) the page will be finalized which in turns disposes of the webview.
A similar effect would be achieved by forward navigating the webview to an empty html page.
Answer: Here is the solution:
Invoke the UnLoaded event of WebView
 - webView.Unloaded += webView_UnLoaded;
Then change the source of the webview in webView_UnLoaded event handler:
Here is my code:
private void webView_UnLoaded(object sender, RoutedEventArgs e)
    {
        WebView webView = (WebView)sender;
        webView.Source = new Uri(" ");
    }


The meaning of probability when large number law fails

Question: When the large number law fails, the frequency of an event does not converge to the probability, so what is the meaning of probability in these cases?
PS: Please adds references to the answers (if it possible).
Comment: An answer to [your previous question](http://stats.stackexchange.com/questions/29882/when-does-the-law-of-large-numbers-fail) demonstrates that it cannot possibly fail in this application (for which it is implicitly assumed the repeated observations of the event are *independent*), so this question is devoid of content.
Comment: We seem to field a fair number of philosophical questions, so I wouldn't be too concerned it's off-topic. But, under standard assumptions, it is a bit vacuous.
Comment: I am not sure what this question is actually asking. If it is a philosophy of mathematics/statistics question I do not think Cross Validated is the right place to ask it. If the question of how to interpret I.I.D random variables when some portion of the hypotheses of a LLN fails you might want to give an example of what you mean (I am having trouble thinking of any example off the top of my head).
Comment: The failure of a law of large numbers does not imply there is an event for which the observed frequency does not converge to the probability.  For example, the failure of the sample mean of a Cauchy variate to converge to anything says something about a particular integral, but not about long run frequency $\to$ probability.  Also what @whuber said (+1).
Answer: As pointed out in the comments and as discussed here, it is extremely difficult to think of practical examples where the LLN fails to hold for the probability of an event. I think this illustrates the strength of Kolmogorov's result.
It is also important to point out that it pacified the debate between Bayesian and frequentists. It means that you do not need to worry about the question "what is a probability?", but only about "can I measure it?".
Still, there is one obvious case when it is impossible to get IID sampling of an event: when it happens only once. In that case the LLN does not apply and we are back to good old debate on what is a probability. But I think this is also outside the scope of this forum so I'll just cite some references from the top of my head.
Henri Poincaré in Science et Méthodes (1914) emphasized the deteministic nature of randomness. Chance is an effect of the imprecision of our measure instruments.
Paul Lévy in Calcul des probabilités (1925) advocates that probabilities of single events are meaningful only if they are close to 0 and 1.
Bruno de Finetti proposed to define probability as a coherent weighing scheme of prior beliefs.
More recently, Peter Walley in Statistical reasoning with imprecise probabilities tried to extend de Finetti's definition to make probability a representation of human knowledge.
This list is obviously very biased and incomplete to say the least.
Answer: I think you are confusing events with random variables.  The strong law of large numbers says that if $S_n= (X_1+X_2+X_3+...+X_n)$ then $S_n/n$ converges to a constant almost surely.  This is convergence of a sequence of random variables to a random variable that is degenerate (i.e. equal to a constant).  If the law of large numbers fails the convergence could be to a non-degenerate distribution or it may just not converge at all. But this does not connect to relative frequencies of measurable events in a probability space.  Suppose $A$ is a measureable event in a probability space.  Define the independent binary variables $X_i$ for $i=1,2,3,..,n$ such that $X_i=1$ if $A$ occurs and $X_i=0$ otherwise.  Then $S_n$ is Binomial in this case and $S_n/n$ does converge to $p=P(A)=E(X_i)$.  So there is no contradiction about measurable events having their probaility expressible as a limiting relative frequency.
Comment: I think the sentence *But this does not connect to relative frequencies of measurable events in a probability space* is (potentially) confusing, especially since you pretty much demonstrate the opposite immediately following. :)
Comment: I said that in the context of failure of the law of large numbers not implying failure of a frequency of occurrence of events to converge to the probability of the event.  That is where the OP seems to be confused.  At least that is what i read out of his question.  The sequence of random variables that fail to converge does not connect to the occurrence or nonoccurrence of a measurable event.  But throught the bernoulli variable that I defined you can connect it to a sequence of random variables but for that sequence the strong law applies.
Answer: The Law of Large numbers as it is commonly defined doesn't deal with events converging to a probability but with the results of events converging to an average value.
Let's take an example of a die with six sides.
According to the law of large numbers the average is supposed to converge towards $\frac{1+2+3+4+5+6}{6}=3.5$. A probability is a value between 0 and 1. The 3.5 in this example is no probability. The probability that a single dice hits 3.5 is even zero.
Comment: That "relative frequencies" converge almost surely to the true probability of the event is a particular *subcase* covered by the LLN, though.


What are the implications of converting all my groups to universal groups?

Question: In Exchange 2010 distribution groups must be universal. This is supported by documentation

You can create or mail-enable only universal distribution groups.

I am trying to create a role based security group structure so that if someone leaves or changes jobs you only have to change the groups membership of a users "role" (Where the role is just another security group). In its simplest form roles would have users for members and the role would itself be a member of other resource-centric security groups e.g. a read-write group for a share. There is more to the model than that but it should be enough for the purpose of this question.
The problem comes from when I want to add these role groups as distribution members. If I try and add a "Marketing Manager" role to the "firstname.lastname@example.com" distribution list it will not forward mail to the role members unless the role security group is universal.
Universal groups cannot be members of global groups though. So, if I wanted to convert my role groups to universal so that I can mail enable them I would then also have to change the groups the role itself is a member of as well. This means that I would be converting near all my security groups in AD to universal to support my proposed structure.
We are a single domain forest with about 1000 users and I would expect once all the groups for this are made to have 1000+. Functional level of the domain is 2008R2
I honestly don't know of the impact this might have in our active directory environment. Is making all the group universal really the only way to do this if I wanted to add my roles to distribution groups? The answer appears to be yes if I want them to be used for mail. I do want this so that way help desk users don't have to worry about what groups users need. They just need to know their "role".
The linked question answers why I cannot just have simple security groups but I want to know if my proposed structure, meaning that I will be converting near all my groups to universal, has any negative implications or is maybe considered a bad practice.
Comment: While it would add (double) the number of groups you would be creating, you might consider each role having two different groups: one global security group for all security related settings and access, and one universal distribution group for e-mail routing.
Comment: @ToddWilcox Yes. That could work. I would only need to double the amount of roles I have or at least the ones that would need to have associated mail groups. While some of the simplicity of a single role would be removed it would prevent changing 100's of groups. Something to ponder.
Answer: If you only have a single domain and all of your domain controllers are global catalogs, there isn't much impact.  Best practice is all domain controllers should be GC's.
In large forests with multiple domains, it can be advantageous to limit what groups are universal.  This is due to the member attribute of universal groups are replicated to the global catalog.  Consider a scenario with a large forest, multiple domains, a large number of universal groups with a high member count, all of those members would exist in the global catalog and be replicated to every domain controller/domain.  This replication and the resulting increase in the database size could be minimized by creating a global group in each domain, and having a single universal group where the members are the global groups.
This is less of an issue today than in the past. Prior to Windows Server 2003, all group members were replicated ever time the group membership was updated.  It wasn't unusual for large universal groups to be in a constant state of replication.  Now only the added/removed members are replicated.
If your AD environment and groups are very old (created prior to Windows 2003), it's possible they may not yet support the new Linked Value Replication capability to replicate only the added/removed members, but that can be fixed by removing/re-adding the members.  You can confirm this by running repadmin /showobjmeta for the group.  If a group member appears as "LEGACY" instead of "PRESENT", it should be fixed before converting to a universal group.
Comment: Adding to this answer, although not strictly related, if a user is member of too many groups through nesting and such, then Windows cannot correctly enumerate all those groups in the user token, causing permission issues. Since universal groups are replicated in all domains of the forest, this can add up quickly if not careful.
Answer: Another way to think it would be to create dynamic distribution group if you don't want to change your groups.

Dynamic distribution groups are mail-enabled Active Directory group
  objects that are created to expedite the mass sending of email
  messages and other information within a Microsoft Exchange
  organization.
Unlike regular distribution groups that contain a defined set of
  members, the membership list for dynamic distribution groups is
  calculated each time a message is sent to the group, based on the
  filters and conditions that you define. When an email message is sent
  to a dynamic distribution group, it's delivered to all recipients in
  the organization that match the criteria defined for that group.

That way if in AD you type for a User X an attribute, like, show there for the Office, then Exchange do the rest.. (image took from there)
You add the attribute;

You create the group;
<code>New-DynamicDistributionGroup -Name "Users in Example Office Name" -OrganizationalUnit "domain.net\users" -RecipientFilter { ((RecipientType -eq 'UserMailbox') –and (Office -eq 'Users in example office name')) }
</code>
Exchange do the rest, as long you keep your attribute up to date when a user quit for another job/office.


Como fazer update de campos com campos de outra tabela?

Question: Não estou conseguindo atualizar uma tabela com o select de outra.
Tenho uma tabela mdl_user que contém várias colunas e criei outra users_sg para copiar algumas colunas.
Copiei com
INSERT INTO
  users_sg (id, username, firstname, lastname)
SELECT
  id, username, firstname, lastname FROM mdl_user

Queria ficar atualizando, mas só consegui fazendo uma coluna e um usuário por vez:
UPDATE
  users_sg
SET
  users_sg.username = (SELECT username FROM mdl_user where id=3)
WHERE id=3

Tenho como atualizar os campos username, firstname e lastname de todos os usuários de uma vez?
Comment: A atualização será periódica, ou quando for alterada em uma tabela você quer que atualize automaticamente na outra?
Comment: @CelsoMarigoJr acho que é para fazer uma vez só.
Comment: @JorgeB. mas nesse caso o insert ja resolveria não!?
Comment: @CelsoMarigoJr pois talvez, está um bocado confuso. Fabio podes explicar?
Comment: A resposta ajudou?
Comment: Oi, precisarei rodar o comando pelo menos uma vez por dia para atualizar os que já existem.
Answer: Você pode fazer um UPDATE COM JOIN com as duas tabelas para atualizar as 3 colunas, user o where caso seja de um único registro que tenha que ser alterado.
UPDATE users_sg as sg
join mdl_user as user_ on user_.Id = sg.Id
SET sg.username = user_.username,
sg.firstname = user_.firstname,
sg.lastname = user_.lastname;
-- where user_.Id = 3 -- caso seja só de um unico registro mais com os 3 campos.

Para fazer isso automaticamente terá que usar um evento.
DELIMITER $
CREATE EVENT AtualizaTabela
    ON SCHEDULE EVERY 1 DAY
    STARTS NOW()
    DO BEGIN
            UPDATE users_sg as sg
            join mdl_user as user_ on user_.Id = sg.Id
            SET sg.username = user_.username,
            sg.firstname = user_.firstname,
            sg.lastname = user_.lastname;
    END
$ DELIMITER

Comment: Goku, sem palavras, muito obrigado...
Comment: Nesse exemplo Goku eu iria conseguir atualizar apenas 1 usuário por vez, correto? Eu precisaria atualizar todos de uma vez.
Comment: Sem o Where você atualizará todos Onde os ids são iguais
Comment: Entendi Goku, seria isso mesmo, porém tentei rodar esse comando agora  e ele da o seguinte erro:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from users_sg sg
join mdl_user user_
on user_.id = sg.id' at line 5
Comment: Ponto e vírgula no final dos comandos
Comment: Oi, coloquei o ponto e virgula, ficou assim:
UPDATE sg
SET sg.username = user_.username,
sg.firstname = user_.firstname,
sg.lastname = user_.lastname;
from users_sg sg;
join mdl_user user_;
on user_.Id = sg.Id;

Mas o erro foi: #1146 - Table 'baseteste.sg' doesn't exist;

Ele tenta criar uma outra tabela? Não era pra atualizar a users_sg?
Comment: Veja a edição,  você colocou  **;**  dentro do comando os **;** tem que ser no final de cada comando tipo `select * from tabela ;`
Comment: Goku, desculpe, mas não estou compreendendo, rodei no phpmyadmin dessa forma:

`UPDATE sg
SET sg.username = user_.username,
sg.firstname = user_.firstname,
sg.lastname = user_.lastname;
from users_sg sg;
join mdl_user user_;
on user_.id = sg.id;`

Veja que coloquei o ; no final de cada instrução (SET, from, join, on), o que fiz errado?
Comment: Não, o ponto e virgula tem que ser no final de tudo.. on user_.id = sg.id; <-- aqui.
Comment: Ah sim, eu tinha feito isso também. Mas o erro é:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from users_sg sg
join mdl_user user_
on user_.id = sg.id' at line 5
Comment: Vacilo meu, o mysql é diferente a sintaxe. editei a pergunta


Is this chord progression in A minor, or C major?

Question: I got in an argument with a buddy of mine over whether the chord progression I had written was in C Major, or A Minor. I've read up on what makes it one or the other, and I strongly feel it is C Major.
F(add9) Dm7 Am G Csus4 C Am G
https://clyp.it/snvtognv
Comment: While @Laurence is no doubt correct... I've got an opinion, and it is purely an opinion, and a lighthearted one at that, but it is not without reason!

I'm leaning toward Am, because the Am chord is expressed in the sequence in all it's minor 3rd glory whereas the C chord has no major 3rd interval, the Cmaj tonality is never expressed. How can Cmaj make a claim upon this harmony if it doesn't even show up to the fight? We are what we do :)
Answer: You give us neither the G7 > C or E7 > Am cadences that would answer your question conclusively.   Which way will you choose to end the piece of which this is an excerpt?  Neither you or you friend is wrong, or right!
Comment: Yep.  In addition, saying that a piece is "really" in C major or "really" in A minor is applying a dualism that is not necessarily useful.  In my field, medieval music, there's a common mode where a melody shifts having its emphasis between two notes a third apart- for instance, A and C, and you really cannot say that it's "in" A or "in" C.  The world doesn't always divide up into black and white.
Comment: I agree with you Laurence.  It could go in either direction and end up in either key from where the snippet is as shown.


Laravel prevent adding too many additional relations

Question: I have a model called Transfer and a model called Account, and two relations in my Transfer model:
public function outgoing()
{
    return $this->belongsTo(Account::class, 'outgoing_id');
}

public function incoming()
{
    return $this->belongsTo(Account::class, 'incoming_id');
}

This is used to transfer money from my bank account to my wallet for example, or from my credit card to my bank, and so on..
So an account can have a few types. For instance, bank can be an account type. Now if I want to grab all outgoing bank related transfers, by using the actual name bank, I have to use an additional relation, for example:
public function outgoingbank()
{
    return $this->belongsTo(Account::class, 'outgoing_id')->where('type', 'bank');
}

And to grab all outgoing transfers that are bank transfers, I can now use this:
auth()->user()->transfers()->has('outgoingbank')->get();

But my question is, is there a better way to do this with for example query scopes in my Account model, instead of adding an additional relation for each account type? Or perhaps an accessor in my Transfer model?
Comment: Might this be better as a `manyToMany` relationship? `outgoing_id`, `incoming_id`,  `type` for example? Would basically be a pivot between two records in the `accounts` table, and you could use `->withPivot(["type"]);` when querying the relationship. Hard to say; there's an argument for having `transfers` act as the pivot, and its own model.
Comment: Have to think about that one yes, since it's just really a `oneToMany` relationship, since every transfer can only have one `incoming_id` and one `outgoing_id`. But it might be a good solution to this problem, although I think it should be easily possible to solve it without having to go the "pivot way"
Answer: Fixed it using whereHas, which just popped into my brain all of a sudden:
$bank_transfers = auth()->user()->transfers()->with('outgoing')->whereHas('outgoing', function ($query){
        return $query->where('type', 'bank');
    })->get();


Closed-form of prime zeta values

Question: The prime zeta function is defined as
$$P(s)=\sum_{p\,\in\mathrm{\mathcal P}} \frac{1}{p^s},$$
where $\mathcal P$ is the set of prime numbers. It converges for all $\Re(s)>1$.
There is a related function defined as
$$\int_s^\infty P(t)\,dt = \sum_p \frac{1}{p^s\log p}.$$
Question. Are there any known closed-form value of $P(s)$ or $\int_s^\infty P(t)\,dt$?
Comment: No, there aren't any.
Comment: @Lucian actually you should make this an answer.It will be really an answer and so simple(I am not kidding)
Answer: There is no closed form for the prime zeta function, but it can be computed as
$$
P(s)=\sum_{n\ge1} \mu(n)\frac{\log\zeta(ns)}{n}
$$
which is more efficient than the standard form. In some sense these are adding in different directions, and a more efficient method can be obtained by adding in both directions and subtracting the overlap.

Closed-form of prime zeta values


Which is the preferred way to change field content before rendered?

Question: I'm working on an existing Drupal 7 module in order to make it work with Drupal 8. And for a peculiar aspect of its operation I'm currently a bit lost.
Th problem is that I must be able to make some changes in content of any text field, everywhere throughout all contents, before they're rendered.
In Drupal 7 I solved it behaving as a formatter, which I "grafted" before any existing formatter.
You can look at this SO post (I didn't know Drupal Answers at this time) to see more precisely how it worked.
After reading a lot of Drupal 8 documentation (which is currently quite messy) I can't yet realize which is the preferred way to achieve what I want.
I noticed some candidates such as the hook_entity_view_alter(), but also services and/or plugins, but keep totally undecided.
So I look for some advices pointing me to the right way.
Answer: hook_entity_view_alter() is for altering the render array of an entity, that is coming out of a view mode. It is not for a single field and changes in this hook would have no effect, when using the field alone, for example in a view. Using this hook would be the answer to the question Which is the preferred way to change the display (view mode) of an entity, before it is rendered?
(When using this hook, don't digg to deep, you can only change the render elements in the top level. Not the referenced objects, they are only to get information, not to change the rendering)
But the question is to change the rendering of a field, you asked "everywhere throughout all contents" For this the right solution is a field formatter, this can be used everywhere in drupal, whenever a field is rendered, no matter if you define a display mode (aka view mode) of an entity or use the field in Views.
To make the picture complete, you can change a field twice while displaying content, first in a field formatter and the second time, when the whole content is build and this build array can be altered in hook_entity_view_alter()
In drupal 8 field formatters are no longer hooks, they are now plugins.
https://api.drupal.org/api/drupal/core!modules!field!field.api.php/group/field_formatter/8
The documentation does not help to setup this plugin. I would copy an example from core and put my own code in it, for example:
core\modules\datetime\src\Plugin\Field\FieldFormatter

Comment: Thanks for these informations. I will take time to examine all that before accepting one of the 2 answers! Meantime, I upvote each of them :) For my try with `hook_entity_view_alter()`, I agree but had found a way to browse all its internal to detect fields in it. Sure it's quite complex...
Comment: But you only have the fields that are configured in the view mode (default is "full", but it can be any view mode, that is going through this hook). And if you use it in Views, you have to use it as content, if you configure it as fields, then this hook has no effect.
Comment: Not had time yet to deeply examine it, but yes: I noticed it should be an uncertain way. It's why I said it's a complex approach. Thanks for pointing it more.
Comment: I think, you should consider `hook_entity_view_alter()` as the answer to the question: _Which is the preferred way to change the display (view mode) of an entity, before it is rendered?_
Comment: Hmm... I don't understand anymore. Maybe it's due to the fact that I'm not easy with English, but I seem you first discouraged me from, then now recommend me to use `hook_entity_view_alter()`. What I'd noticed when trying to work with it was tthat I should iterate deeply `$build` in order to localize all fields, then exploring them (having diferent structures) and yet targetting different sub-places in them such as `text` or `value`... so it seems no easy to be sure I could _in advance_ inventory all cases I would face.
Comment: I put the comments in the answer, I hope now it is clearer
Comment: Yes I think I clearly distinguish the options now. And you targetted the important thing for me, when pointing my "everywhere throughout all contents" condition. So from your precisions I will choose to use a formatter. Thanks a lot for your help!
Answer: You can do the same in Drupal 8 as well. You can create a new formatter or can extend existing formatter. You need to create a field formatter plugin inside src/Plugin/Field/FieldFormatter directory.
/modules/random/src/Plugin/Field/FieldType/RandomDefaultFormatter.php

You can created a formatter for specific fields type types based on Annotations :
/**
 * Plugin implementation of the 'Random_default' formatter.
 *
 * @FieldFormatter(
 *   id = "Random_default",
 *   label = @Translation("Random text"),
 *   field_types = {
 *     "string"
 *   }
 * )
 */

You can extend any existing formatter or extend FormatterBase class:
class RandomDefaultFormatter extends FormatterBase {

The method you may want to use :
FormatterInterface::viewElements()

Related Links that can help :
https://www.drupal.org/node/2620966
http://realize.be/drupal-8-field-api-series-part-1-field-formatters
Comment: Thanks for these informations. I will take time to examine all that before accepting one of the 2 answers! Meantime, I upvote each of them :)
Comment: @cFreed Please see my updated answer. :)