Meta-analysis in R: how to calculate standard error for study with multiple outcomes?

Question: for my PhD, I am working on a meta-analysis. The studies we have identified have means/SDs and % to compare conditions. Several of these studies also have multiple outcomes that we want to pool.
For that, we use the Borenstein 2009 book to calculate Cohen's D for each outcome, and then calculate a combined effect size D per study, as well as a new variance from this combined D (page 229, formula 24.3).
However, if we want to run the meta in metafor in R, we need to have standard error, instead of variance.
metagen(TE, seTE, studlab, data = NULL, subset = NULL)
Can we just square root that new variance? It seems too easy, particularly given all the other more elaborate formulas...
Comment: I would pick the outcome that is of most theoretical interest, or run a sensitivity analysis with different outcomes.
Answer: In this context, the standard error is just the square root of the variance.
Lest somebody gets confused about this: When we are dealing with raw data, then we can compute their variance, the square root thereof is the standard deviation, and if we divide the standard deviation by the square root of the sample size, we have the standard error of the mean. The latter can also be called a standard deviation, but it is not the standard deviation of the raw data, but of a statistic (in this case, the mean). The term "standard error" simply helps to differentiate the standard deviation of the raw data from the standard deviation of the mean. Also, if we square the standard error, we can call this a variance, but again, not of the raw data but of the statistic. To differentiate the variance of the raw data from the latter, we can use the term "sampling variance" to emphasize that we are not talking about the variance of the raw data, but how much variance there is in the statistic (if one were to repeatedly sample the same number of individuals from the same population and compute the statistic in each sample).
PS: The metagen() function is not part of the metafor package, but of the meta package.


Calculation of an integral based on a normal distribution CDF and PDF

Question: Let $X$ be a normally-distributed random variable with mean $0$ and some positive variance.
Denote $f$ as its probability density function, and $F$ as its cumulative distribution function.
I am interested in calculating
$$\int_{-\infty}^{0}F(kx)f(x)\text{ d}x$$
where $k \neq 0$ is a known constant that does not depend on $x$.
How exactly would I calculate this?
When I saw this integral, I made the mistake of thinking it was $\mathbb{E}[F(kX)]$, but soon realized it wasn't, as the integral does not cover all of $\mathbb{R}$, but only $(-\infty, 0)$.
No complete solutions are necessary; hints are appreciated.
Answer: Hint: Write it as
$$
\int_{-\infty}^0 F(kx)f(x)\,\mathrm{d}x
=\iint_{\mathbb{R}^2}f(x)f(y)\mathbf{1}_{x<0}\mathbf{1}_{y<kx}\,\mathrm{d}\mathcal{L}^2(x,y)
$$
and $\{x<0, y<kx\}$ can be easily described in polars.


I tried to install package from github but I get requirement parse error

Question: pip install get+get://github.com/AllenDowney/ThinkBayes/blob/master/code/thinkbayes.py

pip install get+https://github.com/AllenDowney/ThinkBayes/blob/master/code/thinkbayes.py

I tried this in my terminal and I'm a windows user
github link for package
Answer: Ok I figured out .. I users a text editor and copied the code and I saved the file as .py and saved it in the same directory where my main file is saved and used ''' import filename as something ''' . I was able to use the code from the file I got from github


Determine version of package to install via bash command's output in Poetry

Question: I am trying to install a Python package via Poetry whose version to install should be determined based on the output (~return value) of a Bash command.
Is it possible doing something (in the pyproject.toml) along the lines of:
[tool.poetry.dependencies]
python = "^3.8"
this-package = "^$(path-to-executable --version)"

where $(path-to-executable --version) is the bash command call that would output a version?
Ideally, without having to run a script/Makefile/"""something""" on top of Poetry (as this Git thread seems to point to)
Specifically, this is because I'm trying to install GDAL. We don't use too advanced features, so pretty much any version would do. However, the Python package to be installed depends heavily on the version of the Gdal's executable (and its libraries) that is installed in the system. Which can be determined running gdal-config --version in a terminal. In my case (Ubuntu 18.02), that command returns 2.2.3, but in never Ubuntu will return something higher.
So, I'm trying to make the dependency resolution in Poetry's pyproject.toml a liiiiitle bit dynamic: Whomever is trying to install my package would still need to install libgdal-dev and other dependencies, but I'd like it to be a tiiiiiny bit dynamic so they don't have to edit the pyproject.toml file to fill up their version of Gdal. Also, this is for internal use, so it only needs to work in Linux-like systems (no Windows or Apple)
Thank you in advance!
Answer: I'm also trying to keep the pyproject.toml GDAL version in sync with the installation, but I'm doing it the other way around: use the version from Poetry to install the system library.
Unfortunately Poetry doesn't yet have a way to get just the package version, but after a bit of finagling I ended up with this: sudo apt-get --assume-yes install libgdal-dev="$(poetry show gdal | tr --delete ' ' | grep '^version:' | cut --delimiter=':' --fields=2)*". It gets the version which will be installed; it doesn't need to be already installed. (Fortunately Poetry doesn't format the output with ANSI colour codes when passing to a pipe.)


Ajax chamar webmethod com URL amigavel

Question: Não sei se é uma dúvida frequente, ou algo que não é possível.
Durante meus estudos percebi que era possível fazer isso com PHP, mas não vi nada com ASP.NET Web Forms.
Fiz uma URL da mesma pagina:
 routes.MapPageRoute("Pagina de Teste",
            "teste-usuario.com",
            "~/teste.aspx");

Quando passo a página teste-usuario.com ela carrega a teste.aspx.
Minha dúvida é a seguinte, tenho um método AJAX.
jQuery.ajax({
            type: "POST",
            data: "objeto",
            url: "teste.aspx/metodoTeste",
            contentType: "application/json; charset=utf-8",
            dataType: "json",

Sendo metodoTeste meu WebMethod e teste.aspx onde se localiza este método.
Gostaria de saber se é possível passar minha URL amigável (teste-usuario.com) ao invés de teste.aspx para carregar a mesma página. Não gostaria de deixar visível o nome da página (teste.aspx).
Comment: Tenho outro documento default, e queria fazer o mesmo mas para varias paginas, chamando pela url amigavel criada entende?
Answer: Crie uma regra de reescrita onde sufixo .aspx poderá ser ocultado.
Exemplo (web.config):
   <rule name="Append .aspx">
        <match url="^((.*\/)?[^/.]+)$" />
        <action type="Rewrite" url="{R:1}.aspx" />
   </rule>

Uma página http://seu.site/teste.aspx poderá ser acessada assim    http://seu.site/teste.
Na URL com parâmetros, usando como exemplo o script da pergunta:
url: "teste.aspx/metodoTeste",

Trocaria por isso:
url: "teste/metodoTeste",

Comment: Já tentei também, acho que esse esquema não funciona no javascript.
Comment: O que eu queria era chamar o WebMethod através de uma url amigavel e nao o nome próprio da pagina.
Comment: Isso sim, porém só queria chamar de outra maneira para mais segurança, mas sem problemas, se eu não me engano no php é possivel chamar através de uma url amigavel ao invéz do nome proprio da pagina.

Ajax chamar webmethod com URL amigavel


Generic wrapper function that calls a method of an object by a given key

Question: I want to write a generic wrapper function called foo that takes an object o and a key k plus some args and calls o[k](...args) in a type-safe manner with inferred return type.
Here is an example:
const obj = {
   a: 1,
   b: true,
   c: (name: string) => `Hello, ${name}.`,
   d: (name: string) => `Goodbye, ${name}.`,
};

const result = foo(obj, 'c', 'Peter');
// typeof result === 'string'
console.log(result); // Hello, Peter.

Here is what I cooked up so far:
function foo<
  Args extends any[],
  Return,
  Target,
  Key extends keyof {
    [K in keyof Target as Target[K] extends ((...args: Args) => any) ? K : never]: Target[K]
  }
>(target: Target, key: Key, ...args: Args): Return
{
  // typeof method === 'Target[Key]'
  const method = target[key];

  // This expression is not callable. Type 'unknown' has no call signatures.ts(2349)
  return method(...args);
}

// Argument of type 'string' is not assignable to parameter of type 'never'.ts(2345)
const result = foo(obj, 'c');

Is it possible to express such a wrapper function in TypeScript and if so, then how would you go about it?

Edit:
I took Titian Cernicova-Dragomir's answer and adjusted it to give me the correct return type:
type FunctionKeys<Target> = keyof {
  [K in keyof Target as Target[K] extends ((...args: any) => any) ? K : never]: Target[K]
}

function foo<
Target extends Record<Key, (...args: any) => any>,
Key extends FunctionKeys<Target>,
>(...[target, key, ...args]: [Target, Key, ...Parameters<Target[Key]>]) {
  const method = target[key];
  return method(...args) as ReturnType<Target[Key]>;
}

I could have also adjusted Tobias S.' answer the same way, but I found that using the tuple generated better compiler errors. Here is an example:
const obj = {
  greet: (name: string) => `Hello, ${name}.`,
};

// Expected 3 arguments, but got 2.ts(2554)
fooTitian(obj, 'greet');

// Argument of type '{ greet: (name: string) => string; }' is not assignable // to parameter of type 'Record<"greet", () => any>'.
//   Types of property 'greet' are incompatible.
//     Type '(name: string) => string' is not assignable to type '() => any'.ts(2345)
fooTobias(obj, 'greet');

Answer: You don't need the Args parameter, you ca just type the rest parameter using Parameters. You can also use a tuple to convince Typescript that the parameters are tied together

type FunctionKeys<Target> = keyof {
    [K in keyof Target as Target[K] extends ((...args: any) => any) ? K : never]: Target[K]
  }
function foo<
  Target extends Record<Key, (...args: any) => any>,
  Key extends FunctionKeys<Target>,
>(...[target, key, ...args]: [Target, Key, ...Parameters<Target[Key]>]): ReturnType<Target[Key]> {
  // typeof method === 'Target[Key]'
  const method = target[key];
  return method(...args);
}

Playground Link
Comment: @T.J.Crowder The way he does it it inverse to me. He uses the key and the args as the inference site and type the object relative to those. I use the object as the inference site, and type the key and the args relative to the object. The main problem with TobiasS's approach is that we loose code completion for the key and the argument names. Either solution is valid from a type system perpective, I just prefer the DX of the second one
Comment: Tobias' solution seems to do it without the tuple, but is there a footgun if we don't have it? For instance, unions and explicit type arguments?
Answer: You could compose the generic types of the function like this:
function foo<
  Target extends Record<Key, (...args: Args) => any>,
  Args extends unknown[],
  Key extends PropertyKey
>(target: Target, key: Key, ...args: Args): ReturnType<Target[Key]>
{
  const method = target[key];
  return method(...args);
}

The magic happens in the constraint of Target. We constrain it to be a Record where the key is of type Key. The value type is a function with Args as its parameter types. The return type of the function is typed using the utility-type ReturnType.
Using a generic type for Arg also allows for type-safety inside the function implementation. This would be errors:
function foo<
  Target extends Record<Key, (...args: Args) => any>,
  Args extends unknown[],
  Key extends PropertyKey
>(target: Target, key: Key, ...args: Args): ReturnType<Target[Key]> {
  const method = target[key];

  method("abc")
  //     ~~~~~ Argument of type '[string]' is not assignable to
  //           parameter of type 'Args'

  return 123
  //     ~~~ Type 'number' is not assignable to type 'ReturnType<Target[Key]>'
}

This is how calling the function would look like:
// valid
const result = foo(obj, "c", "Peter");

// invalid
foo(obj, "a")
foo(obj, "c", 123)

Playground


Systems of equations word problems in high school Algebra

Question: I'm not sure how to set up the equations to solve a problem like:
Flying to Kampala with a tailwind a plane averaged 158 km/h. On the return trip the plane only averaged 112 km/h while flying back into the same wind. Find the speed of the wind and the speed of plane in still air.
Comment: $x+y = 158$ where $x$ is the wind and $y$ is the plane's speed, then you have $-x + y = 112$. I'll leave the rest to you.
Answer: If you call $v_p$ the speed of the plane and $v_w$ the speed of the wind then
$$v_p+v_w=158\\
v_p-v_w=112$$
Now solve the system.
Answer: Let W and P be the speeds of the wind and the plane respectively.
Then you have that $$W+P=158$$ and $$P-W=112$$
Adding the two equations gives $$2P=270$$ or $$P = 135$$ so $$W=23$$
Answer:
Flying to Kampala with a tailwind a plane averaged 158 km/h.

$$
v + w = 158
$$

On the return trip the plane only averaged 112 km/h while flying back
  into the same wind.

$$
v - w = 112
$$

Find the speed of the wind and the speed of plane in still air.

The linear system has been stated, now solve for $v$ and $w$.


Is there any case in which evaluation of outliers does not render probabilistic sampling deterministic?

Question: As I understand it, probability sampling means that every element in the population has a nonzero probability of being selected as part of the sample. But when some elements have a nonzero probability of being removed from the sample, it means not every element in the population has a nonzero probability of being included in the sample, prior to the sample data being processed by a statistical test. Also, it is pointless to evaluate outliers unless the probability of acting on the results of such an evaluation is nonzero. In contrast, the probability of pruning or treating unevaluated elements (inliers) is zero. Hence, just looking for outliers is akin to selective profiling, and seems to violate the assumption that a sample is a random sample.
Some helpful definitions of true and false outliers etc found in "A review of approaches for the detection and treatment of outliers in processing wind turbine and windfarm measurements.
M. Zou, S Djokic, ENERGIES 2020 13 (6) 4228 PUBLISHED 15 August 2020
Comment: I find this unclear. How does looking for outliers violate simple random sampling? There are various things you can do when looking for outliers, above just removing them.
Answer: I think it's helpful to consider what you would do if you had the entire population.  The basic idea of design-based inference is that you have an estimation procedure that you wish you could run on the population, but you can't. Instead, you run it on a probability sample. Your goal is to estimate the same thing that you would estimate given the population.
Suppose you would, given the population, compute a robust location estimator such as the median or a trimmed mean or a mean trimmed at $\pm 2$ times a robust scale estimator, or otherwise delete the outliers.  In that case you should do the same thing for your probability sample: the trimmed/winsorised/outlier-deleted summary of the sample will estimate the same thing as the same estimator of the population.
This would be a reasonable thing to do if, for example, you suspected that the variable was subject to gross measurement errors and wanted the mean of the non-erroneous values, or if you thought the variable would be long-tailed and you wanted a good estimate of its centre.
On the other hand, if you would just take the mean of the population, that's what you should do to the sample. If you instead delete outliers, you're not really taking advantage of the probability sample. Whether you say it isn't really a probability sample anymore is a semantic point. My guess is that the majority use of the words would be that it is still a probability sample, but that's just a guess.
Comment: Presume I have complete unknowledge of the population. I am a blind analyst. The parameter of interest is the Extremal Quotient (EQ). Sampling randomly and then removing deviates (by whatever process) because they are very large, even though I have no knowledge of whether they are true or false outliers (see Zou &Djokic above); might that bias my sample statistic (i.e. underestimate the population EQ)?
Comment: I didn't assume you knew anything about the population, just about *what analysis you would do* if you had the population data. If you don't know, a probability sample isn't going to help.


Passar valor para TextView

Question: Estou passando um valor para um textview, porém que fazer isso depois que a minha váriavel receber este valor.
public class ariesFragment extends Fragment
{
public String[]textoSeparado2;

        public ariesFragment()
    {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        //executando MyAsyncTask
        MyAsyncTask myAsyncTask = new MyAsyncTask();
        myAsyncTask.execute();

        View view = inflater.inflate(R.layout.fragment_aries, container, false);
        TextView text = (TextView)view.findViewById(R.id.textAries);

        if(textoSeparado2 == null)
        {
            text.setText("ERROR VOCÊ NÃO TEM UMA CONEXÃO COM A INTERNET");
            System.out.println("erro");
        }

        else
        {
            text.setText(textoSeparado2[5]);
        }

        return view;
    }

    private class MyAsyncTask extends AsyncTask
    {
        @Override
        protected Object doInBackground(Object[] params)
        {
            HttpURLConnection conection;
            try
            {
                //Configuração de conexao
                URL url = new URL("http://meusite");
                conection = (HttpURLConnection) url.openConnection();
                conection.connect();

                // Lendo os dados

                InputStream inputStream = conection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                //Storing data

                String line = new String();

                while ((line = bufferedReader.readLine())!= null)
                {
                    textoSeparado2 = line.split("\\|");
                    System.out.println(textoSeparado2[0]);
                    //System.out.println(line);
                }

                //Close Conection
                inputStream.close();
                conection.disconnect();

            }

            catch (MalformedURLException e)
            {
                e.printStackTrace();
            }

            catch (IOException e)
            {
                e.printStackTrace();
            }

            return  null;
        }

        @Override
        protected void onPostExecute(Object o)
        {
            super.onPostExecute(o);
        }
    }
}

Ele busca no arquivo php na internet, porém quando verifica se o meu array tem está nulo, diz que sim, pois ainda não tenho valores nele e só depois irá receber.
Como faço para passar o valor para o textview depois da busca no arquivo php?
Tentei de várias formas e não consegui
View view = inflater.inflate(R.layout.fragment_aries, container, false);
TextView text = (TextView)view.findViewById(R.id.textAries);

Utilizando isto consigo passar para a textview.
Agradeço desde já
Answer: Você pode criar um método para carregar esse TextView.
private void carregarTexto(String texto) {
    TextView text = (TextView)view.findViewById(R.id.textAries);
    text.setText(texto);
}

E o seu AsyncTask deveria ser assim:
private class MyAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        ...
        String texto; //Use essa variável ao invés de textoSeparado2
        ...
        //Close Conection
        inputStream.close();
        conection.disconnect();

        return texto;
    }

    @Override
    protected void onPostExecute(String result)
    {
        carregarTexto(result);
    }
}

Note que alterei o tipo do AsyncTask (consequentemente do método doInBackground e onPostExecute).
Comment: não entendi como fazer, fiz desse jeito e me tenho muitos erros... principalmente na criação do método para o text view

Passar valor para TextView


How to check statistical significance?

Question: I have a machine which produces belts with normalized length of 30 cm. Now there is the assumption that the machine works incorrectly and produces belts with a slightly lesser length.
From a test with 100 measurements a mean value of 25 and a standard deviation of 3 cm have been acquired. How could one check these data against a significance level of 0.05? I am somehow stuck..
Comment: What have you tried?  Look up "students $t$" test or $z$ scores.
Comment: Can you compute the t statistic in the computer output in my Answer. What is the critical value for a one-sided t test at the 5% level with $n = 100$ observations?
Answer: From Minitab, which accepts summary data, here is output for an appropriate test. The null hypothesis that the population mean remains $\mu = 30,$ is strongly rejected. (Because only summary data are provided, there is no way to check whether data are normal, as required for this one-sample t test.)
<code>One-Sample T

Test of μ = 30 vs < 30

  N    Mean  StDev  SE Mean  95% Upper Bound       T      P
100  25.000  3.000    0.300           25.498  -16.67  0.000
</code>

How to check statistical significance?


Matlab: assign to matrix with column\row index pairs

Question:
Possible Duplicate:
How can I change the values of multiple points in a matrix?

I have a matrix A and three vectors of the same length, r, holding the indexes of the rows to assign to, c, holding the indexes of the columns to assign to, and v containing the actual values to assign.
What I want to get is A(r(i),c(i))==v(i) for all i. But doing
A(r,c)=v;

Doesn't yield the correct result as matlab interprets it as choosing every possible combination of r and c and assigning values to it, for instance
n=5;
A=zeros(n);
r=1:n;
c=1:n;

A(r,c)=1;

Yields a matrix of ones, where I would like to get the identity matrix since I want A(r(i),c(i))==1 for each i, that is only elements on the diagonal should be affected.
How can I achieve the desired result, without a for loop?
Comment: @Amro - While I agree the answers to both questions are very similar, the questions are different - I wanted to know how to assign to a matrix, while the other question wants to know how to covert a matrix into a vector. One wouldn't reach the other question when looking for an answer to my question.
Comment: I did not down-vote you, I simply linked to the other question as being similar (as opposed to voting to close as duplicate)..
Comment: similar question: [Converting a matlab matrix to a vector](http://stackoverflow.com/questions/1931545/converting-a-matlab-matrix-to-a-vector)
Comment: possible duplicate of [How can I change the values of multiple points in a matrix?](http://stackoverflow.com/q/6850368/52738)
Answer: OK, I've found the answer - one needs to use linear indexing, that is convert the column\row pairs into a single index:
idx = sub2ind(size(A), r,c);
A(idx)=v;


Size concious method for logging in C#

Question: I have a program that report exceptions to my server. I'd like to also send a complete log of the current session when the exception happens. Since this is a bug report, I'd like to condense it to a tidy little datastream with one or two characters per action. Examples of actions are things like: Clicks File Menu, Opens new spreadsheet, saves current workspace. One method might be to make a key where say each letter in the alphabet represents a particular action, then decode it on my server. This might be problematic if I want to add strings to the log though. (Example: Opens File "example.txt") Is there perhaps a more object oriented approach to this that doesn't sacrifice size and automates the encoding/decoding? I'm just brainstorming here so any suggestions or recommendations are most welcome.
Thanks!
Comment: I'd urge you to consider about user's privacy.  What if the user was typing in his password right before the exception happened?  I recon she'd be rather unhappy to learn that the developer of a crashed application just got a part of her password
Answer: Have you considered whether you need to be "size conscious" at all. Here's a trot through some metrics:
Supposed you have 1000 errors per day, and suppose each error takes up 1k of data. That's about 1MB per day. After a yeah you're going to be at around 350MB of error reporting. OK.
They're fictional numbers but in any case those kinds of metrics seems trivial to me especially since they're also rather overblown... Are you expecting more than 1000 error events per day? Are your individual errors going to be larger than 1k? Are you logging to an embedded device? Probably not.
Comment: @Andre: i liked your post too. Alas, i'm out of votes for the day. :-(
Answer: My opinion is:
You may use exceptions for any purpose, in general, but as you are considering to send exceptions to the server, then you might be using exceptions to represent a programming fault, that is, something you'd be concerned about.
These kinds of exceptions are meant to be rare, your software won't have a dozen of them and throw many times a day. If so, why do you have to be compress so much the information youre sending to the server? Why don't you just GZIP the callstack along with some log4net logging and send it to the server? You'll save time.
Answer:
I'd like to condense it to a tidy little datastream with one or two characters per action

The easiest thing is to save what you want in some convenient (e.g. plain text) format, and then compress it using some standard compression tool: let the compression algorithm work out how to compress it.
Answer: I would just use the command pattern and a persistent background thread sitting in a loop calling the .Execute() method on all the objects coming in to be processed.  then you get the benefit of being able to throttle the db writes, more easily batch db writes, and maybe even use bcp to transfer the data.  you can always archive/delete old exception info too.

Size concious method for logging in C#


How can I make a dictionary with a single value from repeated numbers in a csv file

Question: I am new to Python and want to create a dictionary for my csv file. My data has a format like:
c1     c2     p    trade
GER   USA     1     100
GER   ITA     1     80
JPN   ITA     2     120
USA   GBR     1     70
DNK   CAN     2     100
USA   DNK     2     70
DNK   GER     1     40
FRA   GER     4     50
USA   GER     6     80

I intend to create a dictionary that its keys be countries (c1 and c2) and the values be products(p). Something like this:
dic_c1c2_products={"GER": 1, 4,6 "USA":1,2,6 "ITA": 1,2, "JPN": 2 "GBR":1, DNK:"2,1 "CAN":2 "FRA:4}

I have written the following code but it does not work properly:
rfile = open('filepath','r')
dic_c1c2_products = {}
for i in rfile :
    lns = i.strip().split(',')
    c1 = lns[0]
    c2 = lns[1]
    p = lns[2]
    if not dic_c1c2_products.has_key(c1) and not dic_c1c2_products.has_key(c2):
         dic_c1c2_products[c1] = [p,]
         dic_c1c2_products[c2]=[p,]
    elif dic_c1c2_products.has_key(c1) and not dic_c1c2_products.has_key(c2):
         dic_c1c2_products[c2]=[p,]
         if p not in dic_c1c2_products[c1]:
              dic_c1c2_products[c1].append(p)
   elif not dic_c1c2_products.has_key(c1) and dic_c1c2_products.has_key(c2):
         dic_c1c2_products[c1] = [p,]
         if p not in dic_c1c2_products[c2]:
             dic_c1c2_products[c2].append(p)
    elif dic_c1c2_products.has_key(c1) and dic_c1c2_products.has_key(c2):
         if p not in dic_c1c2_products[c2] and dic_c1c2_products[c1]:
             dic_c1c2_products[c1].append(p)
             dic_c1c2_products[c2].append(p)

Any help would be appreciated.
Answer: You can use collections.defaultdict :
import csv
from collections import defaultdict
d= defaultdict(set)

with open('eggs.csv', 'rb') as csvfile:
     spamreader = csv.reader(csvfile, delimiter=',')
     for row in spamreader:
          i,j,k=row[:3]
          d[i].add(k)
          d[j].add(k)

All you need is create a defaultdict with a set object as its value then loop over your rows and insert 1st and 2nd as its key and add the 3rd element to set value.
Answer: I'd use the csv module here to read the format, rather than manually split.
Collect your values into set objects, so you only get unique values:
import csv

with open('filepath', 'rb') as infile:
    reader = csv.reader(infile)
    dic_c1c2_products = {}

    for c1, c2, p, trade in reader:
        dic_c1c2_products.setdefault(c1, set()).add(int(p))
        dic_c1c2_products.setdefault(c2, set()).add(int(p))

The dict.setdefault() call inserts an empty set() object if the key (c1 or c2) isn't already present in the dictionary.
Demo:
>>> import csv
>>> sample = '''\
... GER,USA,1,100
... GER,ITA,1,80
... JPN,ITA,2,120
... USA,GBR,1,70
... DNK,CAN,2,100
... USA,DNK,2,70
... DNK,GER,1,40
... FRA,GER,4,50
... USA,GER,6,80
... '''.splitlines()
>>> reader = csv.reader(sample)
>>> dic_c1c2_products = {}
>>> for c1, c2, p, trade in reader:
...     dic_c1c2_products.setdefault(c1, set()).add(int(p))
...     dic_c1c2_products.setdefault(c2, set()).add(int(p))
...
>>> dic_c1c2_products
{'GER': set([1, 4, 6]), 'FRA': set([4]), 'USA': set([1, 2, 6]), 'JPN': set([2]), 'DNK': set([1, 2]), 'ITA': set([1, 2]), 'GBR': set([1]), 'CAN': set([2])}
>>> from pprint import pprint
>>> pprint(_)
{'CAN': set([2]),
 'DNK': set([1, 2]),
 'FRA': set([4]),
 'GBR': set([1]),
 'GER': set([1, 4, 6]),
 'ITA': set([1, 2]),
 'JPN': set([2]),
 'USA': set([1, 2, 6])}


Android application - saveEventually() and saveInBackground() callback methods are not functioning

Question: In our Android app, we are using saveEventually() and saveInBackground() of parse sdk (version 1.8.0).
It seems to work fine mostly but sometimes all calls to saveEventually and saveInBackground fail with the callback not getting called.
when this happens, we are still able to fetch data from Parse i.e. all read queries work.
We are using local storage. The updates start working again once we clear the app data.
What could be causing this?
Comment: Please refer: http://stackoverflow.com/questions/24897231/saveinbackground-callback-doesnt-work
Answer: It's because Parse.enableLocalDatabse() is on. I had this one before - it's hard to get to this point (it took me couple of days to figure it out). So get rid of this one in Your Application class and it should work.
Oh, and get latest version 1.10.3


Shiny DT Styling Cell colors

Question: I am attempting to load a file perform various preprocessing steps including subsetting the data. I am doing this all in a single reactive function and then assigning the various formated dataframes to a list to "export" out of the render function. The challenge I am running into when I display the tables renderDT only likes a data frame object, which was ok until I tried to figure out how to color certain cells. All the examples I found for styling cells requires a datatable object not a dataframe. See example: https://rstudio.github.io/DT/010-style.html
I am trying to color column C based on the following rules [1,10] = green, [11,19] = yellow, and [20,25] = red. I appreciate any suggestions on how to modify renderDT to allowing stlying of cells. Also does anyone if there is a way to change the font size inside the table?
require(readxl)
require(openxlsx)

 mydata<-structure(list(A = c(2, 2, 2, 6, 7, 8, 6, 7, 8, 6, 7, 8, 1, 1,
 1, 1, 2), B = c("A", "A", "N", "O", "L", "L", "O", "L", "L",
 "O", "L", "L", "A", "N", "N", "N", "A"), C = c(1, 2, 3, 4, 5,
 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 20, 24)), class = "data.frame", row.names = c(NA,
 -17L))

 runApp(
  list(
    ui = fluidPage(
      titlePanel("Import QUEST, Design, & Mitigation Lists"),
      sidebarLayout(
        sidebarPanel(
          fileInput('file1', 'Choose QUEST xlsx formatted file',
                    accept = c(".xlsx")
                   )),
        mainPanel(
          tabsetPanel(type = "tab",
                      tabPanel("Tab1", DTOutput('first')),
                      tabPanel("Tab2", DTOutput('second'))
                     )))),
    server = function(input, output){
      mydata1 <- reactive({
        req(input$file1)
        inFile <- input$file1
        mydata<-read_excel(inFile$datapath, 1)

        data1<-mydata[which(mydata<3),]
        data2<-mydata[which(mydata>6),]
        quest<-list(data1,data2)
        quest })

        output$first <- renderDT({as.data.frame(mydata1()[1])})

        output$second <- renderDT({as.data.frame(mydata1()[2])})

    }
))
shinyApp(ui, server)

Answer: As you said, you need to style a datatable object and pass this object to the renderDT function.
Any other arguments you want to pass to the renderDT now need to be moved to the DT::datatable constructor, see examples in this other post.
For font-size, see also this other post.
Answer: You have to pass a datatable in renderDT:
output$first <- renderDT({
  datatable(as.data.frame(mydata1()[1])) %>%
      formatStyle(
        columns = "C",
        backgroundColor = styleInterval(c(1,11,20), c("white", "red", "green", "yellow"))
      )
})

Shiny DT Styling Cell colors


Asymptote of largest root of polynomial of order $n$

Question: I have a (log-) polynomial root equation given by
$$
f(n) = \log_2\left( \text{LargestRoot} \left[
\lambda^n - 3\sum_{i=0}^{n-1} \lambda^i = 0
\right]\right)
$$
The final equation of interest is then the fractional loss of $f(n)$ from 2:
$$
L(n) = \frac{2-f(n)}{2}
$$
Numerical solution for small $n$ is plotted below, and shows clear log-linear asymptotic behavior. The line shown is fit using $n \in [5, 20]$. I would like an analytical solution for the asymptote but don't see how to get there. Any help would be much appreciated.
Answer: Let's first simplify the equation:
$$
\lambda^n-3\sum_{i=0}^{n-1}\lambda^i=\lambda^n-3\frac{1-\lambda^n}{1-\lambda}=0
$$
and thus
$$
\lambda^{n+1}-4\lambda^n+3=0
$$
(which has the same roots as the original equation, and an additional one at $\lambda=1$ because we multplied by $\lambda-1$). Since the largest root appears to be converging to $\lambda=4$, let's substitute $\lambda=4+\epsilon$:
\begin{eqnarray}
(4+\epsilon)^{n+1}-4(4+\epsilon)^n+3
&=&
4^{n+1}+4^n(n+1)\epsilon-4^{n+1}-4^nn\epsilon+3+O\left(\epsilon^2\right)
\\
&=&
4^n\epsilon+3+O\left(\epsilon^2\right)
\\
&=&
0\;.
\end{eqnarray}
Thus $\epsilon\approx-\frac3{4^n}$, which yields
\begin{eqnarray}
f(n)
&=&
\log_2(4+\epsilon)
\\
&=&
\log_24+\log_2\left(1+\frac\epsilon4\right)
\\
&\approx&
2+\frac\epsilon{4\ln2}
\\
&\approx&
2-\frac3{4^{n+1}\ln2}
\end{eqnarray}
and thus
\begin{eqnarray}
L(n)
&=&
\frac{2-f(n)}2
\\
&\approx&
\frac3{8\ln2}4^{-n}
\end{eqnarray}
and
\begin{eqnarray}
\log_{10}L(n)
&\approx&\log_{10}\left(\frac3{8\ln2}\right)-n\log_{10}4
\\
&\approx&
-0.27-0.60n\;,
\end{eqnarray}
in agreement with your fit result.
Comment: Beautiful. Thanks!


LLVM NVPTX Backend with CUDA5 Dynamic Parallism

Question: Does LLVM's NVPTX backend (contributed by NVIDIA) have any support for the new Dynamic Parallelism feature found in CUDA5 / Compute Capability 3.5 devices?
Answer: I found some information in the CUDA Dynamic Parallelism Programming Guide, in the section titled "Device-Side Launch from PTX." It seems that a function called cudaLaunchDevice()  is accessible from PTX and the user just has to declare this function in PTX and then call it:
<code>// When .address_size is 64
.extern .func(.param .b32 func_retval0) cudaLaunchDevice
(
.param .b64 func,
.param .b64 parameterBuffer,
.param .align 4 .b8 gridDimension[12],
.param .align 4 .b8 blockDimension[12],
.param .b32 sharedMemSize,
.param .b64 stream
)
;
</code>
So I suppose suppose that the answer is to declare this function in LLVM IR and then just use it. I have not tested this solution.


Show that the function it is a cumulative distribution function of some random vector

Question: Show that the function
$$F(x,y)=\left\{\begin{array}{l}
(1-e^{-x})(1-e^{-y}) & \text {if} x \geqslant 0, y \geqslant 0\\
0 & \text {in another case}
\end{array}\right.$$
it is a cumulative distribution function of some random vector
Normally it is asked to calculate the distribution function, here how to show that it actually comes from a random vector
Comment: You have to find $f\ge 0$ such that $F(x,y) = \int_{-\infty}^x\int_{-\infty}^y f(s,t)\,dt\,ds$. I suggest to make the ansatz $f(s,t) = g(s)g(t)$.
Comment: @eren . See my answer. The method 2 I suggest is the most general. Othwewise if you follow what @ amsmath suggest , then you can do the following. Since you are asked to show that it is a cdf of "some random vector" , you explicitly provide them with the particular random vector, i.e. (X,Y) where X and Y are iid exp(1). Then you just use the density argument.
Answer: First, whitout doing calculations, observe that your $F_{XY}$ is the joint CDF of two exponential iid with parameter 1.
But to solve the question, simply apply the properties of any cumulative bivariate CDF:
$$F_{XY}(-\infty;y)=0$$
$$F_{XY}(x;-\infty)=0$$
$$F_{XY}(x;+\infty)=F_X(x)$$
$$F_{XY}(+\infty;y)=F_Y(y)$$
$$F_{XY}(+\infty;+\infty)=1$$
Answer: To show that a function is a cdf for a one dimensional random variable you need to show the following things:-
Method 1:-
1:- $F$ is non decreasing
2:-$\lim_{x\to\infty}F(x)=1$
3:-$\lim_{x\to -\infty}F(x)=0$
4:-$F$ is right continuous at all points. That is for a fixed $x\in\mathbb{R}$ . If you have a sequence of real numbers $x_{n}\to x$ such that $x_{n}\geq x\forall n\in\mathbb{N}$. Then $\lim_{n\to\infty}F(x_{n})=F(x)$.
You can easily verify these properties for $F(x)= 1-e^{-x}$.
Now you use that if $Y$ is another random variable which is iid as $X$. Then their joint cdf will be the product of the individual cdf's . As you have verified that $F$ is a cdf. Hence you can conclude that the joint cdf found by multiplying is also a cdf.
Method 2:-
Otherwise you just show the analogues of these 4 conditions in 2 dimension.
1.:- $F(x,y)\leq F(x,y')$ if $y\leq y'$
$F(x,y)\leq F(x',y)$ if $x\leq x'$
2.$F_{X}(x)=\lim_{y\to\infty}F(x,y)$ . Where $F_{X}(\cdot)$ denotes the marginal cdf of $X$. Similarly $F_{Y}(y)=\lim_{x\to\infty}F(x,y)$.
3.$\lim_{x\to-\infty}F(x,y)=0$ and $\lim_{y\to-\infty}F(x,y)=0$
4.$\lim_{(x,y)\to(\infty,\infty)}F(x,y)=1$
5.If $x_{n}\geq x$ and $y_{n}\geq y$ be two sequences such that $x_{n}\to x$ and $y_{n}\to y$. Then $\lim_{n\to\infty}F(x_{n},y_{n})=F(x,y)$
6.$F(x',y')-F(x',y)-F(x,y')+F(x,y)=P(x<X\leq x' , y<Y\leq y')$ where $x'\geq x$ and $y'\geq y$.
The verification of 1-5 is mostly the same. The only slightly harder one is 6. Now you can go by either way.
These holds because of a theorem that a function satisfying these 6 properties must be a joint-cdf for some random variables. And for the 1 D case , any function satisfying the four proerties must be a cdf of some random variable.


Two subgroups being conjugate

Question:
As with the element-wise conjugation action, for $H$ and $K$ subgroups of $G$ in the same $G\text{-orbit}$ under this action, say that $H$ and $K$ are conjugate.

I know that $Gs_o = \lbrace gs_o\ :\ g ∈ G\rbrace$ can be one orbit for G-orbits, but I am not just getting what "same $g\text{-orbit}$" means.
If I am somehow mistaken, can anyone show me where I got wrong in the meaning of G-orbits and relate it to the comprehension of the quote?
Answer: Let $\mathcal{S}$ be the set of subgroups of $G$.
For $H \in \mathcal{S}$ and $g \in G$, we denote $gHg^{-1}$ by $g.H$.
Then $G$ acts on $\mathcal{S}$ by $H \rightarrow g.H$.
If $H, K \in \mathcal{S}$ are in the same $G$-orbit in this action, we say $H$ and $K$ are conjugate.
Answer: The $G$-orbit (under conjugation) of a subgroup $H$ is the set of subgroups of the form $gHg^{-1}=\{ghg^{-1}:h\in H\}$ for some $g\in G$. When we say that two subgroups $H$ and $K$ are in the same $G$-orbit, we mean that there is some $g\in G$ such that $gHg^{-1}=K$.

Two subgroups being conjugate


CSS Files from separate to single one

Question: I have 2 CSS Files for few pages, if i put everything just in one css file, my pages does not load the contents of the css file i have deleted, but actually i have moved it into the main css (style.css)
if i keep them separate , the pages load the contents of the 2 css files
Here the example:
http://tommywebdesigner.com/Vision%20General.html - it loads 2 separate css files nav.css and style.css
when i deleted the nav.css file and move the content into one single css file named style.css, the page doesnt read anymore the nav.css content into the style.css
here the example : http://tommywebdesigner.com/Home%20Page.html
Why this happens?
Comment: what about missing closing bracket for `@media (max-width: 979px) {`
Comment: Both examples, same file `/css/style.css` and missing closing bracket  for `@media (max-width: 979px) {`
Comment: no Vison General loads style.css and nav.css, Home Page.html loads just style.css which actually has the nav.css content too
Comment: that was the problem i have put the nav.css content before the
@media (min-width: 1200px) and now it's loading. Terrible mistake and missing.
Answer: For me,
the navigation looks same. What browser you have??
Try delete cache. It sometimes don't load new css style.

CSS Files from separate to single one


How to stop Node.js application using forever module on Windows?

Question: I have gone through so many questions regarding forever module for nodejs APP, but did not find my answer.
Forever module is working fine on a Linux box but now I am putting my APP on Windows 7 and trying to run it with forever.
First i installed forever module as
npm install forever -g

after that I ran my app as
forever start app.js

it's running fine by saying file app.js is running with forever and I am accessing my app successfully.
When I execute a command forever stop app.js I get the error

no forever file is running

Please suggest me if anyone has used forever on windows that how can I stop my application on Windows.
Comment: I suggest running your Node.js app as a service.  Check out http://nssm.cc/.  There are also NPM packages for this purpose.
Comment: Try `forever stopall` command, it may work
Answer: use forever list
then forever stop with the id, e.g. forever stop 0
Here is a sample output
user@some-server]$ forever list
info:    Forever processes running
data:        uid  command                                                  script forever pid   id logfile                          uptime
data:    [0] 9Xzw ng serve --host 0.0.0.0 --port 4009         13164   29579    /home/ec2-user/.forever/9Xzw.log 7:1:20:50.412
data:    [1] wOj1 npm run-script app-start-dev                                    29500   24978    /home/ec2-user/.forever/wOj1.log 0:0:5:3.433

Here 0 is like an index which is in the first column of the output. If there are two processes running, we can use indexes like 0 or 1 to stop the first or the second process.
forever stop 0 OR forever stop 1
Answer: I had this same issue and found that it was because I was running forever start with sudo (on Linux) so that I could run a production site on port 80. This did the trick:
sudo forever list

Answer: This is just to expand on @laktak's answer.  The result of forever list on Windows will look something like this:
info:    Forever processes running
data:        uid  command              script                          forever p
id   id logfile                               uptime
data:    [0] an1b "C:\nodejs\node.exe" C:\sbSerialWidget\server.js 8780    1
0152    C:\Users\username\.forever\an1b.log STOPPED

I wasn't sure which one was the ID initially, but I figured out that it was the first entry after the second data field above, so the line you're interested in is with the ID bolded & italicized:
data:    [0] an1b C:\nodejs\node.exe C:\sbSerialWidget\server.js 8780    1
0152    C:\Users\username.forever\an1b.log STOPPED
So to stop this particular instance, you'd run:
forever stop 0
Hope this helps someone else who was confused like I was
Comment: Yes, this was confusing. The doc says you can stop by id, pid, script, but only the `[0]` seems to work
Answer: It's a bug in windows https://github.com/nodejitsu/forever/issues/337
If you need to stop your app just open task manager and find node.js process and kill it. Hard but work.
Comment: You can also kill all Node processes from the command line with:
`taskkill /f /im node.exe`
That'll kill all running instances of Node at once.
Answer: forever stop 0
where the 0 is the index of your app running, if you just have one so is 0.
Answer: You can follow the forever documents there are all commands related to forever.
Forever
 $ forever --help
      usage: forever [action] [options] SCRIPT [script-options]

      Monitors the script specified in the current process or as a daemon

      actions:
        start               Start SCRIPT as a daemon
        stop                Stop the daemon SCRIPT by Id|Uid|Pid|Index|Script
        stopall             Stop all running forever scripts
        restart             Restart the daemon SCRIPT
        restartall          Restart all running forever scripts
        list                List all running forever scripts
        config              Lists all forever user configuration
        set <key> <val>     Sets the specified forever config <key>
        clear <key>         Clears the specified forever config <key>
        logs                Lists log files for all forever processes
        logs


Beautiful Indefinite Integrals.

Question: These are some of the integrals with beautiful solutions I came across-
$$\int \frac{x^2}{(x\sin x+\cos x)^2} dx$$
$$\int\frac {1}{\sin^3x+\cos^3x} dx$$
$$\int \frac{1}{x^4+1}dx$$
I'd love if you share some of the ones you came across.
Comment: I believe this should be a community wiki though...
Comment: I know perception of beauty is subjective, but what do you see as beautiful about the solution of the third integral, for example?
Comment: Define "beautiful".
Comment: @mirgee actually, second one integrates pretty ugly too.
Comment: I've always been very fond of the integrals of $\sec{x}$ and $\sec^3{x}$.
Comment: @Kaster: The graph is pretty though... :)
Comment: http://en.wikipedia.org/wiki/Lists_of_integrals
Comment: Here is a link that goes thorugh the evalutation of some pretty tough indefinite integrals. http://www-sop.inria.fr/cafe/Manuel.Bronstein/publications/issac98.pdf
Comment: @Mirgee- Breaking the numerator into $\frac{x^2+1-(x^2-1)}{2}$ in the third is quite neat trick to me.
Comment: Related : http://math.stackexchange.com/questions/403167/find-the-value-of-int-frac-x2x-sin-x-cos-x2-dx
Answer: This isn't indefinite. But it's crazy
$$ \int_0^{\pi/2} \frac{ d \theta}{\sqrt{a^2\cos^2\theta +b^2 \sin^2\theta }} = \frac{\pi}{2AGM(a,b)} $$
Where AGM is the arithmetic geometric mean.
Answer: \begin{align}
I_1 & = \int \sqrt{ \sqrt{ x + 2\sqrt{2x-4} } +
                       \sqrt{ x - 2\sqrt{2x-4} } } \,\mathrm{d}x \, , \quad x>4\\
I_2 & = \int \log( \log x) + \frac{2}{\log x}  - \frac{1}{(\log x)^2} \mathrm{d}x \\
I_4 & = \int (1 + 2x^2) e^{x^2}\,  \mathrm{d}x \\
I_5 & = \int \frac{\sqrt{x+\sqrt{x^2+1\,}\,}\,}{\sqrt{x^2+1\,}\,}  \mathrm{d}x \\
I_6 & = \int \frac{2^x 3^x}{9^x - 4^x} \,\mathrm{d}x
\end{align}
\begin{align*}
    I_7
         = \int \left( \frac{\arctan x}{x - \arctan x}\right)^2 \mathrm{d}x
         = \frac{1 + x \arctan x}{\arctan x - x}
  = \frac{1}{\tan (\beta - \tan \beta)}\,,
\end{align*}
where $x = \tan \tan \beta$ or $\beta = \arctan (\arctan x)$.
$$
I_6 = \int \frac{x^2+2x+1+ (3x+1)\sqrt{x+\ln x}}{x\,\sqrt{x+\ln x}(x+\sqrt{x+\ln x})}\mathrm{d}x
= 2 (\sqrt{x+\ln x} + \ln(x+\sqrt{x+\ln x})) + C
$$
I have a bunch more of these here, see p.68 for instance. (click on the problems for solution)
Comment: awesome work, thank you for posting this!
Comment: The link seems to be dead, where can I get the solutions of these?
Answer: $$\int\dfrac{x^{4n}(1+x^{4n})}{1+x^2}dx$$
Why? Because from $0$ to $1$ they give good approximations of $\pi$. See this
Comment: cleverly constructed!! (+1)
Answer: $$\int (\sqrt {\tan x}+\sqrt{\cot x})dx=\sqrt 2\arctan\dfrac{\sqrt{\tan x}-\sqrt{\cot x}}{\sqrt 2} +C$$
Answer: Wolfram alpha gives time exceeded on this one :
$$\int\dfrac{(x-1)\sqrt{x^4+2x^3-x^2+2x+1}}{x^2(x+1)}dx=\sqrt{t^2+2t-3}-\ln{(t+1+\sqrt{t^2+2t-3})}+\sqrt 3 \arcsin{\dfrac{t+5}{2(t+2)}}+C$$
where $t=x+\dfrac 1 x$
One does not simply integrate this.
Comment: I don't understand the reason of the downvote. '+1'
Answer: $$\int \left| \sin{ax} \right|\,dx = {2 \over a} \left\lfloor \frac{ax}{\pi} \right\rfloor - {1 \over a} \cos{\left( ax - \left\lfloor \frac{ax}{\pi} \right\rfloor \pi \right)} + C$$
$$\int \left|\cos {ax}\right|\,dx = {2 \over a} \left\lfloor \frac{ax}{\pi} + \frac12 \right\rfloor + {1 \over a} \sin{\left( ax - \left\lfloor \frac{ax}{\pi} + \frac12 \right\rfloor \pi \right)} + C$$
Answer: The Gaussian integral isn't indefinite but its derivation and answer are still remarkable:
$$\int_{-\infty}^{+\infty} e^{-x^2}\,dx = \sqrt{\pi}$$

Beautiful Indefinite Integrals.


How can I compute inverse matrix using cofactor?

Question:
if $A^{-1}=(b_{ij})$, compute $b_{23}$ using cofactor.
$$ \begin{pmatrix} 1&2&3\\ 0&0&4\\ 5&0&1 \end{pmatrix} $$

I know matrix of cofactors can be obtained by transpose of matrix $A$ and computing cofactors.
But, how can I compute determinant of $A$ which is $3\times 3$ matrix? or Is there are other solutions that not to use determinant?
Answer: But the determinant is easy to compute:   $\left |\begin{matrix}1&2&3\\0&0&4\\5&0&1\end{matrix}\right|=-4\cdot \left|\begin{matrix}1&2\\5&0\end{matrix}\right |=-4\cdot-10=40$.
(This was done by Laplace expansion, or expansion by minors,  along the second row:  you actually get $$-0\cdot A_{21}+0\cdot A_{22}-4\cdot A_{23}$$.)
Comment: I mean how can I compute determinant of $A$, not $A_{23}$
Comment: That's what I computed.  You can go along the middle row...  (it's just a coincidence that it involves $A_{23}$)
Comment: Then, how can I compute inverse of $A_{23}$
Comment: Well, you want $b_{23}$, right?  I believe you need the transpose of the matrix of cofactors.   The cofactor $A_{32}=-4$.  So I'm getting $-\frac1{10}$. Check me on this...
Comment: Umm... how did you compute determinant? Is there a formula to compute? It seems like you used cofactor in your answer.
Comment: I did.  It's called expansion by minors.  The first two ($A_{21}$ and $A_{22}$) get multiplied by zero.
Comment: You used cofactor and multiplied by 4, how did you get 4?
Comment: Thank you Chris


Clarify if the topological sum on $\Bbb R^n\times\Bbb R^n$ is equal to the usual topology.

Question:
For a collection $\mathscr{X}=\{(X_j ,\mathcal{T}_j):j\in J\}$ of topological spaces let be $X:=\bigcup_{j\in J}X_j$ and for each $j\in J$ let be $\iota_j:X_j\rightarrow X$ the inclusion map defined through the condition
$$
\iota_j(x)=x
$$
for any $x\in X$ and thus let be $\mathcal{F}=\{\iota_j:j\in J\}$ the collection of such functions. So we say that $X$ is the topological sum of the collection $\mathscr X$ if it is equipped with the final topology induced by the collection $\mathscr F$ as above defined.

So now I ask to clarify if it is true that the usual product toplogy on $\Bbb R^n\times\Bbb R^n$ is equal to the topological sum induced by the collection $\mathscr{X}:=\Big\{\{x\}\times\Bbb R^n:x\in\Bbb R^n\Big\}$ where $\{x\}\times\Bbb R^n$ is obviously equipped with the subspace topology induced by the product topology of $\Bbb R^n\times\Bbb R^n$. So could someone help me, please?
Answer: Obviously not, as the topological sum is disconnected and the product topology on $\Bbb R^n \times \Bbb R^n$ is not (it's just $\Bbb R^{2n}$ so connected as can be).
Comment: Oh yeah! This because $\bigcup_{x\in\Bbb R^n\setminus\{\xi\}}\Big(\{x\}\times\Bbb R^n\Big)$ and $\{\xi\}\times\Bbb R^n$ for any $\xi\in\Bbb R^n$ are two disjoint open sets with respect sum topology whose union is just $\Bbb R^n\times\Bbb R^n$, right?
Comment: @AntonioMariaDiMauro Indeed they are.
Comment: Okay, all clear. Thanks too much for your assistance!


Bisector of angle between lines

Question: enter image description here
My attempt-
(3x-6y-5)/3root(5)=(x+2y-11)/root(5)
this gives
3y=7
but both my answer and the correct answer are not matching as well as it says that it contains (1,-3) which when substituted in the correct answer does not satisfy it.
Comment: Where did you come across that question.
Comment: Online test series
Comment: Can you share the link please?
Answer: The two bisector lines are

$x=\frac{19}3$
$y=\frac{7}3$

and no one contains the point $(1,-3)$.
Comment: why they say (1,-3)
Comment: Maybe it's just a typo.

Bisector of angle between lines


android.test.InstrumentationTestRunner completing with 0 tests

Question: I have a robotium test that I instrument as follows:
<code>adb -s 169.254.255.1:5555 shell am instrument -w
<my test project identifier>/android.test.InstrumentationTestRunner
</code>
Earlier today, it was working correctly, running my test cases and finishing. However, now it completes
Answer: The answer to this question was to check the following:
- class name has "Test" in it
- testing method is public, and starts with the text "test"


EditText inTextInputLayout calls onTextChanged twice for first letter only

Question: I am developing an open source text masker. You can click here to see source code.
My problem is that, when I wrap my custom edit text with TextInputLayout, onTextChanged is being triggered twice only for first letter. Then it works as expected.
This "twice call" breaks my logic. Do you guys have any idea what might be the problem? Since it is being used by other developers, I don't want to fix it with hacky solution. I need to find out the problem.
I set text manually after removing text watcher, then I add text watcher again.
Here is my main logic;
This method is being called only once;
<code>   private fun initTextWatcher() {
        textWatcher = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                masker?.onTextChanged(s, start, count, before)
            }
        }
        addTextChangedListener(textWatcher)
    }
</code>
And this is how I set my text manually;
<code>    private fun setEditTextWithoutTriggerListener(newText: String) {
        removeTextChangedListener(textWatcher)
        onTextChangedListener?.invoke(newText) // This is a custom listener.
        setText(newText)
        setSelection(text?.length ?: 0) // This puts cursor at the end of the text.
        addTextChangedListener(textWatcher)
    }
</code>
To handle hint position like TextInputEditText does, I simply copied it's functions into mine.
<code>
    override fun getHint(): CharSequence? {
        val layoutHint = getTextInputLayout()?.hint
        return layoutHint ?: super.getHint()
    }

    override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
        val ic = super.onCreateInputConnection(outAttrs)
        if (ic != null && outAttrs.hintText == null) {
            outAttrs.hintText = getHintFromLayout()
        }
        return ic
    }

    private fun getTextInputLayout(): TextInputLayout? {
        var parent = this.parent
        while (parent is View) {
            if (parent is TextInputLayout) {
                return parent
            }
            parent = parent.getParent()
        }
        return null
    }

    private fun getHintFromLayout(): CharSequence? {
        val layout = getTextInputLayout()
        return layout?.hint
    }

</code>
And my class extends AppCompatEditText like TextInputEditText does.
Comment: is initTextWatcher() called from onCreate? try putting addTextChangedListener() in onResume
Comment: @SharoneLev I was calling `initTextWatcher()` in `init` scope. I moved it into `onAttachedToWindow()`, now it is working! Thanks a lot!
Comment: Great, please mark the answer
Answer: If you are calling addTextChangedListener() from onCreate() or init() move the call into onResume() or any other function called later, otherwise onTextChanged() is triggered before the resume


How are differences in R2 of two models with/without variable A related to the (partial) eta2 of variable A in the extended model?

Question: Assume I have two models:
m1: Y = B0 + B1*X1 + e
m2: Y = B0 + B1*X1 + B2*X2 + e
How is the difference in R-squared between m1 and m2 related to the (partial) eta-squared of B2 in m2?
Answer: It's indeterminate.  What does exactly specify the difference between the r-squared of the two models is the semipartial r-squared of X2, also known as its part r-squared.  This tells the amount of r-squared uniquely, or incrementally, accounted for by X2.
You can contrast this with the partial r-squared (aka the partial eta-squared), which identifies the relationship between X2 and Y when X1 is controlled. The partial r-squared will be similar to the standardized regression coefficient and allows an estimate of the direction and strength of the relationship with Y.  The semipartial is a different animal; it's all about the portion of the predictive contribution that's unique to each predictor.  The semipartial will always be <= the partial.
Comment: In many cases you can essentially substitute r for eta or verse-vica.
Comment: Thanks, this helps! When you mention semipartial r-squared, is this the same as eta-squared (not the partial eta-squared)?


Prove that, in the process of growing an array incrementally from size 0 to size $n$, approximately n^2 values must be copied.

Question: Suppose that a precisely sized array is used to hold data, and that each
time the array size is to be increased, it is increased by exactly one and the data are copied over.
Prove that, in the process of growing an array incrementally from size $0$ to size $n$, approximately $n^2$ values must be copied.

so here what I have tried. p.s I have no idea what I am doing here. I get that in order to loop though array of numbers than the timing is $n$.

<code>[1] = 1 value
 |
[1, 2] = 2 values
 |  |
[1, 2, 3] = 3 values
 |  |  |
[1, 2, 3, 4] = 4 values
 |  |  |  |
[1, 2, 3, 4, 5, ..., $n$] = $n$ values
</code>
Answer: The first array has 1 value, the next has 2, the next has 3, and so on. We want to sum these, giving
$$\sum_{k=1}^{n}k = \frac{n(n+1)}{2} = \frac{n^2 + n}{2} = O(n^2) $$
Note that the above is true because of the following:
$$1+2+3+4+5+6+...+n$$
$$= n+(n-1)+(n-2)+...+1$$
If we add the corresponding terms of each series we get $(n+1)+(n+1)+(n+1)+...(n+1)$
This series has $n$ terms as well, yielding $(n+1)n$. We know that is the series added to itself, or the series multiplied by two. Thus, we have to divide by two, yielding $\frac{n(n+1)}{2}$
It would be very difficult for me to explain $O$ notation, so I recommend looking that up.
Answer: Okay so for n=2, you have n-1 (1) copies.
For n=3 you've got an ADDITIONAL n-1 copies (2)
For n=3 you've got an ADDITIONAL n-1 copies (3)
......
You just have to sum your <code>|</code>s
As you should know:

$$\sum_{i=1}^ni=\frac{1}{2}n(n+1)=\frac{1}{2}n^2+\frac{1}{2}n$$

That's where your squared comes from in the complexity.
See it now?


Visual Studio 2017 crashed after changing text zoom

Question: Several issues releted to zoom in VS 2017 text editor. Actually, I don't know if problem has started right after installation or later since I haven't used zoom function before.

CTRL + scrolling doesn't work and result in window prompt (then text just goes 3 lines down and up)
CTRL + . or CTRL + , results in
another window prompt
Selecting any value in the combo box leads to VS crash with a message like this:
<code>Problem signature:
Problem Event Name: CLR20r3
Problem Signature 01:   devenv.exe
Problem Signature 02:   15.0.26403.7
Problem Signature 03:   58f0354e
Problem Signature 04:   Microsoft.VisualStudio.Shell.15.0
Problem Signature 05:   15.0.26403.7
Problem Signature 06:   58f032e2
Problem Signature 07:   1e28
Problem Signature 08:   18
Problem Signature 09:   System.UnauthorizedAccess
OS Version: 6.1.7601.2.1.0.256.49
Locale ID:  1045
Additional Information 1:   0a9e
Additional Information 2:   0a9e372d3b4ad19135b953a78882e789
Additional Information 3:   0a9e
Additional Information 4:   0a9e372d3b4ad19135b953a78882e789
</code>
Comment: I would suggest you report this to Microsoft, I don't know if SO is the place to solve such crashes. VS2017 is still (fairly) new, so it may be a bug.
Comment: Possible duplicate of [How do I diagnose and fix a Visual Studio 2015 crash?](https://stackoverflow.com/questions/43850977/how-do-i-diagnose-and-fix-a-visual-studio-2015-crash)
Comment: System.UnauthorizedAccess = access denied. look at the dump or also run ProcessMonitor and look which operation of devenv.exe fails with access denied
Answer: I had the same issue.
Deleting the folder below solved the issue for me.
C:\Users\Your_user_name\AppData\Local\Microsoft\VisualStudio\15.xxxxx


Is it Necessary to Follow Chord Instruction Above Grand Staff (Piano)?

Question: From old posts on this website, I understand that for piano sheet music, the letters above the grand staff represent chords to be played— and these chords can be played instead of the single notes on the staff. But is it necessary to follow these chord instructions above the staff, or can I simply play the notes on the staff?
I am attaching an example of this from "We Wish You a Merry Christmas," in which, for example, instructions for an E7 chord are written above a single E note for the left hand. In this situation, can I simply play the single E note, or do I have to play the E7 chord instead?
Comment: As a side note, the more usual harmony is for this bar to be played over a C major triad throughout.  For a common variation of the tune, in which the tune goes down to a C on the '-mas' of 'Christmas', the harmony given here would produce consecutive octaves with the bass line.
Answer: You can just play the notes on the grand staff.
To be exact: the notes on the staff are a specific arrangement of the chord symbols above the singing line. The chord symbols are there as information to the player who wants to change (simplify for example) the proposed arrangement or wants to play the song on a different instrument (a guitar for example).
Answer: You don't have to do either. If you wished to play the piece verbatim, then you'd play what's written on the stave. Exactly. The 'E7' is there to guide another muso, usually a guitar player, as to which chord is appropriate for that part of that bar. The notes constituting the E7 chord are there being played by the right hand anyway, with the usual root in the bass. So, it's an entity in itself, although if you wished, you could add extra notes  - choose from E, G#, B and/or D, in the left hand.


Dúvidas sobre instalação e uso do PHP

Question: Boa noite
Como posso fazer para funcionar a linguagem PHP, e qual versão escolher?
S.O Windowns 10, para uso local.
Comment: Procura o xampp....
Answer: Para que possa utilizar o PHP em sua maquina localmente, você deverá instalar um ambiente que faz o papel de servidor do seu projeto. Pacotes como WAMP ou XAMPP são os mais comuns de serem utilizados para este cenário.
Eu particularmente utilizo e gosto mais do XAMPP mas o WAMP também é muito bom.
Neles você terá todas as ferramentas que precisará inicialmente para a programação utilizando a linguagem PHP.
No entanto, recomendo que faça uma pesquisa sobre como criar seus projetos com estas ferramentas. Algumas configurações básicas podem ser necessárias para que consiga desfrutar de uma perfeita utilização.
Aqui neste link Como utilizar o XAMPP para criação de um servidor local, você encontra um exemplo de tutorial básico de utilização do XAMPP.
Sobre a versão acredito que vá depender mais da sua necessidade. Caso não tenha nenhum motivo específico, busque utilizar a versão mais recente da tecnologia que vá usar.

Dúvidas sobre instalação e uso do PHP


Can't finish my web-site validator regular expression

Question: I am preparing to my exams and I am stuck at RegEx validation. I would like to validate an entered web-site. I've surfed for a solution here, but have not found any which will fulfill my needs. For example these links should be validated:

http://www.yahoo.com/cheers/peter.aspx
http://www.yahoo.com/asd/
http://www.regularexpressions.com/reference.html
http://www.gandon.com/

and this should not:

http://www.radsoftware.com.au/articles/regexsyntaxadvanced.aspx

For the moment the closest expression I got is:
<code>http://(www\.)([^\.]+)(\.com)(/([^\.]+)(\.html|\.aspx))?
</code>
It can be a little bit dirty, since it is my first deal with regexes
But in regexTester it highlights/accepts (I am using regexpal):

http://www.yahoo.com from #2 (without /asd/)
http://www.yahoo.com/cheers/peter/steven/mar s.aspx from #6 (although there are spaces)
http://www.radsoftware.com from #5 (but should not accept it at all)
http://www.gandon.com from #4 (without / , but it is not so critical)

What should be changed in my regex?
P.S. Sorry for such a long story, I am just a beginner.
Comment: Can you formalize the rules of validation? Which urls should pass, which should not?
Comment: Why is this tagged both `java` and `C#`?
Comment: emm.. i am not sure what do you mean by that, but the links which should be validated I wrode at the top. (mby I just did not got your question).
Comment: So, you have only these six links to validate? Or there may be other links passed to your program?
Comment: I need the links would be validated with everything before .com and if there are some /ttt/sss they could be closed with .html|.aspx or without them (just .com/some/word)
Comment: 6) should fail because of the spaces, but why should 5) //www.radsoftware.com.au/articles/regexsyntaxadvanced.aspx fail?
Comment: at the moment i tried just these, because it is not a big and serious project so it could be enough for explanation, however of course it would be nice to have validated some links as http://www.forum.ru-board.com either with something like ebay.co.uk, but as I could not finish with those links I even have not started thinking about that
Comment: Beaner, just in my RegEx I did not have something like .com.au :)
Comment: Is this a duplicate of http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url ?
Comment: @asdewka You should indicate exactly what language you are using these Regexes in, so that this question can be tagged appropriately. Different languages will use different Regex engines, so details will differ.
Comment: Andrew Barber I can use both, it is up to me, however right now I study c#
Comment: Problem solved, thanks to David Wallace.
Comment: Then I recommend this question be closed as a duplicate.
Answer: The only difference that I see is whether it has multiple top-level domains (like co.uk or com.au).
Therefore that is what i check for:
<code>^.*www.[a-zA-Z]*.[a-zA-Z]{1,3}/([a-zA-Z].*|)
</code>
that actually just checks whether it has only a single TLD and optionally some more parts in the URL.
I do NOT validate whether it starts with HTTP:// as that is no actual requirement for an URL. I also do not check the document type (html or aspx) as that can be variable or even named as well.


Laravel 5.2 Multi sms

Question: How to explode multi sms number on laravel 5.2?
 public function store(Request $request)
{
    $mes = new Outbox();
    $mes->DestinationNumber = $request->input('DestinationNumber');
    $explode = explode(' ',$mes->DestinationNumber);
    return $explode;
}

Comment: Share `var_dump($mes->DestinationNumber)` please
Comment: can you show what `$request->input('DestinationNumber')` is
Comment: What will be the output you want? Can you give an example.
Answer: This is not a Laravel related question.
Find the documentation from the PHP web and use your logic.
It depends how you have $mes->DestinationNumber stored and how you want them to return from your function.
// CSV to array
$result= explode(',', $mes->DestinationNumber);

// array to CSV
$result= implode(',', $mes->DestinationNumber);

Check before you convert and return your result:
var_dump($mes->DestinationNumber);
// your logic here ..
var_dump($result);exit;

Laravel 5.2 Multi sms


Somar valores de uma string atribuindo valores as letras (Python)

Question: Objetivo:
Atribuir valores a uma string baseada em um dicionario com chaves e valores
Exemplo:
Tenho uma string neste formato:
str = 'ABCD'
e um dicionário neste.
dic = {'A' : 71, 'B' : 103, 'C' : 115, 'D' : 129}
Script
for i in aa:
    soma += dic.get(i, 0)
print(round(soma, 3))

Problema a resolver:
Necessito criar um laço for para atribuir valores a 'str' e somar. Tipo 71 + 103 + 115 + 129 e dar o valor final da soma (418) e se eu atribuir n valores no dicionário o programa seja capaz de me dar a soma final.
Obrigado a todos que puderem ajudar....
Leo
Comment: Olá LCalado, Bem-vindo ao Stack Overflow em Português. Na sua pergunta você está apenas compartilhando o enunciado de um exercício. O que você já tentou? A ideia do site não é fazer o seu trabalho da faculdade ou lição de casa para você, mas se você estiver com dificuldade em alguma parte específica, compartilhe o seu código, diga o que já tentou fazer e qual está sendo a dificuldade, assim você aumenta as suas chances em conseguir uma boa resposta.
Comment: Obrigado Anthony, farei da próxima vez!!!Neste caso fiquei tentando sair do lugar e não consegui, talvez pela grande inexperiência, tanto aqui no stack quanto com a linguagem.
Comment: `print(sum(dic[i] for i in str))`
Answer: Para o caso específico, isso resolve
str = 'ABCD'
dic = {'A' : 71, 'B' : 103, 'C' : 115, 'D' : 129}

soma = 0
for l in str:
    soma += dic.get(l, 0)

print(soma)

O resultado acima é 418
O fato de utilizar o dic.get() é para o caso da letra ou outra coisa não estar no dicionário e, neste caso, o valor atribuído é 0 (zero)
Exemplo:
str = 'MNOPQ'

Como nenhuma das letras está naquele dic, o resultado da soma será 0 (zero)
Comment: Obrigado Paulo, já apliquei aqui!!!! Muito agradecido pela explicação!!!


Technical reasons for not having large background images in websites

Question: Most websites tend to have either a solid color as background, or a small image that is repeated. Why aren't more websites using a large image (such as a photo) as background? I can think of the following reasons:
1) Problems with different screen resolutions. Too small and gaps start to appear on the left and/or right side for higher resolutions, too big and lower resolutions only show part of the image.
2) Bandwidth. Although this is unlikely to be a problem for most websites.
Are there any other reasons why such backgrounds are not being used more often?
Comment: I don't think you have any reasons (except for bandwidth) for **large** images that aren't reasons for **any** image.
Answer: You've pretty much identified the two main reasons, but the most important one is bandwidth.  Depending on the type of image, you'd be best to consider all those users in your target audience whose technical limitations mean that sitting and waiting on a dial-up connection (they're still out there, you know) will alienate them.
In addition to the time and resource cost of sending large images down the pipe to your users, the usability issues of forcing the user to wait for the image to load and the impact of readability of content mean that background images should best be limited to tileable, scalable or small UI enhancements rather than full UI features.
Comment: Dial-up-ers can disable images - *even IE* has that feature. ;) What do you mean with "scalable"?
Comment: You shouldn't be expecting users on lower-level ISP plans to conform to your site's design, you should design your site to include them, not impede them.  By "scalable" I mean a small image (e.g. 1~2kb) whose height or width can be expanded to make it appear larger.
Answer: I think that images as background have a tendency of making the text difficult to read.. :)
Comment: Valid point, and a lot of people seem to dislike it. That's why I named this question "technical reasons for ..." :)
Answer: Your assumption about bandwidth not being a problem is unfounded. This is an illustration of global broadband availability (source):

And that's not including cell phones, which are probably the fastest growing group of devices used to connect to the Internet. Finally, the fact that you took the ergonomic aspects out of the discussion (narrowing it to technical aspects) makes it more of an "academic" discussion as you've excluded the main reasons not to use large background images (i.e. readability).
Comment: I didn't want to discuss the design aspects because it depends largely on the actual design, which makes it difficult to discuss here. The statistics about broadband penetration are very insightful, and in direct contrast to the "everyone used broadband nowadays" mantra.
Comment: The mantra is a result of these sorts of discussions taking place in this sort of social environment where these sorts of people are usually armed with some heavy-duty computer equipment and consequentially know as much about the "average Internet user" as any prime minister knows about the cost of a bottle of milk or loaf of bread, which is "not much".
Answer: Background is not part of the content of your website, it's here to make it more clear.
Pictures are part of the content, and the complexity make the text harder to read.
Comment: I disagree. Bad background images make the text hard to read - it's got nothing to do with complexity.
Comment: That's what I meant by complexity.
Answer: I think that the main problem is about resolution, but with CSS3 we will forget thanks to the new property Background-size
Comment: Resolution? Are you refering to liquid-width layouts?


Can you add a 'select all' option to a webform_select_options_list?

Question: I have a webform that collects a list of flagged items. I'd like to add a "select all" option, because the list can get fairly long (50+) selections, and it can be tedious to manually check the boxes.
I'm using webform with views, sessions, and custom webform_select_options_info function.
Any ideas?
Answer: The Checkall module enables this functionality for any checkboxes form element.

This module provides an extension to the builtin checkboxes element
  that allows developers add "check all" / "toggle" / "uncheck all"
  actions to them. This is specially useful for checkboxes that have a
  lot of elements.

A hook_form_alter() on your webform with this module should get you there.
Comment: so, I'm looking at this now, and it says I need to update the system to 7.8, Is that the drupal core?
Comment: Yes, you need system (core) greater than 7.8. Looking at [the module](http://cgit.drupalcode.org/checkall/tree/checkall.info?h=7.x-1.x), it looks like it has the format of its .info incorrect; it should be `dependencies[] = system (>= 7.8)`. The 7.x branch is still in dev so there's likely to be other bugs.


Logistic Regression in R with different results when I want interaction effect

Question: My dependent variable is Accuracy (that takes 1 or 0 for right and wrong). My IVs are Emotion (Sad, Happy; coded as 1,2 respectively), Load (high or low coded as 1,2 respectively) and Group (Group A and Group B; coded as 1,2 respectively).
I'm running a logistic regression in R using the following formula:
model1 <- glm(Accuracy ~ Emotion + Group + Load, data = file_name, family = Binomial(link = "logit")

summary(model1) gives me a result that I can interpret. However, I notice that the Emotion and Group variables are followed by a number:

I'm new to logistic regression, but I'm not sure why its giving a specific result for an emotion. Why does it say emotion2 instead of emotion? Usually, in ANOVA, I get a simple effect of IVs and then I look inside to know the sub-factors affecting the DV. Why is this different?
Moreover, I'm interested in knowing the interaction effect. So, I executed another command:
model11 <- glm(Accuracy ~ Emotion * Task * Group, data = file_name,
      family = binomial(link = "logit"))

summary(model11) gives me something completely different. I had expected that the main effect will be the same for the two models (model1 and model11), but this is not the case.

Can anyone explain why this is the case?
Answer:
why does it say emotion2 instead of emotion

Emotion is likely coded as a factor.  The model assumes that emotion=1 is the comparison group.  The coefficient for emotion 2 is the log odds ratio of emotion=2 as compared to emotion =1.

summary(model11) gives me something completely different

Those are huge odds ratios.  I suspect there is some strong correlation between covariates causing these enormous odds ratios.
Comment: The covariates aren't necessarily correlated--this looks like an experiment, they're probably orthogonal. Rather, there is complete separation here.


Adicionar classes a um software em tempo de execução

Question: Pergunta

Há algum recurso que alguma linguagem disponibiliza para poder-se adicionar em tempo de execução uma classe ao software em execução, ou seja, o software a reconhecer e assim poder instanciar objetos dessa classe e manipulá-los?

Imaginemos a seguinte situação:
Tomemos com exemplo a linguagem Java. Temos essa classe abstrata disponibilizada como esqueleto para que os usuários possam implementar:
public abstract class TypeGeneral {

    MyAttribute my_atr;   // um objeto qualquer que toda implementação
                          // de TypeGeneral tem que ter
    public General(MyAttribute e) {
         my_atr = e;
    }

    public abstract void run();    // <==

    public MyAttribute getAttr() { /*...*/ }
    public MyAttribute setAttr(MyAttribute e) { /*...*/ }

    // ...
}

Eu queria saber se há algum recurso que dê a possibilidade que, após o usuário fazer a sua classe estendendo a TypeGeneral, e assim implementando o método run(), possa, em tempo de execução, adicioná-la ao sistema que está executando, e o sistema, reconhecendo-a, faça manipulações com o objetos da mesma.
Vi algo sobre Reflection, mas não soube adaptar ao meu  problema. Alguém se dispõe?
Linguagens preferenciais

Java
Python
C#
C++
Comment: Java tem o ClassLoader, veja se te atende: [http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html](http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html)
Comment: Alguém sugere um título melhor? Não edite, sugira aqui mesmo.
Comment: Isso é altamente dependente da linguagem e do ambiente de execução. Seria interessante restringir mais o seu domínio.
Comment: Sei que tem jeito, mas eu Java eu não sei os detalhes de como fazer.
Comment: Em qual linguagem você sabe @bigown? Pode ser em uma das outras 3 que citei... Vou olhar aqui @Piovezan
Comment: A pergunta tem a *tag* [tag:java], até para não ficar ampla.
Comment: Por exemplo em um ambiente Web @Pablo Almeida, com alguma dessas linguagens, onde o servidor receberia de cada usuário suas implementações e retornasse para cada um a funcionalidade adicionada pela sua implementação.
Comment: Eu coloquei ``java`` por conta do exemplo que apresento @bigown kk
Answer: Isso é muito comum em Java. Os drivers JDBC, por exemplo, são carregados na memória por meio desse tipo de mecanismo. Isso é útil nas situações onde não é possível saber a priori (em tempo de desenvolvimento) a classe que será instanciada.
Um pequeno exemplo. Suponha que exista a seguinte classe em seus sistema:
package com.company;

class TesteClasseDinamica {
    public int x;
    public int y;
}

Suponha agora que você esteja em outra classe e queira instanciar um objeto da classe com.company.TesteClasseDinamica de maneira dinâmica:
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    Class clazz = Class.forName("com.company.TesteClasseDinamica");

    TesteClasseDinamica t = (TesteClasseDinamica) clazz.newInstance();
    t.x = 2;
    t.y = 3;

    System.out.print(t.x);
    System.out.print(t.y);
}

Note que, nesse cenário, para instanciar um objeto da classe TesteClasseDinamica utiliza-se o método newInstance() da classe Class.
Isso é muito importante em JDBC, pois a interface precisa ser genérica, de forma a atender qualquer banco de dados relacional. Como não é possível prever qual será a implementação (driver JDBC) utilizado pela aplicação, utiliza-se esse mecanismo para instanciar o driver de forma dinâmica.


Add a class to a page element contained in a particular url

Question: I want to create a class for the title bars of pages that contain a certain piece of url.
My url is www.domainname.com/poste/XXX and I want to add the class only if the part after the .com contains only /poste/.  I've seen examples for "contains this term" but it's not exactly what I'm looking for.
The existing class for the title bar is: .fusion-page-title-bar
Thanks in advance for the help and advice!
Comment: [How to check if the URL contains a given string?](https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string) and [How to add a class to a given element?](https://stackoverflow.com/questions/507138/how-to-add-a-class-to-a-given-element)
Comment: @Wimanicesir Yes ! But how do I proceed for my application which is "contains only /poste/"?
Answer: to check if a url contains any string, do the following:
if(window.location.href.indexOf(".com/poste") > -1) {
       // do something
}

(checking if the index of a string is bigger than -1 is like asking if he is in there)
to conditonally add class:
element.classList.add("my-class");

combined it would be:
if(window.location.href.indexOf(".com/poste") > -1) {
       titleClass = document.querySelector(".your-title-class");
       titleClass.classList.add("conditionalClass");
}

*there are other solutions using jquery (like the one in @Wimanicesir comment), but it personaly prefer not using it :)
Comment: Both solutions provided in the comment are also without jQuery :) The first one has jQuery in it, but it's just used for the document ready. The important code is all vanilla JS. Even more, all the code you used here can be found back literately in those two posts.
Answer: If I understand your problem is that you want to check if the URL ends with /poste/.
You can use the string function endsWith().

  var url = window.location.href
  console.log('Current url: ', url)

  if (url.endsWith("js")) {
    console.log('The url ends with js');
  }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith


Windows module installer delaying login, server 2008 R2

Question: We updated our servers this weekend (windows updates), everything went fine except one of our terminal servers now hangs at login with the message, "waiting for windows modules installer." It eventually times out and leaves an event log message that the service has stopped unexpectedly. I have disabled the service and users can now login in a reasonable time frame. However we will need to re-enable the service in order to install further updates. I'm not sure where to start with this one, I'm an entry level admin and my colleagues are on vacation today, thank God this isn't a serious problem.
Further details:
-It affects all users.
-The only third party software on the server is our ERP software and screwdrivers from Tricerat.
-The only event log message is that the service has stopped unexpectedly.
-The server manager screen does not display any information about roles it just says, "error".
-The remote desktop roles all seem to be functioning properly, Remote app works as well as standard RDP.
Let me know if there is any further details I can provide, I will be checking this frequently throughout the day.
Comment: Okay so it stopped (for no reason) giving the waiting for windows modules installer message. However the roles still just say "error" and the trustedinstaller.exe is constantly crashing. I have tried to run the windows update readiness tool and that hangs for hours until I give up.
Answer: Be patient, give the server time to do what is needed, mine took nearly 30 minutes after going a disk cleanup on the C Drive. I would certainly let it go 30-45 minutes, a hard reboot when the server is deep in thought is not a good thing.
Comment: I was getting worried until I saw this answer.  I also had done a disk cleanup on C Drive and just needed to be patient.
Comment: Thank you. I was getting anxious before reading the answer. In my case, I ran Disk Cleanup, restarted the server,  the server showed "waiting for windows modules installer." for 20 minutes, then "Cleaning up, don not turn off your computer" for about 1 minute. I believe it was directory winsxs cleaning that caused this long delay.
Comment: This explains why "Disk Cleanup" offered to free 6 GB space through "Windows Update Cleanup", but failed to do so when I ran it. It might be doing that just now that I have rebooted...
Comment: I just ran in to this as well after running disk cleanup, and both the console prompt and RDP session login were delayed by 30 minutes. I did notice that the AD server, DNS server, DHCP server were all functioning after their normal (for our server) 60~120 seconds after the system startup event id 12. Also the remote management interface for "computer management" and "event viewer" were working. I also noticed that the available disk space did not start to get better until the message "Cleaning up...." appeared on the RDP screen, which was 25 minutes after startup event id 12. VM has 2GB RAM.
Comment: Microsoft should be more clear with these messages. For example, we cannot see "The installer is calculating free space" taking ages (it isn't calculating some obscure function in physics). Also a "cancel" button (for emergency situations) would be nice.
Answer: Hmm... I've never seen that problem, but here's my take:
Windows Updates needs to finish some post-update tasks and is unable to do so when a non-admin user logs on to the server.
My suggestion would be to log on to the console of the server with the local administrator or domain administrator account and allow Windows Updates to complete it's post-update tasks.
This is a pretty wild guess on my part, but it won't hurt to give it a try.
Comment: That does make sense to me, I'll give it a shot tonight and let you know how it goes.
Comment: No luck, I received the same message when logged into console from the DRAC.
Answer: This is an old thread but, since it was 1st result in Google, I thought I would add in a recent experience consistent with the first answer given.  After executing a cleanmgr of the system files and system drive defrag of a Windows 2008r2 server, I experienced the same message when reconnecting.  It to 4 hours to move to the next step - "Cleaning Up" which took another 2 hours.  In short - PATIENCE! - Wait it out - go home and go to sleep - it will probably be fine in the morning.
Answer: I would suggest to wait patiently for Windows to do its thing. I did a Gparted operation to shift a partition and this came up after the operations. It took 45 mins in total. I was getting impatient and wanted to reboot the system but I saw this thread and decided to wait. Thanks for all the advice.
Comment: How does this relate to the question?
Answer: I'm going to our data center for the weekend to do unrelated repairs so I'm just going to reinstall while I'm there. If anyone finds an actual solution to this problem let me know and I will accept it.
Answer: Like mentioned above, can take some time! I spent fair 2h of waiting for the title to pass "Please wait for the Windows Modules Installer" -screen. Then we got to next phase, which I did not type down. Some thing about installing updates or such. That took fair 1h too. At the end of the day, with waiting patiently and then giving fresh clean boot to Windows Server 2008 R2 OS, I got server running smoothly and issue of disk exhaust due to hickupping updates was gone. Server had 4Gb of disk remaining - when I started to reagt on this. Now it has 19Gb of free disk space. After initial wait and first reboot, it was only 13Gb of free, but then the second (clean reboot) got rid of some excess windowsupdate goo and now we are happy geegs here :)
Answer: you should just give it time, mine took like 10 hours to perform all updates and the message is gone. and I m able to login.
Comment: How is this different from the [highest voted answer](http://serverfault.com/a/740011/214507)?


Really slow torque 4 performance when adding simple key to criteria

Question: I have a really odd performance problem with torque. Look at the loop below. It takes 13 seconds to run as is.
But if I replace the line
                c.and(PicturePeer.ID,SimpleKey.keyFor(2072));
with
c.and(PicturePeer.ID,2072);
the same loop runs in 0.2 second. This make no sense, because it is exactly the same operation, which is getting the Picture with id=2072;
I even enabled full query logs on my PostgreSQL database, and the select query on the database does not change when I change which of the 2 c.add methods I use. So I don't understand why the second solution without the SimpleKey is 50 times faster then the first.
The reason I found out, is that
c.and(PicturePeer.ID,SimpleKey.keyFor(2072))
is the method used by retrieveByPK which kills my performance.
 con = Transaction.begin();
            long start=System.currentTimeMillis();

            for(int i=0;i!=1000;i++) {
                Criteria c=new Criteria();
                c=new Criteria();
                c.and(PicturePeer.ID,SimpleKey.keyFor(2072));
    //          c.and(PicturePeer.ID,2072);
                PicturePeer.doSelect(c,con);
            }
            long end=System.currentTimeMillis();
            long diff=end-start;
            System.out.println("Load diff=" + diff);

            con.rollback();

The Picture relation from schema.xml looks like this:

    <column name="id" primaryKey="true" required="true" type="INTEGER"/>
    <column name="filename" required="true" type="VARCHAR"/>
    <column name="name" required="true" type="VARCHAR"/>
    <column name="description" required="true" type="VARCHAR"/>
    <column name="role" required="true" type="VARCHAR"/>

If I call setLimit(1) on the criteria, the slow methods which uses the SimpleKey gets as fast as the fast method, so it looks like postgresql is using doing a table scan which make no sense to me. Especially since the version with slow and fast versions without limit gives exactly the same query log.
Here is the full log from postgresql. (The select 2 thing is the validate connection thing).
LOG:  execute <unnamed>: SET extra_float_digits = 3
LOG:  execute <unnamed>: SET extra_float_digits = 3
LOG:  execute <unnamed>: SELECT 2
LOG:  execute <unnamed>: BEGIN
LOG:  execute <unnamed>: SELECT picture.id, picture.filename, picture.name, picture.description, picture.role FROM picture WHERE picture.id=$1
DETAIL:  parameters: $1 = '2072'
LOG:  execute S_1: ROLLBACK

And just to be sure:
explain analyze SELECT picture.id, picture.filename, picture.name, picture.description, picture.role FROM picture WHERE picture.id=2072
Gives me:
 Index Scan using picture_pkey on picture  (cost=0.29..8.31 rows=1 width=46) (actual time=0.009..0.010 rows=1 loops=1)
   Index Cond: (id = 2072)
 Planning time: 0.043 ms
 Execution time: 0.022 ms

as expected.
Answer: In case anyone cares, I found the problem.
Torque ends up with a SimpleKey.keyFor value with the type BigDecimal. This causes problems because Postgresql then ends up not using its index when doing a select. (A type cast issue I guess).