Can I change the default schema name in entity framework 4.3 code-first?

Question: Currently I am deploying my application to a shared hosting environment and code-first with migrations has been working great except for one minor hiccup. Everytime I want to push the site I have to use the "Update-Database -script" option because I have to prepend every table name with [dbo] because by default the shared host creates a default schema name that is the same name as the database username.
If I log into my shared host and create a database, I then have to create a user. If I name that user admin, then the tables code-first creates while logged in as admin look something like this "[admin].[BlogPosts]". When the application runs all the tables are created but I get an EF exception because it says "[dbo].[BlogPosts]" is invalid. If I rename the table's schema name to "[dbo]" instead of "[admin]" that fixes it.
To get around this I have to generate a migrations script to be executed manually and add "[dbo]" in front of all the table names because the script only references the tables by their name, not by their schema and their name.
Is there an easy way to get around this? It would be so nice if all I had to do was publish the application and everything just worked. If it wasn't for the schema name discrepancy it would be a one click deploy and everything would be glorious.
Comment: You could try running an [`ALTER USER`](http://msdn.microsoft.com/en-us/library/ms176060.aspx) for your admin account and specify `dbo` as the default schema. (This doesn't answer the question as posed, but may be a solution)
Comment: I actually like this solution far better than having to manually specify table mappings.
Comment: The title of this question is "Can I change the default schema name in entity framework 4.3 code-first?" The accepted answer is the one that I feel best answers that question.
Answer: For those using Entity Framework 6, just use the HasDefaultSchema method:
public class Contexto : DbContext
{
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("MyDefaultDbSchema");
    }
}

Comment: Yay! I'm glad they finally added native support.
Comment: This also works for SQLCE, if you want to leave off the schema entirely. Just use `String.Empty`.
Comment: For those wondering, yes you can just add this one line of code in, and as long as you haven't explicitly set a schema on tables, they will all just 'move' when you do an 'add-migration', then 'update-database'.
Comment: I had a comment on the marked answer... is there a way to get the value of the default schema? without model builder?
Comment: Yeah although i forgot that's why i searched again, this one is the correct answer as it move even migration table to this schema...
Comment: How to change only schema with default table name. Maybe make ToSchema extension method?
Answer: You could use the ToTable method to specify the schema name. If you do not specify the schema name, EF will by convention use dbo.
public class MyContext
{
    private string schemaName = "Foo";

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         modelBuilder.Entity<MyEntity>().ToTable("MyTable", schemaName);
    }
}

Comment: I accepted this, but I did not use it. It is indeed a solution, but I chose to go with the easy option and just change the database user's default schema using Damien_The_Unbeliever's option `ALTER USER admin WITH DEFAULT_SCHEMA=dbo`. Now new tables that don't specify a schema will be created under dbo by default.
Comment: This is an alright solution. Just sucks that I have to explicitly map every single entity to a table. I have a lot of them. I wish I could just specify a default schema name. Or I wish that if EF has decided to go with "dbo" then it should explicitly add "dbo" in front of the table names when it runs the SQL.
Comment: Thank you Alex Ford, After researching 1000 pages, and trying 10 diffrent solutions, i finaly found your comment :D It was the only one working for me, and it was the best solution.
Comment: @JBeckton Not at the time of this question you couldn't. EF 4.3 code-first was a very early code-first implementation. This question isn't relevant to the latest versions of EF.
Comment: @AlexFord True. Wish there was a facility to add custom conventions.
Comment: You can over ride the EF conventions and specify your own schema name.
Comment: In EF7, can I control the schema globally?
Comment: A related question - is there a quick way to find out what the default schema is? I understand it is usually 'dbo' but in case it has been set different by a DBA, is there a way to find out what it is for the context in question?
Answer: In EF Code first, by default, everything is set up based on user access with a managerial access  "DBO-Schema" in the SQL Server. But if a specific user is defined to work with a database that is common in shared hosting, then there will no longer be Dbo management access. This time the names of our tables are dbo.tableName, for example, someUser.tableName, and inaccuracy of this point makes it impossible to run the program. To modify and explicitly assign a user connected to a database. If you use metadata, the following method should be used:
[Table("MyTableName", Schema="MySchemaName")]
public class MyClassName
{
 //Other Lines...
}

Or (Whether or not Fluent API is customizable as follows:)
modelBuilder.Entity<Blog>().ToTable("MyTableName", schemaName:"MySchemaName");

Notice the following:

a good reference for study:
http://www.c-sharpcorner.com/article/fluent-api-in-code-first-approach/
Answer: For database-first implementations, it's easy. Open the edmx file, right click -> Properties and set the default database schema.
For code-first, this article seems most promising: https://web.archive.org/web/20150210181840/http://devproconnections.com/entity-framework/working-schema-names-entity-framework-code-first-design
Comment: This question isn't really relevant with the latest versions of EF code-first. This was an issue in EF 4.3 code-first only. I believe 5 and above no longer have this problem.
Answer: I would like to add since this is for C#, I have written one below for VB
Public Class ClientDbContext
Inherits DbContext
Public Property Clients As DbSet(Of Client)

Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
    modelBuilder.HasDefaultSchema("dbo")
End Sub
End Class


Variable-sized object may not be initializad

Question: Problemas em C. Está aparecendo esse erro:

Variable-sized object may not be initializad

O que fazer para arrumar este erro? Sendo que eu já inicializei tudo.
LINHA 66, 67 e 68
<code>#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
#include <string.h>

void painelPerguntas();
double calculoQtIteracao(double raizA, double raizB, double testeParada);
double calculoC(double raizA, double raizB);
double calculoModuloAB(double raizA, double raizB);
double calculoFxF(double raizA, double resultC);
char verificacaoSinal(double resultFxF);
double trocaAB(double raizA, double raizB, double resultC, char verificacaoSinal);

int main(){
    painelPerguntas();
}

void painelPerguntas(){
    double raizA = 0, raizB = 0, testeParada = 0;
    printf("RAIZ [a]: ");
    scanf("%lf", &raizA);
    fflush(stdin);
    printf("RAIZ [B]: ");
    scanf("%lf", &raizB);
    fflush(stdin);
    printf("PARADA: ");
    scanf("%lf", &testeParada);

    //CALCULO QUANTIDADE DE ITERAÇÕES
    calculoQtIteracao(raizA, raizB, testeParada);
    double qtIteracoes = calculoQtIteracao(raizA, raizB, testeParada);
    int qtIteracao = qtIteracoes;

    // CALCULA VALOR DE C
    calculoC(raizA, raizB);
    double resultC = calculoC(raizA, raizB);;

    //CALCULA |A-B|
    calculoModuloAB(raizA, raizB);
    double resultAB = calculoModuloAB(raizA, raizB);

    //CALCULA F(A).F(C)
    calculoFxF(raizA, resultC);
    double resultFxF = calculoFxF(raizA, resultC);

    //RESULTADO DE SINAL
    verificacaoSinal(resultFxF);
    char resultSinal = verificacaoSinal(resultFxF);

    /*
    printf("\n    N        |    A        |    B         |    C         |   |A-B|        |    F(A).F(C)       |  SINAL");
    printf("\n    %d        |   %lf  |   %lf   |   %lf   |    %lf    |      %lf      |   %c  ", qtIteracao, raizA, raizB, resultC, resultAB, resultFxF, resultSinal);
    */

    //TROCA A/B COM C
    trocaAB(raizA, raizB, resultC, resultSinal);
    double resultTrocaAB = trocaAB(raizA, raizB, resultC, resultSinal);

    //EXIBIÇÃO DO RESULTADO
    printf("\n    N        |    A        |    B         |    C         |   |A-B|        |    F(A).F(C)       |  SINAL");
    int cont = 0;
    for(cont = 0; cont <= qtIteracao; cont++){
        double vetorA[cont] = resultTrocaAB, vetorB[cont] = resultTrocaAB, vetorC[cont] = resultC, vetorAB[cont] = resultAB;
        double vetorFxF[cont] = resultFxF;
        char vetorSinal[cont] = resultSinal;

            printf("\n%d", cont);
    }
}

double calculoQtIteracao(double raizA, double raizB, double testeParada){
    double calculo = (log10(raizB - raizA) - log10(testeParada)) / log10(2);
    return round(calculo);
}

double calculoC(double raizA, double raizB){
    double calculo = (raizA + raizB) / 2;
    return calculo;
}

double calculoModuloAB(double raizA, double raizB){
    double calculo = raizA - raizB;
    if(calculo < 0){
        calculo = calculo * -1;
        return calculo;
    }else {
        return calculo;
    }
}

double calculoFxF(double raizA, double resultC){
    double calculoFA = (pow(raizA,3)) - 3*raizA - 1;
    double calculoFC = (pow(resultC,3)) - 3*resultC - 1;
    double calculoFAxFC = calculoFA * calculoFC;
    return calculoFAxFC;
}

char verificacaoSinal(double resultFxF){
    if(resultFxF < 0){
            char sinalNegativo = '-';
            return sinalNegativo;
    }else{
        char sinalPositivo = '+';
        return sinalPositivo;
    }
}

double trocaAB(double raizA, double raizB, double resultC, char verificacaoSinal){
    if(verificacaoSinal == '+'){
            raizA = resultC;
            return raizA;
    }else{
        return raizA;
    }

    if(verificacaoSinal == '-'){
            raizB = resultC;
            return raizB;
    }else{
        return raizB;
    }
}
</code>
Comment: Quais são as linas 66, 67 e 68?
Comment: A resposta resolveu o que estava em dúvida? Precisa que algo mais seja melhorado? Acha que é possível aceitá-la agora?
Answer: Fiz compilar declarando as variáveis não declaradas, que era o problema (pra mim aquilo é um erro. Talvez a pergunta nem esteja clara. Dei uma boa melhorada geral, mas o código ainda tem vários problemas que eu não posso resolver sem saber o que precisa ser feito. Usei os vetores para evitar o warning do compilador do ideone que sempre fica ligado, como deveria ser mesmo.
<code>#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
#include <string.h>

double calculoQtIteracao(double raizA, double raizB, double testeParada) {
    return round((log10(raizB - raizA) - log10(testeParada)) / log10(2));
}

double calculoC(double raizA, double raizB) {
     return (raizA + raizB) / 2;
}

double calculoModuloAB(double raizA, double raizB) {
    return abs(raizA - raizB);
}

double calculoFxF(double raizA, double resultC){
    return (pow(raizA, 3) - 3 * raizA - 1) * (pow(resultC, 3) - 3 * resultC - 1);
}

char verificacaoSinal(double resultFxF){
    return resultFxF < 0 ? '-' : '+';
}

double trocaAB(double raizA, double raizB, double resultC, char verificacaoSinal) {
    return verificacaoSinal == '+' ? resultC : raizA;
    //o código aqui estava todo errado, isso ainda está errado, mas é o que executaria
}

void painelPerguntas() {
    double raizA = 0, raizB = 0, testeParada = 0;
    printf("RAIZ [a]: ");
    scanf("%lf", &raizA);
    fflush(stdin);
    printf("RAIZ [B]: ");
    scanf("%lf", &raizB);
    fflush(stdin);
    printf("PARADA: ");
    scanf("%lf", &testeParada);

    double qtIteracoes = calculoQtIteracao(raizA, raizB, testeParada);
    double resultC = calculoC(raizA, raizB);
    double resultAB = calculoModuloAB(raizA, raizB);
    double resultFxF = calculoFxF(raizA, resultC);
    char resultSinal = verificacaoSinal(resultFxF);
    double resultTrocaAB = trocaAB(raizA, raizB, resultC, resultSinal);

    printf("\n    N        |    A        |    B         |    C         |   |A-B|        |    F(A).F(C)       |  SINAL");
    //o problema estava aqui, falta declarar os vetores
    double vetorA[(int)qtIteracoes + 1];
    double vetorB[(int)qtIteracoes + 1];
    double vetorC[(int)qtIteracoes + 1];
    double vetorAB[(int)qtIteracoes + 1];
    double vetorFxF[(int)qtIteracoes + 1];
    char vetorSinal[(int)qtIteracoes + 1];
    //isso também não faz sentido no momento
    for (int cont = 0; cont <= qtIteracoes; cont++) {
        vetorA[cont] = resultTrocaAB;
        vetorB[cont] = resultTrocaAB;
        vetorC[cont] = resultC;
        vetorAB[cont] = resultAB;
        vetorFxF[cont] = resultFxF;
        vetorSinal[cont] = resultSinal;
        printf("\n%d %f %f %f %f %f %c", cont, vetorA[cont], vetorB[cont], vetorC[cont], vetorAB[cont], vetorFxF[cont], vetorSinal[cont]);
    }
}

int main(){
    painelPerguntas();
}
</code>
Veja mais ou menos funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


restrict access to IIS virtual directory from root website

Question: I have two domains (domain1.com and domain2.com). Both of them use the same Windows hosting server with IIS7.
One of the domains is being called the "primary domain" by my hosting provider (GoDaddy) and it always points to the root folder that I was given.
For the other domain, I have created a virtual directory in IIS and pointed it there.
The folder structure is like this -
root/
--Default.aspx
--SomeFile.aspx
--domain2folder/
----Default.aspx
----Domain2SomeFile.aspx

So, if I type domain1.com, I see the regulakr Default.aspx. But if I type domain2.com, I am shown the contents of domain2folder as if it were a separate web application - I think that is what IIS virtual directory is meant for. Well and good.
But the problem is, when I type http://domain1.com/domain2folder, I see the domain2's website!
But I don't want that to be shown when I use the path like that from domain1. Only if they use domain2.com, user should be able to see those contents. How can I do that? Hope I am making sense.
Thanks.
Answer: You can use URL Rewrite to prevent access based on the Host header or redirect to the right domain if desired:
http://www.iis.net/download/URLRewrite
If your site is running in IIS 7 or above and your hoster has it installed you can just drop a web.config in your domain2folder with the following contents, it will redirect to the right domain if anybody tries to access it using the wrong domain:
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="HostNameRule">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^domain2\.com$" negate="true" />
          </conditions>
          <action type="Redirect" url="http://domain2.com/{R:1}" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Answer: It seriously doesn't make sense to set it up this way.
You'd typically just set up domain2folder as the root of another web site.


Feeds: Is it possible to set a unique field other than the title field?

Question: I'm trying to create a feed importer that uses a unique ID that is NOT necessarily in the title field of the content type. For example, were I using the feeds importer to import a list of contacts, I'd like to have the unique ID be the phone number, yet I would prefer that the content title be the name of the contact rather than the phone number, for organization and aesthetic purposes. Is this possible? As of now, it seems I am limited to enabling only the title field as unique.
I realize I could simply put the contact name into the title field and set that as unique, but this is less prudent, as contacts may have identical names and similarly with my data, the duplicity of titles and/or misspellings is/are inevitable. Any help would be appreciated!
Thanks!
Answer: For most of my Feeds, I import the Node ID and make that unique.
Comment: Unfortunately, I don't think that will allow me to update the content nodes for which I am continually importing data. If I allow the NID to be unique, I will simply get new content with every upload, where I'd like to update existing nodes.
Comment: You will only get new content when a row in your feed has a blank NID value. If a row contains a valid NID, the corresponding node will be updated accordingly.
Answer: Yes it is. Look at Support unique targets in mappers.


Installing Android

Question: I am having problems installing Android and I would really appreciate your help. My problem is similar to the thread
Installing Android SDK
howeve it seems there people believe it is a problem of Eclipse. It actually is not since when I run the Android SDK Manager(independent from Eclipse at all) the program cant find anything on the repository  https://dl-ssl.google.com/android/eclipse
Can anyone tell me what can I do? have they moved? that URL in a browser says 404 error!
Thanks a lot in advance
Answer: Try to use http if https isn't working. It's not safe, but it works.
http://dl-ssl.google.com/android/eclipse
Answer: There's a manual option to install adt pluings too: http://developer.android.com/sdk/eclipse-adt.html#installing
But it seems like something has changed at google or is offline
Comment: Thanks. Actually I had probelms with the ADT plugging too but in the end could download it. the manual option seems to be for that. now the problem is the "platforms and other components" (there is no manual option for that) . In http://developer.android.com/sdk/installing.html the problem is not the step 3  but the step 4. Help please
Answer: this could be a firewall issue too. if you work in a big company with high network security, most of the ports closed etc, your android avd might be blocked...
if you work at home, switch the firewall off and give it a go!
Comment: good, I'm glad it helped you. please mark this as the correct answer.

Installing Android


Conditional independence given joint

Question: Let us consider variables $A,B,C,D$ such that

$A$ is conditionally independent of $B$ given $C$, i.e. $A \bot B|C$
$A$ is conditionally dependent on $B$ given $D$, i.e. $A \not\bot B|D$

Are $A$ and $B$ conditionally independent of each other given $C,D$? Are they not? Can we conclude anything about their conditional independence?
That is, can we say anything about the following claim? $A \bot B|C,D$
Answer: A situation where $A \perp B \mid C, D$ (dependence arrows run top-to-bottom, i.e. $C \to A$):
<code>D       C
      /   \
     A     B
</code>
A situation where $A \not\perp B \mid C, D$:
<code>  C
 / \
A   B
 \ /
  D
</code>
So we can't say one way or the other.

Conditional independence given joint


Firebase paginating data returns same data?

Question: Currently, I am initially loading the user's messages through :
  func fetchMessages() {

    if started == true {

    let messageRef = Database.database().reference().child("messages").queryOrdered(byChild: "convoID").queryEqual(toValue: convoID).queryLimited(toLast: 10)
    messageRef.observe(.childAdded) { (snapshot) in
        if let value = snapshot.value as? NSDictionary {
            let newMessage = message()
            newMessage.messageText =  value["content"] as? String
            newMessage.sender = value["sender"] as? String
            newMessage.messageID = snapshot.key
            self.messageList.append(newMessage)

            self.queryingStatus = true
            self.messagesTableView.reloadData()
            self.scrollToBottom()
        }

    }
}
}

Now, to minimize the data download, I decided to break the messages into chunks as such so that the user will download ten subsequent messages each time they pull up on the table view:
   @objc func handleRefresh(_ refreshControl: UIRefreshControl) {

    let lastIDDictionary = messageList[0]
    let lastIDQueried = lastIDDictionary.messageID

    let messageRefAddition = Database.database().reference().child("messages").queryOrdered(byChild: "convoID").queryLimited(toLast: 10).queryEnding(atValue: convoID, childKey: lastIDQueried!)
    messageRefAddition.observeSingleEvent(of: .value) { (snapshot) in

        for child in snapshot.children.allObjects as! [DataSnapshot] {

            if let messageValue = child.value as? NSDictionary {

            let newMessage = message()
            newMessage.messageText =  messageValue["content"] as? String
            newMessage.sender = messageValue["sender"] as? String
            newMessage.messageID = child.key

            self.messageList.insert(newMessage, at: 0)
            self.messagesTableView.reloadData()
            }
        }

    }

    refreshControl.endRefreshing()
}

The problem is, when I pull up on the table view, the first time it returns some new messages (I am not sure whether the order is even correct). However, when I pull on the table view again to refresh, it adds those same ten messages again. I printed the lastIDQueried in the refresh method, and after the initial load the ID remains the same even though I am accessing the first item in the array of dictionaries? Basically,when I refresh the table view, it is not querying the correct data and my pagination implementation does not seem to be working correctly.
Answer: Basically, the problem was that I was inserting the post in the wrong place in the array and the last item was still being added to the array which was always the same (as I ended on the value). As such, I added a counter that incremented each time a value was added. Then, I inserted the subsequent post at the counter value in the array then again incremented. Finally, if the message ID was equal to the current first message in array, I would not insert it.


General formula for a diagonal parabola.

Question: What is the general formula for a diagonal parabola facing a given direction with a given vertex (x,y)?
Comment: How do you want to specify the "given direction"? With a unit vector? With an angle measured clockwise from vertical? An angle measured counterclockwise from horizontal? And by "formula", do you want a path that traverses the parabola, the way that $(\cos t, \sin t)$ traverses the unit circle as $t$ goes form $0$ to $2 \pi$, or an implicit expression like $x^2 + y^2 = 1$, which is satisfied by a point $(x, y)$ if and only if the point is on the unit circle?
Comment: to be more clear, I am looking for a f(x,y)=0 type relation with some parameters like theta and a,b that represent the direction and the vertex.
Comment: like you can rotate the parabola around its vertex by changing the angle theta or something.
Answer: The general equation is
$$
y' = mx'^2
$$
where $y'$ and $x'$ are coordinates of a point in a rotated and transalted coordinate system. The good news is that if you're willing to write a point $(x, y)$ as a vector $v = \begin{bmatrix}x \\ y \\ 1\end{bmatrix}$, then the equation of a general parabola is just
$$
v^t M v = 0
$$
where $M$ is the matrix
$$
\frac{1}{2}
\begin{bmatrix}
2d & 0 & 0\\
0 & 0 & 1\\
0 & 1 & 0\\
\end{bmatrix}
$$
The case $d = 1$ corresponds to $y = -x^2$. $d = 2$ corresponds to $y = -(2x)^2$ etc. I went with $ y = -x^2$ to put fewer negative signs in the matrix, and hence give me some hope of getting things right. If you want $y = x^2$ instead, simply rotate by 180 degrees in the formula below (i.e., replace $t$ by $t + 180^\circ$.
If you want to rotate solutions to that equation by an angle $t$ (easier to type than $\theta$), you let
$$
R = \begin{bmatrix}
\cos t & -\sin t & 0\\
\sin t & \cos t & 0\\
0 & 0 & 1\\
\end{bmatrix}
$$
and use the equation
$$
v^t R^t M R v = 0
$$
This will have, as its solutions, the same parabola rotated by angle $t$ clockwise.
Writing $c$ for $\cos t$ and $s$ for $\sin t$, this becomes
$$
\frac{1}{2}
\begin{bmatrix}x & y& 1\end{bmatrix}
\begin{bmatrix}
c & s & 0\\
-s & c & 0\\
0 & 0 & 1\\
\end{bmatrix}
\begin{bmatrix}
2d & 0 & 0\\
0 & 0 & 1\\
0 & 1 & 0\\
\end{bmatrix}
\begin{bmatrix}
c & -s & 0\\
s & c & 0\\
0 & 0 & 1\\
\end{bmatrix}
\begin{bmatrix}x \\ y\\ 1\end{bmatrix} = 0.
$$
Multiplying through by $2$, and doing some matrix multiplies, this becomes
$$
\begin{bmatrix}x & y& 1\end{bmatrix}
\begin{bmatrix}
c & s & 0\\
-s & c & 0\\
0 & 0 & 1\\
\end{bmatrix}
\begin{bmatrix}
2dc & -2ds & 0\\
0 & 0 & 1\\
s & c & 0\\
\end{bmatrix}
\begin{bmatrix}x \\ y\\ 1\end{bmatrix} = 0.
$$
and then
$$
\begin{bmatrix}x & y& 1\end{bmatrix}
\begin{bmatrix}
2dc^2 & -2dcs & s\\
-2dcs & 2ds^2 & c\\
s & c & 0\\
\end{bmatrix}
\begin{bmatrix}x \\ y\\ 1\end{bmatrix} = 0.
$$
Written out without matrices, that's
$$
2dc^2 x^2 - 4dcs xy + 2ds^2 y^2 +2sx + 2cy = 0
$$
and you can substitute in $\cos t$ for $c$ and $\sin t$ for $s$.
To translate that to have its "vertex" at a point $(a, b)$, you could do a similar matrix trick, or something far simpler:
$$
2dc^2 (x-a)^2 - 4dcs (x-a)(y-b) + 2ds^2 (y-b)^2 + 2s(x-a) + 2c(y-b) = 0
$$
And that's your answer. Dividing  by 2 makes it a little prettier:
$$
dc^2 (x-a)^2 - 2dcs (x-a)(y-b) + ds^2 (y-b)^2 + s(x-a) + c(y-b) = 0.
$$
Comment: Great! Thanks a lot!


Como transferir array completo do form para outro arquivo PHP?

Question: Tenho  este form e quero passar o array (tal e qual como está) $array_dos_pagamentos para o recive.php mas só consigo passar valores únicos. Como posso passar o array completo?
<form action='http://www.xxx.com/wp-content/xx/xx/recive.php' method='post'  class="my-form_recibos" target='hidden-form'>
  <input type='checkbox' autocomplete="off" class="" name='enviarmail'    value='yes' >enviar pedido de recibos ?

<input type="hidden" name="result" value="<?php $array_dos_pagamentos); ?>">

  <input type='Submit' value='Salvar'   onclick='saved(<?php echo $fid ?>)' />
</form>

O array:
Array ( [0] => Array ( [nome] => Claudia Mateus [total] => 20 [email] => firstname.lastname@example.com ) [1] => Array ( [nome] => Joana Gonçalves [total] => 20 [email] => email@example.com ) [2] => Array ( [nome] => Paulo Abreu [total] => 20 [email] => firstname.lastname@example.com ) )

Comment: Deve ter solução melhor que essa. Seria legal explicar a necessidade inicial, pois em princípio, se o dado tem que ser reutilizado, provavelmente você já deveria armazenar ele do lado do servidor nem que fosse temporariamente. Ou ao menos manter a estrutura do form original na página seguinte.
Comment: Da onde vem `$array_dos_pagamentos` não seria melhor separar me outros campos?
Answer: Nesse caso você pode transformar o array em um json e no recive.php voltar ele a sua forma original.
<input type="hidden" name="result" value="<?php echo json_encode( $array_dos_pagamentos); ?>">

No recive.php fica assim, a função json_last_error(), detectar erros de sintaxe no json, está disponível na versão 5.3 do php e json_last_error_msg() no php5.5
<?php
    $json = json_decode($_POST['result'], true) or die(json_last_error());
    echo '
';
    print_r($json);

Answer: Existem duas formas para isso, que conheço.
Usando JSON (citado pelo @rray):

Para o formulário:

<?
$json = json_encode($array_dos_pagamentos);
// Isto ira converter a array em json
?>
<input type="hidden" name="result" value="<?= htmlentities($json, ENT_QUOTES, 'UTF-8') ?>">

Para receber os dados:

<?
$array = json_decode($_POST['result'], true);
// Isto irá tornar o JSON em array
?>

Informações em http://php.net/manual/pt_BR/function.json-encode.php
Usando Serialize + HMAC (ou AES-CGM):
Se não puder usar o JSON existe uma alternativa não muito recomendada, usando serialize(), lembre-se de nunca utilizar serialize() sozinho, vise documentação.

Para o formulário:

<?

$serialize = serialize($array_dos_pagamentos);
$hmac = hash_hmac('sha384', $serialize, 'SUA_SENHA');

$value = $hmac.$serialize;

?>
<input type="hidden" name="result" value="<?= htmlentities($value, ENT_QUOTES, 'UTF-8') ?>">

Para receber os dados:

$value = $_POST['result'];

$hmac = mb_substr($value, 0, 96, '8bit');
$serialize = mb_substr($value, 96, null, '8bit');

if(hash_equals($hmac, hash_hmac('sha384', $serialize, 'SUA_SENHA'))){
    $array = unserialize($serialize);
}

Isso irá prevenir que o valor do input seja alterado pelo usuário, o que é um grande problema ao se utilizar o serialize().
Informações em http://php.net/manual/pt_BR/function.serialize.php.
Comment: Faltou escapar o dado serializado antes de por no `value=`. O serialize pode ter uma diversidade de caracteres que quebraria o form/input. A começar por aspas.
Comment: Verdade, havia esquecido isso. Vou editar.
Comment: obrigado com Serialize funcionou  a ver. JSON nao deu por algum motivo :)


Existe um atalho de teclado para alternar entre o terminal e o editor no VS Code?

Question: Eu sei que o atalho Ctrl + Shift + ' abre o terminal e se já estiver aberto ele transfere o cursor de digitação para o terminal, porém eu gostaria de um atalho que alterna entre os dois com mais facilidade, como se fosse um Alt + Tab só que entre o editor e o terminal.
Answer: Tem um jeito bem simples sim
Vamos fazer um passo a passo.
1 - Ctrl + Shift + ' vai abrir o terminal
2 - Ctrl + Tab vai voltar o cursor para a área do Editor
3 - Ctrl + ' vai sai do Editor e voltar pro Terminar
Resumindo, depois que vc abriu o Terminal é só alternar entre Ctrl + Tab e Ctrl + ' para ficar jogando o cursor de um para o outro


Is there any way to edit programmatically nested tables in html file using BeatifulSoup?

Question: I am scraping a table in a webpage with BeautifulSoup. I managed to put the text in a txt file.
However, some  contains multiple tables inside. I guess that the developers had some aesthetic directive and they couldn't edit the cell any other way to meet their requirements. I have many problems in scraping the tables the way they are, so i was wondering if there exists a way to programmatically edit the HTML in order to extrapolate the txt from those nested tables into the original  cell.
Here an example of what I mean.
From a nested table like this

0403

Buttermilk, curdled milk and cream, yoghurt, kephir and other fermented or acidified milk and cream, whether or not concentrated or containing added sugar or other sweetening matter or flavoured or containing added fruit, nuts or cocoa

Manufacture in which:

                   <colgroup><col width="4%">
                   <col width="96%">
                   </colgroup>

—

all the materials of Chapter 4 used are wholly obtained,

                   <colgroup><col width="4%">
                   <col width="96%">
                   </colgroup>

—

all the fruit juice (except that of pineapple, lime or grapefruit) of heading 2009 used is originating,

and

                   <colgroup><col width="4%">
                   <col width="96%">
                   </colgroup>

—

the value of all the materials of Chapter 17 used does not exceed 30 % of the ex-works price of the product

I would like to edit the HTML file in order to get

0403

Buttermilk, curdled milk and cream, yoghurt, kephir and other fermented or acidified milk and cream, whether or not concentrated or containing added sugar or other sweetening matter or flavoured or containing added fruit, nuts or cocoa

Manufacture in which: all the materials of Chapter 4 used are wholly obtained, — all the fruit juice (except that of pineapple, lime or grapefruit) of heading 2009 used is originating, — the value of all the materials of Chapter 17 used does not exceed 30 % of the ex-works price of the product

from all the nested tables in the cells.
Answer: Yes you can do that if your html be always like this.
Find all columns inside each rows and then check if the column has children table
Then get text of all the P tag w.r.t those columns and replace with first P tag text.
Then decompose() all the table tag from the column.
Code:
html='''

0403

Buttermilk, curdled milk and cream, yoghurt, kephir and other fermented or acidified milk and cream, whether or not concentrated or containing added sugar or other sweetening matter or flavoured or containing added fruit, nuts or cocoa

Manufacture in which:

                   <colgroup><col width="4%">
                   <col width="96%">
                   </colgroup>

—

all the materials of Chapter 4 used are wholly obtained,

                   <colgroup><col width="4%">
                   <col width="96%">
                   </colgroup>

—

all the fruit juice (except that of pineapple, lime or grapefruit) of heading 2009 used is originating,

and

                   <colgroup><col width="4%">
                   <col width="96%">
                   </colgroup>

—

the value of all the materials of Chapter 17 used does not exceed 30 % of the ex-works price of the product

'''

soup=BeautifulSoup(html,'lxml')
for row in soup.find_all('tr',class_='table'):
    for col in row.find_all('td'):
        if col.findChildren("table"):
           #Get all the p tag text from col which contains table
           ptag_text=''.join([i.text for i in col.find_all('p')])
           #Get the first p tag and replace the value with previus value
           col.find('p').next_element.replace_with(ptag_text)
           for item in col.findChildren("table"):
                item.decompose()

print(soup)

Output:

0403

Buttermilk, curdled milk and cream, yoghurt, kephir and other fermented or acidified milk and cream, whether or not concentrated or containing added sugar or other sweetening matter or flavoured or containing added fruit, nuts or cocoa

Manufacture in which:—all the materials of Chapter 4 used are wholly obtained,—all the fruit juice (except that of pineapple, lime or grapefruit) of heading 2009 used is originating,and—the value of all the materials of Chapter 17 used does not exceed 30 % of the ex-works price of the product

If you don't want those new lines then do .replace all new lines like below.
finalhtml=str(soup).replace('\n','')
print(finalhtml)

Output:

0403

Buttermilk, curdled milk and cream, yoghurt, kephir and other fermented or acidified milk and cream, whether or not concentrated or containing added sugar or other sweetening matter or flavoured or containing added fruit, nuts or cocoa

Manufacture in which:—all the materials of Chapter 4 used are wholly obtained,—all the fruit juice (except that of pineapple, lime or grapefruit) of heading 2009 used is originating,and—the value of all the materials of Chapter 17 used does not exceed 30 % of the ex-works price of the product

Now if you want to format again then try this
finalhtml=str(soup).replace('\n','')
soup=BeautifulSoup(finalhtml,'lxml')
print(soup.prettify(formatter=None))

Output:

     0403

     Buttermilk, curdled milk and cream, yoghurt, kephir and other fermented or acidified milk and cream, whether or not concentrated or containing added sugar or other sweetening matter or flavoured or containing added fruit, nuts or cocoa

     Manufacture in which:—all the materials of Chapter 4 used are wholly obtained,—all the fruit juice (except that of pineapple, lime or grapefruit) of heading 2009 used is originating,and—the value of all the materials of Chapter 17 used does not exceed 30 % of the ex-works price of the product

Comment: Thanks, I was looking for this since weeks. Everything works perfectly. Just a naive question to be sure I understood how bs4 works: if I do not prettify the final HTML, would it be parsed and then scraped correctly, right? I mean, like the name suggests, '''.prettify()''' is just an aesthetic function for its readability?
Comment: @AleVesprini : yes you are right.If this resolved your problem please mark this as accepted by clicking on hollow under downvote button see this how you can do that https://stackoverflow.com/help/someone-answers


How to embed images in Excel using C#?

Question: I currently have a list of Products in a SQL database, and one of the fields is a blob field that contains an image of the Product, I store it and retreive it using a Byte[] array, and the image is taken from PNG format.  Displaying the images on the website when a user views a Product is working correctly.
What the customer now wants though is an export of all the products to Excel, including the images to be displayed in each row for each product, lets say Column F.
I've not been finding any information online that seems to work - sample code always seems to have an error or reference things that I can't find, which makes me wonder if there's versioning issues.  I'm currently using Visual Studio 2010 and Office 2010 to test this.
I've seen some samples showing how to take the image to Clipboard and paste it, but considering that this will be running on a web server and might have to handle 20 or so products at a time, I'm not sure clipboard would be a good idea for a webserver?
I'd prefer to be able to write it into the excel file directly from the Byte[] array as I'm pulling all the other product data.
Before I update the code on the website, I'm trying to test it locally using a simple Console program.  Once I know I can get an image into Excel, I'll probably write a dll library I can reference on the aspx page.
        var xlApp = new Excel.Application();
        Excel.Workbook xlWorkBook = xlApp.Workbooks.Add();
        Excel.Worksheet xlWorkSheet = xlWorkBook.Worksheets[1];

        byte[] imgdata = File.ReadAllBytes("product.png");

        //what do I enter here to insert the image into cell[1,1]

        xlWorkBook.SaveAs("abc.xlsx");
        xlWorkBook.Close(true);
        xlApp.Quit();

        Marshal.ReleaseComObject(xlApp);

Answer: The key is to use worksheet paste function instead of using AddPicture if you want to use byte data instead of files on hard disk:
Bitmap bmp;
using (var ms = new MemoryStream(imgdata))
{
    bmp = new Bitmap(ms);
    System.Windows.Forms.Clipboard.SetDataObject(bmp, False);
    var rng = xlWorkSheet.Range("A1");
    xlWorkSheet.Paste(rng, bmp);
}

Comment: Would using clipboard be advisable running on a web page?
Comment: I get the error "Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it." - this is similar to another thread I saw the suggestion for clipboard where the guy was saying he was struggling to get it working on an aspx page.
Comment: If you use OLE calls like `Clipboard` you must add `[STAThread]` above the method. https://social.msdn.microsoft.com/Forums/windows/en-US/2411f889-8e30-4a6d-9e28-8a46e66c0fdb/current-thread-must-be-set-to-single-thread-apartment-sta-mode-before-ole?forum=clr
Comment: Is there any way to resize and change the position of the image? I used the above code. It helped but I cannot change the width and height of the image... Any help would be appreciated. Thank you,

How to embed images in Excel using C#?


Binding to TextBox only one-way

Question: I need to bind a List<Key> to TextBox. I've written a converter which converts from List<Key> to string (the ConvertBack method just throws an exception - it isn't used). Problem is that when I try to use this converter, it shows me an error: The TypeConverter for "IValueConverter" does not support converting from a string. It appears that the problem is caused because it's trying to convert string from TextBox to List<Key>, but I don't want to do that (user won't "write" to this TextBox). I've already thought about using something else than TextBox - perhaps TextBlock which I think would solve the problem, but I'd like to use TextBox for some other reasons.
My property I want to bind:
public partial class Settings : Window
{
    public List<Key> hotkeyCapture_keys { get; set; }
    ...

Converter:
class ListKeyToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Join(" + ", (List<Key>)value);
    }
    ...

And TextBox:
<TextBox ... Text="{Binding hotkeyCapture_keys, Converter=ListKeyToStringConverter}" />

When try to Build it, the app immediately shuts down with "XamlParseException occured".
Can anyone tell me how to solve this problem?
Thanks
Answer: Not sure if this is really something you want to do.  If you want a read-only TextBox there are other ways of doing so out there already; one that you mentioned, another being RichTextBox.  But I'll assume you know what you want.
You'll first want to use this in your Convert (don't forget to add using System.Linq;):
return string.Join(" + ", ((List<Key>)value).Select(x=> x.Name));
//where Name is a public property in type Key

Secondly--bingo, TextBox.Text binds Mode=TwoWay by default.  You can change that to OneWay or OneTime:
<TextBox ... Text="{Binding hotkeyCapture_keys, Mode=OneTime, Converter=ListKeyToStringConverter}" />

Also, you're throwing an exception.  Something has to handle that exception.  Nothing is.  Instead of throwing an exception in ConvertBack, just call return null;
Comment: Unfortunately the same problem occurs.
Answer: change your return value in converter to
 return String.Join(" + ", ((List<Key>)value).ToArray());

you can have a look at
WPF textblock binding with List<string>

Binding to TextBox only one-way


Redirect anonymous users to login when they try to access home page for omega sub theme

Question: I would like to redirect my anonymous users to login when they request my Drupal website. I have found many solutions for many themes but not for omega's sub theme. I like my site to limit for authenticated users.
When I used this rule:
<code>{ "rules_test" : {
    "LABEL" : "Test",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "init" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "user\/login" } } ]
  }
}
</code>
browser shows:

The page isn't redirecting properly.

What 's I missing?
Answer: Implement a hook_init().
<code>function YOURMODULE_init(){
  global $user;
  if($user->uid == 0){
    drupal_goto('user/login');
  }
}
</code>
This will work but if you have cache / reverse proxy cache enabled then you might need to consider about a JS solution too.
Comment: Thz @heshanlk. I will try.


Is it true? $\dim(U+W)=\dim(U\cap W)+1$ implies $U\subseteq W$

Question: I'm curious whether or not this statement is true.
If $U,W$ are finite-dimensional space satisfying $\dim(U+W)=\dim(U\cap W)+1,$ then $U\subseteq W.$
Any help would be appreciated!
Thank you
Comment: I think you mean $W$ not $V$. (And you can also have $W \subseteq U$, no ?)
Comment: Let $U$ be $\mathbb R^2$ and $W$ any $1$-dimensional subspace of $U$.
Comment: and of course you probably want to cosider only finite-dimensional sapces
Comment: @HagenvonEitzen Yes its only finite-dimensional
Comment: @nicomezi Thanks for the correction
Answer: Suppose not. Then
$$\dim(U+V)\geq \max(\dim(U),\dim(V))+1>\dim(U\cap V)+1$$
the first inequality follows from the fact that there is one vector in each of the two spaces which does not belong to the span of the other, so the dimension of the cumulative span becomes larger.
The second inequality is strict because of the same reason: the intersection must be of dimension strictly less than the maximal dimension of the two spaces.

EDIT: now that we know that either $U\subseteq V$ (or conversely), we note that
$$U+V=V\quad \text{and}\quad  U\cap V=U.$$
thus the equality becomes
$$\dim(V)=\dim(U)+1$$
Comment: This is interesting, thank you. What if we are going to proof directly, My question: how two spaces subset each other relates to their dimension?
Comment: Can you please rephrase the question? I can't understand what exactly you mean by "how two spaces subset each other relates to their dimension"
Comment: If we want to conclude, say $U\subset V,$ can we deduce such inclusion by the condition only from the dimension of U and of V?
Comment: I've completed my answer, see above


Basic math, Confusion working out chance of failure.

Question: While I am quite technical, I am not a mathematician.  So please be forgiving if this question seems overly simple. My probability abilities left me long ago.
I have a problem which I was arrogant enough to think was simple until I done a few calculations that got me confused.
Lets say we have 2 systems (System A (SA), and System B(SB)). Upon which our overall system relies on.
A typical real world example would be deciding if you want your user to be able to download a library from google server - which is more likely to be cached on the users computer, or download the same library from your own server hosted in the cloud by amazon (on which all your other files reside anyway). This library is obviously something your own system depends on. Now you want to work out the risk of failure considering you have your libraries split across 2 places, instead of on one. However real world is not relevant, I just use that for context so you know where I came across the problem.
Assumption 1: The overall risk of failure if:
SA = 5% and SB = 3% = overall = 15%?

I am assuming this is correct, if not please let me know as this simple math is the basis for my question. Essentially, it is a multiplier, not a divisor or addition?
With assumption 1 assumed to be correct for now, my question is:
As we get closer to either number being 1, the risk of failure grows smaller but is still bigger than either one as long as both are above 1:
SA = 1% x SB = 3% = Overall = 3%

This seems simple, but it's based on assumption 1 being correct.
But once we go below 1 on any or both systems, the risk of failure actually goes down by multiplication, not up:
SA = 0.5% x SB = 0.5% = overall = 0.25%

This doesn't seem right to me, I would have thought it would be 2.5%. I believed the risk of failure should be greater than either of the systems failing combined but this math shows otherwise.
Is there some simple rule for working this kind of thing out consistently for numbers both greater and less than 1 which always give the larger result?
If we change to a divisor, the inverse happens:
SA = 5% / SB = 3% = Overall = 1.67% (smaller than both)
SA = 0.5% / SB = 0.5% = Overall = 1% (bigger than both)

This also introduces the potential of division by zero. As there is a possibility (however remote) that a system will never fail, and that system could in theory be SB. This (along with the number inversion) is the reasons that this approach doesn't feel right.
Or should I be using addition?
SA = 5% + SB = 3% = Overall = 7%
SA = 0.5% + SB = 0.5% = Overall = 1%

While addition consistently gives me larger numbers, I am unsure if this is correct for my circumstances as the last answer doesn't come close to the 2.5% expected, hence my uncertainty on this approach too.
Subtraction would always give a smaller result so I didn't even consider that.
Another reason I am asking is because google-fu comes up with all kinds of crazy formulas for assessing risk of failure on engineering systems, but even my probability at college didn't use formulas like that, so google seems to be failing me.
I'd appreciate any help.
Comment: First of all $0.03\cdot 0.05=0.0015=0.15\%$. But this approach is not correct. The overall failure is the failure, that **at least one** download fail. Therefore you have $0.05\cdot (1-0.03)+(1-0.05)\cdot 0.03+0.05\cdot 0.03$. Or using converse probability $1-$probability that no download fail: $1-0.97\cdot 0.95$
Comment: After you checked it by calculation you can trust both of us. Did you recognize the first part of my comment ? Here you have to be careful.
Comment: @calculus - That sounds strangely familiar. I should have listened more in college :) . Thanks for the comment. By your numbers the risk of failure would be 7.85% for the 5% and 3%. Also .799% if the numbers are 0.5% and 0.3%. In both cases the result is bigger than either numbers. So I would trust this assuming my results are correct?
Answer: For independent events $A, B$,
$$ P(A\text{ and }B) = P(A) P(B). $$
For any two events,
$$ P(A\text{ or }B) = P(A) + P(B) - P(A\text{ and }B). $$
This can be derived either by considering a Euler-Venn diagram or as mentioned in a comment by @calculus.
Then in your example
$$ P(A\text{ or }B) = P(A) + P(B) - P(A) P(B) = 0.05 + 0.03 - 0.05 \cdot 0.03 = 0.0785 = 7.85\%. $$
Comment: Thank you for the formula. I knew I saw that somewhere in college and also for the explanation of independent vs related events are affected. Much appreciated.
Answer: First of all, never do any probability calculations with percentages.
A percentage is just a nice way of saying certain decimal fractions;
that is, we say $15\%$ but the actual number is $0.15$.
If $S_A$ has $3\%$ probability to fail, that's a $0.03$ probability.
If $S_B$ has $5\%$ probability to fail, that's a $0.05$ probability.
If the overall system fails only when both $S_A$ and $S_B$ fail,
then the overall probability of failure is correctly computed by
multiplying the individual probabilities, but it looks like this:
$$ 0.03 \times 0.05 = 0.0015.$$
That is, the probability that both $S_A$ and $S_B$ fail
is $0.15\%$.
In general, if you have redundant subsystems, it will decrease the
probability of failure of the overall system.
(This assumes the subsystems really are redundant, that is,
the overall system can function correctly even when one of the
individual subsystems fails.)
If both subsystems are needed by the overall subsystem, that is,
if the overall subsystem will fail if just one of the subsystems fails,
then the thing to do is to assess the probability that the
system will not fail.
In this case you have $1 - 0.03 = 0.97$ probability that $S_A$ will
not fail, and a $1 - 0.05 = 0.95$ probability that
$S_B$ will not fail.
The probability that neither system fails (that is,
$S_A$ does not fail and $S_B$ does not fail) is
$$ 0.97 \times 0.95 = 0.9215, $$
so the probability that the system fails is $1 - 0.9215 = 0.0785$,
which is $7.85\%$. That is, when you have a system of multiple components
that cannot tolerate the failure of any single component, the
probability of system failure is greater than that of any subsystem.
Comment: I like the way you worked it out. But I really liked the explanation about percentages. I think this is where my confusion was more than anything else as I was using percentages like whole numbers when they are not. This is what led to my confusion. Thanks for clearing that up along with the great example.
Answer: If the overall failure occurs if SA AND SB (both) fail, then you should multiply probabilities, but if the overall failure occurs if SA OR SB (at least one) fails, then you should add the probabilities up.
Comment: Based on this I would use the multiplication result (which is smaller than either number), or the addition result. Neither one of which seems accurate, can you explain more. (for the record, I did not down vote you). Thanks for your answer.


Elliptic integrals, general form

Question: According to https://mathworld.wolfram.com/EllipticIntegral.html, Elliptic integrals are integrals of the form of equation (1).
I am trying to convert an integral of the form
$$\int_{|x_+|}^\infty \frac{dx}{\sqrt{(x^2-x_-^2)(x^2-x_+^2)}}$$
To express as a function of elliptic integrals, where $|x_+|>|x_-|$, we can take $x_+>0$ for simplicity. We can easily see that this integral converges, and that it is real.
I have trying following the method outline in the webpage I linked, with no success, because of the arising of imaginary roots in the process. However, plugging this expression into mathematica with $x_-=1$, $x_+=2$, yields me the expression :
$$\int_{2}^\infty \frac{dx}{\sqrt{(x^2-1)(x^2-4)}}=\frac{i}{2}K(\frac{3}{4})+K(4)$$
Where $K(m) = \int_0^{\pi/2}\frac{1}{\sqrt{1-m\sin^2(\phi)}}d\phi$. Now clearly the integral I'm looking to re-express is well-defined, and real, but it would appear I get an complex number as an answer. However, looking closer, $K(4)$ will be complex because the parameter $m>1$. Thus, if we numerically compute the expression the imaginary parts cancel and we are left with a real answer, which is correct.
So my question is as follows : when we say that Elliptic integrals (as defined in my link) are expressible as a function of the three "kinds" of elliptic integrals (+ elementary functions), do we allow "complex" elliptic integrals ? In other words, is there any way to express my example as a function of "well defined" elliptic integrals, in the sense that we only integrate real numbers ?
I am unsure if I expressed myself clearly, I hope it makes sense.
Comment: Take $u = x_+/x$. You get $(1/x_+) \int_0^1 du/\sqrt {(1 - u^2) (1 - m u^2)}$ with $m = (x_-/x_+)^2$.
Answer: The given integral is $K(1/2)/2$ (convention!), but i will try to follow also a geometric path, the canonical one, detailed in the given particular case $x_-=1$, and $x_+=2$, so that things are easier to type. There will be also numerical check (also for intermediate steps), so that i can calmly sleep tonight.

Let us recall the Complete elliptic integral of the first kind:
$$
K(k)
=
\int_0^{\pi/2}\frac{d\theta}{\sqrt{1-k^2\sin^2\theta}}
=
\int_0^1
\frac {dt}{\sqrt{(1-t^2)(1-k^2t^2)}}\ .
$$
See also DLMF on Elliptic integrals, where $K(k)=F(\pi/2,k)$, and in the definition of $F$ the above convention is used.
Note that the above convention differs from the convention used by Mathematica, as also remarked in loc. cit. .
Taking in the last integral $k=\frac 12$ we obtain an integral "similar" to the given one, at least under the integral, but the limits of integration differ. What can we do?
The lower integration limit $0$ is the point of symmetry for $(1-t^2)(1-k^2t^2)$, and $1$ is one of its roots. In our case, for $(x^2-1)(x^2-4)$ the value $2$ is also a root, so the substitution $t=2/x$ is natural. We get for the given integral $I$ (well, let us have this handy notation):
$$
\begin{aligned}
I&=
\int_{2}^\infty
\frac1{\sqrt{(x^2-1)(x^2-4)}}\; dx
\\
&=
\int_1^0
\frac1{\sqrt{\left(\frac 4{t^2}-1\right)\left(\frac 4{t^2}-4\right)}}\; \left(-\frac 2{t^2}\right)\; dt
\\
&=
\int_0^1
\frac1{\sqrt{(4-t^2)(4- 4t^2)}}\; 2\; dt
\\
&=
\frac12
\int_0^1
\frac1{\sqrt{(1-\frac 14t^2)(1- 1t^2)}}\; dt
\\
&=\frac 12K\left(\frac 12\right)\ .
\end{aligned}
$$

Numerical check using sage, which also suffers from the same convention as Mathematica.
sage: var('x,t');
sage: I = integral( 1/sqrt( (x^2-1)*(x^2-4) ), x, 2, oo, hold=1 )
sage: I.n()
0.8428751774069201
sage: def K(k):    return elliptic_kc(k^2)    # convention
sage: K(1/2).n() / 2
0.842875177406298

pari/gp has the wiki convention, a numerical check using pari, taking advantage of the implementation of ellK, recently made public, October 2020,
is as follows:
? intnum(x=2, oo, 1/sqrt( (x^2-1)*(x^2-4) ))
%1 = 0.84287517740629802143560182889542910036

? \p 60
   realprecision = 77 significant digits (60 digits displayed)

? intnum(x=2, oo, 1/sqrt( (x^2-1)*(x^2-4) ))
%2 = 0.842875177406298021435601828899538494750400447070248008383945

? ellK(1/2)/2
%3 = 0.842875177406298021435601828899538494750400447070544522059974

It seems that Mathematica goes an other way when evaluating the given integral, thus delivering a value which reflects 19.7.3 in DLMF, Legendre's relations, explicitly:
$$K(1/k) = k(K(k)\mp iK(k')\ ,\qquad k^2 + {k'}^2=1\ .$$
In our case, with $k=1/2$, we get $K(2)=\frac 12(K(1/2)\mp iK(\sqrt{3/2}))$.
This is compatible with the result of Mathematica, written in its convention.
This is already an answer to the question.
$\square$

A possible digression: Please ignore, if it feels not related to the question.
This is inserted for my own purpose, so that i can find it next time as an explicit example. For me there is a natural relation, the most natural way to deal with elliptic integrals is to see them explicitly in relation with elliptic curves. We will obtain (after an expensive tour) an other realization of the given integral in terms of the complete elliptic integral, $K(\sqrt{8/9})/3$.
The given integral can be written as
$$
\color{blue}{
I = \int_{(2,0)}^{\infty}\frac{dx}y
} \ ,
$$
and it can be considered on the compact manifold $Q(\Bbb R)$ or $\Bbb C$, where $Q$ is the "quartic curve" (an algebraic variety, thus analytic, thus smooth manifold) with affine equation
$$
Q\ :\ y^2 =(x-1)(x+1)(x-2)(x+2)\ .
$$
(The infinity point is the point $(0:1:0)$ which verifies the projective form, the homogenized form
of this equation, $y^2z^2=(x-z)(x+z)(x-2z)(x+2z)$.)
The idea is to obtain a birational morphism to an elliptic curve.

We use the (birational) transformations:
$$
\left\{
\begin{aligned}
x &=-\frac 4Y(X-5)\ ,\\
y &=2-\frac 4{Y^2}X(X-5)^2\ ,
\end{aligned}
\right.
\qquad
\left\{
\begin{aligned}
X &=-\frac 4{x^2}(y-2)\ ,\\
Y &=\frac 1{x^3}(16(y-2)+20x^2)\ ,
\end{aligned}
\right.
$$
and then
$$
y^2- (x^2-1)(x^2-4)
=
\frac{16(X - 5)^3}{Y^4}\cdot(-Y^2+ X^3 - 5X^2- 16X + 80)\ ,
$$
so we have a passage to the elliptic curve with the equation from the last parentesis,
$$
Y^2 =(X-5)(X-4)(X+4)\ .
$$
We may (or may not) want to keep it simple (and unstructural), thus involve only the substitution
$$
x =
-\frac{4(X-5)}{\sqrt{(X-4)(X+4)(X-5)}}
\ .
$$
We have already made the "natural choice" for the square root.
Note that for $X=2$ we obtain $x=2$. And
$X\searrow -4$ implies $x\nearrow \infty$.

The structure or brute force computations shows now that we have:
$$
\color{blue}{
I=
\int_2^\infty\frac {dx}{\sqrt{(x^2-1)(x^2-4)}}
=
\int_{-4}^2
\frac {dX}{\sqrt{(X-4)(X+4)(X-5)}}\ .
}
$$
This is the passage from the integral on the quartic to an integral on the elliptic curve written in Weierstraß form.

Instead of a proof, here is a
numerical check using pari/gp:
? \p 60
   realprecision = 77 significant digits (60 digits displayed)
? intnum( x=2, oo, 1/sqrt( (x^2-1)*(x^2-4) ) )
%2 = 0.842875177406298021435601828899538494750400447070248008383945
? intnum( X=-4, 2, 1/sqrt( (X-4)*(X+4)*(X-5) ) )
%3 = 0.842875177406298021435601828899538494750400447070446045891423

We are thus in the position to calculate the integral of the canonical differential on the elliptic curve $E$ with equation
$$
(E)\qquad
Y^2=(X-e_1)(X-e_2)(X-e_3)\ ,\qquad e_1,e_2,e_3=5,4,-4,\ e_1>e_2>e_3\ .
$$
The limit of integration $e_1=-4$ corresponds to one torsion point of order two, $(e_1,0)$. The other $2$-torsion points are $(e_2,0)$, and $(e_3,0)$. Can we give a structural sense to the limit of integration $2$ from the blue realtion?!
Yes, the points $(2,\pm 6)$ are ($\Bbb Q$-rational) points on $E$, and they are $4$-torsion points. For this reason we have the chain of relations:
$$
\begin{aligned}
I
&=
\int_2^\infty\frac {dx}{\sqrt{(x^2-1)(x^2-4)}}
\\
&=
\int_{-4}^2
\frac {dX}{\sqrt{(X+4)(X-4)(X-5)}}
=
\int_2^4
\frac {dX}{\sqrt{(X+4)(X-4)(X-5)}}
\\
&=\frac12\int_{e_3=-4}^{e_2=4}
\frac {dX}{\sqrt{(X-e_1)(X-e_2)(X-e_3)}}
\\
&=\frac 12\omega_1(E)\qquad\text{(real half-period of the elliptic curve $E$)}
\\
&=\frac 1{\sqrt{e_1-e_3}}K\left(\sqrt{\frac{e_2-e_3}{e_1-e_3}}\right)
\\
&=\frac 1{\sqrt{5-(-4)}}K\left(\sqrt{\frac{4-(-4)}{5-(-4)}}\right)
\\
&=\frac 13 K\left(\frac{2\sqrt 2}3\right)\ .
\end{aligned}
$$
Let us numerically check again, pari/gp.
? intnum(x=2, oo, 1/sqrt( (x^2-1)*(x^2-4) ))
%10 = 0.842875177406298021435601828899538494750400447070248008383945
? ellK(sqrt(8/9))/3
%11 = 0.842875177406298021435601828899538494750400447070544522059974

Addendum. Computer algebra support for the elliptic curve computations.
Using sage:
sage: var('x,y,X,Y');
sage: def f(x,y): return y^2 - (x^2-1)*(x^2-4)
sage: factor( f(-4*(X-5)/Y, 2-4*X*(X-5)^2/Y^2) )
16*(X^3 - 5*X^2 - Y^2 - 16*X + 80)*(X - 5)^3/Y^4
sage: E = EllipticCurve(QQ, [0, -5, 0, -16, 80])
sage: E
Elliptic Curve defined by y^2 = x^3 - 5*x^2 - 16*x + 80 over Rational Field
sage: for T in E.torsion_points():
....:     if T != E(0):
....:         print(f"Order {T.order()} for the torsion point {T.xy()}")
....:
Order 2 for the torsion point (-4, 0)
Order 4 for the torsion point (2, -6)
Order 4 for the torsion point (2, 6)
Order 2 for the torsion point (4, 0)
Order 2 for the torsion point (5, 0)
Order 4 for the torsion point (8, -12)
Order 4 for the torsion point (8, 12)

This structural aspect explains why, when we compute the integrals of the canonical differential form $\frac{dX}Y$ of $E$ on the intervals delimited (in $\Bbb R$) by the points
$$
-\infty\ ,\
-4\ ,\
2\ ,\
4\ ,\
5\ ,\
8\ ,\
+\infty
$$
we obtain numerically the values for the integral of $(\ (X-4)(X+4)(X-5)\ )^{-1/2}$ on the delimited intervals... (I am taking the absolute value to not confuse sage.)
sage: f = 1/sqrt( abs((X-4)*(X+4)*(X-5)) )
sage: integral(f, X, -oo, -4, hold=True).n()
1.07825782381822
sage: integral(f, X, -4, 2, hold=True).n()
0.8428751689072135
sage: integral(f, X, 2, 4, hold=True).n()
0.8428751680336899
sage: integral(f, X, 4, 5, hold=True).n()
1.0782578072972744
sage: integral(f, X, 5, 8, hold=True).n()
0.8428751637656617
sage: integral(f, X, 8, oo, hold=True).n()
0.8428751775376374

And the above values are related to the periods of $(E)$:
sage: L = E.period_lattice()
sage: L
Period lattice associated to
    Elliptic Curve defined by y^2 = x^3 - 5*x^2 - 16*x + 80 over Rational Field
sage: L.gens()
(1.68575035481260, 1.07825782374982*I)
sage: L.gens()[0]/2
0.842875177406298

Answer: Byrd and Friedman 215.00 gives the answer as
$$\frac1{x_+}K\left(m=\frac{x_-^2}{x_+^2}\right)$$
By the constraints on the variables, the argument always lies in $[0,1]$. This expression is related to the one in the OP's answer by a Gauss transformation.
Nevertheless, elliptic integrals may be evaluated at complex numbers with no hassle, and indeed they are required in a few applications like parametrising minimal surfaces.
Answer: One way to express this integral as a function of the Elliptic Integral K, is as follows. Do the change of variables $x^2 = \frac{x_0+^2}{1-t^2}$. This converts the integral into :
$$
\frac{1}{\sqrt{x_+^2-x_-^2}}\int_0^1 \frac{dt}{\sqrt{(1-t^2)(1+\frac{x_-^2}{x_+^2-x_-^2}t^2)}}
$$
Which can be written formally as $\frac{1}{\sqrt{x_+^2-x_-^2}}K(-\frac{x_-^2}{x_+^2-x_-^2})$. This is fine, but there is an abuse of notation. Usually Elliptic functions are defined for $K(m), 0<m<1$, but here we have a negative $m$. Nonetheless, the integral is defined and convergent, but in principle it is not an Elliptic integral according to the definition.

Elliptic integrals, general form


What is the Galois group of $t^4+2$ over $\mathbb{Z}_5$

Question: I see that $t^4+2$ is irreducible. I now want to find an extension that contains the roots of this - but I'm not sure how to do that.
Comment: Any irreducible polynomial of degree $n$ over the field with $q$ elements splits in the field with $q^n$ elements.
Answer: You are asking for the roots of $x^4=-2=3$ over $\Bbb F_5$, and since $3$ is a primitive fourth root of unity in $\Bbb F_5$, you are asking for the smallest field that contains the sixteenth roots of unity.
In other words, you're looking for the smallest field $\Bbb F_{5^n}$ with $16|(5^n-1)$, thus $16k=5^n-1$, thus $5^n\equiv1\pmod{16}$. The powers of $5$ are $5$, $5^2\equiv9$, $5^3\equiv-3$, $5^4\equiv-15\equiv1$.
So $\Bbb F_{5^4}=\Bbb F_{625}$ is your splitting field, of degree four over the prime field, and so your Galois group is cyclic of order four.
Answer: $t^4+1 = \Phi_8(t)$, hence $t^4+1$ completely splits in a finite field $\mathbb{F}_{p^k}$ as soon as $8$ divides the order of $\mathbb{F}_{p^k}^*$, i.e. $p^k-1$. In our case $p=5$, hence the splitting field of $t^4+1$ over $\mathbb{F}_5$ is $\mathbb{F}_{25}$. That also follows from the fact that over $\mathbb{F}_5$ we have
$t^4+1 = (t^2+2)(t^2+3)$ and neither $-2$ or $-3$ are quadratic residues $\!\!\pmod{5}$. However, you may notice that $t^4+1$ is reducible over $\mathbb{F}_5$, and

If $p$ is some prime, $q(t)=t^4+1$ is never an irreducible polynomial over $\mathbb{F}_p$.

About $t^4+2$: this polynomial is irreducible over $\mathbb{F}_5$, since it has no roots in $\mathbb{F}_5$ and
$$ \gcd\left(t^4+2,t^{25}-t\right) = \gcd(t^4+2,t^{24}-1)=\gcd(t^4+2,(-2)^6-1)=1.$$
It follows that the splitting field of $t^4+2$ over $\mathbb{F}_5$ is $\mathbb{F}_{5^4}$.
Comment: @KyleMiller: it does not. Simply: the OP changed his question after my answer. Now updated.
Comment: Why does $t^4+1$ answer the question about $t^4+2$?


Omitting a moderator

Question: I'm wondering what the effect is if I don't include moderators in my model? Is this the same or different from an omitted variable bias? I am having a hard time grasping this conceptually.
More information: I did a GEE analysis for a binary outcome for a publication. The independent variables were the study group and several demographic variables along with a few other participant characteristics. The CI of the odds ratios were quite wide, but I think it is due to the small sample size. One reviewer indicated we should include moderators in the model to decrease the variability of the estimates. I have never heard of this, so I was wondering if this was correct.
Comment: Can you make this more concrete?  It'd help to see more about the actual scenario, or a simplified or contrived one if that's too complex/sensitive to publicize.
Comment: do you mean to omit the moderator from the model and keep only the interaction terms ?
Comment: I edited the original question to give background information.
Answer: For causal modeling, I think the popular idea is to adjust for precision variables (see Vittinghoff et al "Regression Methods in Biostatistics"). Precision variables are variables that are independent of the exposure of interest but highly prognostic of an outcome. Technically, the actual point estimate shouldn't change much, but the confidence intervals should "narrow" substantially. This is only feasible if you've collected very comprehensive data on the sample and you are able to justify why the variable's role in the multivariate analysis should serve that intended purpose. For this reason, Stephen Senn has advocated using adjustment for prognostic variables in analyses of randomized controlled clinical trial data to improve power and reduce NNT (a very important point!).
Suppose for instance I were looking at the relationship between mammographic breast density and breast cancer risk. Density is a physiologic aspect. Genetic risk factors, such as the presence or absence of the BRCA gene in extreme examples, or family history of breast cancer as a proxy for elevated genetic risk, would serve as a precision variable in such an analysis.
It's very important to ensure that prognostic variables or precision variables are not in the causal pathway (e.g. a direct consequence of the exposure of interest, or a "mediator"). This will eliminate your power to detect an association between the outcome and exposure of interest. Returning to the breast density example, adjusting for prior benign findings or recalled mammographic screens would serve this purpose. Dense breasts are more likely to confuse radiologists and cause them to recall patients for additional screening or even a biopsy. This is one of the ways by which dense breasts are indeed actually associated with greater breast cancer risk, however adjusting for this downstream effect will cause you to infer otherwise.
As a side note, for most categorical analyses (esp logistic regression), the idea that point estimates "do not change" must be relaxed somewhat. This is due to issues of non-collapsibility of the odds ratio. So, while the odds ratio and confidence interval may be compared between models which do and do not adjust for prognostic factors, you may expect small changes in the odds ratio due to this. Contrast that with confounding. I personally never compare adjusted and unadjusted results because I expect point estimates to be substantially different after adjustment for confounding variables, and it's only the latter (confounding adjusted) that I would believe.
Comment: am I correct that the precision variables you refer to are *not* the same as moderators? Not knowing much (but wanting to learn more), my impression is that moderators are variables that *are* related to the exposure of interest.
Comment: I don't think the precision variables are the same as moderators. A moderator is supposed to influence the strength or direction of the association between the dependent and independent variable. So, it is an interaction effect basically. I'm just wondering if omitting a moderator is different from omitting a dependent variable.
Comment: @RussLenth OP's question seems to be the source of the confusion. By referring to the width of the CI as the main problem, they seem to indicate that they are seeking precision variables. It suggests that perhaps they are interested in adjusting for precision (or prognostic) variables.
Comment: AdamO- My question also stemmed from my confusion as to what the reviewer is even talking about. I thought perhaps I was misunderstanding something. I'm also unsure why it matters that the confidence intervals are wide. This is social science research. It doesn't seem to me to be the most important thing to know if women are 3 or 5 times more likely than men to react in a certain way, just that they are significantly more likely.
Comment: @SB3 I would have to have read both the reviewer comments as well as your paper to understand the subtle nuances to the question. I have reviewed a number of studies where the effect size and directions were consistent with hypothesized values, but the tests "failed to achieve significance" (that is an irksome sentence for me). If you said something similar, as in "our study was underpowered" (meaning that the 95% CI actually overlapped a null value), then it makes sense for the reviewer to question whether you have sufficiently utilized adjustment in this study.
Comment: @SB3 on the other hand, such explorations quickly turn into perilous fishing expeditions that greatly inflate type I error rates for inference (due to a large number of models being considered and no controlling for multiple comparisons). It is actually very similar to a phenomenon called Munchaesen's Grid where subgroups defined by adjusted predictors are given undue weight and influence. Perhaps, just maybe, you have a null finding and that is what's most important.

Omitting a moderator


Saving Theme returns TImeout error in Drupal 6.16 after changing server

Question: Everything was working fine till I was on my old server. After migrating it to a new server with same configuration (better memory and added load balancer), when I try saving the theme from the theme page http://mysite.com/admin/build/themes, after waiting for some time I get a 504 Gateway Timeout error from nginx.
Hope I get some response here and the experts can help me resolve this question.
EDIT
I just noticed if I perform any postback operation that is related to Drupal core modules, the issue is present. I am able to add/edit/delete data and do postbacks on admin pages that are created via a custom module, but the page just does nto work when on Core Druapl admin pages -

Save Theme
Clear Cache
Add Node
Answer: Have you made sure that you've allowed enough  time for script execution on your new server? Changing this to a higher value might help:
<code>ini_set('max_execution_time', YOURVALUE);
</code>
Changing theme settings and installing / uninstalling modules needs a longer execution than most other operations I would imagine.
Sorry if my suggestion was already obvious to you.
Comment: Yes, I have checked all I could do. No results. My Server admin says it has something to do with serializing in bootstrap.inc file..
Answer: The issue at my end was related to server configuration. Nginx server was timing out and the load balancer was not redirecting the urls properly.


When I include the html in config it does not work

Question: I am bit confused here, look at the code below:
var arrReqTplTest=["........................."];
var finalStudent=[];
finalStudent.push({
title: "Student Table",
                collapsed: true,
                layout: 'fit',
                items: [
                    {
                        xtype: 'component',
                        itemId: 'StudentTablViewID-' + i,
                        html: arrReqTplTest

                    },
                    {
                        xtype: 'dataview',
                        itemId: 'StudentTable-' + i,
                        height: 200,
                        store: 'studentDetailStore',
                        //itemHeight: 70,
                        scrollable: false,
                        itemSelector: 'div.wrap-requirements-' + i
                    }
                ]
            });
        }

        view.add(finalStudent);
})
}
});

This works fine but now look at the code below which does not work:
 var arrReqTplTest=["........................."];
    var finalStudent=[];
    finalStudent.push({
    title: "Student Table",
                    collapsed: true,
                    layout: 'fit',
                    items: [
                        {
                            xtype: 'component',
                            itemId: 'StudentTablViewID-' + i,
                            config:{
                                    html:arrReqTplTest
                                }

                        },
                        {
                            xtype: 'dataview',
                            itemId: 'StudentTable-' + i,
                            height: 200,
                            store: 'studentDetailStore',
                            //itemHeight: 70,
                            scrollable: false,
                            itemSelector: 'div.wrap-requirements-' + i
                        }
                    ]
                });
            }

            view.add(finalStudent);
    })
    }
    });

Answer: its because "html" is part of component's config.
you are doing it right with the first code:
html: thisIsYourVariableWithHtml //you can store the html value inside a variable or directly paste the value as string

But i will suggest to add:
styleHtmlContent: true,

to make sure that component really render the html value as html.
now in your second code you write:
config: {
    html: thisIsYourVariableWithHtml
}

you are defining custom config variable (dunno what other people call it, but this is my term when defining a property inside component's config object) in this case a object called config that have value "html" and by default sencha's component will not know what to do with this as it is your custom config variable.
Comment: But Sencha's component recognizes html as a config option.
Comment: well if you check by getMyComponent.getConfig().getHtml() yes it return the html value, (that is why i refer it as custom config variable)

but it when it comes to running time and rendering the item on viewport sencha will refer to each of default config inside the "{}" such as: xtype, itemId and etc

I've also checked the default config list of component specificly on the documentation and "config" does not appear http://docs.sencha.com/touch/2.3.1/#!/api/Ext.Component.


Sibelius playback glitch: randomly uneven volume in one score

Question: Recently I went to continue working on an orchestral score that's been sitting on my drive for a couple months, but when I opened it up and started playback, the volume began jumping up and down randomly like a roller-coaster, affecting most (but not all) staves. There's nothing visible in the score that could explain it: no hidden dynamics or other text or symbols, nothing bizarre in the Mixer, etc. The score played back just fine the last time I worked on it.
A few hours of troubleshooting narrowed the problem to the score itself; the issue doesn't replicate in any other score, and all other computer audio (such as music playback) sounds fine. I tried switching audio interfaces (ASIO vs. WASAPI vs. DirectSound, my PreSonus Audiobox USB vs. plain computer audio, etc.), verifying the cables, restarting Sibelius and rebooting my computer, etc. – nothing worked.
Finally, I isolated one particular sequence in the score where the problem is especially noticeable and I then created a new score from scratch in which I replicated the section down to the last note, using the same playback configuration and Mixer settings as the original score. Whilst playback of the original score continues to glitch, the second, new score plays back just fine. However, if I copy elements (such as a staff) from the original score into the new one, the problem then infects the new score as well.
I've saved both files onto my Dropbox, linked below:
» Excerpt 1 – original, glitchy.sib (120 KB)
» Excerpt 2 – recreated, no glitch.sib (48 KB)
(If anyone knows another/better way to attach files to a Stack Exchange post, please let me know.)
To describe the problem as heard in the above-linked "original" file: playback starts too quiet (as if volume was at 30%) for the first bar, then jumps to full volume for the second bar, then falls back down again for the last two bars. The second file ("recreated") plays back at an even, normal volume. (In case it's relevant, the sound library I use in these files is LA Scoring Strings v2.5 for Violins I and II, Viola, Cello I and D.Bass, and Sibelius Sounds for Cello II. The volume glitch occurs with both sound libraries, so this isn't exclusive to LASS or anything.)
So far, all I can think of is to recreate the entire score note-for-note, which would take an eternity.
So here's my two-part question: a) does anyone know what might be causing this bizarre volume glitch, and b) is there any way to fix it in the original score?
Specs:
Sibelius 8.2
Affects all my sound libraries randomly
Windows 8.1 Pro (x64)
Audio interface: PreSonus Audiobox USB (using ASIO driver)

Update 1:
Following @brian-thomas's suggestion in the comments, I tried playing both scores (linked above) back in General MIDI, with interesting results: the volume-jumping went away in the first score, but it played evenly at a much lower volume (maybe 50% or less) than the second score, which plays at full volume. However, I lack any MIDI sequencing software (or knowledge) to test this avenue further.

Update 2:
Following Brian Thomas's latest suggestion, I've exported both excerpts as MusicXML files (linked below) and run them through this difference-checking site, but I don't know much about MusicXML so I can't tell for sure whether the answer is in there. All I see are minor differences in formatting/layout (margins, font sizes, etc.), which I don't think would affect the playback.
» Excerpt 1 – original, glitchy.xml (60.2 KB)
» Excerpt 2 – recreated, no glitch.xml (60.2 KB)

Update 3:
It seems the problem is with my custom House Style specifically. I exported the original score (the full one, not the above-linked excerpt) to MusicXML and imported it back into a new score. The problem was gone. Yet when I import my custom House Style, the problem returns immediately. Hitting Ctrl+Z to undo the House Style import gets rid of the problem again.
So a messed up House Style is the problem. Is there a way to get rid of that? Can you reset a House Style?
Comment: If you export the two score portions to MIDI and then import them into a sequencing program, can you get clues from that? I can't try this myself as I only run Sib 7 and don't have any sequencing sw at all.  Also, do you get the same problem if you use General MIDI sounds rather than sample-based playback?
Comment: Thanks for the suggestion. Playing the scores back with General MIDI gave me interesting results: there's no more volume-jumping, both scores play back at an even volume; however, even with identical Mixers settings (volume sliders in same positions, etc.), the original score plays back only half as loud as the recreated score, which plays back at full volume in MIDI. Unfortunately I don't have any kind of sequencing software either, so I can't test that.
Comment: Export as MusicXML and do a file diff?
Comment: Thanks for the suggestion. I've updated the OP with Update #2. However, I don't know enough about MusicXML to compare them well; all I see are minor formatting/layout differences that shouldn't affect playback.
Comment: I wondered if you export your glitchy score to MusicXML and then reimport it, is it still glitchy?
Comment: I just tried that, and the imported score no longer has any volume bugs (although the formatting is quite messed up, but I take it that's expected when exporting/importing between formats and programs). So whatever causes the volume glitches doesn't seem present in the MusicXML file.
Answer: So I finally identified the problem as a messed-up House Style. I use custom Playback Dictionary entries and other customizations, which I then export and re-import between scores to keep things consistent. When I came back to this score after working on others for a couple months, one of the first things I did was to import my newest custom House Style, and that's when the playback volume issue began.
Luckily, I'm gung-ho about backups, so I was able to pull a version of my score from a few minutes before I imported the screwy House Style, so though I've lost maybe an hour's worth of work on the score, now it works. Fair compromise, I think.
That said, if anyone can comment with any ideas on whether it's possible to reverse changes made by an imported House Style (particularly changes to the score's Playback Dictionary), that would be useful in case the issue ever happened again on a future score.
My thanks to everyone who commented and replied.
Comment: That's interesting.  One of the first things I tried was importing one of the standard House Styles.  Playback was still broken.  And I looked at the Playback Dictionary definitions of the dynamics and hairpins you used, they appeared normal.
Comment: The Playback Dictionary modifications I made were to add pseudo-ghost notes ("g" and "gg") so that bracketed noteheads actually sound quieter, and a few custom dynamics (pppp, più pp, m, più ff, etc.). I don't recall whether I changed anything else. Either way, I don't understand how this could have messed with the playback. What we'd need is a way to completely reset a score's House Style, nixing anything new or changed from the default style, including in the Playback Dictionary, but I have no idea how to do that, or if it's possible.
Comment: You do that by Importing one of the stock House Styles, with all options selected including Playback Directory.   But doing this didn't seem to cure the problem with your score.
Comment: I can confirm that importing a default House Style does not eliminate any new Playback Dictionary entries you may have added. I just tested it in my score: I imported the "Standard Opus (Times)" style with all options selected, and when I opened the Playback Dictionary my custom entries were still present: "g", "gg", "più ff", "più pp", etc. So if anything in there got corrupted in the buggy score, it wouldn't be cleared out just by importing a default House Style.
Comment: You can delete every entry in Staff Text and System Text, the two places where you can create new entries as well as modify stock ones, leaving those categories empty.  Then Import a standard style.  This should reset everything.  But doing it doesn't solve your problem...
Comment: Ah. I hadn't thought of that. Thanks for the tip. In that case it seems something got corrupted on a level that even replacing the Style with a new one couldn't fix.
Answer: If there's an answer to this, it will be found at the main Sibelius support forum.
http://www.sibelius.com/cgi-bin/helpcenter/chat/chat.pl?groupid=3
Do you want me to post your example score there?   Or will you join and do it yourself?
Comment: Thank you for the kind offer, but it is no longer necessary. I've finally identified the problem – a messed-up House Style – and I've worked around it by fetching a good backup copy of my score from before I imported the screwy House Style.
Answer: Have you tried checking the setting of the "Espressivo" feature? (Play -> Interpretation -> Performance)
Depending on how far fetched the variations you mention actually are, the described behaviour could be due to a setting of Espressivo or even Molto Espressivo in a complex multipart score with many expression marks.
If that's the case try setting Performance to "Meccanico".
Comment: Thanks for the reply. I always set my scores to "Meccanico" on everything, since I like to be in total control of dynamics and volume. And it doesn't sound like an Espressivo issue, since that affects certain beats and this glitch affects entire measures.


What can we do with the visualization/understanding of the deep neural network

Question: As far as I know, there is subfield of deep learning that attempt to use gradient to understand what a deep network is learning (e.g., what a filter is detecting). My question is after we know what they are learning, what can do we with those new information (e.g., change architecture design, etc)? Is there any literature on that?
A good Stanford video about visualization deep network.
https://www.youtube.com/watch?v=6wcs6szJWMY
Comment: Well for starters, you have the ability to transfer features between problems. Specifically, taking the convolutional kernels learned in one problem, and using them as initial conditions for another problem. This is especially universal for the first few convolutional layers, but then can diverge since higher level features will vary.
Comment: @AlexR. exactly. But, it would be more useful to interpret deep layer features and how they work.
Answer: Couple of things that can be done with these tools

Checking whether your model's weights make sense when you suspect a bug
Validating that your model doesn't just fit to random noise
Extracting useful features for different models
Compare different models when their performance is similar

I'm by no means an expert on the topic, but it seems like machine learning models interpretability is an active topic - for example you can check out eli5, or techniques mentioned in this repository.
Comment: Great. I will check it out. This topic is interesting.


Where does the drush installtation command set the PROMPT_COMMAND variable?

Question: I installed drush and as part of the installation it makes some changes to the command prompt.
...
# Optional. Enrich the bash startup file with completion and aliases.
drush init
...

Whenever I execute an command at the prompt I get the message:
bash: __drush_ps1: command not found

The env command displays PROMPT_COMMAND as
PROMPT_COMMAND=__git_ps1 "\u@\h \w" "$(__drush_ps1 "[%s]") \\\$ "

I think somewhere at the global level the PROMPT_COMMAND variable is set to that value but I can't locate it in any of the global environment variables and profile scripts.
Because drush was installed as root commands executed as root don't produce that error message. root has a .drush directory with some drush scripts.
Answer: The function that changes the .bash_profile or .bashrc file is drush_init_core_init(). The shell script that effectively sets the prompt is $home/.drush/drush.prompt.sh, where $home is the value returned from drush_server_home(). If the file doesn't exist, drush_init_core_init() creates it from the content of DRUSH_BASE_PATH . "/examples/example.prompt.sh", which contains the following line. (See example.prompt.sh.)
export PROMPT_COMMAND='__git_ps1 "\u@\h \w" "$(__drush_ps1 "[%s]") \\\$ "'

There is also the following line, which sets PS1 and that is is commented out by default. (See the comment before it.)
  # PROMPT_COMMAND is used in the example above rather than PS1 because neither
  # Git nor Drush color hints are compatible with PS1. If you don't want color
  # hints, however, and prefer to use PS1, you can still do so by commenting out
  # the PROMPT_COMMAND line above and uncommenting the PS1 line below:
  #
  # export PS1='\u@\h \w$(__git_ps1 " (%s)")$(__drush_ps1 "[%s]")\$ '

As for the error message you see, __drush_ps1() is a bash function used to change the prompt, defined in drush.complete.sh. bash completion/prompt broken explains exactly when and why you get that error. TLDR; in some circumstances, the shell script is not sourced, and the Bash function results not defined.
For what I understand it, the error has been has been fixed in recent versions, though, so you should just need to update Drush to fix the error.
Comment: The problem is I don't know which file sets the PROMPT_COMMAND in both the user's bash configuration filEs and in /etc/. I'd prefer to change it in there. None of the files in /etc/bash_completion.d contain any command to set PROMPT_COMMAND.
Comment: I will add that information in the answer.
Answer: Kind of simpler work-around to remove that error message - edit:
~/.drusysconfig/bash_prompt

i.e.
nano ~/.drusysconfig/bash_prompt

and remove row:
PS1="\[${BOLD}${MAGENTA}\]\u\[$WHITE\]@\[$ORANGE\]\h\[$WHITE\]:\[$GREEN\]\w \[$PURPLE\]\$(__git_ps1 '(%s)')\[$ORANGE\]\[$WHITE\]\n\$ \[$RESET\]"


Why am I not hearing concepts I'm aware of?

Question: I've been playing guitar for more than 10 years, although not very seriously. I'm not at all gifted, but I'm not tone-deaf either. I've always thought that I'm not meant to understand music, so I didn't try proper ear training or anything. And I've never had any kind of musical training.
I've been taking in more and more music theory, mostly through YouTube channels (12tone, Adam Neely, Rick Beato, Signals Music Studio, Holistic Songwriting...) and some books. But the more I learn, more disappointed I get.
I can't recognise intervals properly (apart from an octave), I can't identify chord quality (I tend to identify lower or quieter ones as minor, and vice versa), I don't ever hear the root or have a "sense of home" when the root note/chord is played, I don't recognise tension and release (you can persuade me you've played a V-I if you only let the last chord ring out longer or strum it slowly), I can't differentiate between I-IV-V and ii-V-I... People talk about chord colour, but I hear it through the qualities of sound (actual sound of a particular instrument or effect), not pitch relationships. And the leading tone? Yeah, I'm not hearing... The list goes on.
What I can do is maybe identify harmonic minor, but you could trick me with Phrygian if you played it with such a purpose, I guess.
I repeat, I'm not tone-deaf. I can sing on pitch most of the time, and although I can't sing an octave above or below very well, I seem to be able to whistle things even more accurately then I can sing them. And I've been exposed and drawn to music that's not exactly "simple", so it's not that I haven't had the chance to hear more than I-IV-V in action.
Is there any way to learn these things? I feel like a colour-blind person being shown a test for colour-blindness. I know the numbers are there, I'm just not seeing them.
Comment: You can't recognize those things just by learning they exist. You have to practice and train your ears, just like you train your fingers to play an instrument. And it takes years, just like playing an instrument.
Comment: Recognising musical things means, "what would I have to do to make it sound like that". How much do you play yourself? How much do you try to play by ear? Do you try to accompany songs by ear? For every hour of youtube videos and internet forums, spend ten hours playing. You only actually learn by doing. Media is mostly just entertainment and a market where your attention is the merchandise. Do you have gigs? Do you accompany songs for friends and family? :)
Comment: When I was young I was a crack in solfege. Since 30 years I am working with computers and I've been realizing how this virtuousity gets lost and lost if I don't imagine or whistle the tones. I have to recover everything.
Comment: Thanks for the comment! I play almost every day, from 15 minutes to 1-2 hours, it depends. I'm not a musician and I do this only as a hobby. I'm not aiming to have the ability of a working musician, but come on! If someone spells it all out and then plays it, I thought I should be able to at least go like "ahh, I get it". Not like "it's all the same to me".
Comment: When you say you "play", can you add a bit more detail? Are you playing from a score? From tabs? By ear? Do you improvise or compose?
Comment: @ToddWilcox Yeah, I get that. But they always speak of chords and cadences as something with a distinct color/flavor. I get that color from the tone of the instrument. I can't identify the same chord if played on acoustic and electric guitar with some effect (not even distortion), for example.
Comment: @topomorto I mostly improvise over pentatonic, harmonic minor and major scale (and its modes). I try adding chords/arpeggios, but they sound like they could be anything. If I play A minor pentatonic, I could easily play over A# or F# key chords and wouldn't notice. Which sometimes actually happens when playing over backing tracks.
Comment: @dzenesiz I'm strongly of the opinion that you do not _learn_ by watching youtube videos. Videos can give ideas that may mean something for those who have developed a sense for the things through practice and therefore can relate to the things. Start ear-training by finding chords to easy songs. Children's songs, Christmas carols, folk music. Use an instrument that gives a strong clear bass note.  Arpeggiate the chords as well, so you hear the notes both individually and as a whole.
Comment: @piiperi thanks. I'll try that. I really thought that we should be able to at least recognise basic concepts from listening to so much music, but I'm happy to see the consensus being that it's more about practice. Sounds doable :)
Answer:
Why am I not hearing concepts I'm aware of?

We have to acknowledge that different people have different abilities. Sometimes these are inborn, sometimes they are learned and of course sometimes there is a combination.
I personally can only marvel when I hear that most conductors can look at a full orchestral score and hear the music in their heads. Their job is then to make the orchestra sound like their imagination. The same is usually true for composers. Mozart was known occasionally to keep his compositions in his head until the last minute and then scribble them down a few minutes before a concert to be sight-read by the musicians.
I do believe that we can maximise our innate ability and Albrecht Hügli has given some good tips - practice makes perfect.
There is a parallel with learning a language. Young children can pick up a new language remarkably quickly - adults not so much. Note that adult learners almost always retain a 'foreign' accent whereas children don't.
The best advice is "Start young!" as did Mozart, but for you and me that is perhaps not possible - I was a late starter in music.
Answer: Here are some things you can do:

Sing everything you play; sing the voicings horizontally and the chords vertically
Follow your inner ear when you play.
Sing canons one voice after the other; try to hear the other voices
Sing the cadence I IV V I horizonally and vertically
Train to sing and hear the resolution of the dom7 (each tone separately!)
Do the same thing with vii°7 chords
Practice singing major and minor triads on the same root
Play the authentic and deceptive cadences, listen to the differences and sing them.
Comment: What do you mean by horizontally and vertically?
Answer:
I feel like a colour-blind person being shown a test for
  colour-blindness.

I'm not a psychologist and I haven't studied pedagogy. But I claim that you develop a better sense for distinguishing colors and tastes and sounds by producing them, not only observing. If you don't see yourself as an active and responsible part of the chain of actions, your observations don't serve anything, you don't even really see, hear or taste things in the analytical sense you want.
For learning to happen there has to be a motivated feedback loop where you are the producer, observer, evaluator, owner and decision maker. If it succeeds, you gain from it, and if it fails, you suffer the consequences. You set out a goal ("throw the ball into the basket"), you try to do it (throw the ball), you observe (look at the trajectory of the ball), you evaluate (did it go in? did it go in only barely or by luck?) and decide if it was what you wanted, you make the decision to try again, something a bit different, or the exact same thing. Repeat. And slowly but certainly, you start to develop a sense for that subject - you start to notice new things about the intricacies of ball throwing, or chord harmony or whatever.
Some people are more "talented" and sensitive to harmony than others, perhaps making the learning process faster, but everyone has to practice. Each time you'll make more and better observations and decisions, and you develop a model of the subject domain in your mind. I strongly believe that you cannot receive the model into your brain from youtube videos or anything, even though that's what everyone would like. That's what technology is for, gain without pain, right? I hope not. Be a subject, not an object.
Practice accompanying easy songs by ear. Use an instrument that gives you a strong bass tone. A real physical acoustic piano might be a good choice, or an acoustic guitar. Play strongly melodic songs that are in C major and can be accompanied with the chords C, F and G, maybe also Am, Dm, E for the minor side of music. Every once in awhile, look at ready-made answers from lead sheets and play the songs from there. Then put the written music away and try to play it again. Try other songs you've never seen written music for, but that are familiar to you. Repeat this. If possible, boost your motivation by trying to do it with an audience. ;) Or imagine there's an audience. But you have to believe very deeply that getting it right matters, like your life depended on it or something.
Answer:
Why am I not hearing concepts I'm aware of?

Most theory concepts aren't inherently "there in the sound" - they just are a way that we choose to model the sounds, or the way those sounds are produced. Often, music theory even offers us more than one way to model a certain sound - if you could actually "hear" the theory concepts, you'd be hearing more than one thing at once.
So - listening to (or even playing) music in itself won't teach you music theory. Learning music theory will teach you music theory, but it won't necessarily teach you to relate that theory to the music you hear, which seems to be where you feel you could improve.
Personally, I found the best activities to do for relating theory to sound are not playing, but composition and figuring out songs by ear. Both of these activities encourage you to use music theory because the theory makes the process a lot easier; you're also naturally constantly correlating the sound with the concept.