using python gooey how to open another GUI after clicking one out of multiple button

Question: Hi I have following code which is working properly for python GUI based on wxpython-gooey. However my task is to create a main GUI with multiple buttons and after clicking any button respective GUI should open and process the respective task and close. The code i have is not for main GUI but after clicking button on main GUI the below code's GUI must open, the sub-GUI code is as follows
from __future__ import print_function
import pandas as pd
import numpy as np
import glob
import os
import json
from argparse import ArgumentParser
from gooey import Gooey, GooeyParser

@Gooey(program_name="Jio Project")

def parse_args():
    """ Use GooeyParser to build up the arguments we will use in our script
    Save the arguments in a default json file so that we can retrieve them
    every time we run the script.
    """
    stored_args = {}
    # get the script name without the extension & use it to build up
    # the json filename
    script_name = os.path.splitext(os.path.basename(__file__))[0]
    args_file = "{}-args.json".format(script_name)
    # Read in the prior arguments as a dictionary
    if os.path.isfile(args_file):
        with open(args_file) as data_file:
            stored_args = json.load(data_file)
    parser = GooeyParser(description='Qualcomm-Samsung a Jio project')
    parser.add_argument('data_directory',
                        action='store',
                        default=stored_args.get('data_directory'),
                        widget='DirChooser',
                        help="Source directory that contains Excel files")
    parser.add_argument('output_directory',
                        action='store',
                        widget='DirChooser',
                        default=stored_args.get('output_directory'),
                        help="Output directory to save summary report")
    parser.add_argument('cust_file',
                        action='store',
                        default=stored_args.get('cust_file'),
                        widget='FileChooser',
                        help='Customer Account Status File')
    parser.add_argument('-d', help='Start date to include',
                        default=stored_args.get('d'),
                        widget='DateChooser')
    args = parser.parse_args()
    # Store the values of the arguments so we have them next time we run
    with open(args_file, 'w') as data_file:
        # Using vars(args) returns the data as a dictionary
        json.dump(vars(args), data_file)
    return args

def combine_files(src_directory):
    """ Read in all of the sales xlsx files and combine into 1
    combined DataFrame
    """
    all_data = pd.DataFrame()
    for f in glob.glob(os.path.join(src_directory, "sales-*.xlsx")):
        df = pd.read_excel(f)
        all_data = all_data.append(df, ignore_index=True)
    all_data['date'] = pd.to_datetime(all_data['date'])
    return all_data

def add_customer_status(sales_data, customer_file):
    """ Read in the customer file and combine with the sales data
    Return the customer with their status as an ordered category
    """
    df = pd.read_excel(customer_file)
    all_data = pd.merge(sales_data, df, how='left')
    # Default everyone to bronze if no data included
    all_data['status'].fillna('bronze', inplace=True)
    # Convert the status to a category and order it
    all_data["status"] = all_data["status"].astype("category")
    all_data["status"].cat.set_categories(["gold", "silver", "bronze"], inplace=True)
    return all_data

def save_results(sales_data, output):
    """ Perform a summary of the data and save the data as an excel file
    """
    summarized_sales = sales_data.groupby(["status"])["unit price"].agg([np.mean])
    output_file = os.path.join(output, "sales-report.xlsx")
    writer = pd.ExcelWriter(output_file, engine='xlsxwriter')
    summarized_sales = summarized_sales.reset_index()
    summarized_sales.to_excel(writer)

if __name__ == '__main__':
   # maingui=main_args()
    conf = parse_args()
    print("Reading sales files")
    sales_df = combine_files(conf.data_directory)
    print("Reading customer data and combining with sales")
    customer_status_sales = add_customer_status(sales_df, conf.cust_file)
    print("Saving sales and customer summary data")
    save_results(customer_status_sales, conf.output_directory)
    print("Done")

Answer: In order to create a real custom interactive gui, I would advice you to get familier with a framwork such as mentioned here: https://wiki.python.org/moin/GuiProgramming
But in order to answer the specific question, Gooey has some little disadvantages, which make it difficult to span a new Gooey window from within the original window (I will not get into detail here), but what you can do is, spawn a new window as a subprocess. Minimal example below:
import sys
import os
from argparse import ArgumentParser

from subprocess import Popen, PIPE

from gooey import Gooey
from gooey import GooeyParser

@Gooey()
def main():

    parser = GooeyParser(
        description='''Test''')

    required = parser.add_argument_group('Optional arguments')

    parser.add_argument(
                        '-i', '--input',
                        required=False,
                        dest = 'input',
                        help='Test_file',
                        widget='FileChooser',
                        )

    args = parser.parse_args()

    ########################################
    # call the next gooey as subprocess from here
    # should work on any system
    ########################################

    PYTHON_PATH = sys.executable
    process = Popen([PYTHON_PATH, 'spawn_next.py'], stdout=PIPE, stderr=PIPE)
    output, error = process.communicate()
    print(output)
    print(error)

if __name__ == "__main__":
    main()

Then you can call the file spawn_next.py, in which you can open another Goopy window like:
from gooey import Gooey
from gooey import GooeyParser

@Gooey()
def main():

    parser = GooeyParser(
        description='''Test''')

    required = parser.add_argument_group('Optional arguments')

    parser.add_argument(
                        '-i', '--input',
                        required=False,
                        dest = 'input',
                        help='Test_file',
                        widget='FileChooser',
                        )

    args = parser.parse_args()

main()


convergence/or divergence of the series $\sum_{n=1}^{\infty}(a_n+b_n)$ given the convergence/divergence of component series

Question: Can we say anything on the convergence/or divergence of the series $\sum_{n=1}^{\infty}(a_n+b_n)$ given the convergence/divergence of $\sum_{n=1}^{\infty}a_n$ and $\sum_{n=1}^{\infty}b_n$. What about the converse ? What about if $a_n$ and $b_n$ are all non-negative
Answer: If $\sum_n a_n$ and $\sum_n b_n$ converge, then the sum $\sum_n a_n + b_n$ converges. If $\sum_n a_n$ and $\sum_n b_n$ diverge, then $\sum_n a_n + b_n$ may converge or diverge (just consider adding $1$ to all $a_n$ and adding $-1$ to all $b_n$). Similarly, if $\sum_n a_n + b_n$ converges, then you can't say much about convergence of $\sum_n a_n$ and $\sum_n b_n$, although if one of them converges then the other must also converge. (And if the sum diverges the one of the summand series must diverge).
Comment: If $a_n$ and $b_n$ are all positive, convergence of the sum is equivalent to both converging, and divergence of the sum equivalent to at least one diverging. This follows basically from that an increasing sequence converges in $\mathbb{R}$ if it's bounded, and diverges to infinity if it's unbounded.
Comment: What about if $a_n$ and $b_n$ are all positive ? in that i guess only convergence of both implies convergence of their sum.
Comment: @user2566092,matt Rigby: "although if one of them converges then the other must also converge" ?. is this true for any arbitrary sequence $\{a_n\}$ and $\{a_n\}$ or only for sequences where one represents the sequence of all positive terms and the other represents the all negative terms. I think that the latter is correct.


Trigger an event created by .on()

Question: I have a jQuery event defined as follows :
$('#pagebody').on('click', '#serverCompTab', function () {
    toggleTabs('#serverComp', '#serverCompTab');
});

I would like to trigger this event manually on my code like $('#'serverCompTab].onclick();
Can anyone help me with this?
Comment: Could you just not call toggleTabs('#serverComp', '#serverCompTab'); ?
Answer: Use click() instead of onclick() :
$('#serverCompTab').click();
//Or
$('#serverCompTab').trigger('click');

NOTE : you should replace ] by ) and move the quote to the end :
$('#'serverCompTab]
____^_____________^
    |             |__ //Replace it by ')'
    |__ //Move it to the end

Hope this helps.
Answer: You were really close. $('#serverCompTab').click() should take care of it for you.

Trigger an event created by .on()


multiplicação de matrizes com minimo maximo de cada linha

Question: olá eu fiz um programa com o intuito de multiplicar cada elemento de cada linha de uma matriz pelo seu elemento de valo mais alto, mas meu programa multiplica cada um por ele mesmo
<code>#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

//achar maior menor de cada linha da matriz e e multiplicar cada numero da linha por ele
int main(int argc, char *argv[])
{
    int mat[4][4];
    int i, j, aux;

    //le matriz
    for(i=0; i<=3; i++)
    {
        for(j=0; j<=3; j++)
        {
            setlocale(LC_ALL, "Portuguese");
            printf("digite um numero para a posição %d e coluna %d de mat:\n", i, j);
            scanf("%d", &mat[i][j]);
        }
    }

    //1ºfase de processamento
    for(i=0; i<=3; i++)
    {
        for(j=0; j<=3; j++)
        {
        if(mat[i][j]>mat[i][j] || mat[i][j]==mat[i][j] )//se o elemento na posição mat={i,j} for o maior numero da linha
            {
                aux=mat[i][j];//guardar em aux
                mat[i][j]=mat[i][j]*aux;
            }
        }
    }

    system("cls");
    fflush(stdin);

    for(i=0; i<=3; i++)
    {
        for(j=0; j<=3; j++)
        {
            printf("[%d]", mat[i][j]);
        }
        printf("\n");
    }

return 0;
}
</code>
Comment: Olá Leonardo, dei uma lida em algumas de suas questões anteriores e tive a impressão de que você está tentando resolver uma série de exercícios com C em ambiente Windows (me corrija se estiver errado). Só gostaria de deixar um comentário: Já descobriu como usar o [GDB](http://www.gnu.org/software/gdb/)? O *debugger* pode vir a te ajudar bastante. Além do mais, a maioria dos IDES (incluindo o Dev-C++ que professores de faculdade gostam de recomendar) suportam GDB.
Comment: sim uso windows, obrigado @AnthonyAccioly eu to no 2 período de ciências da computação eu tiro as duvidas aqui por que o pessoal respondem e os professores da faculdade não irei procurar o GDB
Answer: Crie uma função auxiliar para calcular o maior elemento de um vetor:
<code>int maxElement(int array[], int arraySize)
{
    int max = array[0];
    int i;
    for (i = 1; i < arraySize; i++)
    {
        if (array[i] > max)
            max = array[i];
    }

    return max;
}
</code>
Então adapte sua lógica para utilizar essa função:
<code>//1º fase de processamento
for(i = 0; i < 4; i++)
{
    // Calcula o valor do maior elemento da linha
    int aux = maxElement(mat[i], 4);
    for(j = 0; j < 4; j++)
    {
        // Mesma coisa do que mat[i][j] = mat[i][j] * aux
        mat[i][j] *= aux;
    }
}
</code>

Exemplo funcional no Ideone
Comment: Olá Leonardo. A definição do algoritmo é: Para cada linha (laço externo), encontre o maior elemento da linha (função auxiliar) e multiplique-o por cada elemento da linha (laço interno). O seu algoritmo está pulando o passo de calcular o maior elemento da linha e está fazendo um `if` desnecessário. Recomendo que você passe um tempo debbugando essa solução no GDB caso algo não tenha ficado claro. Caso queira transformar tudo em uma única função, transportar o corpo da função `maxElement` para dentro do laço externo é trivial, porém eu não faria isso (dessa maneira fica bem mais limpo).
Comment: É o tamanho do array. Uma matriz é um array de arrays. Sua matriz é um array de 4 linhas, onde cada linha é um array de 4 posições (logo `int [4][4]`). O `4` é passado como argumento (parâmetro `int arraySize`). Em C é prática comum passar o tamanho do vetor junto com ele.
Comment: ainda não intendi eu nao gostaria de usar função mesmo ja conhecendo pois a professora vai reclamar e pedir para eu explciar função e não estou afiado nesse assunto aidna eu nao intendi o seu algoritmo o meu nao esta tao longe assim ele so multiplica ou cada numero por ele mesmo ou somente o maior numero de cada linha meu ultimo algoritmo
Comment: ` //fase de processamento
 for(i=0; i<=3; i++)
 {
  for(j=0; j<=3; j++)
  {

   if(mat[i][j]>=mat[i][3])//se o elemento na posição mat={i,j}
   {           //for maior que o ultimo elemento da linha

    aux=mat[i][j];//guardar em aux
    mat[i][j]=aux*mat[i][j];//multiplica aux por cada numero da linha
   }

  }
 }`
Comment: // Calcula o valor do maior elemento da linha
    int aux = maxElement(mat[i], 4);
por que o `,4`


How do I construct a parse tree from a series of S-expression tokens in Prolog?

Question: I'm curious about Prolog as a parser, so I'm making a little Lisp front-end. I have already made a tokenizer, which you can see here:
base_tokenize([], Buffer, [Buffer]).
base_tokenize([Char | Chars], Buffer, Tokens) :-
    (Char = '(' ; Char = ')') ->
        base_tokenize(Chars, '', Tail_Tokens),
        Tokens = [Buffer, Char | Tail_Tokens];

    Char = ' ' ->
        base_tokenize(Chars, '', Tail_Tokens),
        Tokens = [Buffer | Tail_Tokens];

    atom_concat(Buffer, Char, New_Buffer),
    base_tokenize(Chars, New_Buffer, Tokens).

filter_empty_blank([], []).
filter_empty_blank([Head | Tail], Result) :-
    filter_empty_blank(Tail, Tail_Result),
    ((Head = [] ; Head = '') ->
        Result = Tail_Result;
        Result = [Head | Tail_Result]).

tokenize(Expr, Tokens) :-
    atom_chars(Expr, Chars),
    base_tokenize(Chars, '', Dirty_Tokens),
    filter_empty_blank(Dirty_Tokens, Tokens).

I now have a new challenge: construct a parse tree from this. First, I tried making one without a grammar, but that turned out really messy. So I'm using DCGs. Wikipedia's page on it is not very clear - especially the portion Parsing with DCGs. Maybe someone can give me a clearer idea of how I would construct a tree? I was very happy to know that Prolog's lists are untyped, so it's a bit easier now that no sum types are needed. I'm just really confused about inputs to grammar clauses like sentence(s(NP,VP)) or verb(v(eats)) (on the Wiki), why the arguments have such abstruse names, and how I can get started with my parser without too much hassle.
expr --> [foo].
expr --> list.

seq --> expr, seq.
seq --> expr.

list --> ['('], seq, [')'].

Comment: A nice intro to dcg,  https://www.metalevel.at/prolog/dcg . It has a good tree construction example.
Comment: Yeah that Wikipedia page is not excellent as is the custom.
Answer: Here is a beginning: Parsing a LISP list-of-atom, which at first is unstructured list-of-token:
List = [ '(', '(', foo, bar, ')', baz ')' ].

First, just accept it.
Write down the grammar directly:
so_list         --> ['('], so_list_content, [')'].

so_list_content --> [].
so_list_content --> so_atom, so_list_content.
so_list_content --> so_list, so_list_content.

so_atom         --> [X], { \+ member(X,['(',')']),atom(X) }.

Add some test cases (is there plunit in GNU Prolog?)
:- begin_tests(accept_list).

test(1,[fail])        :- phrase(so_list,[]).
test(2,[true,nondet]) :- phrase(so_list,['(',')']).
test(3,[true,nondet]) :- phrase(so_list,['(',foo,')']).
test(4,[true,nondet]) :- phrase(so_list,['(',foo,'(',bar,')',')']).
test(5,[true,nondet]) :- phrase(so_list,['(','(',bar,')',foo,')']).
test(6,[fail])        :- phrase(so_list,['(',foo,'(',bar,')']).

:- end_tests(accept_list).

And so:
?- run_tests.
% PL-Unit: accept_list ...... done
% All 6 tests passed
true.

Cool. Looks like we can accept lists-of-tokens.
Now build a parse tree. This is done by growing a Prolog term through parameters of the "DCG predicates". The term (or multiple terms) in the head collect the terms (or multiple terms) appearing in the body into a larger structure, quite naturally. Once the terminal tokens are reached, the structure starts to fill up with actual content:
so_list(list(Stuff))   --> ['('], so_list_content(Stuff), [')'].

so_list_content([])        --> [].
so_list_content([A|Stuff]) --> so_atom(A), so_list_content(Stuff).
so_list_content([L|Stuff]) --> so_list(L), so_list_content(Stuff).

so_atom(X) --> [X], { \+ member(X,['(',')']),atom(X) }.

Yup, tests (move the expected Result out of the test head because the visual noise is too much)
:- begin_tests(parse_list).

test(1,[fail]) :-
   phrase(so_list(_),[]).

test(2,[true(L==Result),nondet]) :-
   phrase(so_list(L),['(',')']),
   Result = list([]).

test(3,[true(L==Result),nondet]) :-
   phrase(so_list(L),['(',foo,')']),
   Result = list([foo]).

test(4,[true(L==Result),nondet]) :-
   phrase(so_list(L),['(',foo,'(',bar,')',')']),
   Result = list([foo,list([bar])]).

test(5,[true(L==Result),nondet]) :-
   phrase(so_list(L),['(','(',bar,')',foo,')']),
   Result = list([list([bar]),foo]).

test(6,[fail]) :-
   phrase(so_list(_),['(',foo,'(',bar,')']).

:- end_tests(parse_list).

And so:
?- run_tests.
% PL-Unit: parse_list ...... done
% All 6 tests passed
true.

Comment: I can't find `plunit` for GNU Prolog, but there's probably some other unit testing system out there. Actually, I already figured out how to verify whether a sequence of tokens is valid - constructing the tree is what's tripping me up. Could you elaborate on that step?
Comment: This was so helpful! Thank you.


How to insert a degree symbol into excel

Question: I'm trying to type a degree symbol into an excel document which is then being saved out as a .csv document before finally being imported into InDesign via an add on called Easycatalog. Having no luck with keeping the degree symbol as a degree symbol when it comes into InDesign and wondered if anyone can help with this.
I'm variably getting lots of other symbols but never the degree symbol. Someone has suggested it is a font encoding issue and said I should use Unicode but not sure how to even specify an excel doc exports with Unicode character encoding.
Any help gratefully received.
Thanks
Alex
Answer: Hold down alt and press 248 then release alt.  ASCII character codes show this: http://www.theasciicode.com.ar/extended-ascii-code/degree-symbol-ascii-code-248.html
However if encoding is really the problem:
Excel to CSV with UTF8 encoding may help.
and a good read on the problem you have:http://www.joelonsoftware.com/articles/Unicode.html


Tightening up Allowed Questions?

Question: Just the opinion of one user here — meant to spur moderator discussion more than anything else.
To good news:  As of this writing the Magento Stack Exchange has 2,023 questions, 435 which have no answer. That's about a 78%  answered rate, and beats the Stack Overflow magento tag percentage (which is at about 64%).
The bad news: That's still not good enough to get out of beta.  I haven't been paying close attention, but anecdotally, every time I check in on the percentage it seems to hover around 75% - 79%.  Based on this, and a brief survey of around 50 unanswered questions last night, it seems like the site definition is too broad to get to the — 85%? 90%? — the StackExchange team requires to get out of beta.
That is, while I'm personally loath to greet new users with an automatic close, there's a certain class of questions that are unlikely to be answered, and are therefore bad for the general health of the site.
Is it time to tighten up the sort of questions that are allowed here?
If we could get rid of the "please diagnose my very specific configuration which doesn't occur in stock Magento and is hard to reproduce elsewhere" questions
Magento admin login process problem at first time after installing it.
https://magento.stackexchange.com/questions/6132/free-shipping-promotional-rule-for-products-in-certain-category-not-working
https://magento.stackexchange.com/questions/6052/button-issues-with-magento-go-admin-theme
Magento/Apache internal redirects hang the server
Missing attributes on product list
Programmatically created attributes showing up in backend but not frontend
https://magento.stackexchange.com/questions/4805/magento-1-7-0-2-category-tree-does-not-auto-expand-in-product-edit-page
Products not showing up in frontend or backend but are enabled and stored correctly in flat table
https://magento.stackexchange.com/questions/6132/free-shipping-promotional-rule-for-products-in-certain-category-not-working
Or the "I'm lonely/frustrated and want someone to pair program with" questions
Remove tax from the invoice pdf
Related Products Trick: A -> B && B -> A
Product attribute not saving programmatically
programmatically
Check if coupon is valid for a quote
implementing xcache to speed up magento
https://magento.stackexchange.com/questions/6194/jquery-animation-in-template-is-not-working
https://magento.stackexchange.com/questions/6178/adding-attachment-in-contact-form
comparing form data with database
Register user product review not reflecting in My account section
Or the "hey we actually answered this in the question body or comments but not in an answer" questions
Magmi image import sets majority of product images, but not all
Paypal shipping address errors
https://magento.stackexchange.com/questions/5721/problem-in-retreiving-data-from-xml
https://magento.stackexchange.com/questions/4733/change-order-state
Preview items are showing in search
Anyone managed to upgrade to EE 1.13 and keep the old urls in place?
It seems like we could get that percentage up in no time.
Comment: Three cheers (three beers?) for Alan Storm!
Comment: Thanks Alan. I'm going through your list. Highly appreciated !!
Comment: I just consulted with SE moderators, closed questions are excluded from answered ratio calculation. So your idea really makes sense. I'm going through your list and will sort it in next 24 hours. Thank a lot!
Comment: I went through your list and closed some of the questions. Many questions are not that bad but I will go through the list once again with a fresh head. Thanks again for the bold of work you did.
Comment: @Tim Address the specific questions is great, but I was wondering if there's some sort of general policy changes/rules we could implement to discourage certain question types that are unlikely to ever be answered.
Comment: Is this site for programmers only, i.e. a subset of stackoverflow users? Or are you going to allow barely computer literate people to post questions here?
Comment: @ButtleButkus Not sure if you're being snarky or not, but the Magento StackOverflow Area51 was pretty explicit about this being a site for programmers,  system administrators, and site users.
Comment: @AlanStorm No not being snarky. I clicked the "about" link and saw this: "Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform." I'm not sure where Area51 is.
Answer: (as always) You are absolutely right. We need a stricter rules for posting lame questions. Of course (as always) it's almost impossible to compile some requirements which will be good for all the variety of cases. However (as always) we can try. Here is my proposition:

The issue has to be well described. Something more then "my promotion rules are not working. what's wrong?"
OP has to show at least minimal effort of solving issue by himself. Something more then "i googled but found nothing".
In most cases it's absolutely important to put a tag with Magneto version (e.g. ce-22.214.171.124, ee-22.214.171.124), note that caches were flushed and indexes refreshed, logging enabled and list the errors there or state their absence.

The questions which are lacking anything of listed above can be put "on-hold" until the required information is provided by OP.
Did I (as always) miss anything?

Tightening up Allowed Questions?


Will a hold-out set of different size than testing set be okey to evaluate performance?

Question: I am working in machine learning. I created a model with the following "parameters" (it is for biometrics):
classes: 21
training: 36 samples for each class
testing: 4 samples for each class
Cross validation: 10x10 StratifiedShufflesplit
*Training set and testing set are used during cross validation (it is a 90%-10%).
I also created a hold-out set of 4 samples (never used during training). I chose this size so that it is the same as the testing set.
I want to proof that my model is capable to generalise. So I was planning to do a barplot showing the difference in accuracy of model (Cross validation) and hold-out set.
But I would also like to test the model with the hold-out set, but only with 1 sample (it will be chosen randomly). Would that be ok or am I breaking any machine learning rule, etc? (training of 4 samples vs hold-out of 1 sample)
I want to do that because 30 seconds (1 sample) is better than 2 minutes (4 samples). Not because of accuracy but because of time.
You can see my confusion matrix and accuracy results.
Thank you
1 sample. 95.24%

4 samples. 89.29%
Answer: Look at it this way: once you have selected and fitted your model, you will use it to do "real" predictions. Perhaps you'll predict a single value. Perhaps you'll predict hundreds. Perhaps you don't even know now how many values you will predict with it.
Should the number $n$ of values you predict have an influence on how many folds you use in cross-validation?
I'd say no, it shouldn't. (Especially since you may not even know $n$ when you build the model!)
But the "real" prediction is essentially the same as your holdout. So if there is no reason to have the number of "real" predictions have an impact on your cross-validation, then analogously there is no reason why the number of cross-validation folds should have an impact on your holdout size.
Bottom line: there does not need to be any relationship between the number of folds and the holdout size.
(That said, your sample size of just 40 points for training and 4 for the holdout appears rather small to me. I hope you are not fitting a very complex model to this, cross-validation or not.)


Real Integral calculation through complex analysis.

Question: I am stuck with this integral, that I must solve with a complex one. First I thought it would get easier, as a polynomial in the denominator and I would get the old and good residue times $2\pi i$  but it didn't get and I refuse to invert the obtained series. Is there any other way.
What I've done so far.
$$  \int_{0}^{2\pi}\frac{1}{\left( 3+2sin(t)\right )^2}dt$$
$$\oint \frac{1}{\left( 9+12\frac{z-z^{-1}}{2i}+4(\frac{z-z^{-1}}{2i})^2  \right )}\frac{dz}{iz} $$
$$ \oint \frac{1}{\left(7iz+6iz^2-6+iz^3+iz^{-1} \right )}dz$$
Should I invert this series, or try to find the roots modifying the denominator, I think I am missing something at plain sight.
Comment: Why expand the square at all? If the goal is to find the zeroes, stay with $$(3+2\sin t)^2=(3-i(z-z^{-1}))^2=-z^{-2}(z^2-3iz-1)^2$$
Comment: You need to find them to know which one of them are in your contour
Comment: You don't need Laurent series. The roots of the denominator don't seem to be pretty. But notice that you only need the residues for the poles that are inside the unit circle. You can show that the real roots are outside the unit circle, for example by bounding from above the roots of $7z^2+6z+1+z^4$, which are the reciprocals of your polynomial. Therefore, the roots that you care about are not real. Since the coefficients are real, those two roots are conjugate of each other.
Comment: Now you use the [residue theorem](https://en.wikipedia.org/wiki/Residue_theorem) and the fact that the integrand is a rational function.
Comment: i have corrected the third integral form. I know I must use the residue theorem, but I do not know how to expand that rational function to its Laurent series.
Comment: Should i find the zeros of $7iz^2+6iz^3+iz^4+i$ or is there an easier way than computing all those roots?
Comment: Ok, I thought it would be much les than computing all those roots. Thanks a lot.
Comment: Ok, I thought it would be much les than computing all those roots. Thanks a lot.
Comment: you are right dude, I mean Did (hehe?). Thanks a lot, thats what i wasn't seeing at all.
Answer: $\dfrac {1}{(3 + 2\frac {e^{it} - e^{-it}}{2i})^2}\ dt\\
z = e^{it}\\
dz = i e^{it} dt\\
-iz^{-1} dz = dt$
$\oint_{|z| = 1} \frac {-iz^{-1}}{(3 -iz + iz^{-1})^2} \ dz$
multiply numerator and denominator by $(iz)^2$
$\oint \frac {iz}{(3iz + z^2 - 1)^2} \ dz\\
\oint \frac {iz}{(z-a)^2(z-b)^2} \ dz$
There is one pole inside the contour and it is of order 2.
$\oint \frac {f(z)}{(z-a)^2} = 2\pi i f'(a)$
$f(z) =  \frac {iz}{(z -b)^2}\\
f'(z) = \frac {-i(z + b)}{(z-b)^3}\\
f'(a) = \frac {-i(a+b)}{(a-b)^3}$
$a = -\frac {3 - \sqrt 5}{2}i\\
b = -\frac {3 + \sqrt 5}{2}i\\
a+b = 3i\\
a-b = -\sqrt 5i\\
2\pi i f'(a) = \frac {6\pi}{5\sqrt5}$


Apache not automatically starting after a reboot of a Scientific Linux Vagrant Box

Question: Every time I reboot my Scientific Linux box, I have the problem that it is
not starting the Apache Web Server (httpd).
I have to do it manually with this code:
[vagrant@magento ~]$ sudo service httpd restart
Stopping httpd:                                            [FAILED]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName
                                                           [  OK  ]

I have a similar setup on a Vagrant box with Ubuntu 12.04 Server which started the httpd services properly, so what's the clue of getting a Scientific Linux Apache server booting the httpd automatically?
Every time I use the command: vagrant reload in my command prompt, the web server doesn't get the httpd service up and I have to use the restart command (sudo service httpd restart) to get it. But I want that function automatically like on my Ubuntu 12.04 before (precise64). So the decisive factor is not the line between the Failed and OK message, the problem is that it is on status FAILED after a reboot.
Update: tried your nice idea instant! But I determine, that all 3 run levels (3,4,5) are already on status ON. This is my current status:
   34  [vagrant@example ~]$ chkconfig --list
   35  crond           0:off   1:off   2:on    3:on    4:on    5:on    6:off
   36  htcacheclean    0:off   1:off   2:off   3:off   4:off   5:off   6:off
   37  httpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off
   38  ip6tables       0:off   1:off   2:on    3:on    4:on    5:on    6:off
   39  iptables        0:off   1:off   2:on    3:on    4:on    5:on    6:off
   40  lvm2-monitor    0:off   1:on    2:on    3:on    4:on    5:on    6:off
   41  mysqld          0:off   1:off   2:on    3:on    4:on    5:on    6:off
   42  netconsole      0:off   1:off   2:off   3:off   4:off   5:off   6:off
   43  netfs           0:off   1:off   2:off   3:on    4:on    5:on    6:off
   44  network         0:off   1:off   2:on    3:on    4:on    5:on    6:off
   45  postfix         0:off   1:off   2:on    3:on    4:on    5:on    6:off
   46  rdisc           0:off   1:off   2:off   3:off   4:off   5:off   6:off
   47  rsyslog         0:off   1:off   2:on    3:on    4:on    5:on    6:off
   48  saslauthd       0:off   1:off   2:off   3:off   4:off   5:off   6:off
   49  sshd            0:off   1:off   2:on    3:on    4:on    5:on    6:off
   50  udev-post       0:off   1:on    2:on    3:on    4:on    5:on    6:off
   51  vboxadd         0:off   1:off   2:on    3:on    4:on    5:on    6:off
   52  vboxadd-service 0:off   1:off   2:on    3:on    4:on    5:on    6:off
   53  vboxadd-x11     0:off   1:off   2:off   3:on    4:off   5:on    6:off
   54  [vagrant@magento ~]$ chkconfig --list | egrep '(apache|httpd)'
   55  httpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off

Comment: Possible duplicate of [httpd service will not start on boot under CentOS 6](http://serverfault.com/questions/589683/httpd-service-will-not-start-on-boot-under-centos-6)
Answer: We have the same problem. For us, it is caused by Apache relying on shared files that are mounted by Vagrant. This causes Apache to fail during loading.
In previous versions of Vagrant, the provisioning scripts were always run on boot/reboot, so Apache would be restarted after the network shares were attached.
Answer: I have been facing the same issue when setting up my dev-environment also with vagrant.
I think one of your documentRoot entries are on a shared drive. Because vagrant is mounting these after the booting (and apache is started before) the apache service cannot start (missing document root)
I was able to solve it using this tutorial on the net. Personally, I ended up using the SysVInit method because I was unable to do it with upstart. You can easily port it to SystemD You just need to change /etc/init.d/httpd [command] to systemctl [command] http.service You can also already use service httpd start
http://razius.com/articles/launching-services-after-vagrant-mount/
JeroenED
Answer: Given the sound of it, the problem is that Apache is not "on" by default after you do "vagrant reload." I believe "vagrant reload" simulates what would happen if you "power-cycled" the virtual machine. It sounds like you would want to have the Apache daemon to be running after the virtual machine boots.
I went to the Scientific Linux website. It states that the underlying distribution is based on "Enterprise Linux." I would normally interpret this to be "RedHat Enterprise Linux." If this is incorrect, let me know.
The way to turn services on/off based on the runlevel of the operating system is usually handled via "chkconfig." I would first confirm what services are on and off.
chkconfig --list

You should get a ton of output that has lines that appear as so:
gpm    0:off 1:off 2:off 3:off 4:off 5:off 6:off

The first column is the name of the service and then the subsequent column contain pairs of values that are <runlevel>:<on|off>. So, in the above line, the gpm service is off at all runlevels.
If I were you, I would filter the output and look for "httpd" or "apache" amongst the list of services:
chkconfig --list | egrep '(apache|httpd)'

On my RHEL box I get the following:
httpd   0:off 1:off 2:off 3:off 4:off 5:off 6:off

The default runlevel is usually number "3". I would then cut this service "on" for this run levels 3, 4, and 5  as so:
chkconfig --level 345 httpd on

Even though this is done, you would still need to restart the service manually if it was off when you brought up the VM:
service httpd start

The ServerName directive warning may be ignored, but you will end up having to manually specify  the IP address you specified for the VM when it was provisioned, if you want to actually see the web content the VM is providing. I would consult the "Private Networking" section of the Vagrant documentation.
Hope this helps!


SwiftUI TextField loses focus inside List

Question: I am still new to SwiftUI and I can't solve this issue. I am displaying a list of products and I've put a TextField at the end in order to add a product to the list. My goal is to keep the focus on the TextField whenever the user submits a new product and so far it works with one exception. Whenever the list is empty, the focus does not go back to the TextField and the user has to click on it again. As soon as there is at least one product, the focus is working as intended.
Here is my code:
struct ContentView: View {

    @State var products: [String] = []
    @State var newProductName = ""
    @FocusState private var isFieldFocused: Bool

    var body: some View {
        List {
            ForEach(products, id: \.self) { product in
                Text(product)
            }

            TextField("...", text: $newProductName)
                .focused($isFieldFocused)
                .onSubmit {
                    if (newProductName.count > 0 && newProductName != "...") {
                        products.append(newProductName)
                        newProductName = ""
                        isFieldFocused = true
                    }
                }
        }

    }
}

Answer: You can use the .onAppear modifier to explicitly set the focus when the view appears, ensuring that the TextField is focused even when the list is empty.
struct ContentView: View {
  @State var products: [String] = []
  @State var newProductName = ""
  @FocusState private var isFieldFocused: Bool
  var body: some View {
    List {
      // your above code
    }
    .onAppear {
      if products.isEmpty {
        isFieldFocused = true
      }
    }
  }
}


Breaking an if loop in JQuery

Question: I'm having trouble stopping a looping if-statement in jquery. The idea is that I have a div which is supposed to start looping through all the colors in the rainbow array and stop when the stop div is clicked. It loops fine, but when I click stop, it doesn't stop looping even though the loop variable is 0. What can I do to get the colors to stop when I click stop?
Click here for a link to my jsfiddle page where I'm coding it.
$(document).ready(function () {
    //Defines variables.
    var loop = 1;
    var rainbow = ["red", "orange", "yellow", "green", "blue", "purple"];
    //loops the color changing if 'loop' is 1.
    $('#go').click(function strobe() {
        if (loop) {
            for (var i = 0; i < rainbow.length; i++) {
                $('#color').animate({
                    "background-color": rainbow[i]
                }, 500);
            }
            strobe();
        }
    });
    //Sets 'loop' to 0 to prevent looping.
    $('#stop').click(function () {
        loop = 0;
    });
});

Comment: It's not the `if` statement that's looping. An `if` statement is executed once and then moves on. The `for` statement inside of the `if` is what's looping.
Comment: You really need to set a timeout when you're doing the animation, it's kicking off a new one hundreds of times every second so even after you stop it would try to catch up with itself so would keep going for ages.
Answer: You need to clear the queue, so
$(document).ready(function () {
    //Defines variables.
    var loop = true,
        //current color index
        current = 0;
    var rainbow = ["red", "orange", "yellow", "green", "blue", "purple"];

    function strobe() {
        if (loop) {
            if (current >= rainbow.length) {
                //reset to initial color
                current = 0;
            }
            $('#color').animate({
                "background-color": rainbow[current++]
            }, 500, strobe);
        }
    };

    //loops the color changing if 'loop' is 1.
    $('#go').click(function () {
        //restart the animation
        loop = true;
        strobe();
    });

    //Sets 'loop' to 0 to prevent looping.
    $('#stop').click(function () {
        loop = false;
        $('#color').stop(true)
    });

});

Demo: Fiddle
Comment: You didn't really fix the code. Open the console : `Uncaught RangeError: Maximum call stack size exceeded ` (see my answer).
Answer: Right now, you're not waiting for the animation to end before you call the next iteration. If you look at your console, you should see a stack overflow error because your function is immediately calling itself.
Here's a solution :
//Defines variables.
var loop = 1, i=0;
var rainbow = ["red","orange","yellow","green","blue","purple"];

//loops the color changing if 'loop' is 1.
$('#go').click(function strobe(){
    if(loop){
       $('#color').animate({"background-color":rainbow[i]}, 500, strobe);
       i = (i+1)%rainbow.length;
    }
});

//Sets 'loop' to 0 to prevent looping.
$('#stop').click(function(){
    loop = 0;
});

Demonstration
Answer: http://jsfiddle.net/HfuvK/35/
$(function(){

    var $color  = $('#color'); // Cache your elements!!
    var rainbow = ["red","orange","yellow","green","blue","purple"];
    var i = 0;
    var n = rainbow.length;

    function loop(){
      $color.stop().animate({backgroundColor:rainbow[++i%n]}, 500, loop);
    }
    function stop(){
      $color.stop();
    }

    $( '#go' ).click(loop);
    $('#stop').click(stop);

});

straightforward, the  loop is simply achieved by recalling the function loop in the animate() callback , 500, loop);
Answer: Your for statement is doing the looping you need another condition to break it. Try replacing i<rainbow.length with  ((i < rainbow.length) && (loop != 0))
Answer: an alternative could be to use setInterval:
    var rainbow = ["red","orange","yellow","green","blue","purple"];
    var interval,i = 0;

    $('#go').click(function(){
        interval = setInterval(function() {
            i = (i+1)%rainbow.length;
            $('#color').animate({"background-color":rainbow[i]},500);
        },500);
    });

    $('#stop').click(function(){
        clearInterval(interval);
    });

FIDDLE

Breaking an if loop in JQuery


Executar comandos do PROMPT / CMD no Java

Question: Bom pessoal, gostaria de saber como executar no Java esse comando:
attrib -R -A -S -H /S /D I:\*.*

Este programinha é para limpar vírus de pendrive. Já consultei alguns materiais aqui no fórum, mas não consegui aplicar.
Basicamente o usuário vai digitar a letra do seu pendrive e clicar em botão de executar, onde fará os comandos abaixo.
String cmd, caminho,comando_01,comando_02;
        String[] executar;
        //************************************************
        cmd = "cmd /c"; // chamada para o cmd
        caminho = txtCaminhoTelaDois.getText() + ":"; //pegando caminho digitado
        comando_01 = "attrib -R -A -S -H /S /D" + caminho + "\\*.*";
        comando_02 = "del *.lnk";

        executar = new String[2];
        executar[0] = cmd + " " + caminho;
        executar[1] = cmd + " " + comando_02;

        //************************************************
        Runtime comando = Runtime.getRuntime();
        try {
            Process proc = comando.exec(executar);

            JOptionPane.showMessageDialog(null, "Concluído");
        }

        catch (IOException ex) {
            Logger.getLogger(TelaDois.class.getName()).log(Level.SEVERE, null, ex);

            JOptionPane.showMessageDialog(null, "Deu ruim...");
        }

Answer: Você não está alterando a letra da unidade que está tentando acessar.
Primeiro coloque este método abaixo no seu programa para melhor reutilização:
public String executar(String... comandos) {
  StringBuilder saida = new StringBuilder();
  BufferedReader leitor;
  ProcessBuilder processos;
  Process processo;

  try {
    processos = new ProcessBuilder("cmd.exe", "/c", String.join(" && ", comandos));
    processo = processos.start();
    processo.waitFor();
    leitor = new BufferedReader(new InputStreamReader(processo.getInputStream()));

    String linha = "";

    while ((linha = leitor.readLine()) != null) {
      saida.append(linha).append("\n");
    }
  } catch (IOException | InterruptedException ex) {
    return ex.getMessage();
  }

  return saida.toString();
}

Depois na chamada utilize:
this.executar("D:", comando_01, comando_02);

Ou altere seu executar para:
executar = new String[3];
executar[0] = "D:";
executar[1] = comando_01;
executar[2] = comando_02;
this.executar(executar);

Note que não é necessário passar o caminho do cmd. Também é importante notar que você deve pegar a letra do drive desejado pelo usuário.
Answer: Acho que isso daqui está errado:
        comando_01 = "attrib -R -A -S -H /S /D" + caminho + "\\*.*";

Acho que deveria ser isso:
        comando_01 = "attrib -R -A -S -H /S /D " + caminho + "\\*.*";

Observe o espaço após o /D.
E depois tem isso:
        executar[0] = cmd + " " + caminho;

Deveria ser:
        executar[0] = cmd + " " + comando_01;


Python Pandas Dataframe: Divide values in two rows based on column values

Question: I have a pandas dataframe:
A    B    C    D

1    1    0    32
          1    4
     2    0    43
          1    12
     3    0    58
          1    34
2    1    0    37
          1    5
[..]

where A, B and C are index columns. What I want to compute is for every group of rows with unique values for A and B: D WHERE C=1 / D WHERE C=0.
The result should look like this:
A    B    NEW

1    1    4/32
     2    12/43
     3    58/34
2    1    37/5
[..]

Can you help me?
Comment: Please post some code that you tried.
Answer: Use Series.unstack first, so possible divide columns 0,1:
new = df['D'].unstack()

new = new[1].div(new[0]).to_frame('NEW')
print (new)
          NEW
A B
1 1  0.125000
  2  0.279070
  3  0.586207
2 2  0.135135

Comment: So unstack did all the magic. Thank you, this worked perfectly!


AngularJS error : TypeError: Cannot read property 'images' of undefined

Question: AngularJS: v1.5.11
Im trying to display images from a JSON array.
Is this the proper way : $scope.mainImage = $scope.template.images[0].name;. This is the line in the error that it says cant read property of images.
My Controller in templates.js file:
.controller("TemplatesDetailsCtrl", ["$scope", "$routeParams", "$http", "$filter", function($scope, $routeParams, $http, $filter ){
    var templateId = $routeParams.templateID;
    $http.get("json/templates.json").success(function(data){
        $scope.template = $filter("filter")(data, function(d){
            return d.id == templateId;
        })[0];
        $scope.mainImage = $scope.template.images[0].name; //THIS IS LINE 30
    });
}]);

I'm trying to display the very first image from the array. So my HTML is:

Ben trying a lot and not able to display the image. Im getting this error:

Please help.
Comment: need to do some basic debugging... what does `$routeParams.templateID` return? What does `$scope.template` return? What does data look like? you clearly aren't getting what you expect in `$scope.template` so you need to dig in to find out why
Comment: There you go...never assume that everything prior is what you expect it to be without checking
Comment: it's really not an answer since it  is just basic debugging steps. A typo in your code really doesn't justify a full answer
Comment: You. I like you. I did a `console.log(templateId)` right after i defined the `var templateId` and got the same error. I mis-spelled `$routeParams.templateID`. Changing it to `$routeParams.templateId` worked. Thanks. I was trying this for a long time.
Comment: How do I mark your comment as answer?
Answer: Seems like 'template' object is undefined. You can test for undefined before trying to use its properties :
if ($scope.template)
   $scope.mainImage = $scope.template.images[0].name; //THIS IS LINE 30

Comment: You are misinterpreting error ... template is undefined , not a property of it


How to create Omega 4 subtheme with new "default" libSass based starterkit?

Question: I am trying to install omega 4, now at 4.4, which uses liBsass for the default starterkit.
How do I proceed about this - I understand I need now npm and gulp instead of the previous Ruby stuff required for Omega 4.3?
Everything installs fine, but drush omega-guard complains about gemfile (which it should not use, as I understand).
Answer: I've had a lot of problems getting started with the new starterkit. It seems to me as if omega-guard does not yet support the new kit. You can still accomplish the same by running gulp in the subthemes directory. This will start the gulp watching process in foreground.
For more information about gulp and the libSass starter kit, I can recommend this post: https://www.drupal.org/node/2537364#comment-10287771
Comment: Thanks for the info. This makes me think about other options for the next projects.


Find the number $b$ such that the line $y = b$ divides the region bounded by the curves $y = 16x^2$ and $y = 25$ into two regions with equal area.

Question: Find the number $b$ such that the line $y = b$ divides the region bounded by the curves $y = 16x^2$ and $y = 25$ into two regions with equal area. (Round your answer to two decimal places.)
My answer is $16.67$
Am I correct?
Answer: Draw a picture. The line $y=25$ meets our parabola at $x=\pm 5/4$. So the area of the region below the line, and above the parabola, is
$$\int_{-5/4}^{5/4} (25-16x^2)\,dx.$$
I think this  is $\frac{125}{3}$, but am error-prone.
We want to choose $b$ so that the area below the line $y=b$ and above the parabola is $\frac{125}{6}$.
The line meets the parabola at $\pm \sqrt{b}/4$. So the area is
$$\int_{-\sqrt{b}/4}^{\sqrt{b}/4} (b-16x^2)\,dx.$$
I think this is $\frac{b\sqrt{b}}{3}$. Set this equal to $\frac{125}{6}$ and solve for $b$. We get $b=\frac{25}{2^{2/3}}$. This is some distance from $16.67$.
Remark: We calculated, but one can do better. By considerations of scaling, it is (after a while) clear that the area above a parabola $y=cx^2$ and below the line $y=a$ is a constant (involving $c$) times $a^{3/2}$. Let us not worry about the constant. The point is that to bisect the area below $y=w$ we use the line $y=\frac{w}{2^{2/3}}$. So we could have found the answer with essentially no computation, and we could similarly find the line $y=b$ that divides the full area in any desired ratio whatsoever.
Comment: Correct to two decimal places, that is the answer.
Comment: Read your last comment in Yoda's voice, I do.
Comment: So the answer is 15.75?


Source for claim that 2 measures that correlate at .70+ measure the same construct?

Question: I am trying to locate a source/sources for this claim (from a reviewer):

I (and other measurement experts) believe that a correlation of .70 or
  higher indicates that two constructs are very much alike because at that
  point, two constructs share at least half of their variance. By
  definition, constructs that share this much variance are similar and
  potentially interchangeable.

The claim seems obviously wrong, simply because no statistic has a meaning independent of context. I've checked with two statisticians. Both agree with me and neither could provide a source for the idea. Does anyone have a source for this idea?
Comment: According to [Quora](https://www.quora.com/What-percentage-of-human-DNA-is-shared-with-other-things), fruit flies share 60% of genes with humans, I guess fruit fly is interchangable with your reviewer. Moreover, in many disciplines with r=0.7 [people would tell you to throw away this data](https://stats.stackexchange.com/questions/132536/how-to-choose-a-confidence-level/132538#132538). This is nonsense, I see no point in trailing such nonsenses, instead you should rather answer your reviewer that he is simply wrong and back it up with reasonable sources that support your claim.
Comment: I've never heard of this, and the idea seems absurd, except for the weasel term "potentially".   You might enjoy browsing through some of the counterexamples at http://www.tylervigen.com/spurious-correlations
Answer: I think this has to do with concurent validity. A related concept is multi-trait multi-analysis analysis. Note that in my reply to the linked question, I rather say that "the traits are defined in a consistent and objective manner." This means that if we were to administrate two different questionnaires that purport to measure the same construct to the very same sample, we expect individual scores to be highly correlated, pending minor issues like measurement error which can be mitigated using a dedicated correction. The choice of the threshold (0.7 or 0.8) is up to you, of course, like any such criteria. They are often arbitrary since it all depends on the sample size, the length and reliability of the questionnaires, etc.
Setting aside the shared variance that can be explained from simply decomposing the correlation between two latent variables, I think it remains tricky to affirm that "constructs that share this much variance are similar and potentially interchangeable." First, you can reach a very high correlation with constructs that are not directly related, i.e. traits that can be found in isolation or combined (in health measurement, for instance, we used to think that measuring quality of life is essentially measuring depression); second, there's a gross approximation between constructs and scale scores (whether your scale effectively measure what it claims to has to do with construct validity), IMO. I believe these two points are in line with @Tim's comments.
Answer: As written, interpreted literally, the quote seems permissible. It isn't as strong as the claim in the title of your question, and "interchangeable" is hedged with "potentially". Of course, there's nothing magic about a .7 correlation or half the variance. The same argument applies to a lesser or greater degree as you change the degree of association. And the same correlation will appear more or less impressive depending on context, in line with your point that "no statistic has a meaning independent of context".
Comment: Sorry but I don't agree, how is it permissible? Such correlation suggests that the variables are "somehow similar", but certainly not "interchangeable".
Comment: @Tim Perhaps I'm being overly generous in my interpretation of the word "interchangeable". I definitely wouldn't expect the two variables to interchangeable for every purpose, but it's not hard to imagine finding that they would have roughly the same coefficient when one is replaced with the other in a regression model—perhaps the common variance is what's driving the coefficient.
Comment: @Tim I believe the context here is very important, the language here sounds like this is psychology. If so, there are extraordinary errors in many measurements (compared to other fields) such that r=0.7 is indeed a reasonably expected relationship between different measures of the same latent variable; this is the reason for the word 'interchangeable' which sounds far too strong but may not be. It's still a rather unhelpful review comment, but I suspect the reviewer simply wants the author to discuss the possibility that two measures in the paper estimate the same latent variable.


Composite variable from Likert items

Question: I have six 5-point Likert items (1-Strongly Disagree, 2-Disagree, 3-Neither agree or disagree, 4-Agree, 5-Strongly Agree) which are related to my dependent variable. I sum the six variables which gives the frequency as follows:
<code>    Frequency
6.00    1
9.00    1
12.00   6
13.00   3
14.00   3
15.00   18
16.00   11
17.00   4
18.00   17
19.00   11
20.00   14
21.00   22
22.00   15
23.00   9
24.00   11
25.00   2
26.00   3
30.00   2
Total   153
</code>
Now I want to recode the sum variable again into a 5-point scale (1-5) to get a composite score of my dependent variable. I will use this composite dependent variable in further analysis of ordinal logistic regression. My question is this:
What is the best way to recode the sum again into 5-point scale?
Or, please let me know if there exists any better way to create a composite scale from Likert items?
just to clarify my quesion: I have six variables that are related to my DV, all are on 5 point likert scale. and I could not find the best way to reduce these six variables into one. The composite score may be considered as one of the option.
Answer: You seem to have made up your mind that you want to turn this 6-30 variable, which for all we know may communicate finely grained information, into a coarser 1-5 variable which figures to have lower reliability.  Also that you want to conduct an ordinal logistic regression.  To tell you the truth it's hard to see good reasons for these decisions.
Moreover --and backing up--it's not always obvious that 6 different rating items will yield a valid and reliable indicator if summed to create a composite.  You'll see why if you browse through threads on this site related to the tags of scale, composite, psychometrics, and/or Likert.
Answer: Your decision appeares inconsistent. By virtue of summing up 6 rating items into the total score you discard your attitude to those six as ordinal level-of-measurement scales; instead, you treat them as interval ones. On the other hand, you disbelieve the total score to be interval - as seen in you wish to categorize it and input to ordinal regression. That means that you fully disregard your done action of summing up. Why then you chose just summing and not some other way of combining?
Answer: I agree with @rolando2 and @ttnphns but would go further. Coarsening a scale invokes magical thinking. It says that something magic happens at the border between categories. And a different division could yield a different solution.
One possible reason for doing this is to look at nonlinearities, but you have eliminated that if you assume proportional odds.  Instead, you could look at spline regression, or polynomial effects.
As to better ways of combining Likert items; one solution is to do a factor analysis and use the factor scores as the DV. However, this usually gives very similar results to just summing.
Comment: yes categorical principle component analysis could be run (if i consider my data as categorical) or PCA (if I consider it as continuous )but in both cases then I have to use linear regression on the factors and my data do not completely fulfil the assumptions of linear regression
Comment: If you create factors, then those factors are continuous. Other assumptions are about the error term, and you can't tell about that before doing the regression
Comment: Do you suggest that using linear regression after obtaining factors from Categorical principle component analysis (CATPCA), is the best option? means is it right to convert categorical data into continuous by CATPCA and run linear regression (not logistic) to find relationships.
Comment: I don't know if it's best, but it certainly seems reasonable. I don't know that you need CATPCA; you want something that captures the ordinality of the Likert items. Regular PCA may be better.

Composite variable from Likert items


How to filter a the required content from a string in linux?

Question: I had a string like:-
sometext sometext BASEDIR=/someword/someword/someword/1342.32 sometext sometext.

Could someone tell me, how to filter this number 1342.32, from the above string in linux??
Comment: are `sometext`'s always delimited from `BASEDIR=/ssdf/sdf/sdf/1324.12` with a space on each side?
Comment: This is terribly underspecified.  Can 'sometext' contain whitespace or digits?  What distinguishes the number that you want from that which you don't?  What do you want from `BASEDIR=/foo/345/bar/928.3k4/baz/34/blah`?
Answer: If sometext is always delimited from the surrounding fields by a white space, try this
cat log.txt | awk '{for (i=1;i<=NF;i++) {if ($i ~
/BASEDIR/) {print i,$i}}}' | awk -F/ '{for (i=1;i<=NF;i++) {if ($i ~
/^[0-9][0-9]*$/) {print $i}}}'

The code snippet above assumes that your data is contained in a file called log.txt and organised in records(read this awk-wise)
Comment: Thanks, but sometimes space will be there and sometimes its like /someword/someword/someword/1342.32/sometext/sometext. so is it possible to get the number, like in some cases space will be there and in some cases as i said above some text will be there
Comment: edited. Also, the more I look at the code, the less I like it... I'm sure that if you dive into some essential awk training you can come up with a simpler, more readable code.
Comment: sorry, thats not working , till here:- cat log.txt | awk '{for (i=1;i<=NF;i++) {if ($i ~
/BASEDIR/) {print i,$i}}}', is fine here we are getting, like basedir= sometext/sometext/1345.76/sometext. but after this the last line of command is not returning anything. but here we need to filter the number 1345.76. could you please make changes i n the above command. Its really needed for me. Thanks!!
Comment: I forgot the dot   xD ... This will work pal. `cat log.txt | awk '{for (i=1;i<=NF;i++) {if ($i ~/BASEDIR/) {print i,$i}}}' | awk -F/ '{for (i=1;i<=NF;i++) { if ($i ~/^[0-9.]+$/) {print $i}}}`
Answer: $ echo "sometext BASEDIR=/someword/1342.32 sometext." |
    sed "s/[^0-9.]//g"
> 1342.32.

The sed command searches for anything not in the set "0123456789" or ".", and replaces it with nothing (deletes it). It does this in global mode, so it doesn't stop on the first match.
This is enough if you're just trying to read it. If you're trying to feed the number into another command and need a real number, you will need to clean it up:
$ ... | cut -f 1-2 -d "."
> 1342.32

cut splits the input on the delemiter, then selects fields 1 and 2 (numbered from one). So "184.108.40.206" would return "1.2".
Answer: This works also if digits appear in sometext before BASEDIR as well as if the input has additional lines:
sed -n 's,.*BASEDIR=\(/\w*\)*/\([0-9.]*\).*,\2,p'

-n do not output lines without BASEDIR…
\(/\w*\)* group of / and someword, repeated
\([0-9.]*\) group of repeated digit or decimal point
\2 replacement of everything matched (the entire line) with the 2nd group
p print the result


How to be notified when traffic comes in on open port?

Question: I have opened port 80 to traffic for some web page development I'm doing (using port forwarding in my router). I realize this opens up my computer to intruders. What's the best way to prevent intruders from coming in through port 80 while it's open?   I'm working on a Mac.
Is there a Mac firewall setting or program that will detect and notify me of traffic (either unexpected traffic or all traffic) on this port? What I imagine is a dialog box would pop up for every access attempt, and I would have to approve it before it comes in.
Answer: If you had a dialogue opened up for every time someone hit your IP on port 80, you'd have a never-ending flood of dialogue boxes. The real solution is to either require authentication on your site (.htaccess style) or alternatively, set up your firewall to only allow connections to port 80 from a pre-determined list of IP addresses.
Comment: Well answered.. +1
Answer: You could keep a terminal open and tail -F /var/log/apache2/access.log (or equivalent). You could also tail -F /var/auth.log | grep -i port 80 (or equivalent) in another window. Or you could use multitail to watch both files in the same window.
Answer: Is there a reason why you have port 80 open to your development machine in the first place?  i.e. are you letting clients view the work in progress of the site off of your Mac?
Assuming that's the case, and that the work you're doing will end up on a Web server/hosting provider eventually, I'd recommend getting into the habit of setting up test sites (with or without authentication) on the Web server that will host the site eventually or a dedicated test or staging server.
This can be as simple as setting up another virtual host in Apache on a sub-domain such as dev.example.com or if you don't have control over their DNS, setting up client.yourdomain.com and having that on a separate virtual host somewhere.
The reason for doing this is a) you don't have to open up the world to your workstation b) you can leave it up 24/7 c) you won't have any "surprises" when promoting your changes live (like broken paths or absolute URLs that you forgot about) because you've already been doing this all along.
Comment: @Doug - if all you're doing is making outbound requests then you don't need any specific firewall rules other than port 80 *outbound* being open.
Comment: Thanks for the suggestion.

I have port 80 open because my program makes requests to Facebook JavaScript API, and I understand I need to open port 80 to receive responses behind the firewall.
Answer: You could just use tcpdump/wireshark and watch eactly what is happening.  Add the appropriate filters so you don't get flooded with more information then you need.
As ErikA mentioned though, it would be much better to just use the firewall rules or Apache config and limit access to the appropriate users.
Answer: You could also check out the app, Little Snitch. It's pretty great at catching all kinds of traffic, and let's you decide which bits you want to allow and deny. I think it's exactly the tool you are looking for.


How to troubleshoot why telerik radmenu ajax control stops working after form post?

Question: I have an ASP.NET form with Telerik Ajax RadMenu control hosted in a "portlet" inside a Plumtree portal.  The control works on first load, but then stops after postback occurs.  The postback occurs as a result of submit by another control on the same form.  So this seems Ajax related.  The trouble is the RadMenu stops working.
How to troubleshoot the issue, and learn WHY this is happening?  The second goal being how to resolve, but first things first.
The tools I am familiar with are the IE debugger, and Fiddler 4 (from Telerik).
What tools should I bring into this course?  What links to how-to use these tools?
The environment:
Windows 7 64 with IIS
Oracle WebCenterInteraction ver 10.3.3 (Plumtree)
EDIT:
This ASP.NET form is running fine outside of the portlet.  It is only when I run this inside the portlet do I lose the effect of the radmenu control.
ALSO IMPORTANT TO NOTE:  If I place this form into an iframe and have this served from the portal / portlet, the trouble is resolved.  The problem with this method is that the menus are clipped by the frame.  This form is a "part" in the page.
Some reading about configuring Portlets
UPDATE:
In order to work around this trouble, the farthest I can move forward with the Telerik controls is latest version supporting .NET 2.0.  I suspect the trouble has to do with the Plumtree portal not handling the javascript required in the Ajaxified Telerik controls while producing the inline controls.  Therefore causing the loss of expected control behaviour.
Thank you.
Answer: Question: What tools should I bring into this course? What links to how-to use these tools?
Answer:
1.Chrome debugger Tutorial
2.IE Debugger Tutorial
I personally found chrome to be my fav one.
*Troubleshooting : * As source code is not available here, i guess you have used the RadAjaxPanel which leads to update your RadMenu which is not intended in your case. I would suggest you to use RadAjaxManager and to specify the controls you want to update on the button's click.
<code> <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
                <AjaxSettings>
                    <telerik:AjaxSetting AjaxControlID="UrButtonID">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="ControlIDUWantToUpdate1"></telerik:AjaxUpdatedControl>
                            <telerik:AjaxUpdatedControl ControlID="ControlIDUWantToUpdate2" LoadingPanelID="RadAjaxLoadingPanel1"></telerik:AjaxUpdatedControl>
                            <telerik:AjaxUpdatedControl ControlID="ControlIDUWantToUpdate3" LoadingPanelID="RadAjaxLoadingPanel1"></telerik:AjaxUpdatedControl>
                        </UpdatedControls>
                    </telerik:AjaxSetting>
                 </AjaxSettings>
            </telerik:RadAjaxManager>
</code>
A Demo with an example is here
Comment: Thanks.  I made an edit to include that the form and controls works outside of the portal / portlet, and not after form submit while running inside the portlet.  It appears to be an issue with how this portal reposts the form contents after submit.  I'm looking for more detail on "how" to use debug tools to see or find the trouble.


GridView com uma linha só - Asp.Net C#

Question: Tenho uma coluna na GridView com Horários, fiz um esquema que pega de tal hora a tal hora por exemplo: 8:00 as 8:30 e assim vai para outras linhas.
Ao todo até as 18h dá 20 linhas.
Como faço para colocar isso tudo em uma linha só ?
Algo que quebrasse por "," e continuasse na mesma linha.
Obrigado.
Comment: Você pode mudar a sua fonte de dados, para possuir um item só ao invés de vários ou mudar de componente, escrever um table na mão talvez.
Comment: Pensei nisso de possuir um item só, mas no caso é uma lista de horários, iria ter problema de qualquer forma na hora de cortar as horas tipo, preciso fazer assim: 8:00 às 8:30, 8:30 ás 9:00 e assim vai numa linha só.
Comment: E se tu fizer um foreach e concatenar o conteúdo numa string?
Comment: Tentei fazer isso, só que tipo, vou atribuir pra string os horários que estou pegando em 2 objetos como hora_inicio e hora_fim e no final adicionar a ",". Só que ai quando acabar a lista a ultima virgula vai ficar lá ..
Comment: A última virgula você retira, isso é simples, mas a pergunta minha seria: Por que tudo numa row? Não entendi o porque, pois em row separadas fica bem mais legível, a menos que haja uma regra muito específica, por isso a pergunta, só por isso.
Comment: Uma forma de retirar a última vírgula: StringBuilder sb = new StringBuilder("1, 2, 3, ");

string resultado = sb.ToString(0, sb.Length - 2);
Answer: Você pode utilizar o componente Repeater para fazer isso. O código similar seria:
<asp:Repeater ID="rptHorarios" runat="server">
   <HeaderTemplate>

   </HeaderTemplate>

   <ItemTemplate>
        Eval("Horario")
   </ItemTemplate>
   <FotterTemplate>

   </FotterTemplate>
</asp:Repeater>

Código:
public void Page_Load(object sender, EventArgs args)
{
   if (!IsPostBack)
   {
      rptHorarios.DataSource = GetHorarios();
      rptHorarios.DataBind();
   }
}

Ou poderia utilizar também o DataList e setar as propriedades RepeatDirection e RepeatColumn com os respectivos valores.

GridView com uma linha só - Asp.Net C#


O que guardar em uma sessão de login?

Question: Estou desenvolvendo um sistema de login em PHP e MySQL para um painel de administração, e já vi muitos sistemas "seguros" de login onde eles armazenam na sessão o login do usuário ou a senha, isso quando não são ambos ou até todos os dados do usuário logado.
Já construí sistemas de login antes, e foi basicamente desta forma, mas preciso de algo mais seguro, não posso guardar a informações de login do usuário na sessão.
Alguma dica? ideia?
Comment: Guardar o ID do usuário é suficiente.
Comment: Confere o seguinte no console do browser `console.log(StackExchange.options.user)`
Comment: @Patrick só compensa guardar coisa que não tem importância ser acessada pelo cliente (como preferências de navegação, etc.). O resto é melhor que fique na sessão mesmo, assim o navegador do cliente não tem como acessar os dados. Se quiser deixar a sessão um pouco mais robusta, pode associar a ela o IP atual do usuário por exemplo (cuidado com efeitos colaterais, entretanto).
Comment: @bfavaretto, se eu guardar algo além do ID, é ruim?
Comment: Pode até salvar senha em cookie ou session desde que seja criptografado. A vantagem de salvar esses dados em cookie,  em client ou server, é poupar recursos de conexão com banco de dados em todas as requisições que exigirem e identificação e autenticação.
Answer: Para clarificar
Qualquer sistema de login implementado em PHP ou seja em que linguagem for que guarda na sessão os dados de login, em particular a password ou a combinação de password + nome de utilizador, é um sistema inseguro.

A segurança dos cookies de sessão
Os cookies de sessão, $_SESSION, cujos mesmos são gerados e guardados no servidor podem ser acedidos por terceiros, apesar de requerer algum trabalho, pelo que, quaisquer dados a guardar na sessão devem ser dados não comprometedores e com o intuito de otimizar o código e/ou reduzir o numero de consultas à base de dados.
PHP Security Consortium tem um guia online sobre segurança onde salienta dois problemas com a sessão, embora os mesmos possam ser ultrapassados com o devido cuidado por parte do programador:

Session Fixation

Fixation is the simplest method of obtaining a valid session identifier. While it's not very difficult to defend against, if your session mechanism consists of nothing more than session_start(), you are vulnerable.

que traduzido:

Fixação é o método mais simples de obter um identificador de sessão válido. Embora não seja muito difícil de defender, se o seu mecanismo de sessão consiste em nada mais do que session_start(), você está vulnerável.

Session Hijacking

Arguably the most common session attack, session hijacking refers to all attacks that attempt to gain access to another user's session.
As with session fixation, if your session mechanism only consists of session_start(), you are vulnerable, although the exploit isn't as simple.

Que traduzido:

Provavelmente o ataque mais comum à sessão, o sequestro de sessão refere-se a todos os ataques onde se tenta ganhar acesso a sessão de outro usuário.
Tal como acontece com fixação de sessão, se o seu mecanismo de sessão consiste apenas de session_start(), você está vulnerável, embora a tentativa com sucesso não seja tão simples.

Limitação da Sessão
A sessão tem um limite no que respeita aos dados armazenados que é imposto pelo tamanho máximo do ficheiro no sistema operativo. Não obstante, existe também o limite da memória imposto pela diretiva memory_limit que limita a quantidade de memória que um script de PHP pode consumir no servidor.
Dos dois, o que for mais baixo será o espaço máximo que a sessão pode ocupar.
Sessão vs Base-de-dados
A sessão quando criada gera um ID único por visitante, ID esse que nos permite identificar a pessoa de forma distinta em relação às outras. Esse ID guardado numa tabela de login na base de dados junto com a restante informação que precisamos para a sessão do utilizador é de fato uma das formas mais seguras de manter o sistema de login do website/aplicação.
Onde a segurança é um fator mais critico do que aquilo que habitualmente já o é, podemos ver as coisas desta maneira: Em teoria, é mais facil chegar aos dados em sessão do que chegar aos dados na base de dados dado a mesma estar por trás de mais passwords de acesso.
O que guardar na sessão
Guardar dados na sessão bem como chegarmos a utilizar ou não a sessão é algo que vai depender da informação a gerir. Por norma a sessão torna-se util para guardar informação do tipo:

Erros dum formulário;
Mensagens ao utilizador;
Endereços para redirecionamento após determinada ação.

Ou seja, a sessão dá-nos a flexibilidade de guardar dados de forma persistente e facilmente acessíveis. A sessão não é propriamente uma base de dados para armazenar informação critica ou comprometedora.

Sumário
Base de dados para guardar os dados do utilizador com login realizado é o caminho a seguir.
O uso da sessão é particularmente útil para guardar informação de auxilio à navegação e interação com o utilizador.
Dados comprometedores devem ficar em base de dados, nunca em sessão.
Login + Password nunca guardar na sessão e a password nunca guardar sem estar encriptada.
Comment: a sua resposta está muito didática..... Gostei. Para melhorar adicione que dados de sessão persistentes a melhor forma é em base de dados e que em sistemas com muitos acessos é importante adicionar ao mecanismo uma cache do tipo "memcached" para que a base de dados não entre colapso melhorando também a capacidade de resposta. Parabéns pela resposta.
Answer: O problema é que o cookie está na máquina do visitante e está disponível facilmente e qualquer pessoa pode editá-lo.
Imagine a minha id é "Peter". Eu estou em seu site, com login. Vou dar uma olhdada no Cookie e ver lá dentro "id = Peter".
Eu vou perguntar um colega qual e seu id, ele vai me dizer que é (por exemplo)  "maximo". Vou colocar um cookie com "id = maximo" e eu poderia me conector como ele.
Não é muito seguro ...
Isto requer que o cookie contém informações suficientes para que você saiba quem está conectado (não só o seu id, mas também outras informações que você pode misturar para verificar se eles são corretas, por exemplo id visitante, a sua idade, o seu CEP etc ...) e também que o cookie é criptografada.
A dificuldade é que você não pode ter uma criptografia assimétrica, porque você vai ter que ler o cookie para levar informações.
Portanto, você deve determinar o que precisa armazenar, preparar os dados como uma string, criptografar a string e colocar no cookie.
Após a leitura, você vai ter que decifrar o cookie e remover as "string" e verificar a integridade. Você pode, por exemplo criptografar de acordo com a data de apresentação do Cookie, a localização do visitante etc ... Então, se alguém consegui "quebrar" o cookie, ele também vai dever saber a localização geográfica de que ele quer usurpar identidade, que rapidamente se torna complicado.
Aqui está uma pequena classe de criptografia que pode ajudá-lo. Eu, obviamente, não pode mostrar-lhe o caminho completo que eu uso para criptografar meus cookies.
 class Chiffrement
{
// Cipher:
// cast-128 gost rijndael-128 twofish arcfour cast-256 loki97 rijndael-192
//  saferplus wake blowfish-compat des rijndael-256 serpent xtea blowfish
// enigma rc2 tripledes

// Modes:
// cbc cfb ctr ecb ncfb nofb ofb stream

private static $cipher  = MCRYPT_RIJNDAEL_256;  // Cipher

private static $mode    = 'cbc';  // Mode (blocoss)

public static function crypt($data,$key)
{
    $keyHash = md5($key);
    $key = substr($keyHash, 0,   mcrypt_get_key_size(self::$cipher, self::$mode) );
    $iv  = substr($keyHash, 0, mcrypt_get_block_size(self::$cipher, self::$mode) );

    $data = mcrypt_encrypt(self::$cipher, $key, $data, self::$mode, $iv);
    return base64_encode($data);
}

public static function decrypt($data,$key)
{
    $keyHash = md5($key);
    $key = substr($keyHash, 0,   mcrypt_get_key_size(self::$cipher, self::$mode) );
    $iv  = substr($keyHash, 0, mcrypt_get_block_size(self::$cipher, self::$mode) );

    $data = base64_decode($data);
    return mcrypt_decrypt(self::$cipher, $key, $data, self::$mode, $iv);
}
}

Vou completar para responder no cometario: no caso dos base de dados, das sessaos, e muito dificil saber onde sao os dados. E de verdade, não importa. Se uma pessoa pode fazer uma injecçao SQL, ela não precisa saber "exatamente onde" são os dados: ela precisa saber como ler os dados. E suficiente.
Então, achar que tudo ta certo porque os dados não no servidor e uma brincadeira: o que precisa e proteger o aceso, então, evitar "dar a chave da casa". A dificuldade e que o visitante... deve ter a chave para acessar! Significa que a chave vai estar no navegador.
O problema maior e a ligaçao entre a chave e os dados e a pergunta principal e "como fazer para evitar a copia da chave e, pior, como evitar que uma pessao entende o sistema da chave para fazer uma copia igual o que parace igual".
Analisar os Cookie no seu navegador permite facilmente ver que tem que não são protegidos: vc vai var o seu id por exemplo. Com um software tipo https://chrome.google.com/webstore/detail/editthiscookie/fngmhnnpilhplaeedifhccceomclgfbg?hl=fr vc pode modificar os cookie.
Isso significa que precisa modificar o cookie para evitar a modificaçao, colocar mas que o Id, criar uma ligaçao entre os dados do cookie.
O objetivo jamais vai ser de colocar todas as info no cookie: o objetivo esta de impedir a modificaço do cookie e ter a capacidade, do lado do servidor, saber que a chave esta coreta. Depois, com uma chave coreta, ler os dados da BDD é facil.
Comment: Os dados da sessão são guardados no servidor. O cookie geralmente só contém um id de sessão para poder recuperar esses dados na outra ponta.
Comment: Não estou contestando que existam medidas adicionais de [segurança contra *session hijacking*](http://pt.stackoverflow.com/questions/33740), só quis esclarecer que os dados de sessão geralmente não ficam guardados em cookies (o autor da pergunta parecia confuso quanto a isso). E, para constar, o -1 na sua resposta não é meu.

O que guardar em uma sessão de login?


Can I translate nodes and provide access to their translated content without the use of a site-wide language switcher?

Question: Intended behaviour / question

Writer creates /node/5001
Translator translates /node/5001 to french using all the niceties of the Content Translation backend system
Visitor goes to /node/5001 and sees a link in the sidebar to the french version
Visitor arrives at /fr/node/5001, reads it, and then clicks away using one of the main menu links or anything in the sidebar
Visitor is now browsing the website in English, since that's the main language of the website, and the language menu links are written in. The viewing of translated content behaves just like viewing any other page on the website; it doesn't change languages for good.

Things are going wrong between steps 4 and 5, since step 4 puts the website in "French mode" which means all menu links point to french versions of content. In theory, all subsequent browsing will be in French (which is not what I want), and in practice the language will switch back and forth between French and English depending on the availability of translations (which is even worse), even though the URL will include the /fr/ prefix no matter what is actually displayed.
Is there a practical solution to this?
Background / supplemental
I've enabled Drupal 8's Content Translation and Language modules. Language detection & selection is done using the default mechanism, which recognizes language code prefixes in the first component of the website's path (for example, /fr/node/1, for the french version of node 1).
I'm now wondering if there's any way, without going toe to toe in a fight to the death with the Drupal final boss, to provide translations ONLY of the content on select pages, but NOT of the entire site, such that the content is made available through links on my website, with the default language being restored to English when navigating away from those same pages?
The intention is to use Drupal's built-in (though other non-core suggestions are welcome) translation management features to create and manage subordinate multilingual content on the backend, but then access these translations on a case by case basis through links in a block for example, without having these navigation actions trigger persistent language selection events (from a user perspective) which rewrite all the menu URLs to match.
Basically, I'm trying to get something to work that would be the Content Translation module equivalent of a bunch of multilingual PDFs attached to a single piece of English content. Except I don't want to link to PDFs, I want to link to ordinary web pages, with the only real difference being that they're written in another language, and linked to an English version behind the scenes.
Am I wasting my time with this, or is there a way to translate just a subset of my content, with access opened up to those translations from the english site, minus the persistence of a full-on language switch for the remainder of the browsing session?
Answer: A simple solution in such cases would be to remove the language switcher and provide for translated content only modal links:
French version

You could add the links to the node, in a template or preprocess hook. Or create a block (View or custom block plugin), which lists the available translations of the current node as modal links.
How to build such links see How to open a popup form from a view link?
Answer: Drupal multilingual features are very versatile and can cover most if not all cases. It is still a fairly complex feature and it is necessary to understand some concepts before you know how to configure everything to satisfy a particular need.
The most important concept to understand in your case is the two-part nature of the multilingual system. One part is called the interface and the other is content. Interface and content are translated separately. Once you translate your interface you can add as many nodes/content as you like and you don't have to translate the parts of the interface again, you only have to translate the node content (if you wish to have that content translated at all).
Interface language and Content language don't need to match. You can have the English interface being active while watching a French node.
The Detection and selection configuration under Languages configuration allows for different settings when it comes to selecting which language to choose for either the interface or content.
There may be more than one combination of options that solves your particular problem, and I haven't tested this, but I'll offer the most likely solution.
You don't want the interface language to change, you always want the English menus etc. That means you shouldn't use the URL under Interface language selection at all, just use the default fallback. This means your URLs won't ever have the /fr/ in from of them (path prefix selects the interface language, not the content).
You need to enable the separate Content detection (separate from Interface selection), and set that to Content language. This option adds a special parameter to your nodes links that tells Drupal which node translation to serve.
Here's the likely config:

Here is what the links might look like:
/node/97?language_content_entity=en
/node/97?language_content_entity=fr
You can use Views or simply create language-specific Menus or menu items that list those links.
Comment: +1 for this in detailed answer. Although the result is not always the expected one, because rendered content contains often interface translated strings, the field configuration runs through it, but also any string added by t().
Comment: Thank you @4k4! Yes, the interface/content separation isn't exactly pure, and it isn't easy to predict what all the configuration combinations might effect. It's best to know what you're after, learn about the concepts and go from there, the right configuration combination can then be found.
Comment: Unfortunately, I just discovered that this still rewrites menu links, albeit inconsistently depending on which language a page is viewed in first following a cache clear. Translate a few nodes and add links to them in the main menu, then clear the cache, then visit one of the nodes incognito in a non-default language. All menu items that include translated content in that language will be rewritten from that page.
Comment: Can you update your question with more details about the symptoms and menu multilingual configuration? What links do you get in the menu, and which ones do you expect instead?
Comment: Sorry prkos, just got your message now. I've created a little demo of the problem at https://translation-menu-bug.textninja.net/ - I hope that brings clarity to the issue.
Comment: This example has my head spinning lol Does the English block have the visibility set to show only on English interface? Then those links/block shouldn't display? It's hard to tell without playing with the configuration and trying things out. BTW what you call "French mode" is actually just using the site with French interface. I must say I haven't noticed your symptoms on my side, nor your example, interface language doesn't change when using English links while on a French content page. The interface language remains English, but the English links get the parameter in fr because I'm guessing
Comment: ... that particular content has both English and french translations available so because you're viewing French content with English interface, the configuration is making those Block links to take you to the same, French content with English interface. I think you have to dig deeper into understanding the differences between interface and content. URL prefix affect the interface lang, which you don't want affected, and the parameters at the link ends affect the content lang. The issue may be that you don't have a strategy for your multilingual experience...
Comment: Here's a problem case: ("interface/content") start with E/F, visit a page that had both E and F translations, then visit a page that only has F translation. What happens with the interface lang? Check the labels translations for that, not how the links are constructed. Maybe your only issue is with how the links get contructed under various conditions WRT translations available? Because that is a bit separate from language negotiation for interface/content. This questions needs to be clarified more in that direction.
Comment: Rather than edit the original question, which you answered sufficiently, I might create a new question (or bug report, or feature request) to get to the bottom of the behaviour you described perfectly here: "...so because you're viewing French content with English interface, the configuration is making those Block links to take you to the same, French content with English interface" . That is what I mean when I say the site's in "French "mode"". I lack a better term for it, don't want it to happen, and see no way to turn it off. Thanks for all your patience and help with this!
Comment: Very simply, my problem now (which is probably not solvable by configuration alone) is that outbound link hrefs are, per a comment in the [language module's processOutbound function](https://api.drupal.org/api/drupal/core%21modules%21language%21src%21Plugin%21LanguageNegotiation%21LanguageNegotiationUrl.php/function/LanguageNegotiationUrl%3A%3AprocessOutbound/8.2.x), rewritten (by design) to point to content in the current page's language. The comment is: "*language can be passed as an option, or we go for current URL language"*. I'd like an option to turn that feature off in some menus.
Comment: Yes, post it on d.o., that's where it's all happening at this deep level :)
Answer: Just to add to prkos's excellent accepted answer, I found that once I configured my website according to his instructions, if I really wanted to let end users use /fr/ language path prefixes, thereby making pages accessible without full-site switching at paths like /fr/node/1, I could do so via the following .htaccess / mod_rewrite rule:
RewriteRule "^fr/(.*)" "https://%{HTTP_HOST}/$1?language_content_entity=fr" [P,QSA]
That assumes that mod_proxy and SSLProxyEngine are both enabled / on.
One issue with the above is that pages will be suddenly be accessible at two different URLs, without a visible redirect, which may or may not interfere with analytics. Also, the canonical URL in the site's meta will differ from the URL shown, even if the Redirect module is enforcing canonical URLs.
Anyhow, I just thought I'd throw that "solution" out to the wind, in case someone reading this in the future REALLY has their heart set on parameterless URLs. As for me, I'll probably just stick to the default of node/1?language_content_entity=fr.
Comment: Great thinking, and you can do a lot more with Rewrite rules, including redirects. Duplicate content is definitely something to avoid, for more than one reason. The shown URLs don't need to be identical to the canonical URL, I guess that's the whole point of them. Machines will care about the canonical, users will care about the shown. I expect lang href is more important for SEO when it comes to multilingual sites.
Comment: Although I'd by far prefer the solution where Drupal handles it the way it makes sense for the purpose of the site. If you can't find a config combination to solve your problem you should report it on drupal.org because then it's a missing feature and there will be more users in need of it.


SQLAlchemy: Delete object directly from one-to-many relationship without using session.delete()

Question: I have the following SQLAlchemy setup:
Base = declarative_base()

class Post(Base):
    __tablename__ = 'post'
    id = Column(Integer, primary_key=True)
    title = Column(String(30))
    comments = relationship('Comment', cascade='all')

class Comment(Base):
    __tablename__ = 'comment'
    id = Column(Integer, primary_key=True)
    post_id = Column(Integer, ForeignKey(Post.id, ondelete='CASCADE'), nullable=False)
    text = Column(Text)

With this, I can create post objects with a one-to-many relationship to comments. I want to handle creation and deletion of comments for posts without referencing the session. Adding a comment to a post works just fine:
post = Post(title='some post')
comment = Comment(text='some comment')
post.comments.append(comment)

My session handler only knows about posts, so it would do a session.add(post) and the comment is placed into the session automatically and is syncronized with the database on the next session.commit(). However, the same is not true for deletion of comments. I want to be able to delete a comment by just doing:
post.comments.remove(comment)

However, this produces the following error on the next session.commit():
sqlalchemy.exc.OperationalError: (OperationalError) (1048, "Column 'post_id' cannot be null") 'UPDATE comment SET post_id=%s WHERE comment.id = %s' (None, 1L)

How do I tell SQLAlchemy to not update the comment with a NULL value for post_id (which is not allowed due to the not null constraint on the column), but delete the comment instead? I know that I could do session.delete(comment), but since I did not need to add the comment to the session explicitly, I don't see a reason why I should have to delete it from the session explicitly.
I found several solutions for cascading deletes to related objects, but since I never issue any explicit deletions to the session (the post is still there), I don't think that is applicable.
Edit: I adjusted the example to include the cascading of deletions from posts. Now it works to do session.delete(post) and all comments are deleted. But I just want to automatically delete the comments I removed from the relationship and not delete the whole post with all comments.
TL;DR: How do I tell SQLAlchemy to issue a delete statement instead of an update statement when I remove an entry from a relationship list of a one-to-many relationship?
Answer: Read Configuring delete/delete-orphan Cascade section of documentation for more information, but basically you need delete-orphan as well in your cascade option of the relationship:
class Post(Base):
    # ...
    comments = relationship('Comment', cascade="all, delete-orphan")

Comment: With the `delete-orphan` option in the cascades, the deletion upon removal from the relationship list works as expected. Thanks.
Answer: I am not a SQLAlchemy user, but I think you should use the ondelete option

    post_id = Column(Integer, ForeignKey(Post.id, ondelete="CASCADE"), nullable=False)

See, Mysql 5.6 Manual  13.6.44, FOREIGN KEY Constraints

SET NULL: Delete or update the row from the parent table, and set the foreign key column or columns in the child table to NULL.
Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported.

CASCADE: Delete or update the row from the parent table, and automatically delete or update the matching rows in the child table.
Both ON DELETE CASCADE and ON UPDATE CASCADE are supported. Between two tables, do not define several ON UPDATE
CASCADE clauses that act on the same column in the parent table or in the child table.

And
http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html  Section: Defining Foreign Keys -> ON UPDATE and ON DELETE
Comment: That would probably work when deleting the post using `session.delete(post)`, but I am not doing this. So there is nothing to cascade down to the comment. I just want to delete the comment.


Making a sunburst diagram with D3.js

Question: I am learning D3 and love it! I am reading books, and I am stuck at an exercise making a sunburst diagram.
Here is my code so far:

   <%--Then write/append script to container--%>

Making a sunburst diagram with D3.js


Athletes under the Olympics flag competing in team sports

Question: The Russian Olympic team has been banned from the 2018 Pyeongchang Winter Olympics due to government supported doping allegations. However, 168 athletes from Russia were permitted to participate in the Olympics headed by the international committee of Olympic Athletes from Russia (OAR) under the Olympic flag.
Similarly, the Russian team was banned from the 2016 Summer Olympics and I asked
Athletes who have won Olympic medals under the olympic flag. This question focused on why the athletes who won medals were competing as independent individuals.
The OAR Hockey team has the best odds of winning the Hockey gold medal in the 2018 games. Since the answers to the aforementioned question didn't list any medal winners in team sports, I'm wondering how many times, if any, athletes under the Olympic flag competed in team sports? Please list the sport, year, and the results of each team.
Comment: The [Unified Team](https://en.wikipedia.org/wiki/Unified_Team_at_the_Olympics) competed under the Olympic Flag, but for somewhat different reasons. Do you want to include their results? (There's a lot of them as they were just about a full Soviet team).
Comment: https://en.wikipedia.org/wiki/Independent_Olympians_at_the_Olympic_Games this seems to have quite a lot of information answering all of the questions here.
Comment: wow didn't know about that, it's before I was born. For the Unified Team lets only look at the medal winners
Comment: Refugees were allowed to compete under the Olympic flag in the Rio games.
Answer: at both the 1992 winter and summer olympics the countries from the former soviet union competed as the unified team. The unified team competed in the following team sports.
Ice Hockey (1992 winter olympics)
Basketball (1992 summer olympics) (men's and women's)
Handball (1992 summer olympics) (men's and women's)
Field Hockey (1992 summer olympics) (men's)
Volleyball (1992 summer olympics) (men's and women's)
Water Polo (1992 summer olympics)