Access attributes of objects in a list

Question: I'm using a book called Python for Absolute Beginners and am doing a challenge in the book's chapter 8 (Software Objects). My  code works but I want to add another capability to the code; What code do I need to add to feed/play/talk with a specific critter?
In choice #7 of my code (7 - Feed a specific critter), I have written some code but it doesn't work. How might I access/change the attributes of a specific object that the user selects?
Also, any feedback to improve/shorten the code?
# Critter Caretaker
# A virtual pet to care for
class Critter(object):
    import random
    """A virtual pet"""
    def __init__(self, name, hunger = random.randint(0,9), boredom = random.randint(0,11)):
        self.name = name
        self.hunger = hunger
        self.boredom = boredom

    def __pass_time(self):
        self.hunger +=1
        self.boredom +=1

    def __str__(self):

        m = "name is: {}, hunger is: {}, boredom is: {}".format(self.name, self.hunger,self.boredom)

        return m

    @property
    def mood(self):
        unhappiness = self.hunger + self.boredom
        if unhappiness <5:
            m = "happy"
        elif 5 <= unhappiness <=10:
            m = "okay"
        elif 11 <= unhappiness <=15:
            m = "frustrated"
        else:
            m= "mad"
        return m

    def talk(self):
        print("I'm", self.name, "and I feel", self.mood, "now.\n")
        self.__pass_time()

    def eat(self, food=3):
        print("Yummy! Thank you.")
        self.hunger -=food
        if self.hunger <0:
            self.hunger = 0
        self.__pass_time()

    def play(self, fun=4):

        print("That was fun! Thanks")
        self.boredom -=fun
        if self.boredom <0:
            self.boredom = 0
        self.__pass_time()

def main():
    noc = []
    noc.append(Critter("Chicken"))
    print("An critter named Chicken has been created")
    choice = None
    while choice != "0":
        print \
        ("""
        Critter Caretaker

        0 - Quit
        1 - Listen to all your critters
        2 - Feed all your critters
        3 - Play with all your critters
        4 - Create a new critter
        5 - Show a list of critters
        6 - Delete a critter
        7 - Feed a specific critter
        """)

        choice = input("Choice: ")
        print()

        # exit
        if choice == "0":
            print("Good-bye.")

        # listen to critters
        elif choice == "1":
            if len(noc) != 0:
                i.talk()
            else:
                print("No critters exist")
        # feed your critters
        elif choice == "2":
            if len(noc) != 0:
                for i in noc:
                    print(i.name, "says:", end = " ")
                    i.eat()
        # play with your critters
        elif choice == "3":
            if len(noc) != 0:
                for i in noc:
                    print(i.name, "says:", end = " ")
                    i.play()
            else:
                print("No critter exists")
        # Create a new critter
        elif choice == "4":
            noc.append(Critter(input("Enter a name for your new critter: ")))
        # Show critters
        elif choice =="5":
            b = 0
            if len(noc) != 0:
                for i in noc:
                    b +=1
                    print(b, "." ,i.name)
            else:
                print("No critter exists")
        # delete a critter
        elif choice == "6":
            a = int(input("Enter the serial number of critter you want to delete: "))
            a = a -1
            del noc[a]

        # feed a specific critter
        elif choice == "7":
            sctd = input("Enter name of critter you want to feed: ")
            if sctd in noc:
                noc.eat()
            else:
                print("That critter doesn't exists")

        # print attributes of critters
        elif choice == "919":
            for i in noc:
                print(i)
        else:
            print("\nSorry, but", choice, "isn't valid.")

main()
("\n\nPress the enter key to exit.")

Answer: In the branch for feeding a specific critter, you have the line noc.eat() -- noc is a list, which has no eat() method. You need to access the critter specified by the input, and call the eat() method on that object. Something like:
for c in noc:
    if c.name == sctd:
        c.eat()
        break

(although there is an issue with this example if multiple critters match sctd -- solving that is something i'll leave to you)
an additional minor point of feedback on your code: a docstring should be the first statement inside the definition as per PEP 0257.
Answer: Just a small note is that I think the convention something like import random should probably be placed at the start rather than inside the class which also gets rid of the problem raised by @nthall which is that your docstring is currently not the first object.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). Or perhaps you want to [ask a new question](https://stackoverflow.com/questions/ask)?
Comment: I was not asking a question I was merely being slightly vague because I was only 90% sure on the python norms about this issue.

Access attributes of objects in a list


Show that if natural $m$ is even, then $2^{m} -1$ is not prime.

Question: Show that if natural $m$ is even, then
$2^{m} -1$ is not prime.
As $m$ is even, so $m= 2n, n \in \mathbb{N}$. Hence,
$2^{2n} -1 \implies  (2^n)^2 -1^2 \implies  (2^n -1)(2^n+1)$.
So, need show either
$(2^{n} -1)$ or  $(2^n+1)$ is not prime.
Suppose if one of them is prime, then other is differing by $2$ only.
So, the problem reduces to showing that for any given prime $p\notin \{3,5,7\}$, $p\pm 2$ is not prime.
Request help.
Comment: If $A=(2^n -1)(2^n+1)$, then $A$ cannot be prime since it has two factors. ($n\in\mathbb{N}$) Holds for every $n$ except $n=1$.
Comment: $3$ always divides $2^{2n}-1$, because $2^2=4\equiv1$ mod $3$. So unless $2^{2n}-1=$ equals $3$, it's not prime. Actually for $n=1$ ($m=2$) it does equal $3$. So the claim is true for even $m$ greater than $2$.
Comment: To finish the proof, you need to show that atleast one of those factors is not 1 or the number itself.
Comment: @alex.jordan please make an answer, more so because modular arithmetic is used. Might be there is a generalization beneath this question.
Comment: You can actually use the recurrence  $2^{m+1}-1=2(2^m-1)+1$ and prove the $m$ have to be prime.
Answer: First of all, the claim is false; if $ m $ is $ 2 $, then $ 2 ^ m - 1 $ is prime.  However, for all even $ m > 2 $, the claim is correct; in fact, in that case, $ 2 ^ m - 1 $ is composite.
In your question, you write that you need to show that either $ 2 ^ n - 1 $ or $ 2 ^ n + 1 $ is not prime.  But this is incorrect; to show that their product is composite, you need to show that either $ 2 ^ n - 1 $ or $ 2 ^ n + 1 $ is not equal to $ 1 $.  To show this, just set up the equations $ 2 ^ n - 1 = 1 $ and $ 2 ^ n + 1 = 1 $ and solve them; see what $ n $ would have to be (if there are even any solutions at all) and check that this is ruled out by the assumption that $ m > 2 $.  (Actually, because the subtraction could take you out of the system of positive integers, you should also check for solutions to $ 2 ^ n - 1 = 0 $ and $ 2 ^ n - 1 = - 1 $.  Still, you will find no solutions for $ n $ that are consistent with the assumption that $ 2 n $ is an even integer greater than $ 2 $.)
Answer: If you take $2^{2n}-1$ mod $3$:
$$\begin{align}
2^{2n}-1&=4^{n}-1\\
&\equiv1^{n}-1\\
&\equiv0
\end{align}$$
So $3$ divides $2^{2n}-1$. Either the number is not prime, or it equals $3$. It equals $3$ exactly when $n=1$.
So for $n\geq2$, $2^{2n}-1$ is not prime. (And it's prime, equal to $3$, when $n=1$.)


Universal quantifier and "such that"

Question: I'm given the following predicate that I'm trying to understand from a course example.
$\forall n \in\mathbb N : n^2 \ge n$
is the colon for such that correct?
I understand that it reads as "for all elements in the natural set such that the square of n is greater or equal to n"
Should it be $\forall n \in\mathbb N, n^2 \ge n$? "for all elements in the natural set the square of $n$ is greater or equal to $n$"
it makes more sense to me this way. But I'm not sure if my assumption is correct.
Answer: As always, you should defer to your professor on matters of convention. If he says to use a colon in such and such way, do it. That being said...
Usually you see a colon in set builder notation, ie $$\{n\in\mathbb{N} : n^2 \geq n\}$$ In which case you would read it as "(the set containing) all natural numbers such that $n$ squared is greater than or equal to $n$."
The colon is usually not used in propositions meant to be read, so you wouldn't use $$\forall n\in\mathbb{N}:n^2≥n$$ to mean "for all elements in the natural set such that the square of n is greater or equal to n... (insert rest of proposition)."
You can simply use a comma to mean "such that," but generally it makes your math much less understandable. For instance, "$\forall n\in \mathbb{N}, n^2 \geq n$" could mean "...for all $n$ such that $n^2 \geq n$" or it could mean "Each $n\in \mathbb{N}$ has the property that $n^2 \geq n$"
Shorthand should never sacrifice clarity, so I would recommend "$\forall n\in \mathbb{N}$ s.t. $n^2 \geq n$..." Basically,

Follow appropriate conventions
Never sacrifice clarity for conciseness.
Answer: You are correct. The punctuation in the examples \begin{gather}\forall n{\in}\mathbb{N}:n^2≥n\tag1\\\exists n{\in}\mathbb{N},\,n^2≥n\tag2\\\exists n {\in}\mathbb N:n^2 \ge n\\\forall n {\in}\mathbb N,\, n^2 \ge n\end{gather} are superfluous, primarily to supply typographical breathing space. In $(1)$ and $(2)$ in particular, the punctuation can be confusing (and break the flow of reading), as evidenced by your Question. In $(1),$ the colon is not to be read as "such that" (doing so renders the statement ungrammatical and incoherent); in $(2),$ the comma is similarly neither literal nor to be understood as a pause.
In more complex formalisations, to delimit quantifier scope, commas/colons/periods are sometimes used in place of parentheses. Because this usage of punctuation conflicts with the above, punctuating quantifiers potentially creates ambiguity and even misinterpretation.
Here's an example where adding commas creates confusion and ambiguity.

Universal quantifier and "such that"


Set PHP version for Symfony project in PhpStorm

Question: In a Symfony 3.4 project which I develop using PhpStorm I use the PhpStorm Terminal Window for running the Symfony server like
php bin/console server:run

This works fine.
However the terminal uses the PHP version that is set in the windows environment path variable.
I don't get it to use the PHP version configured in the project setting (Settings -> Languages & Frameworks -> PHP) in the field CLI Interpreter.
Why is the terminal ignoring this setting totally?
Comment: PHP Interpreter is used by IDE only (when IDE is calling it directly -- e.g. executing/debugging PP script in CLI environment). PHP Interpreter does not influence your terminal environment. Your actual command gets executed with whatever you have got set there in your environment. So instead of just `php` you may specify the path to specific PHP executable.
Comment: lol - thanks for the edit :D
Comment: ah OK - so I can specify the php excutable to be used by adding the path to the call? like [my_path_to_php]/php bin/console... ?
Comment: Another possible alternative (not sure how well it will work though) is to try executing your command via Command Line Tools (`Tools | Run Command`) -- it should use currently selected interpreter. Check more: https://www.jetbrains.com/help/phpstorm/command-line-tool-support.html
Comment: Thank you! I just tried to call the specific php version - that works! It's a bit much to write though. Will try your other suggestion too. If you write me an answere I will accept it gladly.
Comment: *"like [my_path_to_php]/php bin/console..."* Yes, that's what I meant. It's inconvenient ... therefore you may try setting up an alias for that (e.g. `php71` will be `/path/to/php/php71/php`) then your command may look like `php71 bin/console ...`
Comment: OK. Cool. I am not sure how to define an alias though...
Comment: For Linux/Mac that should not be a problem (just google "bash create alias" or alike). For Windows you may use batch script if you cannot find a way to create an alias... Symbolic links will do as well.
Answer: You can configure the terminal for current project and set a custom PATH so php runs whatever interpreter you want. Open the Settings dialogue and head to Tools/ Terminal.
I think the neatest option is to tweak Shell path like this:
"cmd" /k "PATH=C:\php-5.6.0-Win32-VC11-x64;%PATH%"

You can also do the obvious thing and edit the environment variables to set PATH.

It works just fine but this variable totally overrides the parent PATH and I couldn't find a way to just prepend my value (neither $PATH nor %PATH% work).
Some other ideas:

Use "cmd" /k to load a custom configuration script.
Set PowerShell as shell and create aliases.


Mounting centralized NAS server with NFS . Need to forbid users from doing sudo su

Question: long history short:
- we have a bunch of linux servers.

lots of users work with linux Desktops. They use them as testing servers.
All the infrastructure has the Authentication services linked by Quest Auth Services againts an AD. This gives us the option of logon scripts, startup scripts, and other things.
One interesting option this Quest thing gives us is SUDO management. We can edit sudoers file by GPO politics.
Now we are deploying a NAS server from Hitachi with cifs and NFS mapping capabilities.
Servers are managed by IT, so nobody can go root except us.
Desktop users will also mount the NFS shares so they will be able to work with real data and read their own data from servers.
Desktop users can go sudo su.
If desktop users go from root to another user, the NFS let them work as they where the other user.

I would like to keep them from swithching users, but only between AD users, they must be able to switch to apache user or postgres user.
I'm missing something or this is going to be tricky?
Can anybody give me a hand on this thinking?
Many thanks.
Answer: I'm not entirely sure that i have the exact problem here, but let me try. Change the /etc/sudoers file to:-
<code>%user ALL=(apache,postgres) ALL
</code>
So any member of group user can run anything as apache or postgres users. So the commands
<code>sudo -u apache -i
</code>
would change to the person in the user group to apache user. However they wouldn't be able to change to everyone in the active directory domain.
Comment: `sudo su - apache` would not work in this case. The users will need to invoke sudo with the -u option to specify the user and the -I option to start a login shell. So, to get a shell as apache: `sudo -u apache -i`
Answer: Decado pointed a nice approach.
But the user will be able to go to root, on grub going to /bin/sh and do whatever they like. So... it's pointless to cut them on the sudoers, the only way is going to the fileshares by cifs. and so we will do.
THanks.


Fechar app ao finalizar fragment

Question: Olá, tenho uma aplicação, se resume em: uma Activity e um fragment. A activity chama o fragment através do onCreate:
Código da Activivity que chama o fragment:
 @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_mensagem);

            chamaSecondActivity();
        }

        public void chamaSecondActivity() {

            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.containerMensagem, new SecondActivity());
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

        }

Gostaria que quando voltasse do fragment o app fechasse e não retornasse para a activity.
Answer: Você pode remover essa linha do seu codigo:
fragmentTransaction.addToBackStack(null);

Ela faz o botão voltar, voltar do fragment e não da Activity.

Fechar app ao finalizar fragment


Ladder (recurrence) operators for Hermite polynomials?

Question: Generally, Hermite polynomials can be described using the Rodrigues formula:
$$
H_n(x) = (-1)^n e^{x^2}\frac{d^n}{dx^n}e^{-x^2}
$$
And the first few polynomials (for $n = 0,1,2,3,4,5...$) are well known:
$$
H_0(x) = 1\\
H_1(x) = 2x\\
H_2(x) = 4x^2 - 2\\
H_3(x) = 8x^3 - 12x\\
H_4(x) = 16x^4 - 48x^2 + 12\\
H_5(x) = 32x^5 - 160x^3 + 120x\\
$$
I am asked to derive two "ladder operators", $L_{\pm}$, (like the ones used for the harmonic oscillator in quantum mechanics), such that
$$
L_{\pm}H_{n}(x) = H_{n\pm 1}(x)
$$
It seems the $L_{+}$ would be something like "multiply $2x$ each time and do other stuff" -- or more eloquently, "multiply $\frac{d}{dx} e^{x^2}$ and ..." -- but I'm having trouble getting a full answer.
Answer: Note that,
$$H_{n}'(x) = \frac{d}{dx}\left[(-1)^n \exp(x^2) \left(\frac{d}{dx}\right)^n \exp(-x^2)\right] = 2x H_n - H_{n+1}(x),$$
which can be rearranged so that,
$$H_{n+1}(x) = \left(2x-\frac{d}{dx}\right)H_n(x),$$
from which we conclude that,
$$\boxed{L_+ = 2x-\frac{d}{dx}}.$$
For $L_{-}(x)$ note that for the polynomials you have listed $H'_n(x)=2nH_{n-1}(x)$ holds. This suggests an induction proof.
Suppose $H'_n(x)=2nH_{n-1}(x)$ for some $n$ and consider the following,
$$H'_{n+1} = (L_+H_n(x))' = (2xH_n(x)-\color{red}{H'_n(x)})'$$
 $$= (2xH_n(x)-\color{red}{2nH_{n-1}(x)})'$$
$$ = 2H_n(x) + \color{blue}{2xH'(x)} - 2nH'_{n-1}(x)$$
$$ = 2H_n(x) + \color{blue}{2x(2n)H_{n-1}(x)} - 2nH'_{n-1}(x)$$
$$ = 2H_n(x) + 2n(\color{green}{2xH_{n-1}-H_{n-1}'(x)})$$
$$ = 2H_n(x)+2n\color{green}{L_+H_{n-1}(x)} $$
$$=2H_n+2n\color{green}{H_n(x)}$$
$$ = 2(n+1)H_n(x) $$
From this I would conclude that the best we can do for $L_-$ is,
$$\boxed{L_- = \frac{d}{dx} },$$
the result when applied to $H_n(x)$ will introduce a factor of $2n$ which is different than the identity you are looking for.
Comment: This is probably a bit late for your purposes, but I saw the unanswered question during a search and figured I would attempt to answer it.


How should I put my fingers on a piano / electronic keyboard?

Question:
Should the fingers be curved/bent or straight?
Should I press the key actively or let my finger fall by "using gravity"?
Answer: Your fingers should be curved, approximately as much as they curve naturally when you hold you hand loosely.    Flautists can have trouble with this at first ;).  Your hand should be parallel to the keyboard or tilted forward a little.
You'll need to actively press the keys, as well.  Even when playing softly you want exact control of how the key is struck.  You can use gravity to help when playing fortissimo, though, and having your hand "fall" can be used for visual effect when playing staccato (though many overdo it).
For more on hand/arm position, see my answer here.
Answer: We sometimes teach children the basic hand position by saying "pretend you're holding an orange".  The degree of force varies, but it's always more than just letting gravity do its thing!  For rapid and brilliant playing we consciously LIFT our fingers before striking down on the note.  This is maybe more a technique for weighted keyboards on pianos and imitation pianos than for unweighted synthesizer keys.  But either way, the fingers need to WORK, not just flop down.
Answer: Wrist movement is important in preventing over use of the fingers and possible injury. Keep your wrist flexible and as you play a key, let your wrist and arm slightly drop.


Proving that rational numbers cannot have denominator zero (without referring to division by zero)

Question: Given the set $S$ of all pairs $(a, b),$ with $a, b \in \mathbb{Z},$ the relation $Q$ on $S$ is defined by $(a,b)Q(c,d) \iff ad=bc$. How can I prove that $b$ cannot be equal to zero, without using the fact that you cannot divide by zero?
I'm guessing it's something to do with $Q$ being an equivalence relation, and perhaps using the property of transitivity?
Thanks!
Comment: Welcome to MSE. You want to prove that $b$ cannot be $0$ using *which* assumptions?
Comment: You can't. In your assumptions, "division" or "equivalence relation" aren't even mentioned.
Answer: You know that $Q \neq \mathbb Z^2$, because, for example, $1 \neq 2$ and so $(1,1)$ and $(1,2)$ are not related by $Q$.
Now, if we allow $b=0$ (and likewise $d$), then from $0y = 0x$ we get $(0,0) Q (x,y)$, for all $x,y \in \mathbb Z$.
Therefore $Q$ would not be an equivalence relation.


É possivel oferecer opções de retorno num método?

Question: Como já é do meu conhecimento existe o overload na criação dos métodos, que são opções de execução, exemplo(bem simples), um método onde você tem a opção de passar 2 ou 3 parâmetros chamando a mesma função:
//Soma 2 numeros
public int  Somar(int a, int b)
{
    return a + b;
}

//Soma 3 numeros
public int  Somar(int a,int b, int c)
{
    return a + b + c;
}

A pergunta é: Eu posso criar um overload de retorno? Como por exemplo:
public PessoaJuridica RetornarPessoa(string id)
{
    return new PessoaJuridica();
}

public PessoaFisica RetornarPessoa(string id)
{
    return new PessoaFisica();
}

Surgiu a necessidade pois eu tenho dois método com nomes diferentes e seria mais fácil para mim usar o mesmo nome, pois eles fazem "a mesma coisa".
Comment: como você separa pessoa física de pessoa jurídica, digo, no banco de dados, estão em tabelas separadas ?
Comment: Rovann, foi um exemplo só, eu não estou utilizando PessoaF e PessoaJ, é que eu tenho dois tipos de usuario, o Usuario comum(que consulta fotos) e um usuario contribuidor(que envia), e eu queria receber os dados do perfil de ambos através de um nome de método apenas e não dois.
Comment: certo, então, esses dois tipos de usuários, estão na mesma tabela ? há um campo que identifique de qual tipo ele é ?
Comment: Estão em tabelas diferentes, porque nesse caso as informações de cada um são BEEEM diferentes. Digamos que seja outra área do site, eles não tem relação entre sí.
Comment: nesse caso, iria pelo generics mesmo, se tivesse uma relação de herança, até poderia usar o polimorfismo, mas se não tem relação, utilizaria de uma interface e método genérico
Answer: Não é possível. A assinatura do método não considera o tipo de retorno. Se fosse possível, complicaria o trabalho do compilador para saber qual método você quer usar.
Eu não entendo bem qual a intenção de se fazer isso e não há detalhes suficientes para eu poder entender, mas imagino que você possa resolver isso usando um método genérico.
public static T RetornarPessoa<T>(string id) where T: new()
{
    return new T();
}

Eu suponho que você tenha alguma hierarquia nas classes. Por isso, fiz este exemplo de como pode ser implementada a minha ideia:
Veja funcionando no .NET Fiddle.
public class Program
{
    public static void Main()
    {
        var pessoa = RetornarPessoa<PessoaFisica>("a550");
        Console.WriteLine(pessoa.Id);
    }

    public static T RetornarPessoa<T>(string id) where T: Pessoa, new()
    {

        return new T { Id = id };
    }
}

public abstract class Pessoa
{
    public string Id { get; set; }
}

public class PessoaJuridica : Pessoa
{
    public string RazaoSocial { get; set; }
}

public class PessoaFisica : Pessoa
{
    public string NomeCompleto { get; set; }
}

Answer: Isto não é possível, a assinatura do método só considere o seu nome e os tipos dos parâmetros.
Se fizesse com o retorno complicaria o compilador, criaria ambiguidade e possíveis bugs.
A solução mais sensata neste caso é colocar um diferencial no nome do método indicando qual é o tipo de retorno que ele proverá. Fica até mais legível. Cheguei pensar em algumas outras, mas nada que seja recomendado. Cheguei até iniciar uma resposta com uma alternativa, mas é algo que complica o código, cria confusão, abre brecha para bugs, melhor ir para o caminho fácil, seguro e óbvio.
public PessoaJuridica RetornarPessoaJuridica(string id) {
    return new PessoaJuridica();
}

public PessoaFisica RetornarPessoaFisica(string id) {
    return new PessoaFisica();
}

Coloquei no GitHub para referência futura.
Comment: seu post/resposta no link ficou fantástico !
Answer: Na postagem foram feitas duas perguntas.

Eu posso criar um overload de retorno?

Não, isso realmente não pode. A identidade de um método é feito por nome do método x parâmetros. Mesmo que duplique o método modificando apenas o retorno, o compilador vai entender que é o mesmo método - e não uma sobrecarga - e irá dar erro.

É possível oferecer opções de retorno num método?

É possível sim, basta deixar isso claro na assinatura do método.
Um método pode ou não retornar um valor, mas o legal é que esse valor pode ser qualquer coisa.
Usando Either
public interface IPessoaRepository
{
    Either<Option<PessoaFisica>, Option<PessoaJuridica>> RetornaPessoa(string id);
}

public class PessoaRepository : IPessoaRepository
{
    public Either<Option<PessoaFisica>, Option<PessoaJuridica>> RetornaPessoa(string id)
    {
        // { seu codigo aqui }
        return pessoa; // Tanto faz se é tipo PessoaFisica ou PessoaJuridica
    }
}

Fonte: http://www.elemarjr.com/pt/2017/04/exceptions-sao-muito-intrusivas/


Reverter um commit que ainda não recebeu push, e com varios comits esperando para receber push

Question: Em um dos commits que realizei eu inclui uma pasta com varios arquivos os quais totalizam uns 5gB aproximadamente, tentar realizar o push do mesmo commit ocorreu um erro (fatal: The remote end hung up unexpectedly), e o push não finalizou corretamente. Infelizmente eu não percebi que isso tinha acontecido, e continuei a trabalhar e a fazer novos commits, sempre que tentava realizar um push, o erro se repetia. Agora exitem varios commits que não receberam push, são 8 em total.
Este é o output do comando git status:
git status:

$ git status
On branch Optimizando
Your branch is ahead of 'origin/Optimizando' by 8 commits.
  (use "git push" to publish your local commits)

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   MAIN/DataResources/ExcelTables/Consola_00.xlsx
        modified:   MAIN/FUNCTIONS/Operar_Binary.py
        modified:   MAIN/FUNCTIONS/__pycache__/Operar_Binary.cpython-37.pyc
        modified:   MAIN/OPERATION_00.py

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        .gitingnore
        ESTADISTICAS/
        MAIN/DataResources/ExcelTables/LOG.xlsx
        MAIN/F5.py
        MAIN/FUNCTIONS/copia.py
        MAIN/__pycache__/indices.cpython-37.pyc
        MAIN/test-2.py

no changes added to commit (use "git add" and/or "git commit -a")

o output do comando git cherry -v é o seguinte:

$ git cherry -v
+ d67a194ca3abc6847545488471a37a37bdfac060 Estadistica feu incorporado al servidor
+ 90021137be3752cf043fa9a67a9219121b5d9d95 error pabo
+ 6d65ef35c0568c5c261ce9b26d1fbe7526e02048 fix
+ c718a223615e84e2f2ef9172487bac7a58aeafce funcion gigante subdibidida
+ cd3e1e25a84da83e98e01c06df216fcc5e8f81d2 Conflictos
+ 20dae7b7f65762823cdc9f473e5bbe78d02479c7 Incorporacion Indices sintectico y eliminacion de Estadistica
+ 73d93be70f84c71bb98c8d519f7b742a12686472 Correcion en Menu desplegable de activos
+ a5e7f8d5d25f181f2d1ed39a76d509c272417933 Correcion en la seleccion de activo forex

o commit no qual foram incorporados os arquivos que estariam causando o erro é o de id: "d67a194ca3abc6847545488471a37a37bdfac060 Estadistica feu incorporado al servidor"
como poso reverter esse commit sem perder o trabalho que foi realizado apos eu ter adicionado os arquivos? Um detalhe importante, a pasta que continha os arquivos originalmente se chamava "Estatistica", no desespero eu tentei renomea-la para ESTATISTICAS porem isso isso não resolveu o problema.
Desde já muito obrigado pela ajuda.
Answer: Você pode fazer um

git rebase -i d67a194ca^

e vai abrir uma tela onde você pode mudar a ordem dos commits, alterar a descrição, etc. É um comando muito poderoso. Pelo que entendi você quer descartar o commit d67a194, então edite a respectiva linha substituindo "pick" por "drop". Ou simplesmente remova a linha, que o commit vai ser desprezado.
É importante lembrar que isso vai "reescrever a história", ou seja, os commits que vieram depois do d67a194 vão ser refeitos como se aquele não tivesse existido. Se isso causar algum conflito, você pode ter de resolver manualmente.
Se você lê em inglês, pode dar uma olhada no meu texto https://epxx.co/artigos/gitfaces.html que descreve o uso do git rebase -i e da edição de conflitos durante o rebase interativo.


How @@rowcount works if two queries executed simultaneously in two query windows?

Question: I want to use @@rowcount to track rows processed. But I have question if one statement is executed and taking long time, meanwhile if other query executed in other query window will it affect @@rowcount value of first one?
How @@rowcount will behave in this scenario?
Database: SQL Server
Comment: What happens when you try it in two windows?
Comment: When I'm trying it is giving expected output but I want to use this with dynamic query,So wanted to know firm detail on same.
Comment: Does this answer your question? [SQL Server - is using @@ROWCOUNT safe in multithreaded applications?](https://stackoverflow.com/questions/8960510/sql-server-is-using-rowcount-safe-in-multithreaded-applications)
Answer: It will give the corresponding rows affected for the two queries. Two windows here, are effectively two sessions. So they are not affected in any way whatsoever.
@@ROWCOUNT is both scope and connection safe.
In fact, it reads only the last statement row count for that connection and scope. The full rules are here on MSDN (cursors, DML, EXECUTE etc)
To use it in subsequent statements, you need to store it in a local variable.
Comment: @ADITYAPAWAR I have expanded my answer. Hope it answers your question.
Comment: But @@rowcount is global variable. So you are saying every session will have it's own copy?


html form validation with javascript

Question: i am working with simple form validation with javascript but its seems there is small glitch which tried to catch but i am unable to do it here is the code, the problem is that the select list doesn't gets validated i dont know why

<title>Mobile Phone Prices In Pakistan </title>

<form id="theform" name"form1">

Name:
<input type="text" name="username" id="username" />

 Email:
 <input type="text" name="email" id="email" />

Country:
<select name="country" id="country">
<option value="0">choose your country </option>
<option value="pk">pakistan</option>
<option value="ind">India</option>
<option value="afg">afghanistan</option>
<option value="irn">Iran</option>
</select>

Gender

Male
<input type="radio" name="gender" id="radio" value="radio">

Femal
<input type="radio" name="gender" id="radio2" value="radio2">

<input type="checkbox" name="rules" id="rules">
Accept our rules and regulation to continue with form process

<input type="submit" name="button" id="submit" value="register" >

</form>

Comment: Can you make a JSFiddle put of this ?
Comment: You can use `value` instead of `selectedIndex`
Comment: ok here is jsfiddle http://jsfiddle.net/Ldr3f5pw/
Comment: Typo in your code. `email.vlaue.length`
Answer: Mistyped here
if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.**vlaue**.length){

Answer: You have a spelling mistake in your if statement
if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.vlaue.length){
replace  email.vlaue.length with  email.value.length
Answer: The reason is, because you misspelled value at the email part.
Working JSFiddle: http://jsfiddle.net/v4qv7n7m/1/
Your code:
if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.vlaue.length){

    document.getElementById("emailerror").innerHTML = "please enter your email";
    email.focus();
    document.getElementById("emailerror").className = "error";
    return false;

}else{

Working code:
if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.value.length){

    document.getElementById("emailerror").innerHTML = "please enter your email";
    email.focus();
    document.getElementById("emailerror").className = "error";
    return false;

}else{

Answer: typo here email.value.length
if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.value.length){
                                                      ^^^^^^

}

http://jsfiddle.net/Ldr3f5pw/
Answer: What you actually are looking for is to see if the select has a value.
Here is a revised edit of your code.

Please Select a Security Question from the Drop Down List.

    <select name = "Security Question" id="securityQuestion">
        <option></option>
        <option value="m">What is your Mother's maiden name?</option>
        <option value="p">What is the name of your pet?</option>
        <option value="c">What is your favorite color?</option>
    </select>
    <input type="button" value="Click to Check" onClick="checkDropdown(1)" />

Key Differences
I am checking the select's value, not the option's "checked" status
I am selectingbyId, the browser indexes Ids early on (not sure about by name)
I am checking for the absence of a value, not if the value equals one of 3 cases. (cleaner/easier to read)

Comment: upvote require 15 reputation .. sorry dude if i could i would for sure thanks again

html form validation with javascript


Python open() gives "FileNotFoundError: [Errno 2] No such file or directory:", but the file exists

Question: I'm trying to read all the files in a directory and append the text in them into a list but I get the error in the header. However, the file actually exists. My code is:
pos_lines = []
train_pos_path = r'C:\Users\Halid\Desktop\nlp_p5\nlp_dir2\TRAIN\posTr'
# print(os.listdir(train_pos_path))
for filename in os.listdir(train_pos_path):
    with open(filename, "r",encoding="utf-8", errors='ignore') as f:
        for line in f.readlines():
            pos_lines.append(line)

The path is the absolute path of the directory and print(os.listdir(train_pos_path)) gives the list of the files under that directory. However, I can't open the files in it and it gives me the error I mentioned. My code I'm trying to run is in "C:\Users\Halid\Desktop\nlp_p5". Does anybody know why I'm getting this error and how can I solve this?
Answer: You've specified an absolute path to the directory, r'C:\Users\Halid\Desktop\nlp_p5\nlp_dir2\TRAIN\posTr'. You then proceeded to list all files with their filenames, receiving A, B, C, ...
However, A, B, C, ... are not located in the directory you're running your python script.
Try calling
os.chdir(train_pos_path)

before calling the for loop.
Another solution would be to prepend each path with train_pos_path:
train_pos_path = r'C:\Users\Halid\Desktop\nlp_p5\nlp_dir2\TRAIN\posTr'

for filename in os.listdir(train_pos_path):
    with open(os.path.join(train_pos_path, filename), "r",encoding="utf-8", errors='ignore') as f:
        for line in f.readlines():
            pos_lines.append(line)

The key takeaway from this is the fact that os.listdir(directory) returns just the names as seen from the directory, not their absolute paths.


Grafana-server keeps connect and send data to some external addresses

Question: I am running a Grafana-server on an Ubuntu 15 server.  It seems to keep connecting to 151.101.*.133:443.  I have identified a few and listed below.  When I connect to the address manually from a browser, it returns a Github.io SSL certificate.  Of course, the browser would block it because it doesn't match with the URL.
Version Installed: grafana/wheezy,now 3.1.1-1470047149 amd64 [installed]
Here are the addresses I have identified

22.214.171.124/32
188.8.131.52/32
188.8.131.52/32
18.104.22.168/32
Comment: IMHO, this question belongs to Grafana bugtracker (after a brief examination I suppose it requests [some internal metrics from here](https://api.github.com/repos/hawkular/hawkular.github.io/contents/?ref=swagger)
Answer: After setting followings in the config.ini, grafana-server stopped connecting to random addresses
reporting_enabled = false
check_for_updates = false


Baum Welch:Calculating transition probability

Question: I am trying to understand the Baum Welch algorithm by implementing it in xls. I have chosen a simple example of observations from a loaded (L) vs fair (F) die.
I calculate the forward and backward probabilities for L and F states. I then calculate the probability of observations. I know the calculations till this point are correct, since i get the same p(observations) for each row of data.
i.e.p(observations)= forward probability(L)*forward probability(F)+ backward probability(L) * backward probability(F)  is same for all rows as it should be
Then I proceed to calculate the transition probabilities. Here I find that the value of the transition probability for the state transition L->L is coming to be above 1.For other states the values seem to be correct
I calculate the transition probabilities for  L->L for each row as follows:
T(L->L)
(Forward_probability(L,t)* Transition(L->L)* emission(observation|L) * backward_probability(L,t+1))/ probability(observations)
The estimated probability = sum( T(L->L) )/sum(L|observation )
I am unable to find why my transition probability has value > 1.
Any help will be appreciated.
Answer: I found out the issue. I was using the emission probability of current observation whereas I should have used for t+1 th observation. I get correct answer now
Comment: Congratulations on resolving your issue.  You're not the first one to have broken the unity barrier in probability, and with probability $>$ 1, you won't be the last. But unlike some, at least you realized you had probabilities exceeding one.


How to obtain the p-value (check significance) of an effect in a lme4 mixed model?

Question: I use lme4 in R to fit the mixed model
lmer(value~status+(1|experiment)))

where value is continuous, status and experiment are factors, and I get
Linear mixed model fit by REML
Formula: value ~ status + (1 | experiment)
  AIC   BIC logLik deviance REMLdev
 29.1 46.98 -9.548    5.911    19.1
Random effects:
 Groups     Name        Variance Std.Dev.
 experiment (Intercept) 0.065526 0.25598
 Residual               0.053029 0.23028
Number of obs: 264, groups: experiment, 10

Fixed effects:
            Estimate Std. Error t value
(Intercept)  2.78004    0.08448   32.91
statusD      0.20493    0.03389    6.05
statusR      0.88690    0.03583   24.76

Correlation of Fixed Effects:
        (Intr) statsD
statusD -0.204
statusR -0.193  0.476

How can I know that the effect of status is significant? R reports only $t$-values and not $p$-values.
Comment: Going by the answers provided to this question, one wonders in what actually OP is interested here: testing coefficients against a null (vanilla $t$-test one does in regular linear regression against a null $H_0:\beta=\beta_{\text{null}}$), or testing for minimization of variance (the $F$-test we get from the many types of ANOVA). Those two aim at different things. An enlightening answer, while not about mixed-effects models, is found [here](http://stats.stackexchange.com/a/28973/60613).
Comment: library(car)
Anova(mod, test="F")
Answer: There is a lot of information on this topic at the GLMM FAQ. However, in your particular case, I would suggest using
library(nlme)
m1 <- lme(value~status,random=~1|experiment,data=mydata)
anova(m1)

because you don't need any of the stuff that lmer offers (higher speed, handling of crossed random effects, GLMMs ...). lme should give you exactly the same coefficient and variance estimates but will also compute df and p-values for you (which do make  sense in a "classical" design such as you appear to have). You may also want to consider the random term ~status|experiment (allowing for variation of status effects across blocks, or equivalently including a status-by-experiment interaction).  Posters above are also correct that your t statistics are so large that your p-value will definitely be <0.05, but I can imagine you would like "real" p-values.
Comment: For a classical design (balanced, nested, etc.) I think I can indeed argue that there's a real p-vaue, i.e. a probability of getting an estimate of beta of an observed magnitude or greater if the null hypothesis (beta=0) were false ... lme4 doesn't provide these denominator df, I believe, because it's harder to detect in general from an lme4 model structure when the model specified is one where some heuristic for computing a classical denominator df would work ...
Comment: I don't know about this answer. `lmer` could just as easily report the same kinds of p-values but doesn't for valid reasons.  I guess it's the comment that there are any "real" p-values here that bugs me.  You could argue that you can find one possible cutoff, and that any reasonable cutoff is passed.  But you can't argue there's a real p-value.
Comment: try `summary(m1)` instead (I use this with nlme package)
Comment: For testing RE variances: http://bbolker.github.io/mixedmodels-misc/glmmFAQ.html#testing-significance-of-random-effects   . For testing levels of the categorical variable: under standard frequentist, you can't perform significance tests on these effects, because they are random variables rather than parameters.  (Feel free to look around CrossValidated some more for answers to these questions and post a new question if you don't find anything satisfactory ...)
Comment: Can I ask why the p values provided in the summary(m1) are not the same as the ones in the anova(m1)?
Comment: Wald p-values vs likelihood ratio test p-values ...
Comment: What about the variable "experiment"? The output is a variance, how do can know if that variable is significant? How can I know if any of the levels of that categorical variable is significant?
Answer: You could use the package lmerTest. You just install/load it and the lmer models get extended. So e.g.
library(lmerTest)
lmm <- lmer(value~status+(1|experiment)))
summary(lmm)
anova(lmm)

would give you results with p-values. If p-values are the right indication is a little bit disputed, but if you want to have them, this is the way to get them.
Comment: What about the variable "experiment"? The output is a variance, how do can know if that variable is significant? How can I know if any of the levels of that categorical variable is significant?
Comment: see my answer to the same comment above.
Comment: worked nicely for me!
Answer: If you can handle abandoning p-values (and you should), you can compute a likelihood ratio that would represent the weight of evidence for the effect of status via:
#compute a model where the effect of status is estimated
unrestricted_fit = lmer(
    formula = value ~ (1|experiment) + status
    , REML = F #because we want to compare models on likelihood
)
#next, compute a model where the effect of status is not estimated
restricted_fit = lmer(
    formula = value ~ (1|experiment)
    , REML = F #because we want to compare models on likelihood
)
#compute the AIC-corrected log-base-2 likelihood ratio (a.k.a. "bits" of evidence)
(AIC(restricted_fit)-AIC(unrestricted_fit))*log2(exp(1))

Comment: Note that likelihood ratios are asymptotic, i.e. don't account for uncertainty in the estimate of the residual variance ...
Comment: I am interested in your last line. What is the interpretation of the result? Are there sources I can take a look at on that?
Comment: @RosaMaria negative values reflect evidence in favor of the null
Comment: @RosaMaria In my answer, the two models were constructed such that they are identical with the exception that the restricted model did not include the status predictor. In that case $H_0 : \Beta_{status} = 0$ and $H_1 : \Beta_{status} != 0$

Note also that in the intervening decade I converted to Bayes, and the "estimation" flavour therein, where one would fit/sample a single model that includes a possible effect of status and thereby yield a posterior distribution on the magnitude of such effect. The brms package in R is a great entry-point to Bayes for those already familiar with lme4
Comment: @RosaMaria hm, as you wrote them, the restricted and unrestricted models share the same fixed-effects structure and differ only in the random-effects structure such that the unrestricted model has by-subject variability in both intercepts and Time effects, with correlation therein, while the restricted model has only by-subject variability in intercepts. So the resulting likelihood ratio reflects evidence associated with two quantities (the correlation and the by-subject variance in time) either both being precisely zero or both being non-zero. Rarely do such multi-quantity LRs have usefulness
Comment: @skan It's not possible to assess whether a given level of a random effect is "significant" (that can only be done when you treat variables as fixed effects) but it is possible to ask whether inclusion of the random effect as a whole provides a worthwhile increase in the model's performance. You would simply compare a model with the variable (plus all other structure you have already deemed worthwhile) to a model without it, in the same way as in my answer above.
Comment: @MikeLawrence Can't you test if the variance of the random effect is smaller than what we expect from a random population without it?
Comment: @skan sorry, I don't understand. Maybe best to post your query as a new question, where you can elaborate more fully than is possible in these comment boxes?
Comment: What about the variable "experiment"? The output is a variance, how do can know if that variable is significant? How can I know if any of the levels of that categorical variable is significant?
Comment: Hi @MikeLawrence, I computed the likelihood that you suggested in your answer for my model and I got $-277.5714$ negative, how would I interpret this ? Thanks
Comment: Do you mean that if $H_0 :p ≤ 0.5$ and $H_1 :p > .5$ then if $-277$ would mean it is statistically significant but if $+277$ then it is not and then in favor of $H_1$ ? Thanks  @MikeLawrence
Comment: I read in previous comments that the null is $_0 : \beta=\beta_{null}$ but what does it mean $\beta_{null}$ ? Do the $/beta$ takes into account all the fixed effects that we could have in a model (like the intercept, slope and maybe interaction ?) Sorry for the questions, I am trying to understand these models hehe @MikeLawrence
Comment: Thanks, this is very helpful in fact. Just last question hehe If I have a model `lmer(log(Volume) ~ Time*Treatment + (Time|Subject))` can I construct these restricted and unrestricted models, by just removing the Treament 2-factor variable? So, then the restrictedmodel would be `lmer(log(Volume) ~ Time*Treatment+ (1|Subject))`? To check the evidence for the effect on the Treatment variable ?. Also, I will have a look at the brms. Thanks a gain  @MikeLawrence
Comment: Thank you very much!
Answer: The issue is that the calculation of p-values for these models is not trivial, see dicussion here so the authors of the lme4 package have purposely chosen not to include p-values in the output. You may find a method of calculating these, but they will not necessarily be correct.
Answer: Consider what you're asking.  If you just want to know if the overall p-value for the effect of status passes some some sort of arbitrary cutoff value, like 0.05, then that's easy.  First, you want to find out the overall effect.  You could get that from anova.
m <- lmer(...) #just run your lmer command but save the model
anova(m)

Now you have an F value.  You can take that and look it up in some F tables.  Just pick the lowest possible denom. degrees of freedom.  The cutoff there is going to be around 20.  Your F may be larger than that but I could be wrong.  Even if it's not, look at the number of degrees of freedom from a conventional ANOVA calculation here using the number of experiments you have.  Sticking that value in you're down to about 5 for a cutoff.  Now you easily pass it in your study.  The 'true' df for your model will be something higher than that because you're modelling every data point as opposed to aggregate values that an ANOVA would model.
If you actually want an exact p-value there's no such thing unless you're willing to make a theoretical statement about it.  If you read Pinheiro & Bates (2001, and perhaps some more books on the subject... see other links in these answers) and you come away with an argument for a specific df then you could use that.  But you're not actually looking for an exact p-value anyway.  I mention this because you therefore shouldn't report an exact p-value, only that your cutoff is passed.
You should really consider the Mike Lawrence answer because the whole idea of just sticking with a pass point for p-values as the final and most important information to extract from your data is generally misguided (but might not be in your case since we don't really have enough information to know).  Mike is using a pet version of LR calculation that is interesting, but it may be hard to find a lot of documentation on it.  If you look into model selection and interpretation using AIC you may like it.
Answer: Edit: This method is no longer supported in newer versions of lme4. Use the lmerTest package as suggested in this answer by pbx101.
There is a post on the R list by lme4's author for why p-values are not displayed. He suggests using MCMC samples instead, which you do using the pvals.fnc from the languageR package:
library("lme4")
library("languageR")
model=lmer(...)
pvals.fnc(model)

See http://www2.hawaii.edu/~kdrager/MixedEffectsModels.pdf for an example and details.
Comment: lme4 no longer supports this. This post could be updated to spare people having to find this out like I just did.
Answer: Are you interested in knowing if the combined effect of status has a significant effect on value? If so, you can use the Anova function in the car package (not to be confused with the anova function in base R).
dat <- data.frame(
  experiment = sample(c("A","B","C","D"), 264, replace=TRUE),
  status = sample(c("D","R","A"), 264, replace=TRUE),
  value = runif(264)
)
require(lme4)
(fm <- lmer(value~status+(1|experiment), data=dat))

require(car)
Anova(fm)

Have a look at ?Anova after loading the car package.
Comment: Any idea how `car::Anova()` avoids the sticky issues surrounding computation of p-values that Michelle links?
Comment: I think it was definitely a good idea to redirect to an ANOVA calculation to find out the overall effect of stats but I'm not sure finessing the p-values is good.  The regular `anova` command will give you F's.
Comment: I don't, but my guess is that it avoids the sticky issues by ignoring them! Having reread the original post, I feel that I might have misunderstood the question. If the OP wants exact p-values for the fixed effects parameters, s/he is in trouble. But if the OP just wants to know if they're significant, I think the t-values are larger than any uncertainty in how the exact p-value would be calculated. (In other words, they are significant.)
Comment: I think this is a bit stickier than apparent. Running ANOVA's is valid when you want to minimize variance, but from the question wording I think OP wants to establish the marginal effect of variables, _i.e._ test coefficients against a null.
Answer: Simply loading the afex package will print the p-values in the output of the lmer function from the lme4 package (you don't need to be using afex; just load it):
library(lme4)  #for mixed model
library(afex)  #for p-values

This will automatically add a p-value column to the output of the lmer(yourmodel) for the fixed effects.
Answer: You could use parameters::p_value() to get the p-values. I found it to be very useful.
Answer: The function pvals.fnc is not longer supported by lme4.
Using the package lmerTest package, it is possible to use other method to calculate the p-value, such as the Kenward-Roger's approximations
model=lmer(value~status+1|experiment)
anova(model, ddf="Kenward-Roger")

Answer: You can install the jtools package and use the summ function on the output model to get the p-value of the fixed effects.
library(lme4)
library(jtools)
model <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
summ(model)

FIXED EFFECTS:
---------------------------------------------------------
                      Est.   S.E.   t val.    d.f.      p
----------------- -------- ------ -------- ------- ------
(Intercept)         251.41   6.82    36.84   17.00   0.00
Days                 10.47   1.55     6.77   17.00   0.00
---------------------------------------------------------

p values calculated using Satterthwaite d.f.
```


Question about a point process

Question: Q) Let the number of calls we receive on a telephone have a mean density of $1$ per hour. Suppose that we don't get calls at the same time and the number of calls in disjoint intervals of time are independent of each other.
1) We survey $10$ days of calls. How many pairs of calls do we expect to see within $5$ minutes of each other. (If there are $k$ calls in a given $5$ minute interval, there are ${k \choose 2}$ pairs).
2) Suppose that all the calls get delayed by a random amount which is an exponential distribution with mean $10$ minutes. Show that the resulting call times have the same distribution as before.
I am not sure if the question is missing information about the point process being a Poisson point process. I am going to assume that for now.
Let $X$ be the number of calls in a given $5$ minute interval, then $X\sim Pois(1*\frac{5}{60})$ and thus the expected number of calls in a given $5$ minute interval $= \frac{1}{12}$. In $10$ days, we have $\frac{10\times 24\times 60}{5}$ disjoint intervals of $5$ minutes. So would the answer to $(1)$ be $\frac{10\times 24\times 60}{5}\times {1/12 \choose 2}$?
Not sure how to address $(2)?$
Comment: What do you mean by "$10$ days of calls"? Is that assuming the call center is open for e.g. $8$ hours a day?
Answer: For $(1)$ let $n$ be the number of days surveyed, $T$ the number of minutes in the interval, and $\lambda$ the rate of the arrival process. Then the expected pairs of calls within $T$ minutes of each other is given by
\begin{align}
\mathbb E[N(n,T,\lambda)] &= \int_{\frac T{60}}^{8n}\left( \sum_{k=0}^\infty \binom k2\cdot\mathbb P\left(N(t) - N\left(t-\frac T{60}\right) = k \right)\right)\ \mathsf dt\\
&= \int_{\frac T{60}}^{8n}\left( \sum_{k=0}^\infty \binom k2 e^{-\lambda T/60}\frac{(\lambda T/60)^k}{k!}\right)\ \mathsf dt\\
&= \int_{\frac T{60}}^{8n}\left(\left(\frac{\lambda T}{60}\right)^2\sum_{k=0}^\infty e^{-\lambda T/60}\frac{(\lambda T/60)^k}{k!}\right)\ \mathsf dt \\
&= \int_{\frac T{60}}^{8n} \left(\frac{\lambda T}{60}\right)^2\ \mathsf dt\\
&= \int_{\frac T{60}}^{8n}\frac{\lambda  T}{60}\ \mathsf dt\\
&= \frac{\lambda ^2 T^2 \left(8 n-\frac{T}{60}\right)}{7200}
\end{align}
(Note that $T$ has unit $\mathrm{min}$ and $\lambda$ has unit $\mathrm{hour^{-1}}$, hence the division by $60$.) Substituting in your values of $n=8$, $T=5$, and $\lambda = 1$, we have $N= \frac{767}{3456}$.
$(2)$ simply follows from the memoryless property of the exponential distribution. That is, if $X\sim\mathrm{Expo}(\lambda)$ then for $s,t>0$:
\begin{align}
\mathbb P(X>s+t\mid X>s) &= \frac{\mathbb P(X>s+t,X>s)}{\mathbb P(X>s)}\\
&= \frac{\mathbb P(X>s+t)}{\mathbb P(X>s)}\\
&= \frac{e^{-\lambda(s+t)}}{e^{-\lambda s}}\\
&= e^{-\lambda t}\\
&= \mathbb P(X>t).
\end{align}
The times between arrivals in a Poisson process are exponentially distributed, so delaying the arrivals by an exponentially distributed amount of time does not affect their distribution.
Comment: For $(1)$, may I know what happened to ${k \choose 2}$ in the sum?
Comment: Since $\binom k2=k(k-1)$, we have
\begin{align}
\sum_{k=0}^\infty\binom k2 e^{-\lambda T/60}\frac{(\lambda T/60)^k}{k!} &=
\sum_{k=2}^\infty k(k-1) e^{-\lambda T/60}\frac{(\lambda T/60)^k}{k!}\\&=
(\lambda T/60)^2\sum_{k=2}^\infty e^{-\lambda T/60}\frac{(\lambda T/60)^{k-2}}{(k-2)!}\\&=
(\lambda T/60)^2\sum_{k=0}^\infty e^{-\lambda T/60}\frac{(\lambda T/60)^k}{k!}.
\end{align}
We simply shift the index down by $2$ (taking out a factor of $(\lambda T/60)^2$ in the process).
Comment: For $(2)$, may I know what $X$ represents?
Comment: $X$ is just some arbitrary random variable with exponential distribution with parameter $\lambda$.

Question about a point process


What is a best way of binning non-finite continuous variable?

Question: I am having around 40000 records of non-finite continuous weight data(starting from 0.15kg to 5300 kg) .The data is right sided skewed .
I tried binning the data with fixed width .Binned data is used as input for binary classifier.
Please tell me the best way approach the binning.
Binning method i tried.
Comment: [Don't bin your continuous data at all.](https://stats.stackexchange.com/q/68834/1352) Feed them into your algorithm as-is; potentially transform them using (e.g.) restricted cubic splines (see, e.g., Frank Harrell's *Regression Modeling Strategies*) to capture any nonlinearity.
Comment: Orthogonal to the question, but still likely to be practical. (a) Look at these data on logarithmic scale. Here max/min gives >4 orders of magnitude. (b) If you must have a histogram, make sure the bars touch (because the bins do). (c) You can have more bins than this with your sample size.
Answer: You should not bin continuous features in a regression model, it only reduces the model's ability to fit the data.
I discuss this extensively here, where I compare binning with other methods of capturing non-linearity in regression modeling.  The high level is

Binning, which conceptually simple, was seen to suffer from a few issues in comparison to the other methods
With a small number of estimated parameters, the binned regression suffered from a higher bias than its competitors. It was seen across multiple experiments to achieve its minimal hold out error at a larger number of estimated parameters than the other methods, and furthermore, often the minimal error achieved by the binning method was larger than the minimum achieved by the other methods.
The binned regression's hold out error often had a higher variance than the other method's. This means that, even if it performed just as well as another method on average, any individual binned regression is less trustworthy than if using another method.
Additionally, the binned regression method has the disadvantage of producing discontinuous functions, while we expect most processes we encounter in nature or business to vary continuously in their inputs. This is philosophically unappealing, and also accounts for some of the bias seen when comparing the binning regressions to the other basis expansions.

Just don't do it.
Comment: I was using regression in the sense of "logistic regression", so a parametric predictive model for the conditional probability of the target.
Comment: The question is not about regression. It says "data is used as input for binary classifier."


When writing music, is there an optimal speed for vocal parts?

Question: I am used to writing piano music and want to write some vocal stuff now. However, I have noticed that I write melodies which are too fast to be sung.
Can someone tell me roughly what a "slow" vocal melody would be and a "fast" one?
What is an optimal speed range for singing that you would find in a typical, everyday pop song by people like Nicki Minaj, Ke$ha, etc? A crude estimate is fine.
My usual speed for piano pieces is with quarter notes around 160 BPM.
Comment: I am the very model of a modern Major General.
Comment: Ever listen to Eminem? Maybe you just need a faster vocalist.
Comment: It's been a lot more than *One Week* since I thought about how amazingly fast the lyrics are in this song: https://www.youtube.com/watch?v=fC_q9KPczAg
Answer: In my opinion there is no optimal speed. It all depends on different aspects.
There could be a optimal speed for a vocalist, depending on his capabilities.
Also it depends greatly on the style of the song and the singing style. I wanted to give an example of two styles which need really different "optimal" BPMs, but in fact I realised that in every genre you have different speeds varying greatly.
I think the most important thing is that you try to find a balance, so that the song sounds nice on the instruments and isn't to difficult to sing and that everything matches the style of the song.
EDIT: I wanted to add that in some songs even the BPM of the instrumentals doesn't "match" singing speed.
For example: In irish folk there are sometimes songs which aren't played that fast, maybe 120 to 140 BPM, but the singing is extremely fast. Go to youtube and listen to Fiddlers Green - Lannigans Ball or Little Beggarman.
An other version of that is metal, sometimes you have very fast songs, played at 180 BPM or faster but the singing doesn't have to be that fast and can be stretched.
So, it's all a question of the style of the song and the capabilities of the vocalist.
Answer: I have found that the optimal speed (called tempo) range that sounds great lyrically is around 80 - 130 BPM. 160 BPM would mostly be considered to be a running workout song (the conclusion is confirmed by search results when searching "160 BPM songs"). Other than that, if you had a different preference in mind, then keep that tempo! It's up to you really. There aren't any rules here.


R xpathSApply --> extracting Attribute gives empty result

Question: I try to parse out the xmlValue for the attribute "NAME" in an XML Document in R.
<NN ID_NAME="107232" ID_NTYP="6" NAME="dSpace_ECat1Error.STS" KOMMENTAR="dSpace_ECat1Error.STS" IS_SYSTEM="0" IS_LOCKED="0" DTYP="Ganzzahl" ADIM="" AFMT=""/><NN ID_NAME="107233" ID_NTYP="6" NAME="dSpace_ECat2Error.STS" KOMMENTAR="dSpace_ECat2Error.STS" IS_SYSTEM="0" IS_LOCKED="0" DTYP="Ganzzahl" ADIM="" AFMT=""/>

The result should be like this:
dSpace_ECat1Error.STS
dSpace_ECat2Error.STS

I use this function:
xpathSApply(root,"//NN[@NAME]",xmlValue)

But as a result, I get just empty "" (Quotes)
What have I done wrong?
Thank's in advance!
Comment: Maybe `unlist(doc["//NN/@NAME"], use.names = F)` or `xpathApply(doc, "//NN", function(x) xmlAttrs(x)["NAME"])`? In your example, you try to select NNs with a specific NAME attribute, not the value of the NAME attribute itself.
Answer: I just found out by using:
erg<-xpathSApply(root,"//NN",xmlGetAttr,'NAME')

There should be a better tutorial for this particular XML-function in R....


CoreAnimation & Cocos2D - Which one should I go with?

Question: So I am about to start a project for an application (Not a game application) that requires a lot of animation. For example a lot of pie and bar charts that animate on the screen.
If I use cocos2d am I still able to use UI elements such as UITableView, UIButton, UISegmentedControl, etc? Can you combine Cocos2d with normal iOS UI Elements on the same view?
Which one is better for creating simple animations?
What are the advantages and disadvantages of using each for a non-game project?
Answer: There is the ability to combine Cocos2d and UIKit, but I don't know to what extent you can take it. Check out this tutorial on combining them: http://www.raywenderlich.com/4817/how-to-integrate-cocos2d-and-uikit
I'm fairly new to iOS programming and did the same research you are currently doing for my project which is very animation heavy, but not a game. I found much more information, forums and tutorials on doing animations with Cocos2d than I did for Core Animation. Not to say it's not out there, or that 1 is necessarily better than the other for what you're trying to accomplish, just my 2 cents and several weeks of Googling.
Answer: Check out Core Plot maybe you can use that to build your app.
Comment: Here user is asking about Cocos2d and Core Animation integration not for CorePlot example.


How to retrieve the installation ID and confirmation ID for Windows 7?

Question: I am a systems administrator and we are getting ready to deploy Windows 7 to our users.  In our process of learning about activation, we activated a Windows 7 computer with our MAK key using Internet activation instead of doing proxy activation through VAMT 2.0.  The computer is activated, but if we need to reinstall that computer (as it is a technician computer), we'll have to re-activate it and use another one of our allotted activations.
What I'm wondering is if there is a way to gather the installation ID and confirmation ID off of that Windows 7 laptop so I can paste it into or VAMT 2.0 XML (.cil) file?  That will give us the ability to just re-apply the confirmation ID should we need to reinstall that computer.  I don't need to know how to paste the installation ID and confirmation ID into the .cil file as I already know how to do that.  I'm more looking for a way to extract the installation ID and confirmation ID from the Windows 7 computer.
Answer: You can retrieve the Installation ID and Activation ID by entering the following at a command prompt:
<code>slmgr.vbs /dlv
</code>
However, I am not aware of any means to recover the confirmation that was sent by the activation server or KMS.
Comment: Well, that's a bummer.  Thanks for the answer anyway.  I'll mark your post as answering my question.  If someone else posts a way to actually retrieve the confirmation ID as well, then I'll mark their post as the answer instead.
Comment: Have you considered setting up a KMS?  If you have at least 25 computers running any combination of Vista/7/Server2008/Server2008R2, it is definitely the easiest way to go.  All you need is a Win7 KMS key or a Server 2008 R2 KMS key.
Comment: I think the confirmation ID is ephemeral.
Comment: How can you get this outputted on the command line instead of in a GUI?
Answer: This may be late, but by running "slui 4" from the CLI you can re-do the online MAK activation sequence and it will produce the same activation confirmation number as it did the first time.
You can use this number, in combination with the license key, to re-activate (reinstall) windows on that same machine in the future.
Answer: start then run and then type slui 4
Comment: This needs a lot more information to be actual helpful.


Ocultar teclado com Fragment

Question: Estou fazendo uma aplicação mobile que tem telas em fragment com Drawer, e nelas tem EditText, mas estou com um problema que ao clicar no EditText e depois clicar fora, ou clicar no menu o teclado não some, e atrapalha a visualizar tanto o resto do formulário como o menu Drawer.
E se eu voltar pra Home onde não tem EditText ele continua na tela o teclado. Como fazer pra fechar?
Comment: Tive esse problema também, utilizei esta [dica][1]

  [1]: http://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard
Answer: Tente criar um listener para ser executado quando o focus do editText for removido. Algo mais ou menos assim:
EditText editText = (EditText) findViewById(R.id.textbox);
EditText editText2 = (EditText) findViewById(R.id.textbox2);
EditText editText3 = (EditText) findViewById(R.id.textbox3);

OnFocusChangeListener ofcListener = new MyFocusChangeListener();
editText.setOnFocusChangeListener(ofcListener);
editText2.setOnFocusChangeListener(ofcListener);
editText3.setOnFocusChangeListener(ofcListener);
private class MyFocusChangeListener implements OnFocusChangeListener {

    public void onFocusChange(View v, boolean hasFocus){

        if(!v.hasFocus) {

            InputMethodManager imm =  (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

        }
    }
}

Fonte: https://stackoverflow.com/questions/15412943/hide-soft-keyboard-on-losing-focus
Comment: Fiz umas alterações para várias Views, no caso vc seta o listener para todos os seus EditText, no exemplo setei para 3, mas você pode fazer isso dinamicamente caso vc tenha um número X de views.
Comment: Acontece que tenho mais de um EditText, então não to conseguindo acertar como ficaria.
Answer: No onCreateView coloca o código a seguir para esconder o teclado.
getActivity().getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Ou seja:
    @Override
     public View onCreateView(final LayoutInflater inflater,
                        final ViewGroup container, Bundle savedInstanceState)
          {

            view = inflater.inflate(R.layout.fragment_mensal, container,false);

//esconder teclado
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

                    return view;
          }

Ocultar teclado com Fragment


Duplicate name "app" passed to addEntry(): entries must be unique

Question: Hello I try to install sylius BootstrapTheme for my project and I have little problem when i try to install this. If need more code or code of other files for find the problem talk me
/themes/BootstrapTheme/webpack.config.js
const Encore = require('@symfony/webpack-encore');

Encore
  .setOutputPath('public/bootstrap-theme')
  .setPublicPath('/bootstrap-theme')
  .addEntry('app', './themes/BootstrapTheme/assets/app.js')
  .disableSingleRuntimeChunk()
  .cleanupOutputBeforeBuild()
  .enableSassLoader()
  .enableSourceMaps(!Encore.isProduction())
  .enableVersioning(Encore.isProduction());

const config = Encore.getWebpackConfig();
config.name = 'bootstrapTheme';

module.exports = config;

webpack.config.js
const Encore = require('@symfony/webpack-encore');
const bootstrapTheme = require('./themes/BootstrapTheme/webpack.config');
module.exports = [bootstrapTheme];
// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')
    // only needed for CDN's or sub-directory deploy
    //.setManifestKeyPrefix('build/')

    /*
     * ENTRY CONFIG
     *
     * Add 1 entry for each "page" of your app
     * (including one that's included on every page - e.g. "app")
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if your JavaScript imports CSS.
     */
    .addEntry('app', './assets/js/app.js')
    //.addEntry('page1', './assets/js/page1.js')
    //.addEntry('page2', './assets/js/page2.js')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning(Encore.isProduction())

    // enables @babel/preset-env polyfills
    .configureBabel(() => {}, {
        useBuiltIns: 'usage',
        corejs: 3
    })

    // enables Sass/SCSS support
    //.enableSassLoader()

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes(Encore.isProduction())

    // uncomment if you're having problems with a jQuery plugin
    //.autoProvidejQuery()

    // uncomment if you use API Platform Admin (composer req api-admin)
    //.enableReactPreset()
    //.addEntry('admin', './assets/js/admin.js')
;

module.exports = Encore.getWebpackConfig();

but when I when I run yarn encore production I have this error :
Duplicate name "app" passed to addEntry(): entries must be unique.
what I can do for leave this?
Answer: The error message is clear Duplicate name "app" passed to addEntry(): entries must be unique..
In your /themes/BootstrapTheme/webpack.config.js you have:
.addEntry('app', './themes/BootstrapTheme/assets/app.js')

And, in your webpack.config.js:
.addEntry('app', './assets/js/app.js')

I'm far from being an expert in Webpack but I believe you could delete the second one, as now you are using BootstrapTheme's one. If you need both the scripts, you could change the name of the entry in your webpack.config.js to something else, like:
.addEntry('someName', './assets/js/app.js')

Then you add your new tag to the twig file:
{% block javascripts %}
    {{ encore_entry_script_tags('app') }}
    {{ encore_entry_script_tags('someName') }}
//the rest of your js code, if you have
{% endblock %}

Comment: Try to just remove the line `.addEntry('app', './assets/js/app.js')` from your `webpack.config.js`, keeping the one that came with BoostrapTheme. If nothing breaks, the job is done.
Comment: I edited my answer with an example of what you can try next


XSL Transformation: Count Elements

Question: I need to detect the first title element and print out a special comment before this first title element.
<xsl:template match="title[string-length(.) > 0]" mode="content">
    <xsl:comment>%title id="<xsl:value-of select="."/>"%</xsl:comment>
</xsl:template>

I can detect these title elements, but what i've got to do to count and get this special comment before the first title element?
EDIT:
Thanks for the comments, but i can't get it to work unfortunatly. So additionally i add the XML source here, maybe someone could point me to en elegant solution?
<text id="EL_textN10001"><page id="EL_pageN10004">

lorem ipsum dolor sit

msdfsdkfh sdfsfksd sfsdfsdfsdfdsfh LOREM IPSUM. lorem aklsjd asda sdasjdlkjaksld

<title id="EL_titleN10001">my first title here</title>
<subheading id="EL_subheadingN1006E" level="1">MY FIRST SUBHEADING</subheading>
sdfjlksjfsjdf sfsjfljsdf sfklöskdfö sdfölksföksölf sdfksfk

tzputozu lultpülupützu tultlutzulztu wewe rrtrt.
<title id="EL_titleN10001">my second title</title><subheading id="EL_subheadingN100D9" level="1">THIS IS MY SECONT SUBHEADING</subheading>
this is another senseless paragraph test.
</page></text>

Comment: Are all `title` elements siblings of the same parent? Then `match="title[normalize-space()][1]"` suffices. Or you could check there is no `preceding::title`.
Comment: Yes, the elements are alle siblings of the same parent.
Thanks for the hint. I tried it this way:

XXX FIRST %title id=""%

%title id=""%

Doesn't work and i don't know why
Comment: What are you counting?
Comment: I try to count the title element with pos() but the first occurance says pos = 7, the socond pos=15..there must be another way
Answer: Try
<xsl:template match="title[string-length(.) > 0][1]" mode="content">
<xsl:comment>XXX FIRST %title id="<xsl:value-of select="."/>"%</xsl:comment>
</xsl:template>
then write a second template match="title[string-length(.) > 0][position() > 1]" with the other content.
Answer: finally the solution was using:
<xsl:variable name="subHeadingPos" select="count(./preceding-sibling::subheading)+1"/>

Thanks to you, guys

XSL Transformation: Count Elements


How to have "onmouseover" highlight in css?

Question:     protected void MasterCust_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowState == DataControlRowState.Alternate)
        {
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#eefef0';");
        }
    }

how would I get this into css instead?
grid.highlight
{
background-color:Blue;
}

Something like this?
Answer: You can use the hover selector.
grid.highlight:hover
{
    background-color:Blue;
}

IE 6, 7 and 8 sometimes have problems with the hover selector so, for those, you can use Whatever:hover.
Comment: IE6 only allows the :hover pseudo selector to be used in anchors (), other than that you are good to go.
Comment: AFAIK, `Whatever:hover` should fix that issue and have it work with any element on IE6. I don't think OP should consider major alternatives (e.g. Javascript) to compensate for IE6 users.
Answer: I think this is what you're looking for:
grid.highlight:hover
{
    background-color: #eefef0;
}

Just the add the pseudo-class :hover for a mouse-over
Answer: Assuming grid.highlight select your element:
grid.highlight:hover
{
    background-color: blue;
}

Otherwise, you'll have to modify that selector.


Android Tcp Client check connection to the Server

Question: Hi i have a Tcp client and i want to check if he is connected to the server and i dont mean to check if he was connected with socket.isConnected() or socket.isBound() i mean that i want to know if the socket is connected right now and i couldnt find a way to do it because when the server disconnect he dosnt send anything to the client
here is my code:
    public void sendMessage(String message) {
    if (out != null && !out.checkError()) {
        out.println(message);
        out.flush();
    }
}

public void stopClient() {
    mRun = false;
}

public void run() {

    mRun = true;
    try {
        //connecting
        InetAddress serverAddr = InetAddress.getByName(SERVERIP);
        Socket socket = new Socket(serverAddr, SERVERPORT);
        sss = socket;

        try {
            //send the message to the server
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            //receive the message that the server sends back
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            HelloService.firstTouch();

            //in this while the client listens for the messages sent by the server
            while (mRun) {
                serverMessage = in.readLine();

                if (serverMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class to inform main activity that a message has received
                    mMessageListener.messageReceived(serverMessage);
                }
                serverMessage = null;
            }

        } catch (Exception e) {

        } finally {

            socket.close();
        }

    } catch (Exception e) {

    }
}

Comment: If @EJP's answer doesn't work for you (hmmm though), try pinging the server or use `isReachable()`.
Comment: tried it but it kept returning false anything else? its very important please someone ?
Comment: Isn't `isReachable()` returning `false` meaning server disconnected?
Comment: yea but it always returns false even when the server is not disconnected
Answer: When the server disconnects, readLine() returns null, which you need to check for, and break out of the read loop and close the connection if you get it. Your present checking is only sufficient to avoid an NPE.
Comment: the thing is that it dos'nt return anything i have already tried it


Adding songs to Spotify queue Android won't play next song automatically

Question: I am using the spotify sdk in order to search and play songs. I have my own way of searching for songs since the sdk is not finished. The sdk does provide a player object which allows you to pass a song uri to it in order to play a song. There is also a method of the player object called queue(). It is supposed to let you add songs to it and when the song finishes it plays the next one. I can add the song to the queue, as seen below:
mPlayer.queue(new OperationCallback() {
    @Override
    public void onSuccess() {
        Toast.makeText(SoundspaceActivity.this, "Added to queue!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(Error error) {

    }
}, songUris.get(i));

I get the success toast message, but when the song ends nothing happens. Is there something I should do in order for the next song to be played automatically?
Here is a link to the developer page: https://spotify.github.io/android-sdk/player/
Answer: You can use the onPlaybackEvent class like so:
  @Override
    public void onPlaybackEvent(PlayerEvent playerEvent) {
    Log.d("MainActivity", "Playback event received: " +
    playerEvent.name());
    switch (playerEvent) {
        // Handle event type as necessary
        default:
            break;
        case kSpPlaybackNotifyAudioDeliveryDone:

            mPlayer.skipToNext(null);

 }
}

Comment: Sorry for the late response, I'll try this out soon and let you know!


How can i change RealName / User account link destination?

Question: I'm using RealName module in D7 to show real names on nodes and in comments and would like to link the real name [user:first-name] [user:last-name] to a custom content type (a 'profile' page), instead of the standard 'user account'.
It is easy to use RealName in D6, but I've been searching for ages for a solution in D7.
I have read "Have username link to profile rather than regular userpage by default", but I am not using Content Profile.
I wondered if I need to 'preprocess' the user name, but can only read php and have no idea what to change there.
I have set the URLs for account pages to be [user:first-name]-[user:last-name]-account using URL alias patterns and the URLs of the custom content type I am trying to link to look like [user:first-name]-[user:last-name].
What is the simplest way to change the 'View user profile' link, which appears in comments and in node 'Authored by' to point at my custom user profiles instead of the standard 'user account's pages?
Answer: Did you try hook_username_alter()?

Alter the username that is displayed for a user.
Called by format_username() to allow modules to alter the username
that's displayed. Can be used to ensure user privacy in situations
where $account->name is too revealing.

I've used this occassionally, but I find sometimes there are instances where I felt it should have been called/used already and then wasn't (the Webform module submission report tables come to mind ...)
Comment: Thanks tenken, this looks like it might be an idea but, as mentioned, I can read some php ok but don't really know how to write it... any chance you can walk me through how and where to use hook_username_alter? Thanks!
Comment: I'm still wondering if there should be a simple way to do this using the a URL on my profile pages, or similar..?
https://drupal.org/documentation/modules/realname says:
"Link to homepage": This setting will appear only if there are URL fields in the profile, or, for Content Profile, "link" fields. If one of those fields is a link to the user's home page and you want it to be used instead of linking to the user's profile, choose that field here.
anyone know how I can do something similar with RealName in D7?


Multiple subs and using the ScreenUpdating property

Question: My project has 50 subroutines and a main subroutine that calls all of them.
I'm trying to keep my code as quick, clean and effective as possible, so should I add the Application.ScreenUpdating = False/True snippet to the beginning and end of each individual sub, or would it have the same effect if I just add it to the main sub?
Sub CallAllMacros()

Application.ScreenUpdating = False
Call macro1
Call macro2
...
Call macro50
Application.ScreenUpdating = True

End sub

Comment: Just the main sub
Comment: Yes, in that case just don't put it into the subroutines.
Comment: Do you call the single routines also stand alone or only as part of `CallAllMacros`?
Comment: @FunThomas only as part of `CallAllMacros`! I assume in that case it's enough to add it to that sub?
Comment: If you do ever need it in the called subs, don't just reset `screenupdating` to true at the end of each one. Check the value when the sub is called and only reset it if that was true. Otherwise your main sub will end up turning updating on and off 50 times.
Answer: Just add it into main sub. So, only 2 lines are required.

At the very beginning: Application.ScreenUpdating = False
At the end : Application.ScreenUpdating = True


Load all/multiple fields from entity of certain type

Question: I'm quite new to Drupal so bear with me here.
I've created an entity using Drupal Console, specifically using drupal generate:entity:content. Which works perfectly. Kudos to the Drupal console guys.
This specific entity will deal with adding some meta tags on specific URLs thru the site.
It has several fields that need to be completed: url, keywords(if any), one open graph tag, and a tag value.
After looking through this question I've decided that using hook_page_attachments is the way to go for me.
The logic for adding the tags is quite simple:

Get the entity.

$entity = \Drupal::entityTypeManager()->getStorage('meta_tag_entity')

Grab the current url.
Loop through the entity url fields and check if any matches the current url.
If it does, simply add the tags.

And that's it.

The problem boils down this.
After I've loaded the entity ($entity = \Drupal::entityTypeManager()->getStorage('meta_tag_entity')) I have no idea how to grab all the url fields.
I've looked over this question but it's not quite what I'm looking for.
Answer: You should be able to use either get or getFields on your entity object if it is derived from ContentEntityBase.
See: https://drupal.stackexchange.com/a/232219/57
So, after you load the entity:
$fields = $my_entity->getFields();

Or:
$foo = $my_entity->get('bar')->value;

Answer: getStorage() does not load the entity.
It loads the storage handler that is able to load entities.
Usually you don't have one entity, you have many, one for each URL.
So you don't want to loop over fields in PHP, you want to do a query against the DB to find if you have an entity that matches the current url.
Look for entity query, there are various related questions on this site as well as documentation/tutorials elsewhere. For example: https://www.sitepoint.com/drupal-8-version-entityfieldquery/. Try that and if you still have a problem, I'd recommend you ask a more specific question with code you came up with.
Also, did you consider using the metatags module, which does something very similar, although based on a field on other entities and not a standalone entity: http://drupal.org/project/metatag


p2q_EmbedFlash using remotely hosted Flash files

Question: I've embedded a virtual tour on one of my client sites.
The site is hosted by Slicehost, and as you can see the load times for the Flash movies are very slow, so my idea was to serve the swf files from Amazon S3 Europe.
To test it, I have all swfs uploaded to the same directory / bucket on Amazon, while the index.html and p2q_embed_object.js files reside on my local machine. The js file is changed to refer to the Amazon-hosted swfs. The first swf loads fine, but the others don't. What am I doing wrong? Is there a better way to do this that would allow me to serve my Flash assets from elsewhere?
Answer: The solution is to use an iframe that calls a separate html file e.g. video.html. This resides in the Amazon bucket and calls the js and all swfs from the same bucket.


I would like to get the area from latitude and longitude, and then put buildings etc etc

Question: This is my main code
 `graph=ox.graph_from_point((60.199695, 24.948005), distance=500, network_type='drive_service')
area=ox.gdf_from_place(graph)
buildings = ox.footprints_from_place(graph)
nodes, edges = ox.graph_to_gdfs(graph)
fig, ax = ox.plot_graph(graph, show=False, close=False)
area.plot(ax=ax, facecolor='black')
edges.plot(ax=ax, linewidth=1, edgecolor='#BC8F8F')
buildings.plot(ax=ax, facecolor='khaki', alpha=0.7)
ax.scatter(floatlongitudes, floatlatitudes, c=concentration ,s=10)
plt.show()`
And I always get the same error in the area AssertionError: query must be a dict or a string I can't define a name for a place, is that why I chose create my area from latitude and longitude
Answer: I believe gdf_from_place requires specifically a place name (e.g. 'Sydney') as an argument and not a graph that has been obtained. Hence it throws up the error. I do not see another option in the documentation to obtain a gdf of the study area queried using
graph=ox.graph_from_point((60.199695, 24.948005), distance=500, network_type='drive_service')

There is an alternative for buildings though. Instead of buildings = ox.footprints_from_place(graph), you should use buildings = ox.footprints_from_point((60.199695, 24.948005), distance=500,) to get the result.


Measure multiplicative but not dirac

Question: Let's call a measure $\mu$ on a measurable space $(X, \mathcal{A})$ multiplicative if
$$\mu(A \cap B) = \mu(A) \mu(B) \tag{$*$}$$
for all $A,B \in \mathcal{A}$. Any dirac measure $\delta_x$ for some $x \in X$ is multiplicative. Do there exist nonzero multiplicative measures that are not dirac measures?
If so, then can we make additional assumptions on the measurable space and the measure such that nonzero multiplicative implies dirac? The implication is true if $X$ is a compact Hausdorff space and $\mu$ is a regular Borel measure on $X$, but does it hold in more general circumstances?
EDIT: As Jonas pointed out, $(*)$ becomes meaningless if $\mu(A) = 0$ and $\mu(B) = \infty$, so we should not require $(*)$ to hold for pairs of measurable sets where one has measure zero and the other has measure infinity.
EDIT: Under no extra assumptions, $\mathcal{A} = \{\emptyset, X\}$ with $\mu(X) = \infty$ is a counter-example, though a rather uninteresting one. If we assume that at least one measurable set $A$ has finite positive measure then if $\mu(B)=\infty$ we get $\infty > \mu(A) \geq \mu(A \cap B) = \mu(A)\mu(B) = \infty$, a contradiction, so no sets can have infinite measure in this case. Let's therefore assume that the measure space is finite, i.e. all measurable sets have finite measure.
Comment: $\mu(A\cap A) = \left(\mu(A)\right)^2$, which means $\mu(A)$ is either $0$ or $1$ for any measurable set $A$.
Comment: Humm... $\mu(A)=\mu(A)^2$ also allows that $\mu(A)=\infty$.
Comment: Yes, that is a very important consequence of being multiplicative. It also implies $\mu(X) = 1$, because otherwise $\mu$ would be zero.
Comment: Oh, you're right! Thanks
Answer: Let $X$ be a topological space and let $\mu$ be a nonzero Borel measure on $X$ that is outer regular on Borel sets and multiplicative.
As discussed in the opening post, if some Borel set has measure $\infty$ then all Borel sets have either measure sero or $\infty$. To prevent this situation, we assume that $\mu$ is finite.
As already commented, finiteness and multiplicativity implies $\mu(A) = \mu(A \cap A) = \mu(A)^2$ implies $\mu(A) = 0$ or $\mu(A) = 1$ for every measurable set $A$. Since $\mu \neq 0$ we must have $\mu(X) = 1$.
Now assume that there exists a compact set $K \subseteq X$ with positive measure, i.e. $\mu(K) = 1$. This would for instance happen if $X$ was locally compact or if $\mu$ was inner regular.
Now for the proof. Suppose that $\mu$ is not a dirac measure. Then, for any $x \in K$, there exists a measurable set $A_x$ with $x \in A_x$ and $\mu(A_x) = 0$. By outer regularity, for each $x \in X$ there exists an open set $U_x \supseteq A_x$ with $\mu(U_x \setminus A_x) < 1$, i.e. $\mu(U_x) = 0$. Now we have an open covering
$$K = \bigcup_{x\in K} U_x$$
of $K$, which then admits a finite subcovering
$$K = U_1 \cup \cdots \cup U_n$$
But this is impossible, as all the $U_i$'s have measure zero while $X$ has measure one. Hence, $\mu$ must be a Dirac measure.
Answer: I'll assume that the measure has the property that any point has a neighborhood with finite measure. Otherwise one would have the awkward condition
$$
0=\mu(A\cap\emptyset)=\mu(A)\mu(\emptyset)=\infty\times 0
$$
taking $A$ nonempty.
Now let me reply to your question in the particular case when there is an atom $x$ and a decreasing sequence of sets $B_n$ with intersection $x$. Then replacing $B$ by $B_n$ and letting $n\to\infty$ we obtain
$$
\mu(A\cap\{x\})=\mu(A)\mu(\{x\}).
$$
For $A$ containing $x$ we get $\mu(A)=1$, and otherwise $\mu(A)=0$. So $\mu=\delta_x$ (in this particular case).
Comment: If $x \in A$ then $\mu(A) = \mu(A \cap \{ x\}) = \mu(A) \mu(\{x\})$, but why does this imply $\mu(A) = 1$? Are you assuming that $\mu(\{x\}) = 1$?
Comment: @Svinepels Just rephrased my answer, not what you want but the best I can do for now.
Comment: If there exists a measurable singleton $\{x\}$ with $\mu(\{x\}) = 1$, then it follows that $\mu = \delta_x$ (at least if the measure space is finite) so in this case, the argument with the sequence  $B_n$ is not necessary.

Measure multiplicative but not dirac


HTML email font size in gMail

Question: In gMail, the font-size that I set for s work except for this one: (edit: I spotted the typo, changed it but still doesn't work on gmail :( )

           $33

Any idea why this doesn't work? Strangely enough, it works for this:

        We never win because you only believe in science!

On CSS,this rule was added:
div,p,a,li,td {
-webkit-text-size-adjust: none;
-moz-text-size-adjust: none;
-ms-text-size-adjust: none;
text-size-adjust: none;}

Any help will be appreciated!
Comment: deleting the `!important`  seems to solve the problem.
Answer: It appears you have font-family: twice!
Hope that helps!
Comment: I changed it, but still does not appear to fix the problem on gmail.
Comment: Ok, I can't think of anything, I will remove my post.

HTML email font size in gMail


Como faço para arrumar essa tag em JavaScript?

Question: Estou finalizando um código em JavaScript de um Balanço Familiar de custos,
No entanto, quando vou tentar passar a variável para imprimir na tela (que seria a ${totalBalanço} e a $total.Tofixed(2)}R$, aparentemente não esta funcionando.
Tentei alterar as aspas, tentei alterar colocando apostrofe, mas nada altera a cor desse atributo no meu VSCode.

O que devo fazer para conseguir imprimir os resultados na tela?
Answer: Você está tentando utilizar o template literals que é esse símbolo -> ${}
No seu caso, você está utilizando aspas dupla. Assim:
"String com aspas duplas"
Mas só é possível utilizar o template literals em strings atribuídas com a crase. Ex:
 `Aqui é uma string com crase`
`Outra string com crase e com um template literal -> ${algumaVariavel}`
Comment: Agradeço a resposta, coloquei Crase e funcionou!
Answer: Já tentou utilizar literais de modelo(Template String)? talvez seja a solução que você procura.
Template String

let a = 5; b = 10;
console.log(`Sum of ${a} and ${b} is ${a + b}`);