How to compare correlation coeffecients across studies (meta-analysis, simulation-analysis)?

Question: I have one metric dependent variable (grain yield) and three metric traits, A, B and C. Grain yield and all three traits were measured in several studies and each time a Pearson correlation between trait and grain-yield was reported.
So I have correlation-coeffecients for each combination:
grain yield ~ trait A (around 50 correlation-coeffecient values)
grain-yield ~ trait B (around 50 correlation-coeffecient values)
grain-yield ~ trait C (around 50 correlation-coeffecient values)
What statistical test would I use to compare these three sets of correlation coeffecients to see which trait is a better predictor for grain yield?
(One could also think of a scenario where I am doing a simulation study and I look what experimental design allows to predict true values best, in fact this is what I am doing but the example above is easier to explain and understand)
Comment: But you need them if you want to compute the covariance between the three correlations that you are actually interested in.
Comment: Do you have the correlations between A and B, A and C, and B and C?
Comment: No, I don't. In my scenario these are also not of any importance.
Comment: I checked it and I found that I might be able to extract the correlations/covariances between them. But I am just wondering, can I not just do a one-way-ANOVA and a Tukey-test to compare the values?
Answer: You cannot just conduct a one-way ANOVA on the correlations because they are not independent. Within each study, you need to construct the variance-covariance matrix of the correlations (or the r-to-z transformed values). For this, you need to know the correlation between A and B, between A and C, and between B and C. You can find equations for the covariance between correlations in:
Olkin, I., & Finn, J. D. (1990). Testing correlated correlations. Psychological Bulletin, 108(2), 330–333. https://doi.org/10.1037/0033-2909.108.2.330
Steiger, J. H. (1980). Tests for comparing elements of a correlation matrix. Psychological Bulletin, 87(2), 245–251. https://doi.org/10.1037/0033-2909.87.2.245
So, for each study you then have 3 correlations (between grain yield and the three traits) and a 3x3 var-cov matrix. This can be used as input for a multivariate meta-analysis. See, for example:
Kalaian, H. A., & Raudenbush, S. W. (1996). A multivariate mixed linear model for meta-analysis. Psychological Methods, 1(3), 227-235. https://doi.org/10.1037/1082-989X.1.3.227
(this article is not focused on correlations, but the methods are the same). Chapter 16 from The Handbook of Research Synthesis and Meta-Analysis by Cooper et al. (2019) also discusses the required methods and is focused specifically on correlation coefficients. You can conduct such an analysis using the metafor package (for the code corresponding to chapter 16 above, see here) or the metaSEM package.


Need to combine 2 mysql queries

Question: So I want to determine how many hours have taken place since a period in time (compared to a timestamp) and then want to find out how many records I have since that timestamp (they're done hourly) and divide the two to get a percentage.   The two queries go like this:
Table design:
Historical --table
--ID --column with device id#
--TIME --DateTime Field with time entry was made
Query 1:
SELECT ID, min(TIME), timestampdiff(HOUR,NOW(), TIME) as uphours from Historical group by id

Query 2 (Despite how this query is written, I want it to do it for all the ID's in the table):
SELECT count(*) from Historical where ID 1

Then the final part would be:
uphours / secondQuery_return_value as Percentage

Can someone help me understand how to combine these queries?
Comment: can you post the schema for the table please, and I am not clear what you mean by "(Despite how this query is written, I want it to do it for all the ID's in the table)" - perhaps a little sample data and the desired output
Answer: Try something like:
SELECT ID, min(TIME), (timestampdiff(HOUR,NOW(), min(TIME))/count(*)) as Percentage
from Historical
group by id

Edit: as Mark Bannister mentioned, it should make more sense to change TIME for min(TIME) on the percentage, otherwise it won't be the actual difference between now and the oldest time...
Comment: This looks really promising, let me give it a whirl.
Comment: At the moment, `Percentage` will essentially be a random value since it's a function on `TIME`, not an aggregated function of `TIME` - should it be using min(`TIME`)?
Comment: And it works, excellent... now I wonder if I can combine two more... one more question and my work will be done.
Comment: @Damien.Bell I'm glad it works, and you should be able to combine as much as you want, just make sure they're grouped by the same criteria...
Comment: The new question is up, I'm stuck on the join aspect of it, it's getting to be pretty heinous... just trying to reduce the amount of queries that I'm making.

Need to combine 2 mysql queries


Guitar Fetish Pickups - Can anyone describe their tone and quality?

Question: OK. I have seen Guitar Fetish pickups at prices that seem insane compared to what most pickups cost - and they have things like humbucker sized P90s that are hard to find in any case. Their stuff looks great and they actually seem to know what they're talking about.
But I've never heard one. I don't have any friends who've taken the plunge and bought one. I'm reluctant to take a risk on any of these without a real human being reporting on it.

Based on your experience, are these pickups well-built, or are they noisy pickups that won't last?
How do they compare to, say, units built by Gibson or Seymour Duncan?
Can anyone describe the kind of tone they get, compared to other pickups?
Comment: I have the tele pickups from gfs and the active eq. I am very pleased with the tonal variation I can achieve with this setup. Much more variation then a passive system. The tone is clear and can sound like a stock Tele but with the mids cranked you get a gutsy blues/rock tone and you can add more treble as well, on a separate control. Don't forget that an active system can boost not just take away frequencies.
Comment: I have these and put them in a Japanese Jaguar Special. I personally really like them, as I can get a lot of different tones from them. That being said, they sound like large single coils and not too hot. I actually put a switch on the shielding, so I can turn it on and off. Off, they sound like a single coil, and on they sound a little chimey, which I like. The difference is subtle, though. Overall a great pickup. One thing is that I think it lacks a wide response, but most pickups do IMHO, even expensive ones. I really like the sound I get from these, though I wanted the Brooklyns.
Answer: I bought one of the tele style hollow body guitars from guitar fetish with the P90 pickups.  In my opinion they sound great for rock and blues.  I can plug the guitar straight in to all of my amps except the solid state practice amp and get a good sound.
Through my Fender tube amp, cranked, they sound a lot like the tone from "I Fought The Law".
I am debating purchasing a set of the Dream 180s but I've been procrastinating.  Some people on Harmony Central and The Gear page have posted samples of the pickups, if you're interested in listening.
Comment: This is the personal experience with GFS products that I am looking for, thank you. What is wrong with the sound through your practice amp? Does this guitar sound any worse than others on that same amp? Or is it just that your practice amp doesn't sound that great in and of itself?
Comment: @gomad: Very few things sound good through the practice amp, so that's probably not a knock on the pickups.  All the other amps around here are tubes and its the only solid state.  Everything but my strat sounds harsh through it.
Comment: They sound great through my Vox Pathfinder-10, which is a tiny practice amp.
Answer: Although I have no qualms with Guitar Fetish, I would only purchase pickups from reputable dealers that I know to be of high quality. Since the pickups lend so much to the tone of your instrument--they are essentially the microphones to your guitars voice, in my opinion you should be very picky about ensuring that you get quality components. There are many other manufacturers that sell any pickup your heart desires, but at a little more scratch than what GF wants for them. In my experience it will be worth it, however. There's a good chance that if you bought a set from GF it would have Made in China stamped somewhere on it, and although I have nothing against the Chinese that usually doesn't point to a quality product when it comes to electronics. I have upgraded every guitar I own from stock manufacturer's pickups to sets wound by my favorite pickup guy for a couple hundred bucks a pop--and I am absolutely never disappointed by the tonal upgrade.
Call me picky, but pickups are one place where I would never consider skimping. Would you buy a guitar made out of plywood? I'd venture a guess: no.
Comment: Well, yes and no. I took my #1 electric, a 1988 MIJ top-loader Fender Tele to Sweetwater for last year's Gearfest and plugged it in to a nice amp. I believe a Mesa/Boogie. Anyway, after that I pulled a few other Teles off the wall, including a few Custom Shop Teles and a Baja, and I compared them. Remember that within 2 years, the MIJ Tele was a Squier model, so not great electronics, not great pickups, but I didn't think my #1 sounded that much worse than the US-made US-pickup'd Teles at the store.
Comment: In my defense I'm not preaching boutique mumbo-jumbo here :D. I'm just as broke as you guys, but I really do hear a very large difference between my stock MIM Telecaster pups and my Lollar Tele specials. That difference may be small to some folks, but to me it's huge and worth the investment. Totally subjective though I understand.
Answer: Guitar Fetish or GFS is a reputable business and has a very good return policy if you follow the rules.  I have had good luck with their products - best practices: the really inexpensive pickups are going to be a bit better than the ones sold with low end guitars. Note: sometimes the clearance sales are for products they bought on a volume deal and are not their own products. I bought a set of clearance Tele PU's for $21 and they sound pretty good, much better than the stock Squier Affinity PuP's.  I've also purchased a set of the Strat Texas style at $50 and they are pretty good but I understand the $70 set is smoother (from a guy on another forum who has tried both).  Thrir products are decent and might be comparable to higher end parts (Seymor Duncan, etc..) but there is no guarantee of that.  Personally I have been very pleased with their products and the prices and service have been excellent.
Answer: Guitar Fetish don't build their own pickups. Several of their models are identical to those offered by the Artec brand, so it seems likely that Artec are the OEM (as they are for Wilkinson, Tone Rider, Iron Gear, Giovanni, Warman and several other brands). To widen the net slightly you could simply find the corresponding Artec model to the pickup you fancy and see if anybody has reviewed that pickup. For example Artec build a Dimarzio X2N copy that is sold under various brand names (Crunchy Rails in GFS parlance). In general if a cheap pickup looks very similar to another cheap pickup then it is likely from the same OEM. The GFS Crunchy Rails pickup looks pretty identical to the Entwistle Pickups X3 model.
The only issue I can foresee is that because Guitar Fetish can buy in bulk they might specify differences in the pickup specs. For example they may request an overwound cream-coloured PAF-type humbucker with hex-bolt pole pieces. Visually this would look like an Iron Gear Steam Hammer humbucker (and the Dimarzio Super Distortion of course) but may sound different if GFS request a different magnet or output rating.
My biggest concern would be that Artec simply build one style of humbucker, and adjust one attribute without worrying about the others. When Seymour Duncan, Dimarzio, the boutique winders et al decide to build a hot humbucker they don't simply take their standard PAF humbucker flatwork and magnet set and stick a couple of thousand extra turns on each coil. They might have done this in the '70s (back in the bad old days when some guitarists took two original Gibson PAF pickups, stacked them vertically and wired them in series to get a hotter signal), but builders tend to consider ever element of a pickup when it comes to adjusting an element of the design. A cheaper builder will probably not do this, simply swap a magnet or set the winder to a different count number without due consideration for the impact this will have on the pickup's tone.
I would warn that cheaper pickups might be microphonic, but the most loyal PAF clones come without any wax potting, and authentic Strat pickups get a perfunctory dip in lacquer by way of potting. Some people claim the microphonics enhance the tone... but usually only when they've spent considerably more than GFS prices for their pickups.
Answer: Have been playing since '62 and owned a lot of guitars. Few years ago started restoring some of my older and cheaper instruments and tried Guitar Fetish pickups. Was amazed by the sound. Now have their 'lil killers' (I think) on a nice recent US Strat, 2 sets of their humbuckers on good Ibanez gtrs, set of their 'red actives' on a Japan Strat, and a set of their humbucking p90 replacements on a Tele. All these pups sound (imho) very good indeed. On other guitars I have most of the big name active and passive pups. The Guitar Fetish pups hold their own with anything else in my collection. I use expensive amps and am particular about tone. I am in absolutely no way associated with Guitar Fetish and have no idea what their guitars are like. Their pickups are damn good.
Answer: little late to the conversation!!have  guitar fetish p 90,s on a loaded scratch plate,fitted to a project guitar,mostly ebay!.superb sound,plenty of range,every body here loves it!at a cost of £43.00 sterling,including shipping to UK.no hesitation in buying their products.puts my USA strat to shame tonewise!both played thro valve marshall amp.


Configurar Cake bake para Versão 2.x do Cake

Question: Eu tenho uma libary do Cake 2.3 no meu Ubuntu 13.10 configurado e rodando normalmente.
Quando tento usar o cake bake, ele assume automáticamente o Cake 1.3
Welcome to CakePHP v1.3.14 Console
Pergunta: Como configuro o cake bake para usar a versão 2.3 do Cake?
Answer: Tente chamar pelo seguinte comando
/var/www/<caminho do seu cake>/app/Console/cake

ou
cd /var/www/<caminho do seu cake>/app/Console/
php cake.php

Essas são duas possibilidades de chamar o seu bake, sempre confira o caminho do seu cakephp para garantir que está chamando a aplicação correta
Comment: Olá Erlon, obrigado pela resposta. Quando executei o primeiro comando, apresetou a mesma mensagem: Welcome to CakePHP v1.3.14 Console.

No segundo comando já apresentou o correto. Welcome to CakePHP v2.3.4 Console. Obrigado pela Ajuda!


Retrieve taxonomy terms with EntityFieldQuery for a given parent term

Question: I am retrieving a tid of a taxonomy term by using EntityFieldQuery. However, I need to cross-link the taxonomy_term_hierarchy table to list those terms which have a particular parent, but I am not able to get it. In the code below
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term')
      ->propertyCondition('vid', $vocabulary)
      ->propertyCondition('name', $termino)
      ->propertyCondition('parent', $parent_id)

the last line is throwing the following (expected) error. The same code, without the last property condition, works correctly. How can I achieve the result?
The returned error is:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'taxonomy_term_data.parent' in 'where clause'
Comment: Just in case anyone is interested in the answer for Drupal 8, the condition would look like: `$query->condition('parent.target_id', $parent_id);` or if you want to query entities referencing taxonomy terms by a given parent id `$query->condition('field_term_reference.entity.parent.target_id', $parent_id);`
Answer: Using only the EntityFieldQuery class, you cannot because the information about the taxonomy hierarchy is not contained in the database table used for the entity data, but in the taxonomy_term_hierarchy table.
You would need to first get all the taxonomy term IDs having $parent_id as parent, from that table, and then use the EntityFieldQuery class for the other part of the query. Truly, the EntityFieldQuery class is excessive, in this case, since its purpose is to make a query involving the values of field attached to an entity. It also slower than a normal query done with db_select(), and you would not get any benefit, in this case.
Comment: I had convinced myself that EntityFieldQuery was more abstract than db_select, avoiding potential problems when changing field names or the like. For your reply and other info it seems very limitated, and in Drupal 8 this limitation may change. I will use a simple `db_query` as you suggest.


What would be the appropriate statistical test for my study?

Question: What would be the appropriate test for a study that has:
2 categorical independent variables with 2 levels each,
1 moderator variable (and would it matter if my moderator is categorical or continuous?), and 1 continuous dependent variable
I am still undecided on whether I will propose my variables as being correlated or as predictor/criterion variables.
If the results of my moderator (which will most likely be measured on a scale of 1 to 7) are scored as low (1-2.9), medium (3-5), and high (5.1-7), would I be correct in assuming that, as there are more than 2 'levels' of the moderator, I will have to encode them into dummy variables if I'm using SPSS?
Would my choice of carrying out multiple regression be appropriate for this study?
Answer: Yes, you can carry out multiple regression. Alternatively, you can perform an ANOVA. You will get the same outcome either way, so choose one that better fits your context.
As to your moderator variable, yes, if you code it into low-medium-high then it becomes a categorical (dummy) variable regardless of the number of levels.
Comment: Do not recode a 1-7 ordinal variable into intervals.  This loses precision and power and is completely arbitrary.  Spend more time understanding the data, and don't launch into statistics without studying a good intro book.
Comment: Hello and thank you for the response. I should clarify that the Multidimensional Scale of Perceived Social Support (MSPSS)  scoring guide instructs as i have mentioned above with regards to assigning the low, medium, and high values based on the score.

May I ask: what would you advise is the most straightforward way to work with my 3 level categorical moderator on SPSS? Would choosing model 1 of the PROCESS macro be sufficient?


The server tag is not well formed error in my connection string

Question: I am having a problem with my code when trying to run i error below:
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: The server tag is not well formed.
it says there's an error on this line below
Line 109:        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=vremsdb;Initial Catalog=Survey;Persist Security Info=True;User ID=Survey;Password=$urvey12345;Max Pool Size=10000"SelectCommand="SELECT * FROM [vSurveyQuestion] WHERE ([SubmissionID] = @SubmissionID) ORDER BY [QOrderNo]">
Comment: Code did not publish. Error on this line  -
Line 110:
Comment: Hey, edit your question instead.
Comment: @tufaylahmed ; for code to render correctly, you need to format it: https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks
Answer: The server tag is not well formed error tells that there is xml syntax error on asp.net page.
In your case there is invalid xml attribute definition. You have to add whitespace before SelectCommand attribute as follows:
ConnectionString="Data Source=vremsdb;Initial Catalog=Survey;Persist Security Info=True;User ID=Survey;Password=$urvey12345;Max Pool Size=10000" SelectCommand="SELECT * FROM [vSurveyQuestion] WHERE ([SubmissionID] = @SubmissionID) ORDER BY [QOrderNo]"


How to make DataContractSerializer safer?

Question: I ran into a scenario recently where one of our devs added an object to our data contract that was not marked as a data member.  We are using using the DataContractSerializer to store a configuration file for a piece of hardware we are controlling.  The serialize operation did not succeed, obviously.
The major problem this uncovered was that the configuration file got destroyed during the process.  Does anyone know of a way to make sure the object graph will serialize prior to trying to serialize it?
The stack trace from the serialization exception fails at a call to XmlObjectSerializerContext.CheckIfTypeSerializable(..)  I'm wondering if there is something like this, that I can use prior to trying to serialize.
I would like to avoid having to stream the graph to memory and then to file, but I guess this would work...
Any suggestions?
Answer: Scott, I think you mean that serialize succeeded, but *de*serialize didn't succeed. If you add an additional data member but forgot to annonate, the serializer would just ignore it during serialization. Also, if it sees an additional member during deserialization, it will throw if you're requiring strict schema validity or requiring the member to be present; but otherwise, it will simply not parse that value and move on.
There are a few ways to handle this -- using IExtensibleDataObject, requiring DataMembers, using surrogates, etc. See http://msdn.microsoft.com/en-us/library/ms731138.aspx [Data Contract Versioning] and http://msdn.microsoft.com/en-us/library/ms731083.aspx [Forward-Compatible Data Contracts] for more specific guidance.
Hope this helps!
Comment: It was the serialization that didn't succeed.  The application attempted to save an update to the configuration file.  This failed, but not before corrupting the file on disk.


Existe alguma função no PHP que simule um LEFT JOIN?

Question: Estou desenvolvendo uma aplicação em PHP que precisa exibir um indicador gráfico. O problema é que os dados vem de uma API externa e dependendo do filtro aplicado, a API não me retorna pontos que preciso inserir no gráfico.
Exemplo:
// Chama a API sem filtros
$dados = $api->get()->limit(6);

var_dump($dados);
// Retorna
  'metaPontual' =>
    array (size=6)
      3 => float 178036332.62
      4 => float 176975684.39
      5 => float 173823421.06
      6 => float 170114093.13
      7 => float 168775993.4
      8 => float 167259382.68

// Aplicando um filtro
$dadosFiltrado = $api->get(['nome' => 'Lucas'])->limit(6);

var_dump($dadosFiltrado);
// O Array Não retorna todos os pontos.
  'metaPontual' =>
    array (size=6)
      1 => float 183635670.39
      4 => float 176975684.39
      5 => float 173823421.06
      6 => float 170114093.13
      8 => float 167259382.68
      9 => float 167259382.68

Preciso de uma rotina que atue de forma a criar um "LEFT JOIN" entre o array 1 e o array 2, lembrando que os arrays são exemplos, as chaves retornadas pelos arrays são diferentes, de modo que:
$arrayFinal = array_left_join(array_keys($dados), $dadosFiltrado);
var_dump($array_final)

  'metaPontual' =>
    array (size=6)
      3 => null
      4 => float 176975684.39
      5 => float 173823421.06
      6 => float 170114093.13
      7 => null
      8 => float 167259382.68

Comment: Seria um [`array_merge`](http://br2.php.net/array_merge) que você está buscando?
Comment: Cara, não tem função pronta, mas brincar um pouco com uns `foreach` resolve seu problema. Eu eventualmente faço isso, mas sem tempo para dar resposta agora
Comment: Vc quer um array novo com os valores que ambos tem em comum?
Comment: @bfavaretto não seria um array merge pois preciso somente dos valores que ambos tem em comum mais as chaves do primeiro array.
Comment: As chaves que só existem no segundo ficam de fora então?
Comment: @bfaretto exatamente, o que só existe no segundo array devo desconsiderar.
Comment: @EmersonRochaLuiz pensei também em utilizar um `foreach` mas se possível gostaria de evitar seu uso por questões de desenpenho (http://www.phpbench.com/). Irei fazer alguns testes de desempenho com algumas variações do código que postei.
Answer: Você disse que precisa dos valores de ambos os arrays MAIS as chaves do 1º, certo?
Tente com isso:
$array = array_intersect($dados, $dadosFiltrado);
$array_final = (array) ($dados + $array);

var_dump($array_final);

Comment: é quase isso... com array_intersect estou olhando os valores, não as chaves.
Answer: Isso resolve seu problema
array_keys(array_intersect_key($arr1,$arr2));

Retorna um array com as chaves presentes nos dois arrays
Answer: Com base nas respostas e comentários cheguei as seguintes implementações:
function array_left_join($arrayChaves, $arrayValores){
    $arrayIntersect = array_intersect_key($arrayValores, $arrayChaves);
    $chavesLimpas = array_fill_keys(array_keys($arrayChaves), '');

    return array_merge($chavesLimpas, $arrayIntersect);
}

function array_left_join_2($arrayChaves, $arrayValores){
    $chaves = array_keys($arrayChaves);
    $arrayFinal = array();

    foreach ($chaves as $key) {
        $arrayFinal[$key] = !isset($arrayValores[$key]) ? '' : $arrayValores[$key];
    }

    return $arrayFinal;
}

Aplicando essas implementações em um array bem grande cheguei aos seguintes resultados.
$arrayTodosOsPontos = array();
$arrayFiltrado = array();

for ($i=10; $i<100000; $i++) {
    $arrayTodosOsPontos[md5("$i")] = 1;
}

for ($i=10; $i<100000; $i++) {
    $arrayFiltrado[md5("$i")] = 4;
}

Debugbar::startMeasure('array_left_join_v1');
$arrayFinal = array_left_join($arrayTodosOsPontos, $arrayFiltrado);
Debugbar::stopMeasure('array_left_join_v1');

Debugbar::startMeasure('array_left_join_v2');
$arrayFinal2 = array_left_join_2($arrayTodosOsPontos, $arrayFiltrado);
Debugbar::stopMeasure('array_left_join_v2');

Como a segunda opção mostrou um desempenho melhor, acho melhor utilizar ela no projeto.


Why is Solr throwing exceptions on unfound text files after insttalling Apache Solr Multilingual config files?

Question: I have used Apache Solr Multilingual to generate Solr config files; however after installing these files Solr throws many exceptions of the form :
Can't find resource '<text_file_name>_<lang>.txt'
For example
Can't find resource ' mapping-ISOLatin1Accent_fr.txt'
Is the configuration of such files not the purpose of the Apache Solr Multilingual module ?
Answer:
Is the configuration of such files not the purpose of the Apache Solr Multilingual module ?

Seems the answer is 'no'.  I manually created 6 text files per language in my solr config and solr started without complaint.
Each language needs each of these text files:
compoundwords_<lang>.txt
mapping-FoldToASCII_<lang>.txt
mapping-ISOLatin1Accent_<lang>.txt
protwords_<lang>.txt
stopwords_<lang>.txt
synonyms_<lang>.txt

where 'lang' is the Drupal language code which can be confirmed by looking over the schema.xml kicked out by Solr Multilingual Module . for example: 'en', 'es', 'de' ...
I copied the contents of each of said files from the Solr Multilingual Module config. forms


how to use firebase phone auth without create new uid

Question: How to use firebase auth with phone number to verify phone number without create new uid i want to know just if the input code is correct or not
this the code that i used but it creates new uid
<code> manualVerification() {
print("My Id" + verificationId);
FirebaseAuth.instance
    .signInWithPhoneNumber(verificationId: verificationId, smsCode: smsCode)
    .then((user) {
  print("Verification Successful");
  print("$user");
  setState(() {
    showStatus=3;
  });
  widget.onVerificationSuccess();
}).catchError((error) {
  print("Verification Failed Due to $error");
  widget.onVerificationFailure();
});
</code>
}
Answer: The whole point of Firebase Authentication is to create a user account with a unique ID.  There's no way to separate out the process that just verifies the phone number.
Comment: ok , is there any service let me do it with flutter ?
Comment: That sounds like something you'll need to search for.  Stack Overflow isn't a place to seek product recommendations.
Comment: ok, another question please ,if i create new uid how to copy old children from old uid to new uid
Comment: If you have another question, please post it separately as a new question.


Altering Nodecomment $links

Question: I am trying to alter the "reply" links added to Nodecomment comments when the nodes are listed beneath the topic. The problem I have is that I want users to be restricted to the inline submit form, but Nodecomment is adding links to the standalone reply page.
While trying to ovveride the links using hook_link_alter(), I ran into an issue with Nodecomment comments are treated much like regular comments in that hook_link_alter() doesn't seem to be run on them. Here is an example:
/**
* Alter module links.
*
*/
function mymodule_link_alter(&$links, $node) {

    // This is an example of altering links that works as expected
    if (isset($links['comment_add']) && node_access('create', $node)) {
      $links['comment_reply'] = array(
        'title' => t('reply'),
        'title' => t('Link altered'),
        'href' => 'http://example.com',
      );
    }

    // This is an example of altering nodecomment links failing.
    // When rendering a list of topic replies, the comment_reply link
    // will not be altered.
    if (isset($links['comment_reply']) && node_access('create', $node)) {
      $links['comment_reply'] = array(
        'title' => t('reply'),
        'title' => t('Link altered'),
        'href' => 'http://example.com',
      );
    }
}

I am looking for solutions which can (ideally) be packaged in the site's custom module rather than theme.
Answer: Reading the documentation for hook_link_alter() I find the following sentence.

Perform alterations before links on a node or comment are rendered.

The hook implementation you are using is missing the last argument: the definition of the hook given by the documentation is hook_link_alter(&$links, $node, $comment = NULL).
Looking at the code of comment_render(), which is the function that renders all the comments of a node, you can notice that hook_link_alter() is invoked right after the data is loaded from the database (and after hook_link(), of course).
if ($comment = db_fetch_object($result)) {
  $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
  $links = module_invoke_all('link', 'comment', $comment, 1);
  drupal_alter('link', $links, $node, $comment);

  $output .= theme('comment_view', $comment, $node, $links);
}

hook_comment is invoked from theme_comment_view().
if ($visible) {
  $comment->comment = check_markup($comment->comment, $comment->format, FALSE);

  // Comment API hook
  comment_invoke_comment($comment, 'view');

  $output .= theme('comment', $comment, $node, $links);
}
else {
  $output .= theme('comment_folded', $comment);
}

hook_comment(), which is invoked with a call to comment_invoke_comment(), is not called for comments that are not visible.
The implementation of hook_link_alter() you created should at least check which comments it is altering, if it is supposed to alter only specific comments. At least, it should check the last parameter ($comment) is not NULL; if that happens, the hook is invoked to alter node links, which is not what you want as you need to alter comment links.
Answer: If they are rendered like Drupal comments why don't you use hook_comment()?
Here's a kick-start:
function mymodule_comment(&$a1, $op) {
  if ($op === 'view') {
    // $a1 is the comment object
  }
}

Comment: That's gooding thinking! I'll try it on Monday.
Comment: good luck hope it works! :)

Altering Nodecomment $links


Junos Pulse users are competing with eachother for VPN connection

Question: We've having the issues described here: http://kb.juniper.net/InfoCenter/index?page=content&id=KB26822
where one user kicks another user off the VPN when connecting. Our PCs were cloned after the Junos GUID was created. The KB article says to:

The Junos Pulse connection configuration, which is located at C:\Program Files (x86)\Common Files\Juniper Networks\ConnectionStore\connstore.dat, contains the following section:
machine
"local" {
    guid: "9e4898e81ca026623e7fb4c9f4de1f678244fa62"
    pulse-language: "en-US"
}

I've tried deleting the GUID line from the connstore.dat file, but if I restart the Junos client, it sets the same GUID instead of a new one, so the duplicate GUID problem persists.
I also tried deleting the connstore.bak file and then deleting the GUID line from connstore.dat, but that still got the same GUID.
Has anyone else run into this and been able to fix it? I'm guessing the GUID is cached on the VPN server, and when I connect, the client sends some key to lookup the GUID.
Answer: The following solution worked for me:
I stopped the Juniper Unified Network Service as specified in the Walter Stabosz answer, then I removed guid from the connstore.dat file, but also from the Registry:
HKEY_CURRENT_USER\Software\Juniper Networks\Device Id, key: DeviceId
HKEY_LOCAL_MACHINE\SOFTWARE\Juniper Networks\Device Id, key: DeviceId

After restarting Juniper Unified Network Service and the Junos client the new guid was generated.
Comment: This worked for me but on my system the path was `HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Juniper Networks\Device Id`
Answer: I figured it out.
Before you edit connstore.dat to delete the GUID line, you must first to go into Services and stop Juniper Unified Network Service.
Or in Task Manager, you can kill: dsAccessService.exe / Juniper Access Service
The service will restart itself when you restart the Junos client.
Answer: Remove the registry key and then restart the service. Connstore.Dat will automatically update with a new key after you restart the service.
Answer: An KB was created for that on Juniper's website. (http://kb-beta.juniper.net/InfoCenter/index?page=content&id=KB25581, now article located there: https://kb.pulsesecure.net/articles/Pulse_Secure_Article/KB25581)
I confirm too that now you need to erase too the registry like @tafiq3's told:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Juniper Networks\Device Id
Summary:
This article describes the issue of Junos Pulse being frequently
  disconnected for multiple Junos Pulse Desktop users.
This issue can occur, if multiple users have the same guid string
  value for the local machine ID in the Connection Store configuration
  data file; which is created, when installing Junos Pulse for the first
  time.
The issue is intermittent and can occur at any time during the
  session. At other times, the session is not affected and the Junos
  Pulse user stays connected, until they sign out.
Problem or Goal:
Multiple users report frequent disconnects with the Junos Pulse
  desktop client that occur randomly.  The following error message is
  generated on the desktop, when Junos Pulse is disconnected:
Cause:
When deploying Junos Pulse desktop to end-users, if the Junos Pulse
  client is pre-installed on Windows OS and an image is created from
  this, which is shared across multiple endpoints, then the local
  machine ID that gets stored in the Junos Pulse Connection Store
  configuration data file will be the same for every machine that the
  image is used on.
The Junos Pulse Secure Access Gateway Series device identifies user
  sessions that connect with the Junos Pulse clients by the local
  machine identifier, which is sent to the server, when a connection is
  established via Junos Pulse. The Junos Pulse Secure Access Gateway
  Series device will terminate a Junos Pulse session, if another Junos
  Pulse session is started with the same guid value, for security
  reasons.
To determine if Junos Pulse users in your environment are affected by
  this issue, collect the Junos Pulse logs and diagnostics logs from the
  Junos Pulse client, from each individual client PC. Open the logs and
  Diagnostics folder from the user's PC and browse to the
  ConnectionStore folder, which will contain the connstore.dat file.
  Open this file with a text editor and locate the following parameter:
machine "local" {
       guid: "d96b50d4275ef266d402348641e6b57b10b48bd3"
       pulse-language: "en-US" }
If the guid string is identical across multiple client PC's, then this
  confirms the issue.
Solution:
When deploying Junos Pulse, which is pre-installed for a Windows OS
  image being shared across multiple endpoints, the guid value for the
  local machine should be removed from the Junos Pulse configuration
  file, after installing Junos Pulse; so that the Junos Pulse
  configuration data files in the root image do not contain a guid value
  that would be replicated on all machines.  A new and unique guid value
  will be generated for each user, when Junos Pulse is launched and run
  for the first time.
Perform the following procedure to reset the guid for users, who have
  already installed Junos Pulse and have duplicate guid values in the
  Junos Pulse configuration file or the master image (which is used to
  pre-image multiple PC's with an image that Junos Pulse has already
  been pre-installed on):
  1.When Junos Pulse is installed browse to C:\Program Files(x86)\Common Files\Juniper Networks\Connection Store and open the connstore.dat
  file in a text editor.
2.Locate the following parameter:  machine "local" {
      guid: "41cbc0d2a1a100855755b4355d6d2579836694cd"
      pulse-language: "en-US" }
3.Remove the guid value from the parameter by deleting the entire second line. This will change the parameter setting to:
machine "local" {
      pulse-language: "en-US" }
4.Save the modified connstore.dat file to the original directory.
Note: It may be necessary to edit the 'connstore.dat' file in a Text
  Editor, which is 'Run As Administrator', if these changes are locally
  made from the affected PC; due to the folder and file permissions that
  are set on the directory.
5.Go to Task Manager > Services tab, locate and stop the JuniperAccessService service, and/or reboot the PC to restart the
  service. When the service is restarted and Junos Pulse has been
  launched again, a new and unique guid will be generated and stored in
  the user's connstore.dat file.
6.On Mac OS X the following script can be used:
!/bin/bash
stop pulse access service
remove local guid from connstore.dat
restart service plist='/Library/LaunchDaemons/net.juniper.AccessService.plist'
connstore='/Library/Application Support/Juniper Networks/Junos
  Pulse/connstore.dat' guid=xxx....xxx sudo launchctl unload
  ${PLIST.EN_US} sudo sed -i .bak "/${GUID.EN_US}/d"
  "${CONNSTORE.EN_US}" sudo launchctl load ${PLIST.EN_US}
Note: The 'connstore.dat' file also contains the connections that are
  displayed in the Junos Pulse UI, when it is launched. So, it is
  recommended that the above procedure be performed to modify only the
  portion of the 'connstore.dat' file, which was specified above, to
  resolve this issue; as opposed to deleting the 'connstore.dat' file
  from the user's PC. If the connstore.dat file is deleted from the PC,
  the user will need to manually recreate any and all connections that
  they regularly access.
Answer: For a MAC running Junos Pulse 5.x, run the following script:
#!/bin/bash
# stop pulse access service
# remove local guid from connstore.dat
# restart service
sudo launchctl unload /Library/LaunchDaemons/net.juniper.AccessService.plist
sudo rm -rf "/Library/Application Support/Juniper Networks/Junos Pulse/DeviceId"
sudo sed -i .bak "/guid/d" "/Library/Application Support/Juniper Networks/Junos Pulse/connstore.dat"
sudo launchctl load /Library/LaunchDaemons/net.juniper.AccessService.plist

Note:  This script is the version found in the KB (referenced in yagmoth555's answer), but with one mistake fixed.
The link to the KB is now the following:
KB25581 - [Pulse] Pulse Secure Desktop client is intermittently disconnecting for multiple users at random intervals


How can I insert the Calendar plugins?

Question: I have installed the WordPress Calendar plugins, and I'd like (in some point of the page) add this plugins, without add the default Calendar to a widget and call this widget to the page (such as <?php dynamic_sidebar( 'secondary-widget-area' ); ?>).
I mean, like to use SidebarEventsList() for the WP Events Calendar Plugins
How can I do it? Which method I need to call?
Tried with
<? {CALENDAR} ?>

as the readme.txt says, but I get an error Parse error: syntax error, unexpected '}'
Comment: You can't use a WP shortcode within PHP. WP shortcodes need to be inside the content, where WP's filters will parse them and call the appropriate functions. You will need to call those functions directly. Which ones those are, the docs should tell you (or, sometimes, looking into the plugin)
Comment: I thought it, but in fact I don't find it...! Where can I found that WP filters? So I'll check with function call that CALENDAR shortcode
Answer: To use shortcodes where ever you want you do this:
Where CALENDAR is your shortcode. Just add the shortcode in here like you would in the wp-admin.
Attributes are also allowed.

How can I insert the Calendar plugins?


About the "Bounded Convergence Theorem"

Question:
The ``Bounded Convergence Theorem" states that "If a sequence $\{f_n\}$ of measurable functions is uniformly bounded and if $f_n \rightarrow f$ in measure then $lim_{n \rightarrow \infty } \int f_n dP = \int f dP$"
Here does the phrase ``uniformly bounded" mean that there exists $M$ s.t $\forall n, \vert f_n \vert \leq M$ ?

I guess examples like $f_n = n^{1/2}1_{[0,1/n]}$ show that being uniformly bounded is not a necessary condition.

If a sequence of functions $f_n$ were to converge uniformly to $f$ then one would have had $lim_{n \rightarrow \infty } \int f_n dP = \int f dP$. Is the "Bounded Convergence Theorem" a generalization of this?
As in are there examples of sequences of functions not converging uniformly and yet it is true that $lim_{n \rightarrow \infty } \int f_n dP = \int f dP$ because they were uniformly bounded meaurable functions converging in measure ?
Comment: For example, the result holds if $f_n\ge 0$ and $f_n\nearrow f$ (equivalently, if conditions of the Monotone convergence Theorem hold).
Comment: Can you kindly explain a bit more?
Comment: I mean that you can construct an example where $f_n$ converges to $f$ (in pointwise sense and not uniformly) and still get the result.
Comment: Any example you have in mind? (So you are saying that uniform convergence is not a necessary condition) But is your example then satisfying the "bounded convergence theorem" conditions?
Comment: $f_n$  need not be uniformly bounded... For example, $f≥0$ is such that $\int f =\infty$. Take $f_n=f1\{f≤n\}$.
Answer: The assumption of the statement is that $f_n$ and $f$ are point-wise bounded by some function $g$ and that $g$ is integrable. You will find more hits if you look for "dominated convergence". See https://en.wikipedia.org/wiki/Dominated_convergence_theorem
For instance, if $g\in L^1$, then $f_n(x)=\min(1,|x|/n)·g(x)$ is uniformly bounded by $g$, converges pointwise to the zero function, but does not necessarily converge uniformly (in the supremums norm).
Comment: But "dominated convergence theorem" is a separate theorem - right? I amtalking of the "bounded convergece theorem". Is my understanding of the definition of "uniformly bounded" correct as stated in point 1? you have examples of the kind I am looking for in the third point?

About the "Bounded Convergence Theorem"


Disabling backups after "drush up"

Question: I use drush up for sites on a shared server and development sites.
Within some months, my inode volume went from about 25% to 96%. Given I have already 30 days backwards of backup service, I don't really need this specific backup.
How can you disable the automatic backups created by Drush each time drush update is executed?
Answer: Yes, use the --no-backup option with your command.
drush --no-backup up myproject

If you're you're looking to make this a default option, you can do something like Bash aliasing and just run that alias instead:
alias drush-no-bup='drush --no-backup'

Then run:
drush-no-bup up myproject

Disabling backups after "drush up"


Isbell duality between $\text{Set}$ and $\text{Set}^{\text{op}}$.

Question: Provided a small category $G$, the Isbell duality establishes an adjunction:
$$\text{Set}^{G^{\text{op}}}  \leftrightarrows (\text{Set}^{G})^{\text{op}}.  $$
Both maps can be computed as Kan extensions. Call $y : G \to \text{Set}^{G^{\text{op}}}  $ and $y^{t}: G \to (\text{Set}^{G})^{\text{op}} $ the Yoneda embeddings, then one can obtain the two adjoints as $\text{Lan}_y y^t$ and  $\text{Lan}_{y^t} y.$
I am interested in a special computation of these maps. Choose $G$ to be the terminal category, so that we are looking at the adjunction:
$$\text{Set} \leftrightarrows  \text{Set}^{\text{op}} .$$
Is there an explicit presentation of these two adjoint functors?
Answer: Every set is a coproduct of points, and the left adjoint sends the point to itself, so it sends any set to a product of points, that is, it's constant. Similarly, or by adjunction, the right adjoint is constant. There's an error in your treatment: the opposite category of sets is the free completion of a point under limits, and so the right adjoint must be defined by right Kan extension along $y^t$.
Comment: Thus you claim that both functors are the constant functor? I got the same result.
Comment: @IvanDiLiberti Yep.
Comment: Don't you think that is very strange that the functor is so uninteresting?
Comment: @IvanDiLiberti I can't speak for Kevin Carlson, but no it doesn't seem strange at all. When $G=\mathbf 1$ then both $y$ and $y^t$ are the constantly terminal object (of $\mathbf{Set}$) functor. It doesn't seem strange at all that the Kan extension of a trivial functor along another trivial functor is trivial. Being a bit cavalier about size issues, $y^t$ is an initial object so you'd expect $\text{Lan}_J y^t$ to be the initial object for any $J$ of the appropriate type. Similarly, for the right Kan extension.
Comment: I agree with Derek. Cocontinuous functors out of sets are boring.


Desabilitar Input do tipo DATE Após selecionar opção do Select

Question: Preciso Deixar desabilitado o campo "ultimoDiaTrab" e só habilita-lo, quando no Select for selecionado "PARCIALMENTETRABALHADO" opção Nº2.

        Avisio Prévio:
        <select class="form-control" name="avisoPrevio" id="avisoPrevio">
            <option id="avisoPrevio" name="TRABALHADO" value="TRABALHADO">Trabalhado</option>
            <option id="avisoPrevio" name="INDENIZADO" value="INDENIZADO">Indenizado</option>
            <option id="avisoPrevio" name="PARCIALMENTETRABALHADO" value="PARCIALMENTETRABALHADO">Parcialmente Trabalhado</option>
            <option id="avisoPrevio" name="TOTALMENTETRABALHADO" value="TOTALMENTETRABALHADO">Totalmente Trabalhado</option>
        </select>

        Último dia a ser trabalhado:
        <input type="date" id="ultimoDiaTrab" name="ultimoDiaTrab" class="form-control" />

Answer: Repara que

tem o mesmo ID que o teu input
<input type="date" id="ultimoDiaTrab" name="ultimoDiaTrab" class="form-control" />

Iso é HTML inválido e gera bugs dificeis de detetar...
Solução, usando outro seletor que não o ID:

var select = document.getElementById('avisoPrevio');
var ultimoDiaTrab = document.querySelector('input[type="date"][name="ultimoDiaTrab"]');
select.addEventListener('change', function() {
  ultimoDiaTrab.disabled = this.value != 'PARCIALMENTETRABALHADO';
});

  Avisio Prévio:
  <select class="form-control" name="avisoPrevio" id="avisoPrevio">
            <option id="avisoPrevio" name="TRABALHADO" value="TRABALHADO">Trabalhado</option>
            <option id="avisoPrevio" name="INDENIZADO" value="INDENIZADO">Indenizado</option>
            <option id="avisoPrevio" name="PARCIALMENTETRABALHADO" value="PARCIALMENTETRABALHADO">Parcialmente Trabalhado</option>
            <option id="avisoPrevio" name="TOTALMENTETRABALHADO" value="TOTALMENTETRABALHADO">Totalmente Trabalhado</option>
    </select>

  Último dia a ser trabalhado:
  <input type="date" id="ultimoDiaTrab" name="ultimoDiaTrab" class="form-control" disabled="disabled" />

Answer: Existem duas coisas que precisam ser feitas para que funcione corretamente.
A primeira delas é remover o id="ultimoDiaTrab" da div onde se encontra o campo data e colocar o campo ultimoDiaTrab como disabled por default. Onde estava:

    Último dia a ser trabalhado:
    <input type="date" id="ultimoDiaTrab" name="ultimoDiaTrab" class="form-control" />

Deve ficar:

    Último dia a ser trabalhado:
    <input type="date" id="ultimoDiaTrab" name="ultimoDiaTrab" class="form-control" disabled/>

A segunda coisa a ser feita é adicionar um EventListener via Javascript, para quando o valor do select for alterado verificar se o campo data deve ser ativado ou desativado:

Comment: Lucas, Obrigada!! Funcionou Perfeitamente!!
Answer: Como o amigo Sergio disse, cuidado com Ids iguais.

$('#avisoPrevio').change(function(){
if($(this).val() == "PARCIALMENTETRABALHADO"){
$('#ultimoDiaTrabalho').prop("disabled", false);
}else{
$('#ultimoDiaTrabalho').prop("disabled", true);
}
})

        Avisio Prévio:
        <select class="form-control" name="avisoPrevio" id="avisoPrevio">
            <option id="avisoPrevio" name="TRABALHADO" value="TRABALHADO">Trabalhado</option>
            <option id="avisoPrevio" name="INDENIZADO" value="INDENIZADO">Indenizado</option>
            <option id="avisoPrevio" name="PARCIALMENTETRABALHADO" value="PARCIALMENTETRABALHADO">Parcialmente Trabalhado</option>
            <option id="avisoPrevio" name="TOTALMENTETRABALHADO" value="TOTALMENTETRABALHADO">Totalmente Trabalhado</option>
        </select>

        Último dia a ser trabalhado:
        <input type="date" id="ultimoDiaTrabalho" name="ultimoDiaTrab" class="form-control"disabled="disabled" />


asterisk SIP User-to-User

Question: I am trying to make a SIP transfer from one Asterisk to another with passing UUI.
On my asterisk 13 i have a simple dialplan:
exten => 2222,1,Answer
exten => 2222,n,Transfer(SIP/1111@asterisk14&User-to-User=342342ef34;encoding=hex)
exten => 2222,n,Hangup

I have registered SIP trunk between my asterisk 13 ans asterisk 1.4
register => asterisk13:email@example.com/asterisk14
[asterisk14]
type=friend
secret=welcome
context=asterisk14_incomming
host=dynamic

and done similar config on the second asterisk
Now I have error:

Purely numeric hostname (1111), and not a peer--rejecting!

I have read all I can find about this error but cant find how to resolve it.
thanks in advance for any suggestions
Comment: On `Asterisk14`, please show us the CLI result of `sip show peer 1111`.
Comment: this command shows the same on both asterisk's "peer 1111 not found" 1111 refers to extension with some dialplan on  the second asterisk.
Comment: Ok.  please show the relevant piece of dialplan on `Asterisk14` ... Also, please rig a dummy extension `1313` on `Asterisk13` that calls `1111` on `Asterisk14` and show us the result of a test dial to that.
Comment: on asterisk14 i have very basic dialplan which im trying to reach
Answer: No way pass like that. Use SIPAddHeader

asterisk SIP User-to-User


Scope of variables in Qt vs vanilla c++

Question: Disclaimer: I am total newbie to Qt.
Let's assume we have a byte array returned from a function innerFunc that is later used in another function outerFunc.
QByteArray innerFunc(){
 QProcess ls;
 ls.start("ls", QStringList() << "-1");
 return ls.readAll();
}
void outerFunc(){
 QByteArray gotcha = innerFunc();
 .
 .
 .
}

In vanilla c++ I would expect readAll function to return a pointer that needs to be deleted later. In Qt this function returns an instance of the QByteArray class so I guess it shouldn't be accessed outside of the innerFunc's scope.
If so, how should I properly transfer the data to an outer function? Should it copied to QByteArray *tmp = new QByteArray or is it unnecessary?
Comment: this will all be covered in any decent c++ textbook - qt is behaving just like "vanilla c++"
Comment: "_In vanilla c++ I would expect readAll function to return a pointer that needs to be deleted later._": No, that is what you would expect in C, but in C++ that would be considered a bad design whether Qt or not. It is the whole point of RAII, one of the major concepts differentiating C++ from C, that destructors should take care of this implicitly.
Answer: The code you have looks fine.  QByteArray is like std::vector<uint8_t> or std::string and not like a pointer.  It manages its own memory.  It's fine to return it from a function or pass it to a function by value.  The compiler will take care of copying and/or moving the data from one object to another as appropriate, using the contructors/operators defined by the QByteArray class.

QByteArray header file
QByteArray documentation

Scope of variables in Qt vs vanilla c++


Support of a Coherent Sheaf and Noetherianity

Question: Exercise 5.6 b) of Chapter II of Hartshorne's Algebraic Geometry asks to prove that if $A$ is a Noetherian ring and $M$ a finitely generated $A$-module then $Supp(\tilde{M})=V(Ann(M))$. Where $\tilde{M}$ is the sheaf on the scheme $Spec(A)$ associated to the module $M$.
I have "proved" the statement without using the Noetherianity condition on $A$ (or without noticing I'm using it!). So I guess I'm missing something. I would like some help in understanding where my error lies!
Here follows my "proof" of the statement:
First inclusion $V(Ann(M))\subseteq Supp(\tilde{M})$
Let $p\in V(Ann(M))$, so $Ann(M)\subseteq p$. By contradictions I suppose $M_p=0$, in specific for each $m \in M$ there exists $a\in A - p$ such that $am=0$. Let $\{m_i\}$ be a finite set of generators for $M$ and $\{a_i\} \subseteq A$ such that $a_im_i=0$ for each $i$.
On one hand $\prod a_i\in A-p$ because $p$ is a prime ideal, but on the other hand $(\prod a_i)m_j=0$ for each $j$, so $\prod a_i\in \bigcap Ann(m_i) = Ann(M) \subseteq p$. Contradiction.
Second inclusion $Supp(\tilde{M}) \subseteq V(Ann(M))$
Let $p \in Supp(\tilde{M})$, then $M_p\neq 0$ and there exists $m\in M$ such that it does not exist $a \in A - p$ such that $am=0$. Then $Ann(M)\bigcap (A-p)=\emptyset$ so $Ann(M)\subseteq p$, in specific $p\in V(Ann(M))$.
So, what's wrong? Thank you for your help!
Answer: I am happy to report that your statement is perfectly correct:  if $M$ is a finitely generated $A$-module, then $Supp (M)=V(Ann(M))$, and the fact that $A$ is or isn't noetherian is irrelevant.
NB Many people use noetherianity as a blanket assumption (for example Eisenbud in his book Commutative Algebra) but that doesn't mean that their theorems become false without that assumption.
In  contrast, Bourbaki and Matsumura tend to use noetherianity only when it is really needed.
Comment: I'm happy to hear it! Thank you again!


How do I convert object to float in panda using lambda and apply

Question: I need to use apply and lambda to convert "Ping (ms)" and "Download (Mbit/s)" from object type to float type. Both columns contain decimal numbers.
Thank you,
I don't get any error but it doesn't convert!
# Code Cell 14
# this disables a notebook warning that is not relevant for our use case
pd.options.mode.chained_assignment = None
#df_compact.dtypes
# Convert Ping and Download to float
df_compact_clean["Ping (ms)_float"]=df_compact["Ping (ms)"].apply(lambda row:float)
)
df_compact_clean["Download (Mbit/s)_float"] =df_compact["Download (Mbit/s)"].apply(lambda row: float)

Comment: if you want to use lamba then with `()`  like `apply(lambda row: float(row))`. Or directly `apply(float)` without `lambda` and `()`. But it may need rather `as_type(float)
Comment: Search for `df.convert_dtypes()`
Answer: If you want to use lambda then you need function with ()
.apply(lambda row: float(row))

if you use it without lambda then use function without ()
.apply(float)

but you could use
.astype(float)

import pandas as pd

data = {
    'A': ['1', '2', '3'],
    'B': ['4', '5', '6'],
    'C': ['7', '8', '9']
}

df = pd.DataFrame(data)
print(df)
print(df.dtypes)

df['A'] = df['A'].apply(lambda row: float(row))
df['B'] = df['B'].apply(float)
df['C'] = df['C'].astype(float)

print(df)
print(df.dtypes)

Answer: You can use this to format float pandas series to int pandas series, yo can reuse for any kind of data:
for col,items in DataFrame.iteritems():
    colitems = DataFrame[col]
    if colitems.apply(lambda x: isinstance(x,float) ).any() == True:
        DataFrame[col] = DataFrame[col].astype(int)


What does "al primo" mean?

Question: I'm currently playing a sonata from the late baroque period, which ends with two menuets: minuetto primo and minuetto secondo.
Now, under the closing repeat mark of menuet two, "al primo" is notated.
I assume, that this means, that the first menuet has to be played again, but I can't match this with the meaning of "al" as known from "al fine" (meaning up to "fine").
An Italian dictionary was not overly helpful. Any confirmation or other ideas?
Answer: Al is indeed 'go to', and primo is 'the first part'. So it must mean go back and replay the first minuet. Probably DC cannot be used, as it would confuse the reader as to the top of which minuet.With no DS or al coda, you'll probably be expected to run straight through the first minuet, but there should be a 'fine' at the very end of the first minuet, to qualify al primo.
Either that, or was the tune written by Mr. and Mrs. Primo's son Al...
Comment: +1 for a joke as bad as I'd make :-) .  I checked & the Bach Suites have "menuetto I DC" at the end of 2nd menuet.  So "Al Primo" sure seems to be the same direction.
Comment: "Al" means "to the," without a verb.
Answer: There isn't any definitions for al primo on both The Concise Oxford Dictionary of Music and Harvard Dictionary of Music, 2nd Edition. I made a quick research and al defined as 'in the manner of' on this web site. And primo usually means 'principal'. Such as it is in tempo primo.
I suggest that it refers to 'a tempo' rather than a repeat. Because, regarding the style of baroque period, you usually repeat the minuet 1 after minuet 2 and minuet 2 usually creates a contrast with minuet 1, like a minuet sandwich. Thus, I think the composer or most probably the editor intended to say 'repeat the first minuet but not as slow as you play the second minuet.'
Another option might be the composer or again most probably the editor intented to express that you don't have to play with variations when you play the first minuet for the second time. This is because depending on the baroque period style you usually make variations when you repeat a minuet, or even a phrase. Therefore al primo might be a stylistic expression to limit or navigate the performer.
My last suggestion is the composer created a piece out of style -which I'm accustomed to thanks to J.S.Bach- and wanted the performer to repeat the second minuet rather than turning back to first minuet but faster this time. In other words; minuet 1(fast) minuet 2(slow) again minuet 2(but this time fast.). Please note that I assumed your first minuet is fast, and the composer wrote an idiomatic piece.
It'd beneficial to listen to the records, especially the ones that played by artists who don't primarily aim to earn a lot of money (which is not a bad thing). Because 'othantic' records usually doesn't sell much, moreover, most performers don't know the baroque style but they know the rules of the revised one. Luckily, I had the chance to study with one of the masters; it's like a beautiful ocean, I just touched my foot to the sea.

What does "al primo" mean?


Redirect loop in CI after installing SSL Certificate

Question: I just installed ssl certificate on my site to change the URL from http:// to https:// Everything is complete and i also added a code in my httpd.conf file to automatically add https :// to the UR So the connection is always secure.
However I am facing a problem when i try to login into the Admin Panel. It Goes in a redirect Loop and the webpage gives me a "This webpage has a redirect loop" Error.
https://mysite.com Loads fine but https:/mysite.com/admin goes into a redirect loop.
site is built up using codeigniter Framework for php.
Please Help.
I added this code to my httpd.conf file
#
# Redirect http Request to https
# The lines below are used to redirect http request to https
#
<IfModule mod_rewrite.c>
     RewriteEngine On
     RewriteCond %{HTTPS} off
     RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</IfModule>

Comment: It's easier to understand if you add the httpd.conf code...
Comment: I have added the code... please let me know if you find something
Answer: Open config file from location application/config/config.php and enable or set hooks to true like this:

$config['enable_hooks'] = TRUE;
Then create a new file named hooks.php inside the config folder (i.e. application/config/hooks.php) and add the following code in it:

$hook['post_controller_constructor'][] = array(
    'function' => 'redirect_ssl',
    'filename' => 'ssl.php',
    'filepath' => 'hooks'
);
Now create a new directory named hooks inside the application folder (i.e. application/hooks) and then create a new file named ssl.php inside the hooks folder (i.e. application/hooks/ssl.php).

Add the following code in the ssl.php file:

function redirect_ssl() {
    $CI =& get_instance();
    $class = $CI->router->fetch_class();
    $exclude =  array('client');  // add more controller name to exclude ssl.
    if(!in_array($class,$exclude)) {
        // redirecting to ssl.
        $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
    } else {
        // redirecting with no ssl.
        $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
    }
}


views exposed filters capable for this?

Question: I try to create something like questionnaire using views exposed filters. I have a content type xxx with fields:
field_1 (with options a,b,c)
field_2 (with options a,b,c)
field_3 (with options a,b,c)

I have 9 nodes, each containing only one option (node_1 has only "a" option from field_1 selected, node_2 has only "b" option from field_1 selected etc... so together 9 nodes)
Task: User chooses from 3 dropdown lists. For example choices are (field_1 - a, field_2 - a, field_3 - c)
I need the result to contain :
node that has field_1 with option "a" checked
node that has field_2 with option "a" checked
node that has field_3 with option "c" checked

Is this possible to acheive using views filters or I need another solution? I would like to use any views solution  Thank you.
Answer: This seems to be a bug in the Views module. If you have an OR filter group, Views will incorrectly use INNER JOIN instead of LEFT JOIN in the query.
One solution is to patch Views - more info & patch: https://www.drupal.org/node/1766338
Another solution that is using hook_views_query_alter that changes the join type by modifying the query object: Changing an inner join to a left join in views 3.3?
A third solution (see comment below) is to check the "Reduce duplicates" checkbox for the filters in the OR group.
Comment: yes that is it. At the end of first link, there is a solution to tick - reduce duplicates, which works. Thank you
Comment: Can you summarize this a little please?  We prefer answers that can stand on their own (as much as possible), and use links for references (eg, to point to the patch).
Comment: @MPD just did it, I hope it's better now.
Answer: Yep.
In your view, set create a filter criteria for each of your fields.
check expose this filter to visitors, allowing them to change it.
Operator should be "is one of"
Edit -------------------------------------------------
I've recreated your issue on my local machine, and am seeing the same issues you are. I have had some success with creating group like this:

I'm only using 2 filters, but selecting [any, a] does give me back 1-a, 1-b, 1-c, 2-a. However, if I select ANYTHING for field 1, that seems to kill it. It's seems as though if views gets a match for the first group, it doesn't try the second... I'll keep trying to figure out what's going on here... very strange.
Comment: I can not get it to work, I have created filters for all fields and tried it with AND and also OR operator but none of them gives me the resuls I want. Moreover combining fields like this gives no results at all.
Comment: yes, again with OR or AND filter, with separate filter groups, I get no results.

views exposed filters capable for this?


Extracting clusters in from pheatmap in different order to distance

Question: I have created a heatmap in R using pheatmap as seen below. I would like to extract the clusters outlined in black, due to the patterns identified within. The problem I have is that the distances are not in the order I wish to extract the clusters. Is there a smart way I can do this whilst still keeping the information contained? I am using Ward D2 clustering method.
I have so far used:
df$clust <- cbind(df, cluster = cutree(pat$tree_col,  k = 4))

but of course this goes by distance. Thanks!
Answer: It is not obvious what you mean by "the distances are not in the order I wish to extract the clusters": a "distance" is a matrix with pairwise distance values, which are symmetric. It is used to induce an ordering among the samples, via some method; the way you compute or use the distance defines the groups/ clusters.
In this case, pheatmap's clusters are computed by hc(.) via some distance -- see ?pheatmap to change the parameters -- and can be accessed from the return object, along with other information.
Did you annotate the figure yourself? It is not even clear if rows are clustered as well; please provide some complete example.
In my experience, however, R package dynamicTreeCut provides you with some interesting dendrogram cutting heuristics, which seem to make sense in many cases.
Paper: https://academic.oup.com/bioinformatics/article/24/5/719/200751
Package: https://cran.r-project.org/web/packages/dynamicTreeCut/index.html
Comment: This is more like a comment where you are asking questions of the OP to better clarify the question.


If $a,b$ are commuting normal elements of a $C^*$-algebra, then does $a$ commute with $b^*$?

Question: If $a,b$ in a $C^*$-algebra, such that $aa^*=a^*a,bb^*=b^*b$, and $ab=ba$.
Then do we have $ab^*=b^*a$ and $a^*b=ba^*$?
Comment: Yes, this is true, but not so trivial to prove. See https://en.wikipedia.org/wiki/Fuglede%27s_theorem The proof I know uses basic complex analysis (Liouville's theorem).
Comment: What do you think, shin chan?  Please add your thoughts, and the source of the question, e.g.
Comment: Please explain what motivates the problem or what research you did before posting.
Answer: This is true, and this result is known as Fuglede's theorem. Here is a proof outline:
(STEP 1) If $A$ is a unital $C^*$-algebra and $a,b \in A$, show that the map
$$f: \mathbb{C}\to A: \lambda \mapsto e^{i\lambda b}a e^{-i\lambda b}$$
is differentiable with $f'(0) =i(ba-ab).$
(STEP 2) Let $A$ be an arbitrary $C^*$-algebra and $a\in A$ normal and $b \in A$ an element that commutes with $a$. Let $\widetilde{A}$ be the unitisation of $A$ and define
$$f: \mathbb{C}\to \widetilde{A}: \lambda \mapsto e^{i \lambda a^*}be^{-i \lambda a^*}.$$
Show that $\|f(\lambda)\| = \|b\|$ for all $\lambda \in \mathbb{C}$ and invoke's Liouville's theorem from functional analysis to deduce that $f$ is necessarily constant (hint: Liouville's theorem applies only to analytic functions that take values in $\mathbb{C}$, so you will have to compose with functionals on $\widetilde{A}$ and use that functionals separate the points).
(STEP 3) Use step 2 to conclude.
Comment: Please read [Enforcement of Quality Standards](https://math.meta.stackexchange.com/questions/33508/enforcement-of-quality-standards?r=SearchResults&s=2|137.4368), which addresses answerers who regularly answer problem statement questions, like this one, which are lacking context.


Condenser mic to two xlr inputs, would phantom power destroy it?

Question: I just got a condenser mic that uses phantom power and I connect this to both of my inputs (using xlr female to 2 xlr male y-Cable) on my scarlet 2i2 audio interface. I needed to do this to record in quicktime (which only records in stereo). This works good so far. But I was wondering if phantom power's powering it twice might it blow up my microphone or something?
Comment: Does the 2i2 not come with some kind of software configuration interface, where you can just pan an input centrally?
Comment: @Tetsujin it does but I didn't find that option.
Answer: It won't blow it up, because the +48V is the same voltage source, via some resistors of typically a few kilohms. So all you are really doing is decreasing the value of the resistors. They aren't critical and the mic should work fine.
But it's really not a good idea, because you are also shorting the inputs of the two mic amps together, and they just are not designed to work like that. At best you might get a degradation in noise performance and so on, at worst things might start to oscillate or do odd things, possibly at frequencies that you will not hear. I mean - it might seem to work, but things are a bit unpredictable and you could run into all kinds of odd problems.
The way to do this (analogue domain) is first put the mic into a preamp, and then connect the preamp out to two line inputs (L+R).
But there is a much easier way - just record a mono track and then use Audacity or similar to duplicate the recording into both channels of a stereo wav file. This is the way to do it with digital perfection.
(Of course, there is such thing as a mono wav file - are you sure you need a stereo one with identical L and R channels?)
Comment: @foreyez how about using instead of QuickTime a proper DAW that doesn't have such an obnoxious limitation? Most of them will just do the right thing by default (mono track to both stereo channels), if you select a mono channel.
Comment: @leftaroundabout gotta do screencast. I did find a software solution though! ffmpeg -i stereo.mov -codec:v copy -af pan="mono| c0=FL" mono.mov
Comment: if I don't do this quicktime just records to one ear. I suppose I could do it with software but it sounds like more work. how about if I used a dynamic mic instead of a condenser one, would I then be "safe"?


How can I prevent my longboard from sliding under me, into the road/pavement

Question: I am new to longboarding/skateboarding. I have picked up the basics and am able to ride confidently. However, sometime I tend to lose balance and the board slides from under my foot and goes ahead of me or behind me depending on how I lose balance. When this happens, the board just darts and wont stop for a significant distance. I am afraid the board might hit somebody's foot or worse, go into the road. Is there anyway to prevent it. I have a silly idea of tying a twine or something similar to it and hooking to up to my bag/pants, but I don't want to look silly.
Answer: The generally accepted solution is to accept that this will happen - you can minimise the risk by kicking the board backward when you bail, but most skaters would rather damage the board than accidentally get hooked up with a leash in traffic, or trip on the leash when trying to bail at speed etc. Boards are meant to take dings anyway.
That said, there are some situations when you might want one, so you can use a leash (a little like a surfer's leash, but tightly coiled so it won't go under the trucks, hopefully) but you will look silly and will get harassed by other skaters :-)
There was someone who invented a 'dead man's brake' that would stop a longboard quite quickly if your foot came off it, but it didn't catch on.


Proving a Probability Limit is Non Zero

Question: I am reading these lecture notes: on page 1, it mentions (indirectly) that :

Define the Score Function as the first derivative of the likelihood
If the Expected Value of the Score Function is not equal to 0, then the resulting MLE estimator will not be Consistent.

I am trying to understand why this is true.
I understand that this is the definition of Consistency in Statistics: An estimator $\hat{\theta}$ is consistent if when the sample size $n$ grows to infinity, the empirical estimator $\hat{\theta}_n$ subtracted from the theoretical estimator $\theta$ has a 0 probability of being greater than some small number $\epsilon$:
$$\lim_{{n \to \infty}} P(|\hat{\theta}_n - \theta| > \epsilon) = 0$$
I also understand how to obtain the Score Function for a given Likelihood Function:

A random variable $X$.

A probability density function (pdf) $f(x; \theta)$.

The likelihood of $f(x; \theta)$ given data $x_1, x_2, ..., x_n$ is

$$L(\theta; x) = \prod_{i=1}^{n} f(x_i; \theta)$$

The log-likelihood is

$$\log L(\theta; x) = \sum_{i=1}^{n} \log f(x_i; \theta)$$

The derivative of the log-likelihood is

$$\frac{d}{d\theta} \log L(\theta; x) = \frac{d}{d\theta} \sum_{i=1}^{n} \log f(x_i; \theta)$$

The MLE estimator of $\theta$ is the only solution $\hat{\theta}$
of the equation
$$\frac{d}{d\theta} \log L(\theta; x) = 0,$$
provided this equation has a unique solution.

The expected value of the derivative of the log-likelihood is zero, i.e.,

$$E\left[\frac{d}{d\theta} \log L(\theta; x)\right] = 0$$
My Question: But mathematically, how can we show that if $E\left[\frac{d}{d\theta} \log L(\theta; x)\right] \neq 0$ , then $$\lim_{{n \to \infty}} P(|\hat{\theta}_n - \theta| > \epsilon) \neq 0$$ ???
Can someone please show me how this can be proven?
Thanks!
Comment: Not sure if this is the proof that you were looking for but, note that, if the derivative of the log likelihood is not zero, then the resulting $\hat{\theta}$ is not the MLE so it is won't be consistent asymptotically.There's a proof somewhere that all MLE's are CAN ( consistently asymptotically normal ).
Comment: Note that the CAN proof might be in one of LeCam's papers or books but his stuff can difficult to read.
Comment: thank you everyone for your replies! can anyone provide an answer to this?
Comment: Note, the expected value of the score function *at the true parameter value* should be zero.
Comment: @ Annika: thank you so much for your reply! If you have time, can you please write an answer! Your answers are always very detailed and I learn a lot from them!
Comment: @Annika provided certain regularity conditions hold
Comment: @JoseAvilez correct
Comment: @stats_noob gave it a shot --  basically you tie strong consistency of the MLE to the definition of maximizer having derivative zero.
Answer: Hi: Note that this is not an answer ( I needed the space ) but here is a proof that the maximum likelihood estimator is consistent
Unfortunately, that does not prove that, if the estimator is not the MLE, then it is NOT consistent. So, this is close to a proof but it's not quite there.
https://www2.econ.iastate.edu/classes/econ671/hallam/documents/Asymptotic_Dist.pdf
I'm not clear on how to prove that the proof is an if and only if.
#====================================================================
ADDENDUM: Later on I found this. It is a thread showing how the MLE convergence proof breaks down when you don't use the MLE in the various steps. So, with a lot of effort, you can probably use this to prove the other direction. I don't have time to go through the details and show it but Alecos' threads tend to be VERY CLEAR.
https://stats.stackexchange.com/questions/127527/in-max-likelihood-the-expected-score-is-zero-for-the-true-values-is-it-also-tr
#===================================================================
11-01-2023: SECOND ADDENDUM TO ANSWER. THIS ONE REALLY IS AN ANSWER.
#======================================================================
stats_noob: I don't have time to write it all out but, re-reading the actual question you posed, it eventually hit me that it's not as hard as I suspected.
STEP 1) Take asymptotic_dist.pdf and read the first 3 sections  extremely carefully atleast upto and including equation 17).
STEP 2) Notice that 17) uses the fact that the expected value of the score ( which is the first derivative of the log likelihood ) = 0. !!!!
STEP 3) But, in the statement of the question, you state the expected value of the score does not equal zero. Therefore, the proof used in the "Consistency of the MLE" section, namely section 3, breaks down and we are done. QED.
If you don't follow above, let me know. But I think that answer is sufficient. To summarize: Statement in question causes plim of $\beta_{0}$ in second order taylor expansion to not be zero.
This ruins the consistency proof so that the aforementioned MLE described in the question statement cannot be consistent.
-
Answer: Let $f(x;\theta)$ be a family of probability densities or probability mass functions and let $\theta_0$ be the true value of the parameter $\theta$.
As mentioned in the comments, we need some regularity conditions. For example, the likelihood needs to be differentiable in some neighborhood around the true parameter value and cannot be on the boundary of the parameter space.
For any $\theta \neq \theta_0$ we have, by Jensen's Inequality:
$$E_{\theta_0}\left[\log \frac{f(X;\theta)}{f(X;\theta_0)}\right] \leq \log E_{\theta_0}\left[\frac{f(X;\theta)}{f(X;\theta_0)}\right]=0$$
To see why, take the continuous case (discrete case is analogous using $\sum$ or this can be expressed in a unified way using Lebesgue integration):
$$E_{\theta_0}\left[\frac{f(X;\theta)}{f(X;\theta_0)}\right] = \int_{\chi}\left[\frac{f(X;\theta)}{f(X;\theta_0)}\right] f(X;\theta_0) dx = \int_{\chi} f(X;\theta) dx = 1$$
This inequality is strict unless $f(x;\theta) = f(x;\theta_0)$ almost everywhere.
Now, let's take a $\delta>0$ to define two quantities:
$$k_1 =E_{\theta_0}\left[\log \frac{f(X;\theta_0-\delta)}{f(X;\theta_0)}\right]$$
and
$$k_2 =E_{\theta_0}\left[\log \frac{f(X;\theta_0+\delta)}{f(X;\theta_0)}\right]$$
Note that $k_1,k_2 < 0$ by our earlier inequality.
Define $\ell_n(x;\theta) := \log \frac{f(x;\theta)}{f(x;\theta_0)}$
Then by the Strong Law of Large Numbers (SLLN):
$$\frac{\ell_n(x;\theta_0-\delta)-\ell_n(x;\theta_0)}{n} \xrightarrow{a.s.} k_1$$
and similarly
$$\frac{\ell_n(x;\theta_0+\delta)-\ell_n(x;\theta_0)}{n} \xrightarrow{a.s.} k_2$$
Therefore, there is an $N$ such that for $\ell_n(x;\theta_0\pm \delta) < \ell_n(x;\theta_0)$ for all $n>N, \delta >0$. By differentiability of the likelihood, we know there exists some $\hat \theta \in ( \theta_0 - \delta, \theta_0 + \delta)$ that maximizes the likelihood. Since this holds for all $\delta> 0$ this means that the MLE is a strongly consistent estimator.
Since $\theta_0$ maximizes the likelihood, we know $$E_{\theta_0}\left[\frac{d \ell_n(x;\theta)}{d \theta}|_{\theta=\theta_0}\right] = 0$$
Comment: That was interesting but stats_noob wants to show the negative I think. By this I mean that he wants to show that, if the parameter doesn't satisfy the derivative being zero ( so not the MLE), then it can't be a consistent estimator. Atleast that's how I took the question. Thanks.
Comment: @ Annika: Thank you so much for your answer! I am currently also working on these questions as well - do you have any ideas about them? https://math.stackexchange.com/questions/4796679/why-is-this-optimization-problem-difficult  https://math.stackexchange.com/questions/4796714/can-we-prove-that-one-of-these-expressions-is-bigger-than-the-other
Comment: @ Mark leeds: thank you so much for your reply! Yes, you are correct - this is what I am looking for. Do you have any idea how to approach this problem? thank you so much!
Comment: @stats_noob: As I said, I think Alecos' approach ( in my addendum ) is the way to proceed. I will print out that thread and look at it either tonight or tomorrow. My guess is that I won't succeed but I surprise myself once in a while !!!!!
Comment: Thank you so much!
Comment: Thank you for your reply! I will review this. I was hoping to see a mathematical answer and must have missed it
Comment: Do you have any ideas about this one? https://math.stackexchange.com/questions/4796679/why-is-this-optimization-problem-difficult

Proving a Probability Limit is Non Zero


Rails actioncable transmits wrong styling

Question: I build a chat using ActionCable. I want the messages to have a different styling wether I or any other User has written them.
Mainly my own messages should be displayes on the right side and the messages from other users should be displayed left.
Here's the issue. When I submit a message, it is displayed with the wrong styling (wrong site) for the other users. A pagerefresh fixes this until a new message is broadcasted.
Is there a way to fix this?
message_partial
- if current_user == msg.user
  .message.me
    .message-body
        %span.message-username= link_to msg.user.name, msg.user, target: '_blank'
        %time
            %i.icon-clock
            = msg.created_at.strftime('%H:%M:%S')

        = raw(msg.content_html)
    = link_to image_tag(msg.user.avatar.url(:extrasmall), alt: msg.user.name, class: "user-img"), msg.user, target: '_blank'
-  else
  .message.other
    = link_to image_tag(msg.user.avatar.url(:extrasmall), alt: msg.user.name, class: "user-img"), msg.user, target: '_blank'
    .message-body
        %span.message-username= link_to msg.user.name, msg.user, target: '_blank'
        %time
            %i.icon-clock
            = msg.created_at.strftime('%H:%M:%S')

        = raw(msg.content_html)

chatroom_partial
App.proom = App.cable.subscriptions.create "ProomChannel",
connected: ->

disconnected: ->

received: (data) ->
    unless data.msg.blank?
        $('#messages-table').append data.msg
        scroll_bottom()
        play_sound()

$(document).on 'turbolinks:load', ->
  submit_msg()
  scroll_bottom()

submit_msg = () ->
  $('#msg_content').on 'keydown', (event) ->
    if event.keyCode is 13
        $('#msg_button').click()
        event.target.value = ""
        event.preventDefault()

scroll_bottom = () ->
  try
    $('.chat').scrollTop($('.chat')[0].scrollHeight)
  catch

Answer: Probably the best way is to add another attribute to the message, like "who", fill it before broadcasting (current_user == msg.user ? 'me' : 'other') and then use it to decide where to append the message.
something like:
if (data.who == 'me') {
  $('.message.me').append data.msg
}


Post-hoc tests for unexpected outcome of binomial models

Question: This may be too abstract for SE, in which case I will post in other forums.
I am running a binomial glm, where my response variables should be A and B. Response A is actually a grouping of A1 and A2. I accidentally ran the binomial model with A1, A2, and B as my responses. I understand that if you run a binomial model (in lme4) with more than 2 response types, it will classify the first level as Failure, and all of the other levels as Success. As such, my 2 levels are A1 and (A2, B).
I would expect that A1 and A2 are more similar, and so a model differentiating A vs B would be better fit than a model differentiating A1 vs A2 and B. However, I get more significant predictors when I run the model that groups A2 and B, although the log-likelihood is better for the model differentiating A vs B.
I have reproduced the output below, and am wondering which post-hoc tests I should run to drill down into these results. I also see that the degrees of freedom are different in each model.
Model 1 - A vs B:
Call:
glm(formula = SQ_DA.2 ~ pre_utt_gap + utt_IKI * utt_speed + edit_ct,
    family = binomial(link = "probit"), data = study1a.SQ.2.df)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.6524   0.4943   0.5830   0.6505   1.1996

Coefficients:
                   Estimate Std. Error z value Pr(>|z|)
(Intercept)        0.886209   0.036701  24.147  < 2e-16 ***
pre_utt_gap       -0.090382   0.026356  -3.429 0.000605 ***
utt_IKI           -0.077471   0.046980  -1.649 0.099142 .
utt_speed         -0.159251   0.035318  -4.509 6.51e-06 ***
edit_ct            0.020672   0.005083   4.067 4.77e-05 ***
utt_IKI:utt_speed  0.032871   0.024022   1.368 0.171202
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 3320.2  on 3591  degrees of freedom
Residual deviance: 3260.4  on 3586  degrees of freedom
AIC: 3272.4

> logLik(model1)
'log Lik.' -1630.184 (df=6)

Model 2 - A1 vs A2 and B1:
Call:
glm(formula = SQ_DA.3 ~ pre_utt_gap + utt_IKI * utt_speed + edit_ct,
    family = binomial(link = "probit"), data = study1a.SQ.2.df)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.5925  -1.0244  -0.9236   1.3036   1.8997

Coefficients:
                   Estimate Std. Error z value Pr(>|z|)
(Intercept)       -0.176418   0.031157  -5.662 1.49e-08 ***
pre_utt_gap        0.082588   0.022572   3.659 0.000253 ***
utt_IKI            0.098559   0.040861   2.412 0.015863 *
utt_speed          0.134524   0.030912   4.352 1.35e-05 ***
edit_ct           -0.015926   0.003912  -4.071 4.68e-05 ***
utt_IKI:utt_speed  0.005229   0.021416   0.244 0.807104
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 4843.1  on 3591  degrees of freedom
Residual deviance: 4792.9  on 3586  degrees of freedom
AIC: 4804.9

> logLik(model2)
'log Lik.' -2396.439 (df=6)

Any suggestions as to where I should look would be greatly appreciated.
Answer: The extra "significant" predictor in the second model, utt_IKI, is involved in an interaction with utt_speed. It can be misleading to evaluate the individual regression coefficient for a predictor involved in an interaction.
In the first model, although the interaction isn't "statistically significant" by the p < 0.05 criterion, it's of a reasonable magnitude. It's quite possible that a Wald test combining the two coefficients involving utt_IKI would be significant. Think of the interaction term in the first model as taking some "credit" away from utt_IKI by itself (which is evaluated at the reference/0 level of utt_speed), while in the second model the interaction is negligible so that there is nothing hiding the contribution of utt_IKI to outcome.
If utt_speed is a continuous predictor, you could probably re-center it to make the utt_IKI coefficient pass the (irrelevant, in this case) p < 0.05 criterion. See here as one illustration of what can be going on.
If you think that there is a reason to treat all of A1, A2 and B separately, you could do a multinomial or ordinal regression with all three as possible outcomes, depending on whether those categories have an inherent order to them.
Comment: Thanks! This is extremely helpful. If I do run a multinomial model with the 3 responses, what's the best way to compare it to the binomial model? Should I just use R^2 or some other goodness of fit?
Comment: @Adam_G R^2 isn't so helpful for examining goodness-of-fit of a binomial or multinomial model. At least that's true of the usual R^2 measures; there are some types of ["pseudo-R^2"](https://stats.oarc.ucla.edu/other/mult-pkg/faq/general/faq-what-are-pseudo-r-squareds/) for models fit by maximum likelihood. Do your three outcome categories have a natural ordering, like `A1` < `A2` < `B` in some sense? Then you should use ordinal regression. Also, ask yourself what specific hypothesis you want to test: what does it mean to compare a model predicting 3 outcomes to one predicting only 2?
Comment: I'm comparing types of sentences, and how people type them (all the predictors are typing patterns/timings). In this case A1=Statement-non-opinion, A2=Statement-opinion, and A3=Question. A vs B is testing Statement vs Question. So in answer to your question, there is no inherent order.
Comment: @Adam_G then think about which really is the "predictor" here. If people are given different types of sentences to type, then type of sentence would seem to be the independent/predictor variable, while "how people type them" would seem to be the set of dependent/outcome variables. Then you could do a true "multivariate" analysis of variance that takes into account correlations among the outcomes. Also, if the same individual is given multiple sentences to type, you need to take that correlation within individuals into account in the model, for example with a random-effects model.
Comment: My experiment was actually a spontaneous conversation; no one was given anything to type. In this case my question is "Are there significant differences in the way people type statements vs questions?" The 2nd half of my study will actually be `typing-pattern ~ sentence-type`, to answer the question of whether sentence types have distinct typing signatures, even if some of those signatures are  the same for some sentence types (there are 10 different types).


When is $x^2 + 4y$ a square?

Question: Sorry if this is a duplicate. And I probably knew this at one point in my life. But I can't remember or seem to find this easily. Can anyone point me in the right diophantine direction?
For $x,y \in\mathbb{Z}$ when is $(x^2 + 4y)$ a square? In particular I am interested in generating all solutions to this Diophantine equation:$$x^2 + 4y = z^2$$
within some bounds for $x$ and $y$, say $|x| < 1000$ and something similar for $y$. Is there a quick way to do something like this (the generation of solutions)?
I know that $z^2 - x^2$ factors so I can, for example, factor $4y$ and list those out for $(z-x)$ and $(z+x)$ but I'm sure there is actually a parametrization of the solutions.
I used to have a great link to a great site that listed the best known ways of generating solutions to all sort of Diophantine equations. But nothing gold can stay, and I've lost the link. If anyone knows what I'm talking about and can provide that link I'd be very grateful as well.
Many thanks for any help.
Comment: $x$ is any number, $y=n(x+n)$ where $n\in\mathbb Z$.
Comment: Given $x$, you can choose any $y=bx+b^2$, for $b$ any integer.
Comment: @IvanNeretin  Please write up the comment as an answer..It is pretty sweet.
Comment: @ThomasAndrews are these the only solutions??
Answer: If $z=x+c$ then $4y=2cx+c^2$. Thus $c$ is divisible by $2$, say $c=2b$. Then you get:
$$y=bx+b^2$$
Comment: No, if $b<-x/2$ then it still works, just algebra. It is not possible fo4 $x^2+4(bx+b^2)=(x+2b)^2$ to be negative. @amcalde
Comment: OK, I see that. I had got previously that $z$ and $x$ had to be the same parity so this make sense.
Comment: One more point, is that $b$ must be greater than or equal to $-x/2$ or else I don't think it works because you'd get a negative value for $x^2 + 4y$. Add that condition and I'll accept.
Comment: OK, yes. I see. Thanks!

When is $x^2 + 4y$ a square?


Why is my manual calculation of the log-likelihood for a 3-level model different than what nlme provides?

Question: In short: I want to manually calculate the log-likelihood of a 3-level multilevel/mixed/hierarchical model, but my result is different from what nlme gives. I don't understand why. Examples of the code and formulae below

Background
I am trying to identify influential cases in a mixed-model. I came across a method proposed by  Coffman & Millsap (2006) who suggest looking into the individual contribution to the overall log-likelihood. For various reasons I find this method preferable to other methods that I've found and after some searching I came across a function that implements this method in R, thelogLik1 function in the nlmeU package.
The function works great for a two-level random effect model. However, it has not yet been extended to accommodate further levels of nesting. Now, my dataset contains longitudinal measures of students within schools, so I would love to apply this method to a three-level model. I've looked into the function and the book by Galecki & Burzykowski (2013) that describes how logLik1 utilizes the likelihood function.
The paper by Longford (1987) describes an extension of the log-likelihood function for $h = 2, ..., m$ levels. The likelihood function is described as follows:
$$\lambda = -\frac{N}{2}\log (2\pi) - \frac{1}{2} \sum_{i=1}^{N} \log [\det(\mathbf{V})] - \frac{1}{2} (\mathbf{y} - \mathbf{X \beta})'\mathbf{V}^{-1}(\mathbf{y} - \mathbf{X \beta}) $$
Were variance of $\mathbf{y}$ is denoted:
$$\mathbf{V} = \sigma_e^2I_N + \sum_{l=2}^{h}\sum_{i=1}^{n_i}\mathbf{Z}_{li}\Theta_l \mathbf{Z}_{li}' $$
and $\Theta_l$ is the variance-covariance matrix at level l and $\mathbf{Z}_{li}$ the matrix of random-effect regressors. An adaption to the logLik1 function should be as simple as adding the matrix Z and D to the sum that calculates V. I've tried to make these adaptions but the sum of the individual log-likelihoods does not correspond to the overall log-likelihood given by nlme.
Function
The function is changed by adding D2 and Z2 to the original code:
# Modified logLik1() function (simplified for readability)
logLik2.lme <- function(modfit, dt1){
  m            <- modfit$modelStruct                 # Model structure, this gets an additional parameter for the top level variance

  sigma        <- modfit$sigma                       # sigma, residual standard deviation
  D            <- as.matrix(m$reStruct[[1]])         # "subject" ;    as.matrix(m$reStruct[[2]]) will get you the top level intercept variance
  D            <- D  * sigma^2                       # Matrix D, design matrix of random effects; VarCorr(modfit)[,c(1,3)] * sigma^2

  D2  <- as.matrix(m$reStruct[[2]]) * sigma^2        # Matrix D2, variance-covariance matrices for random effects at level 2

  vecR         <- rep(sigma, nrow(dt1))
  vecR2        <- vecR^2
  R            <- diag(vecR2, nrow=length(vecR))        # R_i matrix   Residual variance matrix

  # For now I constructed Z and Z2 to handle a two-level random intercept model, this is easily extended.
  n            <- nrow(dt1)                 # No. of obs for subject dt1

  Z            <- model.matrix(m$reStruc, data=dt1)[,1]     # Z_i matrix gets an additional column of 1's to indicate top level intercept, take first column
  Z2           <- model.matrix(m$reStruc, data=dt1)[,2]     # Z2 second column of Z_i matrix to indicate top level intercept

  V            <- R + Z %*% D %*% t(Z) +  Z2 %*% D2 %*% t(Z2)   # V_i matrix; changes with an addition level, because m changes, D changes and Z
  #J <- matrix(1,ncol = n, nrow = n); V <- D[1]*J+ D2[1]*J  + R   # simplified Longford (1987) 2.4

  predY        <- predict(modfit, dt1, level=0)         # Predict fixed level = 0 (Y - XB); These are an individual's residuals without random effects
  #predict(modfit, dt1, level=0)  + ranef(modfit)[1,1] + ranef(modfit)[1,2] * c(0,2:7) == predict(modfit, dt1, level=1)

  dvName       <- as.character(formula(modfit)[[2]]) # Dependent variable name
  r            <- dt1[[dvName]] - predY              # Residuals; observed - predicted

  lLik         <- n*log(2*pi) + log(det(V)) +  t(r) %*% solve(V) %*% r # page 256, formula 13.27 Galecki & Burzykowski (2013)
  return(-0.5 * as.numeric(lLik)) # Divide everything by 2
}

Example
An example shows that the likelihood remains unchanged (even though nlme says the likelihood is increased in the second model):
require(nlmeU)

# Construct a dataset; simple no regressors
set.seed(1010101)
# id's
school.id = rep(1:10, each = 70)
stud.id = rep(1:100, each = 7)
time <- rep(1:7,100)
# random effects
school <- rnorm(10,0,.5)
stud <- rnorm(100,0,1)
e <- rnorm(700,0,.2)
# dependend variable
math <- school[school.id] + stud[stud.id] + e
df1<-as.data.frame(cbind(school.id,stud.id,time,math))

# Create 2 level model
mod2 <- lme(math~ 1,random= list(stud.id = ~1),data=df1,method="ML",na.action=na.exclude)
summary(mod2)

# Create 3 level model
mod3 <- lme(math~ 1,random= list(school.id = ~ 1, stud.id = ~1),data=df1,method="ML",na.action=na.exclude)
summary(mod3)

# Apply the old function to the two-level model and the new function to the three-level model
lLik.i0 <- by(df1,df1$stud.id, function(dfi) logLik1(mod2,dfi))
lLik.i0 <- as.vector(lLik.i0)

lLik.i <- by(df1,df1$stud.id, function(dfi) logLik2.lme(mod3,dfi))
lLik.i <- as.vector(lLik.i)

# This should be the same?
sum(lLik.i0);logLik(mod2)
sum(lLik.i);logLik(mod3)

Please help me, what am I missing?
Answer: The problem stems from the fact that the Z matrix should be reconstructed to account for the nested random effects when computing the V matrix. In this particular example, it should be
Z <- kronecker(diag(10), rep(1, 7))
DD <- matrix(c(D2), 10, 10)
diag(DD) <- diag(DD) + c(D)
V <- Z %*% DD %*% t(Z) + R

Also you will need
lLik.i <- by(df1, df1$school.id, function(dfi) logLik2.lme(mod3, dfi))

Here I've hardcoded it but you could program it to work in the general case.
Comment: The independent units are the schools (level 2 units), and therefore the likelihood of the whole model is written as the product of the likelihood contributions for each school. AFAIC see this cannot be written as the product of the likelihood contributions of the subjects (level 1 units) because the V matrix is a full covariance matrix (i.e., it is not block-diagonal).
Comment: Thank you for your answer. Can you extend your answer please and explain the R Code?
Comment: Thank you for your answer, it helps a lot! Your suggestion works for calculating the likelihood for each level 2 unit. How would you adapt this to calculate the likelihood for each individual (level 1 unit)? I've tried some things but keeping running into incompatible matrices.