Action on finite non-abelian group

Question: Let $G$ be a finite, non-abelian group. Show that if $Aut(G)$ acts on $G$ by $\sigma.g=\sigma(g)$ for each $\sigma \in Aut(G)$, $g \in G$, then there exist at least three orbits.
I think I could arrive to a solution but I am not sure if it is correct, I would appreciate if someone could take a look at it to check if I've made any mistakes.  Anyone who has an alternative answer is welcome to share it.
Since for every $\sigma \in Aut(G)$, $\sigma(e)=e$, then there is at least one orbit which contains only one element. Now since $G$ is not abelian, there exists at least  one element $x \in G$ such that $gxg^{-1} \neq x$ for some $g \in G$. So we have another orbit $\mathcal O_x$ which contains at least two elements ($x,gxg^{-1})$.
Now suppose these two are the only orbits by this action. Then, by the class equation, if $|G|=n$ we have $$n=|\mathcal O_e|+|\mathcal O_x|=1+|\mathcal O_x|$$ This means $|\mathcal O_x|=n-1$. But $|\mathcal O_x|=[G:E_G(x)]=\dfrac{n}{|E_G(x)|}$. It follows $n=(n-1)|E_G(x)|$ so $|E_G(x)| \geq 2$.
We obtain the inequality $$n \geq 2n-2,$$ or, equivalently $$2\geq n$$
But if $n=1,2$ then $G$ is abelian which is absurd. It follows that there must be at least three orbits.
Comment: This is correct.
Comment: Thanks for taking a look at it, I am extremely absent-minded so I try to check my solutions with other people.
Comment: (In fact, you found that $n-1$ divides $n$, and that immediately gives you what you want)
Comment: The solution is not correct, because $|\mathcal{O}_x| = [\operatorname{\text{Aut}}(G) : E(x)]$, not $[G : E(x)]$.
Answer: Alternatively:
As you noticed, $\{e\}$ is an orbit, so if there are only two in all, $G\setminus\{e\}$ must be an orbit. This implies immediately that all elements of $G$ which are not $e$ are of the same order $n$. The number must be prime, for otherwise $G$ contains cyclic groups of order $n$ which contain elements which are not of order $n$.
It follows that $G$ is a $p$-group for some prime $p$. Its center is therefore not trivial. Since $Aut(G)$ acts transitively on $G\setminus\{e\}$, it follows that $G$ is abelian.
Comment: Nice answer :)!

Action on finite non-abelian group


NSTimer Repeat x times only, then call a selector when it invalidates

Question: Primarily I'm looking for a way to create an nstimer scheduledTimerWithTimeInterval that repeats every 3 seconds 10 times then invalidates just as a no-repeating timer would. Is this possible? Ideally an additional selector would fire once the timer invalidates too
Answer: Just keep track of the number of loops and keep a reference to the timer object.  Then just invalidate it when you've done enough.
<code>// ivars
int loopCount;
NSTimer *myTimer;

// Method that calls your timer.
- (void)doStuff {
    loopCount++;
    if (loopCount >= 10) {
        [myTimer invalidate];
        myTimer = nil;
    } else {

        //do my stuff here...

    }
}

// Method that kicks it all off
- (IBAction)startDoingStuff {
    myTimer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                               target:self
                                             selector:@selector(doStuff)
                                             userInfo:nil
                                              repeats:YES];
}
</code>


Equivalence of NP-complete problems

Question: I am currently studying the concept of NP - complete, and I came across a question that I'm not sure about my own answer (currently, it's a "Yes."). The question is: assuming Problem A requires finding a a maximum number of people. I was able to show that Problem A's answer is equivalent to the cardinality of the maximum independent set of an undirected graph $G$. Now, as we know that finding a maximum independent set of an undirected graph is NP-hard, does it imply Problem A must also be NP-hard, which means A is NP-complete?
Comment: There's a distinction to be drawn between *decision problems* (yes-no answers) and computational problems.  Review the definitions of NP-hard and NP-complete.
Comment: @hardmath: Thank you very much for your suggestion. Can you kindly let me know if my argument below is true?

 First, due to the nature of Problem A, it can always be reduced, in polynomial time, to the problem finding the maximum independent set. So it is sufficient to show Problem A is NP-complete if we can show Problem A is in NP. But given a candidate of the solution to Problem A, it is the matter of verifying if that solution is a maximum independent set in a certain graph. Now, verifying if a set is a maximal independent set can be solved in polynomial time.
Comment: To verify if a maximal independent set is actually a maximum independent set, I don't think there is a polynomial-time algorithm to do that. So can we conclude that Problem A is not in NP?
Answer: (In all cases below, by "reduction" I mean "polynomial-time reduction.")
To prove NP-hardness you must show a reduction from an NP-hard problem to your problem.  You have a reduction from your problem to an NP-hard problem (indeed a  parsimonious reduction from your problem to a #P-complete problem) but that is insufficient to show NP-hardness or #P-completeness.  If you don't have a proof of NP-hardness, you don't have a proof of NP-completeness either.
Comment: Thank you for your help. I can show the problem of finding the maximum independent set is *exactly the same* as Problem A. Is that enough to conclude Problem A is NP-complete?

Equivalence of NP-complete problems


Prove: a set of functions is closed if it contains the pointwise limit and converges uniformly to it

Question: When applying the Arzela Ascoli theorem, I am little bit confused as to what needs to be done to show that a set of functions in $C_0([a,b])$ is closed.
Sifting through MSE I found a claim that :

"a set of functions is closed if it contains the pointwise limit and
  converges uniformly to it"

Is this statement true? What is the motivation behind it and can someone provide a reference to or a proof of the above?
Comment: $C_0 [a,b]$ is a normed space. How do you define "a closed set" in a normed space?
Comment: @user251257 Don't know, can you help?
Comment: You surely have some lecture notes...
Answer: A subset $C$ of a normed space $X$ is closed iff convergent sequences of elements of $C$ have their limits in $C$. In other words, convergent sequences in $C$ cannot escape $C$ (hence, the name closed.)
In the case of $C[a,b]$, a sequence $\{f_n \}\subset C[a,b]$ converges to $f\in C[a,b]$ iff
$$
         \lim_{n\rightarrow\infty} \|f-f_n\|=\lim_{n\rightarrow\infty}\sup_{x\in[a,b]}|f(x)-f_n(x)| = 0.
$$
This is equivalent to uniform convergence of $\{ f_n\}$ to $f$.
If you have an equicontinuous set $\mathcal{E}$ of functions in $C[a,b]$, then pointwise convergence of a sequence $\{ f_n \}\subseteq\mathcal{E}$ implies uniform convergence.
Comment: Thank for an actual answer on stackexchange these days! Can you give an example of a closed set? Thanks!
Comment: @TheSilenceoftheCows : An example: The set of all functions $f \in C[a,b]$ that vanish at $a$ and are Lipschitz continuous with Lipschitz constant bounded by $M$. That is, $|f(x)-f(y)| \le M|x-y|$.


Download file direct to specific location using javascript

Question: I am using jsPDF to generate PDF file. What I want to do is when I click save button to save the file to specific location, for example in Desktop.
So far my code does this:
var doc = new jsPDF();
doc.addImage(imgData, 'JPEG', 0, 0, 210, 40);
doc.save('test.pdf');

The .save function just gives us the opportunity to download the file, but what I want is to save the file to specific location, for example C:\Users\username\Desktop.
Thank you.
Comment: Possible duplicate of [Save files into selected directory (javascript)](http://stackoverflow.com/questions/20888867/save-files-into-selected-directory-javascript) (tl;dr: you can't.)
Comment: _" but what I want is to save the file to specific location, for example `C:\Users\username\Desktop`"_ Select `C:\Users\username\Desktop` at `Save File` dialog?
Answer: You can't do that: JavaScript has no access to filesystem.
Comment: what about saving the file in cloud storage, for example in Azure cloud storage any possibility?
Comment: That's really another kind of thing, you would need to use the API (if there's one) to access the cloud storage of the user.


Optimal Strategy for a Combinatorial Game with Asymmetric Information: Warrior Selection Tournament

Question: Game Setup
Bob and Alice are managing a team of warriors. Alice's team consists of warriors with strengths $3, 4, 6, 7$, and Bob has $4$ warriors with strengths $9, 8, 4, 2$ respectively.
If a warrior with strength x fights another warrior with strength y, warrior with strength x wins with probability $\frac{x}{x+y}$ and there is no draw (i.e. the other one dies), and the victorious gains confidence and after the match his strength becomes $x+y$
In this tournament, warriors fight one-on-one, with Alice picking a warrior first for each fight (she picks randomly), and the winner gaining confidence and increasing their strength to the sum of their original strength and the strength of the defeated warrior. There are no draws, i.e., one of the warriors always wins the battle.
The winner of the tournament is the person who has at least one warrior left at the end.
Problem:
What is the optimal strategy for Bob to maximize his probability of winning the game, given that Alice chooses warriors randomly?
My Attempt
I have a gut feeling that there is no optimal strategy, and all strategies lead to the same probability, which is $\frac{\sum \text{Bob's Warriors}}{\sum \text{Bob's Warriors} + \sum \text{Alice's Warriors}}$. I tried simulating the game with a Monte Carlo simulation on Jupiter Notebook and the results seem to agree with my gut feeling However, I am struggling to prove it formally.
Answer: You're right; it doesn't matter which warriors fight which in what order. A battle doesn't change the expectations of the sums of strengths of each player's warriors, since the warrior who enters the battle with strength $x$ has expected strength $\frac x{x+y}(x+y)+\frac y{x+y}\cdot0=x$ after the battle, and likewise $\frac x{x+y}\cdot0+\frac y{x+y}(x+y)=y$ for the warrior who enters with strength $y$. Since the total expectations aren't changed by any of the battles, they're the same at the end of the game as at the beginning of the game, and that implies the winning probability that you conjectured.
Answer: Here is a rigorous proof that every strategy has the same probability of success.
For any $a,b,n\in\mathbb N$, let $p_n(a,b)$ be the probability of Alice winning when her army total is $a$, when Bob's army total is $b$, and when there are $n$ soldiers left between Alice and Bob combined. We will prove that
$$
p_n(a,b)=\frac{a}{a+b},
$$
by induction on $n$. We can take $n=1$ as a base case, which is easy to verify.
Suppose that Alice sends a soldier with strength $x$, and Bob one with strength $y$. Then
$$
\begin{align}
p_n(a,b)
&=P(\text{Alice wins war}\mid\text{Alice wins battle})\cdot \frac{x}{x+y}
\\&\quad+P(\text{Alice wins war}\mid\text{Alice loses battle})\cdot \frac{y}{x+y}
\\&=\frac{(a+y)}{(a+y)+(b-y)}\cdot \frac{x}{x+y}+\frac{(a-x)}{(a-x)+(b+x)}
\cdot \frac{y}{x+y}=\frac{a}{a+b}.
\end{align}
$$
This completes the proof by induction.
Comment: Thanks a Lot for your Response, it was really helpful. The only issue i have is , in the probability course i am taking i havent been taught about Matinagle Sequence and Optional Sequence Theorem , can there possibly by a more elementary approach to this proof ?
Comment: I added in an elementary proof (as long as you are familiar with proofs by induction).


How to change the field name in the url when using views exposed sort?

Question: I've read a few posts on this and there does not seem to be an answer to that, is that right?
My exposed filters allow the user to change the sorting, but the url is kinda bad:
?sort_by=field_rating instead of just ?sort_by=rating, for instance. Can this be achieved somehow? Is it advisable to try out better exposed filters module when you have already kind of customized your exposed filters? /:
Answer: For order_by filter you can just set the filter identifier:

Although there is no option to set the identifier for sort_by filter, you can achieve your goal by altering the form.
Example
/**
 * Implements hook_form_alter().
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form['#id'] == 'YOUR-FORM-ID') {

    // fields which you want to rename
    $form_state['my_custom_names'] = array(
      'field_rating_value' => 'rating'
    );

    // rename option values
    foreach ($form_state['my_custom_names'] as $name => $new_name) {

      $form['sort_by']['#options'][$new_name] = $form['sort_by']['#options'][$name];
      unset($form['sort_by']['#options'][$name]);

      if ($form_state['input']['sort_by'] == $name) {
        $form_state['input']['sort_by'] = $new_name;
      }
    }

    // the custom submit handler need to be fired before the original one
    array_unshift($form['#submit'], 'my_custom_exposed_form_submit');
  }
}

/**
 * An additional submit handler for exposed filters.
 */
function my_custom_exposed_form_submit(&$form, &$form_state) {

  // set the form state values to their original names.
  foreach ($form_state['my_custom_names'] as $name => $new_name) {
    if ($form_state['values']['sort_by'] == $new_name) {
      $form_state['values']['sort_by'] = $name;
    }
  }
}

Make sure to replace YOURMODULE and YOUR-FORM-ID with proper names.
Comment: that doesnt work for sorting nor the way tids show up in the url
Comment: because there are no filter identifiers in sort fields?
Answer: That's how views are built, the only way to fix that would be to change how you filter, you can try using views contextual filters and see if that works for you. But exposed views filters equate to query strings with field names, otherwise how would views know that "rating" actually means "field_rating" without adding additional overhead to the database.
Comment: i dont know, i thought there might be some alias-ing method. better exposed filters didnt work either. i am afraid i gotta do this with htaccess regex


Gerando campos por código ASP.NET

Question: Estou fazendo uma aplicação web com ASP.NET e C#.
Nessa aplicação eu posso cadastrar vários itens de um mesmo tipo, por isso ela tem um campo texto e um botão do lado para criar novas caixas de texto. Já trabalhei com isso em desktop app, mas não sei como gerar os campos no arquivo .aspx.
Como posso fazer isso? Devo fazer esse comando no .aspx ou no .cs? Como posso passar os dados depois?
Comment: Não é claro o que você está perguntado, considere reformular sua pergunta de forma mais clara e objetiva.
Comment: Eu quero gerar campos em tempo de execução, só isso
Comment: @jpklzm Deixa eu ver se entendi, você quer gerar campos dinamicamente no browser do usuário? Por favor coloque um pedaço do código que vc usa para gerar o primeiro campo, e informe se o objeto gerado será "clone" desse.
Comment: Isso mesmo @LeandroAmorim. Mas quero fazer por C# ou ASP.NET(não sei se existe essa possibilidade)
Answer: TextBox txt = new TextBox();
txt.ID = "textBox1";
txt.Text = "helloo";
form1.Controls.Add(txt);

Comment: Tente Fazer respostas mais completas, além de ecrever o código escreva qual o objetivo e se for o caso explicar o que cada função utilizada (ou apenas as principais) faz, assim sua resposta terá mais qualidade
Comment: Qual foi o motivo do voto negativo nessa resposta? É importante fazer um comentário.
Comment: Eu não negativei essa resposta. Na verdade estou testando ela.
Comment: Só chama esse pequeno bloco de código no método do click do botão.
Comment: Então, quando eu tento adicionar ele pede para dizer que o campo é runat=server. Como faço isso?

Gerando campos por código ASP.NET


Problema com balanceamento de parenteses, em Python

Question: Galera to com o seguinte código:
exp = str(input('Digite a expressão: '))
pilha = []
for simb in exp:
    if simb == '(':
        pilha.append('(')
    elif simb == ')':
        if len(pilha) > 0:
            pilha.pop()
    else:
        if simb == ')':
            pilha.append(')')
            break

if len(pilha) == 0:
    print('Sua expressão está "Correta"!')
else:
    print('Sua expressão está "Errada"!')

Se você executar o código colocando como exemplo:
(((2*2)-1)*(1+4)) assim parece correto
(((2*2)-1)*(1+4))) com parentese a mais do lado direito também aparece correto
((((2*2)-1)*(1+4)) agora com um parentese a mais do lado esquerdo aparece errado
ou seja ficou
((())()) aparece certo
((())())) aparece certo
(((())()) aparece errado

Onde estou errando?
Answer: Trata-se de um problema conhecido como balanceamento de parênteses, e as soluções mais comuns sugerem pilha, fila e eliminação. 1 2 3
Primeiro vamos ao problema em seu código:
    elif simb == ')':
        if len(pilha) > 0:
            pilha.pop()
    else:
        if simb == ')':
            pilha.append(')')
            break

A parte else: if simb == ')': é semelhante elif simb == ')':, portanto nunca será executada, já que a condição é satisfeita no elif.
O problema está em quando você encontra len(pilha) == 0 (ou o else da condição if len(pilha) > 0, você ignora, mas este é antes de mais nada um parênteses desbalanceado, ou seja um fechamento antes da abertura.
Para corrigir isso você pode apenas alterar o else como parte do if len(pilha), ficando:
for simb in exp:
    if simb == '(':
        pilha.append('(')
    elif simb == ')':
        if len(pilha) > 0:
            pilha.pop()
        else:
           pilha.append(')')
           break

Abaixo outra maneira de se resolver um pouco mais didática, com contador:
abertos = 0
for c in exp:
    if c == '(':
        abertos += 1
    elif c == ')':
        abertos -= 1
        if abertos < 0:
            break

print('balanceado' if abertos == 0 else 'desbalanceado')

Answer: Em uma tradução livre desse artigo na wikpedia (em portugues está estranho) "Parentheses matching, Brace matching ou bracket matching refere-se ao recurso chamado "realce de sintaxe" que certos editores de textos e ambientes de desenvolvimento oferecem realçando as aberturas e fechamentos de braces (parenteses, colchetes, ou chaves)". Como diz o artigo, o conceito engloba a abertura e fechamento não só dos parenteses, mas também dos outros "braces", apresento abaixo um algoritmo para esse problema e, em seguida, a codificação em python.

Algoritmo:

Percorra toda a expressão checando cada caracter;
Se o caracter não for um bracket, ignore;
Se for um bracket de abertura, adicione-o à pilha;
Se for um bracket de fechamento:
  4.1 Retorne False se o ultimo caracter da pilha não for um bracket de abertura correspondente;
Remova o bracket de abertura correspondente da pilha;
No final retorne True se a pilha estiver vazia, se não retorne False.

Código em python:
def parenthesis_matching(brackets):
    __open = ['(', '{', '[']
    __close = [')', '}', ']']
    __stack = []
    if brackets=='':
        return False
    for b in brackets:
        if b in __open:
            __stack.append(b)
        elif b in __close:
            if __stack==[]:
                return False
            open_b = __open[ __close.index(b) ]
            last = __stack.pop()
            if not open_b == last:
                return False
    return True if __stack==[] else False

# Expressoes para testar o código
exps = []
exps.append('(a[0]+b[2c[6]]) {24+53}')
exps.append('f(e(d))')
exps.append('[()]{}([])')
exps.append('((b)')
exps.append('(c]')
exps.append('{(a[])')
exps.append('([)]')
exps.append(')(')
exps.append('{[(stackoverflow),(parenthesis_matching(brackets))]}')

# Testando o codigo
for e in exps:
    print(e+' : ', parenthesis_matching(e))

Saida:
(a[0]+b[2c[6]]) {24+53} :  True
f(e(d)) :  True
[()]{}([]) :  True
((b) :  False
(c] :  False
{(a[]) :  False
([)] :  False
)( :  False
{[(stackoverflow),(parenthesis_matching(brackets))]} :  True

Veja funcionando no repl.it.


Polynomial regression interaction features

Question: In polynomial regression input vector $[a,b,c]$ is transformed into $[1, a, b, c, a^2, b^2, c^2, ab, ac, bc]$ before linear regression is applied. At least this is how sklearn.preprocessing.PolynomialFeatures is doing it.
Why interaction features $a^2b, a^2c, b^2a, b^2c, c^2a, c^2b$ and $abc$ are not included?
Comment: Those would be third order interactions and `PolynomialFeatures` has set the default for `degree` to be 2.
Comment: @DemetriPananos Oh I see. It makes sense. Thank you.
Comment: @Demetri Pananos: do you want to post your comment(s) as an answer?
[Better to have a short answer than no answer at
all.](https://stats.meta.stackexchange.com/a/5326/)
Anyone who has a better answer can post it.
Comment: @kjetilbhalvorsen Sure, will dp
Answer: Note that the features you list are the product of 3 terms, hence they are third order interaction terms.
According to the documentation, the default degree computed for the Polynomial transformer is degree=2.  Additionally, if you only wanted those features and not the homogenous terms ($a^3, b^3, c^3$) you could set interaction_only=True.


Per-group repetitions of another captured group

Question: Say I have a large input stream with structure:
key1 valA,valB
key2 valC,valD,valE

The number of values per-key is unbounded, as is the key/value text, besides predefined delimiters ',' and ' '.
Is there a sed one-liner to "flatten" it by line?
key1 valA
key1 valB
key2 valC
key2 valD
key2 valE

I realize this is a very simple Awk or Perl script.  Just wondering if it can be done with straight-up regex.
Answer: awk is here buddy:
AMD$ awk '{gsub(/,/,"\n"$1" ")}1' File
key1 valA
key1 valB
key2 valC
key2 valD
key2 valE

Just substitute all ,s in the line with (newline followed by the first field followed by space). Then print all the lines (thats what 1 is for). Thats it.
Comment: I realize this is a very simple Awk or Perl script. Just wondering if it can be done with straight-up regex.


Modules to set credits/points

Question: I'm looking for a module to allow myself or other moderators to set credits/points for each site member. The site members can use the credits to purchase items in the store.  I don't want to use any real world currency for the transactions, just virtual points.
This site is for an online guild. My hope is to set up a reward system and give each member points for being active in the guild, they can turn around and use the points to get content for their characters in game.
Is there any module that would help me achieve this?
Answer: I did a google search and found the Commerce Credits module; it sounds like what you're looking to do.

Commerce Credits allows you to have users buy or win credits. The credits these users buy or win are fully configurable and can expire after some time. The process used for these credits is also fully configurable through Rules. It allows you to entirely define your own process for the payment and the use of these credits.

Modules to set credits/points


How to use modal dialog with Angular and VMware Clarity?

Question: I need to display a modal dialog control with a question and yes/no buttons, wait for the user's choice, then run some code to perform the selected action.
The VMWare Clarity documentation is very clear about the markup inside the dialog, but it does not talk about how to show or hide it.
I'd love a complete example, thank you.
Comment: .... I mean reusable solution, something like dialog service, not fixed dialog control in every component - this is usable in small applications.
Comment: I think an issue is already filed for this: https://github.com/vmware/clarity/issues/1364. Is this what you are looking for? If yes, you should subscribe to that for more updates from the Clarity team.
Comment: Thank for link - that discussion is about dialog service, but without solution.
Comment: Your question is not clear. Do you mean to say that you want to act on an input user provided in the dialog? You can use `ngModel`. Please describe in detail what you are looking for.
Comment: Need somethig like this, for angular 4: (sorry for bad formatting, I use `` but it not work here)

`
dialogservice.confirm("Are you sure?", {title : "Dialog title"})
          .then(function(p) { code for success },
                function(p) { code for fail }
          );
`

As you see, everything is at one place and simple.
Comment: Still not clear?
Answer: I'm assuming you are describing a situation where you want to confirm an action (like confirm you wish to delete an item), and if so you should review the code found here. You can follow the methods it calls to see the logic.
https://github.com/gnomeontherun/clarity-workshop/blob/master/src/app/budget/budget/budget.component.html#L56
This is a delete button that calls a method, which then opens a modal dialog. The user then confirms or cancels, and then if they confirm it calls the API to actually delete.
If you'd like to make your own service to control the modal, you can follow the example I have for an alert service and alert component (but change it to a modal). https://github.com/angular-in-action/portfolio/tree/master/src/app/alert
Comment: Thank for answer. Yes, I need to wait for user response and then do some action. Your example in link above use create  for every dialog in every component where dialog is needed - modal dialogs are part of component. There are some dialog service in npm sources, but unfortunately is not maintained for angular 4/5.
Comment: Clarity modals are declarative, and do not have a service currently. It is a feature request here https://github.com/vmware/clarity/issues/1364 if you'd like to submit more details about your expectations.
Comment: Also you could have one 'global' modal, and create your own service to control when it appears and what it displays.
Answer: Let's assume the user clicks on a "Delete order" button, and you want to display a modal dialog with "Are you sure?" and "Cancel" and "Delete" buttons.
Jeremy's example above is great. Here is a minimal implementation:
In order.component.ts:
isModalVisible = false;

deleteOrder() {
  ...
}

In order.component.html:

  ...
  <button (click)="isModalVisible = true">Delete Order</button>
  ...

<clr-modal [(clrModalOpen)]="isModalVisible">

Delete order?

This cannot be undone.

    <button type="button" class="btn (click)="isModalVisible = false">Cancel</button>
    <button type="button" class="btn (click)="deleteOrder()">Delete</button>

</clr-modal>

Angular 6.1.9, Clarity 0.13.4


$Name not sent through HTML mail form

Question: i found a good html mail webform online thanks to the people at CSS-tricks and everything seems to work fine. The form uses PHP as a module installed on Apache. In the form I ask for the user's name, emailaddress and a comment. Everything but the user's name arrives in my mailbox. I can't seem to find the reason why this doesn't work. This is my HTML-code:

        <form method="post" name="contact_form" action="contactengine.php">

                Name

            <input id="Name" type="text" maxlength="455" value=""/ size="41>

                Email

            <input id="Email" name="Email" type="text" maxlength="455" value=""/ size="41">

               Message

              <textarea id="Message" class="comment-box" name="Message" maxlength="455">
              </textarea>

            <input type="hidden" name="form_id" value="" />
            <input type="submit" name="submit" value="Submit" class="submit-button" />

      </form>

This is the PHP-code:
<?php

$EmailFrom = "firstname.lastname@example.com;"
$EmailTo = "firstname.lastname@example.com";
$Subject = "Mail";
$Name = Trim(stripslashes($_POST['Name']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>

I assume that the PHP-code under //send mail would insert everything the user enters into the mail and send it to my mailbox. That means that it takes all data entered under $Body, which includes $Name. Yet it never sends me the name.
I also wonder why in the first field "$EmailFrom" i should have to enter a fixed emailaddress (in this case 'firstname.lastname@example.com') while the user enters his address in the html form and that gets sent within the mail i receive. The $EmailFrom field is just for me to see who has sent a mail without having to open the mail. It should also be the user's mail address or the user's name.
I hope i made myself clear enough?
Thanks in advance, i have already found lots of valuable answers on this site regarding other topics :)
B
Comment: `stripslashes`? Why? Are you stuck on an out of date server with Magic Quotes turned on, or do you just want to break user input?
Comment: Why are you redirecting people with `meta` instead of `Location` HTTP headers?
Comment: i found this form through a tutorial online dated 2007 so i assume some functionality might be deprecated. But just to be informed, can i delete the stripslashes and if so how would i do it?
Comment: Same for the redirecting, is it best practice to use Location?
Comment: Probably. Just remove the call to the function. Yes. Doing thing at the HTTP level is much more sane then sending an HTML document which does the same thing.
Answer: Only form controls with name attributes can be successful. You don't have one.
<input id="Name" type="text" maxlength="455" value=""/ size="41>

should be
<input id="Name" name="Name" type="text" maxlength="455" value="" size="41">

Answer: You forgot to put name property in input tag

<input id="Name" type="text" maxlength="455" value="" size="41>

change to

<input id="Name" type="text" name="Name" maxlength="455" value="" size="41>

Answer: You just forgot to set name="Name" in addition to id="Name" ;)
Answer: You should add name attribute for your input tags,
<input id="Name" name="Name" type="text" maxlength="455" value="" size="41>

$Name not sent through HTML mail form


What is error: "Base table or view not found: 1146"

Question: Base table or view not found: 1146 Table '(database).(entity)__(field_name)' doesn't exist
I have problems running my site since i deleted field (field_name) from entity (entity), to be clear entity was created from ContentEntityType.
What kind of field is it, if it has it's own table and those two underscores in table name?
How can i create field of this kind to solve this error?
It is quite urgent and my bad is i don't have any database backups.
Comment: How did you delete the field?
Answer: Found the fix!!! (Yes, i am user96758)
After 3 hours of investigation, internet and uncle Google wasn't helpfull at all.
The problem was that field was created via Drupal UI in Content Type -> Manage fields.
And it was deleted programatically by using UPDATE (code example below), not by using UI.
function hook_update_N(&$sandbox){
    $update_manager = Drupal::service('entity.definition_update_manager');
    $definition = $update_manager->getFieldStorageDefinition('field_name', 'entity_id');
    $update_manager->uninstallFieldStorageDefinition($definition);
    return t('Entity: field was uninstalled');
}

I have installed module named "Devel", which is pretty good damn module and every developer should have it.
I was finding anything that contains name of my problematic field.
Thanks to Devel module i was able to find config of this field.
Usually you can see all configs at url (your_site)/devel/config
Well, i was desperate, so the last chance was to delete the config i found.
Usually the fields are named: field.field.(entity).(entity).(field_name)
I removed the config with this code below
Drupal::configFactory()
    ->getEditable('field.field.(entity).(entity).(field_name)')
    ->delete();

Then i CLEARED CACHE and IT WORKS AGAIN!
Comment: So, if i can ask someone to set this question as "Solved". Thanks again :)
Comment: To mark the question as solved, log in as user96758 and accept your answer.


Add production into development React Webpack config

Question: I have a simplest possible React environment.
That is very efficient in development.
var webpack = require('webpack');

const config = {
  entry: "./index.js",
  output: { filename: "bundle.js" },
  devtool: 'eval',
module: {
   loaders: [
    {  test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['react', 'env'] }  }
   ]
  }
};

module.exports = config;

What I want to do is to add a production build so as to run in console script like this: npm run build, which is defined in package.json:
"build": "webpack --config webpack.config.js"
How can I add production plugins and devtool: "cheap-module-source-map" so that they will work only in production and were not included into development. By production plugins I meant these:
new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }),
new webpack.optimize.UglifyJsPlugin()

I failed to use
var debug = process.env.NODE_ENV !== "production";

with devtool: debug ? "cheap-module-source-map" : "eval",
and
plugins: debug ? [] : [//production plugins here ]
Answer: It's common practice to create a separate file for production config and to change properties there.
webpack.config.production.js:
var webpack = require('webpack');
var config = require('./webpack.config');

config.devtool = 'cheap-module-source-map';
config.plugins = (config.plugins || []).concat([
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('production')
    }),
    new webpack.optimize.UglifyJsPlugin()
]);

module.exports = config;

Answer: It sounds like you are having trouble with the environment variables, which is definitely the way to go. If you post more details I can help figure out the problem.
As an alternative, you can copy your dev config to a file called webpack-prod.config.js and add your production stuff there. Then run it using "build": "webpack --config webpack-prod.config.js"


Is there any way to create a POST HTTP request using window.location?

Question: I have a web app built using node and express, and there is a form I want to submit in an ejs file, but I cannot use form.submit() because I want to pass parameters in the URL.
The form's id is "update" and the submit buttons id is "btnsubmit", I am currently trying to send the post request as follows:

var form = document.getElementById("update");
document.getElementById("btnsubmit").addEventListener("click", function () {
  var lp = "1";
  window.location = ("/dbinsertupdateditem?loadpage="+encodeURIComponent(lp));
});

On button click I get the error: Cannot GET /dbinsertupdateditem, because the express route is expecting a POST request. Is it possible to make a POST request with window.location or do I need to go about a different way of solving this?
Comment: No, window.location.href is a GET. You need need to post a form.
Answer: You can not change how window.location.href works. As a result, you need post a form if the router expects it to be a post. If you have a form on the page you can just set the action
var form = document.getElementById("update");
form.action = "/dbinsertupdateditem?loadpage="+encodeURIComponent(lp);
form.submit();

If you do not have a form, create one
var form = document.createElement("form");
form.method = "POST";
form.action = "/dbinsertupdateditem?loadpage="+encodeURIComponent(lp);
document.body.append(form);
form.submit();

Or probably the best answer, change your backend to allow GET
Comment: Awesome that works thank you. If I were to change the backend to allow GET would I still be able to access the ```request.body``` that is sent when the HTTP POST request is made??


Is it considered possible for women to compete with men professionally in team sports played with a ball other than baseball?

Question: In Little League play, a 13-year old girl, Mo'ne Davis, stunned the baseball world with her 70 mph fastball. Assuming that she "fills out" adequately during her adolescence, it is at least within the realm of possibility that she will develop a 90+ mph fastball with the requisite control to pitch in the majors. And if not her, perhaps another woman like her.
This situation came about because in baseball, you "play the ball, not the man." Assuming you have the required skills to handle the ball, you don't have to worry about being "overpowered" by a larger man.
Are there other sports other than baseball (or tennis, another "non-contact" sport) where there are female high schoolers (or college players) "coming up" that could plausibly play professionally against men? Or are the odds considered too long in contact sports?
Comment: I suspect this question is going to get into another "what's a sport?" discussion. Women already compete professionally against men in things like motor racing, snooker and chess.
Comment: @PhilipKendall: I meant to ask about TEAM sports played with a ball (not one on one) and made that change in the question.And the last paragraph narrows it further to "contact" sports, not including "motor racing, snooker, and chess."
Comment: It might be better if you simply list the sports you consider acceptable answers - I answered assuming the American Big 5 but of course a list could include things like Cricket and Rugby if you wanted to be more international.
Comment: It's probably not considered a sport, but I bet women curlers would compete favorably against men.
Comment: `Melissa Mayeux, a shortstop on the French U-18 junior national team, became the first known female baseball player to be added to MLB's international registration list, which means she will be eligible to be signed by a Major League club on July 2.`.  [see article](http://m.mlb.com/news/article/132044338/melissa-mayeux-france-eligible-sign-mlb)
Answer: The closest a woman has ever come to playing in a major North American sport is probably Manon Rhéaume, who was a goaltender for in the NHL's Tampa Bay Lightning system. She played in an NHL exhibition game and some professional minor league games. The trend seems to be that NHL goaltenders are getting bigger, which makes a woman playing in the NHL less likely, but this might still be the most likely opportunity in North American professional sports.
The knuckleballer Eri Yoshida pitches in a Japanese (independent) minor league against men. A knuckleballer is probably the best opportunity for a woman to make it to Major League Baseball.
At the high school level, there are examples of girls winning against boys in wrestling matches. The weight classes are a huge assist at leveling the playing field there. Of course, there's not really a professional outlet there. I wonder how it would play out in boxing or MMA, although the public might not take to men fighting women.
Answer: There is Korfball: http://en.m.wikipedia.org/wiki/Korfball
Mixed sport, but mainly played in the Netherlands and Belgium.
Comment: It is a requirement for them to have mixed teams.  Why would this be an answer?
Comment: This is not an answer.  Then mixed doubles tennis would be an answer.  This has nothing to do with the spirit of the question.
Comment: Men and women compete in a team sport played with a ball, that their attendance is mandatory is not that important. The flow of the game allows it to be a mixed sport. Contact is limited to (almost) none, technique is more important than physical powers.
Answer: The most likely team sport position (of the major professional league sports in the US, ie Hockey, Basketball, Baseball, American Football, and Soccer) for a woman to play in would be kicker in the NFL; this has come fairly close a few times, with several women playing in college football in that position.  Lauren Silbermann tried out in 2013 with the New York Jets, although she had no success (as she was injured in the tryout).  Several woman have played in college and semi-professional leagues, as Wikipedia notes.
Ultimately even there it will be difficult for a woman to play professionally, because the leg strength for kickoffs is critical - many statisticians believe the only repeatable success kickers have is in gaining a touchback on kickoff, with most other elements being fairly random.  This would be likely the weakness for a female kickers, so even a highly accurate kicker would be weaker on kickoffs and thus have a competitive disadvantage - but who knows.
Answer: To answer this question concerning the most popular sports in the US (Baseball, Basketball, Football, Hockey, and Soccer) it can largely be view by size and athletic ability.
This answer assumes the average woman to be smaller than the average man and the athletic abilities to correspond.  It also applies to only these 5 sports.
Of the sports listed, Basketball and Football are most reliant on size.  This chart shows the average size of players from various sports.
In those two sports, women would have basically no chance because of their limited size combined with the superior athletic ability of men.  Except for a possible long shot of kicker/punter as @Joe explains.
This leaves us with the other three sports:

In the NHL the only position that a woman would stand a chance physically is at goaltender.  @jerepierre has already touched on this.
In soccer the women could match up with the average size according to the business insider article, but the men would be superior in athletic abilities such as jumping and sprinting.
Women would have the best chance in the MLB as a knuckle ball or junk ball pitcher.  To do this they wouldn't necessarily have to be athletic or big.  They would need to perfect their craft of being a junk baller.  This would also obviously lead to other issues besides talent, but as John Kruk once said, Lady, I'm not an athlete. I'm a professional baseball player.

Obviously sports that combine size and athletic ability would be an advantage to men.  This encapsulates most sports.  The possible niche being a sport where technique and practice can over take.  A good example is pitching in baseball.

Notes:
I stated in a comment on @Coach-D's post that I played NCAA baseball and we used to scrimmage the women basketball team at our school.  They had some players that were taller than our players, and they were more fundamentally sound than we were.  We would regularly beat them, and beat them easily.
The thought that Mo'ne Davis could compete in the MLB with a normal skill set (by which I mean a fastball and two off-speed pitches) is absurd.  Unless she developed a devastating knuckle ball she wouldn't stand a chance.  This is purely physiological, females mature earlier than males and most likely we saw the best pure athlete that she will ever be.  Don't get me wrong she could refine mechanics and control, but the likelihood she throws over 85 MPH ever is slim.  If she were able to do that, then she would join the club of thousands of males in the minor leagues and independent leagues that can do so also.

I don't not consider baseball a sport where you play the ball and not the man, as hitting versus a pitcher that throws in the 90's vs the 70's is a significant difference.  A sport that could fit into that is golf.  The ball lies the same no matter whom is playing it.  This leads to Annika Sorenstam who played with the men on the PGA tour and missed the cut in the Bank of America Colonial tournament.  During the same year she was able to win on the LPGA tour, leading me to believe that even for a woman to make the cut on the PGA tour would be a significant accomplishment.
Answer: Ultimate frisbee supports co-ed play up to the highest levels of sport. Even at the WFDF World Championships, there is a separate mixed division where co-ed play occurs. While ultimate is technically a non-contact sport, incidental contact occurs all the time (and is mostly not penalized). Each team does have to field the same number of women, though, so this is not a perfect example of gender equality in sports.
Comment: The title limits the scope to only sports played with a ball, so Ultimate Frisbee wouldn't count.
Answer: OK Mo'ne Davis is a horrible example.  Chances are she doesn't grow at all and her fastball hits 75 mph max.  Many 13 year old girls are fully grown, height-wise.  I have personally been around 2 very athletic girls that were very similar to her - one as an umpire and another I personally coached.  The girls at 13 are just more mature than boys of that age psychologically and developmentally.  Boys hit their growing spurt around 14-15.  So girls have two years in school that they might be faster or more talented in the strength/speed sports.  [Actually 4 years ago one of my boys played against a 12 year old girl in football that was laying kids out.  She is talented and will probably have multiple big-time college offers for 2-3 sports but you would laugh if she had football pads on now.  She's 5-8 120 pounds... almost the same size as when she played football]
I want a disclaimer to my answer in that I am pretty strict what I consider a sport.  Auto racing, board games, and strategy games are not sports to me.  I personally feel that bowling is not a sport (but a great game) and golf is right on the lowest fringe of sport.
Do women have a chance?  Well not anytime soon.  They just don't have the physical attributes that will help them, unless they start altering their physical attributes.  I remember my college (large D1 school) having the WNBA players stay in the dorms over the summer.  I was on the basketball practice team.  Was probably at the level of a DIII starter but nothing great.  We would play the WNBA girls daily.  My team would include 1-2 guys from practice squade and 2-3 "good" pickup players.
In their three weeks there the WNBA players never won a game.  They scratched, clawed, brought out their 6-7 big, it didn't matter.  They couldn't stop our first step or the power drive.   Number don't lie.  We won probably close to 100 games.  Most of these girls were stars at big D1 programs.  We didn't hold back at all (mainly because they started playing dirty in game one) but we weren't also "great" players.  I believe all of the girls we played were better basketball players than us - fundamentals, shooting, tactic, positioning, whatever - but the athletic disadvantage was too much to make up.
What sport are women closest to catching men?  I would think it would be the marathon.  Running that distance requires using your body's existing fat reserves.  Women have an advantage here.  They can possibly be lean and in race shape with more fat in their body.
Comment: I second your women's basketball example. During the fall the baseball team would play the women's basketball team in games and easily beat them. Their coaches tried to hold us back but pure athleticism won almost every time.
Comment: Mo'ne's 5'4'', and 110 lbs. I could imagine her growing to 5'7" or 5'8" and 140 lbs. in three or four years. Using this trajectory, 90 mph is a "stretch" but not out of the question. And even 88 mph and "good command" might get her "drafted," but perhaps not all the way to the majors.And baseball is not a contact sport like basketball. Perhaps it is more like golf, "on the lowest fringe."
Comment: @TomAu - that is not how it works with a young girl's progress.
Comment: @Joe - My point wasn't that women would catch men in the marathon.  It is just that the upper tier of athletes is really closer than any other sport that I can think of (and seems to be getting closer - where ever this might plateau).  Could a woman play minor league baseball with a knuckleball, maybe.  Could a woman be top 50 in the world at baseball... no.
Comment: 5'8" would be a stretch.  75 mph might be a stretch.
Comment: 5'5" and 75 mph this year (2015). 5'6" and 80 mph by next year, 2016. After that, I don't know (just taking the overs).
Comment: Really, marathon runners?  Sorry, there's some chance a physical 'freak' could be successful in something like baseball (particularly in a niche, like having a really amazing curveball - Mark Buehrle and others have managed with low 80s fastballs with other interesting pitches, or a knuckleball or similar), but marathon, absolutely no way.  The reference to 'fat reserves' doesn't make any sense at all (or find a link).  I don't entirely disagree with your answer (though I find the style abrasive and too informal for this site) but that last paragraph is flat-out wrong.
Comment: @Joe - http://www.smh.com.au/executive-style/fitness/catch-her-if-you-can-20110627-1gobc.html - Sorry it doesn't make any sense.  My life is training people and maybe I was assuming that people knew that fat reserves are used for high endurance activities.  Here is another link refuting my claim but also showing women climbing on men bigtime in marathons http://sciencebasedrunning.com/2011/06/women-are-unlikely-to-catch-men-in-the-marathon/
Comment: That first article is not talking about professional runners - but about recreational ones.  Look at marathon times - top woman runner would normally be in the 20s or 30s compared to top male runners, and even a world record woman would be something like 10th (I used 2012 Boston as my example, [here](http://www.marathonguide.com/results/browse.cfm?MIDD=15120416&Gen=M&Begin=1&End=100&Max=12588), though other marathons are typically similar).  Paula Radcliffe finished [15th](http://www.marathonguide.com/results/browse.cfm?MIDD=16030413&Gen=B&Begin=1&End=100&Max=32167) in London when she set
Comment: her record.  Women are climbing on men in times largely because male marathon times are probably reaching the minimum possible time (without some major change in physiology), but I don't see a woman being competitive for first place (which I assume as the bar for 'competing with') under any circumstances in marathons (though I guess that bar is more complicated given top 30 MLB Pitchers would be harder...)
Comment: I guess that's why the question was ball-specific; it's really sort of a different question.  Women do now currently run races with men, but they don't really have a chance to win - but Paula Radcliffe was a top-25 runner certainly in her prime.
Comment: @Joe - your example of kicker might seem the closest (because schools with no kickers let girls play) but there is NO chance.  I was 3rd string kicker high school and 4th-5th string in college.  We had a couple girls from the soccer team do some test kickoffs because this was the height of women kicking.  They could maybe get it to the 20 on kickoffs.  I was getting it to the 5-10 consistently and I sucked.  The gap between the worst kicker in the NFL and the woman with the biggest foot is very very WIDE.  I would bet on baseball pitcher before this.  Kicking is pure strength/explosion.
Comment: It's probably the closest as far as someone actually coming close to doing it professionally, despite that (given women have tried out!).  But I agree, it would be very difficult.
Comment: @Joe - But there has never been a team that has seriously thought about signing a women to kick professionally beyond trying to get some PR.  I mean a women could kick for an NFL team and make a few FGs and XPs.  So could I.  I don't think we should "count" something because it is a nice thing to do or for media hype.  The question should be answered based on merit of the athlete.
Comment: @TomAu - great to revisit past answers.   I wouldn't quit your day job!   5'5" and 75 mph huh?   She topped out at 5'4" and fastest pitch recorded was 71 mph.


Keep left menu in every event node

Question: I created the event calendar using calendar view module. suppose If I click the particular event in calendar it will goes to particular event detail page but suddenly the left menu is disappear. How do I keep my left menu in all the event details pages?
Please assist me on this
Answer: You can use the Context module to set the block active on content types and url wildcards (ex. /event/*). There are also much more conditions available with Context.
Comment: Thx kevin.I done this

Keep left menu in every event node


Why are not all stylesheets in mytheme.info being loaded?

Question: I have a strange issue, when I include the last CSS file (assets/fonts/montserrat/style.css), then the assets/css/style.css doesn't get loaded. It seems to have to do with duplicate naming of files, when I rename the stylesheet to montserrat.css, the issue is gone.
How do I solve this issue while keeping the naming of files intact?
mytheme.info:
name = mytheme
description = My custom theme
core = 7.x

stylesheets[all][] = assets/plugins/bootstrap/css/bootstrap.min.css
stylesheets[all][] = assets/plugins/font-awesome/css/font-awesome.min.css
stylesheets[all][] = assets/css/style.css
stylesheets[all][] = assets/css/custom.css
stylesheets[all][] = assets/fonts/montserrat/style.css

Comment: I mean not to be a jerk, but ... you already solved the problem.
Comment: The question is why, and how to solve it while keeping the duplicate names. It seems preposterous that you would have to rename your files for this.
Answer: the answer is in the drupal_get_css doco page:

Themes may replace module-defined CSS files by adding a stylesheet with the same filename. For example, themes/bartik/system-menus.css would replace modules/system/system-menus.css. This allows themes to override complete CSS files, rather than specific selectors, when necessary.

If you look at the source code at the bottom of the page, the array that contains the css has the basename of the file as the key. So this is an intentional feature.
You will just have to keep the renamed file.
Hope this helps. :)
Comment: Just FYI, I reported it as a bug: https://www.drupal.org/node/2855529
Comment: It will be a duplicate of https://www.drupal.org/node/2303161 or at least a related issue.


MySQL Columns from Recordset

Question: Maybe I am looking at this all wrong or something. I have this table, prices. When I new price is reported it goes into the table and has the type, price, stationid, and date. I can get the result but I want to have the stationid listed and the different fuel types and their prices in the columns.
Here is a sample table http://sqlfiddle.com/#!2/8c04c/1
This is what I am going for, the latest price for each station for each row:
---------------------------------------------------------------------------------------------------------------------------------
stationid    |    regular    |     regDateAdded    |    midgrade    |     midDateAdded    |    premium    |    preDateAdded
---------------------------------------------------------------------------------------------------------------------------------
52775        |      3.61     | 0000-00-00 00:00:00 |     3.71       | 0000-00-00 00:00:00 |      3.81     |     0000-00-00 00:00:00

Maybe I am over thinking this as well.
Comment: How do you determine the latest price?  In the Fiddle you provided, what should be the result for `stationid = 53011` since they have the same date?
Comment: When there is more dates, I would determine the lasted price as the last updated based on the `dateadded`
Answer: While this can result in ties (if multiple stations share the same max dateadded), here is a common approach joining the table to itself using the max aggregate:
select p.stationid, p.price, p.fueltypeid, p.dateadded
from prices p
  join (select stationid, max(dateadded) maxdateadded
        from prices
        group by stationid) p2 on
    p.stationid = p2.stationid and p.dateadded = p2.maxdateadded

Updated Fiddle
Comment: Please review my question again. I updated the expected result.
Comment: @BrandonWilson -- the query provided will return the station and corresponding record that was last entered by dateadded (using `max(dateadded)`).  Looking over your results, are you trying to `pivot` your results?
Comment: Actually, yes a pivot might be the answer.
Comment: @BrandonWilson -- check out this updated fiddle.  You can pivot results with `max` and `case`: http://sqlfiddle.com/#!2/f282e/1
Comment: when this is ran it pulling the `MAX` price not the `MAX` date and price. I've been trying to figure out how to get the date for each price but haven't been successful, would you be able to help?
Comment: @BrandonWilson -- just wrap the above query as a subquery and use `max` with `case` to `pivot` the results.  here you go: http://sqlfiddle.com/#!2/f282e/3
Comment: did I do something wrong, I added a few more records and most of the results come up `null` http://sqlfiddle.com/#!2/3bbc3/3
Comment: My guess is this is what you're looking for -- the max date per station per type: http://sqlfiddle.com/#!2/3bbc3/4.  The other was returning the max date per station, and then using that to return the types that match.

MySQL Columns from Recordset


Properties of Estimators Using Dice Rolls?

Question: I am an MBA student taking courses in statistics.
Today, some of the students from the actual statistics faculty presented a seminar on estimation and probability - it was really interesting! In our own class, we have been learning about concepts such as the "Expected Value" and "Maximum Likelihood", and in this seminar we learned a bit about properties of these estimators. (As a note - we are learning how to write the Log Likelihood for different Probability Distributions, take the derivative, set them to 0 and solve the equations. I myself have taken undergrad courses in Calculus and Algebra and find myself able to do the math required - but at times struggle to understand the intution behind what I am doing)
For example, today we covered 4 important properties of estimators - these are the notes I made:

Unbiasedness: An estimator is said to unbiased if the expected value of the estimator minus the actual estimator is 0. If this difference is not 0, this difference is called the "bias"

Consistency: An estimator is consistent if as the number of samples increase, the value of the estimator becomes closer to the actual estimator.

Sufficiency: An estimator is sufficient if no other estimator provides more information than this estimator.

Efficiency: Unfortunately, I could not understand what the efficiency of an estimator is and why this is important. I read the Wikipedia page for this, and it seems to be related to the Fisher Information (and the Fisher Information appears to be a function of the likelihood).

Based on these notes, I tried to conceptualize them using a "dice roll" as an example. However, I struggle to understand the following points. For example, consider a 6-sided die:

If I take the Expected Value of a single die, the answer is 3.5. If I roll this die many times, the average of all rolls will become closer and closer to 3.5. This being said, I can not understand the difference between Unbiasedness and Consistency here? It seems like one implies the other and vice versa?

If I roll this die many times - the "mean" will tell me what the average value was, the "median" will tell me what the median value was (i.e. more robust with respect to outliers), and the "mode" will tell me the most frequent value that appeared. The mean, median and mode are all different statistics that provide me with different information about this die (e.g. suppose someone rolled this die 1000 times and asked me to judge if this die was "rigged" or not - I could make use of the mean, median and mode of the results from these rolls). This being said, how do I decide which of these statistics provides the most information - which of these is Sufficient?

Finally, I have no idea how this example of rolling a die and different statistics calculated from the results will relate to Efficiency

Could someone please help me unpack all this information?
Answer: I will try to be a bit more rigorous. Suppose you are considering a sequence of random variables $X_1, \ldots, X_n$. For instance: $X_i =$ the result of the $i$-th roll.
Up to now, no data is involved, i.e., we do not actually observe $X_1, \ldots, X_n$, just know that these are the random variables we're studying.
Performing an experiment means actually rolling the dice $n$ times and observing values $(x_1, \ldots, x_n)$, e.g., $(1, 3, ... , 2)$.
The properties of the estimators are studied without actually considering the result of the experiment.
Now, let me give an example of an unbiased estimator which is not consistent:
take as an estimator for the mean the outcome of the first roll. Since the rolls are independent and identically distributed, $E[X_1] = 3.5$. Hence, this estimator is unbiased.
However, no matter the sample size $n$, the estimator for the mean will always be $x_1$ which is always different from $3.5$.
Instead, consider as estimator for the mean
$$
\hat \mu_n := \frac{1}{n} \sum X_i + 1/n
$$
we have that $E[\hat \mu_n] = 3.5 + 1/n$, so that for any fixed $n$, the estimator is biased.
However, letting $n \rightarrow \infty$ $E[\hat \mu_n] \rightarrow 3.5$, moreover its variance shrinks to zero. In fact, you can check that
$$
Var[\hat \mu_n] = \frac{1}{n^2} \sum Var[X_i] = \frac{1}{n} \frac{105}{36}
$$
which shows that, as $n \rightarrow \infty$, $Var[\hat \mu_n] \rightarrow 0$.
Thus, we have that the mean of $\hat \mu_n$ converges to the correct value while its variance shrinks to zero. In other words, we have that $\hat \mu_n$ will converge (almost surely) to the correct value. It is thus consistent.
The concept of sufficiency is a tad more complex. None of the statistics you cited is actually sufficient for dice rolls: you're missing the information about the variability of the rolls.
To decide if the dice is fair, you should perform a test, see for instance here: https://www.reddit.com/r/statistics/comments/gj70x/how_do_you_check_if_a_die_is_fair/
Finally, efficiency is used to compare different estimators. Suppose you have two consistent estimators $\hat \mu$ and $\hat \mu_2$. Which one do you use to draw your conclusions?
Up to now, we have seen estimators as random variables (the outcome of the experiment is never considered). But if you want to make decisions, you need to plug in those numbers. Suppose that when you plug in the data into $\hat \mu_1$ you get 3.7 and when you plug in the data into $\hat \mu_2$ you get $3.1$. How do you decide?
A solution is to pick the most efficient estimator: You pick the one with the lowest variance, because for a fixed sample size $n$, you can be more certain about the conclusion you get.
Comment: Wow! Thank you! I think I understood most of this!
Comment: No problem :) you coul accept my answer as solution then!


Use Color Field Value in Views Field Template File

Question: I have two fields in my view:
field_background_colour and field_heading
The are both being pulled from nodes and displayed in a rotating hero banner. Each node has a different colour and different heading.
The field_background_colour is defined by the color field module and therefore can be any colour they select.
I need to add the value of the background colour in hex (e.g. #000000) to the html output of field_heading.

[field_heading]

I tried using some html and replacement patterns in the rewrite of the field but it seems that gets stripped out by views. It seems to me that I need to use the field's template file to get what I want.
Comment: If this is a view title you are trying to style, where does the color field live? I would guess maybe the user profile or somewhere there are not multiple instances like node?
Comment: I agree inline styles are the best route in this use case all things considered (been there).
Comment: Is it the actual view title you are trying to style, or the title of each node being shown in the view?
Comment: The the heading and the colour field are both on the node. I am using a view with a fields to display them in a rotating hero banner
Comment: If the token `[field_background_colour]` is not working in your view, it could just be a formatting issue for that field. Inspect the element and how it is actually being printed in the DOM.
Answer: In this use case, I believe inline styles are the way to go. There are methods to write a CSS file in your module or theme, for example, but since users can select, and update at any time, any color code, all situations would be very difficult or messy to manage. Inline styles are not ideal in the grand scope of things, but with multiple users, and multiple hex values reaching the millions, sometimes requirements make our choices for us. And plus, we just want to get it done.

Below assumes the view shows nodes, both fields are on the content type, and the title being styled is the node title, not the views title. This is best achieved setting the view to display content, and utilizing template files for your chosen display mode such as node--content-type--teaser.tpl.php.
node--content-type--rotating-hero.tpl.php:

  <h1
    title="<?php print render($title); ?>"
    alt="<?php print render($title); ?>"
    <?php if (isset($content['field_background_colour'])) : ?>
      style="color: #<?php print $content['field_background_colour']['#items'][0]['value']; ?>;"
    <?php endif; ?>
  >
    <?php print render($title); ?>

Here, each .views-row will contain an individual node display, and you can focus your javascript and CSS on those for the slider.
*multiple h1 tags on the same page need to be wrapped in a
 tag, otherwise, use h2 tags.
*Templates are related to structure and usage. Views templates are for the structure and layout of content aggregation, node templates are the structure of individual entities. Wherever the field (or desired data) resides is the best place to theme template files.

Below assumes you need to style the views title itself...
will need more info about where the color field lives. If user profile, for example, you will need to load the user object to access the field value.
MYMODULE.module:
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'view_name') {
    $view->build_info['title'] = "custom title";
  }
}

template.php:
function MYTHEME_views_pre_render(&$variables) {
  if (&$variables['view']->name == 'view_name') {
    &$variables['view']->build_info['title'] = "custom title";
  }
}

Comment: The background colour and heading are both on the node itself. All of the nodes are displayed in a rotating hero banner using fields display in views
Comment: It is possible to theme views type template files, however, I still recommend theming the node type template files. It will be more versatile and compatible for the future. I also think people spend a lot more time theming node templates than views templates, so will be easier to find help. You could even create a view mode named rotating hero and gain a lot of control over the display. Just set the view to display content instead of fields.
Comment: `node—content-type—rotating-hero.tpl.php`
Answer: Aren't you actually just trying to style one of the fields according to the value of the other field?
Inline CSS isn't the best way to go because of a number of reasons, mainly, it can't be easily overriden so it breaks the cascade, and maintenance is a nightmare.
There is a way to style your views rows based on field values: You add a class to your Heading field Style settings that is based on the bg-color field value. Using classes to mark up content and then style the classes with CSS is the way to go.
You need to add the CSS rules applied to the classes to your (sub)theme. Some themes provide the interface to add your custom CSS, if not you can use the CSS Editor or a similar module.
Here are the steps:

Position the bg-color field above the Heading field (good if it's Hidden). If you need it visible in some other order then add a second bg-color field just for this purpose and position it above the Heading field
Edit the Heading field > Uncollapse Style settings > Customize field and label wrapper HTML (or Customize field HTML if you don't need the wrapper) > Create a CSS class and enter the first part of your class (heading) (class names can't start with numbers so that's why)
Uncollapse Rewrite results (don't enable it, you just need to look up the token), uncollapse Replacement patterns, copy the bg-color field token and paste it in the above CSS class field (you end up with something like heading-[field_bg_color]).
Save the View and check your HTML output, you will see a class based on the color field on your Heading, something like class="views-field views-field-title heading-008000". The hash sign has been stripped automatically as it can break CSS.
Add the CSS to your (sub)theme or the CSS Editor, for all the colors you have in your content:

.heading-008000 {
  background-color: #008000;
}

With Sass you can use a list to store all your colors and create the rules automatically.
If this is just a way to allow content editors to choose some preset styles try looking into Paragraphs and Bricks (D8).
Comment: The challenge is that the user defines the colour using the colour field module, so it can literally be any colour they choose. I cannot define every colour in css so I need to do this via the field template.
Comment: Branding nightmare :| I hope it's a legitimate case though. Yes, you'll need to go through views templates, probably with a preprocess to have the color value available in heading field template.
Comment: Indeed it is. Is there any way of using the replacement patterns in views directly in the templates?
Comment: I'm really not the expert, but maybe if you use the token CSS the way I described, or in some similar way you'd get the color field value into the Heading field object, then maybe you could manipulate it in views-view-fields.tpl.php for the Heading field (more specific title, you have suggestions within Views). Usually templates are used to output variables, not to store logic, logic is usually kept in modules or in template.php in your theme.
Answer: You can simply use template_preprocess_views_view_fields to rewrite content of the field, and wrap it inside another div with the markup.
like the following:
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function YourTheme_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];
  foreach ($view->field as $id => $field) {
    if ($id == 'field_background_colour') {
      $content = $vars['fields']['field_heading']->content;
      $background_colour = trim(strip_tags($vars['fields']['field_background_colour']->content));
      $vars['fields']['field_heading']->content = '
' . $content . '
';
    }
  }
}

Result:
Answer: You can use twig file and wrap your div code around {{output}}

    {{ output -}}

Twig File: views-view-field--{page or block machine name}--{field name}.html.twig
Example: views-view-field--frontpage--field-color.html.twig
Note: You can access any field value from any views-view-field--{field name} by using {{ view.field.{field name}.original_value }}
Comment: Thanks for the answer but this question is for Drupal 7 and is tagged as such. Do you know how to do this in 7?
Comment: you can do on views-view-field--field-color.tpl.php and add as  print  $ view['field'][field_color']['original_value']
Comment: Wouldn't I need this to be done in the field-heading.tpl?
Comment: Unfortunately, I don't have Drupal 7 installed. You need to test and see. My first suggestion was from Drupal 8 guidelines. Latter is from Drupal 7 guidelines.
Answer: It's very simple, i added a working example, no need for template, first add colour_field:[field_background_colour], hide from display, then add field:[field_heading], in field settings do choose rewrite results (toggle checkbox), add this in input box:

[field_heading]

or

[field_heading]

[field_background_colour] field must be before of [field_heading] in your list of fields in view settings.
Supouse that [field_background_colour-value] is #000000, HTML output will be:

[field_heading-value]

or

[field_heading-value]

please see my WORKING sample settings, HTML output and CSS:

HTML

css
Comment: How does the <div class="background-color:# get converted to <div style="background-color:#
Comment: This would require pre-defining colours and with using the colour field module, the colour can be anything the user wants.
Comment: no, it does not require pre-defining colours, because you are using them as background, i publish my example, just to demostrate that this method works, indeed my example do require pre-defining colours, yours not. please try my solution.
Comment: yes, my mistake, what i posted i did not tryed with color field module, then i play arround trying to make it work, cleaning tags, ... indeed, it needs a function with this module, my posted answers works, not with this module, it may be helpfull in some other cases.
Answer:
Use the views_html_tags module to add tag  in available HTML tags list.
Add nid (Node ID) to view fields, put it on the top and hide it.
Add class "node-[nid]" to field_heading.
Add field 'field_background_color' to view fields and place it between 'nid' and 'field_heading' fields. Don't hide it.
Rewrite it's output to:
.node-[nid] {
background-color: [field_background_color];
}


Shortest distance between two curves

Question: Let $C_1= \{ (x, y) \in \mathrm{R}^2 : y = x^2 +1 \}$ and $C_2= \{ (x, y) \in \mathrm{R}^2 : x = y^2 +1 \}$, find the points which minimize distance between $C_1$ and $C_2$. What I tried is: we know that a generic point for $C_1$ is $(x, x^2 + 1)$, while a generic point for $C_2$ is $(y^2 + 1, y)$. It is pretty clear that the two curves don't intersect, so the distance between a generic pair is:
$$||(x, x^2+1) - (y^2 + 1, y)||$$
Which for extreme finding is the same as
$$f(x, y) = ||(x - y^2 - 1, x^2+1 - y)||^2$$
Trying to find the critical points means we have to find out what the gradient is:
$$\nabla f(x, y) = (4x^3 - 2y^2 - 4yx +6x - 2, 4y^3 - 2x^2 -4yx +6y -2)$$
Hence, I'm looking for the roots of:
$$2x^3 - 2y^3 -y^2 +x^2 +3x-3y = 0$$
It is pretty clear that $(x, x) : x \in R$ is always a solution. However, I'm not sure there aren't any other roots. Is there any other method or some other way to solve this problem?
Comment: try to parameterize as [ http://www.wolframalpha.com/input/?i=parametric+plot+%7B%7Bt%2Ct%5E2%2B1%7D%2C%7Bt%5E2%2B1%2Ct%7D%7D%2C%7Bt%2C-2%2C2%7D ]
Comment: Looks like at the closet point you have the the derivatives are parallel, or something similar along those lines. This leads to $x \approx 1.056$, which seems plausible from the plots.
Answer: I'd use the fact that the curves are reflections in the line $x=y$: that means it's sufficient to find the point closest to that line (on either curve). The point closest to that line on the curve $y=x^2+1$ has slope $1$ (where a line parallel to $x=y$ is tangent).
Comment: @Julián, the first sentence is intuitive enough? That leaves the second: we want to prove the point closest to $x=y$ is where a tangent line is parallel to $x=y$. Since the graph doesn't touch $x=y$ and is continuous, there's a closest point; since it's everywhere nonlinear and smooth, that's a tangent point. (That's still a bit of handwaving, but should suffice, I hope.)
Comment: I'm worried about the stringency of such a method. Although the statement is fairly intuitive, could you provide any formal proof to the statement above?
Comment: The problem is not about understanding, the problem is that I'm preparing for a final exam in which they ask to prove anything not yet proven in class, hence I'm trying to avoid hand-waving as much as I can
Answer: Factorize with (x-y). If you try to solve the equation in terms of x, let's say, you' ll find that it cannot have any real solutions, which leads us to the result that you have already found: the only solution is y=x.
Comment: After factoring with (x-y), you get $(x-y)(x^2+y^2+yx+x+y+3)$, it is not really clear that this second polynomial does not have any real solution. Could you please elaborate?

Shortest distance between two curves


Prove that every element is a $p$-th power in a cyclic group

Question: Let $p$ be a prime. show that in a cyclic group of order $p^n-1$, every element is a $p$-th power
My concern: I'm not sure if I understand the problem correctly, but I think it should state that "every element is a $p^n$-th power," since I'm only able to show that for any element $g^k$ in cyclic group $G$ where $g$ is a generator, $(g^{k})^{p^{n}} = g^{k}.$
Comment: This is exercise 63 in chapter 4 in Gallian's Contemporary Abstract Algebra.
Answer: Since $p$ does not divide $p^n-1$, it follows that $gcd(p,p^n-1)=1$. For all $x$ in a cyclic group of order $p^n-1$ one has $x^{p^n-1}=e$, by Lagrange's theorem. Now use Bézout's identity:
$$x=x^1=x^{kp+t(p^n-1)}=(x^k)^p$$
Comment: how do you know we have infinite k in order to get ALL $x^{k}$?
Comment: Bezout supplies you with as many $k$'s as you need.
Comment: Many thanks, Ittay! Great solution:)
Comment: Thank you, this answer helped me a lot.
Answer: Consider the homomorphism $\phi:G \rightarrow G$ such that $x \mapsto x^p$.
Consider $x^p = e$.  Is this possible for $x \neq e$?  Of course not: if there were such an $x$, then its order is necessarily $p \implies p|(p^n-1)$, which is a contradiction.
Thus, $\phi$ is injective, so it is an automorphism of $G$.
Comment: Many thanks, Kaj! too slick:)
Answer: Seems like a concise one liner is simply letting $a$ be the generator, and then noting since $\gcd(p,p^n-1)=1$ (since $p$ is prime and does not divide $p^n-1$) that $|a^p|=(p^n-1)/{\gcd(p^n -1,p)}=p^n-1$, so $\langle a\rangle=\langle a^p \rangle$ and we're done.


Why does $\frac{a-x}{x-a} = -1$

Question: Why does $$\frac{a-x}{x-a}$$ simplify to $$-1$$?
I have no idea where to start because there are multiple minus signs involved.
Comment: I remember that for some reason this was mindblowing to me when I first learned fractions
Answer: Hint: $$\frac{a-x}{x-a}=\frac{-(x-a)}{x-a}=\ldots$$ Of course, for this to make sense the denominator shouldn't be equal to $0$, hence $x$ must not be equal to $a$. Otherwise it would be undefined.
Comment: fastest answer I've ever seen, haha. Thanks.
Comment: @user1534664 You're welcome ;)
Answer: The correct way to simplify this is to say that $\frac{a-x}{x-a}=-1$ if $x\ne a$ and undefined if $x=a$.

Why does $\frac{a-x}{x-a} = -1$


How can I create a pixelate interface in android?

Question: I want to create an android app, a tamagochi to be more specific. For that i need to create a pixelated interface. How can I simulate a "big pixel" and how can I animate the "big pixels"?
Comment: What kind of animation do you need? How fast animations should be rendered (fps)?
Answer: In my knowledge, there is no such API out of the box.
Building your own system should be fairly simple.
I would store actual low resolution pixels in a Matrix and then use this Matrix to draw rectangles in View's onDraw method. This drawing involves some very simple math used to calculate position and size of your "big pixels" (rectangles) on the screen.


how can i add classes to the content

Question: I'm trying to add class to the content, however its not adding anything
<code>    function themename_preprocess_page(&$vars) {
      $is_sidebar_first_or_second= (empty($vars['page']['sidebar_first'])) || (empty($vars['page']['sidebar_second']));
      $is_sidebar_first_and_second= (empty($vars['page']['sidebar_first'])) && (empty($vars['page']['sidebar_second']));
      if ($is_sidebar_first_or_second) {
        $vars['page']['content']['#theme_wrappers'][0] .= ' one-sidebar';
      }

      if ($is_sidebar_first_and_second) {
        $vars['page']['content']['#region'] .= ' two-sidebar';
      }

    }
</code>
can anyone help me on this?
Answer: Have you tried this code ?
I have taken it from here
<code>// Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'two-sidebars';
  }
  elseif (!empty($variables['page']['sidebar_first'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-first';
  }
  elseif (!empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-second';
  }
  else {
    $variables['classes_array'][] = 'no-sidebars';
  }
</code>
Comment: yes i got it and worked for me very nice
Comment: but if i want to add some classes to the blocks related to their region

how can i add classes to the content


Struggling with long running query even for explain plan also it was taking very much time

Question:
My query is taking very long time around 1hr.
2.due to this it was impacting on DB performance.
3.even for Explain plan also it was taking very long time.
4.My query is very big.

Query:
select count(*) from
(
    select paid.keyword_id, paid.keyword_name, stat.orgEntrances,
    keyword.rank1, keyword.rank_check,
    SUM(paid.clicks) as sumclick,
    SUM(paid.clicks * paid.avg_position) as sumclickavgpos,
    SUM(paid.itemRevenue) as sumitem,
    SUM(paid.cost) as sumcost,
    SUM(paid.transactions) as sumtrans,
    SUM(paid.impressions) as sumimpress,
    IF(SUM(paid.impressions) = 0, 0,
        SUM(paid.impressions * paid.avg_position) / SUM(paid.impressions))
    as sumimpressavgrank,
    con.item_revenue,  con.transactions,  keyword.monthly_search_volume
    from `t_keyword_paid_analytics_google_ib` paid
    left join
    (
        select outer_t.keyword_id,
        sum(outer_t.item_revenue) as item_revenue,
        sum(outer_t.transactions) as transactions
        from t_keyword_conversion_ga_ib outer_t
        where outer_t.own_domain_id = 720
        and outer_t.traffic_date >= '2012-12-01'
        and outer_t.traffic_date <= '2012-12-31'
        group by outer_t.keyword_id
    ) con
    on paid.keyword_id = con.keyword_id
    left join
    (
        select outer_t.keyword_id, sum(outer_t.entrances) as orgEntrances
        from t_keyword_stat_ga_ib outer_t
        where outer_t.own_domain_id = 720
        and outer_t.traffic_date >= '2012-12-01'
        and outer_t.traffic_date <= '2012-12-31'
        and (outer_t.medium = 'organic' or outer_t.medium is null )
        group by outer_t.keyword_id
    ) stat
    on paid.keyword_id = stat.keyword_id
    left join `t_managed_keyword_ib` keyword on keyword.id = paid.keyword_id
    where paid.own_domain_id = 720  and paid.traffic_date >= '2012-12-01'
    and paid.traffic_date <= '2012-12-31'
    and (paid.channel is null or paid.channel = 'Google')
    group by paid.keyword_id  having paid.keyword_id is not null
) tempt;

Tables Structure:
mysql> show create table t_keyword_paid_analytics_google_ib\G
*************************** 1. row ***************************
Table: t_keyword_paid_analytics_google_ib
Create Table: CREATE TABLE `t_keyword_paid_analytics_google_ib` (
`keyword_name` varchar(255) DEFAULT NULL,
`id` int(11) NOT NULL,
`keyword_id` int(11) NOT NULL,
`target_url_id` int(11) DEFAULT NULL,
`own_domain_id` int(11) NOT NULL,
`log_date` date NOT NULL,
`traffic_date` date NOT NULL,
`impressions` int(11) DEFAULT NULL,
`clicks` int(11) DEFAULT NULL,
`entrances` int(11) DEFAULT NULL,
`match_type` int(11) DEFAULT NULL COMMENT '1: Phrase, 2: Exact, 3:Broad 4: etc',
`ad_group_name` varchar(200) DEFAULT NULL,
`ad_distribution_network` varchar(500) CHARACTER SET latin1 DEFAULT NULL,
`match_query` varchar(500) CHARACTER SET latin1 DEFAULT NULL,
`cost` decimal(10,2) DEFAULT NULL,
`cpm` decimal(10,2) DEFAULT NULL,
`ctr` decimal(10,2) DEFAULT NULL COMMENT 'percent',
`cpc` decimal(10,2) DEFAULT NULL,
`campaign` varchar(200) CHARACTER SET latin1 DEFAULT NULL,
`keyword_status` tinyint(4) DEFAULT NULL COMMENT '1: Active,2: Approved, 3: Disapproved, 4: Paused , 5:Pending, 6: Failed, 7:etc',
`ad_group_status` tinyint(4) DEFAULT NULL COMMENT '1:ELIGIBLE; 2=PAUSED;3=LOW_SEARCH_VOLUME;4 =LOW_QUALITY_SCORE; 5=DISAPPROVED; 6=AD_GROUP_PAUSED; 7=etc',
`max_cpc` decimal(10,2) DEFAULT NULL,
`quality_score` tinyint(4) DEFAULT NULL,
`channel` varchar(100) DEFAULT NULL,
`first_page_cpc` decimal(10,2) DEFAULT NULL,
`avg_position` decimal(10,2) DEFAULT NULL,
`itemRevenue` decimal(10,2) DEFAULT NULL,
`goal1value` decimal(10,2) DEFAULT NULL,
`goal2value` decimal(10,2) DEFAULT NULL,
`goal3value` decimal(10,2) DEFAULT NULL,
`goal4value` decimal(10,2) DEFAULT NULL,
`transactions` int(10) DEFAULT NULL,
`goal1completions` int(10) DEFAULT NULL,
`goal2completions` int(10) DEFAULT NULL,
`goal3completions` int(10) DEFAULT NULL,
`goal4completions` int(10) DEFAULT NULL
) ENGINE=BRIGHTHOUSE DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql> show create table t_keyword_conversion_ga_ib\G
*************************** 1. row ***************************
Table: t_keyword_conversion_ga_ib
Create Table: CREATE TABLE `t_keyword_conversion_ga_ib` (
`keyword_name` varchar(255) COLLATE latin1_bin DEFAULT NULL,
`id` int(11) NOT NULL,
`own_domain_id` int(11) DEFAULT NULL,
`keyword_id` int(11) DEFAULT NULL,
`traffic_date` date DEFAULT NULL,
`targeturl_id` int(11) DEFAULT NULL,
`entrance` int(11) DEFAULT NULL,
`transactions` int(11) DEFAULT NULL,
`item_revenue` decimal(9,2) DEFAULT NULL,
`goal1completions` int(11) DEFAULT NULL,
`goal2completions` int(11) DEFAULT NULL,
`goal3completions` int(11) DEFAULT NULL,
`goal4completions` int(11) DEFAULT NULL,
`goal5completions` int(11) DEFAULT NULL,
`goal6completions` int(11) DEFAULT NULL,
`goal7completions` int(11) DEFAULT NULL,
`goal8completions` int(11) DEFAULT NULL,
`goal9completions` int(11) DEFAULT NULL,
`goal10completions` int(11) DEFAULT NULL,
`goal1Value` decimal(9,2) DEFAULT NULL,
`goal2Value` decimal(9,2) DEFAULT NULL,
`goal3Value` decimal(9,2) DEFAULT NULL,
`goal4Value` decimal(9,2) DEFAULT NULL,
`goal5Value` decimal(9,2) DEFAULT NULL,
`goal6Value` decimal(9,2) DEFAULT NULL,
`goal7Value` decimal(9,2) DEFAULT NULL,
`goal8Value` decimal(9,2) DEFAULT NULL,
`goal9Value` decimal(9,2) DEFAULT NULL,
`goal10Value` decimal(9,2) DEFAULT NULL,
`medium` varchar(255) COLLATE latin1_bin DEFAULT NULL,
`source` varchar(255) COLLATE latin1_bin DEFAULT NULL
) ENGINE=BRIGHTHOUSE DEFAULT CHARSET=latin1 COLLATE=latin1_bin
1 row in set (0.00 sec)

Please help me here.
Comment: On first glance you appear to have a lot of redundant calculations in that SQL. Your first subselect seems to have 9 SUMmed values which are not use nor output in the main select.
You also appear to have no indexes on the tables
Comment: Bit of a check on the Brighthouse storage engine and it looks like it has little index support. As such I wouldn't expect complex queries using this engine to be quick.
Answer: Create index and change where condition. put (outer_t.medium = 'organic' or outer_t.medium is null ) after outer_t.own_domain_id = 720 and (paid.channel is null or paid.channel = 'Google') after paid.own_domain_id = 720. Try, i hope it will make your query faster.
Comment: Please send me re-written query.


How to get instance variables in Python?

Question: Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:
class hi:
  def __init__(self):
    self.ii = "foo"
    self.kk = "bar"

Is there a way for me to do this:
>>> mystery_method(hi)
["ii", "kk"]

Edit: I originally had asked for class variables erroneously.
Comment: Your example shows "instance variables".  Class variables are another thing.
Answer: Every object has a __dict__ variable containing all the variables and its values in it.
Try this
>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()

Output
dict_keys(['ii', 'kk'])

Comment: FWIW, the inspect module gives you a more reliable method than relying on __dict__, which not all instances have.
Comment: Also, anything that uses __slots__.
Comment: Certain built-in types, such as int.  Try saying "x = 5" and then "x.__dict__" and you'll get an AttributeError
Comment: Why would you want to try and get the class instance variables of an int? It's not even a class (although I could be wrong on that).
Comment: What kind of an instance does not have __dict__?  I've never encountered one.
Comment: @MartinSherburn Because someone may want to get instances' variables within knowing in advance what types will be encountered.
Comment: Also re.MatchObjects ( no `__dict__`s )
Comment: What does the example output look like for this code?
Comment: Also numpy ndarrays return an AttributeError when you try to access their attributes using ```__dict__```
Answer: Use vars()
class Foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2

vars(Foo()) #==> {'a': 1, 'b': 2}
vars(Foo()).keys() #==> ['a', 'b']

Comment: +1  I personally think this syntax is cleaner than using __dict__, since attributes with double underscores are supposed to be "private" in Python syntax.
Comment: @Martin: `__method` is private, `__method__` is a special method, not necessarily private; I would like to say the special methods define an object's capabilites rather than methods.
Comment: `__method__` is quite ugly, and I think they have been named that way to try and deter people away from using them unless absolutely necessary. In this case we have the alternative vars().
Comment: in my case I tried calling vars(ObjName) and it returns a dict_proxy with a dictionary whose keys are the methods of the given class/object, but no sign of __init__ elements. Any guesses why?
Comment: Double Underscore Variables `__str__`, `__method__` are for the language itself normally. What happens when you `str(something)`?
Answer: You normally can't get instance attributes given just a class, at least not without instantiating the class. You can get instance attributes given an instance, though, or class attributes given a class. See the 'inspect' module. You can't get a list of instance attributes because instances really can have anything as attribute, and -- as in your example -- the normal way to create them is to just assign to them in the __init__ method.
An exception is if your class uses slots, which is a fixed list of attributes that the class allows instances to have. Slots are explained in http://www.python.org/2.2.3/descrintro.html, but there are various pitfalls with slots; they affect memory layout, so multiple inheritance may be problematic, and inheritance in general has to take slots into account, too.
Comment: I didn't downvote, and please notice what I actually said: you can't get a list of instance attributes *given just a class*, which is what the code accompanying the question tries to do.
Comment: @Carl: Please educate yourself before writing false comments and downvoting based your lack of knowledge.
Comment: I assume he meant "you can't get a list of all possible instance attributes".  For example, I often use lazy generation and the @property decorator to add an instance variable the first time it's requested.  Using __dict__ would tell you about this variable once it existed but not beforehand.
Comment: Downvoting because "you can't get a list of instance attributes" is simply wrong: both vars() and __dict__ give you exactly that.
Answer: You can also test if an object has a specific variable with:
>>> hi_obj = hi()
>>> hasattr(hi_obj, "some attribute")
False
>>> hasattr(hi_obj, "ii")
True
>>> hasattr(hi_obj, "kk")
True

Answer: Both the Vars() and dict methods will work for the example the OP posted, but they won't work for "loosely" defined objects like:
class foo:
  a = 'foo'
  b = 'bar'

To print all non-callable attributes, you can use the following function:
def printVars(object):
    for i in [v for v in dir(object) if not callable(getattr(object,v))]:
        print '\n%s:' % i
        exec('print object.%s\n\n') % i

Comment: `exec('print object.%s\n\n') % i` should be written as `print getattr(object, i)`
Answer: Your example shows "instance variables",  not really class variables.
Look in hi_obj.__class__.__dict__.items() for the class variables, along with other other class members like member functions and the containing module.
class Hi( object ):
    class_var = ( 23, 'skidoo' ) # class variable
    def __init__( self ):
        self.ii = "foo" # instance variable
        self.jj = "bar"

Class variables are shared by all instances of the class.
Comment: ```list(filter(None,[ i[0] if not i[0].startswith('_') else None for i in h.__class__.__dict__.items()]))``` essentially
Answer: Suggest
>>> print vars.__doc__
vars([object]) -> dictionary

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.

In otherwords, it essentially just wraps __dict__
Answer: Although not directly an answer to the OP question, there is a pretty sweet way of finding out what variables are in scope in a function. take a look at this code:
>>> def f(x, y):
    z = x**2 + y**2
    sqrt_z = z**.5
    return sqrt_z

>>> f.func_code.co_varnames
('x', 'y', 'z', 'sqrt_z')
>>>

The func_code attribute has all kinds of interesting things in it. It allows you todo some cool stuff. Here is an example of how I have have used this:
def exec_command(self, cmd, msg, sig):

    def message(msg):
        a = self.link.process(self.link.recieved_message(msg))
        self.exec_command(*a)

    def error(msg):
        self.printer.printInfo(msg)

    def set_usrlist(msg):
        self.client.connected_users = msg

    def chatmessage(msg):
        self.printer.printInfo(msg)

    if not locals().has_key(cmd): return
    cmd = locals()[cmd]

    try:
        if 'sig' in cmd.func_code.co_varnames and \
                       'msg' in cmd.func_code.co_varnames:
            cmd(msg, sig)
        elif 'msg' in cmd.func_code.co_varnames:
            cmd(msg)
        else:
            cmd()
    except Exception, e:
        print '\n-----------ERROR-----------'
        print 'error: ', e
        print 'Error proccessing: ', cmd.__name__
        print 'Message: ', msg
        print 'Sig: ', sig
        print '-----------ERROR-----------\n'

Answer: Sometimes you want to filter the list based on public/private vars.  E.g.
def pub_vars(self):
    """Gives the variable names of our instance we want to expose
    """
    return [k for k in vars(self) if not k.startswith('_')]

Answer: built on dmark's answer to get the following, which is useful if you want the equiv of sprintf and hopefully will help someone...
def sprint(object):
    result = ''
    for i in [v for v in dir(object) if not callable(getattr(object, v)) and v[0] != '_']:
        result += '\n%s:' % i + str(getattr(object, i, ''))
    return result

Answer: You will need to first, examine the class, next, examine the bytecode for functions, then, copy the bytecode, and finally, use the __code__.co_varnames. This is tricky because some classes create their methods using constructors like those in the types module. I will provide code for it on GitHub.
Answer: Based on answer of Ethan Joffe
def print_inspect(obj):
  print(f"{type(obj)}\n")
  var_names = [attr for attr in dir(obj) if not callable(getattr(obj, attr)) and not attr.startswith("__")]
  for v in var_names:
    print(f"\tself.{v} = {getattr(obj, v)}\n")


How to determine a threshold, statistically?

Question: I have a data from 6 months of 20 employees who sell cars and car insurance. I can capture the % of car insurance sold based on the numbers, but how can I figure a number(threshold) which tells me how is a good employee based on insurance sold. I am trying to figure it out statistically. Thank You.
Comment: Please edit your question and clarify what your end goal is.
Answer: With statistical tools, you will only get relative indicators of performance, i.e. you will know how is a person doing compared to everyone else.
In this regard the most straightforward tool is probably the median value of whatever metric of performance you are looking at. Everyone with a value above the median will be part of the best half while those.
You can also raise the number of classes which allow for a more refined approach.For example, using quartiles, you will have your best 5 and worst 5 employees.
Otherwise, I believe it is better to wonder how much does an employee need to sell insurance for your business to be successful, which cannot be derived statistically but must be based on audit/accounting.


Setting default content permissions?

Question: I've got a Drupal site with a large amount of CCK fields already populated. I'd like to allow non registered users to be able to submit a particular content type, but I don't want all the fields to be available to them.
I can, obviously, use Content Permissions to do this, but I have 100+ fields that I would need to set individual permissions for, and would also need to set permissions every time I added a new field.
Is there a way I can set default permissions for all fields? So, for example, all fields are editable by admin and viewable by all.
Answer: I think, the module Field Permissions can solve all of your problems.
Comment: Yeah, I'm aware of that module, but it doesn't solve my immediate problem. What I'm after is a way to set sensible defaults for each field, which I can override if needs be, rather than having to set permissions for 100+ fields and having to remember to set permissions each time I set a new field up.
Answer: OK, so I'm being lazy here, so I just decided to bite the bullet and install the module. However, I have found a shortcut for Chrome users. Here's what I did:

Go to admin/user/permissions
Open up the Javascript console
Assuming your theme already loads jQuery (which it should if you've got the default theme, type $("input[id*=edit-3-edit-field-]").attr('checked','checked'); and press enter to check all the admin permissions boxes to edit
To allow unauthenticated users to view all fields type $("input[id*=edit-1-view-field-]").attr('checked','checked'); and press enter
Adjust as necessary for the permissions you want.
Click 'Save permissions'

I guess this would work for any other browser with a Javascript console too, but I've not tested it.
It doesn't get round the issue of having to add permissions for every single new field, but I guess it's just something I'll have to live with!

Setting default content permissions?