Poisson process for the spatial analysis of accidents

Question: I have a large dataset consisting of the geographic location, company, and date of accident.  I also have a grid with a cell size that is 6 miles x 6 miles to disaggregate the data, since the dataset is much larger than the one shown (>1 million location points over a provincial scale).  I am trying to calculate the probability of a k-number of accidents in each grid cell based on the data points.
The accidents have the following characteristics:

Accidents can randomly occur at any location within each grid cell.
Two accidents can occur at the same time in each grid cell.
Accidents can be counted 1, 2, 3, ... , n.
Accidents are independent of each other.
The average rate of accident can be calculated for each grid cell.

Everything seems to almost fit the criteria for a Poisson Process; however, two accident events can occur at the same time in each grid cell.  I have calculated the Poisson probability CDF of each grid cell for a k-number of accidents, but not comfortable with the results because of the fact that two accidents can occur at the same time within a single grid cell.
Is the Poisson distribution robust enough to handle the fact that two accidents can occur at the same time within a grid cell.
Also, is there a better way to deal with this sort of problem, since I fully expect the results of this probability analysis to have a spatial scale dependence.
Answer: I think your approach is reasonable. You presume a different Poisson process for each cell, which lets you predict the accident rate with a larger resolution. The cells are not too small, so there is still enough data for each cell. You also presume that the rate doesn't change with time, which seems to be OK, too.
You don't have to worry about accidents happening at the same time. You can adopt the viewpoint that none of your accidents will ever happen at the same time, the probability for this is zero, and the fact that the clocks used to measure the time of the accident are not precise enough to show this doesn't have a bearing on the usability of the Poisson distribution. Relevant is the independence between the accidents and the time independence of the rate of the process.


melhor nome para esse metodo em php

Question: Estou com duvida em qual nome colocar no metodo em PHP abaixo:
<code>    public function checkbox($idForm)
    {
        $list = $this->v->getAllInAssocArr();

        foreach ($list as $key => $val) {

            $isRel = $this->v->isRel($idForm, $key);

            if (self::isPost($key) && !$isRel) {
                $this->v->insert($idForm, $key);
            }

            if (!self::isPost($key) && $isRel){
                $this->v->delete($idForm, $key);
            }
        }

    }
</code>
Ele add ou remove Dados no DB conforme os posts selecionados
no checkbox do formulario.
pensei em colocar "updateCheckboxByIdForm" mas ele nao atualiza
Comment: O que vc quer dizer com "ele nao atualiza"? Vc pode colocar o nome que vc quer. Na minha opinao, "updateCheckboxByIdForm" significa nada melhor que o nome original. Se depende do formulário por ser "checkbox_inscricao" ou "checkbox_cliente" etc...
Comment: sobre "nao atualiza" . Eu quiz dizer que o metodo nao foi feito para atualizar os dados. apenas "insere" ou "remove" por isso achei estranho colocar "update ..." como nome para o metodo ...
Answer: Olá, seja bem vindo. Acredito que o nome updateCheckboxById como você mesmo citou seja um bom nome.
Eu sempre costumo seguir um padrão de iniciar verbalizando o que irá fazer , seguido do objeto mais a ação daquele método:
Ex: getUserClear()
<code>    public function updateCheckboxById($idForm)
    {
        $list = $this->v->getAllInAssocArr();

        foreach ($list as $key => $val) {
            $isRel = $this->v->isRel($idForm, $key);
            if (self::isPost($key) && !$isRel) {
                $this->v->insert($idForm, $key);
            }
            if (!self::isPost($key) && $isRel){
                $this->v->delete($idForm, $key);
            }
        }
    }
</code>
Comment: vlw! obrigado josé :)
Comment: Qq coisa é só avisar!

melhor nome para esse metodo em php


Erro 1452 mysql: Cannot add or update a child row

Question: Criei as seguintes tabelas e fiz populate em 2 (utilizador e tipo);
CREATE:
CREATE TABLE utilizador(utilizador_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,username VARCHAR(100) NOT NULL, password VARCHAR(100) NOT NULL, morada VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL, numero_cc INT NOT NULL);
CREATE TABLE produtos(id_produto INT NOT NULL PRIMARY KEY AUTO_INCREMENT,nome VARCHAR(100) NOT NULL, genero CHAR(1) NOT NULL, preco INT NOT NULL,id_tipo INT);
CREATE TABLE tipo(id_tipo INT NOT NULL PRIMARY KEY AUTO_INCREMENT,designacao VARCHAR(100) NOT NULL);
CREATE TABLE cart_produtos(id_produtos INT NOT NULL PRIMARY KEY AUTO_INCREMENT,quantidade INT,valor INT,id_cart INT);
CREATE TABLE cart_utilizador(id_cart INT NOT NULL PRIMARY KEY AUTO_INCREMENT,id_utilizador INT);
CREATE TABLE cart(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,datas DATE NOT NULL);

ALTER TABLE cart_utilizador ADD CONSTRAINT id_utilizador_fk
FOREIGN KEY (id_utilizador_fk) REFERENCES utilizador(utilizador_id);

ALTER TABLE cart_produtos ADD CONSTRAINT id_cart_fk
FOREIGN KEY (id_cart) REFERENCES cart_utilizador(id_cart);

ALTER TABLE produtos ADD CONSTRAINT id_fk
FOREIGN KEY (id_produto) REFERENCES cart_produtos(id_produtos);

ALTER TABLE cart_utilizador ADD CONSTRAINT id_cart_produtos_fk
FOREIGN KEY (id_cart) REFERENCES cart_produtos(id_produtos);

ALTER TABLE produtos ADD CONSTRAINT id_tipo_fk
FOREIGN KEY (id_tipo) REFERENCES tipo(id_tipo);

ALTER TABLE cart ADD CONSTRAINT id_cart_prime_fk
FOREIGN KEY (id) REFERENCES cart_utilizador(id_cart);

POPULATE:
INSERT INTO utilizador(username,password,morada,email,numero_cc) VALUES("ricardinho","oscarpw","Rua dos Aliados","firstname.lastname@example.com",123349574);
INSERT INTO utilizador(username,password,morada,email,numero_cc) VALUES("blitzo","maidpw","Rua das Carrinhas","firstname.lastname@example.com",139845923);
INSERT INTO utilizador(username,password,morada,email,numero_cc) VALUES("ricstu","glamorpw","Rua dos Aliados","email@example.com",188957923);
INSERT INTO utilizador(username,password,morada,email,numero_cc) VALUES("jacintosr","jckoneilpw","Avenida das Ameijoas","email@example.com",123349574);
INSERT INTO tipo(designacao) VALUES("calca");

INSERT INTO tipo(designacao) VALUES("chapeu");

INSERT INTO tipo(designacao) VALUES("camisola");

Quando faço o populate da tabela produtos com este script:
INSERT INTO produtos(nome,genero,preco,id_tipo) VALUES("calca preta com riscas","M",18,1);

Acontece-me o erro (Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (loja.produtos, CONSTRAINT id_fk FOREIGN KEY (id_produto) REFERENCES cart_produtos (id_produtos))
)
Como resolvo isto?
Answer: O problema está aqui:
ALTER TABLE produtos ADD CONSTRAINT id_fk
FOREIGN KEY (id_produto) REFERENCES cart_produtos(id_produtos);

Com isso para criar um registro em produtos, precisa utilizar um id_produto existente em cart_produtos.
Comment: Então, para resolver isso tenho que eliminar a relação e fazer populate primeiro e depois fazer esse script? @karran
Comment: o que eu acredito que você quer é `ALTER TABLE cart_produtos ADD CONSTRAINT id_fk
FOREIGN KEY (id_produtos) REFERENCES produtos(id_produto);`
Comment: nesse caso você teria que remover a relação antiga e adicionar essa nova, talvez haja mais problemas, @fabimetabi
Comment: tem razao faz mais sentido a relação dessa maneira, amanha irei testar obrigado!
Comment: Obrigado, se tudo der certo por favor depois marque a minha resposta como solução


Load balanced asp.net websites and required memory usage

Question: Each of my servers has 8Gb RAM and the memory usage hovers around 7Gb. I have a load balancer available to me but at the moment I'm worried that putting my sites through it will cause the platform to fall over. The load balancer would be configured with a sticky round-robin where a new connection is round robin but subsequent connections for the same source ip will remain on the same server (until a limit is reached). Thats all standard stuff.
How do I know what memory usage my sites will need across the platform when I put them through the load balancer? Rather than knowing that a site is using 150mb on a particular server I could face a situation where the 150mb is taken up on each of the servers. I know that with only 1 gb free I could have a serious problem on my hands. If I free up some memory then how can I work out what I need to have free to prevent this from happening?
Thanks
Matt
Answer: If you're using round-robin with a session database then yes each server will occupy residual memory on both machines that the site/application is loaded, until at least the worker process times out.
Look at using Windows Load balancer in windows 2008, it has processes that monitors where a session is running and orphaned memory is garbage collected.
Also note, memory from the sites app pool in iis will obviously continue to be allocated even while using windows load balancer, it's just the memory used by the worker processed that's better managed.


Gmail accessToken and refreshToken from Android App

Question: I have a backend app which uses gmail access token and refresh token to access user's gmail account.
<code>    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setAccessToken(accessToken);
    tokenResponse.setRefreshToken(refreshToken);
    Credential credential = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).setTransport(
            HTTP_TRANSPORT)
            .setJsonFactory(JSON_FACTORY)
            .setTokenServerUrl(
                new GenericUrl("https://accounts.google.com/o/oauth2/token"))
            .setClientAuthentication(new BasicAuthentication("abc.apps.googleusercontent.com",
                    "xyz"))
            .build()
            .setFromTokenResponse(tokenResponse);
</code>
On the frontend, I have an android App where I have access to the authorizationToken:
<code>    mCredential = GoogleAccountCredential.usingOAuth2(
            getApplicationContext(),SCOPES)
            .setBackOff(new ExponentialBackOff())
            .setSelectedAccountName( (String)SharedPrefUtils.getValue(SharedPrefUtils.PREF_ACCOUNT_NAME,SharedPrefUtils.DATA_TYPE_STRING));
</code>
But how to get the accessToken and refreshToken from this to send to the backend
app?
 Can somebody please help?
Answer: Go through following:
https://developers.google.com/identity/protocols/CrossClientAuth
Look at section :Android app obtains offline access for web back-end


SQL Server 2012 Backups Not Compressing

Question: We recently upgraded from SQL Server 2008R2 to SQL Server 2012 Enterprise. After doing this I noticed that our DB backups were barely compressing at all. Our 22gb DB was compressing down to about 4gb before upgrading to 2012 and after the upgrade our 22gb DB is only compressing down to 19gb. I've checked and double checked the compression setting on the server and all of my backup jobs and compression is turned on. Any ideas on what may be going on?
Comment: The server default can be overridden.  Are you running your backups via script?  If so, can you post?  Or, if you're using a maintenance plan have you double checked the plan's specific compression setting?
Answer: It turns out this was due to also enabling TDE encryption. With TDE enabled the backups compress a very small amount.

SQL Server 2012 Backups Not Compressing


HP P800 PCI controller disables(!) HP 410i internal controller

Question: I have a HP DL360 G6 server with a very strange RAID controller behavior.
I installed a P800 PCI RAID Controller card and all of the sudden I cannot access my hard drives that are connected to the internal P410i controller. To be more precise, the bios automatically disables the P410i interface each and every time I restart.
I already tried updating the BIOS and flashing the P800 to the latest firmware all to no avail I'm afraid. I turned the BIOS upside down looking for something useful but nothing there.
Does anyone have any idea what could be causing this?
Thanks!
Answer: When you say you are unable to access the hard drives that are connected internally, do you mean in the BIOS, and you cannot boot from them?
Do you have many logical drives defined?
Is this legacy BIOS (not EFI)?
If all these questions are yes, then most likely the PCI HBA's OpROM is loading second, and pushing the BBS chain down so that the internal drives are pushed off the bottom. Disabling the OpROM/BIOS on the add-in card is the most straight forward way to deal with this.
Comment: What do you mean "disabling on the add-in card"? Is this something I can access through the bios?
Comment: Normally the BIOS on the RAID card although it can be done through some BIOS for the slot. Check out this page for some tips on changing the order: [link](http://webcache.googleusercontent.com/search?q=cache:http://bizsupport1.austin.hp.com/bc/docs/support/SupportManual/c00806102/c00806102.pdf#14)
Answer: Why not use the P800 to manage the internal disks anyway - you could remove the P410i and reduce overall complexity of the system?
Comment: I didnt have the proper cables for that I'm afraid.


Friend Function C++ how to design the function that takes 2 class objects as the argument

Question: I find difficulties in this part because it takes the class objects as the parameter of the function:
    friend Num_Fact GCD(Num_Fact , Num_Fact);
    friend Num_Fact LCM(Num_Fact , Num_Fact);

How to implement the GCD function with arguments of 2 class objects, and return the value back in as Num_Fact as following in cpp:
    cin >> value;

    Num_Fact A(value);

    cout << "Key in number B: ";
    cin >> value;
    Num_Fact B(value);
    cout << " A = "<< A.output() <<" = "<<A.getnum()<<endl;
    cout << " B = " <<B.output() << " = " << B.getnum() << endl;

    Num_Fact C = GCD(A, B);

Original Code:
    #ifndef NUM_FACTOR
    #define NUM_FACTOR

    #include<iostream>
    #include<array>
    #include<cmath>
    #include<sstream>

    using namespace std;
    #define Z 20

    class Num_Fact {
        friend Num_Fact GCD(Num_Fact , Num_Fact);
        friend Num_Fact LCM(Num_Fact , Num_Fact);

    public:
        Num_Fact(int num) {
            Num = num;
        }
        ~Num_Fact() {};

        long long int findgcd(long long int a, int b) {
            if (b == 0) return a;
            return findgcd(b, a % b);
        }
        long long int LCM2(long long int a[], int n) {
            long long int res = 1, i;
            for (i = 0; i < n; i++) {
                res = res * a[i] / findgcd(res, a[i]);
            }
            fact2num(res);
            return res;
        }
        long long int GCD2(long long int arr[], int n)
        {
            long long int result = arr[0];
            for (int i = 1; i < n; i++)
            {
                result = findgcd(arr[i], result);

                if (result == 1)
                {
                    fact2num(result);
                    return 1;
                }
            }
            fact2num(result);

            return result;

        }

        long long int GCD(int  a, int b) {

            int temp;
            while (b != 0) {
                temp = b;
                b = a % b;
                a = temp;
            }
            return a;
        }
        long long int LCM(int a, int b) {
            int lcm = (a * b) / GCD(a, b);
            return lcm;
        }

        string Factorize() {
            ostringstream output;
            int fac = 2;
            if (Num == 1) {
                output << Num;
            }
            while (Num > 1)
            {
                if (Num % fac == 0)
                {
                    output << fac << "^"; //print the base first
                    Num /= fac;
                    int pow = 1;
                    while (Num % fac == 0) //get the power of current base
                    {
                        Num /= fac;
                        pow++;
                    }
                    output << pow; //print out the power, now we have fac^pow printed

                    //if not the last factor, print a multiplication symbol
                    if (Num != 1)
                        output << " * ";
                }
                else
                {
                    fac++;
                }
            }
            return output.str();
        }

        string output() {
            ostringstream output;
            output << Factorize();
            return output.str();

        }
        int getnum() {
            return Num;
        }
    private:
        int Num;
        array<array<int, Z>, 2>fact;
    };
    #endif

Latest code for Header:
    #ifndef NUM_FACTOR
    #define NUM_FACTOR

    #include<iostream>
    #include<array>
    #include<cmath>
    #include<sstream>

    using namespace std;
    #define Z 20

     int findgcd(long long int a, int b) {
        if (b == 0) return a;
        return findgcd(b, a % b);
    }
     int LCM2(long long int a[], int n) {
        int res = 1, i;
        for (i = 0; i < n; i++) {
            res = res * a[i] / findgcd(res, a[i]);
        }

        return res;
    }
    int GCD2(long long int arr[], int n)
    {
        int result = arr[0];
        for (int i = 1; i < n; i++)
        {
            result = findgcd(arr[i], result);

            if (result == 1)
            {
                return 1;
            }
        }
        return result;

    }

    int GCD1(int  a, int b) {

        int temp;
        while (b != 0) {
            temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
    int LCM(int a, int b) {
        int lcm = (a * b) / GCD1(a, b);
        return lcm;
    }

    class Num_Fact {

    public:
        Num_Fact(int num) {
            Num = num;
        }
        ~Num_Fact() {};

        string Factorize() {
            ostringstream output;
            int fac = 2;
            if (Num == 1) {
                output << Num;
            }
            while (Num > 1)
            {
                if (Num % fac == 0)
                {
                    output << fac << "^"; //print the base first
                    Num /= fac;
                    int pow = 1;
                    while (Num % fac == 0) //get the power of current base
                    {
                        Num /= fac;
                        pow++;
                    }
                    output << pow; //print out the power, now we have fac^pow printed

                    //if not the last factor, print a multiplication symbol
                    if (Num != 1)
                        output << " * ";
                }
                else
                {
                    fac++;
                }
            }
            return output.str();
        }

        string output() {
            ostringstream output;
            output << Factorize();
            return output.str();

        }
        int getnum() {
            return Num;
        }
    private:
        int Num;
        array<array<int, Z>, 2>fact;
    };
    Num_Fact GCD(Num_Fact A, Num_Fact B) {
        return GCD(A.getnum(), B.getnum());
    }
    Num_Fact LCM(Num_Fact A, Num_Fact B) {
        return LCM(A.getnum(), B.getnum());
    }

    #endif

Latest Code for CPP
    #include<iostream>
    #include<array>
    #include<cmath>
    #include<sstream>
    #include"Num_Factor.h"
    using namespace std;
    const int S = 20;
    void bonus();
    int main() {
        int value;
        cout << "Key in number A: ";
        cin >> value;

        Num_Fact A(value);

        cout << "Key in number B: ";
        cin >> value;
        Num_Fact B(value);
        cout << " A = "<< A.output() <<" = "<<A.getnum()<<endl;
        cout << " B = " <<B.output() << " = " << B.getnum() << endl;

        Num_Fact C=GCD(A, B);

        return 0;
    }

It gives error when compiling such as "Unhandled exception at 0x00007FF72E1A53DF in lab09.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x000000C850A03EB8)." And also its pointing at:
Num_Fact GCD(Num_Fact A, Num_Fact B) {
    return GCD(A.getnum(), B.getnum());
}
Num_Fact LCM(Num_Fact A, Num_Fact B) {
    return LCM(A.getnum(), B.getnum());
}

The task is to call the Num_Fact C= GCD(A,B), the program is about to find gcd and lcm using classes and by using constructor such as "Num_Fact"
Answer: There's a lot of confusion in your class design. but I'm only going to address some of it here. First question, ask yourself why are the int versions of GCD and LCM members of the Num_Fact class? These functions work on integers only, so there is absolutely no reason to put them in the Num_Fact class. So move them out of the class, it will simplify the answer to your actual question. Second question, why are these functions returning long long int? They have integer arguments and they can never return a value that is bigger than an int. So change them to return int, again this will simplify the answer to your actual question.
With those changes done we can talk about your actual question. As we've seen you already have functions that calculate GCD and LCM on integers, so just use those functions when you want to calculate GCD or LCM on Num_Fact. Like this
Num_Fact GCD(Num_Fact a, Num_Fact b) {
    return GCD(a.getnum(), b.getnum());
}

Num_Fact LCM(Num_Fact a, Num_Fact b) {
    return LCM(a.getnum(), b.getnum());
}

That's it, really simple. In fact these functions doesn't even need to be friends, since they are only using the public methods of Num_Fact.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/250334/discussion-on-answer-by-john-friend-function-c-how-to-design-the-function-that).


Logout a user without req object Passport js

Question: I am using Passport js with Express js. In my application, I need a functionality that a user should be logged out from the server if he/she is idle for a certain time.
But the problem is it requires req (request) object in order to logout a user. How can I logout a user without req object.
Note: I am using cookie-session for the persistent session.
Thank you.
Comment: Can you please share your code?
Answer: Old question, but in case anyone else stumbles on this as I did:
If you require logging out with req, which is only available on the server, create a route that handles the logout functionality. Then when you need to log out on the client, redirect them to the logout route. (This is often achieved with something like router.push).
Since you're using cookie-session, you can also delete the cookie instead. You will still want to redirect somewhere after, such as a "you've been logged out" page.


Why does $form_state->get('XXX') return an empty value after the form has been submitted?

Question: In the QueueExampleForm.php) file, which is part of the Examples for Developers project, why does $form_state->get('insert_counter') always return an empty value after the form has been submitted and an item was inserted into the queue?
Comment: @leymannx Pings only work if someone was on the comment/post.  We tends to avoid crossposting across SE, but tolerate (to an extent) crossposts to D.O.  What we don't want are bug reports here.
Comment: Cross-posted on https://www.drupal.org/project/examples/issues/2978404
Comment: @Clive – Would this make this question off-topic then as well?
Comment: @mpdonadio, the reason why I first come here was because in my opinion Drupal official examples code should be something well tested before putting that in the official repository. Because lot of people take it naturally as a Bible!!! But now, I think really that it is a bug and non my misunderstanding.
Comment: @ostry.sn No worries.  I think this is a good question here.
Answer: I think it's a bug. So in order to keep the incrementing textfield.
we can remove the setting/getting of the useless arbitrary property "insert_counter" and exploit the call of existing instruction :
$items = $this->retrieveQueue($queue_name);

In resume, we can just replace :
'#default_value' => $this->t('item @counter', ['@counter' => $form_state->get('insert_counter')]),
by
'#default_value' => $this->t('item @counter', ['@counter' => count($items) + 1]),

And remove the $form_state->setRebuild(); inside the addqueue submit handler
Answer: Lets try with
$form_State->getValue('insert_counter');

or
$form_State->get('insert_counter')->getValue();

Comment: In fact, "insert_counter" is not a field form, but an arbitral property set dynamically
Answer: I think try below code
$textfield_1 = $form_state->getValue('insert_counter');  //'#tree' => TRUE
 $values = $form_state->getValues(); // '#tree' => TRUE

Comment: In fact, "insert_counter" is not a field form, but an arbitral property set dynamically


How to join strings conditionally without using let in javascript

Question: I have a situation where I'm trying to join the array of strings only if it has a value. I did using let variable, but I wonder can I do this using map. I'm very mindful on the position, so I used in this way.

const [hours, minutes, seconds] =["", "10", ""]

  let time = "";

 if (hours) {
    time += `${hours}h `;
  }
  if (minutes) {
    time += `${minutes}m `;
  }
  if (seconds) {
    time += `${seconds}s`;
  }

  console.log(time)

Will I be able to do this using map, filter and join?
Answer: If you put the hours, minutes, and seconds back into an array, you can make another array for the suffixes, add the suffixes by mapping the values, then filter out the resulting substrings that are 1 character or less (which would indicate that there wasn't a corresponding value).

const suffixes = ['h', 'm', 's'];
const [hours, minutes, seconds] = ["", "10", ""]; // combine this with the next line if you can
const hms = [hours, minutes, seconds];
const time = hms
  .map((value, i) => value + suffixes[i])
  .filter(substr => substr.length > 1)
  .join(' ');
console.log(time)
Comment: Lovely. This helps
Answer: Here's a nice little snippet

const suffixs = "hms"; // String arrays of single characters can be shortened to this!
const values = ["","10",""];

var string = values
               .map((x,i) => x ? x + suffixs[i] : x)
               .filter(x => x)
               .join(" ");

console.log(string);

// Or if you want to have 0 in place of empty values

var string2 = values
                .map((x,i) => (x || "0") + suffixs[i])
                .join(" ");

console.log(string2);
Answer: Personally, I would create a list of objects, that represents the time.
I prefer this over using two arrays, as it can save some bugs (like changing the order of the data in one list but not in the other one):

const [hours, minutes, seconds] = ["20", "10", ""];

const time = [
  { amount: hours, sign: "h" },
  { amount: minutes, sign: "m" },
  { amount: seconds, sign: "s" },
];

const str = time
  .filter((val) => val.amount)
  .map((val) => val.amount + val.sign)
  .join(" ");

console.log(str);


Unable to get the Copy property of the Worksheet class

Question: I'm trying to copy a worksheet from workbook into another using Worksheets.Copy function. However, this seem to be working in only some of the files and for others I get "Unable to get the Copy property of the Worksheet class" error message. I've tried to copy/move worksheets manually from other workbooks. Also, tried unprotecting/protecting workbook and worksheets but none seem to be working. I'm using Microsoft Office 2010. Is there an Excel feature that enables/disables copying worksheets form other workbooks?
Comment: Did you ever find a solution?
Comment: No, but there's manual workaround.
Answer: In case someone stumbles upon this in the future, my issue was that the worksheet I was trying to copy was set to 'xlSheetVeryHidden'. To overcome this issue, I temporarily made the sheet visible and made it hidden again straight after the Copy call.
<code>templateWorksheet.Visible = xlSheetVisible
Call templateWorksheet.Copy
templateWorksheet.Visible = xlSheetVeryHidden
</code>
Answer: In my case the issue was that I had not been working with the worksheet but the workbook. Make sure you are using the worksheet and not the book.
Answer: In my case, the Excel file was not enabled for editing. Once I did that, it worked.


Plugin Sublime Text - Publica arquivos automaticamente em outra pasta

Question: Alguém conhece algum plugin para o Sublime Text 2 que de alguma forma publique os arquivos modificados em uma dada pasta?
Outro aplicativo que tem este recurso é o Dreamweaver.
Answer: Eu utilizo um build system. É rápido, fácil e simples. :)
Eu uso Windows 8, mas o princípio é o mesmo pra outros sistemas operacionais (e há mais detalhes na documentação que eu referenciei acima):

Crie um arquivo de build system específico para o seu projeto (por exemplo, meuProjeto.sublime-build) no no diretório Packages\User a partir da instalação (no caso do Windows fica em User\AppData\Roaming\Sublime Text 3\Packages\User).
Adicione nesse arquivo uma tag de comando para a execução de um arquivo de script (no caso do Windows, um arquivo batch). Por exemplo:

{
    "cmd": ["C:\\CAMINHO\\DO\\SCRIPT\\meuProjeto-copiaArquivos.bat"]
}

Então, crie o arquivo de script no caminho e com o nome previamente configurados, adicionando os comandos necessários para a cópia dos arquivos do seu projeto.

Eu uso esse esquema para copiar arquivos de projetos Web usando o comando xcopy para uma pasta do Wamp Server, e então abrindo automaticamente o Google Chrome em localhost:
@echo off
xcopy /E /Y /A C:\CAMINHO\DO\PROJETO\*.* C:\wamp\www\MeuProjeto\
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "http://localhost/"

Depois provavelmente você precisará reinicializar o Sublime Text, mas o novo build system poderá ser selecionado no menu Tools -> Build System e executado no menu Tools -> Build.


Query to select appropriate feedback record based on dates

Question: I understand there are many questions and answers outlining how to query data with relation to dates stored in SQL. My question, while in the same vein, is not something I've been able to find a solution for.
There is a SolutionRevisions table with three relevant columns: SR_ID (primary), SR_SolutionID, and SR_CreatedDate.
There is a Feedback table with F_ID, F_ItemID (maps to SR_SolutionID) and F_CreatedDate, F_SubItemID (currently empty).
My goal is to identify which SolutionRevisions record was the active when a feedback item was created and insert the SR_ID value into F_SubItemID column. This could be done by choosing the revision record created most recently before the feedback item.
To begin, I've began by trying to select back appropriate values for testing and verification. What I have looks like this:
SELECT sr.SR_ID, f.F_ItemID, sr.SR_CreatedDateUtc, f.F_CreatedDateUtc
FROM Feedback AS f
INNER JOIN SolutionRevisions AS sr on f.F_ItemID = sr.SR_SolutionID
WHERE f.F_CreatedDateUtc > sr.SR_CreatedDateUtc

This is obviously missing a necessary portion of the where clause (thus returning inaccurate results). The where clause needs to include (in pseudo-code)
AND f.F_CreatedDateUtc < nextSRCreatedDate

^ where "nextSRCreatedDate" represents the sr.SR_CreatedDate of the next record on the SolutionRevisions table for the same SR_SolutionID. My issue lies in getting back the correct value for nextSRCreatedDate
Example data:

Any help is appreciated, if more info is requested I'll promptly reply.
Comment: Sample data and desired results would really help.
Comment: Will get some and share momentarily.
Answer: Try this approach instead. It uses a subselect to determine the most recent record in the SolutionRevisions table at the time any individual Feedback record was created.
It's probably not the fastest solution (pun intended), but it should get you the desired results. If you're able to alter the subselect to a hit a better index, that would of course help with the execution time.
Update
    f
Set
    f.F_SubItemID = (
        Select Top 1
            sr.SR_ID
        From
            SolutionRevisions sr
        Where
            sr.SR_SolutionID = f.F_ItemID
            And sr.SR_CreatedDateUtc < f.F_CreatedDateUtc
        Order By
            sr.SR_CreatedDateUtc Desc
    )
From
    Feedback f

Comment: Thanks I'll try this out and if it works mark it as correct.
Answer:
My goal is to identify which SolutionRevisions record was the active when a feedback item was created and insert the SR_SolutionID value into F_SubItemID column.

I think you want outer apply:
SELECT sr.SR_ID, f.F_ItemID, sr.SR_CreatedDateUtc, f.F_CreatedDateUtc
FROM Feedback f OUTER APPLY
     (SELECT sr.*
      FROM SolutionRevisions sr
      WHERE f.F_ItemID = sr.SR_SolutionID AND
            f.F_CreatedDateUtc >= sr.SR_CreatedDateUtc
      ORDER BY SR_CreatedDateUtc DESC
     ) sr;

Comment: thank you for the response. Is your answer how I get the nextSRCreatedDate I was trying to get for the where clause or do you think that SQL statement is all I need? When I scope your query to a single SolutionID I get the same number of results that I get from my query when scoped to the same SolutionID. (This should be 17, as there are 17 feedback items, but both return 523 items)
Some clarity with respects to how I'm to implement your answer would be great.
Comment: @JakeofSpades . . . This answers your question.  I'm not sure what your comment is referring to.
Comment: I'll check the results and if so mark it as answered, thank you.


jquery prevent unwanted animation

Question: I have a list of of 10 icons that make up a menu. By default, the first icon will be bigger than the others to show that it is active. When the user hovers over another icon, the first icon will shrink and the other will grow and if they hover out, the first icon will return to its big (active) state again.
The problem is, if you quickly hover the other icons, the first will attempt to grow and thus cause it to look like it's shaking. Is there a way to stop this from happening? Here is a test page I set up: http://recoverstudio.com/icon_menu/
jquery:
 $("#icon_one").width(76).height(76).css({ 'top' : '-15px', 'left' : '-15px'});

 $(".icon").hover(function(){
     $(this).stop().css({'z-index':10}).animate({top: -15, left: -15, height: 76, width: 76}, 75);
     $("#icon_one").stop(true).animate({top: 0, left: 0, height: 45, width: 45}, 75);
    },
 function(){
     $(this).stop().css({'z-index':1}).animate({top: 0, left: 0, height: 45, width: 45}, 75);
     $("#icon_one").stop(true).animate({top: -15, left: -15, height: 76, width: 76}, 75);
    });

css:
img {
    border: 0;
}

ul li {
    float:left;
    list-style:none;
    padding: 0 15px 0 0;
    height: 45px;
    width: 45px;
}

ul li a img {
    display: block;
    height: 45px;
    position: relative;
    width: 45px;
}

html:

Answer: Two suggestions come to mind...
1) eliminate the event gaps between the icons by binding hover() to the containing "li" elements instead of the "img" elements directly. Those 15px of padding between icons might be what's causing your problem.
2) If that doesn't work, perhaps you could add a brief time delay to the first icon re-expanding with setTimeout. That way you'd give yourself some breathing room while switching between icons.
Edit:
It just occurred to me that a more foolproof solution to this problem is to re-expand the first icon only when the cursor leaves the entire menu area. You could do this simply by changing the containing "ul" block to something like

    //your menu icon list

Then you can change your code to look like this:
$("#icon_one").width(76).height(76).css({ 'top' : '-15px', 'left' : '-15px'});

$(".icon").hover(function(){
     $(this).stop().css({'z-index':10}).animate({top: -15, left: -15, height: 76, width: 76}, 75);
     $("#icon_one").stop(true).animate({top: 0, left: 0, height: 45, width: 45}, 75);
    },
 function(){
     $(this).stop().css({'z-index':1}).animate({top: 0, left: 0, height: 45, width: 45}, 75);
    });

$("#menu").mouseleave(function(){
     $("#icon_one").stop(true).animate({top: -15, left: -15, height: 76, width: 76}, 75);
    });

jquery prevent unwanted animation


How could I change my html into a vue component?

Question: I want to view a tiff file in a web page, I can finish it with test.html, but I need to do it in a vue file, how can I do that?
and I can't know what the exact content in the tiff.js[![enter image description here][1]][1]

that's what the script I used.
Comment: Sry, I have edited it again, here is the script and I want to use them in my vue-cli, but I don't know how to use them
Comment: I think you need to read up on vue and go from there. There is a difference between vue and Jquery.
Comment: I don't need the Jquery, I just need the tiff.js.
Answer: You could install tiff.js as a npm library  npm i tiff https://www.npmjs.com/package/tiff
And then import tiff to the App.vue for example, other codes go to mounted(){}.
Instead of Jquery, you could use event on vue template directly, or use javascript to query the element. Using Jquery with Vue is redundant Ithink


How to smoothen a path using D3

Question: This is concerning: Making a SVG path like a smooth line instead of being ragged
So would like to smooth all lines on my map if possible. Finally I have a topojson but I was not able to find anything that can smooth a topojson path.
Here is a solution that smoothes for a geojson at least: http://bl.ocks.org/hugolpz/d53d33af6ffb1366e187
And here is something about a single line: http://www.d3noob.org/2013/01/smoothing-out-lines-in-d3js.html
But I have no clue how to change it. Here is a small jsfiddle example where you can play around: jsfiddle.net/kwoxer/kpL1uyy2/6/
Would be awesome if this would be something like a simple command called smooth =)
Answer: Well since there is no good solution on SVG right now, I just solved it with CSS as best as possible. So this might not be the perfect solution, but at least looking way better then without.
First of all we set the path to be way smoother:
<code>path {
    stroke-linejoin: round;
    stroke-miterlimit: 2;
    stroke-linecap: round;
}
</code>
and now assuming we have an outline drawing we use the following:
<code>#outline path{
    fill: #eee;
    stroke: #eee;
    stroke-width: 0.5px;
}
</code>
This one should look very smooth. It for sure depends on the level of detail of the SVG path itself.

How to smoothen a path using D3


How to display taxonomy term image in a view

Question: I have image field in taxonomy tags. Tags are term referenced in article content type, so now I want to show image field of my taxonomy term in my view. I have tried but I did not find any possible solution.
Answer: For that you can add a relationship in advanced.
Search for your term reference field in it and add the relation.
Then go to fields and search for your image field which is inside of the taxonomy. That way you will be able to add the image.
Comment: You are welcome @Shakil. Happy Learning!!


Multivariate multiple regression in R

Question: I have 2 dependent variables (DVs) each of whose score may be influenced by the set of 7 independent variables (IVs). DVs are continuous, while the set of IVs consists of a mix of continuous and binary coded variables. (In code below continuous variables are written in upper case letters and binary variables in lower case letters.)
The aim of the study is to uncover how these DVs are influenced by IVs variables. I proposed the following multivariate multiple regression (MMR) model:
my.model <- lm(cbind(A, B) ~ c + d + e + f + g + H + I)

To interpret the results I call two statements:

summary(manova(my.model))
Manova(my.model)

Outputs from both calls are pasted below and are significantly different. Can somebody please explain which statement among the two should be picked to properly summarize the results of MMR, and why? Any suggestion would be greatly appreciated.
Output using summary(manova(my.model)) statement:
> summary(manova(my.model))
           Df   Pillai approx F num Df den Df    Pr(>F)
c           1 0.105295   5.8255      2     99  0.004057 **
d           1 0.085131   4.6061      2     99  0.012225 *
e           1 0.007886   0.3935      2     99  0.675773
f           1 0.036121   1.8550      2     99  0.161854
g           1 0.002103   0.1043      2     99  0.901049
H           1 0.228766  14.6828      2     99 2.605e-06 ***
I           1 0.011752   0.5887      2     99  0.556999
Residuals 100
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Output using Manova(my.model) statement:
> library(car)
> Manova(my.model)

Type II MANOVA Tests: Pillai test statistic
  Df test stat approx F num Df den Df    Pr(>F)
c  1  0.030928   1.5798      2     99   0.21117
d  1  0.079422   4.2706      2     99   0.01663 *
e  1  0.003067   0.1523      2     99   0.85893
f  1  0.029812   1.5210      2     99   0.22355
g  1  0.004331   0.2153      2     99   0.80668
H  1  0.229303  14.7276      2     99 2.516e-06 ***
I  1  0.011752   0.5887      2     99   0.55700
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Answer: Briefly stated, this is because base-R's manova(lm()) uses sequential model comparisons for so-called Type I sum of squares, whereas car's Manova() by default uses model comparisons for Type II sum of squares.
I assume you're familiar with the model-comparison approach to ANOVA or regression analysis. This approach defines these tests by comparing a restricted model (corresponding to a null hypothesis) to an unrestricted model (corresponding to the alternative hypothesis). If you're not familiar with this idea, I recommend Maxwell & Delaney's excellent "Designing experiments and analyzing data" (2004).
For type I SS, the restricted model in a regression analysis for your first predictor c is the null-model which only uses the absolute term: lm(Y ~ 1), where Y in your case would be the multivariate DV defined by cbind(A, B). The unrestricted model then adds predictor c, i.e. lm(Y ~ c + 1).
For type II SS, the unrestricted model in a regression analysis for your first predictor c is the full model which includes all predictors except for their interactions, i.e., lm(Y ~ c + d + e + f + g + H + I). The restricted model removes predictor c from the unrestricted model, i.e., lm(Y ~ d + e + f + g + H + I).
Since both functions rely on different model comparisons, they lead to different results. The question which one is preferable is hard to answer - it really depends on your hypotheses.
What follows assumes you're familiar with how multivariate test statistics like the Pillai-Bartlett Trace are calculated based on the null-model, the full model, and the pair of restricted-unrestricted models. For brevity, I only consider predictors c and H, and only test for c.
N <- 100                             # generate some data: number of subjects
c <- rbinom(N, 1, 0.2)               # dichotomous predictor c
H <- rnorm(N, -10, 2)                # metric predictor H
A <- -1.4*c + 0.6*H + rnorm(N, 0, 3) # DV A
B <-  1.4*c - 0.6*H + rnorm(N, 0, 3) # DV B
Y <- cbind(A, B)                     # DV matrix
my.model <- lm(Y ~ c + H)            # the multivariate model
summary(manova(my.model))            # from base-R: SS type I
#           Df  Pillai approx F num Df den Df  Pr(>F)
# c          1 0.06835   3.5213      2     96 0.03344 *
# H          1 0.32664  23.2842      2     96 5.7e-09 ***
# Residuals 97

For comparison, the result from car's Manova() function using SS type II.
library(car)                           # for Manova()
Manova(my.model, type="II")
# Type II MANOVA Tests: Pillai test statistic
#   Df test stat approx F num Df den Df  Pr(>F)
# c  1   0.05904   3.0119      2     96 0.05387 .
# H  1   0.32664  23.2842      2     96 5.7e-09 ***

Now manually verify both results. Build the design matrix $X$ first and compare to R's design matrix.
X  <- cbind(1, c, H)
XR <- model.matrix(~ c + H)
all.equal(X, XR, check.attributes=FALSE)
# [1] TRUE

Now define the orthogonal projection for the full model ($P_{f} = X (X'X)^{-1} X'$, using all predictors). This gives us the matrix $W = Y' (I-P_{f}) Y$.
Pf  <- X %*% solve(t(X) %*% X) %*% t(X)
Id  <- diag(N)
WW  <- t(Y) %*% (Id - Pf) %*% Y

Restricted and unrestricted models for SS type I plus their projections $P_{rI}$ and $P_{uI}$, leading to matrix $B_{I} = Y' (P_{uI} - P_{PrI}) Y$.
XrI <- X[ , 1]
PrI <- XrI %*% solve(t(XrI) %*% XrI) %*% t(XrI)
XuI <- X[ , c(1, 2)]
PuI <- XuI %*% solve(t(XuI) %*% XuI) %*% t(XuI)
Bi  <- t(Y) %*% (PuI - PrI) %*% Y

Restricted and unrestricted models for SS type II plus their projections $P_{rI}$ and $P_{uII}$, leading to matrix $B_{II} = Y' (P_{uII} - P_{PrII}) Y$.
XrII <- X[ , -2]
PrII <- XrII %*% solve(t(XrII) %*% XrII) %*% t(XrII)
PuII <- Pf
Bii  <- t(Y) %*% (PuII - PrII) %*% Y

Pillai-Bartlett trace for both types of SS: trace of $(B + W)^{-1} B$.
(PBTi  <- sum(diag(solve(Bi  + WW) %*% Bi)))   # SS type I
# [1] 0.0683467

(PBTii <- sum(diag(solve(Bii + WW) %*% Bii)))  # SS type II
# [1] 0.05904288

Note that the calculations for the orthogonal projections mimic the mathematical formula, but are a bad idea numerically. One should really use QR-decompositions or SVD in combination with crossprod() instead.
Comment: My very big +1 for this nicely illustrated response.
Comment: I wonder that though using `lm` function I am conducting multivariate regression only by specifying more than one respose variable inside the `lm` function. I have learnt that by using `lm` function when my data is actually multivariate give erroneous result for standard error. But in this case `my.model <- lm(cbind(A, B) ~ c + d + e + f + g + H + I);`  will `vcov(my.model )` underestimate the standard error or `lm` will intelligently  adjust the correlation between the dependent variables ?
Answer: Well, I still don't have enough points to comment on previous answer and thats why I am writing it as a separate answer, so please pardon me. (If possible please push me over the 50 rep points ;)
So here are the 2cents:
Type I , II and III errors testing are essentially variations due to data being unbalanced. (Defn Unbalanced: Not having equal number of observations in each of the strata). If the data is balanced Type I , II and III error testing gives exact same results.
So what happens when the data is imbalanced?
Consider a model that includes two factors A and B; there are therefore two main effects, and an interaction, AB.
SS(A, B, AB) indicates full model
SS(A, B) indicates the model with no interaction.
SS(B, AB) indicates the model that does not account for effects from factor A, and so on.
This notation now makes sense. Just keep it in mind.
SS(AB | A, B) = SS(A, B, AB) - SS(A, B)

SS(A | B, AB) = SS(A, B, AB) - SS(B, AB)

SS(B | A, AB) = SS(A, B, AB) - SS(A, AB)

SS(A | B)     = SS(A, B) - SS(B)

SS(B | A)     = SS(A, B) - SS(A)

Type I, also called "sequential" sum of squares:
1) SS(A) for factor A.
2) SS(B | A) for factor B.
3) SS(AB | B, A) for interaction AB.
So we estimate main effect of A first them, effect of B given A, and then estimate interaction AB given A and B
(This is where being imbalanced data, the differences kick in. As we estimate main effect first and then main of other and then interaction in a "sequence")
Type II:
1) SS(A | B) for factor A.
2) SS(B | A) for factor B.
Type II tests significance of main effect of A after B and B after A.
Why is there no SS(AB | B, A) ? Caveat  is that type II method can be used only when we have already tested for interaction to be insignificant.
Given that there is no interaction (SS(AB | B, A) is insignificant) type II test has better power over type III
Type III:
1) SS(A | B, AB) for factor A.
2) SS(B | A, AB) for factor B.
So we tested for interaction during type II and interaction was significant. Now we need to use type III as it takes into account the interaction term.
As @caracal has said already,
When data is balanced, the factors are orthogonal, and types I, II and III all give the same results. I hope this helps !
Disclosure: Most of it is not my own work. I found this excellent page linked
 and felt like boiling it down further to make it simpler.

Multivariate multiple regression in R


How does Word2Vec ensure that antonyms will be far apart in the vector space

Question: Broadly speaking the training of word2vec is a process in which words that are often in the same context are clustered together in the vector space. We start by randomly shuffling the words on the plane and then with each iteration more and more clusters form. I think I understood this but how can we assure that the words that are antonyms or rarely appear in the same context don't end up in clusters that are close by? Also how can we know that words that are more irrelevant are farther away than word that are less irrelevant.
Comment: there is no such guarantee that antonyms are far apart etc
Comment: Cold today and warming tomorrow. Antonyms are often including in comparative statements because classifications occur on axes, good/bad polite/rude smart/dumb high/low and so forth.
Answer: There is no guarantee that antonyms will be far apart -- it's just one of the "nice" properties that falls out as a result of the procedure. The main premise of word2vec is called the "distributional hypothesis" -- related things will tend to appear together (and, implicitly, that unrelated things do not appear together). If that hypothesis is valid for your data, then you'll find that word2vec works well. Otherwise, you'll have to try something else.
One case where antonyms will appear in context together is in a sentence contrasting two alternatives. Carl provides a nice example in his comment: "Cold today and warm tomorrow." With respect to temperature, "cold" and "warm" are opposites. With respect to time, "today" and "tomorrow" are also opposite. Yet in this sentence, both pairs appear nearby.


How to Show that this relation is not well defined.

Question: We represent an element of the domain as an equivalence class $\bar x$, and use the notation $ \left[ x \right]$ for equivalence classes in the codomain. Show that this is not well defined.

$ f: \Bbb Z_{4}  \rightarrow \Bbb Z_{6} \; \text{ given by, } f(\bar x) = \left[ 2x+1\right]$

My question is how do does one determine/ show that this is not a function? How does one show that this not one to one?
$f(\bar 0) =  2(0) +1 = [1]$
$f(\bar 1) = [3]$
$f(\bar 2) = [5]$
$f(\bar 3) = [7]$
$f(\bar 4) = [9]$
$f(\bar 5) = [11]$
$f(\bar 6) = [13]$
I also guessing here that if a number is a multiple of another then that may play a role in determining it if is one-one.
Comment: In your example $\overline 0= \overline 4$ and $[9] = [3] \ne [1]$.  So we have $[1] = f(\overline 0) = f(\overline 4) = [9] = [3] \ne [1]$.  This is a contradiction so f is not well-defined.
Comment: The theory behind this question is similar to that one. But the question itself is different. I did not know that this would merit a deletion.......
Comment: If you finish listing those out $f(\overline 4) = f(\overline 0); f(\overline 5) = f(\overline 1); etc.$ and you also have $[7] = [1]; [9]=[3]; [11]=[5]; [13] =[1]$.  Putting those together we get the incompatible results: $f(\overline 0) = [1]=f{\overline 4} = [9] = [3]=f{\overline 1} = f{\overline 5} = [11]=[5]=f{\overline 2} = ...$ which is utterly contradictory.  This definition doesn't work.
Answer: $$ f(\overline{7}) = [15] = [3].$$
But
$$ f(\overline{3}) = [7] = [1].$$
Since $\overline{7} = \overline{3}$, this is not well-defined.
Comment: $\overline 7 = \overline 3$ because $7 - 3 = 1*4$.  What isn't mentioned is $[1] \ne [3]$ because there is not integer $a$ so that $3 - 1 = 6*a$.  So we have $f(\overline 7)$ equalling two different unequal things.
Comment: The definition of $[x] \in \mathbb Z_6$ is that $[x] = \{a| x - a = n*6 $ for some $n \}$.
Comment: The last line do you mean that $\bar 7 \not = \bar 3$ ? Since they are not multiples of each other?
Comment: where did you come up with $3-1 = 6 *a$, where did you derive 6? Could you not say $3-1 = 2*1$?
Comment: Or if you prefer $[x] = x, x+ 6, x+ 12,....$  so $[1] = 1, 7, 13,....$ and $[3] = 3,6,12,...$.  These are not the same.  So $[1] \ne [3]$.
Comment: To paraphrase mcmathsadist's post.  $\overline 7 = 3,7,11,15...$ and $ f(\overline 7)=[2*7+1] = [15] = 3,6,15,21,...=[3]$.  But $\overline 7 = 3,7,11,15... = \overline 3$  and $f(\overline 3) = [2*3 + 1] = [7] = 1,7,13,19,25...$.  But $[3] = 3,6,15,21 ... \ne 1, 7,13, 19,25....=[1]$.  So this is not well defined because we can interpret $f(\overline 7) $ in two different incompatible ways.
Answer: If we want to get technical.
$\overline 0 = \{a \in \mathbb Z|\exists n \in \mathbb Z: 0 - a = n*4 \}=\{...,-8,-4,0,4,8,12,....\}$
$0 \in \overline 0$ so
$f(\overline 0) = [2*0 + 1] = [1] = \{a \in \mathbb Z|\exists n \in \mathbb Z: 1 - a = n*6 \}=\{..., -5,1,7,13,....\}$
But $0 - 4 = 0-1*4$ so $4 \in \overline 0$.
So $f(\overline 0) = [2*4 + 1] = [9] = \{a \in \mathbb Z|\exists n \in \mathbb A: 9 - a = n*6\} = \{a \in \mathbb Z|\exists n \in \mathbb A: 3 - a = n*6\}=[3]=\{....-9, -3,3,9,15...\}$.
But $[3] = \{a \in \mathbb Z|\exists n \in \mathbb A: 3 - a = n*6\}=\{....-9, -3,3,9,15...\}\ne \{a \in \mathbb Z|\exists n \in \mathbb Z: 1 - a = n*6 \}=[1]=\{..., -5,1,7,13,....\}$
So we have define $f$ in such a way that $f(\overline 0)$ can be interpretted to  have at least two incompatible values.  Thus $f$ is not well-defined.
=====
If "$\overline 0 = \{a \in \mathbb Z|\exists n \in \mathbb Z: 0 - a = n*4 \}$" is too complicated looking, we can alternatively say $\overline 0$ is the class = {all multiples of 4} and $\overline x $ is the class = {all integers that are $x$ plus or minus a multiple of 4}.  Those definitions are exactly the same.
So $[y]$ is {all integers that are y plus or minus a multiple of 6}
So $f(\overline x) = [2x + 1]$ means "take the set of numbers that are $x$ plus or minus a multiple of 4-- and return that set of all numbers that are $2x + 1$ plus or minus a multiple of 6".
That statement is "not well-defined" because if we take different numbers that are $x$ plus or minus a multiple of 4 (example if we took $x-4$ instead of $x$) we'd get different sets.
Example: if we took $1$ we'd get the set "all numbers that are $3$ ($3= 2*1 + 1$) plus or minus a multiple of $6$"  but if we took $5$ (which is $1$ plus or minus a multiple of $4$) we'd get the set "all numbers that are $11$ ($11 = 2*5 + 1$) plus or minus a multiple of $6$".  That's a different set.
Comment: What is $n$ and $a$ for $\overline 0 = \{a \in \mathbb Z|\exists n \in \mathbb Z: 0 - a = n*4 \}$. What would be filled in for these?
Comment: I think this is a bit "too technical" for what the OP needs (as in, I don't think the OP is ready for a plate full of symbols). @LittleJon, you seem to be having the most issues with modular arithmetic (i.e., what $\bar a = \bar b$ means here; to be congruent modulo $4$). Perhaps you should backtrack and just spend some time strengthening your understanding of congruence/modular arithmetic.
Comment: n can be any integer at all. and a can be any multiple of 4.  $\overline x=$ every number that is $x$ plus a multiple of 4.  n and a do not have any single one value.  $\overline x$ = the set of all numbers, $a$, where $a - x$ is a multiple of 4.
Comment: Perhaps. I'm hoping the list of numbers help.  $\overline 0 = ....,-8,-4,0,4,8,12......$ and $\overline x = ..... x - 8, x-4, x, x+4 , x+ 8....$ is clear, I hope.  So defining $f(\overline x) = g(x)$ is usually (but not always) not well-defined because it isn't specified *which* x we should use.  We could use x-4, we could use x, or we could use x + 4,896.  In this case those give different results.  [2x + 1] is different from [2(x + 4) + 1] is different from [2(x + 4,896) + 1].


ZTE Open with Firefox OS as WiFi hotspot

Question: I would like to use this Firefox OS device as WiFi hotspot (with a Mac).
I have noticed some slowness. Does anyone know if that might be due to the WiFi receiver/emitter in the ZTE Open being a low quality component?
Is there any software (Mac preferred) that might enable me to tell where does the low performance come from (connection to the network -speed/latency-, wifi hotspot data exchange)?
Answer: Interesting question. One thing you could test on the device itself with JavaScript, is the connection speed and if it's metered. Hardware could potentially come into play here as well.
Comment: Thanks for the link to the code (and quick answer). I have had a look and perhaps that will help. Is there specific documentation for the code? I am not familiar at all with this (FxOS?) API. Do you think the wifi hotspot connection is going to be tested?
Comment: There is some [basic documentation on MDN](https://developer.mozilla.org/en-US/docs/WebAPI/Network_Information). I'm not sure about the hotspot, to be honest. Please test and see if it works for you!


Portmanteau lemma: Prove that 4 implies 2

Question: If lim inf $E[f(X_n)] \geq E[f(X)]$ for any non-negative, continuous function $f(.)$ then $E[g(X_n)]=E[g(X)]$ for all bounded, continuous functions $g(.)$., where $X_n$ define a sequence of bounded probability measures.
The question talks about the version in Asymptotic Statistics in A.W. van der Vaart. I know how to go from 1 to 4 that is prove lim inf $E[f(X_n)] \geq E[f(X)]$ for any non-negative, continuous function $f(.)$ if we have weak convergence using Fatou's Lemma. I am unsure how to show any of the other statements if 4 holds.
Comment: You don't seem to have written a question we can answer.  You told us where to find it, but that's not much use :)
Comment: I have doubts about the fact that $X_n$ is a probability measure, or if it is then I don't know what $E[f(X_n)]$ is (my guess would have been expectation and then $X_n$ is a random variable with some probability measure right ?).
Comment: @P.Quinton yes as I wrote it defines a probability, the Lesbegue Stieltjes measure
Answer: Let $f$ be any bounded continuous function and $M$ be its supremum. Then $M-f$ is a non-negative continous function so $\lim \inf E(M-f(X_n)) \geq E(M-f(X))$. Cancelling $M$ we get $\lim \sup Ef(X_n) \leq Ef(X)$. Changing $f$ to $-f$ we get $\lim \inf Ef(X_n) \geq Ef(X)$. Hence $\lim Ef(X_n)=Ef(X)$.


Why doesn't clock.tick() measure time accurately in Pygame?

Question: I've created a simple game in Pygame that displays an image of a certain emotion for x amount of time, before giving participants the opportunity to select which emotion was displayed by pressing a button. However, I'm having trouble maintaining the display time for images. I use clock.tick() to get a value for delta time, but it seems that it's 3x slower than it should be. If I set the timer to 1000ms, for example, the image is displayed for ~3 seconds, whereas I only want it to display for 1 second. I can always divide the display time by 3 to get it roughly correct, but I want to understand what's causing this.
Here's the main game loop:
def mainGame(images):
dt = 0    #delta time is set to 0 to begin
timer = displayTime #displayTime by default is 1000ms
imageNumber = 0
gameState = States.VIEWING    #this is the game state where a participant views a question
running = True
while running:
    mouse = pygame.mouse.get_pos()
    screen.fill((255, 255, 255))
    mainDisplay()             #this displays the answer buttons
    clock = pygame.time.Clock()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    if ( gameState == States.VIEWING):
        dt = clock.tick_busy_loop(30)   #should increase delta time by however many ms have passed
        timer -= dt                     #minus delta time from the timer
        if timer >= 0:                  #if the timer remains above 0, continue displaying image
            askQuestion(images, imageNumber)
        else:                           #when timer reaches 0, stop displaying image and move to answering state
            gameState = States.ANSWERING

    elif (gameState == States.ANSWERING):     #this is where participants select their answer
        timer = displayTime                   #reset the timer
        screen.fill((255, 255, 255))
        mainDisplay()                         #displays answer buttons
        for emotion, rects in rectDict.items(): #this detects whether a button has been clicked or not
            if event.type == pygame.MOUSEBUTTONDOWN:
                if rects.collidepoint(mouse):            #if a button is clicked
                    gameState = States.VIEWING           #switch back to viewing state
                    answers.append(emotion)                 #add answer to answer list
                    imageNumber += 1                    #move to the next image
                elif not any(rect.collidepoint(mouse) for rect in rectList):   #if a button is not clicked
                    print("You did not select an answer")
                    break

    if practice == True:   #if in practice mood, stop when number of practice questions is reached
        if len(answers) == pnumberofQuestions:
            break
    elif practice == False: #if in main game loop, stop when number of questions is reached
        if len(answers) == numberofQuestions:
            break

    pygame.display.update()

Answer: You are creating a new clock each pass through the while loop.
Move
    clock = pygame.time.Clock()

out of your
while running:

and put it somewhere above it.
Comment: Thank you @Glenn Mackintosh - I moved clock = pygame.time.Clock() above the while running statement. It seems to be working for the first image blit in terms of timing, but then subsequent image blits don't seem to be showing up following that.
If I print(timer) every frame to try and troubleshoot, the timer reduces as expected from 1000 to 0 for the first blit, but then when I click on an answer the timer value changes to something like -1000, whereas before it would reset back to 1000 every time.

This occurs after I move clock = ... to above the while loop with no other changes.
Comment: Never mind - I think I solved it! The issue was, clock.tick() returns the number of ms since it was last called. Because clock.tick() was only being called during the VIEWING state, when I went to the ANSWERING state and took some time to answer the question, clock.tick() would return the number of ms I took to answer after I moved back to the VIEWING state and clock.tick() was called again.

To solve it, I moved dt = clock.tick() to underneath "while running:", ensuring that clock.tick() is being called every frame, not just in the viewing state.

Thanks again for your help!


Show that $\lim_{a\rightarrow0+}a^{p}\omega(a)=0$ whenever $f\in L^{p}(E)$

Question: Show that $\lim_{a\rightarrow0+}a^{p}\omega(a)=0$ whenever $f\in L^{p}(E)$
,where $p\in(0,\infty)$ and $E$ is a subset of $\mathbb{R^{n}}$ it can be finite measure or not and $\omega(\alpha)=\bigg|\{x\in E :f(x)>\alpha\}\bigg|$
Here is my edited proof :
As $f\in L^{p}(E)$ we have $|f|\in L^{p}$ and $|f|$ is non-negative on $E$, then one has the following formula :
$$\bigg\lVert |f|\bigg\rVert_{L^{p,\infty}}^{p}=p\int_{0}^{\infty}\alpha^{p-1}\omega(\alpha)\,d\alpha<+\infty$$
So,for each $a>0$
\begin{align}
0\leq a^p\omega(a)=p\int_{0}^{a}t^{p-1}\omega(a)\,dt\leq p\int_{0}^{a}t^{p-1}\omega(t)\,dt
\end{align}
Then as $a\longrightarrow0+$,one has $$p\int_{0}^{a}t^{p-1}\omega(t)\,dt\longrightarrow0$$
,since $$p\int_{0}^{\infty}\alpha^{p-1}\omega(\alpha)\,d\alpha<+\infty$$
Whence,our result follows.
Is there any problem about my working ? Any suggestions and remind would be appreciated.Thank you for the time to check my proof.
Answer: The very first line does not hold: The contra-proposition of negative a.e. is not positive a.e.
Rather, you don't have to consider the positiveness of $f$, because we have the nice formula that
\begin{align*}
\|f\|_{L^{p}}^{p}=p\int_{0}^{\infty}t^{p-1}\omega(t)dt<\infty.
\end{align*}
Note that
\begin{align*}
\|f\|_{L^{p}}^{p}=\int_{E}|f|^{p}d\mu=\big\||f|\big\|_{L^{p}}^{p},
\end{align*}
the positiveness of $f$ does not play any role in the proof. And the way to derive the nice formula, the positiveness of the function is not taken into account.


Is there a known point in history where dissonance became acceptable?

Question: So, I'm not a scholar of music history, but I have a basic timeline. The evolution of Western music theory had several times in which certain chords and intervals were considered too "jarring" or "dissonant", but eventually became acceptable as composers found ways to make it work. Obviously, music evolves.
My question is, was there a specific impetus that pushed the role of dissonance out of the jarring mechanism it's normally used as, to simply adding complexity and an "unfinished" quality to chords and phrases? In short, what propelled music from this:
Sergey Rachmaninoff - Bogoroditse Djevo (1915)
... where the chord structure, though complex, stays pretty consonant, to this...
Samuel Barber - Agnus Dei (Adagio for Strings) (1938)
... where the chord progressions introduce and then resolve quite a bit of dissonance through the phrases, to this:
John Tavener - The Lamb (1982)
... where the majority of the piece is atonal, and intervals we don't normally hear figure prominently, to this...
Eric Whitacre - Water Night (1994)
... where at one point the choir builds to a 19-note "cluster chord", containing every pitch in the key through two and a half octaves (and that's not the most "dissonant" part of the piece by far).
There seems to have been a BIG change in the way we think about dissonance between WWII and the roughly present-day. Even in mosuc with an established key and using pretty standard progressions, the movement of voices to create major and minor second dissonances is now often relished instead of glossed over. Example: "Lully, Lulla, Lullay"; It's very tonally-centered, firmly in the minor key, but has dissonant movement all through it. It would be stereotypical to say that the impetus was the change in all kinds of thinking during the 60's, but that may well be the case; the influence of other genres and of environmentalist thought were certainly present in classical music during that time, as evidenced by the mere existence of a classical piece titled "The Second Dream of the High-Tension Line Stepdown Transformer". I don't have too many notable examples of classical music from that era, certainly not a capella choral to fit the rest of the selections. Does anyone have more information than I to back up this hypothesis?
Comment: Don't forget Carlo Gesualdo (1566 – 1613) http://www.bbc.co.uk/programmes/p01w3rp4
Comment: the whole history of music theory is just like: "oh, you should JUST do this and that!" and then some genius arrives and says "but what if I try this? I know it sounds awful to your ears... Here, let me write it in a way that sounds more logical to you". And, hence, something which first was unacceptable becomes the rule. From Palestrina, to Bach, to Debussy, to Charlie Parker, this is pretty much the history of all music. No, there's no "point" in which something becomes acceptable as there's no such thing as a "dissonance". Can you define what's ugliness or beauty?
Comment: To the OP you may find this thread interesting. http://music.stackexchange.com/questions/34253/proper-understanding-of-dissonance
Comment: I find this question quite difficult, since *dissonance* has anything but a fixed meaning over the centuries. It was always there, and even with  todays criteria pieces of Zelenka (1679-1745) and Schubert (1797-1828) use harmonies and key transitions may cobe considered as  *adventurous*.
Answer: Beethoven, throughout his lifetime, created music that pushed the limits of tonality.  In the classical period there were "rules" for how far you could push these limits, governed by contrapuntal techniques that evolved from the 16th century.
In Beethoven's later works you begin to hear more and more dissonance.  Musically speaking, it is agreed by most music history scholars that Beethoven ushered in the Romantic period.  As music progressed, different composers pushed the bounds of consonance vs dissonance with modulations, alternative scales, and even atonality; as well as questioning and expanding everything about music (instrumentation, rhythmic complexity, notation, etc.)
As Beethoven paved the way for Romantic period composers to become more independent of the "rules" of the past, so Wagner did for 20th century composers.  This is not to say that Wagner is the only composer that affected the change, but he had one of the most far reaching impacts on future composers.
The concept of sustained dissonance was brought to its peak by Arnold Schoenberg and his concept of atonal, or pantonal, composition.  However, all musical evolution is just that:  evolution.  The process of musical change is not usually sudden.
Is there a point in history where dissonance became acceptable?  There is not really a specific date.  Schoenberg didn't even start out writing atonal music; his early style is very romantic sounding.  He was a revolutionary and he did greatly affect the musical culture around him in the early 1900's.  It took people time, however, to accept his theories.  This could explain why you hear a change in the mid-1900's.
I hope all this info helps.
Edit: As far as the specific pieces you pointed out, here are some comments about the progression of the musical styles they represent:

Rachmaninoff represents a lush romantic sound
Samuel Barber moves further into a 20th century style, with a great deal of sustained, but at some point resolved, dissonances
The Lamb is not atonal, but does sound tonally ambiguous because of its use of accidentals;
Then to Water Night, where Whitacre uses a technique call pandiatonicism (using all of the notes in the scale in clusters) but staying in the key or in related keys.  His concept of sustained dissonance without resolution gives a very powerful innovative sound.
Comment: You know the famous joke about the tonal experiments and the deafness of Beethoven, right? :P
Answer: I find the Tavener and Whitacre to be very consonant-sounding and beautiful.  On the other hand, the parallel fifths and fourths of Medieval organum sound unpleasant and jarring to me, although they probably sounded melodious and sweet to the original performers.
I see two ways of interpreting your question.

When did the use of dissonance change from shocking and jarring to peaceful and resolved?

This has never happened, in that whatever is shocking and jarring to a particular person's ears is "dissonant", and whatever is peaceful and resolved is "consonant".

When did such-and-such a dissonance become a consonance?

It happens all the time.  Between the Medieval and Baroque eras, parallel fifths changed from consonance to dissonance -- a single open fifth is not dissonant, but a series of them sounds weird and wrong.  At the same time, the major third became a consonance.
I think maybe the specific answer to your question "when did early 20th-century dissonances become consonances" is "when whichever piece of classical music first used an added-sixth chord as an ending."  For instance, C-E-G-A-C in C major.  This turned up in jazz and classical music, in Ravel and Bix Beiderbecke for instance.  I don't know which of the two was first; Ravel was a jazz fan and Bix was a Ravel fan.  It appears in Debussy's "Gollywog's Cakewalk" although not in the real cakewalks that influenced Debussy.  Maybe it appears in Faure or Wagner; I don't know, I'll have to listen carefully for it.  You certainly hear it all the time in jazz from the 1920's on.  (We don't know much about the chords used in jazz in its first two decades, from the 1890's until it was first recorded around 1917.)  Messiaen makes very frequent use of this chord.  Maybe that's what made Pierre Boulez think Messiaen's music is "brothel music".
Milhaud's "Creation du Monde" was influenced by jazz, and the very last chord adds the leading tone (i.e. B in a C major chord).  It's just amazingly beautiful, and if the melody line went G-A-B-C instead of G-A-Bflat-B it would be pleasant but uninteresting.
(Edit:  I suddenly realized that the ending of "Creation du Monde" comes almost directly from the cliched barber-shop "Good Evening Friends" ending!  (Added-6th:  C-E-G-A.  Good Evening Friends:  C-E-G-Bflat. Milhaud:  C-E-G-B.) So if you can find the first use of "Good Evening Friends", you've got an answer.)
Answer: Quite honestly, dissonance has been acceptable for as long as there have been non-octave harmonies. This may seem silly, but let's first define dissonance- any 2 or more notes whose overtones (http://en.wikipedia.org/wiki/Harmonic_series_(music)) do not match up. This means any pair of non-octave, non-unison notes (non-octave and a fifth, non-2-octaves and a third, etc) could be considered dissonant. This is partially why the earliest plainchant (also known as Gregorian Chant) is mainly all sung in unison. The matching of the overtones creates a strong, resonant sound. When overtones do not match (like in the case of a major third), the resonance is somewhat diminished, but they create a pleasing (or crunching, in the case of the minor second) sound as the notes and their overtones vibrate at different rates. Having the extra overtones creates a fullness of sound, which is why chords are so supportive.
But I Digress.
In terms of specific intervals, the definition of dissonance has changed greatly throughout the history of music. For now, I can only speak of Western music since the Renaissance. During the Renaissance, perfect fourths were considered incredibly dissonant and were not used in much of the music written during that era. Now, a perfect fourth is thought of as one of the most stable consonants. The preferred intervals of harmony are determined by what you are used to. An excellent example of this is Charles Ives (I can't post more than 2 links, so put this on the end of the wikipedia url: wiki/Charles_Ives), whose father made him sing songs in one key while playing the accompaniment in a completely different key. As a result, Charles Ives wrote what we would call extremely dissonant music (

).
TL;DR
Here's what happens:
A generation (G1) has a type of harmony they like and are used to. Their children (G2) grow up hearing this, and it is the foundation of 'what music is' to them. They grow up, and a few members test and strain the boundaries of what could be considered 'new' and still 'musical.' There is push back from G1. G2 enjoys the music, and their children, G3, grow up with that as the foundation of 'what music is.' This is how Perfect Fourths went from a dissonance in the Renaissance to a consonance in the Baroque.
You, however, are probably wondering why dissonance is so widely used as a compositional tool for today's modern compositions. Well, we can blame that on the 2nd Viennese School of music (wiki/Second_Viennese_School) and thesubsequent Avant Guarde and Experiment music movements (wiki/Avant-garde_music and wiki/Experimental_music respectively).
These people wanted to create sounds that had never been made before. They succeeded, but in my opinion, they also are the main reason orchestral/non-pop music became so unpopular.
Comment: I wish I could upvote this twice. To claim that "dissonance" was not a part of ancient music would only show ignorance of ancient music. What is "dissonant" is largely cultural, and has changed through time, but music that is entirely consonant within a culture at a certain time is by that very fact boring.
Answer: As the other answers suggest, there's no simple way to answer this question, because what counts as "dissonance" has changed through time, as has the use or avoidance of what people considered dissonant.  I'll just add that there is lots of medieval music that has what most modern listeners would call dissonance.  For example, check out Viderunt Omnes by Pérotin, from around 1200- lots of seconds, even on strong beats, for instance at 1:28:
Comment: Holy melismas, Batman! +1 for going back to early music. Dissonance has always been acceptable (in some form). Not to mention that in much of early music (before the Renaissance), thirds were also considered dissonance.
Comment: Indeed, although thirds were used fairly early on in lots of medieval English music (gymels) and also in Alpine regions (for instance, Mönch von Salzburg).  I wonder how much of the classification of thirds as being dissonant was more of a theoretical stance than a musical practice.  But I guess we'll never know for sure.
Comment: "I wonder how much of the classification of thirds as being dissonant was more of a theoretical stance than a musical practice": with pipe organs in Pythagorean tuning it would have been very much a practical acoustical dissonance.  But it's hard to imagine that singers didn't slip into just third and sixths given the chance.
Comment: @phoog yep. Singing Pythagorean thirds is pretty gnarly.
Answer: I'm also not a scholar on music history, but I think dissonance started to be taken into account with the continuous modulation Wagner used in his compositions.
He is often seen as the father of chromaticism.
After Wagner, we have Debussy. He created a brand new scale, the hexatonic scale (C D E F# G# A#)
where the fundamental C chord (C E G) became a "strange" C chord, C E G#.
Thus, continuing the destruction of the tonal system, started by Wagner.
We can go on and on, one of my favourites is Béla Bartók, his works are completely out of the tonal system. He studied ancient folk songs, which were composed with no knowledge on music theory and where dissonance was peacefully present.
In "Water Night", from Whitacre, there is no key, thus making it perfectly understandable he keeps building from the fifth chord, goes to a seventh, a ninth, and so on.
Long story short: Wagner started to make dissonance acceptable.
EDIT: When I say "dissonance started to be taken into account" I mean when dissonance started to be studied, not only used to create simple tensions and simple modulations.
A whole new music school derived from that study.
Comment: @jadarnel27 To be honest here, I never seen the sheet for "Water Night", I had just listened to it. I'll take a close look at the score later and reply again.
If it actually have a key, than it's very interesting example! Thanks for pointing out.
Comment: Nitpick: "Water Night" does have a key - it's in 6 flats (`G♭` or `E♭m`) according to my copy of the sheet music =)
Comment: @jadarnel27 Having a Key signature does not mean it actually have a key.
The key signature can be used to simplify the writing.
Comment: I completely agree on that point.  I don't actually feel that it applies to "Water Night" - but I will quit nit-picking now!  Interesting perspective on this question regardless.
Answer: There are degrees of dissonance, and over the course of music history, musical compositions became more tolerant of increasing degrees of dissonance and using more acute dissonance more often. It is a continuum. There was not an identifiable point at which any of this changed.
Answer: I'm a professional jazz-classical pianist and author.
Sometimes when you try to describe something "dissonance" would give you hard time. Because it's important to know what is before and after the intervals/the chord we are trying to describe.
Dissonance didn't get acceptable with some composers for sure. It was always with us. We try to name it. There is a sentence says "Art imitates the nature. Even a very simple thing might need big complexity to be able imitate in nature." Arnold Schoenberg creator of Atonal music.
If you are talking about only some intervals which was used in great pieces - which would make us accept it - You must check J.S. Bach compositions. There are many many dissonance sounds in excellent beauty.
On the other hand if you are talking about conceptional attitudes in harmonic movements you might want to check Stravinsky.


Write the Maclaurin series for function $f\left(x\right)=\frac{1}{3x+1}\:$

Question: We have function $f:\mathbb{R}\rightarrow \mathbb{R}$ with $$f\left(x\right)=\frac{1}{3x+1}\:$$ $$x\in \left(-\frac{1}{3},\infty \right)$$
Write the Maclaurin series for this function.
Alright so from what I learned in class, the Maclaurin series is basically the Taylor series for when we have $x_o=0$ and we write the remainder in the Lagrange form. It has this shape:
$f\left(x\right)=\left(T_n;of\right)\left(x\right)+\left(R^Ln;of\right)\left(x\right)=\sum _{k=0}^n\left(\frac{f^{\left(k\right)}\left(0\right)}{k!}x^n+\frac{f^{\left(n+1\right)}\left(c\right)}{\left(n+1\right)!}x^{n+1}\right)$
So when I compute derivatives of my function I can see that the form they take is:$$f^{\left(n\right)}\left(x\right)=\left(-1\right)^n\cdot \frac{3^n\cdot n!}{n!}x^n$$
Does that mean that the Maclaurin series is basically: $$f\left(x\right)=1-3x+3^2x^2-3^3x^3+....+\left(-1\right)^n\cdot 3^n\cdot x^n$$
?
But what about that remainder in Lagrange form? I don't get that part. We didn't really have examples in class, so I've no idea if what I'm doing is correct. Can someone help me with this a bit?
Answer: Hint: Remember that
$$\frac{1}{1 + x} = \sum_{n=0}^{\infty} (-1)^n x^n \,\,\,\, \text{for} \,\,\,\ |x| <1$$
Then $$\frac{1}{1  +3x} = \ldots$$
for $|3x| < 1 \implies |x| < \frac{1}{3}$
Comment: Wouldn't that just be $\frac{1}{1+3x}=\sum _{n=0}^{\infty }\left(-1\right)^n\cdot \:3^nx^n$ ? (What I wrote in my post)
Comment: That's right, you took the long way though. Compositions of functions works faster.
Comment: So is this all I need to do for this exercise? Is that my final MacLaurin series?
Comment: Yup, pretty much.
Comment: Oh, thank you! I thought it was harder than this.
Comment: I'm glad I could help.
Answer: HINT: Use the fact that $\displaystyle \sum_\limits{n=0}^{\infty} x^n=\frac{1}{1-x}$ for $|x|<1$.


Additive Yoneda Lemma

Question: I'm studying Abelian Categories in F. Borceux "Handbook of Categorical Algebra" Vol.2.
In this reference we can find an additive version of the famous Yoneda Lemma :

Let $\mathcal{C}$ be a preadditive category, $A$ be an object in
  $\mathcal{C}$ and $F : \mathcal{C} \rightarrow \mathbf{Ab}$ be an
  additive functor. Then there exist isomorphisms $\Theta_{F,A}$ of
  abelian groups
  \begin{align*} \Theta_{F,A} :
 Nat(Hom_{\mathcal{C}}(A,\_),F) \cong F(A) \end{align*}
  which are
  natural both in $F$ and $A$.

My question is : Why did he not suppose that the category $\mathcal{C}$ is small? I think we need it to state the naturality in $F$, like in the original Yoneda lemma.
Edit : Moreover we need it to define an additive structure on natural transformations and then check that $\Theta_{F,A}$ is a group morphism.
Answer: You're right that if you want to state this as a theorem in ZFC (where large categories are proper classes), you need $\mathcal{C}$ to be small.  It is possible that Borceaux is instead working in the framework of Grothendieck universes or something similar, where actually all categories are assumed to be sets (even "large" ones).
Note though that even in ZFC, you can state and prove this as a theorem schema, where you just have a separate theorem for each different formula that could represent all the proper classes involved.  So, for instance, there is no actual class of natural transformations between two functors $\mathcal{C}\to\mathbf{Ab}$, but given two such functors $F$ and $G$ and a natural transformation $T$ between them and one particular element $x$ of $\mathrm{Nat}(\mathrm{Hom}_{\mathcal{C}}(A,\_),F)$, you can prove the commutativity of the diagram saying $\Theta_{-,A}$ is natural for $T$ when evaluated at $x$.
Comment: Borceux is not working with Grothendieck universes in this reference. In fact, in Vol.1 for the "classical" Yoneda Lemma he does not forget to say that we need the category small to have the naturality in $F$.
Comment: But I think I made a mistake in my edit because the first Yoneda lemma tell us that all the natural transformations form a set, so I can define an additive structure on it pointwise.
Thanks for your answer.
Comment: You can define the additive structure just fine even if it is a proper class.  The definition will itself be a schema rather than an actual definition in the language of ZFC, but you can still prove all the properties you want to be true as theorem schemas.
Comment: Yes but I think I'm working in ZFC (sorry I'm not really familiar with those notions). Because when he proves that the category $Add(\mathcal{C},\mathcal{D})$ of additive functors between two preadditive categories is again preadditive, he asks for the category $\mathcal{C}$ to be small.
Comment: This is necessary if you want $Add(\mathcal{C},\mathcal{D})$ to literally be a category that you can define as a class.  But you can still prove all the properties involved in stating that it is additive if $\mathcal{C}$ is large; they are just theorem schemas (separate theorems for each additive functor $\mathcal{C}\to\mathcal{D}$).  You would only run into _real_  trouble if you tried to talk about arbitrary functors from $Add(\mathcal{C},\mathcal{D})$ to another category.
Comment: Can you advise me a reference so I can understand what you mean by "separate theorem" or "theorem schema"?
Comment: In the language of ZFC, we can't quantify over classes, so we can't say that something is true "for all classes".  But given any particular definition of a specific class, we can prove that the theorem is true for that definition.  A theorem schema is just a "template" theorem that illustrates how, given a definition of a class, you can prove the theorem for that class.  (If you like, it's a metatheorem saying that for each definition, we can prove the theorem is true for that definition.)

Additive Yoneda Lemma


Symfony2: How to getObjects linked to entity filtered by property on Object

Question: I normally try to search thoroughly before asking a question, but in this case I have no idea how to look up what I'm trying to do.
I have two Entities: Category and Ebooks linked in a ManyToMany relationship. Ebooks has a boolean property "active". I can get all Ebooks linked to a category by calling $category->getEbooks();, but I would like to know if it is possible to get only active Ebooks linked to the category without doing a whole query. Something like $category->getEbooks(array('active' => true));
I know I can do
$this->getDoctrine()
->getRepository('PmbLicensingBundle:Ebook')->
findBy(array('category' => $data['category_id'], active => true));
(although I'm not even sure if this would work, as my property on my ebook entity is categorIES (seeing as it's many to many)), but I was wondering if there is a way to do this from the category's side.
Answer: Nevermind. It seems that I should try my "intuitive" ideas before asking questions. category->getEbooks(array('active' = true)); actually works perfectly.


How to scan only dis,flt files

Question: I want to use only with JFileChooser I need to scan only dis,flt files:
I have code like this:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter(
 "dis files (*.dis)", "dis");
FileNameExtensionFilter xmlfilter2 = new FileNameExtensionFilter(
 "flt files (*.flt)", "flt");
   chooser.setFileFilter(xmlfilter);
   chooser.setFileFilter(xmlfilter2);
   chooser.setDialogTitle("Open a file");

chooser.showOpenDialog(null);
    java.io.File f= chooser.getSelectedFile();
    String filename = f.getAbsolutePath();

In the filter it show that but it didnt scan this file why?
Answer: You should use addChoosableFileFilter:
chooser.addChoosableFileFilter(xmlfilter);
chooser.addChoosableFileFilter(xmlfilter2);

How to scan only dis,flt files


Why does isset and !isset both return true?

Question: The following block of code prints FOUND and NOT FOUND for each element in the array.  What am I missing?
$values = DB::query($SQL);

print_r($values);
foreach($values as $value)
{
    $myVal = $value->thisAttribute;

    if(isset($myVal)) print("FOUND");

    if(!isset($myVal)) print("NOT FOUND");
}

Output:
Array
(
    [0] => stdClass Object
        (
            [thisAttribute] =>
        )

    [1] => stdClass Object
        (
            [thisAttribute] => value
        )

    [2] => stdClass Object
        (
            [thisAttribute] =>
        )
)
FOUNDNOTFOUNDFOUNDNOTFOUNDFOUNDNOTFOUND

Comment: Please post a [Short, Self Contained, Correct Example](http://www.sscce.org/).
Comment: Answers so far seem okay but they don't actually explain why _both_ strings are being output for each index in the array. Unless the OP is smoking crack of course :-)
Comment: Id throw in a print("next"); line so you can see if they're actually being printed for each element.
Comment: Well, again, please provide 100% proof that you're not smoking anything. :) How are you 100% certain it prints both every time? There's nothing in your code that proofs exactly that. Throw in a `var_dump($myVal)` there...
Comment: On a side note: you should not be checking variables that you know exist with `isset`. You're just unnecessarily suppressing error reporting.
Comment: @paxdiablo I'm supporting the crack theory. ;-P
Comment: $myVal is always `set` to whatever thisAttribute is...
Comment: @swiss196 Unless `thisAttribute` is `null`...
Comment: Not smoking crack, both strings print.  Try it yourself.  $values is an associative array returned from a laravel query.
Comment: longer example with output
Comment: Cannot reproduce. http://3v4l.org/ng0sd
Comment: [CNR](https://xkcd.com/583/). Which version of PHP are you using?
Answer: I guess the proper way to do that is :
foreach($values as $value)
{
  if(isset($value->thisAttribute)) {
    $myVal = $value->thisAttribute;
    print("FOUND");
  } else
    print("NOT FOUND");
}

Comment: This is the right way to do this but why are both being printed each time?


Interpreting negative interaction effect in regression

Question: I am running a multiple regression in order to understand effect of advertising spend on number of orders we generate. I am particularly interested in impact of TV spend. Below is my model with co-efficients

One of the things I found is there a co-relation between TV spend and Branded Search spend. And my assumption is that as you spend more on TV , more people will search you online by your brand name. In the previous model TV is barely significant. In the next model I tried the interaction effect of TV spend with Branded SEM spend and the results are below.

Trying to understand how suddenly TV spend is so significant and why the interaction has negative co-efficient even though both TV and Brand SEM spend are co-related.
Comment: I'm not entirely sure of the answer but a few thoughts that come to mind. How correlated are TV_spend and SEM_send, if the variables are highly correlated it might be that the model is having a hard time distinguishing between the two variables. Also although the interaction maybe "significant" is it meaningful ? Looking at the coefficient it appears to be quite small (to the power -4) does it have much of an impact in terms of predictions ?  EDIT - perhaps it is capturing part of a non-linear effect in your data - I can imagine TVspend doesn't result in a linear increase orders?
Comment: TV_spend and Brand_SEM_Spend has a co-relation of .26. It used to be close to .5 but I realize that I have made some changes to the raw data and that shows a lesser co-relation.  The interaction co-efficient is low but i am guessing the impact is good enough cause if I am spending 100 in TV and 100 in Bran SEM then the interaction will be multiplied by 10,000 which makes the interaction big enough.
Answer: This behaviour doesn't seem related to correlation between predictors. It seems more related to the actual behaviour of your data.
Positive TVspend parameter means that -being all other variables equal- orders grow when TVspend grows. However, negative interaction means that when Brand_SEM_spend is larger, orders grow less with TVspend than when Brand_SEM_spend is smaller. In fact, depending on the range of your variables, it might even mean that orders decrease with TVspend when Brand_SEM_spend is large.
When you don't take on account Brand_SEM_spend, your model assumes that -being all other variables equal- the effect of TVspend is the same for all values of Brand_SEM_spend. Therefore, you are adjusting a single coefficient that account for TVspend efect, and that effect is actually different for different values of Brand_SEM_spend, so data is somehow conflicting and the parameter is adjusted to the "average" effect but with a large standard error. Since standard error is larger and parameter is smaller, it becomes less significant.
Just for illustration, I build a simple model that shows the same phenomenon.
Let's start with data generation:
> response<-function(tv,nobrand){.5*tv+5*nobrand-1*tv*nobrand}
> tv<-runif(100,0,1)
> nobrand<-runif(100,0,1)
> orders<-response(tv,nobrand)+.1*rnorm(100)

Please notice that since $tv$ is uniformly distributed in the range (0,1), its average effect is zero, although its parameter would be 0.5 when $nobrand=0$ and -0.5 when $nobrand=1$.
Adjusting a model without interaction shows that $tv$ has a parameter close to zero an not significant, as expected:
> summary(lm(orders~tv+nobrand))

Call:
lm(formula = orders ~ tv + nobrand)

Residuals:
     Min       1Q   Median       3Q      Max
-0.34751 -0.08337 -0.01841  0.09197  0.36638

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.22584    0.03600   6.274 9.84e-09 ***
tv           0.05138    0.04598   1.117    0.267
nobrand      4.51445    0.04759  94.864  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1451 on 97 degrees of freedom
Multiple R-squared:  0.9893,    Adjusted R-squared:  0.9891
F-statistic:  4504 on 2 and 97 DF,  p-value: < 2.2e-16

However, adjusting a model with interaction shows clearly significant $tv$ effect and interaction, that is, it shows that $tv$ has an effect but this effect depends on $nobrand$:
> summary(lm(orders~tv*nobrand))

Call:
lm(formula = orders ~ tv * nobrand)

Residuals:
      Min        1Q    Median        3Q       Max
-0.198747 -0.068419 -0.009158  0.068185  0.258584

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.02989    0.03612  -0.828     0.41
tv           0.56321    0.06080   9.263 5.69e-15 ***
nobrand      5.02382    0.06120  82.083  < 2e-16 ***
tv:nobrand  -1.03896    0.10440  -9.952  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1023 on 96 degrees of freedom
Multiple R-squared:  0.9948,    Adjusted R-squared:  0.9946
F-statistic:  6070 on 3 and 96 DF,  p-value: < 2.2e-16

Interestingly, both in your data and my simulation R-adjusted and all p-values are larger when the interaction is included, supporting that interaction should be included in the model.
Comment: Thanks. Its really helpful in understanding the behavior.
Answer: You should not be running multiple regression if your response variable is categorical. This is because by fitting this model, you are assuming that that response variable is conditionally Normally distributed. A Normal random variable is a continuous random variable, so this does not work.
Try Poisson regression or zero-inflated Poisson regression. In R you could use the functions glm and zeroinfl for these tasks. Perhaps you will get parameter estimates that cohere better with your beliefs. If I could see your data I could tell you more.


Google Places API Alternative

Question: My IOS app (Swift 5) HEAVILY relies on googles places API specifically the Places Autocomplete. I'm using it to get addresses and places to show on the map for users. Is there an alternative for this now that they have stopped supporting it or is there a way to fetch autocompleted places using a string. ANY help is greatly appreciated. It's essential for my app to continue working.
Answer: Google has not stopped supporting Places Autocomplete. You can migrate to the new Places SDK for IOS following this migration guide. You may also refer to the places autocomplete guide here.
Hope this helps!

Google Places API Alternative


Grant "Manage Printers" permission for all printers on XP clients via GPO?

Question: Is it possible to grant "Manage Printers" permissions to all printer objects on client machines via group policy?  By default, it looks like this permission is granted to Power Users and Administrators.  I'd like to grant it to a specific security group in the domain.
In this case the printers are installed locally (well, some are network printers, but they're not managed..drivers are installed directly on clients).
Answer: Yes, with a startup script.
setprinter.exe, included with the Windows 2003 resource kit.  You can use:
setprinter.exe  3 "pSecurityDescriptor=xxxxxxxxxx"
You would need to loop through all of the installed printers, and apply the new ACL.  This would assume you could use the same ACL for all printers on all workstations.  This may not be a problem as most people don't use custom security on local printers.
"pSecurityDescriptor= is in SDDL form.  Use setprinter -examples 3 to get more info.
Set a printer with the security the way you want it, the use setprinter -show printerName 3 to get the text of how the SDDL should be applied.
This is what the command and SDDL looks like when Everyone has Manage Printers and all the other permissions are generic defaults:
setprinter.exe  3     pSecurityDescriptor="O:BAG:DUD:(A;OIIO;RPWPSDRCWDWO;;;BA)(A;;LCSWSDRCWDWO;;;BA)(A;CIIO;RC;;;CO)(A;OIIO;RPWPSDRCWDWO;;;CO)(A;;LCSWSDRCWDWO;;;WD)(A;OIIO;RPWPSDRCWDWO;;;PU)(A;;LCSWSDRCWDWO;;;PU)"
All of that must be on one line.
Here is some PowerShell code that lists the printers:
Get-WMIObject Win32_Printer -ComputerName $env:computername | foreach-object{$_.Name}
so the command to do the work would be
Get-WMIObject Win32_Printer -ComputerName $env:computername | foreach-object{setprinter.exe $_.Name 3 pSecurityDescriptor="O:BAG:DUD:(A;OIIO;RPWPSDRCWDWO;;;BA)(A;;LCSWSDRCWDWO;;;BA)(A;CIIO;RC;;;CO)(A;OIIO;RPWPSDRCWDWO;;;CO)(A;;LCSWSDRCWDWO;;;WD)(A;OIIO;RPWPSDRCWDWO;;;PU)(A;;LCSWSDRCWDWO;;;PU)"}
Again, that must be all one line.