Trying to run a regression on three variables that impact equity returns

Question: I have three variables a,b and c, which impact equity returns, y.
a is based on financial statements, so it is a quarterly figure.
b and c are calculated daily, and so are daily (only on trading days).
y is the quarterly return one quarter AFTER I get the first value for a.
I have historical data for each of these variables for about 3000 stocks. I can look at each sector differently, so narrowing down my universe is not an issue, but I will be looking at 300 stocks at the minimum for this.
My question, before I regress this, is - how do I account for the different frames here? Should a be continuous for a quarter and then change?
PS - I will use R.
Answer: It will depend a lot on what your specific data really is.  Consider, for example, if $a$ was the quick ratio.  It isn't actually a variable.  It is made up of variables.  Each of those underlying variables will have a distribution and so $a$ will be a ratio variable.
The variables will be highly correlated.  If you run a correlation on the accounting variables in the Compustat universe you will not find one that is less than .6 and some are nearly collinear.  Many of them are normally distributed or close to normal and so your variable, $a$, will not have a mean.  You will not be able to use anything that minimizes a squared error such as OLS or GLS.
Likewise, equity returns are a future price divided by a current price, which again is a ratio distribution.  This would be multiplied by future quantity divided by original quantity.  The future quantity will depend upon splits, bankruptcies, mergers and stock dividends.  You will need to account for each independent state.
The method of deriving the distribution of returns for a ratio is as follows.  If $$Z=\frac{Y}{X},$$ where $X$ and $Y$ are random variables then the distribution of $Z$ is $$p(z)=\int_{-\infty}^\infty{|x|f(x,zx)\mathrm{d}x.}$$
If you take the log of the returns and the log of the other ratios, assuming the model still makes sense if you do that, then you will get variables with a first moment.  However, it will generally be biased.  I tested the population of returns in the CRSP universe from 1925-2013 and the log approximation shifts the return two percent to the right and reduces the standard deviation by 4%.  This is because, for going concerns once liquidity costs have been removed, is the truncated Cauchy distribution.  Its log transform distribution is the hyperbolic secant distribution.
The hyperbolic secant distribution's mean is also the median of the raw data, but the truncation of the raw data shifts the median two percent to the right of the mode.
If you use the log transform, then you recover the ability to use methods based on least squares.  You are better off using a method that accounts for dividends as well.  Consider two different stocks, one that pays a dividend of all income and one that pays no dividend.  They should have differing distributions.
If the market is in equilibrium, then because stocks are traded in a double auction there is no winner's curse.  It follows from this that the logical behavior is to bid your expectation.  If there are many buyers and many sellers, then the distribution of bids is the distribution of expectations, so the prices will be bivariate normal around the equilibrium price.  In $R^2$  you could think of anywhere as $(0,0)$ via a transformation.  In the error space, the equilibrium errors are $(0,0)$.  If you integrate around the equilibrium with the above formula, then you will get the ratio of two normal distributions around $(0,0)$, or a Cauchy distribution.
However, consider a stock that pays 100% of its income in cash and let us assume that either $\delta_{t+1}\approx{c}$  or $\delta_{t+1}\approx{\delta_t}$.  In either case, the price should be the present value of the dividens and the return from dividends should be $$\frac{\delta_t}{f(\delta_t)},$$ which should just be the discount of the dividends.  This is essentially a variable divided by itself in some form.  It will tend to have a well-behaved distribution such as a log-normal distribution.
Dividend policy matters.
If you want to solve this for raw returns to get rid of the bias, then you will need to use either a Bayesian method or some version of quantile regression.  Theil's method of regression requires independence of the variables and they won't be independent.
The issue of quarterly reporting versus daily reporting isn't a concern.  Investors are using quarterly data to form beliefs, along with news data for competitors, vendors and events.  Nonetheless, you will just end up with a lot of ties in your independent variable.  If you have collected the date data of the disclosure versus the trade, then you can perform a separate analysis of daily data given announcements as events.  The challenge is that you have a handful of firms such as Coca Cola that provide daily data via press releases and so investors of firms such as Coca Cola have extensive continuous source data outside the officially promulgated quarterly financials.
If you have access to the date that the financials were promulgated, you could mediate the effect of the ties by including time since reporting as a variable.  The quality of old data could be thought of as decaying.  If you did this and possibly considered the impact of this decay on daily variables, you could construct a joint variable such as $f(\Delta{t})\times{b}$, to see if this decay is carried in other variables.  Again, it will depend in part on what $b$ and $c$ are.  I brought up the ratio issue because it can impact you through $b$ and $c$ as well and the idea of decaying information will no longer look the same, though how it looks will depend on what you are actually working with.  I cannot provide you assistance there.
See:

Curtiss, J.H. (1941) On the Distribution of the Quotient of Two Chance Variables. Annals of Mathematical Statistics , 12, 409-421.
Ding, P. (2014) Three Occurrences of the Hyperbolic-Secant Distribution. The
  American Statistician , 68, 32-35.
Fama, E.F. (1963) Mandelbrot and the Stable Paretian Hypothesis. Journal of Business, 36, 420-429.
Fama, E. (1965) The Behavior of Stock Market Prices. Journal of Business , 38,
  34-105.
Fama, E.F. and Roll, R. (1968) Some Properties of Symmetric Stable Distributions. Journal of the American Statistical Association, 63, 817-836.
Fama, E.F. and Roll, R. (1971) Parameter Estimates for Symmetric Stable Distributions. Journal of the American Statistical Association, 66, 331-338.
Gurland, J. (1948) Inversion Formulae for the Distribution of Ratios. The Annals of Mathematical Statistics , 19, 228-237.
Harris, D.E. (2017) The Distribution of Returns. Journal of Mathematical Finance, 7, 769-804.
Mandelbrot, B. (1963) The Variation of Certain Speculative Prices. The Journal of Business , 36, 394-419.
Marsaglia, G. (1965) Ratios of Normal Variables and Ratios of Sums of Uniform
  Variables. Journal of the American Statistical Association, 60, 193-204.
Marsaglia, G. (2006) Ratios of Normal Variables. Journal of Statistical Software , 16, 1-10.
Answer: Take a look at  MIDAS regression package, it provides tools for estimating time series  with mixed frequency.
Answer: Try using an xts() object to deal with the data.  You can merge the different time series, regardless of the mismatching times/dates.  Then, you can use na.locf() to roll-forward (not interpolate) the quarterly values down to a daily granularity, while also taking care of any pesky #N/A values in your dataset.  This way, you have daily values for the quarterly data, which are simply the most-recently-reported values.
Then, you can use standard lm() to run a regression directly on the xts object.  Quite handy, actually.


How to create a table during the module installation

Question: I'm trying to create a module for Drupal 7 and I need to create 3 tables and populate it. But first i need to create it.
In the file mymodule.install I have got
function mymodule_install() {

}

function mymodule_uninstall() {

}

function myodule_schema() {
  $schema['mymodule_table'] = array(
    'description' => t('First table'),
    'fields' => array(
      'id' => array(
        'description' => t('My unique identifier'),
        'type' => 'int',
        'unsigned' => true,
        'not null' => true,
      ),
      'list' => array(
        'description' => t('list'),
        'type' => 'varchar',
        'not null' => true,
      ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

What am I doing wrong?
Every time I test the module, I disable it -> uninstall -> Performance clear cache -> enable it.
Comment: If you have drush and devel installed you could use `drush devel-reinstall mymodule` to quickly reinstall your module
Answer: You're missing the length property for the varchar column ('list'). length is required so the CREATE TABLE query will fail.
From the Schema API docs:

All parameters apart from 'type' are optional except that type 'numeric' columns must specify 'precision' and 'scale', and 'varchar' columns must specify 'length'.
Answer: myodule_schema has a typo. An m is missing after the y.
Comment: Thanks BetaRide, it was a transcription mistake. I give you one vote up because you have read my post and actually I really found a spelling mistake on the name of the function eh eh


expected lowest value of 10 normally distributed values

Question: Consider 10 values that follow a standard normal distribution. What would you expect to be the lowest value?
I tried to simulate this problem in R. I basically just simulated 100000 standard normal distribution with 10 values and took the mean of the each lowest value.
<code>> mean(replicate(100000,min(rnorm(10))))
[1] -1.536875
</code>
This corresponds to a probability to get a lower value of
<code>> pnorm(-1.536875)
[1] 0.06216196
</code>
I tried to reach these values analytically but I really have no idea how to approach this.
I thought about it for quite some time now and also tried to look it up. But I can't find a solutions to this simple problem. Probably just overlooking something obvious.
Someone that can help me?
Comment: You're after the expectation of the distribution of the 1st [Order statistic](http://en.wikipedia.org/wiki/Order_statistic), or the expectation of the distribution of the minimum. If you look [here](http://mathworld.wolfram.com/OrderStatistic.html) it gives the general form for the density of the kth order statistic
Comment: See [here](http://stats.stackexchange.com/questions/77692/expected-value-of-minimum-order-statistic-from-a-normal-sample) and [here](http://math.stackexchange.com/questions/113266/expected-value-of-a-minimum) and the answer [here](http://stats.stackexchange.com/a/9007/805). If you use google you can turn up lecture notes on the topic (like [this](http://stat.duke.edu/courses/Spring12/sta104.1/Lectures/Lec15.pdf))
Comment: OK, if you know what you are looking for, you can indeed find a lot of information. Less straightforward then I thought. Thanks
Comment: Nevertheless the normal case has been well studied. Well, more has been written about the maximum, but that's just a matter of flipping about the mean (which for the standard normal is just taking the negative). There are tables, for example, and asymptotic approximations (which are a bit rough at n=10 but which I think do relatively well at higher n). The tables [here](http://faculty.washington.edu/heagerty/Books/Biostatistics/TABLES/NormalOrder.pdf) give an expected value for the maximum at n=10 of 1.53875.
Answer: As has been clarified by Steck (1962), results contained in Ruben (1954) lead to the following expression for the expected value of the $1$st (minimum) and $n$th (maximum) order statistic, of a sample of $n$ i.i.d standard normal random variables:
$$E[X_{(n)}] = -E[X_{(1)}] = \frac {n(n-1)}{2\sqrt{\pi}}\mathcal Z_{n-2}(0,...,0;\rho=1/3) $$
where $\mathcal Z_{n-2}() $ represents the multivariate standard normal cumulative distribution function of $n-2$ identical and equicorrelated standard normal random variables with common correlation coefficient $\rho=1/3$, all r.v's evaluated at $0$.
This is not an analytical solution, but this integral can be (and has been) evaluated.  For $n=10$ the value of the integral, as given in Gupta (1963) is
$\mathcal Z_{8}(0,...,0;\rho=1/3) = 0.06061$ and so we obtain
$$E[X_{(10)}] = -E[X_{(1)}] = \frac {10\cdot 9}{2\sqrt{\pi}}\cdot 0.06061 = 1.538799$$
Chen & Tyler (1999)  provide the following approximation to these expected values:
$$E[X_{(n)}] = -E[X_{(1)}] \approx \Phi^{-1}(0.5264^{1/n})$$
Where $\Phi^{-1}(\cdot)$ is the inverse (not the reciprocal) of the standard normal cumulative distribution function. They report that for $5<n<10$ this has less than $2$% approximation error, while for $n\ge 10$ the approximation error falls below $1$%. They derived this formula by the following approach: They asked "what would the expected value be if the distribution of the extreme order statistics was symmetric around the mean?" If it was symmetric the expected value would equal the value at the median, which is $\Phi^{-1}(0.5^{1/n})$. But since the distribution is not symmetric around the mean, they searched for a correction term, which lead them to the expression above. For $n=10$, this approximation gives
$$E[X_{(10)}] = -E[X_{(1)}] \approx \Phi^{-1}(0.5264^{1/10}) = \Phi^{-1}(0.937846) =1.536941$$
which has percentage approximation error  $-1.2074\cdot10^{-3}$, much less than $1$% $=10^{-2}$.


Greatest common divisor questions?

Question: An integer d is a divisor of a ⇔ ____ | ____.
Equivalently, d is a divisor of a ⇔ ____ mod ____ = _____.
 Is it possible for a divisor of a to be bigger than a?
The first blank would be d|a, and I am not sure about the second.
And for the third question, I believe so. But I am not sure how to explain why.
Comment: Sure, $2$ is a divisor of $-18$. Also, $17$ is a divisor of $0$. But if we restrict to positive integers, the answer is no.
Answer: $a$ mod $d$ = 0 <=> $d | a$.
Divisor of $a$ can not be bigger than $a$, because $d | a$ <=> $a = c * d$. If $d > a$, $c < 1$, and it is impossible.
Answer: $d$ is a divisor of $a$ if $a/d$ is whole, in other words if $a \pmod d = 0$.
If $d$ is a divisor of $a$ and $d>a$, what does $a/d$ look like?
Answer: think mod operator as the remainder.  If d divides a, the remainder should be zero by definition.  Also think what will be the maximum divisor of an integer number?
Answer:
$d|a$
$a=0 \mod d$
It depends. If we are talking about positive integers then no, but for rationals or reals it is possible.

Greatest common divisor questions?


Entire function with $f(0)=1$ and $f(1-1/n^2)=0$

Question: Can we find an entire function with the properties $f(0)=1$ and $f(\frac{n^2-1)}{n^2})=0$
We could have applied the Weirestrass Theorem to find such entire function with prescribed zeros.But ,
the problem is:
The sequence of roots of $f(z)$
$\{\frac{1-n^2}{n^2}\}_{n\geq2}$ has an accumulation point which is $1$. Thus we can not apply Weirestrass.
Another way I tried to approach is :
$$f(z)=\sum_{n=0}^\infty a_n z^n$$
$f(0)=a_0=1$ and $f(1-1/n^2) =1+ a_1 (1-1/n^2)+a_2 (1-1/n^2)^2+......$
If we choose large $n$ then we get $f(1)=1+a_1+a_2+a_3+.....   =0$ is this possible to have. I am kind of confuse on my work.
Any hints?
Comment: What important theorem mentions accumulation points?
Comment: The question in your post is different from the one in the title.
Comment: Weirestrass Theorem for finding entire function with prescribed zeros having no accumulation point . And sorry for typo
Comment: And far far earlier, there was another theorem that mentioned accumulation points of zeros.
Comment: Although no entire function exists, you can find such a function on $B(0,1)$, vanishing with order $1$ at each of those points. However, it cannot vanish say with order $n$ at $1-1/n^2$, since it would violate the Blaschke condition $\sum \mathfrak d(z)(1-|z|)<+\infty$.
Comment: Yes , identity theorem of holomorphich function mention about the accumulation points
Answer: Since $\left \{ 1-1/n^2 \right \}_{n=2}^\infty$ has a finite accumulation point, your function is uniquely determined by its values there. Here the values are all zero, so one holomorphic function with those values is the zero function. Since the function is uniquely determined by those values, no function with all your specified properties exists.
Comment: So $f(z)=0$ identically. but does not $f(0)=1$ disturb to apply this idea?
Comment: @mp100 Right. ${}$


Every number is the sum of three squares with signs

Question:
The question. Can every $n\in \mathbb N$ can be written:
$$n=a^2\pm b^2\pm c^2$$
where $\pm$ are signs of your choice?

We know with Lagrange's four-square theorem that every integer can be written as the sum of four squares.
Plus, with have Legendre's three-square theorem stated that an integer can not be written as the sum of three squares if, and only if, it is of the form:
$$4^k(8n+7).$$
So we just have to prove (or disprove) it for every number of this form.
I have checked it until $55$, and it seems to work so far. So the number we have to check are these ones.
For instance:
$$31=6^2-2^2-1^2$$
and
$$39=6^2+2^2-1^2.$$
The issue here is that $a$, $b$ and $c$ can be arbitrarily large. For instance:
$$183=14542^2-14541^2-170^2.$$
So I don't really know how to prove or disprove this result, and I think it could go either way.
Answer: Hang on, it's actually quite simple!
So suppose that we have a number $l$. Suppose that $l=pq$, with $p,q$ having the same parity. That is, both $p$ and $q$ are even, or both $p$ and $q$ are odd.
If this is the case, consider $a= \frac{p+q}{2},  b= \frac{p-q}{2}$. Then, note that $a^2 - b^2 = pq = l$!
For example, $183 = 61 \times 3$, so $a=32$ and $b = 29$, and $32^2-29^2 = 1024 - 841 = 183$.
Now, when can $l$ be written in this form? At least when $l$ is odd, because then you can split it into two odd factors (even if one of those factors is $1$ : for example $7=7 \times 1 = 4^2-3^2$) and carry out the above procedure.
Finally, given an even number, just subtract (or add!) $1^2=1$ to make it an odd number,which can be expressed as a difference of squares.
For example: given $39$, we can write $39=13 \times  3 = 8^2 - 5^2$. Given $78$, we can write $78 = 77 + 1 = 11 \times 7 +1 = 9^2-2^2+1^2$.
What is the reason for so much flexibility? Simple : $(a^2-b^2)$ has a non-trivial factorization, while $a^2+b^2$ does not. This is what makes the whole additive theory of squares (and the Waring problem) so interesting and difficult.
Answer: $2n+1=(n+1)^2-n^2+0^2$ and $2n=(n+1)^2-n^2-1^2$ cover the odd and even cases respectively.
Comment: Or, to avoid use of zeroes, $2n+1=(n+3)^2-(n+2)^2-2^2$.
Answer: Hint: show that every $n$ which is not of the form $4k+2$ can be written in the form $a^2-b^2+0^2$ for some $a$ and $b$. Then $4k+2$ can be written in the form $a^2-b^2-1^2$ for some $a$ and $b$.
(Thanks to John Bentin for pointing out the silly error in my original post.)
Comment: Thanks, I made a mistake. It is actually anything not 2 mod 4, will edit.
Comment: @E.Joseph you can also get all multiples of $4$ from $(n+1)^2-(n-1)^2$.
Comment: @JohnBentin I do not see the connection either... I want to say *odd* number since $(n+1)^2-n^2=2n+1$ which is odd.


Java, transfer graph, output as * to every 100

Question:     import java.util.Scanner;

public class BatmanBarGraph {
    public static void main(String[] args){
//store the amount of each transfer
 // storage for the variable
 int transfer1;
 int transfer2;
 int transfer3;
 int transfer4;
 int transfer5;

 //greet and ask for the transfers
 System.out.println("Good Morning Lucius. Enter Transfers - ");
 Scanner keyboard = new Scanner(System.in);

 //plug in the transfer
 System.out.println("Transfer 1");

 //keyboard
 transfer1 = keyboard.nextInt();

 System.out.println("Transfer 2");
 transfer2 = keyboard.nextInt();

 System.out.println("Transfer 3");
 transfer3 = keyboard.nextInt();

 System.out.println("Transfer 4");
 transfer4 = keyboard.nextInt();

 System.out.println("Transfer 5");
 transfer5 = keyboard.nextInt();

//print a graph, line by line of each transfer
//Every asterisk ("*") in each bar represents $100. A transfer of $1000 would then have five stars: *****

 //Create another chart for suspicious transactions
 System.out.println("Suspicious transfer chart: ");
 //divides the number we entered by 100
 int Suspicious1 = (transfer1)/100;
 int Suspicious2 = (transfer2)/100;
 int Suspicious3 = (transfer3)/100;
 int Suspicious4 = (transfer4)/100;
 int Suspicious5 = (transfer5)/100;

 System.out.print("Transfer 1:");
 for (int N1 = Suspicious1; N1 > 0; N1--){
     System.out.print("*");
     }

 System.out.print("Transfer 2: ");
 for (int N2 = Suspicious2; N2 > 0; N2--){
     System.out.print("*");
 }
 System.out.print("Transfer 3: ");
 for (int N3 = Suspicious3; N3 > 0; N3--){
     System.out.print("*");
 }

 System.out.print("Transfer 4: ");
 for (int N4 = Suspicious4; N4 > 0; N4--){
     System.out.print("*");
 }

 System.out.print("Transfer 5: ");

 for (int N5 = Suspicious5; N5 > 0; N5--){
     System.out.print("*");
 }
}

}

thats my code, the output i get is
    Suspicious transfer chart:

Transfer 1:*Transfer 2: **Transfer 3: ***Transfer 4: ****Transfer 5: *****
how do i make them like this
Comment: Bit confused. If every asterisk represents $100, wouldn't $1000 be ten stars?
Comment: Side note, it may be time to learn about arrays and loops.
Comment: yes pada, you right, a 1000$ is = to ten *
Comment: The thing with my output(Suspicious transfer chart)
is that when it comes out, the asterisks are printed before the "transfer X"
Comment: @DaniilKim You need to print a new line after you finish printing the asterisks. Also, I recommend using a method for commonly reused code, for example, printing out the asterisks.
Comment: Your question is not very much clear. Can you explain it further?
Comment: Alright, so when you run my program, the suspicious transfer chart will be like this:
      *Transfer 1:
 *****Transfer 2:
    ***Transfer 3:
Comment: and i need those asterisks to be like on the black picture above.(the picture show not what i have but what i desire to have)
Comment: Could you attach an image of your current output?
Comment: @SimplyPanda no no no. Post the output in a code block, don't use an image (this should be done for the desired output as well)
Answer: For educational purposes, this code achieves the apparent intent of your code.
import java.util.Scanner;

public class BatmanBarGraph {
    public static void main(String[] args)
    {
        System.out.println("Good Morning Lucius. Enter Transfers - ");
        Scanner keyboard = new Scanner(System.in);
        int[] transfers = new int[5];
        for (int i = 0; i < transfers.length; i++) {
            System.out.print("Transfer " + (i + 1) + ": ");
            transfers[i] = keyboard.nextInt();
        }
        System.out.println();
        System.out.println("Suspicious transfer chart:");
        for (int i = 0; i < transfers.length; i++) {
            System.out.print("Transfer " + (i + 1) + ": ");
            for (int n = transfers[i] / 100; n > 0; n--) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Primarily, notice that it's using System.out.print instead of println when printing the "Transfer X: ****" output; this keeps all information for each transfer on the same line. Then at the end of the loop it does a System.out.println to move to the next transfer.
The other main difference is obviously that it's using a 5-element array with for loops to store the five transfer amounts, instead of storing each in its own variable.
The output of this modified code is (including my input transfer values):
Transfer 1: 600
Transfer 2: 1000
Transfer 3: 830
Transfer 4: 420
Transfer 5: 1200

Suspicious transfer chart:
Transfer 1: ******
Transfer 2: **********
Transfer 3: ********
Transfer 4: ****
Transfer 5: ************

To show you what this would look like without the array, here's the same code copy-and-paste for two transfers:
import java.util.Scanner;

public class BatmanBarGraph
{
    public static void main(String[] args)
    {
        System.out.println("Good Morning Lucius. Enter Transfers - ");
        Scanner keyboard = new Scanner(System.in);

        System.out.print("Transfer 1: ");
        int transfer1 = keyboard.nextInt();
        System.out.print("Transfer 2: ");
        int transfer2 = keyboard.nextInt();

        System.out.println();
        System.out.println("Suspicious transfer chart:");

        System.out.print("Transfer 1: ");
        for (int n = transfer1 / 100; n > 0; n--) {
            System.out.print("*");
        }
        System.out.println();

        System.out.print("Transfer 2: ");
        for (int n = transfer2 / 100; n > 0; n--) {
            System.out.print("*");
        }
        System.out.println();

    }
}

Comment: Listen, Thats a really beautiful code, but my whole point is to use simple code. Is there is a way to make it with no arrays inside the code?
Comment: i edited my code above, and the output i get is
Suspicious transfer chart:
Transfer 1:*Transfer 2: **Transfer 3: ***Transfer 4: ****Transfer 5: *****

how do i get it to be above each other? (break and next line doesn't work)
Comment: I updated my answer to give you an example with two transfers. Surely you can figure out how to copy and paste the code for the other three transfers.
Comment: Thats a beautiful work, i got it myself now too! thanks a lot!


Line parallel to plane

Question: See if the line e is parallel with to the plane $α$. If not, find the intersecting point.
$$\begin{align} α: & \quad \quad x-3y+z+1=0 \\ e: & \quad \{x+y-z=3, 2x-y-4z=3\} \end{align}$$
Comment: I believe you meant equal instead of a minus for the line $e$.
Comment: how to make line e into a single equation?
Answer: If a line is parallel to the plane, consider the consequences: any vectors that are orthogonal to the plane must be orthogonal to the line. This turns out to be the condition we need to check.
To find the line, work with the system of equations as to single out a variable. Added both equations we get $3x-5z=6$ or $x = 2 + (5z)/3$. Using the first equation we can write $$y=3+z-x = 3+z-2-\frac{5z}{3} = 1 - \frac{2z}{3}.$$ The line is now parameterized by $z$ as $$\begin{align} x & = 2 + \frac{5z}{3}, \\ y & = 1 - \frac{2z}{3}, \\ z & = z. \end{align}$$
To finish, you need to take two points in the line, translate that into a vector with initial and end point as chosen and check if it's orthogonal to the orthogonal vector to the plane, found using the coefficients of the given equation.
Comment: Downvoter: care to explain?
Comment: Glad this has helped. =)
Comment: @johannesvalks Thank you, that is very kind!
Comment: thanks a lot got the right answer. The plane and the line are not parallel and the intersection point is (2,1,0)
Comment: why are there downvotes here?
Comment: @Fantini - nice and clear answer - there should be no downvote! Voteup!
Comment: @Fantini - you deserved the upvote and I don't understand why people downvote without a remark to explain the downvote...
Comment: @johannesvalks Me neither, but it happens every now and then.

Line parallel to plane


Math GRE: Calculus Textbooks - is Spivak + Stewart + Rudin sufficient?

Question: Recently, I splurged and spent $1000 in math textbooks in preparation for the Mathematics GRE subject test. So far, in terms of calculus books, I have purchased Spivak, Stewart, and Baby Rudin.
Is this sufficient preparation for the Math GRE or do I need to get my hands on Apostol?
FYI: I am extremely familiar with the univariate calculus and real analysis material. Multivariate, not so much.
Answer: Stewart's Calculus will prepare you for the calculus questions in the GRE, while Rudin's Principles of Mathematical Analysis will prepare you for the introductory real analysis questions in it.


How to use subgroups in drupal_add_tabledrag()

Question: I am trying to implement a form that is themed with drupal table drag using subgroups. My form consists of a list of 'employees' that need to be assigned to different 'departments'. The order of the employees does not matter once they are inside a department.
The admin/structure/block table is similar to what I am looking for but with just the select box for region and no weights.
I've looked through the documentation here: http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_add_tabledrag/7 and I've also studied the admin/structure/block table code but after several hours of trying different combinations - I am stuck!
The block module uses custom JS and a template tpl file for outputting the table. I think this doesn't take full advantage of Drupal. Therefore, this solution should make use of theme_table and #ajax (for the region select fields).
Comment: You say you're looking for the the admin/structure/block table with only region and no weights -- without weights how would this be draggable? You'd just be picking an option with selects.
Comment: @CharlieS Would this not be possible? A table with draggable rows, allowing items to be separated into regions? If it is not theoretically possible, then I don't mind having weights too - I would just ignore them on the form submit.
Answer: If you want ajaxed example perhaps you can study the Display Suite UI.
In my opinion the easiest way to do this if you need similar functionality is just to use the block module tpl's and change the data presented inside it (from block region to your custom module regions)
to remove the weights, I think if you remove :
drupal_add_tabledrag('blocks', 'order', 'sibling', 'block-weight', 'block-weight-' . $region);

it will remove the ability to drag and sort the weight.
some rough examples for "Drupal compliant" way :
note: this is VERY rough code, you will need to adjust it heavily

function theme_example(&$variables) {
  // build the header
  $header = array(
    '', // this will be hidden when table drag run
    '', // this will be hidden when table drag run
    t('Block Region'),
    t('Region Area'),
  );
  // enabled region
  //$regions = region_area_grab_region('enabled');
  // substitute this to what ever your module provides
  // this should be in $form array
  $regions = array('example_one', 'example_two', 'example_three');

  $region = array('example_block_one', 'example_block_two', 'example_block_three');

  // Add table javascript.
  drupal_add_js('misc/tableheader.js');
  drupal_add_js(drupal_get_path('module', 'block') . '/block.js');

  // take notice of the key that will be related to real options
  // in the select box, this should be in $form array
  $options = array();
  foreach ($regions as $key => $region) {
    $options[$region] = $region;
  }

  // add additional class here
  $attributes = array(
    'class' => array('draggable'),
  );

  // building the table rows
  $rows = array();

  // looping for each regions
  foreach ($regions as $region) {

    // this is the heart of the draggable
    // take good notice for the region-manager (the table id), region-area-weight (group of rows class)
    // and regionarea-weight- $region (unique row class), you will need to add this to the form array
    // element NOT in the table row

    // if you want to emulate the block page table drag, comment out the drupal_add_tabledrag
    drupal_add_tabledrag('region-manager', 'order', 'group', 'regionarea-weight', 'regionarea-weight-' . $region , $hidden = FALSE);
    // build the region row

    // replace this with your form element array eg $variables['form']['whatever']
    $elements = regionarea_build_admin_region_form($region, $form, $form_state);

    $row = array();
    $row[] = '';
    $row[] = drupal_render($elements[$region['name']]['weight']); // replace this to actual form array for the weight
    $row[] = $elements[$region['name']]['name']['#value']; // replace this to actual form array for the value / title
    $row[] = drupal_render($elements[$region['name']]['enabled']); // optional
    $row = array_merge(array('data' => $row), $attributes); // merge the array, add draggable class
    $rows[] = $row; // build the row

    // ----------------------------------------------------------------------------------------------------------------- //
    // Usually up to this point is enough for just normal draggable, only continue if you have a sub child to drag
    // ----------------------------------------------------------------------------------------------------------------- //

    // build the block regions
    // now we looping for the sub child AKA regions as in the block region page
    foreach($region['regions'] as $regionkey => $blockregion) {
      // add two table drag, one for weight the other for 'region'
      drupal_add_tabledrag('region-manager', 'match', 'sibling', 'region-select', 'region-' . $blockregion, NULL, FALSE);
      drupal_add_tabledrag('region-manager', 'order', 'sibling', 'region-weight', 'weight-' . $blockregion);

      // replace this with your form element array eg $variables['form']['whatever']['children']
      $elements = regionarea_build_admin_blockregion_form($blockregion, $regionkey, $options, $form, $form_state);

      // build the current row
      $row = array();
      $row[] = '';
      $row[] = drupal_render($elements[$blockregion]['weight']);
      $row[] = $elements[$blockregion]['name']['#value'];
      $row[] = drupal_render($elements[$blockregion]['regions']);

      $row = array_merge(array('data' => $row), $attributes);
      $rows[] = $row;
    }

  }

  // some options to pass to the theme_table
  $element = array(
    '#empty' => t('There are no region area available'),
    '#attributes' => array(
      'id' => 'region-manager',
    )
  );

  // build the theme
  return theme('table', array('header' => $header, 'rows' => $rows, 'empty' => $element['#empty'], 'attributes' => $element['#attributes'])),
}

Comment: Hmm I don't think the blocks module way of implementing this was the best. In drupal, you shouldn't have to write HTML for your own table in a tpl file. Don't you think?
Comment: well that is the easiest way to do this, if you want really drupal "compliant" way it is more complex
Comment: Hi jason, this seems like a good start. Can you edit the code to make a simple working example? I don't think that code will work in that condition.
Answer: As I can see, Commerce module uses the same functionality and the same realization. File commerce_checkout_admin.js is very similar to draggable part in block.js so you have to use Block way. Maybe you can reuse code in block.js if you will follow the same naming.
You can choose between tpl.php and theme_YOUR_FORM to add tabledrag logic.
Comment: I looked at the js code and the comment at the top reads:

`This code is almost an exact copy of the code used for the block region`

This means they didn't try to re-invent the process, they just went with the block module method. There should definitely be a simpler way to implement this.
Comment: So, you are making us to invent something? :)
Comment: That explains the bounty ;)


PopOver For Annotation View

Question: Well i have a question? Im Confuse!
I have a mapview where the annotations are layed out.Now i want a popover for annotations.
how Should i do it
1.Create a popover controller in storyboard and push it from delgate method.
2.Create a programmatic popover view ,by all sub views and stuff?
I want to use the first method any one help me out.
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control

{
   // UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"annotationPopUp"];
    [self performSegueWithIdentifier: @"annotationPush" sender:nil];
}
Answer: In mapView:didSelectAnnotationView make your popover (preferably a property) in your class and pressent it. Here's a example:
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    self.popover = [[UIPopoverController alloc] initWithContentViewController:yourViewController];

    [self.popover presentPopoverFromRect:view.bounds
                                  inView:view
                permittedArrowDirections:UIPopoverArrowDirectionAny
                                animated:YES];
}

Comment: Think UIPopoverController is only available on iPad
Comment: UIPopoverController is only available on the iPad...But I would use this for iPhone and iPad https://github.com/nicolaschengdev/WYPopoverController

PopOver For Annotation View


Run the command unix2dos  and to make sure I opened the file but it doesn't show me ^M any reason

Question: I run the command unix2dos <file_path> and to make sure I opened the file but it doesn't show me ^M. can anyone tell me the reason?
I want to run some command to copy some text to another file with the windows line ending.
But the destination where I want to copy it doesn't have to install the dos2unix package.
So I want it to convert the file to DOS at source location then copy it but when I run unix2dos it doesn't show me ^M when opened in vi. so could anyone please tell me how can I make sure that the source is getting copied at destination with windows line endings?
Comment: yes, you have reposted your question (Q) as a comment. Please learn to read the comments readers leave for you because what you have posted is not a programming Q. But, just this one time, I may be able to help. Just try using `cat -vet file` to see if you see `^M$` at the end of your converted file. If you don't then something else is wroing with how you are using `unix2dos`. Good luck.
Comment: StackOverflow is dedicated to helping solve programming code problems. Your Q seems  more appropriate for [su]  , but read their help section regarding on-topic questions . AND please read [Help On-topic](https://stackoverflow.com/Help/On-topic) and [Help How-to-ask](https://stackoverflow.com/Help/How-to-ask) before posting more Qs here.  Good luck.
Comment: If it's converted right, I don't think vi would necessarily show you control m's.  I can tell you how to convert in powershell https://stackoverflow.com/questions/724083/unix-newlines-to-windows-newlines-on-windows/52593215#52593215
Comment: Hi @shellter I need the script or shell command so it will send the file to destination like using scp but before that need to convert it to DOS however I tried using dos2unix but when I open to confirm but it is not showing ^M at the end of the line however the text which I actually written in windows shows ^m. in vi I can manually add by appending ctrl+V+M but need command to change the while file
Comment: Hi @shellter,
The question was asked as I think, I need to fire some more commands besides unix2dos so I can see a similar effect i.e. ^M when I open it with vi.
Thanks for your answer and suggestion I will post such a question on other portal and not on this programming portal.
Answer: Thanks, @shellter I understand what you want to say.
anyway, unix2dos command works well but to confirm I can use cat -vet file.


Why do I get this error "HttpRequest.accepts() missing 1 required positional argument: 'media_type'"?

Question: The source code originally had Httpsrequest.is_ajax which after some reading I realised was depricated. So I changed it to Httpsrequest.accepts and it now throws an error:

HttpRequest.accepts() missing 1 required positional argument: 'media_type'

How can I solve or bypass this error ?
def home_view(request):

    published_jobs = Job.objects.filter(is_published=True).order_by('-timestamp')
    jobs = published_jobs.filter(is_closed=False)
    total_candidates = User.objects.filter(role='employee').count()
    total_companies = User.objects.filter(role='employer').count()
    paginator = Paginator(jobs, 3)
    page_number = request.GET.get('page', None)
    page_obj = paginator.get_page(page_number)

    if request.accepts():
        job_lists = []
        job_objects_list = page_obj.object_list.values()
        for job_list in job_objects_list:
            job_lists.append(job_list)

    return render(request, 'jobapp/index.html', context)

Answer: if request.accepts(): #Returns True if the request Accept header matches the mime_type argument.

Ex: request.accepts('text/html') #Add your mime_type argument here to solve this error.

I hope this helps you
Comment: Yes this has solved the error.


How can I prove that the following function is one-one?

Question: Let $f(x)$ be defined on $[a,b]$
such that $$f(x)=x+\frac{g(x)}{20}$$ Where $g(x)$ is differentiable function on [a,b] and $|g'(x)|\leq 10$, Then:
a) $f(x)$ is bounded variation.( I have verified this, because the function has bounded derivative)
b) $f(x)$ is one one.
Please tell me how can prove the function is  one one.
Comment: although I didn't down vote, some person probably did because of your previous title
Comment: Down voter should leave a comment so that I can improve my questions in future.
Comment: I'm upvoting to cancel the anonymous downvote. Don't see anything wrong with the question/
Answer: Fill in details:
$$f'(x)=1+\frac{g'(x)}{20}\stackrel{\text{Why? Justify}}>0\implies\;f\;\;\text{is injective}$$
since it is monotonic increasing in the given interval
Comment: *monotonic increasing?
Comment: @G.Bach Thank you. Of course, typo corrected.
Answer: A sufficient condition for $f$ to be injective ("one-to-one") is for $f'$ to be either strictly positive, or strictly negative. In your case, since $-10 \le g' \le 10$, and $f' = 1 + \frac {g'} {20}$, it follows that
$$\frac 1 2 = 1 + \frac {-10} {20} \le \underbrace {1 + \frac {g'} {20}} _{f'} \le 1 + \frac {10} {20} = \frac 3 2 ,$$
so $f'(x) \in [\frac 1 2, \frac 3 2] \ \forall x \in [a,b]$, which shows that $f'$ is strictly positive, therefore strictly increasing and thus injective.


Homomorphisms from the group $\mathbb Z/n\mathbb Z$ to the additive group of rationals $\mathbb Q$

Question:
There are $n$ homomorphisms from the group $\mathbb Z/n\mathbb Z$ to the additive group of rationals $\mathbb Q$.

how can i find that the above statement is true/false
Answer: Hint: Elements of $\mathbb{Q}$ apart from the identity have infinite order, and all elements of $\mathbb{Z}/n\mathbb{Z}$ have finite order. Can a group homomorphism map an element of finite order to an element which does not have finite order?
Answer: Say the image of $1\in \mathbb Z_n$ is $x\in \mathbb Q$. Then $nx=0$ in the rationals, so $x=0$. Thus all homomorphisms are trivial, all elements are sent to $0$.


Will postgresql allow any sort of concatenation for (double quoted) identifier names?

Question: Most of my constraint names are concise and short, but a few of them are long and including those on a single line exceeds the code style conventions I am working with.
Without thinking about it, I just did a line break and a double pipe, as so:
history         uint4                              constraint "[tablename] The beginning of history must be sooner " ||
                                                       "than the current day" check (history <= hdate)

This of course fails, because it's an identifier and not a string literal. I understand why it fails, and this bums me out because I'm almost certain that there's no way to break and continue the identifier on a second line.
Am I wrong? Is there a trick here? It seems like I should be able to get away with a \ at the end of the line, but then the continuation can't be indented (since those spaces would be part of the identifier name).
Answer: You can execute a statement, which contains the original command, formatting, function calls etc. You may want to put the constraint in an alter table statement instead of wrapping the entire table creation statement in the execute
do $$ BEGIN
 EXECUTE 'CREATE TABLE tex (' ||
    'hdate int, ' ||
    'history int constraint "[tablename] The beginning of history must be sooner ' ||
                            'than the current day" check (history <= hdate));';
end $$;

\d tex
                 Table "public.tex"
 Column  |  Type   | Collation | Nullable | Default
---------+---------+-----------+----------+---------
 hdate   | integer |           |          |
 history | integer |           |          |
Check constraints:
    "[tablename] The beginning of history must be sooner than the cu" CHECK (history <= hdate)

PS: though the text seems too long and will be truncated, regardless of the string concatenation
Comment: I only just noticed that I exceeded 63 chars with it... but it'd still be a problem under that length.


Bulk update displayname attribute to match cn attribute for all AD groups

Question: We are setting up ADFS for identity federation with a Microsoft Online service. The documentation states that "Groups without a displayname will NOT get synchronized..." We have over 250 groups that have a blank displayname attribute.
Does anyone know of a way to set the displayname attribute to match the cn attribute for all groups where the displayname is blank?
Comment: Could also use name or sAMAccountName attributes to update displayname.
Answer: Using the Microsoft Powershell commands you can do this.  You need to import the AD module if you do not have it already imported into your current powershell session.
<code>Get-ADGroup -filter * -Properties Displayname | Where-Object {$_.displayname -eq $null} | ForEach-Object {Set-ADGroup -Identity
$_ -DisplayName $_.SamaccountName}
</code>
Comment: Great.  Glad I could help.


Inequality with square roots and a difference

Question: Prove $$\sqrt{a+b}+\sqrt{b+c}+\sqrt{c+a}-(a+b+c)\leq\frac{3}{2}$$
My difficulty here is that I don't know a way to handle the difference in the question.
Can Cauchy-Schwarz be used here?
Comment: The inequality seems to be false at $a = b = c = 2$: $\sqrt{2+2} + \sqrt{2+2} + \sqrt{2+2} - (2+2+2) = 0 < 3/2$.
Comment: do you mean this here $$\sqrt{a+b}+\sqrt{b+c}+\sqrt{c+a}-(a+b+c)\geq\frac{3}{2}$$
Comment: is here $a,b,c>0$ given?
Comment: Are $a,b,c\in\mathbb R^+$?
Comment: Maybe rewrite as $$\sqrt u+\sqrt v+\sqrt w-\frac{u+v+w}2\ge \frac32$$
Comment: and i tried to prove it on 4 sheet of papers
Comment: My apologies the conditions in the question are:a,b,c are real numbers, where a+b, b+c and c+a are non-negative
Answer: hint
in your inequality, $\ge $ must be $\le $.
For every real $x\ge 0 $ we have
$$ -x^2+2x-1\le 0$$
thus
$$-x+2\sqrt {x}-1\le 0$$
$$\implies 2\sqrt {x}-x\le 1$$
$$\implies \sqrt {x}-\frac {x}{2}\le \frac {1}{2} $$
$$\implies \sqrt {a+b}-\frac {a+b}{2}\le \frac {1}{2} .$$
nearly done.
Comment: Thanks. I have inadvertently typed in the incorrect inequality sign.
Answer: Alternatively using AM-GM inequality: $\sqrt{a+b} = \sqrt{1\cdot (a+b)} \le \dfrac{1+(a+b)}{2}\implies \sqrt{a+b} - \dfrac{a+b}{2} \le \dfrac{1}{2}$. Repeat this application of the AM-GM inequality for the $2$ pairs $(b,c)$, and $(c,a)$ and add up the sought inequality follows.


Verificar se há diferentes elementos em uma lista em R

Question: Eu tenho uma lista que cada elemento é um data frame contendo várias informações sobre um determinado instituidor de pensão. Na coluna CLASSE só pode haver um tipo e eu preciso saber quem possui mais de um tipo.  Como criar uma coluna que retorne TRUE caso o INSTITUIDOR possua pensionistas de diferentes classes.
Abaixo dput do head da lista:
structure(list(`1002538-1` = structure(list(ID.VINC.INST = c("1002538-1",
"1002538-1"), DS_PREFIXO = c("FILHO (A) INVÁLIDO (A)", "VIÚVA"
), ID.FUNCIONAL = c(43189938L, 43189920L), NR_MATRICULA = c("0094712B",
"0094712A"), NOME = c("RAQUEL ELCO CAMPOS", "CELINA ELCO CAMPOS"
), ID_FUNCIONAL_INSTITUIDOR = c(1002538L, 1002538L), VINCULO_INSTITUIDOR = c(1L,
1L), NUMPENS = c(2L, 1L), NM_INSTITUIDOR = c("JOCELINO VILLELA CAMPOS",
"JOCELINO VILLELA CAMPOS"), VL_BRUTO = c(1182.13, 1182.13), MES_REF = c("01/08/2017",
"01/08/2017"), CLASSE = c("CLASSE 1", "CLASSE 1"), Freq = c(2L,
2L)), .Names = c("ID.VINC.INST", "DS_PREFIXO", "ID.FUNCIONAL",
"NR_MATRICULA", "NOME", "ID_FUNCIONAL_INSTITUIDOR", "VINCULO_INSTITUIDOR",
"NUMPENS", "NM_INSTITUIDOR", "VL_BRUTO", "MES_REF", "CLASSE",
"Freq"), row.names = 5:6, class = "data.frame"), `1003437-1` = structure(list(
    ID.VINC.INST = c("1003437-1", "1003437-1"), DS_PREFIXO = c("VIÚVA",
    "DEPENDENTE"), ID.FUNCIONAL = c(44227795L, 44235089L), NR_MATRICULA = c("0416908A",
    "0416908B"), NOME = c("VERGINIA MARIA DE OLIVEIRA ROSA",
    "EMILLY DE OLIVEIRA ROSA"), ID_FUNCIONAL_INSTITUIDOR = c(1003437L,
    1003437L), VINCULO_INSTITUIDOR = c(1L, 1L), NUMPENS = 1:2,
    NM_INSTITUIDOR = c("ANTONIO PLACIDIO LOPES ROSA", "ANTONIO PLACIDIO LOPES ROSA"
    ), VL_BRUTO = c(3047.47, 3047.47), MES_REF = c("01/08/2017",
    "01/08/2017"), CLASSE = c("CLASSE 1", "OUTRAS"), Freq = c(2L,
    2L)), .Names = c("ID.VINC.INST", "DS_PREFIXO", "ID.FUNCIONAL",
"NR_MATRICULA", "NOME", "ID_FUNCIONAL_INSTITUIDOR", "VINCULO_INSTITUIDOR",
"NUMPENS", "NM_INSTITUIDOR", "VL_BRUTO", "MES_REF", "CLASSE",
"Freq"), row.names = 10:11, class = "data.frame"), `10087958-1` = structure(list(
    ID.VINC.INST = c("10087958-1", "10087958-1"), DS_PREFIXO = c("VIÚVA",
    "FILHO (A) MENOR"), ID.FUNCIONAL = c(50740172L, 50740202L
    ), NR_MATRICULA = c("", ""), NOME = c("ALEXANDRA GOMES DE OLIVEIRA MACIEL",
    "JUAN PEDRO DE OLIVEIRA MACIEL"), ID_FUNCIONAL_INSTITUIDOR = c(10087958L,
    10087958L), VINCULO_INSTITUIDOR = c(1L, 1L), NUMPENS = 1:2,
    NM_INSTITUIDOR = c("MARCO ANTONIO DE OLIVEIRA MACIEL", "MARCO ANTONIO DE OLIVEIRA MACIEL"
    ), VL_BRUTO = c(3076.8, 3076.8), MES_REF = c("01/08/2017",
    "01/08/2017"), CLASSE = c("CLASSE 1", "CLASSE 1"), Freq = c(2L,
    2L)), .Names = c("ID.VINC.INST", "DS_PREFIXO", "ID.FUNCIONAL",
"NR_MATRICULA", "NOME", "ID_FUNCIONAL_INSTITUIDOR", "VINCULO_INSTITUIDOR",
"NUMPENS", "NM_INSTITUIDOR", "VL_BRUTO", "MES_REF", "CLASSE",
"Freq"), row.names = 19:20, class = "data.frame"), `10114963-1` = structure(list(
    ID.VINC.INST = c("10114963-1", "10114963-1"), DS_PREFIXO = c("FILHO (A) MENOR",
    "VIÚVA"), ID.FUNCIONAL = c(50853104L, 50853090L), NR_MATRICULA = c("",
    ""), NOME = c("GUILHERME DE ASSIS MARINHO", "ELISANGELA DE ASSIS SILVA MARINHO"
    ), ID_FUNCIONAL_INSTITUIDOR = c(10114963L, 10114963L), VINCULO_INSTITUIDOR = c(1L,
    1L), NUMPENS = c(2L, 1L), NM_INSTITUIDOR = c("EDSON BORBA MARINHO",
    "EDSON BORBA MARINHO"), VL_BRUTO = c(3095.41, 3095.41), MES_REF = c("01/08/2017",
    "01/08/2017"), CLASSE = c("CLASSE 1", "CLASSE 1"), Freq = c(2L,
    2L)), .Names = c("ID.VINC.INST", "DS_PREFIXO", "ID.FUNCIONAL",
"NR_MATRICULA", "NOME", "ID_FUNCIONAL_INSTITUIDOR", "VINCULO_INSTITUIDOR",
"NUMPENS", "NM_INSTITUIDOR", "VL_BRUTO", "MES_REF", "CLASSE",
"Freq"), row.names = 27:28, class = "data.frame"), `10179151-1` = structure(list(
    ID.VINC.INST = c("10179151-1", "10179151-1", "10179151-1"
    ), DS_PREFIXO = c("FILHO (A) MENOR", "COMPANHEIRA", "FILHO (A) MENOR"
    ), ID.FUNCIONAL = c(43038824L, 43300464L, 43038816L), NR_MATRICULA = c("0410258B",
    "0410258C", "0410258A"), NOME = c("ERICA FERREIRA ROGERIO DE SOUZA",
    "PATRICIA FERREIRA DA SILVA", "ERIC ROGERIO DE SOUZA JUNIOR"
    ), ID_FUNCIONAL_INSTITUIDOR = c(10179151L, 10179151L, 10179151L
    ), VINCULO_INSTITUIDOR = c(1L, 1L, 1L), NUMPENS = c(2L, 3L,
    1L), NM_INSTITUIDOR = c("ERIC ROGERIO DE SOUZA", "ERIC ROGERIO DE SOUZA",
    "ERIC ROGERIO DE SOUZA"), VL_BRUTO = c(416.04, 832.09, 416.04
    ), MES_REF = c("01/08/2017", "01/08/2017", "01/08/2017"),
    CLASSE = c("CLASSE 1", "CLASSE 1", "CLASSE 1"), Freq = c(3L,
    3L, 3L)), .Names = c("ID.VINC.INST", "DS_PREFIXO", "ID.FUNCIONAL",
"NR_MATRICULA", "NOME", "ID_FUNCIONAL_INSTITUIDOR", "VINCULO_INSTITUIDOR",
"NUMPENS", "NM_INSTITUIDOR", "VL_BRUTO", "MES_REF", "CLASSE",
"Freq"), row.names = 40:42, class = "data.frame"), `1031945-1` = structure(list(
    ID.VINC.INST = c("1031945-1", "1031945-1"), DS_PREFIXO = c("FILHO (A) MENOR",
    "FILHO (A) MENOR"), ID.FUNCIONAL = c(50840835L, 50840827L
    ), NR_MATRICULA = c("", ""), NOME = c("LUIZ SERGIO RAMOS TORRES",
    "JULIANA RAMOS TORRES"), ID_FUNCIONAL_INSTITUIDOR = c(1031945L,
    1031945L), VINCULO_INSTITUIDOR = c(1L, 1L), NUMPENS = c(2L,
    1L), NM_INSTITUIDOR = c("ETEVALDO CORREA TORRES", "ETEVALDO CORREA TORRES"
    ), VL_BRUTO = c(656.83, 656.83), MES_REF = c("01/08/2017",
    "01/08/2017"), CLASSE = c("CLASSE 1", "CLASSE 1"), Freq = c(2L,
    2L)), .Names = c("ID.VINC.INST", "DS_PREFIXO", "ID.FUNCIONAL",
"NR_MATRICULA", "NOME", "ID_FUNCIONAL_INSTITUIDOR", "VINCULO_INSTITUIDOR",
"NUMPENS", "NM_INSTITUIDOR", "VL_BRUTO", "MES_REF", "CLASSE",
"Freq"), row.names = 86:87, class = "data.frame")), .Names = c("1002538-1",
"1003437-1", "10087958-1", "10114963-1", "10179151-1", "1031945-1"
))

Comment: Não compreendo completamente, quer a nova coluna em cada `data.frame`? Por exemplo, a primeira df tem duas linhas, ambas com a mesma classe, `CLASSE 1`. Quer uma nova coluna com ambos os valores `FALSE`?
Comment: Exatamente. A minha dificuldade neste problema é que cada `data frame` pode ter um diferente número de linhas.
Answer: A seguinte instrução lapply cria uma nova coluna chamada DUPL_CLASSE em cada data.frame. Se todos os valores da coluna CLASSE forem iguais, a nova coluna é toda FALSE, caso contrário é toda TRUE.
nova_lista <- lapply(lista, function(x){
        x$DUPL_CLASSE <- length(unique(x$CLASSE)) > 1
        x
    })

(Eu chamei lista à lista da pergunta.)
Answer: Pode não ser a forma mais elegante,
df <- data.frame(LISTA = names(dados), CLASSE = T)
for(i in 1:nrow(df)){
 ifelse(length(unique(dados[[i]]$CLASSE)) == 1, df$CLASSE[i] <- F, df$CLASSE[i] <- T)
}

sendo dados, a lista que você forneceu.
Comment: Tive o seguinte erro: `Error in multpensao.semcotista[[i]]$CLASSE :
  $ operator is invalid for atomic vectors`.

EDIT: Utilizei a variável errada aqui, já corrigi e deu certo. Muito obrigado


DB Query replaces %s inside LIKE operator

Question: I have one query like :
db_query("SELECT * FROM {foo} WHERE bar LIKE '%supply%' LIMIT %d,%d", 0, 10)
Now if I use db_query API it will replace %s with the argument supplied and resulting query will be like
SELECT * FROM foo WHERE bar LIKE '0upply%' LIMIT 0, 0
Any ideas to overcome this ? I dont want to use mysql_query()
I am using temporarily _db_query()
Answer: You just need to escape % signs with another % sign in a Drupal db query:
db_query("SELECT * FROM {foo} WHERE bar LIKE '%%supply%%' LIMIT %d,%d", 0, 10);

If you wanted to use a placeholder it would be like so:
db_query("SELECT * FROM {foo} WHERE bar LIKE '%%%s%%' LIMIT %d,%d", 'supply', 0, 10);

Answer: I answer belatedly but it might be useful to another.
Simply set the LIKE condition as a string placeholder and passes its value as an argument to the function deb_query():
db_query("SELECT * FROM {foo} WHERE bar LIKE '%s' LIMIT %d, %d", '%supply%', 0, 10);


Nginx reverse proxy rewrite to hide app name

Question: This question may be asked many times, I have been reading but still can't get what I want.
I have an application running in http://172.17.1.10:8080/myapp I would like to setup nginx reverse proxy accessing the application using   http://sub.domain.com only , hidding  "myapp" in the address bar.
My current setting is:
server{
        listen 80;
        server_name sub.domain.com;
        location /myapp {
                rewrite ^/myapp(.*) /$1 break;
                proxy_pass http://172.17.1.10:8080;
                proxy_redirect off;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP      $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                include /etc/nginx/proxy_params;
        }

}

But I keep viewing the Nginx index page with http://sub.domain.com, and http://sub.domain.com/myapp the tomcat index page. What am I missing?
Answer: Change these three lines should fix you:
location /myapp {
            rewrite ^/myapp(.*) /$1 break;
            proxy_pass http://172.17.1.10:8080;

To:
location / {
            proxy_pass http://172.17.1.10:8080/myapp;

Comment: I first tried that, but it just redirect to sub.domain.com/myapp, and "myapp" will still be part of url
Comment: You need to follow the redirects and find out why, my suggestion does not included redirects.  Did you remove the rewrite?
Comment: I did exactly what you mentiones, removed the  locationand the rewrite line.  now when I type sub.domain.com  it automatically redirect to  sub.domain.com/myapp   (and also with error  "myappmyapp not found" )
Comment: You could try adding a forward slash after /myapp in proxy_pass.  But it seems to me like your myapp or something else is redirecting requests.
Answer: When you change the content of the URI being processed within a location block containing a proxy_pass directive then you need to handle Location header rewrites with proxy_redirect :

In some cases, the part of a request URI to be replaced cannot be determined:

When location is specified using a regular expression.
  In this case, the directive should be specified without a URI.
When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break).

But in your case there's no reason to use a rewrite because nginx already handles this in the proxy_pass directive while adding an URI prefix:

If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the
  directive.

Also you need to remove the proxy_redirect directive so nginx can rewrite Location headers using the proxy_pass URI prefix as a pattern and the location prefix as a replacement.
So simply use this :
server {

    server_name sub.domain.com;

    location / {
            proxy_pass http://172.17.1.10:8080/myapp/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            include /etc/nginx/proxy_params;
    }

}

Comment: I get infinite redirect loop... I think something else is redirecting it...
Comment: @Kossel Check you backend replies, it doens't come from this nginx configuration (except if your include directive imports something inappropriate).
Comment: by default the app is checked by spring Security and will redirect to /login or /home I think the further problem is not nginx related... thanks


NSAutoreleasePool issues on the iPhone

Question: I have a small iPhone app which has a button on the first view. When I select this button I load up my new view which has an image on it. I'm currently using the following code to load the image from an online source on a separate thread, whilst allowing the user to continue controlling the application:
- (void) loadImageTest
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSURL *url = [[NSURL alloc] init];
    url = [NSURL URLWithString:logoPath];

    NSData *data = [[NSData alloc] init];
    data = [NSData dataWithContentsOfURL:url];

    loadingImage = [UIImage imageWithData:data];
    titleLogoImage.image = loadingImage;

    //[pool drain];
    [pool release];
}

This is called from this line of code in the new view's init:
[NSThread detachNewThreadSelector:@selector(loadImageTest) toTarget:self withObject:nil];

Now this works fine (ish), but if I close the new view and then load a new one up again in quick succession (or just after-wards in some cases) it will bomb out with the classic EXC_BAD_ACCESS. I'm sure that this is due to the code within the thread pool, but can anyone see why this is happening?
Thanks
Comment: The zombies will save you. http://www.cocoadev.com/index.pl?NSZombieEnabled
Answer: Yours:
// This is ok, you might try using NSURLConnections asynchronous methods instead of making
// your own thread.
[NSThread detachNewThreadSelector:@selector(loadImageTest) toTarget:self withObject:nil];
- (void)loadImageTest
{
    // This is fine
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    // you're making and then abandoning this url object so it will leak
    NSURL *url = [[NSURL alloc] init];
    // this is fine
    url = [NSURL URLWithString:logoPath];
    // again making and abandoning an object
    NSData *data = [[NSData alloc] init];
    data = [NSData dataWithContentsOfURL:url];
    // this works, but is not thread safe,
    // can't operate on UIKit objects off the
    // main thread
    loadingImage = [UIImage imageWithData:data];
    titleLogoImage.image = loadingImage;
    // this is fine
    //[pool drain];
    [pool release];
}

Cleaned up to make things thread safe, etc. Should help:
// I'm assuming you have a iVar for logoPath but we don't want to
// make threaded calls to an iVar (it's not mutable, so you could do it, but it's just bad form)
// If i'm wrong about logoPath being an iVar don't sweat copying it.
- (void)whateverMethodYouWant
{
    NSString *aLogoPath = [[logoPath copy] autorelease];
    [NSThread detachNewThreadSelector:@selector(loadImageForPath:) toTarget:self withObject:aLogoPath];
}
- (void)loadImageForPath:(NSString *)aLogoPath
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:aLogoPath]];
    // the performSelector will retain the data until the method can be performed
    [self performSelectorOnMainThread:@selector(setImageForTitleLogo:) withObject:imgData waitUntilDone:NO];

    [pool release];
}
- (void)setImageForTitleLogo:(NSData *)imgData
{
    // This part is not strictly necessary
    // but it's a nice way to wrap a method that needs to happen on the main thread.
    if ([NSThread isMainThread])
    {
        // make the image (i'm assuming you meant loadingImage to be a local scope variable)
        UIImage *loadingImage = [UIImage imageWithData:imgData];
        // make sure the button still exists
        // also make sure you're setting any references to this button to nil when you're releasing and making new views
        // so that you're not addressing a button that's been released
        // (assigning the image to the button will cause the button to retain it for you)
        if (titleLogoImage != nil)
            titleLogoImage.image = loadingImage;
    }
    else
    {
        [self performSelectorOnMainThread:@selector(setImageForTitleLogo:) withObject:imgData waitUntilDone:NO];
    }
}

Comment: Excellent anyways :) I think it was not performing the setting of the image on the main thread which was the issue. Thanks so much :)
Comment: I pop in now and again. Glad it helped.
Answer: You're doing weird stuff.
NSURL *url = [[NSURL alloc] init];

means you create an NSURL object, which you own.
url = [NSURL URLWithString:logoPath];

This means you create another NSURL object, which is autoreleased. The NSURL you just created, just leaks. The same goes for the NSData here.
The loadingImage must be retained by titleLogoImage, or it will be deallocated on the drain of your NSAutoReleasePool. What is titleLogoImage and does it retain image?
edit ps: what also disturbes me, is that loadingImage is not confined to the scope of the function. To cut things short:
NSURL *url = [NSURL URLWithString:logoPath];
NSData *data = [NSData dataWithContentsOfURL:url];
titleLogoImage.image = [UIImage imageWithData:data];

may save some headaches, at least.
Comment: This is what I had, but when reading up about NSAutoReleasePool's I read somewhere to do this... Anyway, anyway even with your method, which I had earlier, I get the same issue. Thanks anyway.
Answer: There is nothing in the posted code that would trigger a crash. Depending on how titleLogoImage is defined, it might be affects by the autorelease.
However, beyond the problems outlined by mvds, you have no pressing needs for a localized autorelease pool. It will do nothing here but cause you trouble.
Autorelease pools are dangerous and not for beginners. They will kill any autoreleased objects in them. You generally only create your own pool when you are rapidly creating a large number of memory intensive objects. That does not appear to be the case here.
Despite the attention given them, custom pools are seldom used. After over a decade Apple API work, I can probably count on my fingers the number of times I have used my own custom pool.

NSAutoreleasePool issues on the iPhone


Linux routing issue with two nics

Question: I have a Server (SERVER1) with two network interfaces, as shown in the diagram.  I have another Server (SERVER2) from which I am trying to connect to SERVER1.
When I connect to eth0 (10.0.0.124) I succeed. However, when i connect to eth1 (10.0.15.213) I fail.
I suspect it is down to the routing table on SERVER1 whereby SERVER1 receives the signal on eth1 but routes the response down eth0, thus breaking the TCP communication chain.
So how can I tell the routing table to respond down the same network interface that it received the connection on, but nothing is being sent back?

To further this, a tcpdump of the connection on SERVER1 shows the following, which shows SERVER2 is making the connection:
# tcpdump -i eth1 -n
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth1, link-type EN10MB (Ethernet), capture size 262144 bytes
06:01:35.543172 IP 10.0.2.109.51554 > 10.0.15.213.22: Flags [S], seq 1526846784, win 26883, options [mss 8961,sackOK,TS val 311066 ecr 0,nop,wscale 7], length 0
06:01:36.540677 IP 10.0.2.109.51554 > 10.0.15.213.22: Flags [S], seq 1526846784, win 26883, options [mss 8961,sackOK,TS val 311316 ecr 0,nop,wscale 7], length 0
06:01:38.544674 IP 10.0.2.109.51554 > 10.0.15.213.22: Flags [S], seq 1526846784, win 26883, options [mss 8961,sackOK,TS val 311817 ecr 0,nop,wscale 7], length 0
06:01:42.556548 IP 10.0.2.109.51554 > 10.0.15.213.22: Flags [S], seq 1526846784, win 26883, options [mss 8961,sackOK,TS val 312820 ecr 0,nop,wscale 7], length 0

A netstat when connected to eth0
# netstat -tnp
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0    280 10.0.0.124:22           10.0.2.109:54298        ESTABLISHED 8562/sshd: ubuntu [

Answer: There are many strange things in this setup.
You omitted important information about the devices with 10.0.0.1 and 10.0.2.1. Presumably they are on the same device, a router between the networks. Without a router between your machines, they would not be able to reach either interface.
You can start diagnosing with pings. Use tcpdump on the interfaces eth1, eth0 and all. I suspect you will find out the the responses are sent back via eth0 but don't arrive at your server2. Use tcpdump or something equivalent on your router.
Answer: Short lived question as I found another thread [1] with the answer.
From what I understand, it creates a rule that says "if traffic from 10.0.15.213 then route it back down itself"
echo 200 nic2 >> /etc/iproute2/rt_tables
ip rule add from 10.0.15.213 table nic2
ip route add default via 10.0.15.1 dev eth1 table nic2

Comment: This works because it causes the responses to use eth1 instead of eth0. It seems your router cares about that. It probably runs a firewall with connection tracking.
Comment: It's Amazon Web Services...

Linux routing issue with two nics


Can't Draw Graphics Because Of "@Override" Annotation

Question: I have been experimenting with drawing on a JFrame, so I could use these experiments in the future for a program I might create. However, I have found a problem that I am not able to solve:
How to draw stuff while having a timer set up.
public static void MyTimer() {
JFrame frame = new JFrame("Colors");

    int width = 700;
    int height = 700;

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setBackground(Color.BLACK);
    frame.pack();
    frame.setSize(width, height);
    frame.setVisible(true);
    frame.setResizable(false);
    TimerTask task;
task = new TimerTask() {
    int a = 2;

    @Override
    public void run(Graphics g) {
        g.drawRect(a, 2, a + 66, 68);
    g.fillRect(a, 2, a + 66, 68);

        a = a + 20;
    }
};
     timer.schedule(task, 0, 1000);

}

As you can see, I am trying to draw a new square every second. The problem is, I get an error in the code:

method does not override or implement a method from a supertype

How can I fix this?
Answer:
How can I fix this?

The run() method does not take a parameter. Get rid of the Graphics parameter. That will get rid of the compile error.
However, that still will not help with your painting.
Instead you need to override the paintComponent(...) method of a JPanel then you add the panel to the frame. Then you use the Graphics object passed to the paintComponent() method to do your painting.
Read the section from the Swing tutorial on Custom Painting for more information and working examples to get you started.
Also you should NOT be using a TimerTask for animation. You should be using a Swing Timer. Then in the actionPerformed(...) method of the ActionListener you would change the properties of your custom painting (ie in your case add a new square object to be painted) and then invoke repaint() on the panel.

, I am trying to draw a new square every second

Check out the DrawOnImage example found in Custom Painting Approaches. It will show you how to add a Rectangle object to a BufferedImage.
Comment: Using the Swing timer took care of it.


Is Vitess supports sequence(auto-increment) only in unsharded keyspaces?

Question: As documentation says, it should be first creating backing table, so it confused what it should be
Comment: Please state your goal; maybe it is achievable some other way.  There are other ways to produce "unique" numbers across multiple servers; describe your use case.
Answer: The docs describe how sequences are implemented. Vitess needs a one-row table that keeps the state of the sequence. That state table needs to be un-sharded.
The sequence values themselves can be used in a sharded table.
Looking at the docs: https://vitess.io/docs/18.0/reference/features/vitess-sequences/
user_seq is a un-sharded table, user is a sharded table that utilises the sequence for auto-increment.


Loading image from sqllite does not appear

Question: I have an app that loads data from a sqllite database, then converts the data to appropriate formats so it could pass on the data to fragment tabs.
Everything works fine except for the images.
In the DB images are stored in full path, for example R.drawable.muntjakas and the images are available in the resource drawable folder.
The app pulls the data from the db and then converts it to int format so it could be passed on. Eclipse is not giving me any errors, but when the app loads images are not displayed. My xml files have the image id set up and displays the images if I assign the values manually for example
flag = new int[] { R.drawable.muntjakas,.... };

What's the problem?
fragmenttab1.java class that loads data from sql and converts it:
public class FragmentTab1 extends SherlockFragment {

    ListView list;
    ListViewAdapter adapter;

       private static final String DB_NAME = "animalsDB.sqllite3";
        private static final String TABLE_NAME = "animals";
        private static final String ANIMAL_ID = "_id";
        private static final String ANIMAL_NAME = "name";
        private static final String ANIMAL_PIC = "pic";
        public static final String[] ALL_KEYS = new String[] {ANIMAL_ID, ANIMAL_NAME,ANIMAL_PIC };

        private SQLiteDatabase database;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragmenttab1, container,
                false);

        ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(getActivity(), DB_NAME);
            database = dbOpenHelper.openDataBase();
        Cursor cursor = getAllRows();

        ArrayList<String> nameArray = new ArrayList<String>();
        ArrayList<Integer> picArray = new ArrayList<Integer>();
        for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
            nameArray.add(cursor.getString(cursor.getColumnIndex(ANIMAL_NAME)));
            picArray.add(cursor.getInt(cursor.getColumnIndex(ANIMAL_PIC)));
        }
        final String[] name = (String[]) nameArray.toArray(new String[nameArray.size()]);
        final Integer[] pic = (Integer[]) picArray.toArray(new Integer[picArray.size()]);

        final int[] flag =  new int[pic.length];

        for (int i = 0; i < pic.length; i++ ) {
           flag[i] = pic[i];
        }

        // Locate the ListView in fragmenttab1.xml
        list = (ListView) rootView.findViewById(R.id.listview);

        // Pass results to ListViewAdapter Class
        adapter = new ListViewAdapter(getActivity(), name, flag);
        // Binds the Adapter to the ListView
        list.setAdapter(adapter);
        // Capture clicks on ListView items
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // Send single item click data to SingleItemView Class
                Intent i = new Intent(getActivity(), SingleItemView.class);

                // Pass all data country
                i.putExtra("country", name);
                // Pass all data flag
                i.putExtra("flag", flag);
                // Pass a single position
                i.putExtra("position", position);
                // Open SingleItemView.java Activity
                startActivity(i);

            }});
        return rootView;
    }

    public Cursor getAllRows() {
        String where = null;
        Cursor c =  database.query(true, TABLE_NAME, ALL_KEYS,
                            where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

}

My listViewAdapter.java class that should load the data on the screen:
package kf.kaunozoo;
public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    String[] country;
    int[] flag;
    LayoutInflater inflater;

    public ListViewAdapter(Context context, String[] country, int[] flag) {
        this.context = context;
        this.country = country;
        this.flag = flag;

    }

    public int getCount() {
        return country.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        // Declare Variables

        TextView txtcountry;
        ImageView imgflag;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item, parent, false);

        // Locate the TextViews in listview_item.xml

        txtcountry = (TextView) itemView.findViewById(R.id.country);
        // Locate the ImageView in listview_item.xml
        imgflag = (ImageView) itemView.findViewById(R.id.flag);

        // Capture position and set to the TextViews
        txtcountry.setText(country[position]);

        // Capture position and set to the ImageView
        imgflag.setImageResource(flag[position]);

        return itemView;
    }
}

What am I doing wrong? All answers are appreciated
Comment: first of all if your data is in sqlite db use one of CursorAdapter subclass
Answer: I have had this problem once in one of my apps, however, what I did was, I saved unique ids for each drawable in database as I had limited images. While displaying I wrote a small function where I used switch statement to check for each id from database and then loaded images accordingly in ImageView.
However, when you have lots of images, try to use below function, where you can provide image names dynamically from database.
// image from res/drawable
int resID = getResources().getIdentifier("your_image_name",
        "drawable", getPackageName());

Also, you may try the solution given at this blog.


What is the Maximum Likelihood Estimator for which coin was tossed?

Question: You are given three coins with the following probabilities of observing a Head when tossed:
Coin 1 has a P(H) = 1/2,
Coin 2 has a P(H) = 1/3,
Coin 3 has a P(H) = 1/4.
You observed two heads among three tosses, and you would like to find which coin the observations come from. What is the Maximum Likelihood Estimator for which coin was tossed (Coin 1, 2, or 3)?
I found this question on an online question site and I am confused of what the question is trying to ask.
I know that the possibility of getting 2 heads within 3 tosses is 3/8.
But I am not sure where to go from here. How do I solve this?
Comment: Are all three coins tossed? Or are the observed three tosses done with a randomly selected coin?
Comment: @drhab all three are tossed!
Answer: Considering the Binomial experiment $\mathcal Bin(3,p)$  where two heads among three tosses are observed using one and only one of the three coins with different probabilities $p$, if $\eta$ denotes the unknown label of the coin $(\eta=1,2,3)$, the likelihood of the parameter $\eta$ associated with the available data $\mathcal D$ is
$$L(\eta|\mathcal D)=
\begin{cases}(1/2)(1/2)^{2} & \text{if }\eta=1\\
(2/3)(1/3)^2 & \text{if }\eta=2\\
(3/4)(1/4)^2 & \text{if }\eta=3\\
\end{cases}$$
$-$ where the multiplicative term$^\dagger$ $${3 \choose 2}=3$$ in the Binomial probability$$\mathbb P_p(X=2)={3 \choose 2}p^2(1-p)^1$$ is omitted since it does not depend on the parameter $\eta$ $-$ which corresponds to
$$L(\eta|\mathcal D)=
\begin{cases}0.125 & \text{if }\eta=1\\
0.074 & \text{if }\eta=2\\
0.047 & \text{if }\eta=3\\
\end{cases}$$
The maximum likelihood estimator is thus $\hat\eta=1$, meaning coin #1 is the most likely in producing this outcome.

$^\dagger$One should note that the likelihood function is usually defined up to a multiplicative constant.
Comment: It seems that your $L(\eta\mid\mathcal D)$ stands for $P(C=\eta\mid H=2)$ where $C$ denotes the coin label and $H$ the number of heads that are thrown. Is that indeed the intention? If so then you forgot a factor $3$ in all cases. Your answer seems to be that most likely the coin with label $1$ has been thrown (is my interpretation correct?). However in a comment on my comment on the question the OP tells us that all $3$ coins are thrown.
Comment: (+1) Things are clear now. Up to some level I am familiar with "probability" but not so much with "likelihood". Statistics is for a large deal beyond my scope.
Comment: can you explain how you got those numbers ?
Comment: @drhab Although I had answered your question like that. I reread the question and it seemed like only one of the coin was tossed? That is why it is asking which coin the observations come from.
Comment: @jimmy1998 Then do you understand this answer now? In a certain way I made clear how the Xi'an got those numbers (the forgotten factor $3$ does not play an essential role because we are only interested in the maximum of these numbers).
Comment: Unfortunately I wrote $P(C=\eta\mid H=2)$ in my first comment. What I meant was $P(H=2\mid C=\eta)$. Sorry.
Comment: @drhab Is it possible for you to write the formula of when (=∣=2). I am new to MLE and I don't know where to insert which numbers. I suppose that that is Joint probability distribution?
Comment: @drhab or is it possible to write a more detailed answer in another section? I can vote it as helpful later and ask you there if I have more questions.
Answer: If I understand things well now then one of the coins is thrown $3$ times and this resulted in $2$ heads and $1$ tail.
The question we ask ourselves is: which of the $3$ will be used most likely?
If $H$ denotes the number of heads and $C$ denotes the label of the coin then it is not difficult to find:

$P(H=2\mid C=1)=3\times 2^{-3}$
$P(H=2\mid C=2)=3\times(1/3)^2(2/3)$
$P(H=2\mid C=3)=3\times(1/4)^2(3/4)$

That tells us that: $$P\left(H=2\mid C=1\right)=\max\left\{ P\left(H=2\mid C=\eta\right)\mid\eta\in\left\{ 1,2,3\right\} \right\} $$and makes us decide that most likely it was coin $1$ that was used.
Another expression for $P(H=2\mid C=\eta)$ is $L(C=\eta\mid H=2)$.
Here $P$ represents probability (of some event) and $L$ represents likelihood (of some parameter).
Comment: There was a typo in second and third equation. That is fixed now. The second equation states that the probability on 2 heads by 3 throws is 3(1/3)^2(2/3) (binomial distribution) if the probability on heads is 1/3.
Comment: I do not really understand the question you posed in your second comment. If you throw a fair coin 3 times then the probability on twice a head is 3/8. Is that what you mean? For that not the term likelihood is used but term probability. It concerns an event. Term likelihood is preserved for parameters (in this context the coin labels).
Comment: My answer does not find the *likelihood* of getting two heads among three tosses for each coin but find the *probability* of getting two heads among three tosses for each coin. Do you want to know the probability of getting two heads among three tosses if all three coins are used? If so then for that we must first have a probability distribution for the coin labels. In the case where they are equiprobable then the answer is $$P(H=2)=\frac13P(H=2\mid C=1)+\frac13P(H=2\mid C=2)+\frac13P(H=2\mid C=3)$$ Here $P(C=i)=\frac13$ for $i=1,2,3$.
Comment: where did ((2/3)^2) come from in the second equation and (2/4)*2 in the third equation?
Comment: and if I was to find the likelihood of finding two heads among three tosses. Does it mean the answer is P(H) = 3/8?
Comment: thanks for being so helpful. What your answer does is to  find the likelihood of getting two heads among three tosses for each coin. So I was wondering if we can define the likelihood of getting two heads among three tosses (not for each coin). What
Comment: Thank you so much! I want to learn how to use the maximum likelihood and the likelihood in this problem. After looking at the two answers I think I get an idea to do that now. I will look for the likelihood of getting two heads among three tosses myself. Thanks again!


Is it reasonable to study neural networks without mathematical education?

Question: Given the modern state of machine learning technologies and tools (e.g. TensorFlow, Theano, etc.), it seems like entry threshold have recently lowered and it is enough to be able to program on, say, Python, to build interesting things. Another source that supports this point is Machine Learning Specialization on Coursera, that states the following in their FAQ:

What background knowledge is necessary?
You should have some experience with computer programming; most assignments in this Specialization will use the Python programming language. This Specialization is designed specifically for scientists and software developers who want to expand their skills into data science and machine learning, but is appropriate for anyone with basic math and programming skills and an interest in deriving intelligence from data.

On the other hand, there are plenty of other on-line courses (e.g. Stanford Machine Learning on Coursera or Google's Deep Learning on Udacity), as well as classical books, like S. Haykin, Neural Networks: A Comprehensive Foundation, packed with mathematics. Even though I was studying math for several years in university, including statistics, matrices, integral calculus and so on, it's been so long unused that I feel despair by merely looking at those equations. Even Concrete Mathematics by Knuth is discerned at such slow pace that it is seems impossible to finish it at all.
Thus, the following questions arise:

Is it reasonable for someone with shallow knowledge in math but programming skills to dive into neural network/machine learning studies?
Is it possible to build interesting projects in this area, like those playing atari, using only high-level tools?

Or would it take so much time, that it is better not to make oneself struggle and do something else?
Answer: It depends upon your type of Work:
Maths is required if you are working in an applied Science role, i.e. you try to experiments with the known things in Hand i.e. try word embeddings, may be with CNN, and see if the results are good or NOT.
On the other hand ,  a lot of maths is required if you want to end up as a research scientist, example finding new ways to represent word embedding, or improve the existing word embeddings itself, in case of Text mining.
On the other hand, If you are working as a Software engineer in Machine Learning OR a Machine Learning Engineer, then you just need to train the models using existing knowledge of doing things and Tune it for better performance.
There is a trade off between research and Engineering. More towards Research is More Maths, but More towards  Engineering is lesser Maths and More on performance of system in Production.
Another Example to explain would be, for chat Bots.
Research Scientist with Maths background require to write a paper for a new models like how LSTM works and can be Used.
A applied scientiest will try out a business problem like building a chat bot with LSTM first and publish papers how it worked for them in Labs.
A Machine Learning Engineer will replicate the concept which the Applied Scientist had published for their engineering Work (i.e. need to understand maths of paper and replicate it in code, that's it.)
Hope this helps with respect to requirement of knowledge of Maths in Machine Learning
Answer: Google is having courses on Deep Learning to train its employees. Given that most of them are in the situation you describe (not much math experience, but good software skills) I would say it's proof that you can profit from Deep Learning without excelling at math.
Now there are tons of tools and sample codes online on lots of cool deep learning projects so it's easy to get started and play with them. For example there's tensorflow which already doesn't require much knowledge of how the backpropagation algorithm works, but there are even simpler layers build on top of it that require even less Deep Learning/theory knowledge, such as Keras.
If you want to build your own you have to keep in mind that you will sometimes need lots of data and lots of computing power for a subset of those projects. (For example, at MIT's Machine Learning class lots of students wanted to replicate the atari project you mentioned, but the TAs suggested not to because of lack of Google-level compute power).
Things you will probably be able to do with 1-2 days of effort include:

Build your own, relatively simple, architecture.
Train a complex architecture (using online code) on a dataset of your interest.

Finally, if what you want is to create your new cool architecture that overperforms the state of the art I would say this will be hard to do without understanding the math behind it well.
Answer: I'm a PhD candidate in Computational Neuroscience and I work with this kind of software and stuff every day. We also have many students coming in and doing their projects in this field. So I have a bit of experience.

Is it reasonable for someone with shallow knowledge in math but programming skills to dive into neural network/machine learning studies?

Yes, it is. You can use high level abstractions like Keras and get started right away. In my opinion you do not need to know the exact dynamics of the ANN to use it.
As with everything it depends highly on you and how much time and effort you want to invest. I'd say that you need a bit of math to understand the basics of it. An example is the activation functions in a neural net. They play a crucial role but are simple to understand.
If you want to get to the depths of it and really understand how and why it works you'll need pretty extensive math skills. There is no way around that. What I mean are advanced probability theory, advanced calculus and advanced algebra. For example, take a look at the Backpropagation Algorithm.. For more about maths in machine learning you can read this blog post.

Is it possible to build interesting projects in this area, like those playing atari, using only high-level tools?

Yes, it is. There are many great tools out there that allow you to do this. Of course as soon as you'd try to program something new you would hit your limits quite soon, for example, if you wanted to modify a neural network or an algorithm such that it improves or gets faster.
As for Atari I suggest you read this nice blog post. It explains everything in such a detail that you can implement it but still shallow enough to understand it.
So to add to the other answers: I've seen students coming in with low/basic maths skills but good programming skills and they were all able to implement, test and run a solid machine learning pipeline. Here a pipeline means gathering data, preprocessing, training and evaluation of the system as a whole.
So, yes, you can do it.
Answer: I'll limit my answer to neural networks.

Is it reasonable for someone with shallow knowledge in math but programming skills to dive into neural network/machine learning studies?

It's reasonable and possible. Here are few reasons to support this conclusion:

Neural networks are inspired by the functioning of our brains. Therefore lots of concepts are familiar and easy to understand: neurons, connections, activation etc. This makes the introduction to neural networks smooth and exciting, and doesn't require any math.
The basic operation of a neural network, regardless of its size, is easy to understand: forward passing, signals flowing from one level to another, neuron activation etc. Not too much math required here: wighted sums, and non-linear functions such as sigmoid.
The math underlying some of the most fundamental algorithms for training neural networks (e.g., back propagation) is not complex: sums, logarithms, multiplications and divisions. And you calculate values that have concrete meaning: error cost, gradient etc. Some other ML techniques require calculation of intermediary values (often matrices) whose meaning is not that clear or intuitive.
It's often not the more sophisticated math but rather understanding and experience with the basics that let you dive into more advanced topics such as regularisation, pre-training, dropout etc.

To make things clear there're more complex network architectures and mathematically demanding algorithms for training neural networks. Also, although calculations involved in back propagation are simple its derivation is complex for someone who didn't study calculus. Still the difficulty of derivation or existence of more complex algorithms doesn't mean that studying neural networks is unreasonable. These issues won't prevent you from building good understanding and making practical use of neural networks.

Is it possible to build interesting projects in this area, like those playing atari, using only high-level tools?

In the recent years the interest in neural networks (deep learning especially) is spiking. This resulted in the creation of many good tools and libraries as you observed, some of which are coming from factories such as Google, Microsoft or NVidia. No doubt the quality of these is sufficient to create interesting projects. What might prove more challenging is getting the right amount of quality data to train your network (given such data is not currently available).
Comment: Thank you for the answer. May I ask what is your experience in the field and how do you use NNs? Also, do you know of any particular projects that are built using only high-level tools or that are built by people without diving deeply in maths?
Answer: It depends. I assume you understand backpropagation algorithm, as it is used by most of NN architectures, and CNNs and RNNs and all that stuff is not that hard if you know backpropagation.
On the one hand, Theano/Tensorflow don't seem to be a good example since they are basically DSLs to write matrix/tensor computations, and they're pretty math-heavy and low-level (you write down actual mathematical operations, and not only use fit, transform/predict api).
On the other hand, there is Keras and scikit-learn, which only have high-level apis, and don't require as much plumbing.
In particular, in Keras you can use some models that were pretrained or have a predefined architecture that is known to work for some problems.
Of course if you don't have good math knowledge you can run into problems with black-box models, but if you just want to apply stuff that seems to work with something to some other thing, then it's definitely possible, for example check out this simple project.
You might also be interested in Creative Applications of Deep Learning with TensorFlow as it seems to be aimed at nontechnical people (I don't know if it's feasible to learn it without any technical background, but at least it contains lots of cool examples).
Answer: The essence of a neural network is the graph.  While graphs may be part of math, their concepts are as old as relationship itself and pre-date it.
If it were necessary for learning to be complex, then brains probably wouldn't have evolved at all, for the probability of ordered complexity is too improbable.
So, then, one must ask: what is the simplest machine that can learn?  But, of course, that begs the epistemological question:  what is learning?
Learning is the juxtaposition of two novel states, forming a memory.  And there you have the basis of AI:  memory.
Comment: This doesn't really add to other answers or indeed address the question directly.


How to echo command result in the command prompt

Question: I want to echo the result of dir comamnd in the command prompt.
How do I do that?
I've already tried:

echo dir
echo $dir
Comment: Run `dir` instead of `echo dir`. Please run in the command prompt window the command `help` to get output an incomplete list of [Windows commands](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands) with a brief description. Every Windows command can be executed with `/?` as argument to get output its usage help in the command prompt window. Try that out with `echo /?` and with `dir /?`.
Answer: an example of this shown in another stackoverflow post is.
<code>FOR /F "delims=" %i IN ('date /t') DO set today=%i
echo %today%
</code>
Displays todays current day.
u could replace that for dir.
Comment: Why is used one of the worst examples from all of the thousands of examples which demonstrate how to capture the output of a command line, process the captured output with `for /F`, and define an environment variable with a string value of (part of) captured output? I explained in [this answer](https://stackoverflow.com/a/57189369/3074564) why the first command line in your answer is one of the worst methods to get current date. The first line can be removed and second line changed to `echo %DATE%` to get same output much faster.


Offline Address Book Synchronization Troubles

Question: I'm unable to access the oab.xml file on my Exchange 2010 CAS.  I've recreated the OAB virtual directory and it didn't make a difference.  Using "Effective Permissions", I've verified that I have rights to view oab.xml, but any attempt to download it remotely (from Outlook 2010 or IE 9) is refused by IIS.  Here are the pertinent log entries --
2012-04-20 18:38:41 126.96.36.199 HEAD /OAB/2c34c9f5-5521-4c8c-b684-538df815052a/oab.xml - 80 - 22.214.171.124 Microsoft+BITS/7.5 401 2 5 203
2012-04-20 18:38:44 188.8.131.52 HEAD /OAB/2c34c9f5-5521-4c8c-b684-538df815052a/oab.xml - 80 - 220.127.116.11 Microsoft+BITS/7.5 401 2 5 31
2012-04-20 18:38:44 220.127.116.11 HEAD /OAB/2c34c9f5-5521-4c8c-b684-538df815052a/oab.xml - 80 domain\jdoe 126.96.36.199 Microsoft+BITS/7.5 403 1 64 31
2012-04-20 18:38:46 18.104.22.168 HEAD /OAB/2c34c9f5-5521-4c8c-b684-538df815052a/oab.xml - 443 - 220.127.116.11 Microsoft+BITS/7.5 401 2 5 203
2012-04-20 18:38:48 126.96.36.199 HEAD /OAB/2c34c9f5-5521-4c8c-b684-538df815052a/oab.xml - 443 - 126.96.36.199 Microsoft+BITS/7.5 401 2 5 31
2012-04-20 18:38:48 188.8.131.52 HEAD /OAB/2c34c9f5-5521-4c8c-b684-538df815052a/oab.xml - 443 - 126.96.36.199 Microsoft+BITS/7.5 401 1 2148074254 0
2012-04-20 18:38:48 22.214.171.124 HEAD /OAB/2c34c9f5-5521-4c8c-b684-538df815052a/oab.xml - 443 domain\jdoe 22.214.171.124 Microsoft+BITS/7.5 403 1 5 218

Does anyone have any ideas?
Answer: I've resolved this one.  I thought to try to access the oab.xml file from the server so that I'd see the detailed error information.  It turned out that the issue was with the Handler Mappings in IIS.  Steps to resolve were as follows:

Open IIS Manager and navigate to the the OAB\<GUID> virtual directory.
On the Features page, double-click the Handler Mappings feature.
On the Handler Mappings page, in the Actions pane, click Edit Feature Permissions.
In the Edit Handler Mappings dialog box, I checked Scripts (Read was already checked).


Disable remove pemission on linux

Question: I have made a ftp directory I want that virtual users can create and update folders and files but they can not delete them. how do I suppose to do that? I have created this ftp by vsftp in fedora 16 platform.
Thank you,
Comment: So users can "modify" files to zero length, but they cant delete them?  I think the write bit authorizes both file modification and unlinking - and it can't be seperated.
Answer: You can instruct vsftpd to no longer honor the DELE and RMD commands:
# Disable delete commands
cmds_denied=DELE,RMD

Though user1131467's concern still stands -- if the users can modify files, they can truncate the files or overwrite them with garbage. (Well, the chattr(1) append only attribute can enforce append-only behavior, but this is far from an ideal solution.)
Comment: +1 Other FTP daemons have similar functionality.
Answer: You can find your answer in this page:
http://vsftpd.beasts.org/vsftpd_conf.html
look for the value "file_open_mode" to set the umask for the uploded files to the desired value to prevent the write permission.
the default value is 0666, in your case it may be 0440. (do not forget the leading 0).
Comment: you might also need to do something to prevent them from using chmod.

Disable remove pemission on linux