Converter Binário fracionário"flutuante" para Decimal

Question: Então galera alguém aqui sabe como eu faço para converter
1,01010101 para base 10 no caso esta em base 2 "binaria" a resposta é essa em base10 1.3320312510
.
Preciso da logica para tratar esse caso ..
att
#include<stdio.h>
#include<stdlib.h>

int c[18],bcd[20];

//Função de conversão de decimal para binário

void conv_d2b ( unsigned long x,int *c)
{
    int i;
    for(i=0; i<18; i++)
        *(c++)=(x>>i)&0x1;
}

int main()
{
    int escolha;
    double bina ,deci ;
    int k;
    unsigned long int j,x;
    int pos, decimal=0;
    char numb[17];
    int cont=0;

    printf("Conversor de numeros binarios e decimais \n\n");
    printf(" ----------Menu----------\n 1 - Binario para decimal\n 2 - Decimal para binario\n 3 - Decimal fracionario para binario\n 4 - Binario'flutuante' fracionario para Decimal\n 5 - Exit\n\n Opcao: ");
    scanf("%d", &escolha);

    switch(escolha)
    {
    case 1:
        //Conversão de BInarios para Decimal

        printf("Digite um numero Binario qualquer");
        scanf("%s",numb);
        //Processamento da informação
        for (pos=strlen(numb) -1; pos >=0; pos--)
            decimal=decimal + (numb[cont++] - '0')*pow(2,pos);
        //Exibindo a informação
        printf("Seu numero Binario em Decimal eh: %d\n\n", decimal);

        break;

    case 2:

        printf("Digite o numero que deseja converter :");
        scanf("%lu",&x);
        printf("\n\n       \t  Decimal\t      Binario\n");

        printf("   ----  %lu\t    ", x);

        conv_d2b(x,c);
        for(k=17; k>=0; k--)
            printf("%d",c[k]);
        printf("\n\n\r");
        break;

    case 3:

        break;
    case 4:

        break;
    case 5:
        exit(0);
        break;
    default:
        printf("Opcao invalida");
        break;
    }

    return 0;
}

fiz algo assim
int main()
{
    int  inteiro, binarioInt = 0, i = 1;
    float  binarioFrac = 0, k =0.1f, frac, temp1, binarioTotal, f;

    printf("***** Converter valor FLOAT para BINARIO *******\n");
     printf("***** POR FAVOR UTILIZE PONTO PARA SEPARAR OS NUMEROS *******\n");
    printf("\nEnter com o valor : ");
    scanf("%f",&f);

    //Separando parte inteira
    inteiro = (int)f;

    //Separanto parte fracionada
    frac = f - (int)f;

    //Loop para converter decimal parte inteira em binario
    while(inteiro>0)
    {
        binarioInt = binarioInt + inteiro % 2 * i;
        i = i * 10;
        inteiro = inteiro / 2;
    }

    //Loop para converter fracao em binario
    while(k>0.00000001)
    {
        temp1 = frac *2;
        binarioFrac = binarioFrac+((int)temp1)*k;
        frac = temp1 - (int)temp1;
        k = k / 10;
    }

        //
        binarioTotal = binarioInt +binarioFrac;
        printf(" \nbinary equivalent = %lf\n\n\n\n\n", binarioTotal);
}

Answer: Isso é fácil de se resolver com matemática básica:
1.01010101

é o mesmo que
101010101 / 100000000

(basta contar as casas depois da vírgula)
 Binário       Decimal
 101010101 ÷   314 ÷
 100000000     256
────────────  ─────────────
 1.01010101    1.332031251

Em resumo, basta converter normalmente, e trabalhar em decimal.
Para simplificar, conte as casas depois da vírgula, faça 2 ^ Número de casas1 e use como divisor:
1.01010101
  └───┬──┘
      └── 8 casas

101010101 = 314
    2 ^ 8 = 256
    │   └───────── 8 casas
    └───────────── base 2, binário. Se fosse decimal, seria 10, hexadecimal 16 etc.

314/256 = 1.332031251

1. Estou usando a ^ b para indicar a elevado a b.
E se fosse hexadecimal?
Mesma coisa:
  F,1BC
    └┬┘
     └── 3 casas

  F1BC = 61884
16 ^ 3 =  4096
 │   └───────── 3 casas
 └───────────── base 16

61884/4096 = 15,1083984375

Nota: eu vi a outra pergunta aqui no site sobre mostrar número com casas decimais em binário. Acho que fica muito mais simples usar esta mesma técnica aqui naquele caso também:
Vá multiplicando o número por 2, até não ter mais decimais. Anote quantas vezes multiplicou. O número de vezes é a posição da vírgula no binário. (se quiser adiantar esta etapa, dá pra deduzir com logaritmo, mas como está fora da pergunta atual, não vou entrar em detalhes).
Uma coisa que eu já mencionei em outra questão e se aplica neste caso: independente da base que você trabalha, a matemática é a mesma.
Answer: Fugindo um pouco da teoria e indo direto a pratica.
#include <string.h>
#include <stdio.h>

int bin2des(unsigned long long bin){
    int x;
    int y;
    char num[18];
    sprintf(num,"%d",bin);
    x = strlen(num);
    y = 1;
    int res;

    while(x--){
        if(num[x] == '-')
            res *= -1;
        else
            res += (num[x]-48)*y;
        y *= 2;
    }

    return res;
}

void main(){
    printf("%i\n",bin2des(101));
}

Comment: Eu consegui fazer aqui depois eu envio o código pra caso alguém queira !!!
Comment: @MatheusFrancisco mesmo a pergunta sendo sua, você pode postar sua solução no espaço para respostas. É uma prática normal, e também é uma maneira de ajudar outras pessoas com o mesmo problema.
Answer: Desculpa a demora para postar a resposta ..
Caso alguém consiga de outras formas só enviar, seria de ajuda para muitos.
No caso o programa ai também converte decimal float para binário,
binario float para decimal...
/*Trabalho de Calculo numerico  - Converter numero binario para numero decimal*/

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<math.h>
#define max 30

int fraci[max],inteiro[max];

//Funcoes
void decimalparabinario();
void binarioparadecimal();
float pow();
//Fim Funcoes

int main()
{
    int op;
    float aux,num,f;
    int i,cnum,ch;
    do
    {
        printf("===== Menu ======\n");
        printf("1. Binario para Decimal\n");
        printf("2. Decimal para Binario\n");
        printf("3. Sair\n");
        printf("Digite uma opcao: \n");
        scanf("%d",&op); //
        system("clear"); //Comando utilizado para limpar tela

        switch(op)
        {
        case 1:

            binarioparadecimal();
            system("PAUSE");

            break;
        case 2:
            decimalparabinario();

            system("PAUSE");

            break;
        case 3://Sair do programa
            printf("Saindo..\n");

            break;
        default://Caso não seja nenhuma das anteriores...
            printf("Opcao Invalida\n");
            break;

        }

    }
    while(op != 3);

    system("PAUSE");

    return 0;
}

void decimalparabinario(){

    float numero,f;
    int i,cnum,t;

    printf("Digite um numero Decimal  : ");
    scanf("%f",&numero);
    printf("\n");

    f=numero-(int)numero;

    for(i=0; i<max; i++)
    {
        f=f-(int)f;
        fraci[i]=(int)(f*2);
        f*=2;
    }

    cnum=(int)numero;
    for(i=max-1; i>=0; i--)
    {
        if(cnum%2==0)
        {
            inteiro[i]=0;
        }
        else
            inteiro[i]=1;
        cnum/=2;
    }

    printf("O numero em Binario é igual   = ");
    t=0;

    for(i=0; i<max; i++)
    {
        if(inteiro[i]||t)
        {
            t=1;
            printf("%d",inteiro[i]);
        }
    }
    printf(".");

    for(i=0; i<7; i++)
        printf("%d",fraci[i]);

    printf("\n");

}

void binarioparadecimal()
{
    char num[50];
    int antesDec[50], depoisDec[50];
    int antesDecnum, depoisDecnum, tint=0, l, j=0, k=0;
    float fract=0, floatValue;
    char p = 'd';

    printf("******* Insira o binario para converter  para decimal *********\n");

    //
    printf("Digite o numero binario : ");
    scanf("%s",&num);

    //Separa o inteiro do fracionado

    for(l=0; l<strlen(num); l++)
    {
        if(num[l]=='.')
        {
            p='u';
        }
        else if(p=='d')
        {

            antesDec[l] = (int)num[l]-48;
            k++;
        }
        else
        {
            depoisDec[j] = (int)num[l]-48;
            j++;
        }
    }

    // Armazena o tamanho do inteiro e do fracionario
    antesDecnum = k;
    depoisDecnum= j;

    //Converter parte inteira para decimal
    j=0;
    for(l = antesDecnum-1; l>=0; l--)
    {
        tint = tint + (antesDec[l] *(int) pow(2,j));
        j++;
    }

    //Converter parte fracionaria para decimal
    j = -1;
    for(l = 0; l<depoisDecnum; l++)
    {
        fract = fract + (depoisDec[l]*pow(2,j));
        j--;
    }

    //Juntando as duas partes
    floatValue = tint + fract;
    printf("Numero em decimal é  = %f\n\n\n\n\n",floatValue);

}
float pow(int c, int d)
{
    float pow=1;
    if (d >= 0)
    {
        int i = 1;
        while (i <= d)
        {
            pow = pow * c;
            i++;
        }
    }
    else
    {
        int i = 0;
        while (i > d)
        {
            pow = pow/c;
            i--;
        }
    }
    return pow;
}

// intnum = numero inteiro.
// fracnume = numero fracionario

Comment: Sempre que possível é preferível usar `double` para números de vírgula flutuante. Todas as operações com `float` convertem primeiro esse valor no tipo `double`, por exemplo: `float x = 4.2; x *= 2; /* operação feita em double */`. Além disto os processadores aritméticos actuais estão optimizados para o tipo `double` fazendo com que operações com tipos `float` sejam mais lentas embora o número de bits usado seja menor.
Comment: Ótima dica, vou usar nos proximos!!!


Unable to access web application after upgrading from .Net Framework 4.6 to .Net Framework 4.8

Question: I have a web application was running on IIS 6.0 and was targeting .Net Framework 4.6.1. I have recently upgraded IIS to version to and I have installed .Net Framework 4.8 both on my development machine and my web server. I have confirmed that version 4.8 is running on the server by following the steps outlined here. I also made sure to change the Target Framework to 4.8 by going to the project property pages. After creating a new application in IIS 10 and moving the published files to the directory, I visit the application URL to find the following error:

BC31007: Unable to open module file 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\the_application\0d68bd1e\5c2220e1\App_Web_the_application_page.aspx.cdcab7d2.foubj9oz.0.vb': System Error &Hc0000005& (Visual Basic internal compiler error)
c:\windows\system32\inetsrv> "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\vbc.exe" /t:library /utf8output /R:"C:\windows\Microsoft.Net\assembly\GAC_64\System.Data\v4.0_184.108.40.206__b77a5c561934e089\System.Data.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_220.127.116.11__b77a5c561934e089\System.IdentityModel.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_184.108.40.206__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_126.96.36.199__31bf3856ad364e35\System.Activities.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_64\System.Web\v4.0_188.8.131.52__b03f5f7f11d50a3a\System.Web.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\the_application\0d68bd1e\5c2220e1\assembly\dl3\56a54d06\835fed79_c7a0d601\App_Web_the_application_page.aspx.cdcab7d2.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_220.127.116.11__b77a5c561934e089\System.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_220.127.116.11__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ComponentModel.DataAnnotations\v4.0_22.214.171.124__31bf3856ad364e35\System.ComponentModel.DataAnnotations.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_126.96.36.199__b03f5f7f11d50a3a\System.Drawing.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_18.104.22.168__b77a5c561934e089\System.Data.DataSetExtensions.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_184.108.40.206__b03f5f7f11d50a3a\Microsoft.CSharp.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Services\v4.0_18.104.22.168__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.DynamicData\v4.0_126.96.36.199__31bf3856ad364e35\System.Web.DynamicData.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.ApplicationServices\v4.0_188.8.131.52__31bf3856ad364e35\System.Web.ApplicationServices.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activation\v4.0_184.108.40.206__31bf3856ad364e35\System.ServiceModel.Activation.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_184.108.40.206__b77a5c561934e089\System.Runtime.Serialization.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel\v4.0_220.127.116.11__b77a5c561934e089\System.ServiceModel.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_188.8.131.52__b77a5c561934e089\System.Xml.Linq.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_126.96.36.199__b77a5c561934e089\System.Core.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_64\System.EnterpriseServices\v4.0_22.214.171.124__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_126.96.36.199__b77a5c561934e089\System.Xml.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_188.8.131.52__31bf3856ad364e35\System.ServiceModel.Activities.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\the_application\0d68bd1e\5c2220e1\assembly\dl3\4c4b96c5\b638438d_bca0d601\Interop.IWshRuntimeLibrary.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Entity\v4.0_220.127.116.11__b77a5c561934e089\System.Web.Entity.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Extensions\v4.0_126.96.36.199__31bf3856ad364e35\System.Web.Extensions.dll" /R:"C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_184.108.40.206__b03f5f7f11d50a3a\System.Configuration.dll" /out:"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\the_application\0d68bd1e\5c2220e1\App_Web_the_application_page.aspx.cdcab7d2.foubj9oz.dll" /D:DEBUG=1 /debug+ /nowarn:41008,40000,40008 /define:_MYTYPE="Web" /imports:Microsoft.VisualBasic,System,System.Collections,System.Collections.Specialized,System.Configuration,System.Text,System.Text.RegularExpressions,System.Web,System.Web.Caching,System.Web.SessionState,System.Web.Security,System.Web.Profile,System.Web.UI,System.Web.UI.WebControls,System.Web.UI.WebControls.WebParts,System.Web.UI.HtmlControls /warnaserror- /optionInfer+  "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\the_application\0d68bd1e\5c2220e1\App_Web_the_application_page.aspx.cdcab7d2.foubj9oz.0.vb" "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\the_application\0d68bd1e\5c2220e1\App_Web_the_application_page.aspx.cdcab7d2.foubj9oz.1.vb"

Microsoft (R) Visual Basic Compiler version 14.8.3761
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to Visual Basic 2012, which is no longer the latest version. For compilers that support newer versions of the Visual Basic programming language, see http://go.microsoft.com/fwlink/?LinkID=533241
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\the_application\0d68bd1e\5c2220e1\App_Web_the_application_page.aspx.cdcab7d2.foubj9oz.0.vb : error BC31007: Unable to open module file 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\the_application\0d68bd1e\5c2220e1\App_Web_the_application_page.aspx.cdcab7d2.foubj9oz.0.vb': System Error &Hc0000005& (Visual Basic internal compiler error)
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\the_application\0d68bd1e\5c2220e1\App_Web_the_application_page.aspx.cdcab7d2.foubj9oz.1.vb : error BC31007: Unable to open module file 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\the_application\0d68bd1e\5c2220e1\App_Web_the_application_page.aspx.cdcab7d2.foubj9oz.1.vb': System Error &Hc0000005& (Visual Basic internal compiler error)
I have also made sure to Enable Directory Browsing for the application in IIS. Any help on this is greatly appreciated.
~Billy
Comment: I suggest you try to change the identity of the application pool to the local system. If it still cannot work, you can raise a support ticket:https://support.microsoft.com/
Comment: IIS upgrade requires a windows system upgrade. Before Windows XP is iis6, and iis10 requires at least Windows8, did you upgrade iis to replace a device, copy the original application directly to the new device and compile and run it directly? Another point is whether your application has been tested in a test environment and can it run normally? If you deploy directly to a new production environment without testing, it is difficult to find problems.
Comment: Thank you for your comment Bruce. What I did was create a new 2016 server and in Visual Studio 2019, I compiled the new code and copied it over to the new web server. I made sure to run the new 4.8 code in Visual Studio debug mode before doing the copy to the server. In debug mode everything appears fine in the browser. I notice the issue when I try to visit the code while it is on the server.
Comment: That did the trick. Thank you Bruce!
Comment: You can mark the answer so that it can help others with similar problems.
Answer: Switching the identity of the application pool to the local system will raise the authority of the application pool to the highest level, which can solve the problem well.
Comment: This worked for us, after a Windows Update this week broke our long-established (as in, approaching 20 years) apps.  An extremely stressful evening was spent trying to find a resolution, so this really saved us a long sleepless night.

What I'd really like to know is why Microsoft have shifted the system so that AppPools that were working happily under ApplicationPoolIdentity now had to all be edited and set as LocalSystem.  We can't have been the only IIS server to have experienced this major screw-up.


como incrementar um array de objeto javascript em loop?

Question: Boa tarde, estou treinando meu javascript, mas estou com uma dúvida que não encontrei solução na internet, quero incrementar um array de objeto em loop, achei apenas como incrementar array, sendo objeto em loop não consegui solucionar, agradeço desde já.
<code>var post = {
            teste: 'teste'
        };
        var i = 1;
        while (i <= countOption) {
            option = $('#options'+i).val();
            post.option+i = questionOption;
            i++;
        }
console.log(post)
</code>
esse é o código que estou testando
Answer: Não estou no Pc
var post = {
teste: 'teste',
option: []
};
E depois:
post.option[i] = questionOption;
Comment: Obrigado cara, isso serviu pra mim, vlw mesmo


What is this CVS command doing?

Question: I have been scouring the CVS man page for a while now, but am not able to follow what this CVS command is meant to do exactly. There appears to be multiple listings for -F in the man page, Im not sure if this is being used to specify a log file or regex or what. Is it merging ${newTag} into ${mainTag} or is constantPerl the tag? mainTag is defined as 'Production' and newTag is passed in as an argument to the script that runs this:
cvs -d /home/main/cvs rtag -r ${newTag} -F ${mainTag} constantPerl
Answer: CVS has two kinds of options, global options and command options.
The form of a cvs command is:
cvs [ GLOBAL_OPTIONS ] COMMAND [ COMMAND_OPTIONS ] [ COMMAND_ARGS ]

In your case
cvs -d /home/main/cvs rtag -r ${newTag} -F ${mainTag} constantPerl

the COMMAND is rtag. You can tell from that that
-d /home/main/cvs

is a global option (that can apply to any cvs command) and that
-r ${newTag}

and
-F ${mainTag}

are command options, specific to the rtag command. Anything between the cvs command and the sub-command name (rtag, log, etc.) is a global option; anything following the sub-command name is a command option or a command argument.
In the CVS documentation (info cvs), go to the "Invoking CVS" section and search for rtag, where you'll find the following:

'-r TAG[:DATE]'
            Tag the revision already tagged with TAG or, when DATE is
            specified and TAG is a branch tag, the version from the branch
            TAG as it existed on DATE.  See *note Tagging by date/tag::
            and *note Common options::.

and:

'-F'
  Move TAG if it already exists.  See *note Modifying tags::.

What is this CVS command doing?


How to match only equals pattern , in other word not contain pattern

Question: String allString = " I1 + I6 + I9 + I8 + I3 + I2 + I20 + I21 + I18 + I23 + I28 + I27 + I31 + I24 + I12 + I15 + I14 + I13 + I16 + I11 "

How i check only "I1" in java regular expression pattern. Input patterns is "I1" , "I6"..... "I11". In this case "I1" , "I12" , "I15" , "I14" , "I13" , "I16" "I11" are same "I1" input pattern. How to solve?
Comment: @AvinashRaj he wants same pattern like the number which contains I1* pattern so the regex might be `I1.\d*`
Comment: my question is how to check only match pattern
Comment: can you post some expected output and your attempts
Answer: You can use the simple regex pattern I1\d* i.e. I1 followed by any number of digits.
String allString = "...";

Pattern pattern = Pattern.compile("I1\\d*");
Matcher matcher = pattern.matcher(allString);

while (matcher.find()) {
    System.out.print(matcher.group() + ", ");
}

In Java, we need to escape the \ too and so the final pattern will become I1\\d*.
Output :
I1, I18, I12, I15, I14, I13, I16, I11,

Answer: I1(?!\d) will match I1 but not I11, I12 etc.
    String allString = " I1 + I6 + I9 + I8 + I3 + I2 + I20 + I21 + I18 + I23 + I28 + I27 + I31 + I24 + I12 + I15 + I14 + I13 + I16 + I11 ";
    Pattern p = Pattern.compile("I1(?!\\d)");
    Matcher matcher = p.matcher(allString);
    matcher.find();
    System.out.println(matcher.group(0));

Output:
I1


Solving the functional equation $ xf(x) - yf(y) = (x - y)f(x + y) $

Question: I found the following functional equation:

Find all functions $f : \Bbb R \rightarrow \Bbb R $ such that:
$$ xf(x) - yf(y) = (x - y)f(x + y) \text{ for all }x, y \in \mathbb R $$

Could you please help me? I think I proved that if $f(0) = 0$ then for each $x \in \Bbb Q$ and every integer $k$ we have $f(kx) = kf(x)$, but I don't know how to continue. Thanks in advance.
Comment: Can you explain how that would help? I tried it multiple times before, but nothing came out.
Comment: Yeah, also every $f(x) = a * x + b$ I think
Comment: But this equation doesn't prove that $f=ax+b$, right? I mean, the function is symmetric with respect to f(0), but not always in that form. Do you have any idea how can I prove that $f(x)=ax+b$(assuming my guess at the answer is right)?
Comment: **Hint:** Take $y=-x$ .
Comment: For a start, the functions $f(x)=x$ and $f(x)=c$ for any $c\in\Bbb{R}$ work.
Comment: You get $\frac{f(x)+f(-x)}{2}=f(0)$ . Set $f(0)$ whatever you want and use the geometricic meaning of the left side and see if your solution is complete.
Answer: For $x=0$ we find that $yf(y)=-yf(y)$ for all $y\in\Bbb{R}$, so $yf(y)=0$ for all $y\in\Bbb{R}$. It follows that $f(y)=0$ whenever $y\neq0$. Then taking $x=1$ and $y=-1$ shows that $f(1)-f(-1)=2f(0)$, where $f(1)=f(-1)=0$, hence also $f(0)=0$. So $f=0$.
Comment: Sorry, I saw I have made a mistake in the statement. I'll correct it shortly. Anyways, thank you
Answer: It's obvious that every function of the form $f(x)=ax+b$ satisfies the equation:
$$xf(x)-yf(y)=(x-y)f(x+y)\tag0\label0$$
It can be shown that those are the only solutions indeed. To show that, let $a=f(1)-f(0)$ and $b=f(0)$, and define $g(x)=f(x)-ax-b$. It's easy to see that by \eqref{0}, $g$ satisfies
$$xg(x)-yg(y)=(x-y)g(x+y)\tag1\label1$$
and we have $g(0)=0$ and $g(1)=0$. Letting $x=1$ and $y=-1$ in \eqref{1} we get $g(-1)=0$. Now, letting $y=1$ and $y=-1$ in \eqref{1}, we respectively get:
$$xg(x)=(x-1)g(x+1)\tag2\label2$$
$$xg(x)=(x+1)g(x-1)\tag3\label3$$
Substituting $x+1$ for $x$ in \eqref{3} we have:
$$(x+2)g(x)=(x+1)g(x+1)\tag4\label4$$
Subtracting \eqref{4} and \eqref{2} we get $2g(x)=2g(x+1)$ and thus $g(x)=g(x+1)$. Hence by \eqref{4} we have $(x+2)g(x)=(x+1)g(x)$ and therefore $g$ is the constant zero function. So $f(x)=ax+b$.


React native Render Error how to solve this

Question: Render Error
Error: Text strings must be rendered within a <Text> component.

How to fix the above error in React Native? Here is my code:
Challenge1.jsx
import { View, Text, StyleSheet } from "react-native-web";
function Challenge1() {
    return (<View>
        <Text style={style.first}>
            Welcome to Thapa Technical Channel
        </Text>
        <Text style={style.second}>
            We love React native and i'm a subscriber of thapa technical channel
        </Text>
        <Text style={style.third}>
            Hii, My name is
        </Text>
    </View>)
}

const style = StyleSheet.create({
    first: {
        fontSize: 40,
        textAlign: "center",
        fontWeight: "bold"
    },
    second: {
        fontSize: 30,
        textAlign: "center"

    },
    third: {
        fontSize: 20,
        textAlign: "center",
        fontWeight: "bold"

    },
})
export default Challenge1;

Here is some information:

Error: Text strings must be rendered within a  component.
This error is located at:
in div (created by Text)
in Text (created by Challenge1)
in div (created by View)
in View (created by Challenge1)
in Challenge1 (created by App)
in RCTText (created by Text)
in Text (created by App)
in RCTView (created by View)
in View (created by App)
in App (created by ExpoRoot)
in ExpoRoot
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent)
Comment: I'm getting this same error, and I don't know how to solve this :(
Answer: When you save code, an empty string is placed i.e. <View> {" "} /View>
You should have to remove this String.


Can SEM distinguish between the following models?

Question: Suppose I have 3 manifest variables, x, y and z. I would like to use path analysis to determine the direction of influence. Is there a test that lets me distinguish between the following models?

and

In the first, z is caused directly by x, and indirectly by x through y. In the second, x is caused by y and z.
I fear that it is not, given that my SEM model is saturated in both cases, but I would like to be able to distinguish these situations.
Would it make a difference if there were a measurement component to the model, as below?

which should be distinguished from, say, this:
Answer: I think I know the answer to my question. I tried a few models like the ones shown above, using the sample data sets from lavaan in R. Typically, models that simply replace a two-headed arrow (correlation) with a one-way arrow (regression) have the same number of degrees of freedom and cannot be distinguished from each other. A model like $X \rightarrow Y \rightarrow Z$ has one more degree of freedom from model $X \rightarrow Y \rightarrow Z, X \rightarrow Z$, and these can be distinguished.
Intuitively, if it were possibly to distinguish the models I outlined in my question, correlation would show causality, and this XKCD comic would no longer be funny.
Comment: More generally, this is the problem of 'equivalent models' (e.g., http://www2.gsu.edu/~mkteer/equival.html). You cannot distinguish equivalent models based on their fit (since it is the same). This is unfortunately an often ignored issue (i.e., just because a particular model fits does not automatically imply that we have established how the variables are related to each other).
Comment: The answer by @Placidia isn't always  true. (a) X -> Y -> Z implies a correlation between X and Z, (b) X -> Y <-> Z does not, nor does (c) X -> Y <- Z. You can distinguish (a) from (b) and (c) , you can't distinguish (b) and (c).
Comment: That's great. That's just the kind of reference I was hoping to find. Thanks.


Sum of number of partitons of $k$ into distinct parts as $k$ ranges from $1$ to $n$ is less than $n$th power of $2$.

Question: Prove, with a direct combinatorial argument,that for all positive integers $n$, we have $q(1)+q(2)+...+q(n) \leq 2^{n}$, where $q(n)$ denotes the number of partitons of n into distinct parts.
I have found this problem in the book 'Introduction to Enumerative and Analytic Combinatorics' by Miklos Bona. I am going nowhere with this problem. Can anyone please give me a hint or a solution?
Comment: Partition of $n$ into how many distinct parts because $P(n, k) $ denotes partition of $n$ objects into $k$ groups.
Comment: It can be any number of parts. Just that in the partition, no number should occur more than once. For example, 4 can be partitioned into 4+0 and 3+1. So 2 partitions with distinct parts.
Comment: I think you mean partition into 2 parts. Otherwise, you could partition 4 also into 3+1+0, I.e. three parts
Comment: No, I am sorry. 4 can be partitioned into 4 and 3+1. 0 will not come. Distinct numbers should be there except 0.
Answer: Every partition of a number $k\le n$ into distinct parts corresponds uniquely to a subset of $\{1,2,\dots,n\}$; the inequality follows since the number of such subsets is $2^n$.
Comment: Thank you. It is a beautiful solution.


Reorder Python List

Question: I have a list of 4 items like this:
a, b, c, d = [1, 2, 3, 4]

I'm reordering the list, flipping each pair:
[b, a, d, c]

Is there a way to do this in one expression? I've tried using list comprehension and unpacking, but can't seem to get it right.
I have [1, 2, 3, 4]. I'm trying to get [2, 1, 4, 3].
Comment: http://stackoverflow.com/a/2493980/1628832 ?
Comment: can you elaborate what your desired input and output are?
Comment: Don't you mean to expect `[2,1,4,3]` as output?
Answer: More generically, if you're looking to flip pairs of numbers in a list:
>>> L = [1, 2, 3, 4, 5, 6]
>>> from itertools import chain
>>> list(chain.from_iterable(zip(L[1::2], L[::2])))
[2, 1, 4, 3, 6, 5]

Answer: Look at this:
>>> lst = [1, 2, 3, 4]
>>> [y for x in zip(*[iter(lst)]*2) for y in x[::-1]]
[2, 1, 4, 3]
>>>
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [y for x in zip(*[iter(lst)]*2) for y in x[::-1]]
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
>>>

Comment: Slick. Going to have to spend some time figuring out how this works.
Comment: @nathancahill - Thank you.  I assume you understand the list comprehension parts.  What I did with `zip` and `iter` is a very helpful trick you should memorize (it's used a lot and will _really_ help you).  Here is a reference on it:  http://stackoverflow.com/questions/18541215/how-do-you-access-a-list-in-group-of-3-in-python  Scroll down to @abarnert's answer.
Answer: If this is only about 4 member lists - this would suffice:
list = [1, 2, 3, 4]
reordered_list = [list[1], list[0], list[3],list[2]]

Answer: Because absolutely nobody has given an answer that works on generic iterables,
from itertools import chain

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

zip(*[iter(items)]*2)
#>>> <zip object at 0x7fd673afd050>

[itms for itms in zip(*[iter(items)]*2)]
#>>> [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]

So zip(*[iter(x)]*2) means ix = iter(x); zip(ix, ix) which pairs each element.
Then you can reverse:
[(y, x) for (x, y) in zip(*[iter(items)]*2)]
#>>> [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)]

Putting it all together and flattening:
[itm for (x, y) in zip(*[iter(items)]*2) for itm in (y, x)]
#>>> [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]

It's generic and short!

If you want something faster at the expense of genericism, you'll be hard pressed to better this:
new = list(items)
new[::2], new[1::2] = new[1::2], new[::2]

new
#>>> [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]

Note that this still works on arbitrary iterables, but there are fewer layers of abstraction; you can't bump up the size of the flipped sub-lists as easily and can't output iterables, etc.
Comment: Excellent answer. Thanks for breaking it down step by step.
Answer: Do you mean this:
>>> a, b, c, d = [1, 2, 3, 4]
>>> b, a, d, c = a, b, c, d
>>> a
2
>>> b
1
>>> c
4
>>> d
3

?
Comment: No, I'm not trying to reassign the variables, I'm trying to get [2, 1, 4, 3] from [1, 2, 3, 4]
Answer: Try this list comprenhension solution:
a = [1,2,3,4,5,6] # Any list with even number of elements
b = [a[e+1] if (e%2 == 0) else a[e-1] for e in range(len(a))]

This just works if the list a have an even number of elements.
Answer: In [1]: l = [1, 2, 3, 4]

In [2]: list(chain(*map(reversed, zip(l[::2], l[1::2]))))
Out[2]: [2, 1, 4, 3]

Answer: Am I missing something? Reorder given_list with a loop:
rez = []
for i in range(len(given_list)-1, -1, -1):
    rez.append(given_list[i])
return rez

Reorder Python List


Drupal services add location

Question: I am trying to add a location to a node using Drupal services.
This is the JSON sent to the service
<code>{
   "node":{
      "type":"restaurant",
      "title":"Restaurant from JSON API",
      "field_restaurant_location ":{
         "und":{
            "locpick":{
               "user_latitude":"22.38131",
               "user_longitude":"114.168639"
            }
         }
      }
   }
}
</code>
I can not get it to save the location to the node. Any ideas ?
Answer: Should anyone else have this problem, the correct answer is:
<code>{
    "node": {
        "field_restaurant_location": {
            "und": [
                {
                    "country": "us",
                    "latitude": "-26.2041",
                    "locpick": {
                        "user_latitude": "-26.2041",
                        "user_longitude": "28.0473"
                    },
                    "longitude": "28.0473"
                }
            ]
        },
        "title": "Restaurant from JSON API",
        "type": "restaurant"
    }
}
</code>
Answer: Try this once, I hope would work for you. Sometime "Access denied for user anonymous" error also comes, if this issue is coming then it is coming due to different reason. If it doesn't work then share the error with us.
<code>{
    "node": {
        "type": "restaurant",
        "title": "Restaurant from JSON API",
        "field_restaurant_location ": {
            "und": [
                {
                    "locpick": {
                        "user_latitude": "22.38131",
                        "user_longitude": "114.168639"
                    }
                }
            ]
        }
    }
}
</code>
Comment: Thanks, but I am not trying to create an article. I am trying to create a restaurant, and I have a content type named restaurant with a title and a location.
Comment: I tried your JSON by changing the type into restaurant, but got the same result as before. A restaurant was created without a location.
Comment: I am not getting any errors

Drupal services add location


wysiwyg + ckeditor - failed to open stream sites/default/files/js/wysiwyg/wysiwyg_ckeditor_XXX.js

Question: I am using WYSiWYG with CK editor. I am getting this error whenever i am trying to access a form with ckeditor.

file_get_contents(MYSITE/sites/default/files/js/wysiwyg/wysiwyg_ckeditor_lMF9rzHK588_LcHaW11FHc_RkSCpdKrS7MgWsyqXXEM.js)
[function.file-get-contents]: failed to open stream: HTTP request
  failed!
HTTP/1.1 404 Not Found in drupal_build_js_cache() (line 4846 of
  /var/www/html/dev3/wifh/includes/common.inc).

This file "wysiwyg_ckeditor_lMF9rzHK588_LcHaW11FHc_RkSCpdKrS7MgWsyqXXEM.js" exist with content
window.CKEDITOR_BASEPATH = '/MYSITE/sites/all/libraries/ckeditor/';

Answer: This bug should be fixed in the latest dev snapshot of wysiwyg:
See also http://drupal.org/node/1802394 (which essentially provides a patch for the previous response above).
Answer:
Edit wysiwyg.module file
Find this drupal_add_js(file_create_url($uri), $default_library_options);`
Replace with this drupal_add_js($uri, $default_library_options);
Comment: Definitely the solution but more explanations are welcome.
Comment: please do not hack core or contrib modules..


Download loop for .txt taking to long

Question: this is a bit of an abstract question but was wondering if there was any simple suggestions or answers that anyone might have for me.
I have an AsyncTask that contains a loop for downloading a few text files, the files are small and there are about 12 of them. It is currently taking up to 10 seconds to download which is longer than i thought it should, is there anything that i could perhaps do that will speed up the download, or is there a way to download them all at the same time rather than one by one?
heres the code i have for the Async and download.
<code>@Override
protected Long doInBackground(URL... params) {

    try {
        // Loop to download
        distance dis = new distance();
        URL[] urlArray = dis.urlArray();
        URL[] urlExtra = dis.urlArrayExtra();
        String [] stationName = dis.getStationName();
        String [] stationNameExtra = dis.getStationNameExtra();
        for  (int i = 0; i < urlArray.length; i++) {

        String fileName = stationName[i];

        File file = new File(sdCard.getAbsolutePath() +
                "/Download/" + fileName);
        URL url = urlArray[i];
        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();

        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
                baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
        }
} catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
}
    return null;

}
</code>
Answer: I think perhaps the bottleneck being your ByteArrayBuffer only being set to 50.
Here is the code that I use to download some files.
<code>        @Override
    protected String doInBackground(Void... params) {
        String filename = "inputAFileName";

        HttpURLConnection c;
        try {
            URL url = new URL("http://someurl/" + filename);
            c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
        } catch (IOException e1) {
            return e1.getMessage();
        }

        File myFilesDir = new File(Environment
                .getExternalStorageDirectory().getAbsolutePath()
                + "/Download");

        File file = new File(myFilesDir, filename);

        if (file.exists()) {
            file.delete();
        }

        if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
            try {
                InputStream is = c.getInputStream();
                FileOutputStream fos = new FileOutputStream(myFilesDir
                        + "/" + filename);

                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);
                }
                fos.close();
                is.close();

            } catch (Exception e) {
                return e.getMessage();
            }

            if (file.exists()) {
                return "File downloaded!";
            } else {
                 Log.e(TAG, "file not found");
            }
        } else {
            Log.e(TAG, "unable to create folder");
        }
    }
</code>
You can try it out and see if it is faster.
Comment: Not entirely sure whether it's sped up the download or not but it does seem to be running a little bit faster.

Download loop for .txt taking to long


JSDoc how to document array of arrays and boolean or other types for returns?

Question: I have a function that returns a array like this: [ [true, true], true] where index 0 is an array of boolean and second a boolean. How can I document this in JSDoc return type.
I have tried: @returns {[boolean[], boolean]} which produces "unable to parse.."..."invalid type expression.." error.
Answer: You have complex type to return and perhaps @typedef will be better option to set the type of return. But if you want to leave it as is, the following should work for you ...
@return {Array<Array<Boolean>, Boolean>}


Solarized theme for multiple windows on terminator not working

Question: I am using ubuntu 12.04 LTS with terminator and zsh
i tried to change the theme of the terminator using  https://github.com/ghuntley/terminator-solarized/blob/master/README.md
i have successfully changed the theme of the termninator but when i split the window the splited window is in the old theme instead of new theme
this is how it looks
What is wrong in it
Answer: One way to preserve the profile on splits would be to put under
[profiles]
  [[default]]

the code corresponding to the profile that you want.
For example, if you want solarized-light it should look like this:
[profiles]
  [[default]]
    palette = "#073642:#dc322f:#859900:#b58900:#268bd2:#d33682:#2aa198:#eee8d5:#002b36:#cb4b16:#586e75:#657b83:#839496:#6c71c4:#93a1a1:#fdf6e3"
    background_color = "#eee8d5"
    foreground_color = "#002b36"
    cursor_color = "#002b36"


Assigning a page title to forms created with the form API FAPI

Question: I have a moule called newsl witch display a page containing a form.
I would like the way to specify the page title.
Is it with drupal_set_title() ? How to call it ?
Answer: if your page url http://site.com/my_page
you can use
<code>function hook_page_alter(&$page)
{

    if(arg(0)=="my_page")
    {
                 drupal_set_title("Ahmed");
    }
}
</code>
Comment: Why bother with implementing another hook? Just stick `drupal_set_title()` in the form building function and you're good to go
Comment: if he can do it in form building it will be the best
Comment: Where in form building ?
Comment: Thank you guys. I just call my drupal_set_title () in my form builder


Don't show a field when a more important field is shown in a View Drupal 7

Question: On my homepage blog messages from the users are shown. When a user adds a Youtube movie and/or one or more pictures these are shown as a preview.
The thing is though that when a user picks a movie and one or more pictures the home page message show the Youtube movie and the picture. But when both are added to a blog message I only want to see the youtube preview, so Youtube is more important than the picture so the picture should not be shown.
When there are only pictures 1 picture is shown (this works fine).
How can I change something in my View to make it prioritize Youtube over the picture so it doesn't the picture when there is a Youtube movie.
Screenie of what I have now, so the picture has to leave:
http://imageshack.com/a/img844/1833/bqer.jpg
I have a multisite setup with 11 websites so the easiest solution is welcome :)
Thanks in advance!
Answer: Use the Views Conditional module. It does exactly what you want to achieve.

How to use Views Conditional in your Views:

Create a view. Add some fields under "FIELDS".
Click on "ADD" next to fields. Scroll down to "Views: Views
  Conditional", probably found near the bottom of the list.
Add and configure fields...
Choose a field to run a condition against, and provide values
  accordingly.
Save, views conditional handles the logic and returns as specified.
Comment: You might need to hide the fields from display and then use them after the condition probably.
Comment: Looks like the answer I need!
Thanks!
Will come back here if I have problems but I think it's ok :D


Allign block content next to title - CSS

Question: My goal is to display a button group to the right of the page title. Currently it resides in region-content, which wastes space.
I tried adding my own class to the div that contains btn-group class and use margin-top to move it up, but as soon as I save content, I get system help message that overlaps with the button group.
I also tried to add the block to other regions and get same thing if, say, I use breadcrumbs.
What's the best way or what are the classes I should use to position my block with button group to the right of the page title in main-container instead of region-content?
Comment: This is hard to answer without knowing more about your HTML structure/theme/page template, but one sure-fire way to do this is with absolute positioning, though that's probably not ideal. You could also try to style your system help messages to not overlap the buttons. But if adding a block into the same region the page title is in won't work, you may need to modify your page template or use JavaScript.
Comment: I'm using [Bootstrap 3](https://www.drupal.org/project/bootstrap) out of the box theme settings. The only thing I did is used the sub theme, which have not been modified yet.
Comment: Sorry, still doesn't help me that much. What version of Drupal are you using? Also, would it be possible for you to provide a link to this page or to at least copy the essential section of the page (as shown in the screenshot) over to Code Pen or jsfiddle or a similar site?
Comment: Sure, here's the link to demo I set up a while ago: http://admincenter.semargl.ca/contracts
Answer: Okay, so after looking at your demo, there's a couple things you can do.
The easiest method is to simply float #block-block-16 right, float .page-header left, set #block-system-main to clear: both, and be done with it.
But that's not great because we are kinda circumventing div.region.region-content by doing that. It'd be better if the header and the buttons actually shared a common parent. That seems to be what you truly want to do here. We can accomplish that with some JavaScript. That will also help with the minor problem the first solution introduces of having your gray underline not stretch across the page.
$(function() {

  $('#block-block-16').insertAfter($('h1.page-header'));
  $('#block-block-16, h1.page-header').wrapAll('

');

});

From here, again we'll just float the buttons right and the page header left as before.
We can also take care of some details and clearfix the new div (included in the JS) and perhaps change our bottom border from being set on the h1 to being set on our new div, so that it stretches across the page, below the header and buttons.
You may also choose to remove the 9px padding-bottom on the h1 and instead change that to a 9px padding-top on div.region.region-content.
Hope that helps!


How can I add background music to an existing Drupal 7 website?

Question: I have a nice little website built with Drupal 7. It's very basic, nothing crazy going on.
The client is demanding there be background music playing on the site. I have pleaded with them not to do this, but they are insistent and they are also signing the checks. :)
What is the best way to add background music to an existing Drupal 7 site that won't stop playing between pages? For any given solution what are the consequences to search engine friendliness and impact in general to the structure of Drupal?
Looking only for solutions to the music problem as not having music on the site isn't an option here.
Comment: This question seriously needs an update — having persistent audio players for music sites is a pretty common thing now. See: http://www.themusicninja.com/
Answer: I'm looking at doing the same thing for a band's website where the music can keep playing even when switching pages. AJAX is definitely the way to go here.
Check out the pjax for Drupal module.

pjax is a jQuery plugin that loads new content into the current page without a full page load. This is usually quicker and smoother than a full page reload, because Drupal only has to deliver the main page content and not the full page – and the browser only has to redraw a smaller amount of markup.
In addition to this, pjax updates the page URL with the proper page path using HTML5 pushState – not with #url-fragments that are commonly used with ajax-loaded content. It also updates the page title with the title of the loaded page. In other words, it has all of the benefits of standard page loads (permalinks, SEO), while taking advantage of partial page loads in the browser.
Answer: If you want the music to continue playing even while you go from one page to another, you'll have to make the site so that all pages are loaded with AJAX, or in frames.  With regular page loading, the music will be interrupted between each page.
As far as a player to use, I haven't tried anything, but this one looks pretty good to me:
http://www.cincopa.com/media-platform/services/add-music-to-website
Answer: From a Google/Search perspective, the frames idea is a bad one. Has the client also considered people accessing via Mobile platform? Also an issue.
I hate pop-unders, but in this case, a pop under spawning the player might also be the way to go...then do mobile agent detection, and kill the spawn for that platform.
Answer: This is an old question but some may still stumble upon it so here is the solution:
Combine two modules, https://drupal.org/project/ajax_pages and https://drupal.org/project/background_audio
This allows a user to browse the site (visiting different pages) and have an audio file continuously playing (without interruption).
In essence you are using ajax to have constant regions which do not change when a page is loaded.


AES-128-GCM Tag doest not match

Question: I'm trying to encrypt and decrypt with aes-128-gcm.
But when I'm running a test I have an error :
System.Security.Cryptography.CryptographicException : The computed authentication tag did not match the input authentication tag.
I don't understand why this error appears because when I print the tag in the encrypt method and print it in the decrypt method, they are the same ? I have read that the Associated Data could change something but I didn't find something.
Here is the test
[TestCase("ABC", "ABC")]
public void TestEncrypDecrypt(string message, string expected)
{
     string cle = "FnUoIZvBUzC1Q/rn5WMi7Q==";
     var aes = new AESEncryption(cle);
     var crypted = aes.Encrypt(message);
     Assert.That(aes.Decrypt(crypted), Is.EqualTo(expected));
}

And here is my class :
public class AESEncryption : IEncryption
    {
        private byte[] KEY { get; set; }
        private byte[] TAG { get; set; }

        public AESEncryption(string key)
        {
            KEY = Convert.FromBase64String(key);
            TAG = new byte[16];
        }

        public string Encrypt(string message)
        {
            byte[] plainText = Encoding.UTF8.GetBytes(message);
            byte[] ciphertext = new byte[plainText.Length];
            using (AesGcm aesGcm = new AesGcm(KEY))
            {
                aesGcm.Encrypt(
                    new byte[]{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B },
                    plainText,
                    ciphertext,
                    TAG);
            }
            return Convert.ToBase64String(ciphertext);
        }

        public string Decrypt(string message)
        {
            byte[] cipherText = Encoding.UTF8.GetBytes(message);
            byte[] plainText = new byte[cipherText.Length];
            using (AesGcm aesGcm = new AesGcm(KEY))
            {
                aesGcm.Decrypt(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B },
                    cipherText,
                    TAG,
                    plainText);
                Console.WriteLine("d1 " + Convert.ToBase64String(TAG));
            }

            return Convert.ToBase64String(plainText);
        }

    }

Thanks a lot !
Answer: You have just missed the ToBase64String and Encoding.GetBytes order:
    public class AESEncryption
    {
        private byte[] KEY { get; set; }
        private byte[] TAG { get; set; }
        private byte[] NONCE { get; set; }

        public AESEncryption(string key)
        {
            KEY = Convert.FromBase64String(key);
            TAG = new byte[16];
            NONCE = new byte[12] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B };
        }

        public string Encrypt(string message)
        {
            byte[] plainText = Encoding.UTF8.GetBytes(message);
            byte[] ciphertext = new byte[plainText.Length];
            using (AesGcm aesGcm = new AesGcm(KEY))
            {
                aesGcm.Encrypt(
                    NONCE,
                    plainText,
                    ciphertext,
                    TAG);
            }
            Debug.WriteLine("e " + Convert.ToBase64String(TAG));

            return Convert.ToBase64String(ciphertext);
        }

        public string Decrypt(string message)
        {
            Debug.WriteLine("d " + Convert.ToBase64String(TAG));

            // Notice here -> First get byte from the encoded base64.
            byte[] cipherText = Convert.FromBase64String(message);
            byte[] plainText = new byte[cipherText.Length];
            using (AesGcm aesGcm = new AesGcm(KEY))
            {
                aesGcm.Decrypt(
                    NONCE,
                    cipherText,
                    TAG,
                    plainText);
            }

            // Notice here -> then get back the string from plain text.
            return Encoding.UTF8.GetString(plainText);
        }

    }

Then,
        string cle = "FnUoIZvBUzC1Q/rn5WMi7Q==";
        var aes = new AESEncryption(cle);
        var crypted = aes.Encrypt("Hello");
        Debug.WriteLine($"DECRYPT TEST: {aes.Decrypt(crypted)}");
        // Prints "Hello"

AES-128-GCM Tag doest not match


How was this result obtained?

Question: In Stein's and Sharakachi's Complex Analysis (Chapter 1), the authors state that, to prove that $F$ (where $F: (x,y)\mapsto(u(x,y),v(x,y))$) is differentiable it suffices to observe that $H=(h_1,h_2)$ and $h=h_1+i\,h_2$ then the Cauchy-Riemann equations imply:
$$J_F(x_0,y_0)(H)=\left(\frac{\partial u}{\partial x}-i\frac{\partial u}{\partial y}\right)(h_1+i\,h_2)=f'(z_0)h.$$
However, I can't see how this result is obtained, as I understood $J.H$ being a matrix multiplication:
$$J_F(x_0,y_0)(H)=\begin{bmatrix}\frac{\partial u}{\partial x} & \frac{\partial u}{\partial y}\\ -\frac{\partial u}{\partial y} & \frac{\partial u}{\partial x}\end{bmatrix}\begin{bmatrix}h_1\\h_2\end{bmatrix}=\begin{bmatrix}h_1\frac{\partial u}{\partial x}+h_2\frac{\partial u}{\partial y}\\h_2\frac{\partial u}{\partial x}-h_1\frac{\partial u}{\partial y}\end{bmatrix}$$
which does not conclude anything.
Comment: I don't have the book, but the usual formulation is: if $F$ as function form a open subset of $\Bbb R^2$ to $\Bbb R^2$ is $\Bbb R$-differentiable, then is $\Bbb C$-differentiable iff verifies the C-R equations.
Answer: The essential fact: a $\Bbb R$-linear function form $\Bbb R^2$ to $\Bbb R^2$ is $\Bbb C$-linear iff its matrix in the canonical base has the form
$$\pmatrix{a & b\cr -b &a}.$$
Edit:
$$(a + bi)(x + yi) = (ax - by) + (ay + bx)i,$$
$$\pmatrix{a & b\cr -b &a}\pmatrix{x & y\cr -y &x} = \cdots$$
Comment: I don't understand the transition they made between the matrix multiplication and $f'(z_0)h$. How did they convert the matrix into that form?
Answer: This is a little late, but I was working to understand the same proof and think I can clarify.  We use both the Cauchy-Riemann equations and the fact that we've already proven that $f'(z_0) = 2\partial_z u(z_0)$.  So starting where you left off and using the association of $\mathbb{C}$ and $\mathbb{R}^2$:
\begin{align*}
\begin{bmatrix}
h_1 u_x +h_2 u_y\\ h_1 v_x + h_2 v_y
\end{bmatrix} ={}& h_1 u_x + h_2u_y + i(h_1 v_x +h_2 v_y)\\
={}& h_1u_x + h_2 u_y +i(-h_1 u_y + h_2 u_x)\\
={}& (u_x - iu_y)(h_1 + ih_2)\\
={}& (u_x + \frac{1}{i}u_y)(h_1+ih_2)\\
={}& f'(z_0)h.
\end{align*}
I left out the earlier parts in each line that we're evaluating this at $(x_0,y_0)$.

How was this result obtained?


Difference between an "Empirical Strategy" and an "Identification Strategy" in econometrics?

Question: What are the substantive differences between these terms, specifically for economists?
Are instrumental variables, difference-in-differences, and regression discontinuity designs considered 'identification strategies?'
For example, if I am using difference-in-differences to obtain a causal effect, and someone asked me 'what is your identification strategy?' would 'I used a difference-in-differences design' be the appropriate response?
Comment: That is economics-speak for methods of using observational data to identify effects when a proper experiment is not possible.   Here are some [lecture notes on identification strategies](http://home.cerge-ei.cz/jurajda/rms07b.pdf) which might help you understand some of the ways the phrase is used.
Answer: Both terms are fairly loaded terms with meanings that will depend on who is using it.
Broadly speaking, "empirical strategy" is an umbrella term used by researchers to indicate their overall "process" in approaching a question and delivering an answer. Indeed, Angrist and Krueger write in Empirical Strategies in Labor Economics (my own highlighting):

We use the term empirical strategy broadly, beginning with the
statement of a causal question, and extending to identification
strategies and econometric methods, selection of data sources,
measurement issues, and sensitivity tests.

This re-affirms the idea that empirical strategy is a catch-all term to indicate your overall method.
In contrast, I would argue "identification strategy" means something very specific. I wrote a bit about identification in this CV question. Based on my definition of identification presented there, I would define identification strategy as the process of

defining a parameter you are interested in (such as the causal effect of treatment on outcome), and
proving that your observed data (a DGP) and imposed assumptions (such as parallel trends in diff in diffs) identify this parameter

In applied work, you'll probably notice people are not so rigorous about this, and instead will say something hand-wavy such as "our identification strategy leverages a difference in difference design..." This is fine, because in many commonly used designs, previous work has already done the tedious work of showing the formalities, so applied research can simply state that they are doing a diff in diff without having to explain every detail. But in works where the identification strategy is novel, then they have to actually prove the identification strategy "works".
Comment: @Steve yeah, that's right (in the hand wavy sense :-) ). When you say your identification strategy is a difference in difference design, under the hood you're making all the standard assumptions that are required. For example, if you're also identifying the effect using a linear regression design, then you're probably also assuming standard gauss markov assumptions.
Comment: Thank you for this clarification! Taking the identification strategy process definition, then is it fair to say for instance difference in differences is an identification strategy because it is a way to make comparisons with observed data that uncover (or identify) the causal parameter of interest, if the underlying assumptions are valid? is that at least a slightly less hand waivy way of saying it

Difference between an “Empirical Strategy” and an “Identification Strategy” in econometrics?


Morse functions dense in a trigonometric polynomial space

Question: Let $V$ be the vector space of trigonometric polynomials of degree $\le D$ on the flat torus $\mathbb T^n$. That is,
$$V=\operatorname{Span}\left\{\cos (2\pi \lambda \cdot x), \sin (2\pi \lambda \cdot x)\mid\lambda\in\mathbb Z^n,|\lambda|_1 \le D\right\}$$
Are the Morse functions (functions for which zero is a regular value of the gradient) dense in $V$?
What would be the simplest argument for this (I know calculus, but I don't know Morse theory)?
Comment: With polynomials, one proves that for any $f(x)$, and for almost all scalar $a$, $f(x)+a x$ is Morse. Maybe you can try to imitate it here? (I think that with polynomials it is allowed that x is a tuple of variables, a is a tuple of scalars and ax is the scalar product, but I am not sure)
Comment: The proof (that I know) of what you wrote is 1 line: By Sard's theorem, $\nabla f$ has a null set of singular values, so $\nabla f + a = \nabla(f + ax)$ has $0$ as a regular value for almost all constants $a$. In the flat torus I think this doesn't work, because there's no periodic function with a constant nonzero gradient.
Answer: Lets observe the $1$-dimensional case for a start.
You can approximate cosines, just take $\cos(x)+\frac{1}{N}\sin(x)$ as a function with non-zero derivative approximating cosine by error bounded $O(1/N)$, and clearly all the sine functions have non-zero derivatives at $0$.
Now notice that if $f,g$ are two Morse-like functions, then their sum can be approximated as well in the following manner - if their sum has non-zero derivative, then the claim is obvious, but if the sum is $0$, then look at $(1+\frac{1}{n})f(x)+(1-\frac{1}{n})g(x)$, the difference from the original sum is bounded by $\frac{2\max\{\|f\|_{\infty},\|g\|_{\infty}\}}{N}$ in the sup. norm, and its derivative equals to $\frac{f'(0)-g'(0)}{N}\neq 0$.
Therefore, given a general polynomial expression, just approximate the basis functions and then approximate the whole sum (as your space is finite dimensional).
P.S. by changing the approximation rate with each summand, and taking rapidly decreasing sequence, one can approximate like that a Fourier series, say assuming you have nice convergence by assumption on the decay rate of the coefficients (and even keep the approximation in a suitable Sobolev space).
Comment: Are you sure we use the same definition of Morse functions? Your answer seems to use "$f'(0) \ne 0$", but my definition is "zero is a regular value of the gradient", i.e. $\nabla f(x) = 0 \implies \det \text{Hessian} f(x) \ne 0$.


How to center the links in mobile view

Question:

                        Watch introductory video

View program details

See what nonprofits say

Hi, the above HTML gives the following arrangement of URL in Desktop View and Mobile View
I have used nav-justified class to justify the links in both desktop view and mobile view. While the desktop view is just fine (Three links appearing horizontally), In mobile view the 2nd link is slightly misaligned (links have to appear vertically). Is there a cleaner way to align the links in mobile view?
Answer: answer updated
you can now individually give margin-right to your second link #PgmDetails

<!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css">

                        Watch introductory video

View program details

See what nonprofits say

Comment: Thanks for the answer @Maulik, really appreciate it. But let's try to position the URL in the center while maintaining the same left alignment.
Comment: @Purushottam.Prasad you can check now my updated answer : )
Answer:

   some text

Try like that ?
Answer: I think glyphicon used extra padding or margin in your code.
just update

or you can inspect element so that you can see where is that extra padding
Comment: Hi Maulik. There is same amount of padding for all three glyphicon. However I think the misalignment has something to do with the length of the text as when I increase the length of the text the URL's get perfectly aligned. So, could we have some way around for this ?
Comment: @Purushottam.Prasad are those 3 links is in left side in mobile view?? if yes then you can add text-left class
Answer: I think your using Bootstrap. We can use flex-column class Reference link
Comment: Thanks for the answer prime417 but adding flex column will distort the horizontal alignment in desktop view.

How to center the links in mobile view


Qual a melhor forma de utilizar notifications no Laravel 5.3

Question: Estou utilizando o evento Registered do próprio Laravel (Illuminate\Auth\Events\Registered) para disparar um listener que criei para disparar um email de boas vindas.
Veja como ficou o Listener:
<?php

namespace App\Listeners;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

// instância do evento registered do próprio Laravel
use Illuminate\Auth\Events\Registered;
use Illuminate\Notifications\Notifiable;
use App\Notifications\EnviarEmailBoasVindasNotification;

class EnviarEmailBoasVindas
{
    use Notifiable;
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  NovoUsuario  $event
     * @return void
     */
    public function handle(Registered $event)
    {
        // No "envelope" $event podemos acessar a instância User assim $event->user
        $event->user->notify(new EnviarEmailBoasVindasNotification($event));
    }
}

Minha dúvida fica por conta de "use Illuminate\Notifications\Notifiable" e pela ocorrência "use Notifiable" já dentro da classe. Qual a utilidade destas? Pelo que vi se retirar ambas tudo continuará funcionando normalmente.
Comment: eu faria uma `notification` e um `observers`? eu acho que fica mais lógico.
Comment: Tem alguma coisa que não bate no seu código, porque, esses `namespace` e `traits` possa ser não exigido ai, mas, pode ser exigido na classe dentro do método `notify`. Você seguiu a documentação eu fez outra coisa?
Comment: Tudo correto, a principio segui a documentação conforme deveria ser. Veja se estou correto, $event possui uma instância da model User, dentro desta model eu tenho a ocorrência **use Illuminate\Notifications\Notifiable;**, seria este o motivo pelo qual não preciso ter uma nova ocorrência no arquivo acima?
Comment: Aonde você chama `EnviarEmailBoasVindas`?
Comment: Tenho um event que chama esse listener (EnviarEmailBoasVindas) aí.
Comment: De fato Virgilio, neste caso é melhor utilizar observers. Não conhecia essa opção. Porém, acredito que no caso acima, meu entendimento esteja correto ao imaginar que não preciso instanciar novamente a classe notification já que está é instanciada na model User
Comment: Eu não consigui entender o que você fez porque eu já fiz isso e tenho exemplos e precisa sim, pelo que pude perceber ou imagina tem duas classes uma chamando a outra! bom é suposição. mas, no seu caso é melhor um observer com método created com notification!
Answer: Primeiramente, você precisa entender o que está usando ao fazer a utilização de use Notifiable.
Isso trata-se de um trait. Um trait em PHP é um mecanismo de reutilização de código que visa resolver problemas de herança de métodos.
Com um trait, você pode escrever algo como se fosse "um pedaço" da classe e herdar em várias outras classes.
Foi isso que o Laravel fez. Isso que você está usando é um trait que possui alguns métodos para facilitar a utilização da sua notificação.
O trait Notifiable herda outros dois traits: HasDatabaseNotifications e RoutesNotifications. Eles possuem vários métodos.
Para você poder notar a diferença, bastaria fazer assim:
print_r(get_class_methods(new App\Listeners\EnviarEmailBoasVindas));

Isso vai exibir todos os métodos da sua classe. Você debuga usando o use Notificable, depois debuga sem. Vai notar que os métodos são adicionados na sua classe.
Conclusão
Se você não está utilizando nenhum dos métodos de Notifiable, realmente não é necessário herdá-lo. Use caso necessitar.
Há casos onde os traits são colocados para manter o comportamento padrão do Framework, como no caso dos traits de autenticação (depois eu coloco um exemplo pra você entender melhor).
Comment: Muito bom, bela explicação. Agora compreendi.


Evento Click, pegar o valor do input da linha de forma dinâmico

Question: Tenho o seguinte código abaixo

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany
    <input type="hidden" value="0">

    Centro comercial Moctezuma
    Francisco Chang
    Mexico
    <input type="hidden" value="1">

Quero pegar o valor do input invisível ou até mesmo de alguma determinada coluna. O evento click que fiz eu consigo pegar todo o elemento TR e elementos filhos, porem não consigo acessar um dado em especifico pelo This. Alguém consegue me ajudar, se consigo pegar o valor do input que vem no This?
Answer:


How to save iotop's output for a specific period of time

Question: I am trying to discern what processes are making huge Read/Writes on my server disk. I know I can use
iotop -ao

but is there a way I can save iotop's output for a specific period of time to study later?
Comment: i would use a cronjob to fire it up, put it in the background, and kill it after $X seconds.
Answer: This isn't strictly answering your question, but you might find atop more useful.  It can run as a daemon and write to a binary log file.  The file contains all data necessary to reproduce what would have been seen had atop been run 'live'.
To run atop as a daemon, you could kick it off as
/usr/bin/atop -a -w /var/log/atop.log 60

to write a snapshot to the log every 60 seconds.  Later you can see what was going on at a specific time by doing e.g.
atop -r /var/log/atop.log -b 10:00

to start at 10am.  You can then step backwards and forwards throught the log to see how system activity developed.
To address your specific question of disk activity, pressing d while in atop will sort processes by their total disk activity at that point in time, and in the summary at the top of the screen you'll be able to see aggregated per-device statistics.


Reinterpreting Unicode strings

Question: I'm receiving unicode data from a client, stored in a dictionary called "data". The following code
variable1 = '\u03b5\u0061\u0073\u0064\u0066'
print("TYPE1 = " + str(type(variable1)))
print("VAR1 = " + variable1)

variable2 = data['text']
print("TYPE2 = " + str(type(variable2)))
print("VAR2 = " + variable2)

prints
TYPE1 = <class 'str'>
VAR1 = εasdf
TYPE2 = <class 'str'>
VAR2 = \u03b5\u0061\u0073\u0064\u0066

This suggests that the data from the client is somehow not interpreted properly. Writing the variables to file also gives the exact same result: the file has the literal "\u03b5\u0061\u0073\u0064\u0066". How can I "reinterpret" that unicode string so that I get the same result as the inline variable?
The following did NOT work:

eval(variable2) (Error: "unexpected character after line
continuation character")

With print(variable2.encode().decode()), I get VAR2 = ε.
By using .encode('ascii').decode('unicode_escape'), I get UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
In the shell:
>>> "\u03b5\u0061\u0073\u0064\u0066"
'εasdf'

Comment: What about `u'\u03b5\u0061\u0073\u0064\u0066'`?
Answer: It depends on how consistently the input data got corrupted (or encoded in some particular way), but for the given example the following should work:
>>> data = '\\u03b5\\u0061\\u0073\\u0064\\u0066'
>>> print(data)
\u03b5\u0061\u0073\u0064\u0066
>>> text = data.encode('ascii').decode('unicode_escape')
>>> print(text)
εasdf

The "unicode_escape" codec is provided exactly for Python-style Unicode escapes. It also works with escapes of the form \xNN and \U000NNNNN, mixed with literal ASCII characters.
A few things to note:

The .encode('ascii') step is necessary, because .decode only exists for bytes, not str.
If you have a mixture of non-ASCII literals and Unicode escapes (as is allowed in Python str literals), you can try encode('utf-8'), but I haven't thought this through.
eval doesn't work here because there are no quotes around the data.
It's possible that your data originates from JSON, where the \uNNNN escapes also exist (but not the \xNN and \U000NNNNN ones). If this is the case, you have to deal separately with characters above U+FFFF (eg. emojis), which are represented by surrogate pairs.
Comment: Updated my question with your suggestions and the results.
Comment: The data does indeed originate from JSON.
Comment: Have you tried `.encode('utf-8')` instead of ASCII? Maybe you could also update your example to reproduce the `UnicodeEncodeError` as well.
Comment: I don't know how to reproduce it without the client sending it (that would have made it a lot simpler). In the Python shell, printing these literals gives the right output. I guess `str = "ε"` is the closest thing: if you can make that into an `ε` then I guess it would work.
Comment: It would seem that `"ε"` indeed is what is actually received.
Comment: "Îμ" looks like an issue with the terminal configuration. If Python sends the bytes for "ε", but your terminal interpretes them as Latin-1 (or Windows CP-1252), it will print mojibake "Îμ".
Comment: ... but if you get the original JSON data, you can just `import json; json.loads(data)` if data is a string, or `json.load(stream)` if it is a filehandle.
Comment: I use `json.loads(data)` where `data` is the raw data before attempting to use it.
Comment: Got it working, thanks for the tips which got me in the right direction (see my answer).
Answer: Escaping the unicode (JavaScript example below)
function escapeUnicode(str) {
    return str.replace(/[^\0-~]/g, function(ch) {
        return "\\u" + ("000" + ch.charCodeAt().toString(16)).slice(-4);
    });
}

before sending the data and using
input.encode("utf-8").decode('unicode-escape')
seemed to work.

Reinterpreting Unicode strings


Adicionar url evento json em fullcalendar

Question: Estou usando o fullcalendar, nodejs e mongoose.
Já consegui gerar o arquivo json.
Mas ao passar o caminho no js do fullcalendar, nao consigo recuperar os eventos.
Criei um arquivo de teste em json e chamei da seguinte forma:
 script(type='text/javascript').
    $(document).ready(function() {
      $('.calendar').fullCalendar( {
          header: {
            right: 'prev,next today,month,agendaWeek,agendaDay'
          },
          aspectRatio: 2,
          events: "/calendars.json"
      } );
    });

Porem não funciona.
Queria saber como posso fazer para chamar as informações do mongoose e exibir no calendário.
Comment: Bem vindo ao SOPt, Nodejs. Você disse que seu código não funciona. Mas, que erro é retornado? [Edite](http://pt.stackoverflow.com/posts/68931/edit) sua pergunta e adicione essa e outras informações que achar relevante para resolução do problema. Sugiro uma leitura em [tour] e [ask].
Comment: ja resolvi. Obrigada!
Comment: Como deve ser esse caminho? esse `calendarjson` seria `calendar.json`? usando `events: "/calendars/calendarjson",` como caminho para o arquivo.json
Answer: resolvido:
obs: é necessario baixar o js qtip para adicionar pop-up com os eventos.
script(type='text/javascript').$(document).ready(function() {
      $('.calendar').fullCalendar({
        header: {
          right: 'prev,next today,month,agendaWeek,agendaDay'
        },
        events: "/calendars/calendarjson",//caminho arq. json
        eventRender: function(event, element)//abrir popup cm eventos {
          element.qtip({
            content: "" + event.flRoot+""+"
" + "Cliente: " + event.client+""+"
" + "Pauta: " + event.name+"",
          });
        }
      });
    });


Como entregar ligações na fila na ordem que os agentes fazem login?

Question: Eu tenho uma fila no asterisk onde a estratégia está no modo leastrecent.
Porém, tenho observado que a ordem que os atendentes fazem login na fila não é a mesma na hora de receber a primeira ligação.
A distribuição só funciona de fato após todos eles atenderem uma ligação e ficar com a informação do tempo de ocioso.
Enquanto isso, a distribuição acontece de forma aleatória para quem ainda não atendeu a primeira chamada.
Como fazer para as primeiras ligações serem entregues na ordem que fazem o login?
Agradeço desde já.
Answer: De acordo com a documentação do asterisk, estratégia de toque leastrecent encaminha a próxima chamada para o agente mais ocioso, portanto acredito que não é o que você procura.
A estratégia que melhor se encaixa na necessidade descrita é a linear, que encaminha as chamadas para os agentes na mesma ordem em que eles foram adicionados à fila, ou seja a ordem em que eles fizeram login.
Fonte: Repositório oficial do asterisk


Disagreement between p-values and confidence intervals

Question: This is a question regarding the t-test in SPSS.
I have two groups and I want to test if the two means are equal. I am using the t-test with bootstrapping. In the end I got a p-value<0.005, which would generally cause me to reject the null hypothesis that the means of the two populations are equal but in my case the zero lies within the 95% BCa bootstrap confidence intervals based on 1000 samples.
Do I still reject the hypothesis of equal means?
Comment: To clarify, did you conduct a bootstrapped t-test from which you are now comparing the p value and 95%CI, or did you run a standard t-test (not bootstrapped) to get the p-value and only used bootstrapping for the CI?
Answer: Caveat: This answer assumes that the question is about interpreting bootstrapped p-values and CIs. A comparison between a traditional p-value (not bootstrapped) and a bootstrapped CI would be a different issue.
With a traditional (not bootstrapped) t-test, the 95%CI and the p-value's position relative to the .05 cutoff for significance will always tell you the same thing. That's because they're both based on the same information: the t-distribution for your degrees of freedom and the mean and standard error observed in your sample (or difference between means and standard error, in the case of a two-sample t-test). If your CI doesn't overlap with 0, then your p-value will necessarily be < .05 --- unless, of course, there's a bug in the software or a user error in implementation or interpretation of the test.
With a bootstrapped t-test, the CI and p value are both calculated directly from the empirical distribution generated by the bootstrapping: the p value is simply what percent of bootstrapped group differences are more extreme than the original observed difference; the 95%CI is the middle 95% of bootstrapped group differences. It is not impossible for the p-value and the CI to disagree about significance in a bootstrapped test.
Do you accept or reject the null hypothesis?
In the context of a bootstrapped test, the p-value (as compared to the CI) more directly reflects the spirit of the hypothesis test, so it makes the most sense to rely on that value to decide whether or not to reject the null at your desired alpha (generally .05). So in your case, where the p value is less than .05 but the 95%CI contains zero, I recommend rejecting the null hypothesis.
All of this skips over the big ideas about how important "significance" really should be and whether or not null hypothesis significance testing is actually that useful of a tool. Briefly, I always recommend complimenting any significance testing analysis with estimation of effect sizes (for a two-sample t-test, the best effect size estimate will probably be Cohen's d), which can provide some additional context to help you understand your results.
Related helpful post: What is the meaning of a confidence interval taken from bootstrapped resamples?
Comment: This is a great answer (+1), but some advice on how the OP approaches whether he accepts or rejects the Null would round out the answer for the OP's final question.
Comment: @Ashe Thanks! You're right that I didn't address the central question head-on. I'll edit to improve that.
Comment: "for a two-sample t-test, the best effect size estimate will probably be Cohen's d" Is this specific to the bootstrapping? Because I would think for a normal t-test, the confidence interval is gives you the best information about effect size on the actual scale that you tested on.
Comment: Cohen's d is for any two group difference; bootstrapping or not is irrelevant. CIs are generally not considered estimates of "effect size" since they depend on sample size (e.g. https://en.wikipedia.org/wiki/Effect_size#Difference_family:_Effect_sizes_based_on_differences_between_means: "Unlike the t-test statistic, the effect size aims to estimate a population parameter and is not affected by the sample size.") Perhaps what you're wondering about is standardized vs. unstandardized effect size estimates? The unstandardized effect size for two groups is just the raw difference between means.
Comment: Many thanks! Your explanation about what p-value and CI are in the context of a bootstrapped t-test was very useful. As you suggest I determined the  Cohen's d, a very helpful statistic in understanding my results.
Comment: I upvoted your post before you added what to conclude. After the edit I must say I disagree. But don't worry, not enough to want to retract my +1 ;) The reason I disagree is that I'd argue to follow the bootstrap CI instead of the t-test p-value (not rejecting $H_0$). My main argument: bootstrapping is performed to make inferences less sensitive to rare outliers or other data-idiosyncrasies. Especially 'BCa' CI provides adjustments which lend bootstrapping its advantages. As such I'd follow the results of the bootstrap. Most importantly though, this should be decided before seeing the results.
Comment: @IWS I agree that the bootstrapped results have several desirable qualities. I was assuming that both the p value and CI were based on the bootstrapped distribution. Is that not the case in this SPSS test? If so, a few things about my answer probably need to be edited!
Comment: Interesting, I read this as a comparison of a regular t-test and a bootstrapped confidence interval of the difference of group means. Maybe the OP can enlighten us?
Answer: If the p-value of the null hypothesis is smaller than 0.05, then zero should not be contained in the confidence interval at 0.05 of the parameter that you are assuming to be zero in the null hypothesis. This is the same thing. So there is a bug or you don't test the same hypothesis.
EDIT, as the other answers and the comment below correctly indicate, this is not the full story. However, I still think that if one test indicates groups have different mean (p < 0.005), and the other does not reject (p > 0.05), probably the tests are really checking a different thing.
While theoretically this difference could be due to asymptotics (bootstraps are approximations on finite sample, other tests are approximations based on normality assumptions), that difference is surprisingly large. I argue it is alarmingly large, and without figuring out what is going on with that, you should not yet draw conclusions. That is also exactly what you are doing, by the way, by posting the question here. Maybe you can share the numbers and make this interesting question a bit more concrete.
Comment: I disagree. A bootstrapped confidence interval may not follow the results of a t-test, as it is a different kind of procedure altogether (in this case based on the difference of group means). Especially when 'bias-corrected and accelerated bootstrap confidence interval is made, things like asymmetric confidence intervals around the original estimate (i.e. difference of group means in this case) could occur.


How many homomorphism are there of the form $S_n \to \mathbb{Z_2},n\geq 5$?

Question:
How many homomorphism are there of the form $S_n \to \mathbb{Z_2},n\geq 5$?

My solution:
Using first isomorphism theorem each kernel of homomorphism is a normal subgroup in $S_n$.
I know the only normal subgroups of $S_n$ are $1,A_n,S_n$.
Let $q$ be a homomorphism using first isomorphism theorem $\frac{S_n}{\ker q}\cong{\rm Im}(q)\leq \mathbb{Z_2}$.
Case 1: $\ker q= S_n \implies \frac{S_n}{\{S_n\}}\cong{\rm Im}(q)\leq \mathbb{Z_2}\implies{\rm Im}(q)=\{1\}$
Case 2: $\ker q= A_n \implies \frac{S_n}{\{A_n\}}\cong{\rm Im}(q)\leq \mathbb{Z_2}\implies{\rm Im}(q)= \mathbb{Z_2}$.
Case 3: $\ker q=\{1\} \implies \frac{S_n}{1}\cong{\rm Im}(q)\leq \mathbb{Z_2}$, which  isn't possible since $|S_n|=n!>|\mathbb{Z_2}|$
There are $2$ homomorphisms: case 1 and case 2.
Is my solution correct?
Thanks!
Comment: It looks fine to me!
Comment: See also https://math.stackexchange.com/a/2763380/589
Answer: If you didn't know about normal subgroups of $S_n$, you could've still reached the same conclusion like this:

Note that in $S_n$ every two $2$-cycles (transpositions) are conjugate to each other. Namely, if $f=(x\,y)$ and $g=(z\,t)$ then you can easily construct $h$ such that $g=h^{-1}fh$. Say, if all $x,y,z,t$ are different, then $h=(z\,x)(t\,y)$. If one pair is the same, say $x=z$, then $h=(t\,y)$. If both pairs are the same, then $h=id_{S_n}$.
A homomorphism into $\mathbb Z_2$ must map conjugate elements to the same element, as $\mathbb Z_2$ is Abelian. Namely, if $F:S_n\to\mathbb Z_2$ is a homomorphism, and $g=h^{-1}fh$ in $S_n$, then $F(g)=F(h)^{-1}F(f)F(h)=F(h)^{-1}F(h)F(f)=F(f)$.
That means that all $2$-cycles must map into the same element of $\mathbb Z_2$.

Thus, we have only two cases:

Every $2$-cycle maps to $0$ and so every other element of $S_n$ maps to $0$ - trivial homomorphism
Every $2$-cycle maps to $1$, which means that every odd permutation in $S_n$ (a composition of an odd number of $2$-cycles) maps to $1$ (a sum of an odd number of $1$'s) and, similarly, every even permutation maps to $0$.
Answer: You can add that the two homonorphism are known. Of course the first one is the trivial morphism, while the second one is the $sgn \colon S_n\to \mathbb{Z}_2$ permutation morphism, that sends any permutation to its sign.


Computing Hilbert polynomial

Question: We have the following condition:

For each $i=2,...,m$ multiplication by $f_{i}$ is injective on $S/(f_{1},...,f_{i-1})$, where $S=k[T_{0},...,T_{n}]$, $m \leq n$, and the $f_{i} \in S_{d_{i}}$ are non-zero homogeneous elements of degree $d_{i}>0$.
Given this, we wish to compute the Hilbert polynomial of $M=S/(f_{1},...,f_{m})$.

The general theory of Hilbert polynomials makes sense when I read it, but I am somewhat confused in how to approach this problem. Any help would be appreciated!
Comment: Can you do it when $m=1$?
Answer: Use induction by using the following exact sequence: $$0\to S/(f_{1},...,f_{i-1})\stackrel{f_i\cdot}\to S/(f_{1},...,f_{i-1})\to S/(f_{1},...,f_{i})\to 0.$$
But wait, the multiplication by $f_i$ is not a graded homomorphism! Then we have to correct the grading by a shift and the exact sequence of graded $S$-modules looks like $$0\to S/(f_{1},...,f_{i-1})(-d_i)\stackrel{f_i\cdot}\to S/(f_{1},...,f_{i-1})\to S/(f_{1},...,f_{i})\to 0.$$ Now you get the following relation for Hilbert series: $H_{S/(f_{1},...,f_{i})}(t)=(1-t^{d_i})H_{S/(f_{1},...,f_{i-1})}(t)$.

Computing Hilbert polynomial


Geometric distribution with multiple successes

Question: Here's the question:
"A sales representative vows to keep knocking on doors until he makes two sales. Given that his probability of success is $u$, let $X$ = the number of doors he knocks on.
Find the probability mass function of $X$"
My thought is that $x$ cannot be less than $2$, since he would have to knock on two doors to make two sales.
I'm thinking the function would be $\displaystyle\binom{x}{2} (u^2)(1-u)^{x-2}.$
But when I go to find $E(x)$, that doesn't lend itself well to the geometric form I've learned to love.
Am I on the right track at least?
Thanks for any help.
Answer: Let us find the probability that $X=x$, that is, the probability she has to knock on $x$ doors.
She has to have $1$ success (and therefore $x-2$ failures) in the first $x-1$ trials, and then a success. The probability of this is
$$\binom{x-1}{1}u(1-u)^{x-2}u.$$
Comment: I think I generalized correctly this logic to `n` successes
$$\binom{x-1}{n-1}(1-u)^{x-n}u^n.$$
Interactive version here: https://www.desmos.com/calculator/ls9mbyrtul
Answer: The formula
$$p_x=\binom x2 u^2(1-u)^{x-2}$$
is the probability that he knocks on at most $x$ doors.  But you want the probability that he knocks on exactly $x$ doors.  One way to find this would be:

number of possibilities for the first successful knock is $x-1$;
probability of each case is $u^2(1-u)^{x-2}$;
total probability is $(x-1)u^2(1-u)^{x-2}$.

Indeed it's not geometric, but instead of summing the series, you can use linearity of expectation: the expected value of $X$ will be the expected number of knocks to get one success, plus the number of additional knocks required to get the second success.  And the latter is just the same as the former.
Answer: The negative binomial distribution of trials until the second success is: $$\mathsf P(X_2=x) = {x-1\choose 1}u^2(1-u)^{x-2}$$
There must be $x-2$ failures and one success in any order before the last success.

The negative binomial distribution of trials until the r-th success is: $$\mathsf P(X_r=x) = {x-r+1\choose r-1}u^{r}(1-u)^{x-r}$$
The geometric distribution is the special case of a negative binomial where $r=1$.
$$\mathsf P(X_1=x) = {x\choose 0}u^{1}(1-u)^{x-1} = u(1-u)^{x-1}$$
Comment: I believe your general case formula is incorrect, the binomial's upper parameter should be `x-1` instead of `x-r+1`. Imagine 10 trials and 7 successes, the 7th success is at the 10th trial, but the previous 6 successes are in any combination inside the first 9 trials, so it should be `9 choose 6` instead of `4 choose 6` (which is impossible).