projection of plane on a line

Question: In basic algebra by Nathan Jacobson, he said that a plane can be projected to a line. The text states that "if the plane is the domain and a line is co domain,then one maps any point P in the plane on the foot of the perpendicular from P to the given line."
I feel slight difficulty in imagining this. Can anyone help me with a diagram? ..
Comment: Can you explain for both dimensions two and three@mvw
Comment: What if the plane and the line intersect? How to define perpendicular at the point of intersection?
Comment: For what dimensions?
Answer: As far as I understand, what is meant is that the line lies within the plane.
An image would be something like this:

The line is a subset of the plane. All points on the perpendicular are mapped on the intersecting point. So $P,Q,R$ are mapped to $P'$, $S$ is mapped to $S'$ etc.
EDIT: This is very simplified for two dimensions. If I misunderstood, I'll delete the answer.
Comment: But sir Jacobson explains That as a orthogonal projection of plane on a line.If your answer is correct then there are infinite number of projection to a plane isn't it? So I need some clear answer .could you please explain
Comment: I don't think it means the line must lie within the plane.
Comment: Just had a quick look in the book. I believe OP is referring to the introduction of the book, where Jacobson explains what a map is. There it is used as a simple geometric example of how a map can look like, so I think in regard to the introduction of the book, this special case could suffice. In general, of course not.
Comment: Do you mean infinite number of projections from a the plane to any line on the plane?

projection of plane on a line


Qual a melhor ferramenta para realizar um integração de Javascript com MySQL?

Question: estou programando um sistema de ponto eletrônico web, estou no inicio ainda e meu conhecimento com programação web ainda está no começo. Inicialmente desenvolvi a parte de front-end por HTML e então comecei a pensar na parte do back-end.
Eu estava utilizando firebase como back-end (scripts direto no Javascript) mas acabei desistindo por alguns problemas e com pesquisas vi que não era a melhor maneira para ser feito. Eu tenho conhecimento em MySQL e pensei em utilizar como back-end e o Javascript como front-end, porém não encontrei nenhuma ferramenta que possa fazer isso para mim.
Pesquisei sobre Node.js mas pelo o que encontrei o inicio era desenvolvido por APIs. Então eu queria saber se tem alguma forma de utilizar o Javascript com mais alguma ferramenta para se comunicar com o banco de dados (MySQL) de forma que eu possa aproveitar as telas (forms) já feitas em HTML.
Answer: Primeiramente alguns conceitos precisam ser consolidados. O que você faz no frontend não influencia o que você faz no backend e vice-versa. Ambas as partes se comunicam através de um protocolo que ambos entendem e que não depende da implementação (é uma especificação em comum).
O frontend será responsável por gerar uma requisição HTTP e esperará receber uma resposta HTTP; o backend esperará receber uma requisição HTTP e irá gerar uma resposta HTTP. Ou seja, para o frontend não importa quem é o backend, desde que ele saiba analisar requisições HTTP; para o backend não importa quem é o frontend, desde que faça requisições HTTP e saiba lidar com as respostas geradas.
Portanto, a pergunta sobre o que usar no backend para não perder o que foi feito no frontend não faz sentido. Você pode utilizar Node JS, PHP, Python, C#, C, Java, o que preferir no backend e isso não interferirá nas decisões do frontend.
E não, Node JS não é utilizado apenas para APIs. Você pode servir páginas com ele sem problemas e se comunicar com o MySQL sem muita dificuldade. Existem muitos pacotes do Node que interagem com o MySQL.
Comment: Tudo bem então digamos que eu escolha o Node.js, eu vi alguns exemplos e a forma que eram feitos era via console.

Desenvolviam comandos de conexão com o banco e comandos de por exemplo criar uma tabela em um arquivo Javascript e mandava ele executar por meio de um comando no console (ex: node create-table.js). Eu preciso entender como realizar isso de forma "automática". O que eu estou pensando é: o usuário interagi com a pagina em um form, eu obtenho esses dados pelo Javascript e envio para o banco utilizando o node.js.

Eu quero entender como fazer isso corretamente e de forma segura.
Comment: @TiagoAbdalla Se entendeu bem a resposta, a pergunta que deve ser feita será "como processar uma requisição HTTP com Node?". Busque responder isso e sanará as suas dúvidas.
Answer: vou deixar aqui minha opinião como resposta, já que não é uma dúvida específica.
Resposta: Backend em PHP para trabalhar com MySQL
Vou te dar 4 motivos razoáveis:

O MySql têm uma ferramenta ótima para administrar o banco, feita em PHP, inclusive, que é https://www.phpmyadmin.net/
Há muita documentação e kilos de tutoriais abordando o relacionamento entre PHP e MySQL, então, é mais difícil você travar por não ter documentação ou onde recorrer quando têm dúvidas (ps.: pesquise aqui no StackFlow por exemplo pela tag PHP e outras possíveis l linguagens para ver a diferença de material)
PHP têm funções específicas para trabalhar com MySQL, por exemplo:
new mysqli("localhost","root","");
mysql_connect("localhost","root","");
mysql_query();
mysql_real_escape_string();
Comment: Como a resposta é baseada em opinião, deixei meu negativo por não concordar com ela. Não acho que os três itens listados justifiquem o uso de PHP no *backend*.
Comment: @AndersonCarlosWoss ok
Comment: @AndersonCarlosWoss, eu particularmente só usei o nodejs para notificações, gostei do seu link com os módulos, vou baixar depois, obrigado pela opinião
Comment: Apenas justificando melhor agora que tenho mais tempo: o item (1) cita o PHPMyAdmin, mas esse é apenas um cliente MySQL escrito em PHP, não interfere na decisão da linguagem de *backend*; pode, inclusive, utilizar outra linguagem no servidor e utilizar o PHPMyAdmin (embora eu não recomende isso); (2) ok, essa talvez seja uma justificativa, pois, de fato, PHP é uma das linguagens com curva de aprendizado bem pequena, mas no final acaba sendo mais prejudicada do que beneficiada com isso [...]
Comment: [...] dado que a grande parte do conteúdo sobre PHP na internet é escrito por quem não entende o que está escrevendo. Para um usuário novo tirar proveito é necessário ter um mínimo de conhecimento para entender o que deve ser filtrado e, por ser novo, isso é um obstáculo no aprendizado; (3) Possuir nativamente funções para se trabalhar com o MySQL é um facilitador, mas não chega a ser uma justificativa. Outras linguagens também possuem ou possuem pacotes muito bem consolidados na comunidade que fazem o serviço.
Comment: Fora isso, no item (3) você acabou misturando a API `mysqli` com a `mysql`; dada que a segunda é obsoleta e nem existe mais no PHP 7, acaba confundindo bastante.


How to update records based on condition?

Question: I have a table tbl_loyaltypoints in this table a column status = 2 has default value
Now I have following Query to get all records
select lp.order_id, DATEDIFF(CURDATE(), FROM_UNIXTIME(lp.created_at)) as createon,
       oi.deal_id, wo.returnWithin, lp.status
from tbl_loyaltypoints lp
inner join tbl_orders ord on lp.order_id = ord.id
inner join tbl_order_item oi on lp.order_id = oi.order_id
inner join tbl_workorders wo on oi.deal_id = wo.id
where ord.order_type = 1
order by lp.id DESC;

Output:
order_id  createon   deal_id  returnWithin status
1045        4           160     20          2
1044        4           160     20          2
1043        20          160     20          2

I want to update status tbl_loyaltypoints.status when createon==returnWithin.
Is there any way to do this using Mysql?
Answer: You can transform the select into a join:
update tbl_loyaltypoints lp inner join
       tbl_orders ord
       on lp.order_id = ord.id inner join
       tbl_order_item oi
       on lp.order_id = oi.order_id inner join
       tbl_workorders wo
       on oi.deal_id = wo.id
    set lp.status = ??
where ord.order_type = 1 and
      DATEDIFF(CURDATE(), FROM_UNIXTIME(lp.created_at)) = wo.returnWithin;

You don't specify what the new status is.  The ?? is a placeholder.
Comment: The new status will be status=1


Improvising over quartal voicings

Question: One particular jazz piano technique is to voice chords using quartal voicings. A quartal voicing is a chord built on fourths. For example, one might voice Cmin with the notes (in ascending order) F-B♭-E♭. Iconic examples of this technique can be found in Chick Corea's album Now He Sings, Now He Sobs.
Jazz pianists often use this technique to "go out." That is, they often use quartal voicings to depart from the written chords/harmonies. However, quartal voicings are ambiguous. For instance, the chord above (F-B♭-E♭) could also be a voicing for E♭Maj, E♭min, B♭sus, G7♯9, D♭Maj, D♭7, etc.
So, in these contexts, how are quartal voicings used to "go out" when improvising?
Answer: Typically you choose the quartal voicing after you have decided on what mode to improvise with. For example, if the chord is Cm, you are likely to choose the dorian mode. Then you have many choices for quartal voicings that are enharmonic to that mode. The example you've given, F-Bb-Eb, is widely used over Cm because it includes both the 3rd and the 7th, but there are many (seven) quartal voicings of this shape that come from C dorian:

C-F-Bb
D-G-C
Eb-A-D
F-Bb-Eb
G-C-F
A-D-G
Bb-Eb-A

(You might note that these are exactly the same as the voicings you get in Eb lydian or F mixolydian, which are equivalent modes to C dorian. But since the chord symbol was Cm, we know the bass note is C, so strictly speaking we should refer to this mode as C dorian.)
Practice making the quartal "claw" with your left hand and moving up and down the dorian mode enharmonically in this manner. If you play around with these voicings, you will notice that some feel especially dissonant, others somewhat hollow. That variance is what makes quartal comping interesting. As you comp, you can create little countermelodies by choosing voicings that match (or contrast) with what you're doing in your right hand.
This approach is discussed in detail in Mark Levine, The Jazz Piano Book.
Your question is about what notes you can use in your right hand, but I hope my answer makes it clear that the right hand and left hand are actually following a similar thought process when you use this approach to improvising. First, you look at the chord and choose a suitable mode. Then, you combine left hand voicings and right hand melodies to your liking according to that mode.
As for "going out," this term usually refers to when we break from the expected mode and play notes that normally "don't work." Quartal voicings (especially those that consist of perfect fourths only) are useful when playing out because they have such a symmetrical, strong structure. They sound OK even if you choose a quartal voicing with an arbitrary relationship to the tonic.
For example, after playing in C dorian over a Cm chord for a while, you may choose to create tension by playing in C# dorian for a phrase and then resolving back down. Your left hand voicing could move in parallel from F-Bb-Eb to F#-B-E for a moment, with the right hand following suit by playing melodies from the C# dorian scale, then you would resolve back on a C dorian voicing. It takes a lot of practice to learn to do this tastefully, of course, but Chick Corea makes for an excellent reference.
Comment: I really like this answer, +1! I tend to think of the approach described here and by Mark Levine as a great starting point/a good description of the basics. I've tried to elaborate on some things I've heard Chick doing and some of the ways I've thought about this which have helped me develop useful practice techniques. Please check out my answer too, and if you have any thoughts, I'd love to hear them.
Answer: There are a lot of ways to think about this, in part because quartal voicings are so ambiguous. It opens the door to many different scale and chord pairings.
Harmonize a Melody Note with a Quartal Voicing Outside the Key
This is something we can hear Chick Corea doing. Imagine we're improvising over a Cmin chord and we want to play a lick ending on E♭. Instead of harmonizing the E♭ with a traditional Cmin chord, we could play the quartal voicing D♭-G♭-B♮ in our left hand, along with the E♭ in our right hand. The left hand thus "goes out," but the entire voicing D♭-G♭-B♮-E♭ sounds good.
This is something valuable to practice. Pick a note at random (like E♭), and in the left hand, harmonize the note with different quartal voicings that sound good. (It's worth noting that quartal voicings can be inverted.) For example, some quartal voicings that I like under E♭ are:
 - D♭-G♭-B♮(-E♭)
 - C♮-F♮-B♭(-E♭)
 - B♭-E♭-A♭(-E♭)
 - G♭-B♮-E♮(-E♭)
Use Movement of the Quartal Chords to Go Out
Another way to go out is to let the left hand take the lead. That is, play a quartal voicing that fits in the designated key. Then move the quartal voicing up or down a half step, a minor third, or any other interval which introduces notes that are outside the designated key.
Once you have your quartal voicing, pick a scale that works with it. An easy way to do this is to build a pentatonic scale from any one of the three notes in the quartal chord. For the voicing F-B♭-E♭, the "best fitting" pentatonic scales are F minor pentatonic, B♭ minor pentatonic, and E♭ Major pentatonic.
Or instead of using a pentatonic scale, another quick trick is to use a triad pair.1 Build the triad pair from the top note of the quartal voicing (E♭Maj triad) and a whole step down (D♭Maj triad). So over the quartal voicing F-B♭-E♭, we could use the triads E♭Maj and D♭Maj. This is another great way to practice--pick a quartal voicing at random, and then improvise using the associated triad pairs.
Go Out the Traditional Way
Another more traditional approach is to simply pick a new scale that deviates from the given scale. For example, if you're playing over a Cmin chord, you could start playing in D♭min and then pull quartal voicings from the D♭min scale. Using this technique, common intervals to use are a half step, a minor third, and a tritone. So if you're improvising over a Cmin chord, you might switch to Bmin or D♭min, Amin or E♭min, or G♭min.
1. Generally, this technique involves building a six-note scale from two triads. Soloing built from this technique often use arpeggios that alternate between the two triads. There are good videos on YouTube about this technique.
Comment: I love these ideas, especially your first one, which sounds distinctly Chick. It might be worth pointing out that just as there are many pentatonic scales that can go with a given quartal voicing, there are also multiple triad pairs. If we interpret F-Bb-Eb as coming from Gb ionian, for example, we can even use the Db and B (Cb) triad pair--crunchy!
Comment: @MaxKapur, YES!! That's such a great suggestion. I hadn't thought systematically about that pair before. Thanks!
Answer: hope this helps

the Dm7 and G7 can be subbed for 4ths whose roots are based on a G major pentatonic scale. Cmaj7 can be subbed for 4ths built on a D major pentatonic scale.
For that outside sound, soloing using major pentatonics, for the Dm7/G7, will be based on the notes of the Fmyx scale.(F major pent, G major pent,A major pent, Bb major pent etc)and for the Cmaj7 based on the Cmyx scale.
by replacing/subbing a chord with a 4th you have obscured the original chord. each 4th chord infers multiple possible pentatonics.

Improvising over quartal voicings


direct limit presheaf being sheaf on Noetherian space

Question: Let $X$ be a noetherian topological space and $\{\mathcal{F}_i\}$ be a directed system. Assuming $U\mapsto \varinjlim \mathcal{F}_i(U)$ is a presheaf, I am trying to see that this is a sheaf on $X$.
Let $s,t\in \mathcal{G}(U)=\varinjlim \mathcal{F}_i(U)$. We have natural maps $\tau_i(U):\mathcal{F}_i(U)\rightarrow \mathcal{G}(U)$ for each $i$. Given $s,t\in \mathcal{G}(U)$ we have $s=\tau_i(x_i), t=\tau_j(x_j)$ for some $x_i\in \mathcal{F}_i(U)$ and $x_j\in \mathcal{F}_j(U)$.
Suppose we are given an open cover $\{U_l\}$ such that $s|_{U_l}=t|_{U_l}$ for all $l$. Then we have following commutative diagram

from this question. So, we have  $$s|_{U_l}=\Phi_l(s)=\Phi_l(\tau_i(U))(x_i)=\tau_i(U_l)(x_i|_{U_l}).$$
So, $s|_{U_l}=t|_{U_l}$ implies $$\tau_i(U_l)(x_i|_{U_l})=\tau_j(U_l)(s_j|_{U_l})\in \mathcal{G}(U_l).$$
This, means, for some $k$ we have $$f_{ik}(U_l)(x_i|_{U_l})=f_{jk}(U_l)(x_j|_{U_l})$$
which is same as saying
$$f_{ik}(U)(x_i)|_{U_l}=f_{jk}(U)(x_j)|_{U_l}.$$
So, $f_{ik}(U)(x_i),f_{jk}(U)(x_j)\in \mathcal{F}_k(U)$ such that
$$f_{ik}(U)(x_i)|_{U_l}=f_{jk}(U)(x_j)|_{U_l}.$$
As $\mathcal{F}_k$ is a sheaf, we have $$f_{ik}(U)(x_i)=f_{jk}(U)(x_j)$$
which is same as saying $s=t$.
I have not used that $X$ is Noetherian. What am I missing here
Comment: Come to think of it, I think that part does require $X$ to be Noetherian as well.  The issue would be that your $k$ depends on $l$, so you need to be able to restrict to a finite subcover before you can construct a single $k$ that works for all $l$.
Comment: What about gluing of sections?  I think that is where you would need to use that the space is Noetherian (and therefore every open subset is pseudo-compact) to get a single $i$ such that the sections come from $\mathcal{F}_i$ and agree on overlaps.
Comment: @DanielSchepler : I have yet to check that. I checked this and I do not see necessity of $X$ is Noetherian. I was surprised, so posted here. Are you sure identity axiom satisfies with out noetherian property?
Comment: @DanielSchepler : I understand where we have used that $X$ is noetherian. I will type it soon, post it and accept it. Credits goes toi you :) Thnak you :)
Comment: @DanielSchepler : I have added the justification as an answer. See that and let me know if that is correct.
Answer: Identity axiom : Let $U$ be an open subset of $X$, $\{U_l\}$ be an open cover of $X$.
  Let $s,t\in \mathcal{G}(U)=\varinjlim \mathcal{F}_i(U)$ be such that $s|_{U_l}=t|_{U_l}$ for each $l$.
  As $s\in \mathcal{G}(U)$ there exists $i\in I$ such that $s=\tau_i(U)(x_i)$ for some $x_i\in \mathcal{F}_i(U)$,
  similarly $t=\tau_j(x_j)$ for some $x_j\in \mathcal{F}_j(U)$.
To show that $s=t$ i.e., $\tau_i(U)(x_i)=\tau_j(U)(x_j)$ we show that there exists $k\in I$ with $i\leq k$ and
  $j\leq k$ such that $f_{ik}(U)(x_i)=f_{jk}(U)(x_j)$.

So, we have $s|_{U_l}=t_{U_l}$ implies $\tau_i(U_l)(x_i|_{U_l})=\tau_j(U_l)(x_j|_{U_l})$.
Fix $l$, we have $$\tau_i(U_l)(x_i|_{U_l})=\tau_j(U_l)(x_j|_{U_l})\in \mathcal{G}(U_l).$$
So, there exists $k$ (depending on $l$) such that
$$f_{ik}(U_l)(x_i|_{U_l})=f_{jk}(U_l)(x_j|_{U_l}).$$
Which is same as saying
$$f_{ik}(U)(x_i)|_{U_l}=f_{jk}(U)(x_j)|_{U_l}.$$
So, we have $f_{ik}(U)(x_i),f_{jk}(U)(x_j)\in \mathcal{F}_k(U)$ such that
$$f_{ik}(U)(x_i)|_{U_l}=f_{jk}(U)(x_j)|_{U_l}.$$
This $k$ may not work for all $l$ in the index set of the open cover $\{U_l\}$. As $X$ is noetherian,
$U$ is quasi compact, so, there exists a finite subcover $\{U_1,\cdots,U_n\}$ of $U$. For each $l\in \{1,2,\cdots,n\}$
there exists $k_l$ such that $$f_{i{k_l}}(U)(x_i)|_{U_l}=f_{j{k_l}}(U)(x_j)|_{U_l}.$$
Let $k\in I$ be such that $k_l\leq k$ for all $1\leq l\leq n$. For this $k$ and for all $l$
we have $$f_{ik}(U)(x_i)|_{U_l}=f_{jk}(U)(x_j)|_{U_l}.$$
As $\mathcal{F}_k$ is a sheaf,  we have $f_{ik}(U)(x_i)=f_{jk}(U)(x_j)$ i.e., $s=t$.
Gluing Axiom: Let $\{U_l\}$ be an open cover of $U$ and $s_l\in \mathcal{G}(U_l)$ be such that $s_l|_{U_l\cap U_m}=s_m|_{U_l\cap U_m}$.
As $X$ is noetherian, there exists a finite subcover say $\{U_1,\cdots,U_n\}$ for $U$.
For each $1\leq p\leq n$ there exists $x_{i_p}\in \mathcal{F}_{i_p}(U_p)$ such that
$\tau_{i_p}(U_p)(x_{i_p})=s_p$.
Fix $p,q\in \{1,2,\cdots,n\}$. We have $s_p|_{U_p\cap U_q}=s_q|_{U_p\cap U_q}$ i.e.,
$\tau_{i_p}(U_p)(x_{i_p})|_{U_p\cap U_q}=\tau_{i_q}(U_q)(x_{i_q})|_{U_p\cap U_q}$ i.e.,
$\tau_{i_p}(U_p\cap U_q)(x_{i_p}|_{U_p\cap U_q})=\tau_{i_q}(U_p\cap U_q)(x_{i_q}|_{U_p\cap U_q})$.

There exists $k_{p,q}$ with $i_p\leq k_{p,q}$ and $i_q\leq k_{p,q}$
such that $$f_{i_pk_{p,q}}(U_p\cap U_q)(x_{i_p}|_{U_p\cap U_q})=f_{i_qk_{p,q}}(U_p\cap U_q)(x_{i_q}|_{U_p\cap U_q}).$$
Which is same as saying
$$f_{i_pk_{p,q}}(U_p)(x_{i_p})|_{U_p\cap U_q}=f_{i_qk_{p,q}}(U_q)(x_{i_q})|_{U_p\cap U_q}.$$
So, we have $f_{i_pk_{p,q}}(U_p)(s_{i_p})\in \mathcal{F}_{k_{p,q}}(U_p)$ such that
$$f_{i_pk_{p,q}}(U_p)(x_{i_p})|_{U_p\cap U_q}=f_{i_qk_{p,q}}(U_q)(x_{i_q})|_{U_p\cap U_q}.$$
For $k\in I$ with $k_{p,q}\leq k$ for all $p, q$ we have
$$f_{i_pk}(U_p)(x_{i_p})|_{U_p\cap U_q}=f_{i_qk}(U_q)(x_{i_q})|_{U_p\cap U_q}.$$
So, there exists $s\in \mathcal{F}_k(U)$ such that
$$s|_{U_p}=f_{i_pk}(U_p)(x_{i_p}).$$
We have $$\tau_k(U)(s)|_{U_p}=\tau_k(U_p)(s|_{U_p})=\tau_k(U_p)f_{i_pk}(U_p)(x_{i_p})
=\tau_{i_p}(U_p)(x_{i_p})=s_p.$$

So, we have $\tau_k(U)(s)\in \mathcal{G}(U)$ is such that
$\tau_k(U)(s)|_{U_p}=s_p$ for all $1\leq p\leq n$. The same is true for any open subset in the open cover.
Thus, gluing axiom is satsfied.
So, $U\mapsto \mathcal{G}(U)=\varinjlim \mathcal{F}_i(U)$ gives a sheaf structure on noetherian space $X$.


Website directories with the same name but different capitalizations

Question: I've been asked to create a few different folders with the same name but with different capitalizations. The idea behind this is to allow for errors in capitalization when someone types in a specific url.  They want to do something like this:
www.website.com/youtube
www.website.com/Youtube
www.website.com/youTube
www.website.com/YouTube
I believe this is bad practice for many reasons, mainly that it seems confusing and unnecessary and any updates to these pages will have to be done 4 times over.  I've also noticed that VSCode won't let me create these directories from within the editor and my computer, a windows machine, won't let me do it from within the file manager either.
I've seen that this can create a problem with git as it won't recognize the files as separate files regardless of capitalization.
So really my questions are:
1.) Is there a way to do this?
2.) If so, is it a bad practice?
3.) If it's a bad practice, why?
I'd like to do it for them if possible, but not if there are some unforeseen consequences that I'm not aware of.  Any insight would be appreciated.
Thanks in advance.
edit: Just to be clear, we already have www.website.com/youtube but a few users have reported that their browser autocorrects the 'youtube' section of the url to have the Y or the T capitalized.  From what I see now, to accomplish this we must do something on the server side, of which my knowledge is limited.  All I know for sure is that it is a Linux server.
Comment: You should not have different files for the same purpose, 4x the chance of errors during changes. Depending on the system the site will run on you should just make the url's lowercase. For example look at https://stackoverflow.com/questions/2923658/convert-to-lowercase-in-a-mod-rewrite-rule
Comment: Thanks Rene.  For clarification we already have www.website.com/youtube, but some users claim that their browser automatically capitalizes one ofthe letters in the 'youtube' part of the URL.  This results in a 404.
Answer: To start with, the sane solution would be redirect those routes to the proper one, which is not an uncommon task. I don't know what your infrastructure looks like to the ease of doing so is unknown.

1.) Is there a way to do this?

Assuming that your server is Linux/BSD/Using anything but a Windows NTFS filesystem, yes. You can have one folder as source of truth and create symlinks. Or again, you could make the routes case-insensitive on whatever server you're using.

2.) If so, is it a bad practice?

Cloning the same information and making the same updates repeatedly is terrible practice. Making symlinks on the server is slightly less bad but still pretty bad practice, as that's cluttering up your directory tree with unnecessary nonsense.

3.) If it's a bad practice, why?

The idea isn't bad practice, you can make case-insensitive routes on most modern server configurations. The provided suggestions are pretty bad. But without knowing what your stack looks like, we can't provide much more information on how to do it.
Comment: Thanks for the insight Mark I appreciate it.  I know that our server is Linux but I don't have much more knowledge than that.  I figured I would just create 4 folders with the same name but varying capitalization and it would be done.  Apparently it is more complicated than that.


Banco de dados nao retornando nenhum valor

Question: Tenho o seguinte codigo:
 $sql="SELECT * FROM imoveis WHERE
          (suite LIKE '%".$suites."%'
           OR banheiro LIKE '%".$banheiro."%'
           OR quarto LIKE '%".$quarto."%'
           OR garagem LIKE '%".$garagens."%')

           AND (motivo LIKE '%".$tipo1."%'
           OR tipo LIKE '%".$tipo."%')
           AND cidade LIKE '%".$cidadd."%'
           AND estado LIKE '%".$local."%'
           AND preco >= '$valor'
           AND tamanho <= '$tamanho' ";

        $anunciarRadio=mysqli_query($conexao,$sql);

O que eu preciso é que retorne a as casas na mesma cidadade da minha variavel com determinado com os valores de quantidade de garagem, suites, banheiros, quartos aproximados, com o valor de preço inferior variavel $valor, e tamanho superior a variavel $tamanho.
O que estou fazendo de errado??
Ao colocar os valores exatamente iguais aos gravados no banco de dados ele nao me retorna nada...
sera que é erro de  sintaxe ou logica ?
Quando coloco tudo para or  ele retorna porem vem todos.
Ou seja preciso de um pente fino, porem nem tanto, preciso nao priorizar alguns campos como quartos, banheiros, garagem,suite e o restante priorizar como sendo exato...
Answer: Isso aqui
       AND preco >= '$valor'
       AND tamanho <= '$tamanho' ";

não seria assim?
       AND preco >= '" .$valor. "'
       AND tamanho <= '" .$tamanho. "'";

Corrigindo seu select:
Sobre o BETWEEN: Voce pode ver melhor aqui aqui
     $sql="SELECT * FROM imoveis WHERE
      (suite BETWEEN ".($suites - 2)." AND ".($suites + 2)."
       OR banheiro BETWEEN ".($banheiro - 2)." AND ".($banheiro + 2)."
       OR quarto BETWEEN ".($quarto - 2)." AND ".($quarto + 2)."
       OR garagem BETWEEN ".($garagens - 2)." AND ".($garagens + 2).")

       AND (motivo LIKE '%".$tipo1."%'
       OR tipo LIKE '%".$tipo."%')
       AND cidade LIKE '%".$cidadd."%'
       AND estado LIKE '%".$local."%'
       AND preco >= '".$valor."'
       AND tamanho <= '".$tamanho."' ";

Pelo que entendi vc quer que os numero de garagem, suítes, banheiros, quartos sejam próximos do que o usuário digitou logo isso serve para fazer isso:
// supon que suites sejam 4
suite BETWEEN ".($suites - 2)." AND ".($suites + 2)."
// Nessa parte abaixo eu diminuo 2 para que ele procure apartir de 2
".($suites - 2)."
// ate 6. aqui eu aumento 2 para o valor ser 6
".($suites + 2)."

Resumindo o código irá retorna se o numero do imóvel seja entre 2 e 6.
Espero que tenha ficado claro e ajudado você agora.
ps: não manjo de php então não tenho certeza que .($suites - 2). seja operação correta, mas acho que sim por nas outra linguagens são assim um ,abraço. :D
Comment: Atualizei minha resposta veja se agora pode ser de ajuda.
Comment: fiz essa correção e continua nao vindo nada., acredito que seja referente ao AND e OR @.@ estava estudando o uso deles mas nao entendi corretamente, como usar da forma descrita acima com aspas podendo deixar alguns campos como nao tao necessario e outros como sendo obrigatoriamente igua, porem podendo ter erros gramaticais
Comment: Bom vou tentar passa pra ti de forma rápida, AND vc usa quando quer que o valor retornado seja aquilo que a variável de comparação contenha se não contiver não irá retornar, ou seja se no seu código se o 'imovel' que vc esta procurando no select tiver todas as variáveis iguais a da comparação ou no caso do 'AND var like %algo%' o valor 'var' estiver contido dentro de 'algo' ele irá retornar oimovel, agora se alguma variavel da comparação AND retornar false, ou seja não contiver, o seu select não irá retornar nada.
Comment: Veja que não falei do OR pois o OR é mais simples se ele achar o valor ele retorna porém se ele não encontrar o valor correspondente ele não irá retornar se ele estiver comparando sozinho.
Exemplo "select * from imoveis where 1 = 0 OR nome like '%nameImovel%' "
Aqui o where 1=0 é so para sempre ser 0(false) ou seja se o OR for 1 ele retornar e for 0 ele não retorna nada.
No caso do se select se apenas o OR for verdadeiro ele não irá retornar e se apenas o OR for false e os AND forem verdadeiros ele irá retornar
Comment: Resumindo AND so retornará quando as todas as condições forem Verdadeiras.
OR retornará quando alguma das condições forem atendidas.
Comment: Funcionou obrigado.. era isso que estava em duvida.. perfeito parabéns obrigado.
Comment: que isso disponha, fico feliz em poder ajudar :D
Answer: essa variável é assim mesmo?
AND cidade LIKE '%".$cidadd."%'

e o exemplo do amigo @Will pode ser assim tb.
AND preco >= '{$valor}'
AND tamanho <= '{$tamanho}'";

Comment: opa, a variavel é assim mesmo, acredito que seja referente ao AND e OR @.@  estava estudando o uso deles mas nao entendi corretamente, como usar da forma descrita acima com aspas podendo deixar alguns campos como nao tao necessario e outros como sendo obrigatoriamente igua, porem podendo ter erros gramaticais.


Como ter duas versões do php no mesmo servidor Apache?

Question: Tenho um servidor Apache/2.4.10 (Ubuntu) rodando um site em php 5.5. Porém eu estou criando um novo site e ele precisa do php 5.6. Tem como ter duas versões do php instalado no meu servidor e usar cada um em pastas diferentes?
Comment: Curiosidade: existe algum problema de usar a 5.6 em ambos? Da 5.5 para a 5.6 não deve ter mudado tanto. Aliás, por que ainda a versão 5 e não a 7, que é a mais recente?
Comment: Basicamente o servidor comporta outros sistemas, como por exemplo um sistema de câmeras e eu não tenho contato com o desenvolvedor. Mudar a versão do php pode fzr com que tudo que já está no servidor pare de funcionar!
Comment: Concordo que caso as versões sejam muito próximas não terá diferença, mas caso sejam estas muito distantes poderá interferir no funcionamento.
Answer: Exemplo no Linux Mint 18
Asumindo que o Apache está instalado, criado o host virtual para os dois projetos e adicionafo os necessarios php PPAs. Vamos supor o projeto site56.local em php5.6 e o projeto site70.local no php7.0.
Instale php5.6-fpm e php7.0fpm com o seguinte comando:
sudo apt-get install php7.0-fpm

Crie dois arquivos em /usr/lib/cgi-bin/ e salve
sudo nano /usr/lib/cgi-bin/php56-fcgi

sudo nano /usr/lib/cgi-bin/php70-fcgi

Abra o php56 conf arquivo "/etc/apache2/conf-available/php5.6-fpm.conf" adicione as seguintes configurações e salve.
<IfModule mod_fastcgi.c> AddHandler php56-fcgi .php Action php56-fcgi /php56-fcgi Alias /php56-fcgi /usr/lib/cgi-bin/php56-fcgi -socket /var/run/php/php5.6-fpm.sock -pass-header Authorization Action php70-fcgi /php70-fcgi Alias /php70-fcgi /usr/lib/cgi-bin/php70-fcgi -socket /var/run/php/php7.0-fpm.sock -pass-header Authorization </IfModule> <Directory /usr/lib/cgi-bin> Require all granted </Directory>

Agora habilite a nova configuração do Apache.
sudo a2enconf php5.6-fpm

Se você instalou o php5.6 e php5.7, veriique se você desativou os dois e reiniciou o Apache.
sudo a2dismod php5.6 php7.0

sudo systemctl restart apache2

Crie um arquivo .htacces no projeto que deve estar no php7.0 e adicione o seguinte Handler.
AddHandler php70-fcgi .php

Agora crie um arquivo phpinfo no projeto e veja se funcionou.
Nota: Verifique se o htaccess está habilitado em seu apache2.conf ou httpd.conf.
site56:

site70:


Como selecionar texto de campo TEdit no Delphi 10

Question: Estou com um problema bem básico e não descubro a causa... Preciso que o texto de dentro de um TEdit fique inteiro selecionado quando o campo receber foco. Nos tempos de Delphi 7 com VCL eu fazia apenas TEdit(Sender).SelLength := Length(TEdit(Sender).Text) no evento OnEnter. Agora com Delphi 10.2 e FireMonkey já tentei de várias maneiras diferentes, mas não funciona.
Exemplo:
procedure TfPrincipal.Edit1Enter(Sender: TObject);
begin
   TEdit(Sender).SetFocus;
   TEdit(Sender).SelStart  := 0; // Ja tentei mudar este valor
   TEdit(Sender).SelLength := Length(TEdit(Sender).Text); // Ja tentei mudar este valor também
end;

No Firemonkey funciona diferente?
Comment: Fiz o teste e realmente não funciona. veja a resposta.
Answer: Outra coisa definir para SelLength um valor maior do que o número de caracteres de SelStart para resulta na seleção de todos os caracteres de SelStart até o final do texto.
TEdit(Sender).SetFocus ;
TEdit(Sender).SelStart  : = 0;
TEdit(Sender).SelLength := Length(TEdit(Sender).Text)+1;

Comment: Fiz os testes no Delphi 10.1 Berlin e funcionou perfeito. Adicione um +1 no tamanho da Length.
Comment: outra coisa você pode retirar o `TEdit(Sender).SetFocus;` já que na entrada  do controle o mesmo já está com o foco.
Comment: Eduardo, você fez seus testes usando o evento `OnClick` ou `OnEnter` do TEdit? Pois no evento `OnEnter`, que é o evento que eu estou usando, não funciona. Então estou adaptando um pouquinho a mais de código e usando o `OnClick`. Já a propriedade `HideSelection` eu não encontrei no Delphi 10.2 Tokyo.
Comment: os dois  com o `OnClick` eu coloquei o `SetFocus` e no `OnEnter` sem o `SetFocus`.
Comment: Sei lá... muito estranho o que está ocorrendo aqui. Não funciona nem no Windows nem no Android com evento `OnEnter` (e não existe a propriedade HideSelection). Mas obrigado pela atenção
Comment: HideSelection eu me confundi ... é para vlc vou editar a resposta
Comment: Acabei de fazer o teste no android com o Botão é seleciona normal tanto no windows como no android  mais ao entra no campo só funciona no windows vou verificar
Comment: Acabei de testar com um evento Edit1Tap tanto o Edit1Enter eles funcionam o problema que percebi é que quando ele entra no Controle o foco vai embora provavelmente por conta do teclado virtual que entra na frente.
Comment: Essa parada é estranha... Mas não se preocupe. Vou usar o evento `OnClick`, adaptando algumas coisas. Não gosto de fazer isso, mas não dá para ficar gastando muita energia em determinadas coisas também. Obrigado!
Comment: marca como respontado se te ajudou...
Comment: Ah sim, para VCL funciona tudo OK.
Comment: só posso marcar como resposta válida se tiver sido resolvido o problema tal como foi proposto, que neste caso é no Firemonkey com evento `OnEnter` do TEdit. Sua dica não se aplica a este caso e tive que contornar o problema usando o evento `OnClick` como comentei antes. Mas obrigado!


Add the Brave's homepage to Firefox

Question: I installed Brave for fun, and I am impressed by Brave's homepage which i want to add in to my Firefox's homepage with some changes.

As you see above the homepage of Brave has time on right-up corner which I want it to be in center and the background images should be custom.
I was not able to even find the homepage's HTML and JavaScript so that I can just change them.
Answer: In Preferences -> Home, you can use a custom URL and point to a local file where you store the homepage you want :
Comment: You can save it with `File -> Save Page As...`, but you cannot reuse it easily on Firefox because it uses Javascript files specific to Chrome.
Comment: CSS is embedded in the HTML file. JavaScript is embedded in the Brave browser, you can access it with URL such as `chrome://resources/js/util.js`, but this won't work ,as is, in Firefox.
Comment: Thanks man but i have a last doubt how can i get homepage filesof brave browser??
Comment: well by using `File -> Save Page As...` u only get html what about css and js
Comment: thanks i will just go through the code and check out if can do it or not

Add the Brave's homepage to Firefox


How can I merge a content type's fields and settings from dev to staging?

Question: I have an existing content type on staging. On dev we've added a ton of new fields and display and form setting changes, etc.
It's not practical to go through the config files and find all of the many dozens if not hundreds of interconnected config files related to the content types, its fields and its settings.
So I heard Features is the way to go (even though I thought config sync in D8 was supposed to make Features not needed anymore).
So I've created my Feature. Keeping it simple I just checked the single content type. Saved my feature module and moved it to staging.
When I try to enable to the module I get a screen full of "unable to install" because the configuration already exists errors. Ugg.
So I read that I should remove the configurations. But this removes content and/or associated configurations like vocabularies.
Surely there must be a practical way to merge a content type from dev to staging?
Comment: Okay, so first: Get the database from live to stage, dev and local. Now export config on local first to get a clean working state. This will be the current config from live. Deploy it. Now start to add fields and settings as you wish on your local page and when you are done, export config, deploy to all other environments.
Comment: What do you mean by merge? What's wrong with exporting the config, pushing it and importing the config on stage then?
Comment: That's what I thought would work but it's not. By 'merge' I mean update an existing content type. The type exists already on staging with content in it. On dev we've added new fields and displays. But when using Features to import the content we get tons of 'config already exists' errors.
Comment: Yes, this is CMI and the practical way the OP is looking for. Features is something different. See https://drupal.stackexchange.com/questions/230270/features-and-cmi-together
Comment: @quantumized updated the answer for your use case.
Comment: You really should re-consider your workflow. Config changes should be strictly one-way upstream only. There is no easy way to merge, it is not impossible, but merging always is a PITA. CM is great, simple and stable - if you work in one direction dev => stage => live only.
Answer: To fix the issue include config in optional directory instead of install directory in your features module. It will then only install the config which are not present in the new site. Which will solve your issue.

When I try to enable to the module I get a screen full of "unable to install" because the configuration already exists errors.

Ok, I misread your question. To update existing config as well you need to do partial cim.
Copy the feature configs into a different directory named feature-config-sync (can be anything other than standard folder names) in default site config directory. And execute the below command. It will import new config and update existing configs if needed. Limitation is it wont delete any configs.

drush cim --partial --source=../path/to/config/feature-config-sync

IIRC you can even map the module install/optional config directory as source during partial import.
Once your import is done you can delete the feature-config-sync directory.
Comment: This will just skip processing any config that already exists, it won't update the existing config to the new config.
Comment: Right. I just found that out. If I rename install to optional then the module installs but the content type is not updated at all.
Comment: I thought renaming install to optional would work as the Feature now enables but when I checked the content type it does not get updated at all.
Comment: @quantumized has the updated solution worked?
Comment: I finally got it to work but I'm not exactly sure how. After many attempts of retrying the Features module finally installed and merged the changes to the content type.


Creating an RGB CVOpenGLESTexture in iOS

Question: I am trying to create a 3-channel CVOpenGLESTexture in iOS.
I can successfully create a single-channel texture by specifying kCVPixelFormatType_OneComponent8 in CVPixelBufferCreate() and GL_LUMINANCE for both format and internalFormat in CVOpenGLESTextureCacheCreateTextureFromImage().
Similarly, I can successfully create a 4-channel RGBA texture by specifying kCVPixelFormatType_32BGRA in CVPixelBufferCreate() and GL_RGBA for both format and internalFormat in CVOpenGLESTextureCacheCreateTextureFromImage().
I need to create 3-channel, 24-bit, RGB (or BGR) texture with accessible pixels.
I cannot seem to find the correct parameters (or combination thereof) to CVPixelBufferCreate() and CVOpenGLESTextureCacheCreateTextureFromImage() that will not cause either of them to fail.
Additional Info
The supported FOURCC format types reported by CVPixelFormatDescriptionArrayCreateWithAllPixelFormatTypes() on my device:
32, 24, 16, L565, 5551, L555, 2vuy, 2vuf, yuvs, yuvf, 40, L008, L010, 2C08, r408, v408, y408, y416, BGRA, b64a, b48r, b32a, b16g, R10k, v308, v216, v210, v410, r4fl, grb4, rgg4, bgg4, gbr4, 420v, 420f, 411v, 411f, 422v, 422f, 444v, 444f, y420, f420, a2vy, L00h, L00f, 2C0h, 2C0f, RGhA, RGfA, w30r, w40a, w40m, x420, x422, x444, x44p, xf20, xf22, xf44, xf4p, x22p, xf2p, b3a8.
Interestingly, some of these values are not defined in CVPixelBuffer.h.
When I pass kCVPixelFormatType_24RGB (24 == 0x18) to CVPixelBufferCreate() it succeeds, but then CVOpenGLESTextureCacheCreateTextureFromImage() fails with error code -6683:kCVReturnPixelBufferNotOpenGLCompatible.
Answer: Answering myself, though I will be happy to be proved wrong and shown how to do this.
As I show here (answering myself yet again) it is possible to list all the fourCC buffer formats supported on the device, and a bunch of format attributes associated with each such fourCC format.
The flags pertinent to this question are:

kCVPixelFormatOpenGLESCompatibility
kCVPixelFormatContainsAlpha : Should be false;
kCVPixelFormatContainsRGB : Note: supported only from __IPHONE_8_0, but not strictly necessary;
Using the debugger, I found another helpful key: CFSTR("IOSurfaceOpenGLESTextureCompatibility") which will verify that the OpenGL ES texture supports direct pixel access with no need for (the slower) glReadPixels() and glTexImage2D().

Unfortunately, using these flags, it seems that there is currently no such RGB/BGR supported format.


how to log sql queries executed by sequlize ORM?

Question: I am setting up a project with express js, sequelize ORM and mysql database. is there a way i can also log or set up something , so that I can log/dump sql queries constructed/executed by sequlize ORM?
index.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize({

  host: 'localhost'
  dialect: 'mysql'
  ..
});

Answer: const Sequelize = require('sequelize')

const sequelize = new Sequelize(database, user, password, {
  dialect: 'mysql',
  logging: console.log
})

Comment: Another way , you can make logging: true as well, it will work same.
`logging: true`


Positive definite matrices: minor criteria vs quadratic form

Question: Let $$A=\begin{bmatrix}
1 & -8\\
1 & 1
\end{bmatrix}$$
Clearly $\Delta _1>0$ and $\Delta _2 >0$. Hence, we can say that $A$ is positive definite .
But there are $X=\begin{pmatrix}
x & y
\end{pmatrix}\neq 0 $ such that $X^T \cdot AX <0$
EX : $X=\begin{pmatrix}
1 & 1
\end{pmatrix}$
Does this contradict the fact that $A$ is positive definite according to minor criteria?
Comment: Your $A$ is not symmetric..
Answer: Of course, Calculon is right. More precisely, we can give the following definition: $A\in M_n(\mathbb{R})$ is $\geq 0$ IFF for every vector $x$, $x^TAx\geq 0$. This is equivalent to $A+A^T$ is symmetric $\geq 0$.
On the other hand, the test using the principal minors is valid only when  the considered matrix is symmetric. Here, $\det(A+A^T)<0$...


Merge SQL Rows in Subquery

Question: I am trying to work with two tables on BigQuery. From table1 I want to find the accession ID of all records that are "World", and then from each of those accession numbers I want to create a column with every name in a separate row. Unfortunately, when I run this:
Select name
From `table2`
Where acc IN (Select acc
                From `table1`
                WHERE source = 'World')

Instead of getting something like this:

Acc1
Acc2
Acc3

Jeff
Jeff
Ted

Chris
Ted
Blake

Rob
Jack

Jack

I get something more like this:

row
name

1
Jeff

2
Chris

3
Rob

4
Jack

5
Jeff

6
Jack

7
Ted

8
Blake

Ultimately, I am hoping to download the data and somehow use python or something to take each name and count the number of times it shows up with each other name at a given accession number, and furthermore measure the degree to which each pairing is also found with third names in any given column, i.e. the degree to which they share a cohort. So I need to preserve the groupings which exist with each accession number, but I am struggling to find info on how one might do this.
Could anybody point me in the right direct for this, or otherwise is the way I am going about this wise if that is my end goal?
Thanks!
Comment: What does your data look like?  Do you know the list of "accession numbers" in the final result?
Comment: you need to use pivot() - https://hoffa.medium.com/easy-pivot-in-bigquery-one-step-5a1f13c6c710
Comment: no way to answer this question without sample of input and expected output! please provide [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)
Answer: This is not a direct answer to the question you asked.  In general, it is easier to handle multiple rows rather than multiple columns.
So, I would recommend that you put each acc value in a separate row and then list the names as an array:
select t2.acc, array_agg(t2.name order by t2.name) as names
from `table2` t2
where t2.acc in (Select t1.acc
                 From `table1` t1
                 where t1.source = 'World'
                )
group by t2.acc;

Otherwise, you are going to have a challenge just naming the columns in your result set.

Merge SQL Rows in Subquery


Como somar todos os elementos de um ng-repeat?

Question: Exemplo: Tenho um ng-repeat qualquer, que repete cada um um número. Como faço para armazenar uma variável que seja igual à soma deste número de cada repeat?
Código AngularJS:

ngular.module('meumodulo', [])

.controller('mercadoria', function($rootScope, $http) {

    var ctrl = this;
    $rootScope.listademercadoria = [];

    $rootScope.mercadoria0 = {
        id: 'id1',
        setor: 'setor1',
        foto: 'foto1',
        descr: 'descr1',
        de: de1,
        por: por1,
        mercadoria: '0',
        quantidade: 1,
        total: ''
    }

    $rootScope.listademercadoria.push($rootScope.mercadoria0);

    $rootScope.mercadoria1 = {
        id: 'id2',
        setor: 'setor2',
        foto: 'foto2',
        descr: 'descr2',
        de: 'de2',
        por: 'por2',
        mercadoria: '1',
        quantidade: 1,
        total: ''
    }
    $rootScope.listademercadoria.push($rootScope.mercadoria1);

    $rootScope.showPanel = true;
    $rootScope.listademercadoria.push($rootScope.mercadoria1);

    $rootScope.remover = function(b) {

        {
            $rootScope.showPanel = !$rootScope.showPanel;
        }
    }

});

Código HTML:

...

  Total dos produtos: {{listademercadoria[0]['total']}}

...

Estes códigos mostram apenas o valor da variável "total" dentro de $rootScope.mercadoria0.
É preciso que mostre a soma das variáveis "total" de todos os repeats que houverem, mesmo que seja inserido no futuro mais mercadorias, como mercadoria2, mercadoria3, mecadoria4, então o total teria que se alterar conforme o número de mercadorias inseridas.
Já pesquisei muito, mas em tudo o que vejo, parece que seria necessário inserir, a cada mercadoria nova, uma nova parcela na soma. Ex: {{listademercadoria[0]['total']}}+{{listademercadoria[1]['total']}}+{{listademercadoria[2]['total']}} etc...
Answer: Você pode criar uma função que retorna a soma executada no controller. Note que fiz isso no exemplo abaixo com a função somar:

angular
  .module('meumodulo',[])
  .controller('MercadoriaCarrinhoController', MercadoriaCarrinhoController);

MercadoriaCarrinhoController.$inject = [];

function MercadoriaCarrinhoController(){
  var vm = this;

  vm.somar = _somar;

  _iniciar();

  function _iniciar() {
    vm.listaDoCarrinho = [];

    vm.listaDoCarrinho.push({
      id: 'id',
      setor: 'setor',
      foto: 'foto',
      descr: 'descr',
      de: 'de',
      por: 'por',
      mercadoria: '0',
      quantidade: 0,
      total: 5,
      boto: -1
    });

    vm.listaDoCarrinho.push({
      id: 'id2',
      setor: 'setor2',
      foto: 'foto2',
      descr: 'descr2',
      de: 'de2',
      por: 'por2',
      mercadoria: '1',
      quantidade: 1,
      total: 0
    });
  }

  function _somar() {
    var tamanho = vm.listaDoCarrinho.length;
    var soma = 0;

    for (var indice = 0; indice < tamanho; indice++) {
      soma = soma + vm.listaDoCarrinho[indice].total;
    }

    return soma;
  }
}

    Total: {{vm.somar()}}

Observação: O ideal é que sua propriedade total seja declarada sem aspas, afinal é um número e não uma String.
Answer: Guilherme,
Não é recomendado utilizar $rootScope, pois ele é uma variável global. Utilize somente quando necessário. (e.g. usar um $rootScope que salva a sua página anterior e sua atual, para criar um botão de "Voltar" inteligente)
Utilize no lugar o $scope.
Eu fiz da forma que faria e montei um Plunker para facilitar a visualização do seu problema: Clique Aqui
Básicamente criar uma variável totalSum e atribui ela em um laço loop For
controller.js
$scope.totalSum = 0

for(var i = 0 ; i < $rootScope.listademercadoria.length; i++){
       $scope.totalSum = $scope.totalSum +
       $rootScope.listademercadoria[i].quantidade
}

index.html
Total dos produtos: {{totalSum}}


Why do we need Bootstrapping?

Question: I'm currently reading Larry Wasserman's "All of Statistics" and puzzled by something he wrote in the chapter about estimating statistical functions of nonparametric models.
He wrote

"Sometimes we can find the estimated standard error of a statistical
  function by doing some calculations. However in other cases it's not
  obvious how to estimate the standard error".

I'd like to point out that in the next chapter he talks about bootstrap to address this issue, but since I don't really understand this statement I don't fully get the incentive behind Bootstrapping?
What example is there for when it's not obvious how to estimate the standard error?
All the examples I've seen so far have been "obvious" such as $X_1,...X_n ~Ber(p)$ then $ \hat{se}(\hat{p}_n )=\sqrt{\hat{p}\cdot(1-\hat{p})/n}$
Comment: I am finding a lot of examples in a [site search for other answers that propose a bootstrap](http://stats.stackexchange.com/search?tab=votes&q=[bootstrap]%20is%3aanswer%20standard%20error). They include http://stats.stackexchange.com/questions/14213, http://stats.stackexchange.com/questions/63979, http://stats.stackexchange.com/questions/25218, and plenty more.
Answer: Two answers.

What's the standard error of the ratio of two means? What's the standard error of the median? What's the standard error of any complex statistic? Maybe there's a closed form equation, but it's possible that no one has worked it out yet.
In order to use the formula for (say) the standard error of the mean, we must make some assumptions. If those assumptions are violated, we can't necessarily use the method. As @Whuber points out in the comments, bootstrapping allows us to relax some of these assumptions and hence might provide more appropriate standard errors (although it may also make additional assumptions).
Comment: Thank you for the edits. But isn't it the case that bootstrapping typically makes *different assumptions*, rather than actually *relaxing* some? For instance, the assumptions needed to estimate an SE of a sample mean are that the data are iid and the underlying distribution has a finite variance. The bootstrap actually has to *add* assumptions in this case: it doesn't work unless the sample size is "sufficiently large." Although this might seem like quibbling over technicalities, what I am trying to address is the big picture: bootstrapping is neither a panacea nor is it always applicable.
Comment: @JeremyMiles the bootstrap is not free of assumptions. You need to verify that the distribution is pivotal for most bootstrap error calculations which can often be more complicated than obtaining a consistent estimator for a standard error. Additionally, the ratio of means has a very easy error approximation obtained from the δ-method. So I don't think that example defies the OP's point.
Comment: Answer 1 is fine, but answer 2 seems to beg the question, because bootstrapping makes assumptions, too.  I suppose the point might be that it typically makes *different* assumptions than other popular procedures, but that's just my guess about what you're trying to say and I could be mistaken.
Comment: @Whuber - thanks, I've added a bit of clarification.
Answer: An example might help to illustrate. Suppose, in a causal modeling framework, you're interested in determining whether the relation between $X$ (an exposure of interest) an $Y$ (an outcome of interest) is mediated by a variable $W$. This means that in the two regression models:
$$\begin{eqnarray}
E[Y|X] &=& \beta_0 + \beta_1 X \\
E[Y|X, W] &=& \gamma_0 + \gamma_1 X + \gamma_2 W \\
\end{eqnarray}$$
The effect $\beta_1$ is different than the effect $\gamma_1$.
As an example, consider the relationship between smoking and cardiovascular (CV) risk. Smoking obviously increases CV risk (for events like heart attack and stroke) by causing veins to become brittle and calcified. However, smoking is also an appetite suppressant. So we would be curious whether the estimated relationship between smoking and CV risk is mediated by BMI, which independently is a risk factor for CV risk. Here $Y$ could be a binary event (myocardial or neurological infarction) in a logistic regression model or a continuous variable like coronary arterial calcification (CAC), left ventricular ejection fraction (LVEF), or left ventricular mass (LVM).
We would fit two models 1: adjusting for smoking and the outcome along with other confounders like age, sex, income, and family history of heart disease then 2: all the previous covariates as well as body mass index. The difference in the smoking effect between models 1 and 2 is where we base our inference.
We are interested in testing the hypotheses
$$\begin{eqnarray}
\mathcal{H} &:& \beta_1 = \gamma_1\\
\mathcal{K} &:& \beta_1 \ne \gamma_1\\
\end{eqnarray}$$
One possible effect measurement could be: $T = \beta_1 - \gamma_1$ or $S = \beta_1 / \gamma_1$ or any number of measurements. You can use the usual estimators for $T$ and $S$. The standard error of these estimators is very complicated to derive. Bootstrapping the distribution of them, however, is a commonly applied technique, and it is easy to calculate the $p$-value directly from that.
Comment: I think I understand where you're going with this answer, but I am puzzled by the details. Did you intend to put hats over the parameters in your descriptions of $T$ and $S$? The text sounds like these should be properties of a model rather than estimators. What sense does it make to mix properties of two *different* models like this?  If you really did mean hats, then $T$ and $S$ are statistics, apparently to be used as estimators, but what are they intended to estimate?
Comment: @whuber I think you're right that in conventional notation they don't use hats. I will make the edit. Perhaps I was not clear enough... there are two parameters for the same variable fit in two different models on the same dataset. It is very difficult to directly calculate the standard error of the statistics $T$ and $S$.
Comment: The only way I have been able to make sense of this is to understand the second model to be nested in the first, so that the hypothesis you are testing is $\gamma_2 = 0$. I do not even know of a valid definition of "hypothesis" that involves two separate models.
Comment: @whuber Ah I see the confusion. Please see a [recommended article from MacKinnon here](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2819368/).
Comment: Thank you: that reference helps me understand your example much better. Although I have reservations about the many theoretical solecisms involved in that approach, they are irrelevant to the aptness of your example: it suffices that people have actually tried to understand data in this way and have seen a need to estimate standard errors for estimators of $T$ or $S$. I notice, though, that your last paragraph still does not distinguish between $T$ and its estimator: $T$ is a *model property* and as such has no distribution and no SE. An estimator of $T$ does have a distribution.
Answer: Having parametric solutions for each statistical measure would be desirable but, at the same time, quite unrealistic. Bootstrap comes in handy in those instances. The example that springs to my mind concerns the difference between two means of highly skewed cost distributions. In that case, the classic two-sample t-test fails to meet its theoretical requirements (the distributions from which the samples under investigation were drawn surely depart from normality, due to their long right-tail) and non-parametric tests lack to convey useful infromation to decision-makers (who are usually not interested in ranks). A possible solution to avoid being stalled on that issue is a two-sample bootstrap t-test.

Why do we need Bootstrapping?


Why does t-SNE not separate linearly separable classes?

Question: I have small convolution neural net for classification EEG patterns (2 class problem)  with several conv layers and one dense layer. This net performs pretty well. For education purposes I used convolutional part of this pretrained net (all net except dense layer) to extract features from training samples. So this new data representation lineary seperable (because dense layer can correctly classify them) But when I used TSNE on this training set representation and got only one blob and points from different classes where mixed.
This situation repeats independently from TSNE parameters. Does it possible to get only one cluster with mixed classes for linearly separable dataset?
Comment: "This net performs pretty well" - What does "pretty well" mean? What is the test-set (or cross-validated) performance?
Comment: roc auc equal ~0.75
Comment: On a test set? Using cross-validation?
Comment: On validation set. But for this picture I used training set, wich is definetly seperable by this net
Answer: Yes.
You can use the following code to convince yourself.
<code>N <- 1000
P <- 3

# Generates some random data
data <- matrix(data = rnorm(N*P), nrow = N, ncol = P)

# Assignate linearly separable classes
labels <- (data[,1]+data[,2]>0)+1.

# Make sure that the data can be separated
plot(data[,1],data[,2], col = labels, xlab = 'x1', ylab = 'x2')

require(Rtsne)
model <- Rtsne::Rtsne(data)

# Observe this result while varying P
plot(model$Y, col = labels, type = 'p', pch = 21, xlab = 'tSNE x_1', ylab = 'tSNE x_2')
</code>
This is what you would observe when P is 3 (only one irrelevant attribute with respect to the linear separation, we are close to reproducing the linear separation).

And for P is 15, the tSNE cannot reproduce the linear separation.

What happened ?
This is simple. The tSNE method relies on pairwise distances between points to produce clusters and is therefore totally unaware of any possible linear separability of your data.
If your points are "close" to each other, on different sides of a "border", a tSNE will consider that they belong to a same cluster.
This was exactly the point of the simulations above. When the number of dimensions is large, points look close to each other, no matter the side of the border they belong to. This is what tSNE fails to capture here.
On the other hand, when the number of irrelevant dimension is low, close points had "no other choice" but to be on the same side of the border.
Side note.
Even though you may have a nice performance with a neural network, it may not mean that your data is linearly separable (unless there is only one unit in your neural, hum, network). Indeed neural networks can recognize non linear boundaries. If you want to test how "linearly separable" a data set is, you should use linear Support Vector Machines or regressions.
Comment: +1 but the last paragraph somewhat misses what OP says: they used t-sne on the output of the last layer (presumably before softmax) so that would indeed be linearly separable. Re-read the part of the question before the figure.
Comment: @amoeba thank you I missed it indeed. For my arguments to apply we would need to know how many features appear on the last layer...


EntitySQL and SQL injection

Question: I've got the following query string
"SELECT VALUE entity FROM Entities AS entity WHERE entity.Client_id
= 0 && entity.Name LIKE @searchvalue ORDER BY @sorting SKIP @skip LIMIT @limit"

with the following param replacement
query.Parameters.Add(new ObjectParameter("skip", start));
query.Parameters.Add(new ObjectParameter("limit", limit));
query.Parameters.Add(new ObjectParameter("searchvalue", searchValue + "%"));
query.Parameters.Add(new ObjectParameter("sorting", sortField + " " + sortDirection.ToUpper()));

But I always end up in the exception:

The key expression 'ORDER BY' must have at least one reference to the
  immediate input scope. Near ORDER BY clause item

I guess this happends cause query.Parameters.Add(...) wraps all in quotes? I also read this but for what benefit then do I need query.Parameters.Add(...) if nothing can happens? OK, the attacker may not start a new query but I guess he can manipulate the current?
Comment: Not familiar with entity-sql, but my guess is yes, it thinks that, e.g. `fieldname asc` is the name of the field you want. Can you try with `... ORDER BY @sortfield @sortdir ...` and using two parms?
Answer: Guess:
The first thing I would try it to do something like this

SELECT VALUE entity FROM Entities AS entity WHERE entity.Client_id
  = 0 && entity.Name LIKE '@searchvalue' ORDER BY @sorting @sortorder SKIP @skip LIMIT @limit

query.Parameters.Add(new ObjectParameter("searchvalue", searchValue + "%"));
query.Parameters.Add(new ObjectParameter("sorting",   sortField ));
query.Parameters.Add(new ObjectParameter("sortorder", sortDirection));

In other words: move sorting order to seprated parameter.
EDIT
If this doesn't work use Query Builder to construct a query.
Look here for example.
Good luck.
Comment: that was my initial one... So no, that result in the same error
Comment: @sra: ok, so probably it's a worst case, when you can not do this. But it should be possible to do with ObjectQuery builder. Look [here](http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/6b95ad32-6642-4ec7-8051-e0bdfe022eff/)
Comment: that is the answer! You should copy that at the bottom of your answer.
Answer: Have tried removing the quotes @searchvalue, since you are using a parameterized query IMO, quotes are no longer required.
Instead of:
"SELECT VALUE entity FROM Entities AS entity WHERE entity.Client_id
= 0 && entity.Name LIKE '@searchvalue' ORDER BY @sorting SKIP @skip LIMIT @limit"

Try this:
"SELECT VALUE entity FROM Entities AS entity WHERE entity.Client_id
= 0 && entity.Name LIKE @searchvalue ORDER BY @sorting SKIP @skip LIMIT @limit"

Comment: I've forgot these, you're absolutely right. But nonetheless that's not my error... I've fixed this in my post. But does parameterized query automatic quote?
Comment: It will automatically apply the quotes if necessary (e.g. when working with strings). There's no need to wrap a parameter in quotes.
Answer: You cant use parameters as replacement of column names.

EntitySQL and SQL injection


Skip other hosts if first host is reachable in Ansible

Question: I am having file consists of Ip address I using below method to to make this inventory for my tasks
ips.text
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4

main.yml
    - name: Add Instance IP Addresses to temporary inventory groups
      shell: cat ~/ips.text
      register: serverlist
    - debug: msg={{ serverlist.stdout_lines }}
    - name: Add Instance IP Addresses to temporary inventory groups
    add_host
        groups: working_hosts
        hostname: "{{item}}"
      with_items: "{{ serverlist.stdout_lines }}"

- hosts: working_hosts
  become: yes

Now I want to make it like if 192.168.0.1 is reachable then it should skip rest of the ips from that file and if 192.168.0.1 is unreachable then only goes to next 192.168.0.2.
How can we achieve this?
Answer:
Q: "If 192.168.0.1 is reachable then it should skip the rest of the IPs."

A: Let's wait_for_connection on all hosts in the block and store the connection status in the variable reachable. Then use the variable reachable to create the group of reachable hosts reachable and run new play with the first host from the group groups.reachable.0. For example
- name: Test reachable hosts
  hosts: working_hosts
  gather_facts: false
  vars:
    connection_timeout: "10"
  tasks:
    - block:
        - wait_for_connection:
            timeout: "{{ connection_timeout }}"
      rescue:
        - set_fact:
            reachable: false
        - meta: clear_host_errors
        - meta: end_host
    - set_fact:
        reachable: true

    - add_host:
        name: '{{ item }}'
        groups: 'reachable'
      loop: "{{ hostvars|dict2items|json_query('[?value.reachable].key') }}"
      run_once: true

- hosts: "{{ groups.reachable.0 }}"
  tasks:
    - debug:
        msg: "{{ inventory_hostname }}"

Answer: Well, order your host as you want them in the inventory, set gather_facts: yes, and run_once: yes of the tasks, and you're good to go:
---
- hosts: all
  gather_facts: yes
  tasks:
  - debug:
      var: ansible_hostname
    run_once: yes

Run this playbook on a set of hosts, with the first few in your list powered down, and you will see the task only runs on the first host that is responding.
Another option is similar to what Vladimir suggested, but using the (lack of) results from gather_facts:
---
- hosts: all
  gather_facts: yes
  tasks:
  - set_fact:
      first_good_host: "{{ ansible_play_hosts | map('extract', hostvars) | list | json_query(query) | first }}"
    run_once: yes
    delegate_to: localhost
    vars:
      query: "[?ansible_facts!=''].inventory_hostname"

  - debug:
      var: first_good_host
    delegate_to: localhost

  - add_host:
      name: '{{ first_good_host }}'
      groups: 'reachable'
    run_once: yes

- hosts: reachable
  gather_facts: yes
  tasks:
  - debug:
      msg: "{{ inventory_hostname }}"

Good luck!


Find equation of Tangent line at $(4, 1)$ on $5y^3 + x^2 = y + 5x$

Question: Can someone help me find equation of tangent line at $(4, 1)$ on
 $5y^3 + x^2 = y + 5x$
$Y=f(x)$
I dont know how to isolate the $Y$
Comment: Don't isolate $y$, use implicit differentiation.
Comment: Welcome to SE! Can you show us your attempt? That would help us to help you.
Answer: knowing
$$
y-y_0 = y'(x-x_0)
$$
$$
\frac{d}{dx}[3y^3+x^2] = \frac{d}{dx}[y+5x]
$$
$$
15y^2 y' + 2x = y' + 5
$$
$$
2x-5 = y'[1-15y^2] \therefore
$$
$$
y' = \frac{2x-5}{1-15y^2}
$$
When at the point (4,1) you get
$$
y-1 = \frac{2(4)-5}{1-15}(x-4)
$$
$$
y = \frac{12-3x}{14}+1 = \frac{13}{7}-\frac{3x}{14}
$$
Comment: Thank you so much Eric! Yeah i tried implicit differentiation but was lost after that. But thanks again i understand it know :)
Answer: $$\dfrac{d}{dx}5y^3 + x^2 = y + 5x$$
$$=y'15y^2 + 2x = y' + 5$$
$$=y'15y^2-y' = -2x + 5$$
$$=y'(15y^2-1) = -2x + 5$$
$$=y' = \dfrac{-2x + 5}{(15y^2-1)}$$
Plugging in the point $(4,1)$ gives
$$y'=-\dfrac{3}{14}$$


How to show a gradient diagonally in a view

Question: I am generating a gradient from 2 UIColors and then generating a UIImage out of it using these functions.
//Function to generate the UIImage from 2 colors.
func createGradient(color1: UIColor, color2: UIColor) -> UIImage {
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.view.bounds
    gradientLayer.colors = [color1.cgColor, color2.cgColor]
    let image = image(from: gradientLayer)
    return image
}

//Function to generate an Image from a CALayer.
func image(from layer: CALayer) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, true, 0)
    layer.render(in: UIGraphicsGetCurrentContext()!)
    let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return outputImage ?? UIImage()
}

My result is this

But I would like to show this diagonally from the top left corner to the bottom right corner .... So the Red should start from the top left corner and fade into the Yellow as it goes down diagonally towards the bottom right corner.
I am not sure if should be generating the Gradient diagonally or if i should rotate the image after it is generated to show it diagonally.
Thanks
Answer: Simply add the startPoint and endPoint to the gradient layer:
[...]
gradientLayer.startPoint = .init(x: 0, y: 0) // top left
gradientLayer.endPoint = .init(x: 1, y: 1) // bottom right
[...]

Comment: Agree with @André Slotta. But the parameters should be adjusted to fit the question: gradientLayer.startPoint = .init(x: 0.5, y: 1.0)  ,
gradientLayer.endPoint = .init(x: 0.5, y: 0.0)
Comment: That worked perfectly .... Thanks.... Although i adjusted the `X` & `Y` values a little to make it exactly how i wanted it. But yes this was the solution.
Comment: I don't get your comment, @YunCHEN. Shouldn't top left -> bottom right be `(0,0)` -> `(1,1)`?
Comment: @AndréSlotta, according to the screenshot, the gradientLayer's start position is x:0.5,y:0.0. Means it's from top-middle to bottom-middle.
Comment: Right, @YunCHEN. But the screenshot does not show what the author is trying to achieve. So I am not sure why someone voted your comment to be correct.
Comment: @AndréSlotta, ahh... you are right, according to the text, what the author wants is top-left to right-bottom. So let my comment be an additional suggestion for screenshot case.


Como Chamar um Relatório Jaspersoft que tem um SubReport

Question: Bom dia pessoal, sou novo nessa área de fórum e tbm na de programação. Estou criando um pequeno sistema para uma empresa que trabalho, nela a menina do financeiro protocola os boletos hoje na mão e no caderno... queria deixar uma coisa mais automática, então resolvi colocar a mão na massa! Porem agora estou criando um relatório para ela que contem um sub-relatora, no Previwer do jaspersoft ele funciona, mas quando tempo chamar ele no java não consigo. Serei muito grato para quem puder me ajudar, esse é meu código que eu chamo o relatório.
public void Rel_Titulos_so_Data(final String data){
    try {
        final ConectaBanco conn = this.conn;
        ConectaBanco.getConnection();
        this.conn.executaSql("SELECT\n"
                        +"  protocolar_documentos.razao_social,  SUM(protocolar_documentos.valor_documento),\n"
                        +"  cad_fornecedor.id,\n"
                        +"  cad_fornecedor.razao_social,\n"
                        +"  protocolar_documentos.*\n"
                        +"  \n"
                        +"  FROM \n"
                        +"  protocolar_documentos\n"
                        +"  LEFT JOIN cad_fornecedor ON \n"
                        +"  ( cad_fornecedor.id = protocolar_documentos.fornecedor)\n"
                        +"   \n"
                        +"  WHERE \n"
                        +"  protocolar_documentos.data = '"+data+"' GROUP BY protocolar_documentos.razao_social\n"
                        +"  ORDER BY protocolar_documentos.razao_social");
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("Arquivos_Relatorios/Relatorio_Titulos.jasper");
        final JRResultSetDataSource jrRS = new JRResultSetDataSource(this.conn.rs);
        final JasperPrint jasperPrint = JasperFillManager.fillReport(is, (Map)null, (JRDataSource)jrRS);
        JasperViewer.viewReport(jasperPrint, false);
    }
    catch (JRException ex) {
        System.out.println(ex);
    }
}

Answer: Passei por este mesmo problema a algumas semanas e nao encontrei nada na internet que me ajudasse de fato, entao criei esta solucao.
public static Object printJasper(@NonNull final Collection data,
                                 @NonNull String titulo,
                                 String subReport) throws JRException {

    /*exemplo de codigo para compilar relatorio dentro do codigo
    final String sub = "/jasper/sub.jrxml";
    JasperReport subCompilado = JasperCompileManager.compileReport(sub);*/

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("SUBREPORT_DIR",  new ClassPathResource(String.format("/target/classes/jasper/%s.jasper", subReport)));

    JasperPrint print  = JasperFillManager.fillReport(String.valueOf(new ClassPathResource(String.format("/target/classes/jasper/%s.jasper"
            , titulo))),map, buildDatasource(data));

    return exportPdf(print);

}

Note que eu uso o "Map" para imputar meu sub-report por parametro (e assim que o Jasper trabalha);
Entao dentro do teu jrxml voce deve ter uma tag desta forma;
<subreport>
            <reportElement positionType="Float" x="1" y="0" width="553" height="20" uuid="dcb4de43-b64f-4e50-a4b1-5ad31a1cd9a2"/>
            <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("carga.ordens")]]></dataSourceExpression>
            <subreportExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportExpression>
</subreport>

Para este caso estou usando um json como datasource, mas nao deve mudar nada.
Comment: tentei fazer tudo o que vc falou, mas por conta do meu baixo conhecimento não obtive êxito... Muito obrigada pela força vou continuar estudando para ver se consigo fazer com que funcione
Comment: @AllysonHenrique pelo oque eu vi no seu codigo, voce nao esta passando o subreport para o java rodar.

Por mais que dentro do Main (seu relatorio prinicipal) ele esta com o subreport vinculado, quando voce chama o JasperPrint voce deve passar o subreport como parametro.

    `final JasperPrint jasperPrint = JasperFillManager.fillReport("seu main report", "seu sub report", "seu data source");`

Voce deve deixar o jrxml esperando o subreport como parametro, como passei no exemplo a tag subreport esperando um $P{SUBREPORT_DIR}
Comment: voce esta (Map) null, no lugar do subreport, por isto nao roda ;)


Hardware-only 'Undefined' database error on openDatabase in Cordova 2.5 on Android - only for first attempt

Question: Just updated my android app to Cordova 2.5 and, although it works beautifully in the emulator, it has developed a problem on my HTC desire such that I get a  'undefined' databse error when I try
db = window.openDatabase("ProblemDirectoryDB", "1.0", "PhoneGap Demo", 100000);

However, if I open the same page a second time, it works fine and from then on, even after a forced stop and restart. I can recreate the error by deleting the application's data. The relevant code is below. Any help/thoughts very gratefully received.
var db;
var dbCreated = false;

function onBodyLoad(){
$.mobile.loadingMessageTextVisible = true;
$.mobile.loadingMessage = "Loading...";
$.mobile.showPageLoadingMsg();
if (!window.device){
     document.addEventListener("deviceready", onDeviceReady, false);
    }
else {
    onDeviceReady();
    }
}

function onDeviceReady() {
db = window.openDatabase("ProblemDirectoryDB", "1.0", "PhoneGap Demo", 100000);
    if (dbCreated){
        db.transaction(getProblems, read_transaction_error);
        }
    else{
        db.transaction(populateDB, create_transaction_error, populateDB_success);
        }
navigator.splashscreen.hide();
}

function populateDB_success() {
dbCreated = true;
    db.transaction(getProblems, transaction_error);
}

function create_transaction_error(tx, error) {
$.mobile.hidePageLoadingMsg();
    alert("Create Database Error: " + error);
}

Answer: Unbelievably, after hours and hours and a near-total rewrite, I finally spotted the 100000 bytes size parameter in my window.openDatabase call - my DB now exceeds 256K so simply changing it to 300000 appears to have solved my problem!!
No wonder no-one else seems to have had the same problem - no-one else has been stupid enough not to notice the size parameter! Although quite why it worked on the emulator and on second and successive opens on the hardware, I don't know. Anyway, problem solved.


What is the proper way to notate the end of a section played "sul ponticello"?

Question: That is, what is the standard way to tell a string player to play normally again?
Answer: You can use ordinario or normale:

ordinario or normale: to bow in the ordinary or normal fashion, canceling a previous instruction to play s.p. or s.t.
  abbreviations: ord. ; norm.; N.  - source
Answer: 'loco' is also used in these situations.


Let $M, N$ be subgroups of $G$ such that $G=M\times N$. Suppose $H$ is a subgroup of $G$ s.t. $HM=G=HN$ and $H\cap M= H\cap N=1$. Show $M\cong N$.

Question: Question: Let $M, N$ be subgroups of $G$ such that $G=M\times N$.  Suppose $H$ is a subgroup of $G$ such that $HM=G=HN$ and $H\cap M= H\cap N=1$.  Show $M\cong N$.
Thoughts: We have that $HM=G=HN$, and so $|HN|=|HM|\implies |H||N|=|H||M|$, since $H\cap M= H\cap N=1$.  Dividing both sides by $|H|$ gives us that $|M|=|N|$.  Now, I believe to show equality (I guess, isomorphism only), I need to show that either $M\subseteq N$ or $N\subseteq M$, since their orders are already equal.  Maybe this is just trivial?  If $N=M$, then we're done, so would I then just consider the cases when $N\subset M\subseteq G$ and $M\subset N\subseteq G$, and maybe try to use that $G=M\times N$, somehow?
Any thoughts are, as always, greatly appreciated!  Thank you.
Comment: Observations: are you allowed to assume $G$ is finite? Even if so, you can't expect to prove $M = N$: consider the 3 non-trivial subgroups of the Klein four-group.
Comment: @RobArthan Ah, yes, that's a good point.  I suppose we can't assume $G$ is finite.
Answer: Because $G = M \times N$, we know $M$ and $N$ both are normal in $G$, so $N \cong G/M = HM/M \cong H/(H \cap M) \cong H \cong H/(H \cap N) \cong HN/N = G/N \cong M$.
Comment: Note, by the way, that you only need $H \cap M = H \cap N$.  You don't also need that $H \cap M = \{ 1 \}$.  Just note that the two quotient groups on either side of $H$ are equal (not just isomorphic), and the rest of the proof works.
Comment: I did notice that!  Thank you!  I really appreciate your insight!!!
Comment: How do you know that $M,N\trianglelefteq G$?
Comment: Because $G=M \times N$, so any element of $N$ doesn't just normalize $M$, in fact it commutes with $M$.
Answer: It seems like the second isomorphism theorem should be some help here. Note that
$$N \simeq \frac{M\times N}{M} = \frac{HM}{M}\simeq \frac{H}{H\cap M}\simeq H $$
And similarly $M\simeq H$ so that $N\simeq H \simeq M$
Answer: Probably $M$ will not be equal to $N$.  However, given that every $g \in G$ can be written uniquely as $h_1m$ for $h_1 \in H$ and $m \in M$, and written uniquely as $h_2n$ for $h_2 \in H$ and $n \in N$, and explicit isomorphism from $\phi: M \rightarrow N$ can be given as follows: given $m \in M$, write $m$ uniquely as $hn$ for some $h \in H$ and $n \in N$, and define $\phi(m) = n$.


Using JSContextGroupSetExecutionTimeLimit in iOS

Question: I need to stop the execution of Javascript in a JSContext object? I found the following method which exactly what I need
@function
@abstract Sets the script execution time limit.
@param group The JavaScript context group that this time limit applies to.
@param limit The time limit of allowed script execution time in seconds.
@param callback The callback function that will be invoked when the time limit
 has been reached. This will give you a chance to decide if you want to
 terminate the script or not. If you pass a NULL callback, the script will be
 terminated unconditionally when the time limit has been reached.
@param context User data that you can provide to be passed back to you
 in your callback.

 In order to guarantee that the execution time limit will take effect, you will
 need to call JSContextGroupSetExecutionTimeLimit before you start executing
 any scripts.
*/
JS_EXPORT void JSContextGroupSetExecutionTimeLimit(JSContextGroupRef, double limit, JSShouldTerminateCallback, void* context) AVAILABLE_IN_WEBKIT_VERSION_4_0;

Unfortunately the method is not well documented and I can't figure out how I can use it.
My code is
JSContextGroupRef group = JSContextGroupCreate();
JSGlobalContextRef context = JSGlobalContextCreateInGroup(group, NULL);
NSString *code = @"while(1){}";
JSStringRef script = JSStringCreateWithCFString((__bridge CFStringRef)code);
JSContextGroupSetExecutionTimeLimit(group,.200f,nil,0);
JSValueRef error = NULL;
JSValueRef value = JSEvaluateScript(context, script, NULL, NULL, 0, &error);

when I try to to call to JSContextGroupSetExecutionTimeLimit I get compilation error.

Implicit declaration of function "JSContextGroupSetExecutionTimeLimit"
  is invalid in C99,

seems like the call comes from JSContextRefPrivate.h, the question how I can add this header to my project and where is the implementation.
any advice how can I handle this. thanks
Comment: This is an undocumented method that might cause apple to reject the app
Answer: It's actually pretty trivial: Just copy the declarations of the relevant functions (and the JSShouldTerminateCallback typedef) into your source code. This tells the compiler the exact signatures with which the functions will be available at runtime.
As JavascriptCore is part of the open source WebKit project, the function declarations are available even with useful descriptions in the WebKit repository. The relevant parts are:
typedef bool
(*JSShouldTerminateCallback) (JSContextRef ctx, void* context);

JS_EXPORT void JSContextGroupSetExecutionTimeLimit(JSContextGroupRef group,
                                                   double limit, JSShouldTerminateCallback callback, void* context) CF_AVAILABLE(10_6, 7_0);

JS_EXPORT void JSContextGroupClearExecutionTimeLimit(JSContextGroupRef group) CF_AVAILABLE(10_6, 7_0);

Also, you don't have to create a group yourself, as according to the JavascriptCore documentation, every JSContextRef you create is assigned a new JSContextGroup. You can get the group of a context using the public JSContextGetGroup function.
An example using the private JSContextGroupSetExecutionTimeLimit API is available in the WebKit tests.
IMPORTANT: As already pointed out, an app using this private API is likely to be rejected from the App Store.
Comment: Do you know how to terminate the evaluation of `JSContext` (Objective-C object)? I tried `JSGlobalContextRef contextRef = [jscontext JSGlobalContextRef];` with the WebKit tests same way, but doesn't work, any idea? Thank you!


how to retrieve data from SQL database in Word 2010?

Question: I would like to populate a Word document with data from our MS SQL database.
Is this possible, and if yes how?
Answer: I have done it various ways in the past. It depends whether the user initiates the action from OUTSIDE of Microsoft Word or from INSIDE Microsoft Word.
From INSIDE Microsoft Word, you can use one of the following techniques:

Open a template with placeholders and use VBA or VSTO to iterate over them using a data source using copy & paste. Please note that tables are also a crime here. This approach resembles approach 1 below with "OUTSIDE". Disadvantage that it is relatively slow (copy & paste) and that Microsoft Word autocorrect likes to kick in when least needed.
Open a template with placeholders and use VBA or VSTO to parse the XML representation and then replace these. It is faster, but harder to write. Especially since the XML representation can contain XML fragments within the placeholders (such as '&lt;&lt;PUT_<xxx/>IT_HERE&gt;&gt;' and more complex cases). Also, you need to make sure you keep a valid XML document and well balanced.

From OUTSIDE Microsoft Word (such as web interface) you can use one of the following techniques:

Store a template somewhere using RTF (which is far easier to process than Word's own structure). Put '<<PLACEHOLDER-FOR-NAME>>' or similar easily recognized texts where you like to replace it. When user requests the Word document, fetch the RTF, fetch the data, replace the placeholders, server RTF to user. RTF has some restrictions, but some advantages. Advantages are: ease of creating new templates and also works with Microsoft Wordpad and other Office packages. Disadvantages are that tables are a real mess to process and that not all Microsoft Word constructs are possible. Repeating rows in a table are even less recommended. High volume can be an issue.
Use a reporting package that happens to also output docx, doc or RTF documents. Write a report. In general perfectly suited for high volume. Less suited if you want the end user to type a major amount of additional text, since reporting packages typically work based on pages instead on a flowing text, where sometimes an explicit or implicit page break is inserted. But if you only need the end user to enter one or two sentences in addition, it is sufficient.
Fat-client. Put the SQL data somewhere. Open Word. Read the data and see further techniques for from INSIDE Microsoft Word.

If you need to fill a Word document from SQL Server (or any other database or data platform) , I can suggest the free edition of Invantive Composition for filling Word documents from the database (please note that I've been involved with that product). It opens templates and merges them from within Word, but is more targeted at non-developers; just specify the template and datablocks (possibly nested) and publish. Developers can only add some C# in plugins. I think it is a good product when you have MANY templates (over 50) because it scales easier.
Answer: You may use microsoft query to fetch data from SQL database to your document, this video may be usefull
https://vimeo.com/83983247
Answer: You could also try using MS-Excel as it binds to XML better than Word does.
It's easy too to make Excel produce 'Word' styled output.
Comment: this not nearly answers the question.


Use joint pdf to answer questions about random variables

Question:
Hi, can I get some help on this I already did this but I need to collaborate my work to see if Im on the right track: my answers to the questions are
a) Prob{ total water level < 3 } = 0.4037
b) EA = 0.6673
c) xlow = 0.0526 xhi = 1.9474
Comment: It is not collabrate, but corroborate.
Comment: well sorry I try with my english
Comment: Please show some of your work...
Comment: @peter,  I have worked out the problem for you and you are almost right on all parts except the last for which I differ from your answer.  Take a look at it and see if you agree.
Answer: I have given the solution in hand-written form.  Let me know if it is legible.  See if you approached the problem differently than mine.  This is my best effort.


Amazon RSQL concat of two tables with 2 shared columns

Question: I have such an example of tables:
table1:

col 1
col2
col3
col4

1
a
x1
asdc

2
b
x2
czxa

3
c
x3
xfsdaa

table2:

col2
col3

l
x56

q
x99

All I want is to receive such a final concatenation

col 1
col2
col3
col4

1
a
x1
asdc

2
b
x2
czxa

3
c
x3
xfsdaa

null
l
x56
null

null
q
x99
null

How can I make it in RSQL (postgresql based SQL)? I thought about selecting all columns from the first table, then union all and use NULL AS col1 [...] NULL AS col4 in the place of missing columns, but in real data I have dozens of columns so the code won't look great with it.
Is there some other way to achieve it?
Answer: If you don't mind reordered columns you can get away with a natural full outer join:

USING clause is a shorthand that allows you to take advantage of the specific situation where both sides of the join use the same name for the joining column(s). It takes a comma-separated list of the shared column names and forms a join condition that includes an equality comparison for each one. For example, joining T1 and T2 with USING (a, b) produces the join condition ON T1.a = T2.a AND T1.b = T2.b.

NATURAL is a shorthand form of USING: it forms a USING list consisting of all column names that appear in both input tables. As with USING, these columns appear only once in the output table. If there are no common column names, NATURAL JOIN behaves like JOIN ... ON TRUE, producing a cross-product join.

Which means it'll deduplicate columns with matching names, without you having to name them or even know them. Demo at db<>fiddle:
select * from table1 natural full outer join table2;

col2
col3
col1
col4

a
x1
1
asdc

b
x2
2
czxa

c
x3
3
xfsdaa

l
x56
null
null

q
x99
null
null

Problem is, matching values in columns with matching names will be joined together. It might as well be the desired effect but if it's not, you can force the mismatch using the fact that joining on null values results in a mismatch:
select *
from (select tableoid::regclass,null as force_mismatch,* from table1) a
natural full outer join
     (select tableoid::regclass,null as force_mismatch,* from table2) b;

tableoid
force_mismatch
col2
col3
col1
col4

table1
null
a
x1
1
asdc

table1
null
b
x2
2
czxa

table1
null
c
x3
3
xfsdaa

table2
null
c
x3
null
null

table2
null
l
x56
null
null

table2
null
q
x99
null
null

I've added tableoid system column only to show (c, x3) was in both tables. It potentially offers some added utility and you can force the mismatch using just that, but otherwise it's enough to add a constantly null column with the same name on both sides.
Keep in mind that natural join is a sensitive topic: it's risky and typically advised against.
That being said, what you proposed with the UNION clause and null constants wherever you want to skip a field is the most obvious, but it should also perform better: demo
create table table1(col1, col2, col3, col4) as values
 (1,    'a',    'x1',   'asdc')
,(2,    'b',    'x2',   'czxa')
,(3,    'c',    'x3',   'xfsdaa');

create table table2(col2,col3) as values
 ('l',  'x56')
,('q',  'x99');

select col1, col2, col3, col4 from table1
union all
select null, col2, col3, null from table2;

col1
col2
col3
col4

1
a
x1
asdc

2
b
x2
czxa

3
c
x3
xfsdaa

null
l
x56
null

null
q
x99
null
Answer: If you don't like Union and have multiple tables then you can use full outer join
db-fiddle
Query
select col1,
    coalesce(t1.col2,t2.col2) as col2,
    coalesce(t1.col3,t2.col3) as col3,
    col4
from t1
full outer join t2
on 1=2;

col1
col2
col3
col4

l
x56

q
x99

1
a
x1
asdc

2
b
x2
czxa

3
c
x3
xfsdaa


Variance of linear combination of Normal distributions

Question: A company that develops software received an order for a service to be performed within a week and, in order to decide on the profile of the team of programmers to be used, it should take into account that:
The total number of lines of code (commands, instructions) to be developed is approximately 30 thousand.
The productivity of your most experienced programmers, in hourly commands, follows a with an average of 50 and a standard deviation of 15.
The productivity of its less experienced programmers, in hourly commands, follows a with a mean of 30 and a standard deviation of 10.
Each programmer works six hours a day, five days a week.
What is the probability that the service will be ready in a week if the team consists of 10 more experienced programmers and 20 less experienced programmers?
Solution:
Let P be the team productivity, X the productivity of most experienced programmers and Y the productivity of less experienced programmers:
$X \sim N(50, 15^2)$
$Y \sim N(30, 10^2)$
$P = 10X + 20Y$
Since P is a linear combination of Normal distributions:
$E[P] = 10E[X] + 20E[Y] = 10(50) + 20(30) = 1100$
$Var(P) = 10^2Var[X] + 20^2Var[Y] = 10^2(15^2) + 20^2(10^2) = 62500$
(...)
Question:
The  textbook answer says that $Var(P) = 10Var[X] + 20Var[Y] = 10(15^2) + 20(10^2) = 4250$.
Why?
Comment: The book's answer seems to be wrong.
Comment: The book's author needs to read Fred Brooks' classic [The Mythical Man-Month](https://en.wikipedia.org/wiki/The_Mythical_Man-Month) to understand what is so awfully wrong about this question.
Comment: Perhaps the company can outsource this on Twitter to 30,000 marginally efficient volunteer programmers, each of whom can write one line of code in an hour. Then, if all the volunteer tweets come back quickly, the project might be completed within a few hours.
Answer: Model 1. Consider two experienced programmers, each producing
$X_1 \sim \mathsf{Norm}(\mu = 50, \sigma=15)$ and
$X_2 \sim \mathsf{Norm}(\mu = 50, \sigma=15)$ lines of
code in an hour, respectively. Then make the assumption that together they produce $X_1 + X_2$ lines of code in and hour.
Then $$X_1 + X_2 \sim \mathsf{Norm}\left(\mu=50+50=100,\\ \sigma = \sqrt{15^2+15^2} =  21.2132\right)$$ lines of code are produced in an hour (and we suppose a magic elf instantly puts the lines of code into a coherent whole).
Model 2. By contrast, suppose that, grossly over-caffeinated and working a double rate, the first exerienced programmer can produce
$$2X_1 \sim
\mathsf{Norm}\left(\mu=2(50)=100,\, \sigma = \sqrt{4*15^2} = 30\right)$$
 coherent lines of code in an hour.
Notice that two different probability models have been used here.  Hence, I don't believe your expression
$P=10X+20Y$ is what the problem means (assuming, contrary to @whubeer's link, that it makes any practical sense at all). I fear for the health of a single programmer (on whatever drugs) working at 20 times normal rate.


Link não funciona ao ser clicado

Question: Tenho esse código de um menu e ao ser clicado no item Biografia o link não funciona:

HOME

BIOGRAFIA

DISCOGRAFIA

FOTOS

VIDEOS

AGENDA

CONVITE

CONTATO

Código CSS:
#ul-menu {
   text-align: center;
   padding-top: 25px;
   word-spacing: 50px;
}

.li-menu {
    display: inline;
    font-family: 'Abel', sans-serif;
 }

.li-menu a {
    color: white;
    text-decoration: none;
    font-size: 15px;
    background: #483D45;
    -moz-transition: all 0.2s linear;
    -webkit-transition: all 0.2s linear;
    -o-transition: all 0.2s linear;
    transition: all 0.2s linear;
}

Já coloquei o destino do link no "href" mas quando eu clico não vai.
Comment: Esse site `http://www.iracemafilha.com` está numa lista negra como site inseguro... podes dar mais detalhes que site é esse e quais os links que não funcionam?
Comment: Amigo, antes de fazer o site precisei da hospedagem pra criar uma página fake afim de estudos de uma disciplina "Desenvolvimento de Código Seguro" da Faculdade, porém já retirei todos os links e arquivos maliciosos, já enviei mensagem pro Google retirar o site da lista e fazer um novo scam mas ainda não responderem, eu terei que registrar um novo domínio .com.br, mas não se preocupe que não tem nada de malicioso no site, o problema é que o Google ainda não retirou o alerta mesmo retirando todos os arquivos maliciosos. O item iografia não vai para o destino http://www.iracemafilha.com/biografia
Comment: Testei no fiddle e funcionou ele redirecionou pra página na mesma aba, coloque soloque um taget="_blank" pra ver melhor o redirecionamento, tenha certeza que há um elemento com id igual aos href="#".
Comment: Ricardo, não estou utilizando mais a navegação por âncoras utilizando IDs, resolvi fazer as páginas individuais mesmo. Estou me referindo ao primeiro item de menu "Biografia", aqui ele não está redirecionando para o alvo.
Comment: O que tens na pasta `/biografia`? devia ser `biografia.html`? ou `.php`? ou talvez falte somente uma `/` para ser `http://www.iracemafilha.com/biografia/`. Eu não vou testar mais no seu site e não vejo como reproduzir este erro para poder ajudar mais.
Answer: No  da página, tem um script:
jQuery(document).ready(function($) {
    $(".scroll").click(function(event){
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 200);
    });
});

O seu link tem a classe scroll, por isso está disparando o evento configurado em $(".scroll").click. O método event.preventDefault() interrompe a navegação do link. Para corrigir, remova o preventDefault ou remova a classe scroll do link.
Além disso, o script está dando o seguinte erro:

Uncaught TypeError: Cannot read property 'top' of null
Comment: Marcus Vinicius, eu tinha realmente esquecido desse script, justo que eu até tinha desativado a navegação por âncoras na mesma página e esqueci do script. Vou testar.
Comment: Funcionou, obrigado Marcus Vinicius, achei que por não estar utilizando o script ele seria inútil mesmo não tendo as ãncoras.

Link não funciona ao ser clicado