Can you express this easy theorem in fancy categorical terms?

Question: Here is a theorem (of homological algebra):

Given $A \rightarrow B \rightarrow C$ in an abelian category
  $\mathcal{A}$.
If for all $D \in \mathcal{A}$ we have that $Hom(D,A) \rightarrow
 Hom(D,B) \rightarrow Hom(D,C)$ is an exact sequence, then $A
 \rightarrow B \rightarrow C$ is an exact sequence.

This is a nice enough theorem that it feels like this can be expressed by saying that some certain representable functor is exact, or faithful, or a generator.
I tried using that an additive functor is faithful iff it sends nonexact sequences to nonexact sequences, but still haven't come up with anything.
Comment: "$\mathsf{Hom}(D,-)$ *reflects* exact sequences of length 3"? ;-)
Comment: "Representables jointly reflect exact sequences"? Something in that neighborhood?
Comment: You mean for a fixed choice of $D$? That can't be it, right?
To say that for some fixed $D$, $Hom(D,-)$ reflects exacts sequences of length 3 would be the following statement:

"Given $D$ and $A \rightarrow B \rightarrow C$ in an abelian category $\mathcal{A}$, if $Hom(D,A) \rightarrow
 Hom(D,B) \rightarrow Hom(D,C)$ is an exact sequence, then $A
 \rightarrow B \rightarrow C$ is an exact sequence."

And that's surely not a true statement. Whereas the theorem I gave is really a true statement, because it asks for the premise to hold over all $D$.
Answer: I'm gonna have to go with @Malice on this one.

Recall that a functor $F$ is "representable"
precisely when $F ≅ \mathsf{Hom}(D,-)$ for some object $D$.
Recall that a functor $F$ "reflects a property $P$"
precisely when $P(X) \;⇐\; P(F\, X)$ for all $X$.
( This' the converse of property preservation. )
Recall that a family of functors consists of a functor $Fᵢ$
for each $i$ in some index set $I$.
Recall that a family $Fᵢ$ "jointly reflects property $P$"
precisely when $P(X) \;⇐\; (∀ i.\; P(Fᵢ \, x))$ for all $X$.

Now your phrase can be stated compactly,

"Representables jointly reflect exact ternary sequences"

Neato!
Comment: I'm just extrapolating, but consider comparing with legitimate phrases such as "jointly monic" in which each member of the family must satisfy the monic premise in order for the monic conclusion to hold..
Comment: I actually googled this because I was sure I had just made it up on the spot, but "jointly reflects" has been used is basically this sense in the literature before. It looks like our sense of reasonable terminology is vindicated.
Comment: That's nice, I accept it.
Have you seen "jointly reflects" defined anywhere in the literature before?
Comment: sweet! way to go MV!


Problema em zerar o score de um jogo

Question: Bem, eu leio o livro do Bjarne sobre programação e estou aprendendo programação por lá, estou no capitulo 5 que é sobre erros, no final do capitulo tem uma lista de exercícios para que eu os faça, me deparei com um exercício em que tenho que criar uma especie de um joguinho que verifica um vetor de 4 numero de 1 a 9 que o usuário digita com o valor randômico criado no computador pra cada numero certo na posição certa que você acerta é um tatu e pra cada numero certo na posição errada é uma capivara, o problema é que de primeiro momento funciona, mas ai o que acontece é que o programa não zera o valor de tatus e capivaras, já tentei de tudo quanto é forma, será que alguém tem alguma sugestão? As vezes é alguma coisa boba que eu errei e nem percebi.
<code>#include <iostream>
#include <algorithm>
#include <vector>
#include <locale>
using namespace std;

vector<int> chave; //chave q o user vai tentar advinhar
vector<int> adv; //vetor com os valores do user
int jogadas = 0; //quantitades de vezes que o jogador jogou
int tatu = 0; // numero certo no lugar certo
int capi = 0; // numero certo no lugar errado
const int jogador = 4;

class Deubad{
    //exceção do rolê que deu ruim
};

class acabou{
    //exceção do fim
};

int gerador(int s){
    srand(s); //gera uma seed nova pra cada vez que é chamado
    for(int x = 0; x < 9; x++){ //gera um vetor de 1 a 9 ou seja com 10 valores dentro
        chave.push_back(x+1);
    }
    random_shuffle(chave.begin(),chave.end()); //tipo embaralha as cartas hehe, lembrando que usa somente os 4 primeiros numeros da sequencia
    for(int x : chave){
        cout<<x<<endl; //isso é só pra listar, pois não sei usar depurador
    }
}

vector<int> inserir(vector<int> f){ //insere os valores que o user digitar
    for(int x = 0; x < 4;x++){
        int val;
        cin>>val;
        if(val == 0 || val > 9) throw Deubad{};
        else;
        f.push_back(val);
    }
    return f;
}

int verificar(){
    for(int x = 0; x < 4;x++){
        if(adv[x] == chave[x]){ //comparando se os números são de mesmo valor e mesma posição
            tatu += 1;
        }else{
        }
        for(int y = 0; y < 4;y++){
            if(adv[x] == chave[y] && adv[x] != chave[x]){ //comparando se os numeros são de mesmo valor e posição diferente
                capi += 1;
            }else{
            }
        }
    }
    jogadas += 1;
    cout<<"Você tem "<<tatu<<" tatus e "<<capi<<" capivaras..."<<endl;
    tatu = 0;
    capi = 0;
}

int ganhou(){ //verifica se o jogador acertou tudo
    int val = 1;
    if(tatu == 4){
        cout<<"Você ganhou!!!"<<endl;
        return val;
    }else{
        val = 2;
        return val;
    }
}

int jogardnov(){ // pergunta se o usuario quer jogar novamente
    char r = ' ';
    cout<<"Quer jogar novamente? Digite S para sim e N para não"<<endl;
    cin>>r;
    int val = 2;
    if(r == 'S' || r == 's'){
        return val;
    }else if(r == 'N' || r == 'n'){
        return 0;
    }else{
        throw Deubad{};
    }
}

void novament(){ //executa tudo dnovo
    do{
        cout<<"Você já tentou "<<jogadas<<" vezes"<<endl;
        tatu = 0;
        capi = 0;
        adv = inserir(adv);
        verificar();
        int vef = ganhou();
        if(vef == 1){
            if(jogardnov() == 2){
                break;
            }else{
                throw acabou{};
            }
        }else{
            tatu = 0;
            capi = 0;
            break;
        }
    } while(tatu != 4);
}

int main(){
try{
    setlocale(LC_ALL,"Portuguese");
    cout<<"Isto é um jogo, mesmo que não tenha um grande gráfico é um jogo"<<endl
        <<"Esse jogo chama tatus e capivaras"<<endl //o charme do joguin tá no nome que ele recebe saca
        <<"Funciona da seguinte maneira, tenho uma chave de 4 digitos \n que contém números de 1 a 9 aqui comigo..."<<endl
        <<"Voce tem que ser ninja pra acertar tudo de primeira..."<<endl
        <<"Pra cada número certo no lugar certo que você tem tatu"<<endl
        <<"Já se você acertar o número no lugar errado você tem uma capivara"<<endl
        <<"Então vamos ver o que aconteceu..."<<endl
        <<"Preciso que você digite um número qualquer"<<endl;
    int n;
    cin>>n;
    if(chave.size() == 0){
        gerador(n);
    }else{
        srand(n);
        random_shuffle(chave.begin(),chave.end());
    }
    cout<<"Agora você vai preencher as suas possibilidades, \n com números de 1 a 9, não esqueça!!"<<endl;
    adv = inserir(adv);
    verificar();
    int val = ganhou();
    do{
        if(val == 1){
            val = jogardnov();
            if(val == 2){
                system("CLS");
                main();
            }else{
                return 0;
            }
        }else{
            novament();
        }
    }while(true);
}
catch(Deubad){
    cerr<<"Você digitou algo errado em... SEU BABACA ANALFABETO OTARIO"<<endl;
    novament();
}
catch(acabou){
    cerr<<"Seu arrogante não gostou do meu jogo seu babacão!! \nfalo mesmo não sou baú"<<endl;
}
}
</code>
Comment: todos os casos(perder, ganhar, etc...) não esta zerando?
Comment: Fui rever o código por inteiro achei o erro
Comment: Coloca a resposta então.
Answer: Eu encontrei o erro, não é problema com score e sim com vetor.
O vetor q você digitou na rodada passada continua ali, e por isso atrapalha verificar os itens do vetor. Usei uma linha pra resolver esse problema:
<code>adv.clear();
</code>

Problema em zerar o score de um jogo


Instruments that don't require hand strength

Question: I am a vocalist and a guitarist, but I suffer from wrist problems, so if I want to ever heal from them, I have got to play music for a while without using my hands too much (as long as there is no hand strength or strong grip required, it's fine).
Examples I've found for instruments which follow the criteria are: Harmonica, recorder, slide-whistle, kazoo and theremin.
I am unsure if an electronic unweighted keyboard would also match the criteria.
So my question is: Which instruments could I play that would match the previously said criteria?
Answer: I would be cautious of any instrument that requires finger action, such as the recorder or keyboards. Finger movements are controlled by tendons that go through the wrist and connect to muscles in the forearm.
Some instruments require the wrist to be in a "fixed" position, which means that two sets of opposing muscles are constantly working "against each other" to maintain that position. You have to learn how to minimize those opposing forces.
Other instruments (like keyboards) require constant bending of the wrist, both side-to-side and up-and-down.
Beginners playing keyboard instruments often get "wrist ache" in the early stages of learning, without any medical conditions to aggravate it. It takes time to build up the wrist strength to play continuously for an extended period of time without a break (i.e. more than 2 or 3 minutes).
Also, some unweighted keyboards may require a heavier key force than weighted ones. "Unweighted" simply means the key weight is constant, not that it is light. Cheap unweighted keyboards are often "heavy," partly because the heavier mechanical parts can be made stronger to withstand abuse, and partly because it's easier for beginners to avoid pressing more keys than they intend to when they don't "aim straight," if the keys require more force to press them.
See http://eorthopod.com/wrist-anatomy/
Answer: well, i only know piano well.  but i'd think it'd be similar for all instruments.
the point is to play as relaaaxed as possible.  you know how yoga people shake out the stress and try to get as loose as possible?  that floppiness is how you should be playing your instrument.  you should only be using the least amount of muscles possible to make the key go down, plug the hole, hold the fret, whatever.
using extra muscles is a waste and will often (especially with piano) give you serious pain issues over time.
during practice, always take a moment, say halfway through a short loop of the song that you're practicing and feeeel if you're playing as loose and stress free as possible.
you can play for long periods of time, even on piano, ooonly if you're playing loose, floppy, lightly, and relaxed.  Stress in your jaw and muscles not even related to playing will cause you issued with playing, too.
So don't "strength train".  Do "relax train".
Answer: If you play guitar already you might try using a slide and tuning the guitar to an open tuning. This way you can still play chords and use picking patterns. This mainly works with steel string guitars. The action of the guitar can't be too low also or else you get interference from the fret if you push down with the slide. You buy guitars that are set up to be slide guitars as well.
You could also try a lap steel guitar, but I would be careful about your posture and the position of your hands and wrists while playing. With any instrument, it's not only the gripping but the posture of your body from your back to shoulders to arms and of course your wrists.
I guess part the issue is what type of music you would like to play as well.


iOS Core Data unique object fetch

Question: I'm fairly new to iOS/Cocoa and I have a very fundamental question about core data. I was looking over the internet to find a appropriate answer/solution but I wasn't able to.
So the question is how do you handle uniqueness in core data? I know that core data is not a database, its something like an object graph. Lets assume we have an entity called 'User' with the attributes 'id' and 'name' and a few relations to the other entities. Now we want to update the name of a specific user (e.g. a web service gave us the id and the new name).
This was the way I have done that before:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"User" inManagedObjectContext:context]];
[request setPredicate:[NSPredicate predicateWithFormat:@"id == %@", anId]];

NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
User *user = [results lastObject];

But than I've heard this is bad practice. Is it because fetch requests with predicates are very slow? I can't imagine that this is such a big deal. As far as I know there is no other way to get a unique object rather than go over each object and checking for equality..
Would it be more efficient to fetch all objects of the entity, put them in an array and looping through it manually (instead of the fetch request)?
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"User" inManagedObjectContext:context]];

NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];

User *resultUser;

for(User *user in results){
    if([user.id isEqual:anId]) resultUser = user;
}

Please help me finding the right path and thanks.
Answer: If you have an index for the property that you're fetching (there's a checkbox in the model editor), it's definitely a lot more efficient to use an equality predicate for fetching. Actually, it's never more efficient to fetch all objects and iterate over them in memory, but an index makes the difference more significant.
Answer: You're not fetching a unique object but rather objects containing a notionally unique atrribute value.
All managed objects are unique instances but nothing in Core Data enforces that the attribute values are unique. You could in principle have an arbitrary number of unique managed objects all which had identical attribute values. Only relationships enforce a unique position in the object-graph.
There's no particular reason not to fetch a particular object that contains a particular value if that is what your app requires.
I think what you've read is warnings against trying to cram SQL-like key values into entities and then to try and link managed objects together with those keys using predicates, for example doing something like:
EntityOne{
  sqlKey:string
}

EntityTwo{
  sqlKey:string
}

… and then trying to relate objects of the two entities with predicates.
   (anEntityOneObject.)sqlKey == anEntityTwoObject.sqlKey

… instead of just setting a relationship in the data model.
EntityOne{
  two<-->EntityTwo.entityOne
}

EntityTwo{
  one<-->EntityOne.two
}

… and just finding the related objects with AnEntityOneObj.two.

iOS Core Data unique object fetch


ffmpeg HTTP LIVE STREAMING remove old segments

Question: Hello i Have a Live HTTP stream input for ffmpeg
i want to create HLS streaming im using ffmpeg to do this
ffmpeg -i http://127.0.0.1:4242/bysid/7275 -map 0 -codec:v libx264 -codec:a copy -f ssegment -segment_list playlist.m3u8 -segment_list_type hls -segment_list_size 10 -segment_list_flags +live -segment_time 10 out%03d.ts

i works fine i just want to delete the old segmens that are not shown in playlist.m3u8
segment_list_size 10

this will keep the last 10 in the playlist file i want to keep only these files on hard disk
Answer: You can use the recently added option to the HLS segmenter:
-hls_flags delete_segments

You will need to change your command to use the HLS segmenter rather than the stream segmenter by using -f hls instead of -f ssegment.
I've been using this option and it doesn't do exactly what you request, but rather it's implemented to be compliant with the HLS spec. See the ffmpeg documentation for more information: https://www.ffmpeg.org/ffmpeg-formats.html
Comment: An example using -f hls and also  -hls_flags delete_segments:

ffmpeg -v verbose -i "rtsp://admin:email@example.com:554/cam/realmonitor?channel=1&subtype=0"
-vf scale=1920:1080 -vcodec libx264 -r 25 -b:v 1000000 -crf 31 -an -sc_threshold 0 -f hls -hls_time 5 -hls_list_size 5 -hls_flags delete_segments stream.m3u8
Comment: I replaced -f segment to -f hls, but I got error: Could not write header for output file #0 (incorrect codec parameters ?): Invali
d argument
Answer: USE
-segment_wrap 10

for wrap and rewrite segment files


If I repeat every sample observation in a linear regression model and rerun the regression how would the result be affected?

Question: Say I have N observations, possibly multiple factors and I repeat each observation twice (or M times) how would a regression on this new set of size NM compare to a regression on just the original observations?
Answer: Conceptually, you are adding no "new" information, but you "know" that information more precisely.
This would therefore result in the same regression coefficients, with smaller standard errors.
For example, in Stata, the expand x function duplicates each observation x times.
<code>sysuse auto, clear
regress mpg weight length
------------------------------------------------------------------------------
         mpg |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
      weight |  -.0038515    .001586    -2.43   0.018    -.0070138   -.0006891
      length |  -.0795935   .0553577    -1.44   0.155    -.1899736    .0307867
       _cons |   47.88487    6.08787     7.87   0.000       35.746    60.02374
------------------------------------------------------------------------------

expand 5

regress mpg weight length
------------------------------------------------------------------------------
         mpg |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
      weight |  -.0038515   .0006976    -5.52   0.000    -.0052232   -.0024797
      length |  -.0795935   .0243486    -3.27   0.001    -.1274738   -.0317131
       _cons |   47.88487   2.677698    17.88   0.000     42.61932    53.15043
------------------------------------------------------------------------------
</code>
As you can see, formerly insignifcant coefficients (length) become statistically significant in the expanded model, representing the precision with which you "know" what you know.
Comment: Yes standard errors do indeed go down. Some recommend weighted linear regression for this.. Is there a method you use to fix this?
Answer: Ordinary linear regression solves the problem $$w^* = \mbox{argmin}_w ||Xw - y||^2$$ where $X$ is the matrix of predictors and $y$ is the response. If you repeat each sample $M$ times, it would leave the objective function to be minimized unchanged (except for a multiplicative factor $M$). Therefore the weight vector that  is optimum for the larger problem would be the same as for the original smaller problem.
Comment: Agreed, but i think t stats and standard errors should change given the change from N to NM?
Comment: Since OLS assumes that the noise is independent, the standard error would be different because the number of degrees of freedom would be $M*N - P$ ($N$ is original sample size and $P$ is the number of predictors) and the length of the residual vector goes up by a factor of $M$.


Where should I be storing custom node-related data?

Question: There are several types of data my website generates for every node. Node's popularity score, node's comment count obtained from a 3rd party API, etc... This data is set for every node.
In the past I've used to just add hidden fields to each node, i.e. field_popularity_score, field_comment_count, etc..., and had the fields updated on hook_cron; but I've ran into an issue. Each time those fields are updated, the node's revision date would change also.
Where should I be storing this data? I'd prefer to stay away from using the standard node fields, as it would break its purpose.
Update
Apparently, per this post, Drupal 5 used to allow storage of serialized data into $node->data.
Update
Interesting enough, Node object reference page lists $node->data as part of Drupal 7. I would love to hear if there is a way to use that field to store serialized data in Drupal 7.
Comment: $node->data was there in D5 era, but no longer used in 6 or 7. It's probably there to prevent PHP notices when accessing $node->data.
Custom tables aer perfectly suitable for this. Just make sure you delete the keys in node_delete hook, and load them using a single query in node_load hook.
Comment: You might run into a few issues down the line. Firstly, you might not be able to port your code over to Drupal 8 as I think they might have done away with $node->data. At least in the posts about $user->data there was talk about deprecating it. And secondly, how are you going to pull reports from this? You might not plan on doing it now, but in future you might.
Answer: I would suggest making your own table in the database, it's a perfectly acceptable practice if you name the table something unique that isn't likely to collide with other modules.
The database API is an extremely useful resource for this.

[edit:] Thanks to J. Reynolds - in this instance you will definitely need to tell Views about your table.
Comment: And of course you can always take this further and create a [custom module using the Entity API](http://www.trellon.com/content/blog/creating-own-entities-entity-api).
Comment: And essential then to this implementation would be to add views integration for the table. [Drupal 7 Views Module Tutorial 7 of 10 - Integrating Your Module with the Views AP](https://www.youtube.com/watch?v=Ih88T6F8i1A)
Comment: Maybe @Wtower meant to create a 'data' Entity, parallel to the nodes.... or a 'data' content type, parallel to the content type needing the custom data? For example, for a content type 'blog', create a content type 'blog-data', and upon a new node of content type 'blog', simply add a new node to content type 'blog-data'... hmmm, that can be an idea.
Comment: Thanks. I was hoping it wouldn't involve a custom table, since you have to create a new field on node save, remove a field on node delete, etc.. That said, the thought of altering a Drupal database... just wish Drupal left us a hook for it :)
Comment: I think I understand the concept. Will be going with a custom database.
Comment: The entity API is to create whole new entities. Not sure how Entity API relates to node meta data storage though.
Comment: I think the point was that you could create your own node-like-object that has all of the fields you want in it, but I take your point, doesn't really answer the question as asked.
Comment: @AyeshK, as timofey figured out, Entity API is the Drupal way to go to create proper data objects instead of simple DB API calls. By using the Entity API, not only you enjoy the benefits of the Field API but your data object can become easily interactable with many more modules such as Views, Rules, Feeds etc etc etc.
Answer: Set $node->revision = FALSE when saving your node and continue to use the field API. There are many advantages to using fields and they can be spooled up and destroyed programmatically (see commerce_price for an example) when your module is enabled an disabled.
Advantages are:

Use existing table schema from defined field types.
Integrates with display management tools (DS, Panels or "manage display"), with all the field formatters for that type.
UI is there if you need it. You can set #access => false or use form displays in D8.
More modules will be aware of your data and integrate with it (views was a good example).
Way less custom code to maintain.
Way less time consuming.

For a simple comment count or popularity score you should be staying well away from a custom table or the entity API.
Also, using $entity->data is also a recipe for a disaster. Not being able to filter or query on your data pretty much mitigates any advantage of using a relational database.
Comment: Wow! Love the idea, thanks for taking your time to share. I totally forgot about using the `#access` permission. I will try to use this within the next few weeks and if this does work as it says, I'm definitely going with this option.


What is the logic behind this answer?

Question: $$9^x = 2 \times  3^{x}+6$$
The method in my book to solve this:
$$(3^2)^x = 2 \times 3^x + 6$$
$$(3^x)^2 = 2 \times 3^x + 6$$
$$ p=3^x, p^2=2p+6$$
After using quadratic equation we get the answers ($x = \log_3(1+\sqrt{7})$)
This bothers me:

Why does $(3^2)^x = (3^x)^2$, this seems incorrect to me (LHS = $9^x$ and RHS = $9^{xx}$)
Comment: $\left(a^b\right)^c=a^{bc}=a^{cb}=\left(a^c\right)^b$
Comment: Multiplication is commutative...
Comment: Your RHS is incorrect. You put down $9^{xx}$, which is $9^{(x^2)}$, not $(9^x)^2$.
Comment: I think Brian M. Scott's comment is more to the point than Fant's is.  You can't use commutativity of multiplication until what you've got is multiplication.
Answer: I am not sure what kind of answer you are looking for, but perhaps this will help:  $$\left(3^{x}\right)^{2}=3^{x}\cdot3^{x}=3^{x+x}=3^{2x} $$ and $$\left(3^{2}\right)^{x}=\left(3\cdot3\right)^{x}=3^{x}\cdot3^{x}=3^{2x}.$$
In general, $$\left(x^y\right)^z=x^{yz}=(x^z)^y.$$
Comment: Note: This law only holds if the base/power are real... http://mathworld.wolfram.com/ExponentLaws.html
Answer: Consider the following theorems (with proofs): Power of Power and Power of Product. These results should help you understand the concepts better. Needless to say, real multiplication is commutative.
Answer: http://hotmath.com/hotmath_help/topics/properties-of-exponents.html here is a pretty good collection of examples and explanations to your problem. it is a simple property of exponents.

What is the logic behind this answer?


Solving an equation for angle $\theta$

Question: The shape of the ellipse can be represented parametrically in terms of the angle $\theta$ around the cycle, assuming $\theta$ is measured clockwise from the point $(V_0-(V_0-V_\mathrm{max}),P_0)$:
$$P=P_0+(P_\mathrm{max}-P_0)\sin{\theta}\tag{1a}$$
$$V=V_0-(V_\mathrm{max}-V_0)\cos{\theta}\tag{1b}$$
There are two angles $\theta$ at which adiabats are tangent to the ellipse.  These two angles can be obtained by substituting Eqns. 1 into Eqn. 3
$$dQ=\frac{1}{R}[(C_v+R)PdV+C_VVdP]\tag{3}$$
with $dQ = 0$.
So what I did was deriving $P$ and $V$ wrt the angle:
$$dP = (P_{max} -P_0)\cos \theta$$
$$dV = -(V_{max} -V_0)\sin \theta$$
And plugging it into 3:
$$0=[-(C_v+R)P(V_{max} -V_0)\sin \theta+C_VV(P_{max} -P_0)\cos \theta]$$
This above equation is satisfied by two $\theta$ angles. But how to solve it?
This is what I have been told:
There are two angles $\theta$ at which adiabats are tangent to the ellipse.  These two angles can be obtained by substituting Eqns. 1 into Eqn. 3 with $dQ = 0.$
More details: https://chemistry.stackexchange.com/questions/116757/how-to-get-the-efficiency-of-a-heat-engine-which-undergoes-an-elliptical-cycle/116770#116770
Answer: We assume the extremes in pressure are given by $P_1$ and $P_2=rP_1$ where $r$ is the pressure compression ratio so
$$P_0=\frac{P_2+P_1}2=\frac{r+1}2P_1$$
and then
$$P_{max}-P_0=P_2-P_0=rP_1-\frac{r+1}2P_1=\frac{r-1}2P_1$$
So on the ellipse
$$P=\left(\frac{r+1}2+\frac{r-1}2\sin\theta\right)P_1$$
Similarly the extremes in volume are $V_1$ and $V_2=sV_1$ where $s$ is the volume compression ratio, so on the ellipse
$$V=\left(\frac{s+1}2+\frac{s-1}2\cos\theta\right)V_1$$
The path is oriented such that $\theta$ decreases as the engine produces power. $P$ and $V$ then satisfy the equation
$$\frac{\left(V-\frac{s+1}2V_1\right)^2}{\left(\frac{s-1}2V_1\right)^2}+\frac{\left(P-\frac{r+1}2P_1\right)^2}{\left(\frac{r-1}2P_1\right)^2}=1$$
So
$$\frac{dP}{dV}=-\frac{\left(\frac{r-1}2P_1\right)^2}{\left(\frac{s-1}2V_1\right)^2}\frac{\left(V-\frac{s+1}2V_1\right)}{\left(P-\frac{r+1}2P_1\right)}$$
During adiabatic compression and expansion, $P$ and $V$ satisfy
$$PV^{\gamma}=\text{constant}$$
Where $\gamma$ is the ratio of specific heats: $C_P=C_V+R=\gamma C_V$. Then
$$\frac{dP}{dV}=-\gamma\frac PV=-\gamma\frac{\left(P-\frac{r+1}2P_1\right)+\frac{r+1}2P_1}{\left(V-\frac{s+1}2V_1\right)+\frac{s+1}2V_1}$$
If we equate our $2$ expressions for $\frac{dP}{dV}$ we get
$$\gamma\frac{\left(P-\frac{r+1}2P_1\right)^2+\left(\frac{r+1}2P_1\right)\left(P-\frac{r+1}2P_1\right)}{\left(\frac{r-1}2P_1\right)^2}=\frac{\left(V-\frac{s+1}2V_1\right)^2+\left(\frac{s+1}2V_1\right)\left(V-\frac{s+1}2V_1\right)}{\left(\frac{s-1}2V_1\right)^2}$$
We can substitute
$$\frac{V-\frac{s+1}2V_1}{\frac{s-1}2V_1}=\pm\sqrt{1-\left(\frac{P-\frac{r+1}2P_1}{\frac{r-1}2P_1}\right)^1}$$
And also let
$$y=\frac{P-\frac{r+1}2P_1}{\frac{r-1}2P_1}$$
And we get
$$\gamma y^2+\gamma\frac{r+1}{r-1}y=1-y^2\pm\frac{s+1}{s-1}\sqrt{1-y^2}$$
Since the adiabats are decreasing functions of $V$ we want solutions in the first and third quadrants so we take the plus sign when $y>0$ and the minus sign whe $y<0$. Squaring we get the horrible quartic equation
$$\left((\gamma+1)y^2+\gamma\frac{r+1}{r-1}y-1\right)^2=\left(\frac{s+1}{s-1}\right)^2\left(1-y^2\right)$$
We can solve to get solutions $-1<y_1<0$ and $0<y_2<1$ and then find $x_1=-\sqrt{1-y_1^2}$ and $x_2=\sqrt{1-y_2^2}$. Then $\theta_1=\text{atan2}\left(y_1,x_1\right)+2\pi$, $\theta_2=\text{atan2}\left(y_2,x_2\right)$. Then we have
$$dQ=\frac1R(C_V+R)P\,dV+\frac1RC_VV\,dP=\frac1{\gamma-1}\left(\gamma P\,dV+V\,dP\right)$$
$$\begin{align}Q_h&=\frac1{\gamma-1}\int_{\theta_1}^{\theta_2}\left[-\gamma\left(\frac{r+1}2P_1+\frac{r-1}2P_1\sin\theta\right)\frac{s-1}2V_1\sin\theta\right.\\
&+\left.\left(\frac{s+1}2V_1+\frac{s-1}2V_1\cos\theta\right)\frac{r-1}2P_1\cos\theta\right]d\theta\\
&=\frac{P_1V_1}{\gamma-1}\left[\gamma\left(\frac{r+1}2\right)\left(\frac{s-1}2\right)\sin\theta+\gamma\left(\frac{r-1}2\right)\left(\frac{s-1}2\right)\frac12\left(\theta+\sin\theta\cos\theta\right)\right.\\
&+\left.\left(\frac{s+1}2\right)\left(\frac{r-1}2\right)\cos\theta-\left(\frac{s-1}2\right)\left(\frac{r-1}2\right)\frac12\left(\theta-\sin\theta\cos\theta\right)\right]_{\theta_1}^{\theta_2}\end{align}$$
And
$$W=\text{Area}=\pi\left(\frac{s-1}2V_1\right)\left(\frac{r-1}2P_1\right)$$
And then we can get the efficiency
$$\eta=\frac W{Q_h}$$
So I worked this into a Matlab program
<code>% ellipse.m

clear all;
close all;

r = 2; % Pressure compression ratio: P2 = r*P1
s = 3; % Volume compression ratio: V2 = s*V1
gamma = 1.4; % Ratio of specific heats
F = [(gamma+1)^2 2*gamma*(gamma+1)*(r+1)/(r-1) ...
    ((s+1)/(s-1))^2-2*(gamma+1)+gamma^2*((r+1)/(r-1))^2 ...
    -2*gamma*(r+1)/(r-1) 1-((s+1)/(s-1))^2];
yvals = roots(F);
ind1 = find(~imag(yvals) & yvals < 0 & yvals > -1 & ...
    (gamma+1)*yvals.^2+gamma*(r+1)/(r-1)*yvals-1 < 0);
y1 = yvals(ind1);
x1 = -sqrt(1-y1^2);
theta1 = atan2(y1,x1)+2*pi;
theta1*180/pi
ind2 = find(~imag(yvals) & yvals > 0 & yvals < 1 & ...
    (gamma+1)*yvals.^2+gamma*(r+1)/(r-1)*yvals-1 > 0);
y2 = yvals(ind2);
x2 = sqrt(1-y2^2);
theta2 = atan2(y2,x2);
theta2*180/pi
Q1 = 1/(gamma-1)*(gamma*(r+1)*(s-1)/4*cos(theta1)- ...
    gamma*(r-1)*(s-1)/8*(theta1-sin(theta1)*cos(theta1))+ ...
    (s+1)*(r-1)/4*sin(theta1)+ ...
    (s-1)*(r-1)/8*(theta1+sin(theta1)*cos(theta1)));
Q2 = 1/(gamma-1)*(gamma*(r+1)*(s-1)/4*cos(theta2)- ...
    gamma*(r-1)*(s-1)/8*(theta2-sin(theta2)*cos(theta2))+ ...
    (s+1)*(r-1)/4*sin(theta2)+ ...
    (s-1)*(r-1)/8*(theta2+sin(theta2)*cos(theta2)));
Q = Q2-Q1
W = pi*(r-1)*(s-1)/4
eta = W/Q
theta = linspace(0,2*pi,400);
plot((s+1)/2+(s-1)/2*cos(theta),(r+1)/2+(r-1)/2*sin(theta),'b-');
title(['Elliptical heat engine for s=' num2str(s) ', r=' num2str(r) ...
    ', \eta=' num2str(eta)]);
xlabel('V/V_1');
ylabel('P/P_1');
hold on;
axis([0 s+1 0 r+1]);
c1 = ((r+1)/2+(r-1)/2*y1)*((s+1)/2+(s-1)/2*x1)^gamma;
V1 = linspace(1/2,s+1,400);
plot(V1,c1./V1.^gamma,'r-');
c2 = ((r+1)/2+(r-1)/2*y2)*((s+1)/2+(s-1)/2*x2)^gamma;
V2 = linspace(1,s+1,400);
plot(V2,c2./V2.^gamma,'k-');
hold off;
</code>
And plotted the ellipse and the critical adiabats in the $PV$-plane:
Comment: For a diatomic gas, $C_V=2.5R$ and $C_P=C_V+R=3.5R$. Then $\gamma=C_P/C_V=1.4$.
Comment: As for the quartic equation, I expanded mine out to the form $$ay^4+by^3+cy^2+dy+e=0$$. There is a [tag for quartic equations](https://math.stackexchange.com/questions/tagged/quartic-equations), you know. Since their solution implies solving a resolvent cubic, you probably also need the [tag for cubic equations](https://math.stackexchange.com/questions/tagged/cubic-equations). Rather than do all that I just used Matlab's [roots](https://www.mathworks.com/help/matlab/ref/roots.html) function. Then knowing $y=\sin\theta$ and $x=\pm\sqrt{1-y^2}=\cos\theta$ has the same sign as $y$...
Comment: Note we are working with a diatomic gas; $\gamma = 3.5$. Why are you using $\gamma = 1.4$?
Comment: Your answer is great. However, could you add how you got $\theta_1=195.0948° $and $\theta_2=30.2732°$? I am not acquainted with solving that kind of quadratic equations (you gave two lines of explanation but I still don't know how to get the angles).
Comment: Then Matlab has a function that is useful for rectangular to polar conversions, [atan2](https://www.mathworks.com/help/matlab/ref/atan2.html) which got me $\theta$. Since $\theta$ decreases as the engine produces work I needed to add $2\pi$ to my value for $\theta_1$ to make it bigger than $\theta_2$.

Solving an equation for angle $\theta$


Reducing crosstab size by frequency of responses

Question: Excuse my neophyte question - I'm new to R and pretty unversed in statistics.
I have a simple contingency table representing the number of queries per user for a group of web pages gathered over a period of time. There are about 15,000 total observations. This works out to a table of around 100 users viewing 50 groups of pages.
Since a 50x100 matrix is unwieldy to visualize, I would like to present a subset of this table sorted by the largest aggregates - either column (page groups), row (users), or perhaps even the largest row-by-column counts. For example I might choose the top 20 users and the top 10 groups, or the top 99% row-by-column counts.
Ideally, I end up with a table that still represents the major interactions between the most represented users and the page groups.
Is this a reasonable approach? Will I lose some large amount of statistical significance; and, is there a way to compare the before and after significance.
I must admit that I still don't know how to sort and subset a table based on two factors without resorting to row-by-column manipulation.
Comment: Take a look at the [stats.se](http://stats.stackexchange.com/faq) site -- your question might be a better fit there. If you think so, flag your question and ask a moderator to migrate it for you.
Comment: (oh, wait, flagging requires more points than you've got so far -- just reply with `@sarnold` in a comment and I'll happily cast the flag for you if you wish.)
Comment: Looks like a perfectly R-computable problem. What's missing is the code to produce the sample problem.
Answer: S <- trunc(10*runif(1000) )
R <- trunc(10*runif(1000))
RStab <- table(R, S)
str(RStab)
# 'table' int [1:10, 1:10] 6 12 10 13 10 7 8 6 9 10 ...
# - attr(*, "dimnames")=List of 2
#  ..$ R: chr [1:10] "0" "1" "2" "3" ...
#  ..$ S: chr [1:10] "0" "1" "2" "3" ...
 rowSums( RStab[ order(rowSums(RStab)) , order(colSums(RStab) ) ])
#  8   0   1   3   2   5   9   4   6   7
# 90  94  96  99 100 101 101 103 107 109
colSums( RStab[ order(rowSums(RStab)) , order(colSums(RStab) ) ])
  6   0   3   5   7   2   4   8   9   1
 80  91  94  96  98 100 106 109 112 114

The 5 highest marginals for row and columns:
RStab[ order(rowSums(RStab)) , order(colSums(RStab) ) ][ 6:10, 6:10]
#-------------
   S
R    2  4  8  9  1
  5 14 10 12 10 12
  9  6  8  9 10 13
  4 10 10  8  8 18
  6  9 12 12 17  8
  7 14 10 14 12  9

It does sound as though you might be a little shakey on the statistical issues. Can you explain more fully what you mean by "losing a large amount of significance"? What sort of statistical test were you thinking of?
Comment: @sarnold - Thanks for the pointer to the [link](stats.se) site - I was able to immediately find a good example of what I was trying to do. No need to cross-post, but thanks for the offer.
Comment: yes, I am shakey. Most of my knowledge comes from social psych studies about 40 years ago - and that was just as a CS student. Thank you very much for the excellent example - it is directly applicable to what I need.


What does check_markup() actually do?

Question: The following code:
var_dump(check_markup('This is a test', 'plain_text'));

outputs:
string(22) "
This is a test
"

Why does it do this?
Comment: I was looking in drupal and it looks like it does this:

Display any HTML as plain text

Convert URLs into links

Convert line breaks into HTML (i.e.  and )
Answer: check_markup() will:

Run all the enabled filters on a piece of text.

Since one of those filters will probably be the HTML corrector, you'll get the

 tags wrapping your text string.
Answer: It depends from the input filters enabled for the input format. By default, for the "Plain text" input format, they are the following ones.

"Convert URLs into links," and "Convert line breaks into HTML" add HTML tags into the text.

What does check_markup() actually do?


References on number of features to use in Random Forest Regression

Question: The default number of features $m$ used when making splits in a random forest regression is $m=p$ in Python's sklearn, where $p$ is the number of predictors in the regression problem (see the sklearn docs: If auto, then max_features=n_features).  In R's randomForest package, the default number of features used when making splits in a regression problem is $m=p\,/\,3$ (see the randomForest docs, and specifically the mtry argument to randomForest).
This point is (briefly) discussed at https://github.com/scikit-learn/scikit-learn/issues/7254, where an sklearn contributor says that $m=p$ is recommended. I've seen the $m=p\,/\,3$ recommendation in several places (e.g. https://stackoverflow.com/questions/23939750/understanding-max-features-parameter-in-randomforestregressor and https://web.stanford.edu/~hastie/Papers/ESLII.pdf)
My general understanding is that $m$ should always be tuned in random forest regression problems, and that the optimal $m$ could vary depending on the setting. Are there any references that discuss $m$ specifically in the context of regression (as opposed to classification)?  Is there any well-founded reason to prefer either R's or sklearn's default value for $m$ (or should the answer be "don't use the default, always tune," so that the default doesn't matter)?
Comment: Authoritative literature on selecting values of m is hard to find. Leo Breiman's paper https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf uses log(M + 1) where M is number of variables. But gives experimental justification. I guess log or square roots or even n_features/constants are used  to reduced computation cost and not for accuracy arguments. So tuning should be the way to go, but albeit not using the sklearn default.
Comment: I've always been suspicious that the default is straight bagging.  There are other bizarre defaults in sklearn, `subsample = 1.0` in gradient boosting.
Comment: What's wrong with the paper that the github link you posted links to? They vary the choice of $m$ from $1$ to $p$ and show that in almost all cases *for regression* their best results were at $m=p$
Comment: @Dan the accepted answer (below) covers that point:  "However, the paper they cite is about 'extremely randomized trees', not standard random forests. Extremely randomized trees choose completely random split points, whereas random forests optimize the split point."
Answer: According to Elements of Statistical Learning (section 15.3):

Recommended default values are $m = p/3$ for regression problems and $m = \sqrt{p}$ for classification problems (attributed to Breiman)
The best value of $m$ depends on the problem, so $m$ should be treated as a tuning parameter.

As discussed by Breiman (2001), the generalization error of a random forest decreases with the generalization error of the individual trees, and with the correlation between trees. Subsampling features is a way to decorrelate the trees. Increasing $m$ makes individual trees more powerful, but also increases their correlation. The optimal value of $m$ achieves a tradeoff between these two opposing effects, and typically lies somewhere in the middle of the range. He states that, in regression problems (compared to classification problems), the generalization error of individual trees decreases more slowly with $m$, and the correlation between trees increases more slowly. So, a larger value of $m$ is needed. This would explain why the commonly recommended default values for $m$ scale faster with $p$ for regression problems than classification problems. However, I didn't see an explicit recommendation for $m = p/3$ in this paper.
Regarding scikit-learn's default setting of $m=p$: As mentioned above, subsampling features is one of the essential properties of random forests, and improves their performance by decorrelating the trees. Setting $m=p$ would remove this benefit, and would make the model equivalent to simple bagged trees. Breiman (2001) showed that this gives inferior performance on regression problems. Someone on the scikit-learn github page you linked claimed that $m=p$ is indeed recommended. However, the paper they cite is about 'extremely randomized trees', not standard random forests. Extremely randomized trees choose completely random split points, whereas random forests optimize the split point. As above, good performance requires a balance between strengthening the individual trees and injecting randomness to decorrelate them. Because extremely randomized trees inject a higher degree of randomness in the split points, it makes sense that they would benefit by compensating with searching over more features to split on. Conversely, random forests fully optimize the split points, so it makes sense that they would benefit by subsampling features to increase randomness.
References:
Breiman (2001). Random Forests.
Hastie, Tibshirani, Friedman (2009). The Elements of Statistical Learning.
Comment: +1, but why are these values recommended, and why do other authors disagree? I'm aware of the ESLII recommendation, but where does it come from?
Comment: I edited the post to add more information. Hopefully it addresses your questions a bit more. Regardless of any default values, I think the proper approach is to tune $m$


print value of a column in django

Question: How to print the test field in the following query in django
res=Resources.objects.filter(test=request.profile)
logging.debug(test) # won't work

I wanted to check what this value is compared with..
Answer: You have to iterate through res and print each model's value of test in turn.
Answer: You may also try the values_list method, eg:
Resource.objects.filter(test=request.profile).values_list("test")

It returns a list of tuples with the value of "test" for each matched record.

print value of a column in django


cookie is being stored as different value

Question: I have the following code:

if(isset($ret["token"])) {
    drupal_set_message("TOKEN: " . $ret["token"]);
    user_cookie_save(array("my_token"=>$ret["token"]));
    drupal_set_message("KEY: " . $_COOKIE['Drupal_visitor_my_token']);
  }

Here is the printout of values:
TOKEN: 339497878
KEY: 354541465

Why am I getting different values?
Comment: why the down vote?
Comment: Probably for similar reason as the close vote? It's pretty basic question about how pretty basic aspect of HTTP works.
Answer: $_COOKIE superglobal contains values that was in cookies at the moment of HTTP request. Setting new cookies does not affect / update this array - new value will be available at next page load.


Googlebot asks for png and then my whole Heroku site crashes. What is going on?

Question: Two days in a row my site has gone down and started responding with Error 500 to every request. Both times, I found this in the logs.
Started GET "/apple-touch-icon-precomposed.png"
Processing by ShopsController#index as PNG
Parameters: {"page"=>"apple-touch-icon-precomposed"}
Completed 406 Not Acceptable in 25ms
F, [2013-09-06T04:15:13.827363 #2] FATAL
ActionController::UnknownFormat (ActionController::UnknownFormat)

Followed immediately by hours of
ActiveRecord::ConnectionTimeoutError

(could not obtain a database connection within 5.000 seconds)

and responding with 500 errors until I restart the server. I have increased the pool size, but I still can't understand why Googlebot asking for a PNG makes the database freak out and the whole site go down.
Answer: The image should be requested as /assets/apple-touch-icon-precomposed.png. Without the /assets part it is delegated by the router to ShopsController#index, something you don't want.
Comment: But I have no control over how it gets requested. Googlebot has just decided to request that. I don't have any apple-touch-icon-precomposed.png on my site.


Test whether cross-sectional dependence in panel data follows known (network/spatial) structure

Question: I want to test whether cross-sectional dependence in one specific variable (y) in panel data format follows a known structure (W) (e.g. network, spatial dependence), after controlling for individual fixed effects and time fixed effects. The aim is simply to show that this structure is describing cross-sectional dependence in a statistically significant way.
My first idea was to look into the spatial econometrics literature. Here, W would be the spatial weight matrix. For purely cross-sectional data, Moran's I would probably be the relevant test but I am unsure how and whether this measure can be applied to panel data.
What would be the correct way of testing a known cross-sectional dependence structure on a panel of one variable, after controlling for individual fixed effects and time fixed effects? Any guidance and help would be very much appreciated! Thank you very much in advance.
Answer: Maybe you a looking for the local variant of Pesaran's CD (cross-sectional dependence) test?
Have a look at the literature cited in the R package plm for function pcdtest (pcdtest has an argument W to define a spatial property), e.g., on the web here: http://rdocumentation.org/packages/plm/versions/2.4-1/topics/pcdtest:

Baltagi BH, Feng Q, Kao C (2012). "A Lagrange Multiplier test for
cross-sectional dependence in a fixed effects panel data model."
Journal of Econometrics, 170(1), 164 - 177. ISSN 0304-4076,
https://www.sciencedirect.com/science/article/pii/S030440761200098X.
Breusch TS, Pagan AR (1980). "The Lagrange Multiplier Test and Its
Applications to Model Specification in Econometrics." Review of
Economic Studies, 47, 239–253.
Pesaran MH (2004). "General Diagnostic Tests for Cross Section
Dependence in Panels." CESifo Working Paper Series, 1229.
Pesaran MH (2015). "Testing Weak Cross-Sectional Dependence in Large
Panels." Econometric Reviews, 34(6-10), 1089-1117. doi:
10.1080/07474938.2014.956623, https://doi.org/10.1080/07474938.2014.956623.


Notes on treble line extend down to bass line

Question: What is happening when some notes extend down from the treble to the bass on this piano score? Piece is 'Wandering Sprite' by JC Engelbrecht
Comment: Welcome! Can you clarify a bit what you mean by "what is happening"? The notes take up a beat, and some are on treble clef and some on bass. Is the question what these pitches are, or why they're beamed together? Sometimes you see something similar but with the beam between the staves.
Answer: All of the notes that are beamed together, beginning in the treble stave but descending into the bass stave, are to be played by the right hand. As has been pointed out, it's easier to read than using multiple leger lines.
One sees this with some frequency in more advanced piano literature — the notes from one staff encroaching on another staff. It's typically clear from context, such as beaming, which hand is intended to play those notes.
Here's an example from Chopin's Etude in A minor, Op. 25, No. 11, mm. 7–8. It's clear in m. 8 that the right-hand line is continuing into the left-hand staff. An additional benefit of writing this way, beyond the absence of leger lines, is that it's easy to see that the left and right hands are playing relatively close together.

(Image Source: IMSLP, Mikuli edition)
It's slightly less common to see the left-hand part move into the right-hand staff, but it does happen. In the below example from Chopin's Etude in C Minor, Op. 25, no. 12, mm. 1–2, by extending the left hand into the right-hand staff, the relationship between the two hands' parts is made visually more clear than using leger lines or changing clefs within the left-hand staff.

(Image Source: IMSLP, Mikuli edition)
Comment: Cross-stave notation doesn't necessarily define which hand should play what.  It's just a neat way of notating a musical line when it would otherwise require a lot of ledger lines.  (Though in your examples, the hand distribution is pretty clear.)
Answer: It means that a musical line drops below treble clef range, so rather than using lots of ledger lines it's more convenient to notate them in the bass clef.
In itself, this notation tells us nothing about which hand should play the notes.   But in this case it's pretty clear that the RH continues to play the cross-stave notes.  After all, how ELSE could it all be played?
In cases where it isn't abundantly obvious which hand plays what, a 'RH' or 'LH' instruction may be added, and the player may or not follow the suggestion.
(And it IS just a suggestion.  The composer gets to decide what notes get played, ultimately it's the player choice how to achieve them.)
Comment: Actually, all the composer gets to decide is what notes the performer should be instructed to produce.  If the performer is for whatever reason unable to perform the notes as written, the performer is going to determine what if anything gets played instead.
Comment: "It's more convenient to notate them in the bass clef" — that could be accomplished by changing the clef within the upper staff.
Comment: @Aaron Yes, that's another possibility.   But this way when the musical line goes down it LOOKS as if it goes down, which is a lot clearer to read.
Comment: @Laurence I'm saying the language in your post should be more specific. It's not just that they're notated in the bass clef, it's that they're notated in the lower staff.
Answer: This is probably a better way to write out low notes than using leger lines. At least it tidies things up, and means reading the lower notes is simpler. How one would write those lower notes on leger lines in the space usually provided beggars belief!
Comment: It would only require 4 ledger lines, which is not at all unheard of.
Answer: I guess from that C you're supposed to just go down to Ab.
Answer: If notes on the treble line extend down to the bass line, this means that the music contains notes that are in the bass clef register but are written on the treble staff. In this situation, the notes are played on a lower-pitched instrument, such as a bass guitar, piano, or cello, but the composer has chosen to write them on the treble clef staff for ease of reading. This technique is commonly used in music notation, particularly in orchestral or ensemble music where different instruments play different parts, and it allows the composer to convey the musical ideas clearly without having to switch between staves frequently.
Comment: No.  This is all played on piano!
Comment: Do you have a source to support any of this?  Unless the two staves were labeled with different instrument names, I would not consider this to possibly be the composer's intent.
Comment: This answer seems to discuss a different sort of situation than this question; for instance, it seems more relevant to moments in which one part contains a cue replicating another instrument's part, and some of the language seems to be about ledger lines. Was this answer perhaps generated by an AI?


HTML5, usar  numa  para digitar uma das

Question: tudo bom? Seguinte, eu tenho uma select dentro de um html, veja:

 <select>
  <option selected="selected" value>...</option>
  <option>opção 1</option>
  <option>opção 2</option>
 </select>

Eu tentei usar um input para digitar, ao invés de selecionar a option clicando.
Mas o input fica de lado, como se não fizesse parte da select
Minha dúvida é; realmente é possível fazer isto, digitar para selecionar as option, invés de selecionar clicando?
Agradeço desde já.
Comment: Saiba mais sobre datalist https://pt.stackoverflow.com/questions/197571/pra-que-serve-a-tag-datalist/197573#197573
Comment: @LeoCaracciolo já até inclui o link na resposta! Bem completo o material lá!
Comment: @LeoCaracciolo Valeu! eu realmente não achei, porque estava pesquisando de um jeito errado. Ainda bem que você e o Hugo me ajudaram. Abraços
Answer: Cara não sei se vai servir exatamente para vc, mas as vezes o <datalist> te atende.
Link sobre a tag: https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/datalist
A diferença entre um <select> e um <datalist> é que no select vc determina as opções que o usuário é "obrigado" a escolher entre elas. Já o datalist vc oferece algumas sugestões para o usuário, mas ele é livre para digitar o que quiser, ou seja, é uma lista pre-definida, não uma lista pre-determinada como a select.

The <datalist> element represents the list that represent predefined
  options for other controls.

Traduzindo: O elemento <datalist> representa a lista que representa opções predefinidas para outros controles.
Fonte oficial W3C: https://www.w3.org/wiki/Html/Elements/datalist
Dica: Apesar de não ser o foco dessa pergunta aqui tem outra Pergunta que foi feita aqui no Stackoverflow e que tem mais informações sobre essas duas tags: Pra que serve a tag </datalist>?
Veja o exemplo da datalist funcionando.

<input list="browsers" />
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
</datalist>
Comment: Sofri muito já com autocomplete num `input`... Nem conhecia essa tal `datalist`. ;O
Comment: exatamente o que eu precisava mano! Eu sou iniciante ainda, eu estava o dia inteiro tentando pesquisar como colocar um input dentro de uma select, mas nao sabia que existia uma tag que fazia o que eu precisava... muito obrigado pelos links e pela resposta, pode ter certeza que eu vou estudar muito.
Comment: @MSHijo isso meu jovem! Estudo! Principalmente as fontes oficiais, mesmo parecendo ser um texto mais chato, com certeza é o texto mais certo! Mas a principal linguagem que vc tem que aprender é o inglês, não se esqueça dela, pois infelizmente 90% do conteúdo em PT é copiado do Inglês e cheio de "lacunas". Então leia e tire sempre suas próprias conclusões. Sucesso! []´s
Comment: @MSHijo essa resposta tem mais umas informações sobre o Datalist que podem te ajudar a entender o funcionamento da tag e a diferença para a Select https://pt.stackoverflow.com/questions/197571/pra-que-serve-a-tag-datalist
Comment: @LipESprY-defolga- Em algumas situações é bem útil e fácil de implementar :D
Comment: Justamente. Quando precisei, fiz um "webservice" que retornasse um JSON, daí uma requisição ajax retornava esse JSON e por fim jogava no .autocomplete do jQuery-UI. Mó mão de obra comparado a esse datalist ser populado direto na renderização da página. kk

HTML5, usar  numa  para digitar uma das


Não consigo formatar data

Question: Estou tentando formatar uma data para ficar igual a outra, a primeira vem direto do banco mas a outra precisa estar no mesmo formato.
Calendar cal = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String d = df.format(cal.getTime());

Date antigo = rs.getDate("datapi");
DiasUteis du = new DiasUteis();

Date data = new SimpleDateFormat("yyyy-MM-dd").parse(d);

System.out.println(antigo + " - " + data);

O resultado é o seguinte:

2017-10-03 - Mon Jul 02 00:00:00 BRT 2018
Answer: Supondo que rs é um java.sql.ResultSet

Primeiro, uma explicação do que acontece.
O método rs.getDate() retorna um java.sql.Date, e o código só funciona porque esta é uma subclasse de java.util.Date. Mas o objeto que está lá na variável antigo é um java.sql.Date.
Já o método SimpleDateFormat.parse() retorna um java.util.Date.
Quando você imprime ambas com System.out.println, internamente ele chama o método toString() destas classes. E em cada uma delas este método retorna a data em um formato diferente:

em java.sql.Date, é usado o formato ISO 8601 (2017-10-03)
em java.util.Date, é usado esse outro formato (que não lembro se tem um nome específico): Mon Jul 02 00:00:00 BRT 2018

Mas isso não quer dizer que a data está nesse formato. Na verdade, conforme já dito aqui, aqui e aqui, datas não têm formato.
Provavelmente o campo no banco de dados é de algum tipo de data (como DATE, DATETIME, TIMESTAMP, etc, depende do banco), e internamente só são gravados valores (geralmente os valores numéricos da data, ou qualquer outra representação interna, não importa).
O que o método toString() faz é converter estes valores para um texto (uma String) em algum formato específico, mas isso não quer dizer que a data está nesse formato.
Se eu quero uma data (valores numéricos do dia, mês, ano, etc), eu uso os respectivos objetos (Date, Calendar, etc).
Se eu quero os valores da data em um formato específico, eu gero uma String usando classes específicas para este fim, como por exemplo SimpleDateFormat.

Agora vamos ao seu código:
Calendar cal = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String d = df.format(cal.getTime());

Aqui você criou uma String (a variável d), que contém a data atual (retornada por Calendar.getInstance()), no formato "ano-mês-dia". Por que você simplesmente não imprimiu esta data, já que ela está no formato que você precisa? (a menos que não seja esta a data que você quer imprimir).

Date antigo = rs.getDate("datapi");

Aqui você está obtendo o java.sql.Date. Se você quer esta data no formato correto, basta chamar antigo.toString(), que retorna uma String no formato "ano-mês-dia".

Date data = new SimpleDateFormat("yyyy-MM-dd").parse(d);

E aqui você está transformando a String d em um java.util.Date. Isso é desnecessário, pois o d já contém uma String com a data no formato que você quer (e mesmo que fosse necessário, você poderia usar a variável df criada anteriormente, ao invés de criar outro SimpleDateFormat).
Enfim, se você tem um objeto Date e quer gerar uma String em um formato específico, use SimpleDateFormat e o método format, passando o Date como parâmetro.
Answer: Calendar cal = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String d = df.format(cal.getTime());

Date antigo = rs.getDate("datapi");
DiasUteis du = new DiasUteis();

Date data = new SimpleDateFormat("yyyy-MM-dd").parse(d);

System.out.println(antigo + " - " + df.format(data));

Você poderia testar o código acima e comentar qual foi o resultado?

Não consigo formatar data


why use protocol buffers in java

Question: Recently,I read code of HBase.I find client use protobuf to communicate with server in HBase's code.
Java has "Serializable". why not use it?
Comment: If you do not see a reason preventing you from using `Serializable` in your project, then you should use `Serializable` in your project.
Comment: @dasblinkenlight: I would disagree - just because you don't *know* about Java serializations flaws doesn't mean they won't bite you.
Answer:
Efficiency: protocol buffers are generally much more efficient at transmitting the same amount of data than Java binary serialization
Portability: Java binary serialization is not widely implemented outside Java, as far as I'm aware (unsurprisingly)
Robustness in the face of unrelated changes: unless you manually specify the serializable UUID, you can end up making breaking changes without touching data at all in Java. Ick.
Backward and forward compatiblity: old code can read data written by new code. New code can read data written by old code. (You still need to be careful, and the implications of changes are slightly different between proto2 and proto3, but basically protobuf makes this a lot easier to reason about than Java.)
It's a lot easier to accidentally introduce non-serializable members into Java binary serialization, as proto descriptor files are all about serialization... you can't refer to an arbitrary class, etc.

I've worked on projects using protocol buffers, and I've worked on projects using Java binary serialization - and I would be very reluctant to use the latter again...
Answer: Protocol Buffers is an open serialization protocol.  You could write a client in C++ or C# and still be able to communicate with the server if both ends are using the same Protocol Buffer schema.  Java Serializable is Java only

why use protocol buffers in java


Sessions Table Getting Huge

Question: Currently, my sessions table is 1.6gb with 3,956,161 total rows. I think the sessions does not expired. I have a default settings in my settings.php as follows:
ini_set('arg_separator.output',     '&');
ini_set('magic_quotes_runtime',     0);
ini_set('magic_quotes_sybase',      0);
ini_set('session.cache_expire',     200000);
ini_set('session.cache_limiter',    'none');
ini_set('session.cookie_lifetime',  2000000);
ini_set('session.gc_maxlifetime',   200000);
ini_set('session.save_handler',     'user');
ini_set('session.use_only_cookies', 1);
ini_set('session.use_trans_sid',    0);
ini_set('url_rewriter.tags',        '');

is the variable above related to sessions table? If yes, what is the recommended settings to expire the session after 2 days?
Update:
I just found that this is due to OS limitation of ubuntu which I am currently using. This was explain at this drupal module: https://drupal.org/project/session_expire
The problem is, Session Expire module is still in alpha release.
Is there any other module that can do this same?
Comment: You are wrong. They are related. I'm glad i've found the answer.
Comment: I wrote they are not related *directly*. Of course if you found your answer, you are most welcome to post it.
Comment: Nope, variables above are not related to session table directly. Also, asking for resources is not a good thing to do, see help center. If you would ask something more practical, like "how to prevent session table growth" or "how to make sessions expire", it would be more useful for future. Last but not least, ever considered moving sessions out of DB?
Answer: While waiting for an answer, I found the solution at this blog.
All you need to do is to edit the settings.php under /sites/default folder.
Here are the two variables that need to be set:
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

Be sure to change also the cache expiry of the following variable according to your needs:
ini_set('session.cache_expire',     3600);
ini_set('session.cookie_lifetime',  3600);
ini_set('session.gc_maxlifetime',   3600);

The default is 200000. 3600 is equavalent to 1 hour.

Sessions Table Getting Huge


How to set user flood limit role wise?

Question: If user account is locked after entering wrong password 5 times. That's a default setting.
That can be changed via
drush cset user.flood user_limit 10

I have different roles. I need to set flood user_limit role wise
Role A, It will be 10
Role B, It will be 7

Can we achieve same thing via CLI?
Comment: There are two modules `https://www.drupal.org/project/flood_settings` and `https://www.drupal.org/project/floodcontrol_settings_api` you can modify them or extend them.
Answer: No you can't.
The user.flood user_limit config setting feeds into the DatabaseBackend::isAllowed() method as the $threshold arg, which is used to compare the row count for this query:
  $number = $this->connection
      ->select(static::TABLE_NAME, 'f')
      ->condition('event', $name)
      ->condition('identifier', $identifier)
      ->condition('timestamp', REQUEST_TIME - $window, '>')
      ->countQuery()
      ->execute()
      ->fetchField();

It only compares the threshold login count against a unique user ID, $identifier.
You'd have to do some sort of modification to the flood core service to make some sort of per-role flood limit.
Comment: Since the question is asking how to achieve it from the command line interface, this is the only possible answer. Replacing a Drupal service would be one of the alternatives, but writing an answer about that would make the answer too long, considering the question isn't even showing any knowledge of what that means.

How to set user flood limit role wise?


Querying deep nested json value from postgresql

Question: I would like to count distinct values from someText property from nested jbson object, but I can't figure out how properly do it. Any suggestions are appreciated.
This is my jbson object
{ options: [
        {
            "object": { "someText": "example1"}
        },
        {
            "object": { "someText": "example2"}
        },
        {
            "object": { "someText": "example3"}
        }
    ]
}

This is my query:
SELECT COUNT(distinct option_tb) AS uniqueOptions FROM tableT
WHERE option_tb->'options'->0 IS NOT NULL
AND option_tb->'options'->>'object'-> 'someText' is not null

Answer: You can use set-returning jsonb_path_query():
SELECT COUNT(distinct v) AS uniqueOptions FROM tableT,
jsonb_path_query(option_tb,'$.options[*].object.someText?(@!=null)') as _(v);

This produces implicit lateral join with your table, each option_tb spawning one row per match found by the function. No match means no rows returned. You will end up counting all possible distinct values of someText in all rows. This also doesn't mind varying jsonb structures with missing elements in some rows: demo
create table tableT (option_tb jsonb);
insert into tableT values
('{ "options": [ {"object": { "someText": "example1"}},
                 {"object": { "someText": "example2"}},
                 {"object": { "someText": "example3"}},
                 {"object": { "someText": null}}      ]}'),
('{ "options": [ {"object": {"someText": "example4"}} ]}'),
('{ "options": [ {"differentObject": { }            } ]}'),
('{ "options": []}'), ('{ "options": {}}'),
('{ "options": "hello"}'), ('{ "notEvenOptions": 1}'),
('[]'),('{}'),('1'),('"a"'),('false'),('"null"'),('null'),(null);

SELECT COUNT(distinct v) AS uniqueOptions,array_agg(distinct v) FROM tableT,
jsonb_path_query(option_tb,'$.options[*].object.someText?(@!=null)') as _(v);

uniqueoptions
array_agg

4
{""example1"",""example2"",""example3"",""example4""}

Note that null comparison in JSONPath expressions works differently from plain SQL: in SQL v=null yields null regardless of the v value. In JSONPath, it works like v is null.

To get the same result in versions 9.4 to 11 that didn't yet support JSONPath expressions, with a bit of care you can use jsonb_array_elements(), similar to what @SelVazi suggested: demo
SELECT count(distinct v) AS uniqueOptions, array_agg(v) FROM (
    SELECT v#>'{object,someText}' AS v FROM tableT,
    jsonb_array_elements( case when 'array'=jsonb_typeof(option_tb->'options')
                          then option_tb->'options'
                          else '[]'::jsonb end) as _(v)
) as _(v) WHERE jsonb_typeof(v)<>'null';

It's good to remember that your tableT is actually tablet, unless you double-quote it.
Comment: What version of PostgreSQL are you on? This the JSONPath support was added in version 12. The oldest supported version is 11, and its support ends 3 weeks from now: [doc](https://www.postgresql.org/support/versioning/)
Comment: Thank you. I have tried the code above, but I getting an error: [42883] ERROR: function jsonb_path_query(product, unknown) does not exist Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Comment: Zegarek, thank you very much. The issue was with the version - 11 in my case. The first answer with jsonb_path_query() works fine.
Answer: You can use the jsonb_array_elements() function to turn a JSON array into rows :
select option_tb, count(opt->'object'->'someText')
from tableT
  cross join jsonb_array_elements(tableT.option_tb->'options') AS opt
group by option_tb

Demo here
Comment: Selvazi, thank you. This also works, but it's a bit slow copare with @ Zegarek answer. The is is probably the use of cross join.
Answer: Simply you can use operators and functions to achieve this for example:
SELECT COUNT(DISTINCT option_tb->>'someText') AS uniqueOptions
FROM tableT
WHERE option_tb->'options' IS NOT NULL;


What is the if statement doing in the code?

Question: edited = False
i, j = 0, 0
while i < len(s1) and j < len(s2):
    if s1[i] != s2[j]:
        if edited:
            return False
        edited = True
        j += 1
    else:
        i += 1
        j += 1
return True

What is the code doing in the if edited statement? So if it's False, it returns False?
Source: https://github.com/careercup/CtCI-6th-Edition-Python/blob/master/Chapter%201/5_One%20Away/OneAway.py
Comment: No, if it is *True*, the function returns False. `edited` is set True the first time `if s1[i] != s2[j]` is true, and the second time that test is true the function returns `False`.
Comment: edited is a boolean. you can use if to decide going into that branch or not.
Answer: No, if edited is True, the function returns False. edited is set True the first time if s1[i] != s2[j] is true, and the second time that test is true the function returns False.
The code tests if there is only one difference between the sequences s1 and s2; if there is just one change, the function returns True, otherwise it'll return False.


How to make my validateForm working?

Question: In a custom module of mine, I have two custom entities A and B with a one to many relationship from A to B.
This is Edit form for EntityB:

I want to have this check in validateForm: if 'Contact' (boolean) is checked, 'Adhérent' (entity_reference to EntityA) shouldn't be empty.
Here is my validateForm:
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $values=$form_state->getValues();
ksm($values);
    if ($values['estlecontact']['value']==1 && $values['adherentid']['target_id']==NULL) {
      $form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.'));
    }
  }

In this case, I should not have the error message and still...
What am I doing wrong?
Here is the result of ksm:
Comment: Hi, can you check and say if your logic is even entering inside the if statement ?
Comment: It is the case: I get the error message sent by `$form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.'));`
Answer: I figured it out!
this works:
$values=$form_state->getValues();
if ($values['estlecontact']['value']==1 && $values['adherentid'][0]['target_id']==NULL) {
  $form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.'));
}

Note that $values['adherentid'] is a mutliple value field. I was missing an array level. Adding [0] before accesing target_id solves the problem.
Comment: Nice that you found it.
I am not still used to kint. I preferred the output of the old dpm() command.
Lately I am using PHP storm copy path feature in the xdebug. it allows me to copy the structure in complex nested arrays
Comment: @sanzante thanks for adding details to the solution.

How to make my validateForm working?


Probability mass function

Question: The probability mass function of a random variable $X$ is 0 except at the point $X=0,1$ and $2$. at these points it has $P(0)= 3C^2$; $P(1) = 4C-10C^2$; $P(2) = 5C-1$ for values of $C>0$.
i) Determine the value of $C$,
ii) compute the values of $P(X<2)$ and $P (1<X ≤ 2)$.
iii) Suppose that the random variable $X$ assumes three values $0, 1$ and $2$ with probabilities $1/3, 1/6,$ and $1/2$ respectively. Obtain the distribution function.
Comment: Your question needed some editing to make the equations clear and fix a symbol that caused part of the question at the end to be cut off. If you need to make any other changes feel free to do so.
Comment: Please add the `[self-study]` tag & read its
[wiki](http://stats.stackexchange.com/tags/self-study/info). Then tell us
what you understand thus far, what you've tried & where you're stuck. We'll
provide hints to help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you is grounds for closing.
Comment: @whuber Now that I can see the reason for closure is because the question is written in a way to request and answer.  So I now concur with the decision to close. I also think that if the OP can rewrite the question in a way that is not demanding and adds the self study tag there is a possibility to reopen but I do not see that it would be appropriate for anyone to add to my answer since it is self study.
Comment: I'm voting to close this as off topic because the poster has not described their understanding or what they've attempted per community guidelines.
Comment: You need a self study tag.
Comment: I disagree with AdamO because the question can be viewed as a problem in elementary probability which in my interpretation can fall under the category of probability theory which is in the community guidelines.
Comment: @Michael Please discuss such disagreements on meta.  You are in an extremely small minority here: see the stated reason for closing.
Comment: @whuber I was just raising the point to let the OP know.  I know that my position is a stretch and I can understand the arguments for closer.  I see my statement as a way to be transparent to the OP rather than to argue with the five that chose to close.  So I do not think this should be discussed separately on meta.
Answer: Hint: i) Recognize that P(0)+P(1)+P(2)=1 and do the necessary algebra.
ii) Just need to use the value of C from part i) So add P(0) + P(1) for P(X<2) and P(1) + P(2) for the first part and P(2) for the second.
iii) The result is practically given to you. You just need to know how to go from the probability mass function to the cumulative distribution function.
Comment: Note that this is a rather elementary problem and some are voting to close.
Comment: +1 This is just the right approach to answering self-study questions: ask leading questions and provide informative hints.
Comment: @whuber I think I am learning.

Probability mass function


Can I block network access for a specific moment?

Question: Writing an iOS app, I neet to give the user the option to block the network access for this app only.
Is it possible doing that in code?
Meaning every call, made by whatever part of the code (and that's including static libraries) should be blocked for that particular moment.
Answer: You can use a custom NSURLProtocol that will intercept all your network calls.
That's exactly what I do in my OHHTTPStubs library to stub network requests (my library use then private API to simulate a network response, but in your case if you don't need to fake a response you can avoid these calls to the private API and use this technique in production code)

[EDIT] Since this answer, OHHTTPStubs has been updated and don't use any private API anymore, so you can use it even in production code. See my EDIT below at the end of this answer for some code example.

@interface BlockAllRequestsProtocol : NSURLProtocol
@end

@implementation BlockAllRequestsProtocol
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    return YES; // Intercept all outgoing requests, whatever the URL scheme
    // (you can adapt this at your convenience of course if you need to block only specific requests)
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { return request; }
- (NSCachedURLResponse *)cachedResponse { return nil; }

- (void)startLoading
{
    // For every request, emit "didFailWithError:" with an NSError to reflect the network blocking state
    id<NSURLProtocolClient> client = [self client];
    NSError* error = [NSError errorWithDomain:NSURLErrorDomain
                                         code:kCFURLErrorNotConnectedToInternet // = -1009 = error code when network is down
                                     userInfo:@{ NSLocalizedDescriptionKey:@"All network requests are blocked by the application"}];
    [client URLProtocol:self didFailWithError:error];
}
- (void)stopLoading { }

@end

And then to install this protocol and block all your network requests:
[NSURLProtocol registerClass:[BlockAllRequestsProtocol class]];

And to later uninstall it and let your network requests hit the real world:
[NSURLProtocol unregisterClass:[BlockAllRequestsProtocol class]];

[EDIT] Since my answer, I've updated my library which does not use any private API anymore. So anyone can use OHHTTPStubs directly, even for the usage you need, like this:
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest* request) {
    return YES; // In your case, you want to prevent ALL requests to hit the real world
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest* request) {
    NSError* noNetworkError = [NSError errorWithDomain:NSURLErrorDomain
                    code:kCFURLErrorNotConnectedToInternet userInfo:nil];
    return [OHHTTPStubsResponse responseWithError:noNetworkError];
}];

Comment: How would I use it to block only certain calls (lets say, based on the base url) ?
Comment: Simply implement the `canInitWithRequest:` method accordingly (instead of returning `YES`, return `[request.URL.absoluteString hasPrefix:...]` for example). _For more information, don't hesitate to read the `NSURLProtocol` documentation that explains it all._
Comment: This is VERY close to what I need, but still not exactly; as returning this error code doesn't 100% mimic a no-connectivity situation. I need that static lib to think there's no connection at all. Maybe we should go deeper than NSURLProtocol?
Comment: When you don't have any internet connection, you will get an NSError with code kCFURLErrorNotConnectedToInternet = -1009 (I just tested it to confirm). So you can simply mimic that. (I should have used -1009 instead of 500, will edit my answer)
Comment: The lib still reacts differently..something, somewhere is not identical.. :\
Comment: Maybe you should investigate on that "act differently". Do the requests of your lib still hits the real world? Does it goes thru your `NSURLProtocol` code when a lib's request is triggered? Are you sure the lib does not use low-level networking like sockets? (I can't investigate and debug all that for you…)
Comment: You're absolutely right! And I did all those tests..the connection indeed goes through the , and I managed to return my 'fail' response. Perhaps there are other calls that don't, maybe there's a usual reachability test that responsible for the difference. I guess I need to snif it and come back with better understanding..stay tuned.. :)
Answer: I dont think you can make the network connection blocked progamatically
Work Around
Keep a bool variable for blocking network.Check on every network call the value on variable.If block is set to yes Dont call any webservice.
Comment: Could take control of HTTP and HTTPS using NSURLProtocol and subclass the start/stop loading methods to your desire
Answer: I'm using a crittercism library that does network analysis on every single network call within the app, no matter if it's your own code or a third party library.
It's closed source, but from what I've seen from the occasional stack track, they are method swizzling methods on CFNetwork classes. These are pretty low level network classes which will be used by the higher level apis such as NSURLConnection (this is just my assumption).
So I'd start by looking there.
Comment: do you use their basic or pro plan?
Comment: If they are swizzling low level methods on CFNetwork, I would recommend not using the library.
Comment: I'm not positive they are doing this, but I remember seeing the word 'swizzle' when i was evaluating their forthcoming network product. This code isn't in their stable release.


Is it possible to declare option inside drupal_add_js?

Question: I'm stuck on including an external JavaScript file on a custom page. The API service requires the HTML to be formatted as below
<code><script type="text/javascript" src="//platform.example.com/api.js">
api_key:   [key]
</script>
</code>
No idea if this can be done the Drupal way. I tried:
<code>// load SDK
drupal_add_js('//platform.example.com/api.js', 'external');
drupal_add_js('api_key:   [key]', 'inline');
</code>
But without success. The API_key declaration need to be done inside the first  tag that links to the external JS. I know you can add extra parameters like documented on https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7.x but this case is not described.
Comment: I think what you're looking for is [here](http://drupal.stackexchange.com/questions/4482/how-to-send-variable-from-php-file-to-js-file-in-drupal-7)
Answer: You can try something like
<code>$external_js = array(
  '#markup' => '<script type="text/javascript" src="//platform.example.com/api.js">
    api_key:   [key]
  </script>',
);

drupal_add_html_head($external_js, 'my_module');
</code>


Hypothesis Test for mean vector of Multivariate Normal Distribution

Question: Given two independently $X_1$ and $X_2$ and that these are bivariately normally distributed with mean vector components $\mu_1$ and $\mu_2$ and variance-covariance matrix shown below:
If we want to test $H_0: \mu_1=0$ v.s. $H_a: \mu_1\neq 0$. How to show that the likelihood ratio test for testing $H_0$?
Comment: Please add the `self-study` tag and read its wiki.
Comment: You need to revise your solution to the constrained optimization problem. You can satisfy the constraint if $\mu_1 = 0$ or $\mu_2 = 0$ (or both). You need to solve each problem independently (setting one of the parameters to zero).  The solutions are of the form $(\mu_{1,constr},0)$ or $(0,\mu_{2,constr})$. Your current solutions don't look like this. After you have figured the solution to the two simpler problems, you need to figure out which solution has the largest log-likelihood.
Answer: A likelihood ratio statistic is equal to:
$$ \mathcal{L}(\hat{\mu}_{M}) - \mathcal{L}(\hat{\mu}_{constr}) $$
where $\mathcal{L}(\cdot)$ is the normal log-likelihood function, $\hat{\mu}_{M}$ is the maximum-likelihood estimator, and
$$ \hat{\mu}_{constr} = {\arg\max}_{\{\mu \in \mathbb{R}^2: \ \mu_1\mu_2 = 0 \}} \mathcal{L}(\mu) $$
You can easily solve for the constrained estimator by computing

The $\mu_1$ maximizer of $\mathcal{L}(\mu)$ given $\mu_2 = 0$.
The $\mu_2$ maximizer of $\mathcal{L}(\mu)$ given $\mu_1 = 0$.
Choose the solution with the largest likelihood.


Responsividade de colunas no BootStrap

Question: Tenho duas linhas com duas colunas, a primeira coluna da primeira linha tem uma imagem e a segunda coluna dessa linha tem um texto. A segunda linha tem um texto na primeira coluna e uma imagem na segunda.
Quando a responsividade acontece, fica imagem e texto um embaixo do outro e depois texto e imagem um embaixo do outro.
Eu preciso que quando ocorrer a responsividade, fique imagem e texto um embaixo do outro.
Como posso fazer isso?
Comment: Oi! Você pode mandar o trecho de código ou uma imagem de como deveria ficar?
Answer: Isso acontece porque a grade do bs usa alinhamento a esquerda, então realmente vai ficar imagem->texto->texto->imagem, mas você pode criar uma classe css específica para essas colunas usando @media{}, por exemplo:
Essas são as @media utilizadas pelo bootstrap4
@media (min-width: 576px) { ... }
@media (min-width: 768px) { ... }
@media (min-width: 992px) { ... }
@media (min-width: 1200px) { ... }

Então para dispositivos menores você pode fazer assim:
Primeiramente, definir o elemento pai com display:flex; e flex-direction: column;, depois definir a ordem da coluna:
@media (max-width: 768px) {//aqui você ajusta o tamanho máximo do display para ter a alteração
    .alinhamento{
        order:2;
    }
}

Basta atribuir a classe a coluna desejada, e a ordem será invertida.
EDIT: Claro que as alterações deverão ser feitas de acordo com a necessidade do seu código e da quantidade de elementos que você gostaria de alterar a ordem, relacionando seus posicionamentos no elemento pai.
Comment: Jovem não precisa colocar display flex é só colocar o *order*, pois o grid do BS4 já é *flex* por default
Comment: Obrigado @hugocsl, eu não tinha conhecimento disso, gratidão!
Comment: Tranquilo olha ali que na resposta que inclui um exemplo, repara que é só colocar o `order` e já é.
Comment: Então, pude ver só dps que comentei, pois comentamos ao mesmo tempo, mas bom que ficam dois aprendizados.
Comment: Depois da uma olhada no Utilites do BS4, la tem várias classes prontas para usar com display flex, olha ai https://getbootstrap.com/docs/4.0/utilities/flex/
Comment: Vou olhar sim, obrigado mais uma vez.
Answer: Com Bootstrap3 vc pode fazer usando display:flex e column-reverse apenas para as resoluções pequenas usando a medida @media do Bootstrap.
Veja como fica no exemplo abaixo. Mande exibir como "Pagina toda" para ver funcionando!

@media (max-width: 767px) {
  .row.reverse {
    display: flex;
    flex-direction: column-reverse;
  }
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Laboriosam, iure ab eos iste cum quam quo voluptatibus! Quae, dolor placeat?

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe expedita iure nesciunt, modi voluptate corporis voluptatum sunt ducimus magni delectus.

Para o Bootstrap 4 basta vc trocar a order dos elementos na medida @media que vc quiser. No caso na menor medida oficial 577px eu troquei a ordem, pois o grid do Bootstrap 4 já é flex por default
Veja como fica. OBS: Como a medida é 577px aqui ainda aparece um do lado do outro, mas se a tela for menor que isso vai quebrar direitinho, é só testar ai.

@media (max-width: 576px) {
  .col-sm-6.reverse {
    order: 2;
  }
}
 <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" />

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Laboriosam, iure ab eos iste cum quam quo voluptatibus! Quae, dolor placeat?

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe expedita iure nesciunt, modi voluptate corporis voluptatum sunt ducimus magni delectus.

Responsividade de colunas no BootStrap


Proving $\sqrt{5a^2+4ab}+\sqrt{5b^2+4bc}+\sqrt{5c^2+4ca}\ge 9$ when $ab+bc+ca=3.$

Question:
Problem. Let $a,b,c\ge 0: ab+bc+ca=3.$ Prove that $$\sqrt{5a^2+4ab}+\sqrt{5b^2+4bc}+\sqrt{5c^2+4ca}\ge 9.$$

A big trouble is around $(a,b,c)=(2,3/2,0).$
I've tried to square both side and we'll prove $$5(a^2+b^2+c^2)+4(ab+bc+ca)+2\sum_{cyc}\sqrt{5a^2+4ab}\cdot\sqrt{5b^2+4bc}\ge 81,$$
or $$5(a^2+b^2+c^2)+2\sum_{cyc}\sqrt{5a^2+4ab}\cdot\sqrt{5b^2+4bc}\ge 69.$$
We have $$a^2+b^2+c^2\ge ab+bc+ca=3,$$and it's enough to prove
$$\sum_{cyc}\sqrt{5a^2+4ab}\cdot\sqrt{5b^2+4bc}\ge 27.$$
By using CBS inequality $$\sum_{cyc}\sqrt{5a^2+4ab}\cdot\sqrt{5b^2+4bc}\ge \sum_{cyc}(5ab+4b\sqrt{ca})=15+4\sqrt{abc}\left(\sqrt{a}+\sqrt{b}+\sqrt{c}\right).$$
The rest is proving $$\sqrt{abc}\left(\sqrt{a}+\sqrt{b}+\sqrt{c}\right)\ge 3$$but $$3=ab+bc+ca\ge \sqrt{abc}\left(\sqrt{a}+\sqrt{b}+\sqrt{c}\right). $$

Hence, my approach is wrong. Could you please help me prove the starting inequality?
Thank you for your help.
Answer: EDIT: There is some problem in the original proof below. Specifically $p^3r\geqslant q^3$ does not necessarily hold. I found this inequality accidently at that time but did not check the correctness. So, sorry for my carelessness.
Here is a new proof (still complicated, though).
Our goal is to prove
$$
\sum\sqrt{5a^2+4ab}\geqslant9=3\sqrt{3(ab+bc+ca)}.
$$
We can prove
$$
\sum\sqrt{\frac{5a^2+4ab}{3(ab+bc+ca)}}\geqslant3.
$$
We can simplify the square root operation, by the following equality:
$$
\sqrt{t}\geqslant\frac{6t^3+20t^2+6t}{t^3+15t^2+15t+1},
$$
which can be derived from $(\sqrt t-1)^6\geqslant0\iff t^3+15t^2+15t+1\geqslant\sqrt t(6t^2+20t+6)$.
Therefore
$$
\sqrt t-1\geqslant\frac{(t - 1) (5 t^2 + 10 t + 1)}{(t + 1) (t^2 + 14 t + 1)}=:f(t).
$$
Let
$$
u=\frac{5a^2+4bc}{3(ab+bc+ca)},\, v=\frac{5b^2+4bc}{3(ab+bc+ca)},\, w=\frac{5c^2+4ca}{3(ab+bc+ca)}.
$$
It can be proved
$$
f(u)+f(v)+f(w)\geqslant0.
$$
It can be verified with the help of Mathematica. We can assume without loss of generality $c=\min(a,b,c)$. We need to consider both the case $c\leqslant a\leqslant b$ and $c\leqslant b\leqslant a$. The first case is simplier than the second. For the second case, the minimum is achieved only if $c=0$, so by the homogeneity we just need to consider $(a,b,c)=(a,1,0)$. The rest is just to verify the positiveness for all $a$ in such case.
The proof is done.
PS: If the estimation of $\sqrt t$ is based on $(\sqrt t-1)^4\geqslant0$ instead of $(\sqrt t-1)^6$, it seems the positiveness cannot be guaranteed in the case $c\leqslant b\leqslant a$.

Original answer

This is NOT a nice solution so only the idea is sketched.
You have proved $\sum\sqrt{5a^2+4ab}\cdot\sqrt{5b^2+4bc}\geqslant 15+4\sqrt{abc}\left(\sqrt{a}+\sqrt{b}+\sqrt{c}\right)$. Hence
$$
\sum\sqrt{5a^2+4ab}\cdot\sqrt{5b^2+4bc}\geqslant15+12(abc)^{2/3}.
$$
Then, in order to prove the original inequality, we just need to prove
$$
\begin{gathered}
\vphantom{\sum}\\
\impliedby\vphantom{a^2} \\
\impliedby\vphantom{a^2}
\end{gathered}
\begin{gathered}
5(a^2+b^2+c^2)+2\sum \sqrt{5a^2+4ab}\cdot\sqrt{5b^2+4bc}\geqslant 69\\
5(a^2+b^2+c^2)+24(abc)^{2/3}\geqslant39\\
5(a^2+b^2+c^2)+24(abc)^{2/3}\geqslant13(ab+bc+ca).
\end{gathered}
$$
This is true but in a short time I haven't found an elegant proof.
There is an ugly proof available. Let $a=x^3$, $b=y^3$, $c=z^3$, $p=x+y+z$, $q=xy+yz+xz$, $r=xyz$. We can prove
$$
5\sum x^6+24(xyz)^2\geqslant 13\sum x^3y^3,
$$
using the facts that
$$
\begin{gathered}
\sum x^6= p^6−6p^4q+6p^3r+9p^2q^2−2q^3−12pqr+3r^2,\\
\sum x^3y^3=q^3-3pqr+3r^2,\\
p^3r\geqslant q^3,\\
p^3r\geqslant 3pqr.
\end{gathered}
$$
After simplification, the only thing left is
$$
5p^6+45p^2q^2\geqslant5p^2\cdot 6p^2q,
$$
which is obvious.
Comment: @FurryNick You're right. I did not check the source in which the inequality $p^3r\geqslant q^3$ was given (just found it accidently). It turns out it's not reliable. I will give another proof later.
Comment: I check $a=2,b=3/2,c=0.$ Am I missing something?
Comment: I recommend that you avoid using "EDIT:".  Instead, revise the answer so it reads well for someone who encounters it for the first time.  I suggest deleting the old, incorrect answer.  The old version can still be found in the revision history.  We're looking to build an archive of knowledge that will be useful to others in the future.


How to detect that a given PE file (exe or dll) is 64 bit or 32 bit

Question: I need to detect whether a given .dll or .exe file is 32 bit or 64 bit
At the moment I have only one solution: read the PE Header from the specified file and take the 'Machine' field from there.
( Specification: Microsoft Portable Executable and Common Object File Format Specification (.docx file) at section "3.3. COFF File Header (Object and Image)" )
This field can take up to about 20 values. Three of them are:
IMAGE_FILE_MACHINE_I386  ( == 32bit )

IMAGE_FILE_MACHINE_IA64  ( == 64bit )

IMAGE_FILE_MACHINE_AMD64 ( == 64bit )

My questions:
1) Is 'Machine' to bitness mapping correct or did I miss something? Are there any other caveats?
2) Is there easier way to detect 32/64 bitness (probably some specific field in PE format I didn't notice or some special system function)?
Comment: dup: http://stackoverflow.com/questions/971689/win32-api-to-tell-whether-a-given-binary-exe-or-dll-is-x86-x64-or-ia64/971715#971715
Comment: That other question is asking about architecture, this one is asking about word size.
Comment: Documentation is updated from v8 to v11 as of now in 2017: http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
Answer: GetBinaryType(...) returns SCS_32BIT_BINARY for a 32-bit Windows-based application
and SCS_64BIT_BINARY for a 64-bit Windows-based application.
Comment: This unfortunately returns 0 when analyzing a DLL.
Comment: Made it in Python: import win32file; print win32file.GetBinaryType("myfile.exe"). This returns 0 for 32bits exe or 6 for 64 bits file.
Comment: This function fails when loading a non-matching arch (e.g. 64-bit DLL in 32-bit program).
Answer: Check this: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680339%28v=vs.85%29.aspx
Look for "Magic" member - you can find out whether PE header is 32 bit(PE32) or 64 bit(PE32+).


Animating color values in open gles 1.0 on Android

Question: I am working on an application in which I will perform some drawing using openGL. In this application I will draw a 3d-object with each vertex a different color. This can be done by using a colorpointer.
Now, my problem is that I would like these colors to animate over time.
As the color values are given using a buffer, I would have to either recreate the buffer every frame with new colors, or replacing the values in the buffer somehow (which is probably quite error prone). I also thought about the possibility of using two buffers and switching between them (drawing with one buffer, and changing the other, then switch).
And in any case, I would have to upload the buffer to the video memory every frame...
So, my question is this; how do I, as efficient as possible, animate the different colors of an object in GL10?
Note; It would of course be easy to do this using shaders in gles 2.0, but I would prefer it if I could just use GL10 (or 11) for this project.
Answer: Instead of using vertex colors, maybe you could come up with a clever way to use a texture instead, and animate this using the texture matrix? That way you wouldn't have to update your vertex buffers ever.
Comment: I was thinking about using textures, but the problem is that I (probably) would have to redraw the textures relatively often (and also upload the new texture to the video memory), which pretty much defeats my purpose of using opengl.


Show that $\ker f(T) = \ker d(T)$

Question: I'm having trouble solving the following question:

Let $T$ be a linear operator on $V$ with minimal polynomial $p(x)$ over $F$. Let $f(x)$ be any polynomial over $F$ and $d(x)$ be the greatest common divisor of $f(x)$ and $p(x)$. Prove that $\ker f(T) = \ker d(T)$.
Comment: Please make use of the body of the Question to give a full statement of the problem you want help with and provide some context for why the problem is important, interesting or challenging for you.  Simply posting an assigned exercise with no more context than "Please solve this for me, I'm having trouble" will often result in downvoting and/or closure of the Question.
Answer: Since $d=\gcd(f,p)$, there are polynomials $a,b$ such that $af+bp=d$.
Therefore, $d(T)=a(T)f(T)+b(T)p(T)=a(T)f(T)$.
This implies that if $f(T)x=0$, then $d(T)x=0$. In other words, $\ker(f(T))\subset\ker(d(T))$.
The converse is trivial. Since there is $c$ such that $f=cd$, then $f(T)x=c(T)d(T)x$. Therefore, if $d(T)x=0$, this implies that $f(T)x=0$. In other words $\ker(d(T))\subset \ker(f(T))$.
Comment: Thank you very much, I totally forgot about that theorem.

Show that $\ker f(T) = \ker d(T)$


Custom hover text, singular/plural (plotly.js)

Question: I'm building a scatter graph.
My X axis represents dates, and Y axis represents the number of responses given.
When mouse hovering, I'd like to show either:

1 response
OR
N responses

I suppose it is something to do with custom hovering, but can't see how to do it with the hoverinfo property of the trace or Y-axis.
Answer: You need to use the text attribute in the trace.
https://jsfiddle.net/abalter/n54k9zzj/
var data =
[
  {x: "2015-05-01", y: 5},
  {x: "2015-05-02", y: 10},
  {x: "2015-05-03", y: 0},
  {x: "2015-05-04", y: 1}
];

var x = [];
var y = [];
var text = [];
data.forEach(function(item, index)
{
  x.push(item.x);
  y.push(item.y);
  if (item.y == 0)
  {
    text.push("No responses");
  }
  else if (item.y == 1)
  {
    text.push("1 reponse");
  }
  else
  {
    text.push(item.y + " responses");
  }
});

var trace =
{
  x: x,
  y: y,
  text: text,
  hoverinfo: "text",
  mode: "markers",
  name: "Responses"
}

var yaxis =
{
    title: "Responses"
}

var xaxis =
{
    type: "date"
}

var layout =
{
  xaxis: xaxis,
  yaxis: yaxis
}

Plotly.plot
(
  "graph",
  [trace],
  layout
);

Answer: If you want custom text added , then try something like this :
var myText = "Namaste" ;

var trace = {
    x: [1,2,3],
    y: [4,5,6],
    z: [7,8,9],
    text: ["A","B","C"],
    hovertemplate: ' x: %{x}
 y: %{y}
 z: %{z}
 Placement:%{text}
 myText: ' + myText,
    mode: 'markers' ,
    type: 'scatter3d' ,
    marker: {
        size:3,
        color: 'rgb(112, 32, 130)'
    }
};

Note : Property "text", "hovertemplate" plays important role in adding your own custom text .
Comment: Note that you can use the keyword `%{text}` and `%{customdata}` in `hovertemplate` if you need more custom texts