Finding the region for a triple integral

Question: So the semester is over and i'm studying for exams, and this is one of the practice questions I came across.
Where is the centroid of the solid bounded above by the plane z = 1 + x + y, below
by the plane z = −2 and on the sides by the planes x = 1, x = 2, y = 1, y = 2?
I'll be able to work out the centroid bit once I find the volume but I amn't sure which is right  here's what i think it is
say [ (a->b) is the integral from a to b. (sorry, don't know how to do the correct symbols)
then   V = [(1->2) [(4->5) [(-2-> 1+x+y) dz dy dx
or is it V = [(1->2) [(1->2) [(-2-> 1+x+y) dz dy dx
or neither??  Thanks for any help.
Comment: Woops!! sorry forgot the give you the link
here it is http://www.codecogs.com/latex/eqneditor.php
Answer: A rectangular room whose floor is $z=-2$ and ceiling is slanted plane $z = 1 + x + y$
The volume is
$$\int_{1}^2 \int_1^2 ((1+x+y) - (-2)) dy dx= \int_{1}^2 \int_1^2 \int_{-2}^{1+x+y}dz dy dx$$
Comment: ahhh,  yes.  thank you
Comment: @Madmarkshero you are welcome, are you familiar with [latex](http://www.codecogs.com/latex/eqneditor.php)?
Comment: I've seen people use it, but don't know how to myself.
Comment: @Madmarkshero use the link to create your equations and wrap them between dollar signs to create beautiful equation $\$ \LaTeX \$$


What is the probability that you pick 3 green, no red, 1 of each, at least 1 blue marble if a jar contains 5 blue, 3 green, and 4 red marbles.

Question:
A jar contains $5$ blue, $3$ green, and $4$ red marbles.  If you pull out three of these marbles at random, what is the probability that you have pulled:
a) $3$ green marbles?
b) $0$ red marbles?
c) $1$ marble of each color?
d) at least $1$ blue marble?

For the first part I got, $\frac3{12} = \frac14 = 0.25 = 25\%$
But I am not sure if it is correct and how to do the rest correctly.
Comment: The probability that the first picked marble is green equals $\frac3{12}$, but you are asked to give the probability that *all* $3$ marbles that are picked out are green.
Comment: Oh okay, but how would I go about solving it? I don't know how
Comment: For $i=1,2,3$ let $G_i$ denote the event that the $i$-th marble that is picked is green. Then be found is:$$P(G_1\cap G_2\cap G_3)=P(G_1)P(G_2\mid G_1)P(G_3\mid G_1\cap G_2)$$Can you find these probabilities on RHS? I preassume that the marbles are not placed back after being picked. For b) you can use the same principle but then for marbles that are not red. Then for d) again use the same principle for finding the probability of $0$ blue marbles (the complement). c) is the most problematic question I think.
Answer: For a),b),d) see my comment.
c)
The probability that first we pick according to order (blue,green,red) equals:$$\frac5{12}\frac3{11}\frac4{10}$$
However there are other orders possible. So for each of them find the probability of occuring and take the summation of these probabilities.


White space when i scroll a semi-parallax in a resized window

Question: I got a wordpress which i took over from another guy, and it appears that there's a bug with the parallax section in the top. Well semi-parallax, it scrolls somewhat slower than the mainpage. I've tried fiddling around, changing width and stuff like that. The issue seems to be that the original crop is too small, but i can't figure out how i change the original crop.
Because when it's full screen it works perfectly when scrolling, but if i make it half of the screen, there's white space when i scroll down. So i assume it's the original crop that needs to be smaller, so when it resizes there's still "more image". (And yes i've tried using a larger image, same issue). All referred images in this post can be found on this url
See last image for the white space
See middle image for desired effect when scrolling
This is the html code for the image:

')  50% 0 no-repeat fixed;">

See the first image in the imgur link above (this url) for the background script.
hero-header
#hero-header {
    height: 100%;
    width: 100%;
    position: relative;
    -webkit-background-size: cover !important;
    -moz-background-size: cover !important;
    -o-background-size: cover !important;
    background-size: cover !important;
}

Some of the resize code, i hope this is enough
@media handheld, only screen and (max-width: 769px) {

    #hero-header {
        background-position: center center !important;
        background-attachment: scroll !important;
}
}

Answer: Trick is with dataspeed attribute and parallax.js line #18 and #37
Comment: Okay, so as you can tell by my title here on stack which is very fittingly "scrubcoder", i'm not the brightest of coders. So i have to try different dataspeeds, and then change the coords or the ypos?
Comment: Oh my bad xD
As you are a scrub you have to try data speeds :( or 40% instead of %50 in that javascript (lines I mentioned)
Answer: Okay, so since it doesn't seem like i'm getting an answer i can work with, here's what i ended up doing.
Basically i don't have much time on my hands at the moment, so i went for a more temporary solution, which is removing the parallax after the window is below 1800 px, which was roughly the point of which it started adding the white space.
Code is here:
@media handheld, only screen and (max-width: 1799px) {
    #hero-header {
        background-position: center center !important;
        background-attachment: scroll !important;
    }
}


Improved Monte-Carlo method vs. hit-and-miss method

Question: I do not understand  Which is more accurate, the hit-and-miss method or the improved Monte-Carlo method?
Here it is written that that the hit-and-miss has a higher variance but they showed <code>(variance of improved Monte-Carlo) - (variance of hit-and-miss method) > 0</code>
$$\sigma^2_M-\sigma^2_H>0$$
Doesn't it imply improved Monte-Carlo method  has a higher variance?
Can you please explain it experimentally to me with an easy example (such as for a small integration)?
Answer: First, they compare crude (M) and hit-or-miss (H) there; they don't mention 'improvements' until after that section where the comparison is done.
The page apparently contains a typographical error.
The crude estimate ($M$) has a smaller variance, $\sigma^2_M$ than the hit-and-miss estimate's ($H$) variance, $\sigma^2_H$. That is, $\sigma^2_M<\sigma^2_H$
As requested, I will illustrate this via a simple example. Consider using both methods on the following integration problem:

that is, $\int_0^1 f(x) dx$ where $f(x)=x,\quad 0<x<1$.
Here's the results of 1000 simulations with 1000 points of each kind of estimator:

As you see, $\sigma^2_M$ has the smaller variance, so the claim from the page that $\sigma^2_M-\sigma^2_H>0$ is a mistake.
I did the simulations in R:
<code> x=matrix(runif(1000000),nr=1000)
 y=matrix(runif(1000000),nr=1000)
 crude=colMeans(x)
 mean(crude)
[1] 0.5001032
 sd(crude)
[1] 0.009110159
 hitmiss=colSums(y<x)/1000
 mean(hitmiss)
[1] 0.500518
 sd(hitmiss)
[1] 0.01622797
</code>
We can also calculate the variance of the two algebraically.
The variance of the crude
estimate for my example problem is simply $\frac{1}{n} \text{Var}(X)$ where $X$ is uniform on $(0,1)$; that is, it should be 1/(12n) for this problem.
The variance of the hit-or-miss estimate is given here. For our problem, $\theta=1/2$, so the variance for this problem should be 1/(4n).
The standard deviations for $n=1000$ should then be about 0.00913 for the crude and about 0.0158 for the hit-and-miss. The above simulations came out pretty close to those values (0.00911 vs 0.0162).
Note that the integral they give there, $\frac{1}{n}\int_0^1 f(u)(1-f(u))du$ works out to be 1/(6n) for our toy problem here... which happens to be the same as 1/(4n) - 1/(12n) ... which is $\sigma^2_H-\sigma^2_M$ in our example. That's no accident, and - as I said at the start - apparently it's just a typo.
That is, they just got the subscripts backward; they actually prove that $\sigma^2_H-\sigma^2_M >0$ (edit: their result isn't true in all circumstances; they must elsewhere restrict the class of functions)
Answer: I would have said this as comment, except I don't have enough rep.
As Glen_b already pointed out, the claim contains a typo. It should really be $$\begin{align}\sigma^2_M-\sigma^2_H&={1\over n} E(f^2)-{\theta^2\over n}-{\theta\over n} +{\theta^2\over n}\\&={1\over n}(E(f^2)-\theta)\\&={1\over n}(E(f^2)-E(f))\\&={1\over n}\int^1_0 f(u)(f(u)-1)du\end{align}$$ Therefore $$\sigma^2_H-\sigma^2_M={1\over n}\int^1_0 f(u)(1-f(u))du$$ Moreover, the next claim that $${1\over n}\int^1_0 f(u)(1-f(u))du>0$$ is neither always true nor false.  Consider as example $f(u)=Ku$ where $K$ is just a constant. Then $${1\over n}\int^1_0 f(u)(1-f(u))du={K\over 2}-{K^2\over 3}>0 \iff 0<K<{3\over 2}$$ So that claim is only sometimes true, and $f(u)=Ku$ is only one class of functions of $u$.
Comment: I think the page is discussing a class of functions restricted to the unit box (I think there's several problems with that page if they don't). That is, I believe (though it's not explicit on that page so my impression may be wrong) that for a function of the form $f(u)=Ku$, they already keep themselves to $K\leq 1$
Comment: At the very least, $\theta$ must be $<1$ for the binomial to apply.
Comment: @Glen_b That makes sense.


I get this error when refreshing gradle project: Cause: invalid type code: B3

Question: After I hit "Refresh all gradle projects"
I get the error:

Cause: invalid type code: B3

I am trying to refresh it because I added this dependencies:
implementation 'com.squareup.okhttp3:okhttp:3.0.1'

compile 'com.squareup.okhttp3:okhttp:3.0.1'

and now want to import OkHttpClient in the class but it isn't working
Java is 12.0.1 Gradle is 5.5
Gradle code:
settings.gradle file:
    pluginManagement {
    repositories {
        mavenCentral()

        maven {
            url  "http://dl.bintray.com/mbuhot/maven"
        }
    }
    dependencies {
        compile 'mbuhot:eskotlin:0.7.0'
        compile group: 'com.mashape.unirest', name: 'unirest-java', version: '1.3.1'
        compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'

        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:23.0.0'
        compile 'com.google.android.gms:play-services:8.4.0'
        compile 'com.squareup.okhttp:okhttp:2.5.0'

    }
}
rootProject.name = 'ndmWebApp'

build.gradle file:

    plugins {
    id 'org.springframework.boot' version '2.1.3.RELEASE'
    id 'org.jetbrains.kotlin.jvm' version '1.3.21'
    id 'org.jetbrains.kotlin.plugin.spring' version '1.3.21'
}

apply plugin: 'io.spring.dependency-management'

group = 'ProjectoFinal.ndmWebApp'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.fasterxml.jackson.module:jackson-module-kotlin'
    implementation 'org.jetbrains.kotlin:kotlin-reflect'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
    //elasticSearch
    implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch'

    implementation 'com.squareup.okhttp3:okhttp:3.0.1'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

compileKotlin {
    kotlinOptions {
        freeCompilerArgs = ['-Xjsr305=strict']
        jvmTarget = '1.8'
    }

Comment: Which version of Gradle and Java are you using?
Comment: Could you please add entire code of build.gradle?
Comment: @AndiCover Java is 12.0.1 Gradle is 5.5
Answer: This seems to be an open bug with Java 11+, Gradle 5 and IntelliJ.
As far as I have seen it you have two options:

Downgrade Gradle to a version below 5.
Build your project outside of IntelliJ using the commandline.

This bug is also mentioned here.


Código não executa instrução corretamente em C++

Question: Eu tenho um código na main que funciona normalmente. Esse código diz que o usuário deverá informar os dados e  pede que o usuário digite o nome do funcionário e a instrução seguinte inicia o objeto i1. O objeto i1 chama seu construtor e o restante do código segue até o programa (na main) solicitar que o usuário digite o CPF do funcionário e a instrução seguinte inicia o objeto i1. O que eu não entendo é o que acontece quando eu altero o código da main. Quando eu insiro 4 linhas antes da linha que diz que o usuário deverá informar os dados, solicitando que o usuário informe quantos funcionários serão cadastrados, declaro uma variável quantidade, leio a variável quantidade informada pelo usuário e imprimo o valor da variável quantidade, o programa chega a imprimir que o usuário deverá informar os dados e pede que o usuário digite o nome do funcionário mas então o cursor já vai para a linha onde o usuário deve informar o CPF não permitindo que ele digite o nome do funcionário. Por que isso acontece?
//código da main que não está funcionando corretamente
int main()
{
    ofstream saidaArquivoCadastro( "cadastro.dat", ios::out );

    if ( !saidaArquivoCadastro ) // operador ! sobrecarregado
 {
 cerr << "Arquivo nao pode ser aberto" << endl;
 exit( 1 );
 }

    cout << "Informe a quantidade de funcionarios a serem cadastrados: ";
    int quantidade;
    cin >> quantidade;
    cout << quantidade;
    cout << "\nInforme os dados: \n\n";
    cout << "Nome do funcionario: ";
    info i1;
    cout << "\nCPF: ";
    info i2;

//código da main que está funcionando corretamente
int main()
{
    ofstream saidaArquivoCadastro( "cadastro.dat", ios::out );

    if ( !saidaArquivoCadastro ) // operador ! sobrecarregado
 {
 cerr << "Arquivo nao pode ser aberto" << endl;
 exit( 1 );
 }

    cout << "\nInforme os dados: \n\n";
    cout << "Nome do funcionario: ";
    info i1;
    cout << "\nCPF: ";
    info i2;

//descrição da classe info
#include <string>
using std::string;

#ifndef INFO_H
#define INFO_H

class info
{
    public:
        info (string = "");
        void setInfoDado (string);
        void setInfo ();
        void print () const;
    private:
        string infoDado;
};

#endif

  //descrição dos métodos info
  #include <iostream>
using std::cout;
using std::cin;

#include <string>
using std::string;
using std::getline;

#include "info.h"

info::info (string info)
{
    setInfoDado (info);
}

void info::setInfoDado (string info)
{
    infoDado = info;
    setInfo();
}

void info::setInfo ()
{
    string nome;
    getline (cin, nome);
    infoDado = nome;
}

void info::print () const
{
    cout << infoDado << "\n";
}

Percebi que esse problema acontece apenas quando eu coloco a instrução cin >> quantidade;. Quando eu não coloco essa instrução o cursor para em cout << "Nome do funcionario: "; para que eu possa digitar o nome do usuário (uma vez que ao instanciar o objeto i1  o método da classe info void info::setInfo () faz com que o programa espere o usuário digitar o nome). Quando eu coloco a instrução cin >> quantidade; algo faz com que esse método ou a instrução de atribuição no escopo desse método não seja executada. O interessante é que quando o objeto i2 é instanciado o código funciona normalmente (com ou sem a instrução cin >> quantidade; antes do objeto i1).
Comment: Importante você [edit] sua pergunta e explicar de maneira objetiva e pontual a dificuldade encontrada, acompanhada de um [mcve] do problema e tentativa de solução. Para aproveitar melhor o site, entender e evitar fechamentos e negativações vale a pena ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70).
Answer:
Eu tenho um código na main que funciona normalmente.

Talvez não funcione assim tão normalmente.

Por que isso acontece?

A resposta curta é que você errou na declaração dos construtores de info e familia e invalidou o que talvez você achasse que era o construtor padrão para uma classe que só tem uma variável.

Esse código diz que o usuário deverá informar os dados e pede que o
usuário digite o nome do funcionário e a instrução seguinte inicia o
objeto i1. O objeto i1 chama seu construtor e o restante do código
segue até o programa (na main) solicitar que o usuário digite o CPF do
funcionário e a instrução seguinte inicia o objeto i1

Isso que escreveu não faz muito sentido. Na prática
cout << "Nome do funcionario: ";
info i1;
cout << "\nCPF: ";
info i2;

você escreveu esses cout como prompts para orientar a leitura que acontece dentro do construtor, após você chamar 3 (!) funções. Não é uma idéia nada boa. Para alguém (incluindo você mesmo daqui um dia ou dois) entender o que o programa está fazendo teria que ter o código do construtor disponível a toda hora. Não faz sentido algum. A mensagem deveria estar junto da leitura ou ter sido passada como parâmetro.
A declaração da variável é que dispara a construção do mesmo. Só que escreveu errado. Provavelmente pretendia escrever isso
    familia() : Dado("") {};

Definindo o construtor padrão e colocando um "" na única variável de sua classe. E teria funcionado.
Só que escreveu isso
class info
{
    public:
        info (string = "");
        void setInfoDado (string);
        void setInfo ();
        void print () const;
    private:
        string infoDado;
};

E acabou criando um construtor sem sentido que tem um parâmetro string que nada significa.
Podia usar algo simples como
class info
{
public:

    info() : Dado(""){};
    info(string prompt) { setDado(prompt); };
    void setDado(string);
    void print() const;

private:

    string Dado;
};

e setDado() receberia a mensagem a cada vez:
void info::setDado(string prompt)
{
    cout << prompt << ": ";
    getline(cin, Dado);
}

E usado simplesmente assim:
    info i1("Nome");
    info i2("CPF");
    i1.print();
    i2.print();


Problem about the generalized pigeonhole principle

Question: This problem from Discrete Mathematics and its application's for Rosen

What is the least number of area codes needed to guarantee that the 25
million phones in a state can be assigned distinct 10-digit telephone
numbers? (Assume that telephone numbers are of the form NXX-NXX-XXXX,
where the first three digits form the area code, N represents a digit
from 2 to 9 inclusive, and X represents any digit.)

The answer I found in the book is :

There are eight million different phone numbers of the form NXX-XXXX
(as shown in Example 8 of Section 6.1). Hence, by the generalized
pigeonhole principle, among 25 million telephones, at least
$\lceil25,000,000/8,000,000\rceil = 4$ of them must have identical phone numbers.
Hence, at least four area codes are required to ensure that all
10-digit numbers are different

Can anyone please explain this answer as I tried a lot to understand it but I can't.
Comment: Do you understand that there are eight million distinct phone numbers?
Comment: yes of the form NXX-XXXX
Answer: Since there are at most $8,000,000$ distinct numbers in an area code, if we had $3$ areas codes, we could only accommodate $3\cdot8,000,00=24,000,000$ phone numbers.  If we have $4$ area codes, we can accommodate $4\cdot8,000,00=32,000,000$ numbers, so we need $4$.
The short way to do this is to notice that $$\frac{25,000,000}{8,000,000}=\frac{25}8=3.125$$ so that $3$ area codes won't be enough, but $4$ will be.  The most compact way of writing it is that we need $$\left\lceil\frac{25,000,000}{8,000,000}\right\rceil$$ area codes.
Comment: @HUMAN An area code is a sequence of $3$ digits like $123$  For any fixed area code, there are $8,000,000$ possible numbers.
Comment: @Avra I don't understand.  We are told that we have $8,000,000$ numbers for each area code.  This is not a permutation.  (The problem says that the numbers are of the form NXX-XXXX, so I suppose that there are $8$ choices for N and $10$ choices for each of the X's.)
Comment: why 4 area codes give us 4 * 8,000,000  ?
 I think it will give us  10^4 * 8,000,000 as 4 area codes is a number with 4 digits as i think
Comment: @saulspatz. Amazing explanation. Thank you. In case of 8 million numbers, this is a permutation, but this is not arrangement of numbers, so how do we know if we should use arrangement or not please?
Answer: I honestly think the answer is a bit unclear as well, but here is my similar explanation. There are $8$ million possible numbers of the form NXX - XXXX since:
$$
8 \times 10^6 = 8,000,000.
$$
Imagine you divide the $25$ million phones into groups of $8$ million phones. Evidently you get $4$ groups, the last group (only $1$ million) of course not being all the way full (hence the ceiling function in the answer). Each of the first $3$ groups use all of the numbers exactly once, and then there is guaranteed repetition again when assigning the fourth group of $1$ million people phone numbers. However, no number is repeated more than $4$ times. Thus, by having $4$ distinct area codes NXX, we can avoid any repetition.
Comment: It's not unclear: it just requires the reader to recognize that taking the ceiling of a positive number has the effect of rounding it up, so that any leftover 'fractional' group — in this case the extra million — is correctly counted as needing an area code.
Answer: There are 8000000 telephone numbers of the form NXX-XXXX .( For first element i.e N we have 8 choices and for remaining 6 elements we have 10 choices for each so by product rule we have 8000000 choices).Then by generalized pigeon hole principle there must be at least [25000000/8000000]=4 of 25 millions telephones which have identical phone numbers. So at least 4 area codes are required to guarantee that all 10 digit numbers are different.


Is it possible to find k-th quantile only from frequencies of a value list?

Question: Suppose we have a discrete continuous interval [0, N-1].
And, there exists $M$ samples where each value belongs to the interval.
Now, we want to find a $k$-th quantile (say, 4th quantile) from the samples.
I denote the frequency of value $n \in [0, N-1]$ by $freq_n$ and $freq_n \in [0, M]$.
What we actually have is only a list of frequencies for each value, $\vec{f}$ = ($f_0, f_1, \ldots f_{N-1}$).
The naive solution to find the k-th quantile is aligning samples in sorted order and doing something.
Is it possible to find the k-th quantile from $\vec{f}$ without samples in sorted order?
In other words, can we somehow express the function $g(\vec{f})$ that finds the k-th quantile?
Taking a example for N=5 and M=10:
$f_0 = 3$
$f_1 = 2$
$f_2 = 0$
$f_3 = 1$
$f_4 = 4$
That means we have a sequence $\mathbf{X} =$(0, 0, 0, 1, 1, 3, 4, 4, 4, 4). But we want to compute $k$-th quantile only from $f_i$.
Answer: Let me rephrase to make sure I understood your problem:
I have M random variables $X_1,..,X_M$  independent and following the same distribution as a random variable X taking values uniformly in $0,1,2,..,N-1$.
I observe the realized frequency of each possible values in my sample is $F=(f_0,f_1,...,f_{N-1})$
Solution based of the sorted sample:
you want the 0.1-quantile let's take the sample in ascending order: $X_{(0)},..,X_{(N-1)}$
i.e $X_{(0)}$ is the minimum
then k-th quantile = $X_{(floor(kM+1))}$ (k is the proportion of values below the k-th quantile)
Solution based on the frequencies:
$k-th$ quantile $= g(F) = \underset{j}{argmax}\bigg(\sum\limits_{i=0}^j f_i \leq k \bigg)$
The k-th quantile is the highest values j such that at most k percentage of my values are below j.
A sum of frequency allows to approximate the cumulative distribution function:
$\sum\limits_{i=0}^j f_i = \sum\limits_{i=0}^j \hat P(X = i) = \hat P(X\leq j)$
$\hat P$ are the probabilities guessed from the observed frequencies.
k-th quantile: 0.2-th quantile of a sample of size N=100 is the N*k-th (20th) lowest value in the sample.
Definitions:
A frequency is defined like this: $f_i = \frac{\text{number of observations taking the value I}}{\text{number of observations}}$
The median is a $\frac 12$quantile
Comment: Thank you for perfectly rephrasing my messy question and providing your excellent answer! Is the value inside the sum $(f_i \leq k)$ 0 or 1?
Comment: Or, is it $f_i$ if $f_i \leq k$ and $0$ otherwise?
Comment: I gave an example in the question. How can I obtain 2nd quantile (median) from frequency-based solution?
Comment: I updated my answer to add what I refer to with frequency and k-quantile.

$f_0 = \frac 3{3+2+0+1+4} = 0.3$, $f_1 = 0.2$...  $k=0.5$ for the median
Comment: Thank you for your kind reply. I understand the value of $f_i$. But, I have not yet understood the values inside the parenthesis $(f_i \leq k)$ (what is the objective of $\leq$ predicate?). I'm wondering what value I can get if the equation is applied to my given example. Can you elaborate on it more? (Is that really $\max$ instead of $argmax$?)
Comment: You are right it was argmax I am really sorry for the confusion.. I updated it. $f_0$ = 0.3 means there is a 30% chance that your value is 0. $f_1 = 0.2$ means there is a 20% chance that your value is 1.
$f_0+f_1=0.5$ means there is a 50% chance that your value is below or equal to 1. 1 should be your median.

You want to sum enough frequencies (in ascending order of the values) until you reach the probability you want. At this point it means the last frequency present in your sum is the frequency of your quantile


How to reduce this ODE $ x''+x=f(t)$ to affine ODE of first order?

Question: let $f$ be a real valued continous function such that $$x''+x=f(t) $$ , It is easy to reduce this ODE to first ODE just multiplying its sides by the term $2x'$ and integrating yields :$$\frac12 x'^2+\frac{x^2}{2}=2F(t)$$, $F(t)+c$ is the antiderivative of  $x'f(t) $ but what i have  got is not affine ODE ?
Source:I have got this question in Doctorat exams (Algeria 2016) .(see the attached picture exo 1 . first question)
Answer: For the left-hand side, we can find the homogeneous part of the solution $x''+x=0$ giving $x(t) = C_1 \cos(t) + C_2 \sin(t)$. So try setting $x(t) = u(t) \cos(t)$. Then
$$x'(t) = -\sin(t) u(t) + \cos(t) u'(t)$$
$$x''(t) = -\cos(t) u(t) - 2 \sin(t) u'(t) + \cos(t) u''(t)$$
So
$$x''(t) + x(t) = -\cos(t) u(t) - 2\sin(t) u'(t) + \cos(t) u''(t) +\cos(t) u(t) =f(t)$$
So now we have an equation
$$ u''(t)\cos(t) - 2\sin(t) u'(t) = f(t)$$
We can treat this equation like a first order linear equation in $u'(t)$. Find a multiplier $\rho(t)$ and then integrate the equation to put it into the form
$$u'(t) = \frac{1}{\rho(t)}\int \rho(t) f(t) \sec(t) dt$$
Answer: $x''+x=f(t)$
Using reduction of order.
Let $y=u(t)\sin{t}$.
$y'=u'\sin t + u \cos t$
$y''=u''\sin t + 2u'\cos t -u\sin t$
$y''+y=u''\sin t + 2u'\cos t=f(t)$
$u''+2u'\cot t=f(t)\csc t$
$d(u'\sin^2 t)=f(t)\sin t$
$u'\sin^2 t=\int f(t)\sin t dt$
$u'=\csc^2 t\int f(t)\sin t dt$
Integrate to find $u$, then $x=u\sin t.$
Answer: We only need to let $x'=y$ and rewrite the equation in the affine form
$$
\begin{pmatrix} x \\ y\end{pmatrix}'=\begin{pmatrix} 0 & 1\\ -1 & 0\end{pmatrix}\begin{pmatrix} x \\ y\end{pmatrix}+\begin{pmatrix} 0 \\ f(t)\end{pmatrix}.
$$
Comment: I have tried this but id dosn't work , what about x ? pleas i need more detail for your matricial form and this what i need exactly
Comment: What is it that you don't understand?


Poor models from PCA and CFA

Question: For my undergraduate dissertation I'm analysing a 75-item self-report questionnaire filled out by 1140 autistic participants (randomly split into two groups. I have split the sample and am carrying out a PCA on one sample, and a CFA on the other. Previous Rasch analyses have indicated that this questionnaire is meant to be unidimensional, but my one-factor model is coming back with terrible fit indices. I've tried multiple different models by now, including a 2-factor, 3-factor, 4-factor model (always using oblimin rotation, always removing items with cross-loadings, but varying different cut-offs/ inclusion criteria- for example removing items which don't correlate highly with other items).
None of these models have returned with good fits. I'm okay with this, I know it's not good to keep running the analysis until I get something, and I know there are many issues with the exploratory nature of this analysis and the very simple tests I'm using.
But I'm wondering if I'm doing something wrong, or if there's something obviously wrong that will cost me marks on my dissertation. Is this an appropriate analysis for a 75-item questionnaire? Or should I be trying to do something with parcelling or correlated error in SEM?
The basic code I'm using is below.
Thank you
<code>one.factor.model <-   'Factor1 =~ Q11 + Q29 + Q14 + Q65 + Q72 + Q52 + Q68 + Q55 + Q2 + Q5 + Q28 + Q62 + Q22 + Q75'
one.factor.fit <- cfa(one.factor.one, data= half2)
summary(one.factor.fit, fit.measures=TRUE)
</code>
Answer: You're not doing anything wrong.
Scales which have been developed using things like exploratory factor analysis never fit well in new samples, especially if they have 75 items.
75 items is far too many to get clean single dimensional fit. Why are so many items needed?
Also, don't do PCA, do EFA.
Comment: Thanks for your answer. All the 75 items aren't really needed. Ideally, I want to create a more unidimensional questionnaire. I think my next move will be to use EFA to reduce the items down to a smaller questionnaire, and then use CFA on a separate sample to confirm the new unidimensional model. I just have one question: if I find, for example, 45 questions that form a strong unidimensional first factor, and I want to use CFA to test it. Would my CFA sample only include those 45 questions? Or would it include all 75?
Comment: 45. But that's still way too many (IMHO).

Poor models from PCA and CFA


Node and revision id

Question: I am working with a company setting up a drupal website. I am responsible for entering our product information into the drupal tables. I am having difficulty getting a straight answer/an answer that makes sense as to what the values for nid and vid should be in the drupal_node and drupal_node_revision tables should be. I am being told by our vendor that the values for nid and vid need to be the same (ie 27 and 27) but that doesn't make sense to me. Shouldn't the vid just start at 0 or 1 and increment up from there. Isn't it simply what the node table uses to read the current version from the revision table.
I know very little about drupal so I may be wrong but their answers aren't making sense to me. And as the nid is automatically incremented in the table, I have no way of knowing what the nid value is until after the insert. So I would have to read the value and run an update statement, which seems really sloppy.
Comment: Are you trying to "write" nodes directly to the database? The node id (nid) and revision id (vid) should be handled by the Entity API when you create nodes using entity_create() or the UI.
Answer: If you begin to add nodes and never edit them, like you would do when migrating data to a new Drupal installation, then the nid and vid would increment at the same pace, and would happen to be the same. After first edit though, assuming you have revisioning on, the new vid would be what ever is the next available number for all revisions.
Comment: So, do they have to be the same at the beginning? For my example each node corresponds to a specific product. Should the revision id's start at 1 or the corresponding node id?
Comment: I was just describing what happens when you create nodes with node_save or in the UI, and then edit them. You really don't need to worry about vid when using node_save or UI. For entering your data one good way is to create nodes with node_save function. There are also modules for that, for example Migrate. Writing sql for creating nodes directly to the database is the hardest way, I think.

Node and revision id


Thread try catch continue if access to file was denied

Question: Looping through a folder using system thread, how to ignore and continue if access to file was denied.
// Start thread.
System.Threading.ThreadStart start = delegate { scanner(@"C:\", "*.html;*.txt"); };
System.Threading.Thread thread = new System.Threading.Thread(start);
thread.Start();

private static string scanstatus = string.Empty;
private static void scanner(string folder, string patterns)
{
    try
    {
        // Get the patterns.
        string[] pattern_array = patterns.Split(';');

        // Search.
        foreach (string pattern in pattern_array)
        {
            foreach (string path in System.IO.Directory.GetFiles(folder, pattern, System.IO.SearchOption.AllDirectories))
            {
                // trim path
                scanstatus = (path.Length > 60) ? "../" + path.Substring(path.Length - 59, 59) : path;

                System.Threading.Thread.Sleep(5000);
            }
        }

    }
    catch (System.Exception excpt)
    {
        Console.WriteLine(excpt.Message);
    }
    finally
    {
        Console.WriteLine("*************DONE*************");
    }

}

Comment: What is the problem with putting a `try-catch` inside the loop?
Comment: it doesn't continue. I'm not sure what i do wrong
Comment: You need to put the `try-catch` **inside** the loop. You have it **outside** the loop...
Comment: It is because your loop is inside the try catch.When access denied exception raised the flow of program transfer to the catch which is out from your loop.
Comment: http://www.codeproject.com/Articles/14402/Testing-File-Access-Rights-in-NET-2-0
Answer: As Daniel mentioned in the comment, basically when you want to keep going with the next iteration, you need to move the try/catch to inside the loop. Currently your catch is outside the outer loop, so if an exception is thrown, execution can't continue. There's no concept of "continue from where you'd got to" within C#.
I'd strongly suggest that you also limit what you catch. For example:
foreach (string pattern in patternArray)
{
    try
    {
        foreach (string path in Directory.GetFiles(...))
        {
            // ...
        }
    }
    catch (IOException e)
    {
        // Log it or whatever
    }
    // Any other exceptions you want to catch?
}

Notes:

Catching Exception is almost always a bad idea, except as a final backstop at the top level of your request (or whatever) handling
Underscores in variable names aren't conventional in .NET; typically you'd use camelCase for variables (and PascalCase for methods, classes etc)
With using directives you can avoid putting the fully-qualified type names in your code, which would make it much easier to read
This method will end up being quite long - I'd suggest extracting the inner loop; possibly including the try/catch, or possibly not.
Comment: This doesn't work for me. In particular with Excel files, this line just hangs and the exception isn't raised: `wb = excel.Workbooks.Open(filePath, false, true,5,null,"WrongPAssword");`. Do you know how to test if you have permission?
Comment: @Power-Mosfet: Well what *does* it do? If the exception is thrown, it *will* continue to the next thread.
Comment: @JeremyThompson: I don't see what Excel has to do with this question. The OP certainly never mentioned it. The way the question is phrased certainly *implies* that an exception is thrown.


R feature selection

Question: I am working with the method randomForest for model building. And for a good model performance, it is very important to select the right features. At my example I have 30 variables and I would like to try to build different models with all possible combination with the given features, to choose at the and the best performed model. I am working with R and my question is if someone knows a method which could perform all feature combination as training data for model building
thanks
Answer: This is an impossible task in any programming language.
You have 30 features. There are therefore $2^{30}$ possible combinations of features.
$2^{30} = 1,073,741,824$.
If you fit one model a second, you'll be done in $298,261.68$ hours, or about 34 years (give or take a few days due to leap years).
Therefore you need a different feature selection approach. And that question has been asked before: Feature selection with Random Forests
Answer: I have tried recently Boruta algorithm. "It finds relevant features by comparing original attributes importance with importance achievable at random, estimated using their permuted copies". As a result algorithm separates input features on 3 classes: important, tentative and rejected.

R feature selection


Alertdialog not_showing

Question: I am new to android development. tried to implement android dialog in my project but the it's not showing .There are no errors in the logcat.
This is the XML code for it :
<android.support.design.widget.FloatingActionButton
    android:id="@+id/add_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:clickable="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.927"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.935"
    app:srcCompat="@android:drawable/ic_input_add" />

This is the part where I have implemented alertdialog :
FloatingActionButton add_button = findViewById(R.id.add_item);
    add_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Create item list");
            final EditText enter_item_list=new EditText(MainActivity.this);
            enter_item_list.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
            enter_item_list.setHint("Type a name");
            enter_item_list.setHintTextColor(Color.RED);
            builder.setView(enter_item_list);

            builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    String item_name = enter_item_list.getText().toString().trim();
                    add_item_to_list(item_name);

                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which) {
                    dialogInterface.dismiss();
                    AlertDialog alertDialog=builder.create();
                    alertDialog.show();

                }
            });
            itemList_ref = Firestore_ref.collection("itemList").document(UserEmail).collection("user_item_list");
        }
    });
}

private void add_item_to_list(String item_name) {
    String item_id = itemList_ref.document().getId();
 InventoryModel inventoryModel = new InventoryModel(item_id,item_name ,UserName);
itemList_ref.document(item_id).set(inventoryModel).addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        Log.d("TAG","Inventory list created");
    }
});
}

This is the full code :
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.omniheart.elloslai.storage_checker.model.InventoryModel;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

private String UserEmail , UserName ;
private GoogleApiClient googleApiClient ;
private FirebaseAuth firebase_auth;
private FirebaseFirestore Firestore_ref;
private FirebaseAuth.AuthStateListener authStateListener;
private CollectionReference itemList_ref ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    GoogleSignInAccount googleSignInAccount = GoogleSignIn.getLastSignedInAccount(this);
    if(googleSignInAccount!=null){
        UserEmail=googleSignInAccount.getEmail();
        UserName = googleSignInAccount.getDisplayName();
        Toast.makeText(this,"Welcome" + UserName,Toast.LENGTH_LONG).show();
    }

     googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Auth.GOOGLE_SIGN_IN_API)
            .build();

    firebase_auth=FirebaseAuth.getInstance();
    Firestore_ref=FirebaseFirestore.getInstance();
    authStateListener=new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser firebaseUser = firebase_auth.getCurrentUser();
            if(firebaseUser == null) {
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
                finish();
            }
        }
    };
    FloatingActionButton add_button = findViewById(R.id.add_item);
    add_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Create item list");
            final EditText enter_item_list=new EditText(MainActivity.this);
            enter_item_list.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
            enter_item_list.setHint("Type a name");
            enter_item_list.setHintTextColor(Color.RED);
            builder.setView(enter_item_list);

            builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    String item_name = enter_item_list.getText().toString().trim();
                    add_item_to_list(item_name);

                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which) {
                    dialogInterface.dismiss();
                    AlertDialog alertDialog=builder.create();
                    alertDialog.show();

                }
            });
            itemList_ref = Firestore_ref.collection("itemList").document(UserEmail).collection("user_item_list");
        }
    });
}

private void add_item_to_list(String item_name) {
    String item_id = itemList_ref.document().getId();
 InventoryModel inventoryModel = new InventoryModel(item_id,item_name ,UserName);
itemList_ref.document(item_id).set(inventoryModel).addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        Log.d("TAG","Inventory list created");
    }
});
}

@Override
protected void onStart() {
    super.onStart();
    googleApiClient.connect();
    firebase_auth.addAuthStateListener(authStateListener);
}

@Override
protected void onStop() {
    super.onStop();
    if(googleApiClient.isConnected()){
        googleApiClient.disconnect();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true ;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()){
       case R.id.sign_out_button:
       signOut() ;
       return true ;

       default:
                return super.onOptionsItemSelected(item);
   }
}

private void signOut() {
    Map<String ,Object> map = new HashMap<>();
    map.put("tokenId", FieldValue.delete());
    Firestore_ref.collection("users").document(UserEmail).update(map).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            firebase_auth.signOut();
            if (googleApiClient.isConnected()){
                Auth.GoogleSignInApi.signOut(googleApiClient);
            }
        }
    });
}

}

Answer: You forgot to use alertDialog.show(); to display your AlertDialog
Check your code you have put alertDialog.show(); inside  builder.setNegativeButton that's why your alertDialog is not displaying
Change your code like below code
add_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Create item list");
            final EditText enter_item_list=new EditText(MainActivity.this);
            enter_item_list.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
            enter_item_list.setHint("Type a name");
            enter_item_list.setHintTextColor(Color.RED);
            builder.setView(enter_item_list);

            builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    String item_name = enter_item_list.getText().toString().trim();
                    add_item_to_list(item_name);

                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which) {
                    dialogInterface.dismiss();

                }
            });

            AlertDialog alertDialog=builder.create();
            alertDialog.show();
            itemList_ref = Firestore_ref.collection("itemList").document(UserEmail).collection("user_item_list");
        }
    });

Comment: Thank you for your answer :)
Comment: @EllosLai happy to help you my friend
Answer: Declare Variable globally
AlertDialog alertDialog ;

add this after your negative button click
alertDialog = builder.create();
        alertDialog.show();

Comment: Most welcome and hope will help you  in future problems
Comment: Happy to help. Consider up voting as well for the benefit of people who stumble upon this question.

Alertdialog not_showing


Approximating Fresnel integrals with standard functions

Question: I would like to approximate the Fresnel S and Fresnel C with standard functions.
I've started with the $ S(x) $ function:
$$ approxS(x) = sgn(x) * \left ( sgn(x)* \left ( \frac{ \sin( \frac{x^2}{2}  ) }{x} \right) + 0.5 \right ) $$
The result looks like this:

This is the FresnelS function:

The difference ( $ approxS(x) - S(x) $ ):

What do I wrong? How could I approximate it better?
Comment: well to be fair to yourself, the error looks worse than it is due to the scale of your axes.
Comment: over what range of values of x?
Comment: $ x \in \mathbb{R} $
Comment: You want one formula that is accurate everywhere?
Comment: I am looking for a forula, which can approximate the Fresnel function everywhere as close, as possible
Comment: But not too close, to keep the formula simple
Answer: According to
https://en.wikipedia.org/wiki/Fresnel_integral,
for large $x$,
$S(x)
=\sqrt{\dfrac{\pi}{2}}\left(\dfrac{sign(x)}{2}
-(1+O(x^{-4}))\left(\dfrac{\cos(x^2)}{x\sqrt{2\pi}}
+\dfrac{\sin(x^2)}{x^3\sqrt{8\pi}} \right)\right)
$
and
$C(x)
=\sqrt{\dfrac{\pi}{2}}\left(\dfrac{sign(x)}{2}
+(1+O(x^{-4}))\left(\dfrac{\sin(x^2)}{x\sqrt{2\pi}}
+\dfrac{\cos(x^2)}{x^3\sqrt{8\pi}} \right)\right)
$.
You can get the
direct power series
(good for small $x$)
by expanding the integral
term-by-term.
It might be interesting
to see how close these are.


Fetch certain values from dictionary

Question: I have below dictionary. I need to drop OS::<name> from this dictionary (In this case first 3 key,value pairs). I am only interested in the rest of the key,value pairs. How can I achieve this? It would help if I can get the logic to be as short as possible.
{u'OS::project_id': u'xyz',
u'OS::stack_id': u'xyz',
u'OS::stack_name': u'XYZ',
u'image': u'RHEL-7.2',
u'private_network_id': u'xyz',
u'floating_ip': u'xyz',
u'volume_type': u'ceph_fake',
u'volume_size': u'10',
u'key': u'my_key',
u'flavor': u'm1.small'}

Comment: Dict comprehension? It seems pretty simple. Where are you stuck? Or did you not try anything?
Comment: What have you tried, and what exactly is the problem with it. Note that dictionaries are unordered; they don't have a "first" key.
Comment: `{key: value for key, value in d.items()  if not key.startswith('OS::')}`
Comment: Thanks, that gives me what I need
Comment: I thought this was read by you guys https://stackoverflow.com/help/be-nice
Comment: If you are wondering about the downvotes, they are most likely because of the total lack of research effort displayed on your part. This question has been asked a thousand times before.
Answer: use dict comprehension.
{key: value for key, value in d.iteritems()  if not key.startswith('OS::')}

{u'flavor': u'm1.small',
 u'floating_ip': u'xyz',
 u'image': u'RHEL-7.2',
 u'key': u'my_key',
 u'private_network_id': u'xyz',
 u'volume_size': u'10',
 u'volume_type': u'ceph_fake'}

Comment: why negative votes?
Comment: I got my answer, not sure about the neg votes though. Voted up. Thanks @VishnuUpadhyay
Comment: @VishnuUpadhyay: Because you have answered the question they indented to. In python 3 `d.items()` will do the same trick.
Comment: @Rahul there is no tag of python3 that's why i prefer python2.7.
Comment: Oh. I didn't see it.

Fetch certain values from dictionary


onclick() em elementos gerados através de ajax?

Question: Eu estou a tentar usar um evento onclick em
 gerados através de um formulário ajax(). Eu tenho o seguinte código
$(".option").click(function(){
  alert();
  var text = $(this).attr("href");
  window.location.href=href;
});

Neste código, ele nem alert() dá, o
 tem aquela class e mesmo assim ele não dá sinal.
Daria informação do código ajax mas é contra a política do meu cliente divulgar informações por isso é este exemplo de linha de html que ele escreve.
echo "
[Texto] Nome
";

Comment: basta fazer assim `$(document).on('click', '.option', function(){})`
Comment: Uma pergunta simples, se este elemento contém um link e você está usando redirecionamento com base neste link quando clicado, poruqe não facilita sua vida e usa um `[Texto] Nome` ?
Comment: Porque todos os `` estão com as classes definidas assim `ul > li{` e se puser um `` antes do `` as classes não serão aplicadas. Eu sei que poderia mudar mas gostaria de saber outras alternativas.
Comment: Na verdade, não há problemas no seu código, o problema está só em onde que ele está executando e quando ele está executando, pois no momento, você está executando essa atribuição de evento de clique antes do elemento mesmo existir na página, por isso não tem como funcionar, então você apenas precisa colocar este seu código dentro do metodo `.done()` do teu ajax, depois que o elemento ter sido jogado na página, que assim ele irá executar somente quando o elemento já realmente exista.
Answer: O que você pode é atribuir ao document um evento click na sua classe, pois os elementos estão sendo gerados depois da DOM já ter sido carregada, sendo assim não pegará o evento do click, faça da seguinte maneira:
$(document).on('click', '.option', function(){
  //Evento do click
})

Dessa maneira você diz que sempre que for clicado no document nessa classe ele executa esse metódo!
Outra maneira é usar o delegate() do jQuery, dessa maneira você fala que em todo elemento(div) na classe (option1) ele irá executar esse método
$('div').delegate('.option1','click', function() {
    //Evento do click
});

Adicionei 3 exemplos separados por uma linha, verifique que no primeiro exemplo a cada clique ele gera um elemento, porém o elemento gerado não tem ação, já no segundo e terceiro exemplos os elementos gerados possuem a ação desejada:

Click1

Click1

Click1

Comment: @PauloRoberto Seu questionamento me lembrou que podemos usar o delegate para não precisar atribuir o click ao documento, adicionei outro exemplo na resposta
Comment: parece ser funcional, porém não me parece ser uma coisa boa atribuir um evento ao documento todo executando checagens de classe a cada clique do usuário na página... acredito ser melhor só colocar a atribuição como o cara fez só que depois que o elemento foi criado mesmo.
Comment: Funcionou perfeitamente! Não era necessário os exemplos mas obrigado pelo esforço tomado :)
Answer: Para elementos como esse gerados a partir do javascript você vai precisar usar o .on()
$(".option").on("click", function(){
  alert();
  var text = $(this).attr("href");
  window.location.href=href;
});

Comment: Removi minha resposta para deixar como comentário aqui, faça o bind do click dentro do seu bloco de success do retorno do ajax.
Comment: @LeandroAngelo acho que seu comentario deveria ser no post e não na resposta do nosso amigo
Comment: @RafaelAugusto, como o colega havia postado o código antes, o restante da minha resposta seria apenas um complemento, que ele pode ser incorporada a mesma resposta, caso o autor deseje.
Comment: porque o `$('.option').click(function(){});` não funcionaria se fosse colocado dentro do bloco de sucesso do retorno do ajax? não vejo motivos para alterar para o `on`
Comment: o erro ocorre se o objeto for gerado depois da página carregada, se voce cria um novo elemento deve redeclarar a sintaxe do onclick apos sua criação para que seja aderida a ele


Exibindo aviso de 'carregando' quando iframe atualizar - html

Question: Estou com dificuldades em uma aplicação, onde as telas demoram para redirecionar. Para contornar o problema, criei uma página apenas com um iframe, o qual contém a navegação entre as páginas.
O problema maior é que não é possível deixar as trocas de janelas mais rápidas, pois as mesmas ficam armazenadas em um CLP Siemens s7-1200.
Então, surgiu a idéia de quando o usuário trocar de página dentro do iframe, seja exibido uma mensagem que está carregando.
Ou seja, toda vez que o conteúdo do frame atualizar, deverá aparecer uma mensagem de carregando.
Para isso posso utilizar JavaScript e html.
Abaixo segue código da página inicial:

Dentro do iframe, existe menus para navegações para outras páginas, dentro do iframe.
Comment: É bom sempre postar alguma parte relevante do código, facilita bastante o entendimento da pergunta e uma possível resposta rápida e precisa. Senão gera mts comentários com pedidos de mais explicações.
Comment: Pelo que entendi, a página contem um frame onde as páginas mudam dentro frame, ou seja, a URL no navegador continua a mesma?
Comment: Isso mesmo @Dvdsamm. Porém, cada vez que as páginas mudam dentro do iframe, preciso que seja exibida uma mensagem de carregando. Pois a troca entre páginas é lenta.
Answer: É preciso fazer uma estrutura de comunicação entre o frame e a janela principal, verificando quando um link de navegação dentro do frame for clicado e quando o frame for carregado. Para isso, é preciso adicionar uma classe para cada link nas páginas do frame, por exemplo:

Em seguida adicione um atributo onload na tag do frame que irá chamar a função onLoadHandler() quando o mesmo for carregado:

No código da página que contém o frame (página-mãe), adicione o JS abaixo com as funções necessárias:

Em cada página a ser carregada dentro do frame (páginas-filhas), adicione o código:

Sempre que um link com a classe navega for clicado dentro do frame, irá exibir uma div "Carregando..." na janela principal. Quando o frame terminar de ser carregado, essa div será eliminada.


Encoding ID variables for machine learning

Question: Is it possible to encode ID variables for an ML model in a way that the model can work with IDs not seen before?
For example, I want to predict the sentiment of a tweet, the account it may be originating from, and directed to, may help the classifier a lot to decide whether classify it as negative or positive.
Hence, is it possible to pass these features to the model in a way that, if a known id (shown whilst training) appears, it can help the prediction, and if there's a new id (unseen whilst training), the model can still work with it; either by no having impact whatsoever or by weighting the fact that it is an unrecognized id? If so, how would a Python + Sklearn implementation look like?
Comment: Short answer: no. Some workarounds: compute _features_ of the ID (e.g. clustering them based on their behaviors), or create a special ID for "unseen during training". It's smart to label some of the training examples as "unseen during training" to learn the corresponding weights.
Comment: See also https://stats.stackexchange.com/q/350353/232706, https://datascience.stackexchange.com/q/64460/55122, https://datascience.stackexchange.com/q/63749/55122
Answer: One of the general rules of building usable machine learning models is that you never include features that won't be available at prediction time, account ID is one of such features.
Technically, you could encode the ID using something like feature hashing, but this would only mean that for an unknown ID you would be using another, random ID from the training set. Another approach would be to replace the unknown ID with the average prediction from all the training set. Such solutions are not much better than not including the ID at all.
Another problem with using IDs is the high cardinality. According to this site Twitter has 300 million active users. Let's imagine a perfect scenario, where you have the data on all the users. Let's also say that you are using a very simple linear regression model where you use as features one-hot encoded IDs of the accounts where the tweet originated from, one-hot encoded IDs of the accounts where it was directed to, and their interaction. Such model would have 300,000,000 + 300,000,000 + 300,000,000² number of parameters. Are you sure you want to do this?
The third problem is that for any ID you would usually not have much data. How many datapoints do you have on average per account ID, for how many do you have only a single point? To have reasonable estimates, you would want to have multiple points per each ID.
Moreover, it sounds like a rather useless feature if you want to predict the sentiment of a tweet. With such a feature, your model would learn things like "Jack always sends depressive tweets" and "Ann sends happy tweets", so what? This doesn't tell you anything about the sentiment of a particular tweet. Even if for some reason it makes sense for you to assume that it is a constant characteristic of a person to send happy or sad tweets (is it?), you could do better by clustering people into two groups of "happy" and "sad" users and use this as a feature, this would be both available at prediction time and results in one parameter rather than a quadrillion.
Using IDs as features may make sense in case they will be available at prediction time and you have them all represented in the training set, there is not a huge number of them, and you have many datapoints per each ID. For example, you are doing medical research and use the ICD-10 codes of diagnosed diseases as features (still, some codes may be very rare), or you could use one-hot-encoded countries as features in an econometric model, etc. Notice that such features represent some general groupings that apply to many samples in your dataset, rather than individual IDs. With individual IDs you are learning to make predictions for the particular person, but then, you need to have enough data for that person.
Finally, if you have the account IDs and other data, and data on interactions of this account with other accounts, it can be used to de-anonymize the data. Using such data may pose ethical and legal concerns. Say that you train a neural network using account ID as a feature, then one of the users fills a GDPR request to be forgotten. In such a case, you should throw away your model and re-train it with the data not containing this user or face high penalties. I'm not saying that if you didn't use account ID as a feature this won't be a problem, but if you used the ID it's a much more obvious violation since your model de facto serves as a kind of black-box database that records the history of the user indexed by their account ID.
Answer: That's one of the important things in Data Science : you have to create your variables, good enough so your model can predict well.
Here, you pointed well, that you can't directly use IDs, but with profiles information, you can create variables that will reflect what you see as a human when you analyze the tweet. A few examples : Number of people followed by the publisher, Number of people followed by the person it's directed to, Number of people followed by both the publisher and the person it's directed to, Percentage of the publisher's follows also followed by the person it's directed to, sentiment (% positive) of past tweets done by sender, sentiment (% positive) of past tweets done by receiver, do they follow each other...
You have to use your knowledge of the problem to create such variables, and find the necessary info to create them (form APIs, etc). If you have enough of such variables, you can make each user fairly unique (just like an id variable would do). Then, you can test those variables on your model, make feature selection etc.
Comment: True, that's the obvious way, related features, I was wondering if there was some kind of way of encoding the IDs directly in a way that work because the number of followers most likely won't say much about whether the tweet is positive or not, but the account directed to (id)  most likely will, so that's the doubt; so far I haven't found an answer to whether there is some smart workaround around this, I'm reluctant to think it is impossible at all haha


Rails parsing json

Question: After requesting some API, i get a json hash. What I want is to loop through that hash to  get the tags but I get no implicit conversion of String into Integer. any help or a better way of doing this, please?
{
  "status": "OK",
  "result": [
   {
    "verdict": "OK",
    "problem": {
      "tags": [
        "implementation", ...
      ]
    }
   },
   .
   .
  ]
}

models/codeforces_api.rb
def self.retrieve_results(current_user)

    json = JSON.parse(open("http://codeforces.com/api/user.status?handle=#{current_user.code_forces_handle}&key='my-key'&secret='my-secret'").read).to_json

    ActiveSupport::JSON.decode(json)["result"].each do |record|
       if record["verdict"] == "OK"
          record ["problem"].each do |problem|
             problem ["tags"].each do |tag|
                puts tag
             end
           end
       end
    end
end

Answer: It looks like you want:
record["problem"]["tags"].each do |tag|

Rails parsing json


Event volunteers registration module

Question: I'm looking for a module for an event website which calls for volunteers to register by sending name/email.
Ideally, it would allow some users to access the registered volunteers database in some downloadable format (CSV for instance).
Is there something like this for D7? I've been googling but found nothing.
Answer: I've used the Webform module for this situation in the past.   Just create a name and email component!

Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

Event volunteers registration module


Facebook tagging multiple users using php sdk

Question: I'm having a hard time getting the solution for this. I'm intending to tag many users using php sdk. The sdk returns "Fatal error: Uncaught OAuthException: (#100) Invalid keys "tags" were found in param "tags"..
In my controller I have this:
$tags = array();
foreach($to as $id){
    $tag = array();
    $tag['tag_uid'] = $id;
    $tag['x'] = rand() % 100;
    $tag['y'] = rand() % 100;
    $tags[] = $tag;
}
$argsTag = array(
    'tags'=> $tags
);
$photo_details['message'] = $message;
$photo_details['image'] = '@' . realpath($file_path);
$photo_details['tags'] = array($argsTag);
$upload_photo = $this->fb_obj->api("/me/photos", 'post', $photo_details);

Tried using $tag as well as $tags variable.
Using $tags, I got an error of Invalid keys "0,1,2" were found in param "tags".
Using $tag, I only tagged 1 user instead of three.
Comment: are you sure `$to` array containing three users?
Comment: Your $tags variable with contain 3 values in item 0, because you're assigning it  `$tags[] = $tag;`
Comment: how should I be assigning it?
Comment: yes. I logged it into the console.
Answer: try this
foreach($to as $key => $id){
    $tag = array();
    $tag['tag_uid'] = $id;
    $tag['x'] = rand() % 100;
    $tag['y'] = rand() % 100;
    $tags[$key] = $tag;
}

i dont think there be need to this part array($argsTag); and  this
$argsTag = array(
    'tags'=> $tags
);
because you defined it as array before
Comment: Nailed it! I was confused because of too much arrays for me to handle.


PushSharp Google Cloud Messaging Heads-up notification

Question: I'm developing an application for Android and iOS and I'm using PushSharp (on server-side) to send push notifications to both platform. In particular I'm using (for Android) the Firebase platform (FCM).
Following this guide I was able to send push notification to an Android device setting icon and sound too but I think there is a problem.
When the notification arrives it doesn't being shown as Heads-up notification but only as status bar notification.
To be clear, I would:

but i see only the application icon that appears on the status bar.
How can I tell to FCM to show my notification as Head-Up notification similary to what I obtain with the following code?
NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_media_play)
                        .setContentTitle("My notification")
                        .setContentText("Hello World!")
                        .setDefaults(Notification.DEFAULT_ALL)
                        .setPriority(Notification.PRIORITY_HIGH);

Comment: Did you find solution for this. I am having the same issue
Comment: I'm also having the same issue. I am able to generate a heads-up notification when the app is in the foreground, but not when the app is in the background or dead. All I get is the system tray notification
Comment: @Carlos I haven't found a solution yet :(
Comment: @Carlos any luck?
Comment: @AmilcarAndrade: The new version of push notification work even app is killed. So what I am doing whenever I am getting remote notification. I am showing local notification inside onNotification event
Comment: @Carlos: I am facing same problem, Could you please explain how did you solve it out.
Answer: I have fixed it by installing following version of react-native-push-notification
npm install zo0r/react-native-push-notification.git

in your index.android.js
function init(){
    PushNotification.configure({
        onNotification:async (notification)=>{
                if(!notification.userInteraction && !notification.foreground){
                    PushNotification.localNotification({
                      message: "you message"
                    });
                  }
               ,
                requestPermissions:true,
                senderID:"31************",
                popInitialNotification:false
        })
}

Comment: I was talking about an Android native app ;)
Answer:
you must create a channel in your MainActivity.java.

+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.os.Build;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

+      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+        NotificationChannel notificationChannel = new
+        NotificationChannel("500", "MainChannel",
+        NotificationManager.IMPORTANCE_HIGH);
+        notificationChannel.setShowBadge(true);
+        notificationChannel.setDescription("Test Notifications");
+        notificationChannel.enableVibration(true);
+        notificationChannel.enableLights(true);
+        notificationChannel.setVibrationPattern(new long[]{400, 200, 400});
+        NotificationManager manager = getSystemService(NotificationManager.class);
+         manager.createNotificationChannel(notificationChannel);
+      }

Add the channelId to your server: an example with node.js

        await admin
            .messaging()
            .send({
                android: {
                    priority: 'high',
                    notification: {
                        sound: 'default',
                        title: 'your title',
                        body: 'your message',
                        imageUrl: 'img-uri',
                        priority: 'high', // this is importnat
                        channelId: '500', // the channelId we created in MainActivity.java
                    },
                },
                apns: {
                    payload: {
                        aps: {
                            contentAvailable: true,
                        },
                    },
                    headers: {
                        'apns-push-type': 'background',
                        'apns-priority': '5',
                        'apns-topic': '', // your app bundle identifier
                    },
                },
                topic: //topic or token,
                data: {//send a custom data here to your client},
                notification: {
                    title: 'your title',
                    body:'your message',
                    imageUrl: 'img-url',
                },


Independent variables in the conditional variance GARCH(1,1)

Question: I am using a GARCH(1,1) model, and I would like to add some variables to my conditional variance.
I have the data for these variables, but I was wondering if I have to change these variables to variance-data themselves.
Let's say my data is 1, 4, 6, 8, 2. Before adding it as a variable to the conditional variance, do I have to transform it to (1-mean)/mean before I can add it? So my data would then be (1-4.2)/4.2, (4-4.2)/4.2, etc.
Comment: 1) It all depends on the software you use and the input it `requires`. 2) Conceptually, please include why you think you need that transformation.
Comment: @Jim, it's more so a conceptual question. I use stata, so the input would be something in the line of: -- arch log_return, het(L.var) arch(1) garch(1) -- The reason for me was that when transforming this data, it would explain more about the variance..
Answer: There are several possible perspectives on the question. For example, you can have an idea of what the data generating process (DGP) could be, dictated by the knowledge about the physical/economic/... processes at hand or some theory about them. If you think it is a GARCH(1,1) with additional regressors, i.e. something like
\begin{aligned}
x_t &= \mu_t + u_t, \\
\mu_t &= \dots, \\
u_t &= \sigma_t \varepsilon_t, \\
\sigma_t^2 &= \omega + \alpha_1 u_{t-1}^2 + \beta_1 \sigma_{t-1}^2 + \gamma_1 x_1 + \dots + \gamma_k x_k, \\
\varepsilon_t &\sim i.i.d.(0,1),
\end{aligned}
then it is natural to include the additional regressors $x_1$ to $x_k$ as they are in the conditional variance equation instead of changing them from $x_i$ to $z_i:=\frac{x_i-\bar{x}_i}{\bar{x}_i}$ for $=1,\dots,k$.
If you have no idea about the transformation of the $x$s in the DGP, you may try different alternatives and see which one leads to best model fit, adjusted for the fact that more complex models tend to fit better even if the true model is not complex (e.g. by careful use of AIC or BIC or cross validation / out-of-sample evaluation).
If you want to prevent the possibility of getting a negative fitted value of the conditional variance, you might either (1) transform the $x$s to make them nonnegative and restrict the $\gamma$s to be nonnegative or (2) use, say, a log-GARCH model where $\log(\sigma_t^2)$ replaces $\sigma_t^2$ in the conditional variance equation. (Log-GARCH is an alternative to EGARCH and has certain advantages over the latter; see e.g. the recent works of Genaro Sucarrat and his R packages lgarch and gets). (2) might be a computationally simpler alternative than (1), but bare in mind that the interpretation of the two models is not identical.
Comment: Thank you for your answer. My x's are in total 1, so for example x1 = 0.2, x2 = 0.5 and x3 = 0.3, so that's why i tried this transformation (and i would make a separate regression for each x).
Comment: That's called compositional data and there are some special methods for dealing with it. I am no expert, but including all of these in one equation would lead to perfect multicollinearity (I guess you know that already), so you may instead include all but one. A transformation making them linearly independent is probably not a good idea as the three variables together still can be summarized without loss of information as two variables...
Comment: Thanks again. Let's say I have 20 variables summing to 1, but with further inspection I'm only using 16. Would there in that case be any problem?
Comment: From the perspective of collinearity, there would not be a problem as long as at least one variable is left out.


Linguagem R: Formatar string de acordo com o primeiro caracter

Question: Estou escrevendo um script R para converter dados que estão em arquivos de texto com campos de largura fixa para arquivos CSV.
Ocorre que além da transformação eu faço algumas "formatações" nos dados e tem uma coluna com o código de receita que pode assumir dois tipos de formato, de acordo com o primeiro caractere de cada string:
Se o primeiro caractere for "9", o formato é 220.127.116.11.0.00.0.0.00.00.00, caso contrário será 0.0.0.0.00.0.0.00.00.00
Os dados são armazenados num data frame dfe o campo a ser formatado é o codigo_receita.
Eu tentei isso, mas obviamente não está dando certo:
  if(startsWith(df$codigo_receita, "9")){
    df$codigo_receita <- sprintf(
      "%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s",
      str_sub(df$codigo_receita, start = 1, end = 1),
      str_sub(df$codigo_receita, start = 2, end = 2),
      str_sub(df$codigo_receita, start = 3, end = 3),
      str_sub(df$codigo_receita, start = 4, end = 4),
      str_sub(df$codigo_receita, start = 5, end = 5),
      str_sub(df$codigo_receita, start = 6, end = 7),
      str_sub(df$codigo_receita, start = 8, end = 8),
      str_sub(df$codigo_receita, start = 9, end = 9),
      str_sub(df$codigo_receita, start = 10, end = 11),
      str_sub(df$codigo_receita, start = 12, end = 13),
      str_sub(df$codigo_receita, start = 15, end = 15)
    )
  }else{
    df$codigo_receita <- sprintf(
      "%s.%s.%s.%s.%s.%s.%s.%s.%s.%s",
      str_sub(df$codigo_receita, start = 1, end = 1),
      str_sub(df$codigo_receita, start = 2, end = 2),
      str_sub(df$codigo_receita, start = 3, end = 3),
      str_sub(df$codigo_receita, start = 4, end = 4),
      str_sub(df$codigo_receita, start = 5, end = 6),
      str_sub(df$codigo_receita, start = 7, end = 7),
      str_sub(df$codigo_receita, start = 8, end = 8),
      str_sub(df$codigo_receita, start = 9, end = 10),
      str_sub(df$codigo_receita, start = 11, end = 12),
      str_sub(df$codigo_receita, start = 13, end = 14)
    )
  }

Comment: E trocar o if/else pela função ifelse pode ser um lugar para começar. if/else só funcionam para um elemento, eles não olham um vetor inteiro. O ifelse sim
Comment: Pode dar um exemplo de dois códigos antes e depois da formatação? Acho que fica mais fácil sugerir algo tendo eles pra se basear
Answer: Seguindo a sugestão do Jorge Mendes, usando a função ifelse foi possível alcançar o resultado desejado.
Segue código de exemplo:
library(stringr)
raw_data <- data.frame(nro = c("00000000000000", "900000000000000"))
raw_data$nrof <- ""
print(class(raw_data))
print(raw_data)

format9 <- function(nro) {
    return(
        sprintf(
                "%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s",
                str_sub(nro, start = 1, end = 1),
                str_sub(nro, start = 2, end = 2),
                str_sub(nro, start = 3, end = 3),
                str_sub(nro, start = 4, end = 4),
                str_sub(nro, start = 5, end = 5),
                str_sub(nro, start = 6, end = 7),
                str_sub(nro, start = 8, end = 8),
                str_sub(nro, start = 9, end = 9),
                str_sub(nro, start = 10, end = 11),
                str_sub(nro, start = 12, end = 13),
                str_sub(nro, start = 15, end = 15)
            )
    )
}

format0 <- function(nro) {
    return(
        sprintf(
            "%s.%s.%s.%s.%s.%s.%s.%s.%s.%s",
            str_sub(nro, start = 1, end = 1),
            str_sub(nro, start = 2, end = 2),
            str_sub(nro, start = 3, end = 3),
            str_sub(nro, start = 4, end = 4),
            str_sub(nro, start = 5, end = 6),
            str_sub(nro, start = 7, end = 7),
            str_sub(nro, start = 8, end = 8),
            str_sub(nro, start = 9, end = 10),
            str_sub(nro, start = 11, end = 12),
            str_sub(nro, start = 13, end = 14)
        )
    )
}

ifelse(startsWith(raw_data$nro, "9"), raw_data$nrof <- format9(raw_data$nro), raw_data$nrof <- format0(raw_data$nro))

print(raw_data)


How to display a image and some text instead of unset a field using form_alter hook?

Question: In D7 I have a field photo on the user account page (user edit form).
I have a conflict between the modules conditional state and simplecrop therefore I like to disable the conditional state module for this field and replaced it by some code in the form_alter hook..
When another field has a value of ok/not oke I can e.g. use the function like
if( set my check here) {
        unset($form['field_photo']);
}

But I do not want to unset the field. I would like to display the image and put some text here.
How to achieve this?
Answer: Using unset() with form elements is always wrong.
To avoid the form element is shown, just set its #access property to FALSE or to the value returned from a function, and that form element will not appear in the form, or it will appear basing on what returned from that function.
Once you make it not accessible from the currently logged-in user, you can add the form elements you need, not forgetting to add the form submission handler to handle the input given from the users for those form elements you add.
Comment: Thxs that is good to know, i will use that. It is however very unclear for me how to add a form element in the way I need. What I need is displaying a image and some text. How will this form element looks like in code?


Existe alguma maneira de recuperar o histórico de todas as queries executadas num servidor MySql?

Question: Tenho uma transação em uma tabela de um banco de dados MySql e (php+apache).
Eu queria saber se eu poderia recuperar (seja no log do apache ou no log do MySql) o ip de onde foi gerada a query que fez essa inserção.
Alguma idéia?
Comment: Tem como configurar o log de queries, mas não é possível recuperar o IP, pois todas as queries são executados do mesmo servidor. https://stackoverflow.com/questions/303994/log-all-queries-in-mysql
Comment: Na verdade se o servidor de aplicação não está no mesmo _host_ do de banco de dados é possível recuperar este endereço. Mas se o que você deseja é a informação do lado do cliente então a coisa fica mais difícil. Você pode tentar cruzar os _logs_ do Apache e do MySQL mas a solução mais simples é fazer o programa em PHP registrar no _log_ do Apache ou num arquivo próprio a informação que você precisa.
Answer: Chama-se general query log e vem desabilitado por padrão. Habilitando-o o servidor passará a armazenar cada operação realizada; vale a pena ler a documentação sobre o assunto pois é possível criar uma lista de comandos SQL que você não precisa salvar no log.
Comment: era isso mesmo que eu procurava. mas infelizmente o meu nao esta habilitado. vou habilitar para as logs futuras. valeu


UTF-8 is not working for TextArea contents

Question: I'm interacting a website using HttpRequests in C#
I can read the page contents but when i try to post some information back to the server, everything works correctly but not about the value of TextAreas  in the page...
The text I'm trying to set for them is in  Persian (Farsi)   and the page I'm receiving is set for Windows-1256 encoding...
The problem is that the content of the textarea is not shown as I expect in Farsi!
Update: here is the code I use to send  the request:
public static string PostMultipart(string URL, List<RequestParameterInfo> parameters, List<string> cookies, string referer, string acceptLanguage, string acceptCharset, object KeepAliveValue)
{
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(URL));
   var boundary = "---------------------------7dc283270344";
   var messageBytes = Encoding.UTF8.GetBytes("--" + boundary);

   foreach (var item in parameters)
   {
      var prefixBytes = Encoding.UTF8.GetBytes("\n");
      var itemBytes = item.ToBytes();
      var postfixBytes = Encoding.UTF8.GetBytes("\n--" + boundary);

      var startIndex = messageBytes.Length;
      Array.Resize<byte>(ref messageBytes, messageBytes.Length + itemBytes.Length + prefixBytes.Length + postfixBytes.Length);

      prefixBytes.CopyTo(messageBytes, startIndex);
      itemBytes.CopyTo(messageBytes, startIndex + prefixBytes.Length);
      postfixBytes.CopyTo(messageBytes, startIndex + prefixBytes.Length + itemBytes.Length);
     }

     var lastPostfixBytes = Encoding.UTF8.GetBytes("--");
     var startIndex2 = messageBytes.Length;
     Array.Resize<byte>(ref messageBytes, messageBytes.Length + lastPostfixBytes.Length);
     lastPostfixBytes.CopyTo(messageBytes, startIndex2);

     request.Headers.Clear();
     request.Accept = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */*";
     request.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
     request.ContentLength = messageBytes.Length;

     request.Referer = referer;
     request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)";
     request.ContentType = "multipart/form-data; boundary=" + boundary;
     request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
     request.Headers.Add(HttpRequestHeader.AcceptLanguage, acceptLanguage);

     if (!string.IsNullOrWhiteSpace(acceptCharset))
         request.Headers.Add(HttpRequestHeader.AcceptCharset, acceptCharset);

     if (KeepAliveValue is Boolean)
         request.KeepAlive = (bool)KeepAliveValue;
     else
         request.Headers.Add(HttpRequestHeader.KeepAlive, (string)KeepAliveValue);

     request.Expect = null;

     request.CookieContainer = new CookieContainer();
     foreach (var item in cookies)
         request.CookieContainer.SetCookies(new Uri(URL), item);

     request.AllowWriteStreamBuffering = true;
     request.Method = "POST";

     using (var strm = request.GetRequestStream())
     {
         strm.Write(messageBytes, 0, messageBytes.Length);
     }

     string resPage = "";
     using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
     {
         using (StreamReader srResponse = new StreamReader(response.GetResponseStream()))
         {
             resPage = srResponse.ReadToEnd();
         }
     }

     return resPage;
 }

Comment: how do you post to the server?
Comment: I tried many ways... including converting the text to UTF-8 and putting that in the request data package
Answer: Change your Form element to use the correct encoding:
<form method="post" accept-charset="Windows-1256" />

or <form accept-charset="utf-8" />
Update:
request.ContentType = "multipart/form-data; charset: utf-8; boundary=" + boundary;

Comment: ok that wasn't clear before update! try `request.ContentType = "multipart/form-data; charset: utf-8; boundary=" + boundary;`
Comment: i'm using `HttpWebRequest`!
Comment: It wasn't the answer... but anyway I found it!


Friedman test for rank order question - Comparing between groups

Question: In my study, participants ranked a total of 5 designs (different lamp types) in their order of preference (absolute favourite, second favourite, etc.). Participants ranked all lamps, and lamps were presented in random order to participants. Participants could not give the same rank to two lamps. I now want to evaluate whether there are any differences in the participant preferences. My second step will be to test whether there are any differences between male / female participants.
To answer my initial question, I believe a Friedman Test is appropriate. As far as I understood, Friedman would transform my data to rank data (which it already is, as participants have indicated their preference order). As shown in the code below, using both 'raw' numeric values and 'ranked' numeric values (done manually by me) produce the same Friedman Test results. I previously made an error in creating the ranked table, but the code below showcases that the comparison between raw and ranked values produces identical results.
My question now focuses on the comparison between two groups (e.g., man/woman) in their lamp (order) preference. I'd like to know whether there is a significant difference between participant groups in their preference, but have no idea how to tackle this. Imagine that the group (e.g., gender) is an additional column in the dataframe.
I came across the Scheirer-Ray-Hare test online, although the test does not seem to be universally accepted. Thank you very much in advance for your time!
--
<code># load data. Letters are lamp designs (columns), numbers are individual participants (rows)
y <- structure(c(3.88, 5.64, 5.76, 4.25, 5.91, 4.33, 30.58, 30.14,
16.92, 23.19, 26.74, 10.91, 25.24, 33.52, 25.45, 18.85, 20.45,
26.67, 4.44, 7.94, 4.04, 4.4, 4.23, 4.36, 29.41, 30.72, 32.92,
28.23, 23.35, 12, 38.87, 33.12, 39.15, 28.06, 38.23, 26.65), .Dim = c(6L,
6L), .Dimnames = list(c("1", "2", "3", "4", "5", "6"), c("A",
"B", "C", "D", "E", "F")))

y_ranked <- structure(c(6, 6, 5, 6, 5, 6, 2, 4, 4, 3, 2, 4, 4, 1, 3, 4, 4,
1, 5, 5, 6, 5, 6, 5, 3, 3, 2, 1, 3, 3, 1, 2, 1, 2, 1, 2), .Dim = c(6L,
6L), .Dimnames = list(c("1", "2", "3", "4", "5", "6"), c("A",
"B", "C", "D", "E", "F")))

friedman.test(y)
> Friedman chi-squared = 23.333, df = 5, p-value = 0.0002915

friedman.test(y_ranked)
> Friedman chi-squared = 23.333, df = 5, p-value = 0.0002915
</code>
Comment: Your ranks don't seem to relate to the original data. Please explain how you got them.
Comment: I think you may be looking for a technique called ANACONDA. See my answer to a similar question here https://stats.stackexchange.com/questions/251691/looking-for-a-statistical-difference-between-two-groups-of-ranked-data/251775#251775
Comment: Your code doesn't run in a clean session; i.e. your example is NOT reproducible (*reproducible* means if I paste your code then what I see *reproduces* what you see). R does not come with a function called `freidmanTest`. Whatever package it's from (scmamp? PMCMRplus? something else?), try reading the help on that function (which should include examples for you to follow). However, R does come with a test called `friedman.test` and the example in the help there shows the two main ways to call it (the last two lines), each matching the calling syntax given at the top of the `friedman.test` help
Comment: Having trouble making sense of what you're doing and asking: Please clarify-- (1) Are the letters A, B, C, ... the Groups (lamp designs) and the numbers 1, 2, 3, ... the Participants? Is that 5 or 6 of each? (2) Can you clarify exactly how you got matrix `z` from matrix `y`---with a row or col as an example to show it's right? (3) Do you know the difference btw `friedman.test` and `friedmanTest`? Does your test procedure expect matrix columns to be Groups or Participants?
Comment: @Glen_b Apologies, I tested both base-R and PMCMRplus Friedman test, have now changed my code back to base-R and it should be reproducible. Sorry for the oversight on my part.
Thank you for your time.
Comment: @BruceET, I have now updated my question to hopefully clarify this.
I am mostly interested in (2), how to evaluate between two different groups - but would also like to understand the difference between two identically 'ranked' groups (1). Thank you very much!
Comment: @Glen_b Thank you Glen - you were absolutely right. I made an error in calculating the ranks of my data, and after fixing this error the test produces the expected result! Now I'm left wondering how to best compare between groups.
Comment: @Walter You can probably remove question 1; it seems like it was perhaps a coding issue after all; it may be best to focus on the other question. For question 2, can you clearly identify what 'groups' you mean? Do you mean the male vs female comparison?
Comment: @mdewey Thank you. Is there by any chance an R package available to use with ANACONDA? Googling for R + ANACONDA is quite challenging given the name of related software packages. I also wonder how valid ANACONDA is for non-parametric data? Thanks!
Comment: @Glen_b Thank you, I've updated my original question as this was indeed 'simply' a coding issue from my side. Hopefully someone can answer my remaining question.
Comment: I do not know of any R package. Calculating the statistic is fairly easy but unless you can rely on asymptotic normality going beyond that is harder. It is suitable for rankings so if you can rank your data you can use it.
Answer: It sounds like Friedman's test is an appropriate approach to answer the first question.  And, yes, I would avoid the Scheirer-Ray-Hare test.  It appears to not be well regarded from a theoretical standpoint, but also in my experience it  will fail to find a significant interaction effect in cases where other tests will find one. For a model more complex than can be handled by Friedman or Kruskal-Wallis, you might look into aligned ranks transformation (ART) anova. The ARTool software for R and Windows makes the process relatively easy, but be sure to read the complete documentation. For example, all interactions should be included in the model, and handling post-hoc comparisons of interactions can be tricky. ART anova is a rank based method and allows for relatively complex models including repeated measures. Below I've given you the code of a possible model. There are some resources for ART at the bottom of this page, that you may want to review.  (Caveat: I am the author of that page.) (At the time of writing this R code will run at rdrr.io).
<code>### Load data. Letters are lamp designs (columns),
###  numbers are individual participants (rows)

y <- structure(c(3.88, 5.64, 5.76, 4.25, 5.91, 4.33, 30.58, 30.14,
16.92, 23.19, 26.74, 10.91, 25.24, 33.52, 25.45, 18.85, 20.45,
26.67, 4.44, 7.94, 4.04, 4.4, 4.23, 4.36, 29.41, 30.72, 32.92,
28.23, 23.35, 12, 38.87, 33.12, 39.15, 28.06, 38.23, 26.65), .Dim = c(6L,
6L), .Dimnames = list(c("1", "2", "3", "4", "5", "6"), c("A",
"B", "C", "D", "E", "F")))

y

### Transform data to long format

Data = reshape(as.data.frame(y), varying = LETTERS[1:6],
       timevar = "Lamp", v.names="Score",
       times = LETTERS[1:6],
       direction = 'long')

Data$Gender[Data$id==1]="Female"
Data$Gender[Data$id==2]="Female"
Data$Gender[Data$id==3]="Female"
Data$Gender[Data$id==4]="Male"
Data$Gender[Data$id==5]="Male"
Data$Gender[Data$id==6]="Male"

Data$Lamp   = factor(Data$Lamp)
Data$Gender = factor(Data$Gender)
Data$id     = factor(Data$id)

Data

### ART anova

if(!require(ARTool)){install.packages("ARTool")}
library(ARTool)

model = art(Score ~ Lamp + Gender + Lamp:Gender,
                data = Data)

anova(model)

### Post-hoc comparisons
### Be sure to read documentation about this topic.

model.lm = artlm(model, "Lamp")

if(!require(emmeans)){install.packages("emmeans")}
library(emmeans)

marginal = emmeans(model.lm, ~ Lamp)

CLD(marginal, adjust = "tukey", Letters=letters)
</code>
Comment: This is exactly what I was I looking for, thank you very much! Really appreciated.


Proving $\forall d\in\mathbb{Z_+},\ \min\{n:\lambda^n(10^d)=1\}=d+2,$ where $\lambda()$ is the Carmichael function.

Question: (I'm posting this question in the spirit of this advice and will post an answer if no one else does so.)
[This paper] proves the following:

If $k, x$ and $a_1,a_2,a_3\dots$ are positive integers, then $a_1\uparrow a_2\uparrow\dots a_{s}\uparrow x\pmod k$ is independent of the value of $x$, provided $s\gt h(k).$ Here $h(k):=\min\{n:\lambda^n(k)=1\}$, where $\lambda()$ is the Carmichael function.

Thus, if we're considering the last $d$ decimal digits of such a tower, the proviso involves $k=10^d.$ I've verified by computer that $h(10^d)=d+2$ for $1\le d\le 10^3$.
Q: Is it correct that $\ h(10^d)=d+2\ $ for every positive integer $d$? How to prove it? For other bases $b$ as well, are there correspondingly simple formulas for $\ h(b^d)?$
EDIT: Since my answer would essentially coincide with that of @Onir, let me instead just mention here that the same method gives the following explicit formula for $\lambda^n(10^d), \ \ n,d\in\mathbb{Z_+}:$
$$\lambda^n(10^d)=\begin{cases}
1&\text{if $1\le d\le n-2$}\\
2&\text{if $d=n-1$}\\
2^2\,5^{d-n}&\text{if $n\le d\le 2n-1$}\\
2^{d-2n}\,5^{d-n}&\text{if $d\ge 2n+2$}
\end{cases}$$
Comment: for general $b$ it seems a bit hard, for example, if $b=p$ it would require being able to factor $p-1$, and then for each prime $q$ dividing $p-1$ we would also have to factor $q-1$ and so on
Comment: @Onir Yes, I see. What I had in mind was that there might be a few special bases of interest that might be worth the trouble.
Comment: I think for bases in which the prime divisors of $b$ are all $2$ or fermat primes we can do something similar
Answer: for $a\geq 4$ and $b\geq 1$ we have
$\lambda(2^a 5^b) = \operatorname{lcm}(2^{a-2},4\cdot 5^{b-1}) = 2^{a-2}5^{b-1}$.
Let $k = \lceil d/2 \rceil$.
Then $\lambda^k(10^d) = 2^25^{d-k}$
From here each application of $\lambda$ just reduces the exponent of $5$ by one, so we have:
$\lambda^d(10^d) = 2^2$
$\lambda^{d+1}(10^d) = 2$
$\lambda^{d+2}(10^d) = 1$


How to programmatically link commerce products to taxonomy terms

Question: I'm trying to link existing commerce products to an existing taxonomy term in Drupal 7:
<code>$products = commerce_product_load_multiple($pids);
foreach($products as $product){
    $product->field_some_option[LANGUAGE_NONE][0]=$tid; //the taxonomy term id
    commerce_product_save($product);
}
</code>
This doesn't work.
Typically when I assign the taxonomy term to the product via the admin pages it adds an entry to a database table called field_data_field_some_option, which contains the product and term id. When I use the above code, a new entry is again made in the table, but the term id is set as NULL.
Note that I'm trying to link commerce products, not product displays, which as far as I understand means I can't use the typical node-taxonomy linking approach.
Anyone know how to get this working, short of bypassing Drupal APIs and editing the database directly?
Answer: You're close, but need to tweak setting the field value to:
<code>$product->field_some_option[LANGUAGE_NONE][0]['tid'] = $tid;
</code>
For the taxonomy term reference field uses the 'tid' key there.
You could also do it with a metadata wrapper like:
<code>$wrapper = entity_metadata_wrapper('commerce_product', $product);
// Append to existing field value
$values = $wrapper->field_some_option->raw();
$values[] = $tid;
// Set field values
$wrapper->field_some_option->set($values);
$wrapper->save();
</code>


Passing a parameter from control to custom Authorization

Question: I am creating a class that derive from AuthorizeAttribute class. I need to pass the parameter in my controller, where I decorate the derive class. How can I achieve that in this situation?
[SampleAuthorization]
public ActionResult GetFileContent(Guid planId)
{
}

 public class PlanAuthorizationAttribute :  AuthorizeAttribute
 {
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // how can I use my planId to my custom plan authorizaton

        base.OnAuthorization(filterContext);
    }
}

Answer: You can find the values in authorizationContext.RequestContext.HttpContext or if planId is part of the route you can even find it in authorizationContext.RequestContext.RouteData.
Comment: Then its probably only in the `.HttpContext.Params` because its not part of the route data.
Comment: yap they are there but how can I access that?
Comment: You get the `AuthorizationContext` passed to `OnAuthorization` as a parameter!


Can a residual neural network be interpreted as a form of ensemble learning?

Question: I stumbled over this paper: "Veit, A., Wilber, M. & Belongie, S. Residual Networks Behave Like Ensembles of Relatively Shallow Networks. (2016).". In it, they argue that residual neural networks are in fact using short-paths during optimization. Meaning that very deep networks are behaving like multiple not-so-deep networks. These paths apparently show ensemble-like behavior in the sense that they do not strongly depend on each other.
I interpret this as a form of ensemble learning in which we mix predictions from various algorithms to get better results.
Is this intuition of mine correct? And is this, in fact, the reason that ResNets work so well?
We should be able to verify this by training multiple shallow networks and combine their results. Has anyone tried this?
Answer: Probably not.
Although resnets have ensemble-like behaviour, it's still a bit of a leap to say they are directly equivalent to an ensemble of shallow networks.
It's quite computationally infeasible since a resnet with only 50 layers has the ensemble equivalent of $2^{50}$ shallow networks.
Also, the "ensemble" of paths in a resnet all share the same common set of weights, whereas a traditional ensemble would learn $2^{50}$ independent sets of weights, so there is a qualitative difference.
Of course if you tied all the weights the right ways you would just end up with a very computationally expensive equivalent of the original network.