What is the meaning of the error: [method] cannot be applied to [arguments]?

Question: public class Numbers2
{
    public static void main(String[] args)
    {
        int number;
        int numberTwo;
        int jordan;
        number = 5;
        numberTwo = 10;
        sum(number, numberTwo);
        difference (number, numberTwo);
        product (number, numberTwo);
        System.out.println(jordan);
    }
    public static void sum(int number, int numberTwo, int jordan)
    {
        System.out.print("The sum of the numbers is");
        System.out.println((number + numberTwo));
    }
    public static void difference(int number, int numberTwo, int jordan)
    {
        System.out.print(" The difference of the two numbers is");
            System.out.println((number - numberTwo));
    }
    public static void product(int number, int numberTwo, int jordan)
    {
        jordan = number * numberTwo;
        return jordan;
    }
}

Errors are:
H:\Numbers2.java:10: sum(int,int,int) in Numbers2 cannot be applied to (int,int)
        sum(number, numberTwo);
        ^
H:\Numbers2.java:11: difference(int,int,int) in Numbers2 cannot be applied to (int,int)
        difference (number, numberTwo);
        ^
H:\Numbers2.java:12: product(int,int,int) in Numbers2 cannot be applied to (int,int)
        product (number, numberTwo);
        ^
H:\Numbers2.java:28: cannot return a value from method whose result type is void
        return jordan;
               ^
4 errors

Comment: The number of parameters in your method call has to match the number of parameters in the method declaration. If you want a variable number of arguments, you'll have to use varargs: http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
Answer: Change your code like that...
public class Numbers2
{
public static void main(String[] args)
{
    int number;
    int numberTwo;
    int jordan;
    number = 5;
    numberTwo = 10;
    sum(number, numberTwo);
    difference (number, numberTwo);
    product (number, numberTwo);

}
public static int sum(int number, int numberTwo)
{
    System.out.print("The sum of the numbers is");
    System.out.println((number + numberTwo));
 return number + numberTwo;   // returns addition
}
public static intdifference(int number, int numberTwo)
{
    System.out.print(" The difference of the two numbers is");
        System.out.println((number - numberTwo));
 return number - numberTwo;  // returns the subtraction
}
public static int product(int number, int numberTwo)
{
    jordan = number * numberTwo;
    return jordan;   // returns the product
}
}

Answer: It appears that you are a bit confused about how to define and call methods in Java.
I see that your methods each have three parameters, but the third one is being set inside your method and returned.  When defining a method, you declare the type that the output will be before you define your parameters.  In your case, you are currently defining it as void.  This tells the compiler that your method does not return anything.  In your case, you want to tell it that your method returns an integer.  An example of this would be the following:
public static int product(...
In addition, when you make a call to a method, your call must match the signature of the method.  That means you must pass in the same number and type of parameters.  In your case, your methods are all declared as taking three ints as input, but you are only passing in two when you call them.
Lastly, I see that you are passing in a parameter called jordan, and attempting to modify its value.  By default, java passes objects "by value" (technically, it passes a reference to the object and the reference itself is "by value").  If you want to actually modify the value of a parameter, it must be passed inside a wrapper object.  In most cases though, you will want to create a new variable inside of your method and return that.  An example would be the following:
// note the "int" keyword before the method name
public static int product(int number, int numberTwo)
{
    int jordan = number * numberTwo; // create a new variable to hold our response
    return jordan;   // returns the product

    // You can also just return the result of an operation:
    //return number * numberTwo;
}


opposite of .add method in Flutter

Question: I need to subtract from my list. The list is a list of integers, to add to it I wrote the code below, but to subtract from the list I do not know how to do
<code>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class Data extends ChangeNotifier {

  int numberOfItems;

  Data({this.numberOfItems});

  List<Data> individualList = [];

  void addIndividual(int newNumber){
    final individualItem = Data(numberOfItems: newNumber);
    individualList.add(individualItem);
    notifyListeners();
  }

}
</code>
<code>                  Expanded(
                    flex: 2,
                    child: GestureDetector(
                        onTap: (){
                          Provider.of<Data>(context, listen: false).removeIndividual(numberOfItems);},
                        child: Icon(Icons.remove_circle_outline, color: Colors.grey[700], size: 20.0,)),),
                  Expanded(
                    flex: 0,
                    child: Text('${Provider.of<Data>(context).individualList.length + 1}',
                    ),
                  ),
</code>
Comment: Suggest u read this:https://bezkoder.com/dart-list/#Remove_items_from_List_in_DartFlutter
Answer: <code> void removeIndividual(numberOfItems){
   individualList.remove(individualList.firstWhere((item) => item.numberOfItems == numberofItems););
    notifyListeners();
  }
</code>
Edit: Please note, numberOfItems must be unique for every Data object that is created and added to the individualList. Otherwise on removing, you might end up removing some other instance of data object instead of what you desire.
Voila!
Comment: I figured that that's what I should do too, but for some reason when I call the method as                           Provider.of(context, listen: false).removeIndividual(numberOfItems); it doesn't work.
Comment: I added in numberOfItems as an int above my build method in my stateless widget by the way
Comment: add the code you wrote to try to remove item in the question so we can see what exactly is the problem.
Comment: I meant the function, your UI part is okay. The removeIndividual function that you are running. Is it the one I gave as an answer?
Comment: I made a change to the answer. Try and let me know!
Comment: Yeah that's the one I tried: void removeIndividual(item){
    individualList.remove(item);
    notifyListeners();
  }
Comment: Your most recent edit worked! Thank you so so much, I was really struggling there!
Comment: Glad to help! I'm adding more information in the answer caus it's not foolproof. Must read it.

opposite of .add method in Flutter


Recommend way to Artisan on Docker

Question: I am yet to find an elegant and efficient way to run Laravel Artisan commands in my Docker based local dev environment.
Could anybody suggest the recommended or "proper" way to do things like migrations?
Or, has anybody found a neat way of doing this? Ideally with examples or suggestions.
Things that I've considered:

A new container (sharing the same volume and db link) with ssh, just for running commands (seems nasty).
Hacks in supervisor that could then end up running on live (not ideal).
Editing db configs, or trying to hack in a "host" environment, so that at least things like migrate can be run from the host.
Creating web front ends to run things (really nasty).
Trying to build a "signal" for it things.

I'm still getting my head around Docker and it's new-container-for-everything approach.
I suppose I want to balance cool-dev-ops stuff with why-do-I-need-another-fake-server-just-get-it-working-already.
I'd love to commit to it for my dev workflow, but it seems to become awkward to use under certain circumstances, like this one...
Any suggestions and ideas are welcome. Thanks all.
Comment: I've created a post about using a few different tools such as NPM, Bower, Grunt as well as Artisan and Composer, without SSH, the proper way [here](https://medium.com/@tomsowerby/proper-provisioning-with-docker-c412211b97bb).

I'd also recommend dylans blog for serving your app under a proper setup of a separate data volume and separate php container.
Answer: Docker 1.3 bring new command exec
So now you can "enter" running container like
docker exec -it my-container-name /bin/bash

After that you can run any command you want
php artisan --version

Comment: ? if the running container is not in TTY mode
Answer: The best practice regarding Docker is to run each process inside it's own container. Therefore, the ideal way to run artisan commands is to have an image for creating containers specifically for this purpose.
I've created an image which can be pulled from the Docker Hub dylanlindgren/docker-laravel-artisan and it works really well. It's on GitHub as well if you want to take a look at the Dockerfile behind it.
I've also just written a blog post describing the way that all these seperate containers fit together.
Comment: The link post is not available. Please correct the link
Comment: @TaraPrasadGurung I know it's more than 2 years later but the link is available on the Wayback Machine https://web.archive.org/web/20161121074037/http://www.dylanlindgren.com/docker-for-the-laravel-framework/
Comment: Yes! I came to the same conclusion. I found database connections a bit of a pain, especially with so many connection types being possible it's tricky to have a one-size-fits-all Dockerfile/container. Good blog post though, I'd recommend it to anyone that stumbles across this page.
Answer: There are a couple of possibilities...

Mounting a host directory in your container as the folder in which your Laravel app lives. That way you can just run php artisan migrate or composer update from the host. You might have problems with deployment, though, since you would have to replicate that part of your environment on the server.
adding an SSH server to your container (which is not recommended; here's a good discussion of that).
build and use nsenter, a tool for "entering" a running container and getting shell access. Note, I haven't used it, I just found it a while ago via a reference in the link above.

If you're primarily interested in deployment and you're doing it via a dockerfile, then the answer would be to add composer install and php artisan migrate to your dockerfile so they run when the container is built.
I'm interested in hearing more answers to this. It's something that I'm just getting into as well and would like to learn more about.
Comment: hi, i know this is an old post. but, how are you running migrate in a dockerfile. this means the db is connected during the build?
Answer: I use SSH and run migrations from a terminal inside the container.
I personally like Phusion's approach of using Docker as a 'lightweight virtual machine'. So I used their baseimage-docker which I've extended to create my own Docker image for Laravel applications.
I'm aware Phusion's image can be contentious in the Docker community, and that SSH is frowned upon by some who advocate Docker containers as microservices. But I'm happy with Phusion's approach until there are more established tools and practices for the multi-container approach.
Answer: I'm in the process of figuring out creating Docker images for Laravel projects, this is what I have so far.
FROM base_image_with_LAMP_stack_and_dependencies

WORKDIR /var/www/html/app

COPY composer.json composer.json

RUN composer install --no-scripts --no-dev --no-autoloader

COPY . .

RUN echo 'chown -R www-data:www-data /var/www/ \
&& composer dump-autoload \
&& cp .env.example .env \
&& php artisan key:generate \
&& php artisan migrate \
&& apachectl -D FOREGROUND' >> /root/container_init.sh && \
 chmod 755 /root/container_init.sh

EXPOSE 80

CMD /root/container_init.sh

This way, there is no dependency on database during build time, and the migration process can run every time a new container is started.
Comment: what is container_init.sh?
Comment: If you follow the Dockerfile steps above, all the comments starting from `chown -R www-data...` upto `... apachectl -D FOREGROUND` are being written to a file called `container_init.sh`, and then running it as the container's `CMD`

Recommend way to Artisan on Docker


Should scripts/*.sh files be executable?

Question: Drupal 7's recommended file permissions don't allow it's /scripts/*.sh files to execute. Should any server user have the ability to run those?
Answer: No. You don't need to execute permissions on those scripts in a production server environment.
The only reason you'd need those scripts executable on a server is for running code testing utilities (e.g. simpletest test cases, generating dummy content, etc.) on the codebase. Unless you're wanting to run some of those testing utilities on a CI server, they don't need to be executable for Drupal to work.


Duvida ao Ligar formulário no PHP para enviar por email

Question: Eu estou com um pequeno problema na hora de ligar o formulário de contato para ser enviado por email, ele não esta enviando por email e eu não consegui entender o motivo disso, segue abaixo o código em html com o nome contato.html

 <form action="sendemail.php" id="main-contact-form" name="contact-form" method="post"  >

                      <input type="text" name="Nome" class="form-control" placeholder="Nome" required="required">

Obrigatorio

                      <input type="email" name="Email" class="form-control" placeholder="Email" required="required">

Obrigatorio

                  <input type="text" name="Instituição" class="form-control" placeholder="Instituição" >

                  <textarea name="message" id="message" class="form-control" rows="4" placeholder="Escreve sua menssagem" required="required"></textarea>

                  <button type="submit" class="btn-submit">Enviar</button>

              </form>

Abaixo está o codigo php com o nome sendemail.php

<?php
$name       = @trim(stripslashes($_POST['Nome']));
$from       = @trim(stripslashes($_POST['Email']));
$subject    = @trim(stripslashes($_POST['Instituicao']));
$message    = @trim(stripslashes($_POST['message']));
$to     = 'firstname.lastname@example.com';//replace with your email

$headers   = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

mail($to, $subject, $message, $headers);

?>

Eu sou bem noob no php por hora, por isso estou com esse problema,
o site já está no servidor e eu não estou conseguindo achar o erro.
Comment: OI Gabriel, onde está hospedada a sua aplicação? Dependente de onde for, você deve usar alguns parâmetros adicionais na função mail.
Answer: Gabriel, corrija o nome do campo Instituição para Instituicao (sem acentos).
A função mail() do PHP não é mais recomendada para envio de emails uma vez que diversos motivos impedem o email de chegar ao destinatário, até mesmo um simples bloqueio do servidor onde o site está hospedado ou mesmo as verificações de SPAM do destinatário.
Envie utilizando servidor SMTP e uma classe apropriada para isto.
Recomendo o phpmailer, é famoso e muito simples de implementar veja um tutorial simples:
http://wiki.locaweb.com/pt-br/Enviar_e-mails_pelo_PHP_usando_o_PHPMailer
Comment: Outro link sobre o assunto: http://blog.patriciodossantos.net/2012/05/enviando-e-mail-com-o-phpmailer/
Comment: Não funcionou, eu segui corretamente o tutorial e não funciona do mesmo jeito. Além de que esse phpmailer serve para eu enviar email para diversas pessoas, eu gostaria apenas de enviar pra min a parte do formulario para eu saber a pessoa que entrou em contato.
Comment: @GabrielSilva, você checou as configurações SMTP?
Answer: Como citado acima também lhe recomendo usar a classe de envio de email PHPMailler. Eu a utilizo já tem um bom tempo e nunca tive problemas com a mesma,
é simples de usar e se seu e-mail estiver no padrão não entrará como spam nas caixas de entradas dos servidores de e-mails (Gmail, Hotmail, etc), por que a mesma tem todo um processo de autenticação.
Dica: Não use nomenclatura de variáveis ou vetores com caracteres especiais, você terá problemas com a codificação do arquivo futuramente.
http://www.revistaphp.com.br/artigo.php?id=78


yellowbrick visualiser.fit() raises ValueError

Question: I am trying you Visualise a dispersion plot for my twitter data
Here is the link to the datset
dataset
This is the code
from yellowbrick.text import DispersionPlot

text = combine['tweet']
target_words = ht_negative_unnest

visualizer = DispersionPlot(target_words)
visualizer.fit(text)
visualizer.poof()

I'm trying to pass a list like this in the above code stored in ht_negative_unnest
 ['cnn',
     'michigan',
     'tcot',
     'australia',
     'opkillingbay']

The error raised
 YellowbrickValueError                     Traceback (most recent call last)
<ipython-input-114-d6a94f150164> in <module>
      7 # Create the visualizer and draw the plot
      8 visualizer = DispersionPlot(target_words)
----> 9 visualizer.fit(text)
     10 visualizer.poof()

c:\users\hp\appdata\local\programs\python\python37\lib\site-packages\yellowbrick\text\dispersion.py in fit(self, X, y, **kwargs)
    171         self.target = points_target[:,2]
    172
--> 173         self._check_missing_words(points)
    174
    175         self.draw(points, self.target)

c:\users\hp\appdata\local\programs\python\python37\lib\site-packages\yellowbrick\text\dispersion.py in _check_missing_words(self, points)
    119                     "The indexed word '{}' is not found in "
    120                     "this corpus"
--> 121                     ).format(self.indexed_words_[index]))
    122
    123     def fit(self, X, y=None, **kwargs):

YellowbrickValueError: The indexed word 'wso' is not found in this corpus

Comment: Are you still having problems?  Did my answer below make sense?
Answer: I think wso isn't found in your corpus; only #wso.
Have you tried a single target word like ['love']?  Do you still get the error?
Comment: @deepak-das 'wso' is in your target_words list but isn't found in the text
Comment: You mean a word in the list as 'wso' is not found in the list ?
Comment: Got it. Thank you for your help @larrywgray


Configuration Interface inside an interface in appsettings.json

Question: I am designing a basic logger just for educational purpose I've designed the configuration interface in such way below
public interface ILoggerConfiguration
{
    string LoggingPattern { get; set; }
    IFileLoggerConfiguration FileLogger { get; set; }
}

public interface IFileLoggerConfiguration
{
    string FileName { get; set; }
    string DirectoryName { get; set; }
    string FileExtension { get; set; }
}

public class LoggerConfiguration : ILoggerConfiguration
{
    string LoggingPattern { get; set; }
    IFileLoggerConfiguration FileLogger { get; set; }
}

public class FileLoggerConfiguration : IFileLoggerConfiguration
{
    string FileName { get; set; }
    string DirectoryName { get; set; }
    string FileExtension { get; set; }
}

These all exists in the logger library(which is a class library) I have created and in the ASP.net core project I tried calling as follows.
services.AddSingleton<ILoggerConfiguration, LoggerConfiguration>(_ =>
           Configuration
               .GetSection(nameof(LoggerConfiguration))
               .Get<LoggerConfiguration>());

And I was trying to instantiate it via dependency injection then I am getting an error message as follows.

System.InvalidOperationException: 'Cannot create instance of type
'Logger.IFileLoggerConfiguration' because it is either abstract or an
interface.'

I know I'm trying to instantiate the interface here is the wrong thing. I couldn't find a way to come out of this. Do somebody have some suggestion how to inject the IFileLoggerConfiguration inside ILoggerConfiguration at the time of fetching from appsettings.json?
The appsettings.json have this values as below
"LoggerConfiguration": {
"LoggingPattern": "Message|Date|LogLevel",
"FileLogger": {
  "FileName": "Test it",
  "DirectoryName": "D:\\Logger",
  "FileExtension": ".log"
}
}

Comment: The message is clear. The configuration classes can't guess what type of object to create when all they have is an interface. Why are you using interfaces instead of classes? When a property is an interface - which class should it instantiate? There may be an infinite number of classes that implement this specific interface.
Comment: @SebastianSiemens Yeah you're right. I know and I can change the class structure for the same but I am looking if someone has better solution and I am new to ASP .Net core functionalities
Answer: This is not possible, you indeed need to change the class structure (use only classes, no interfaces) or construct the object with the nested object yourself.
A comparable question + answer can be found here: Options pattern - Interface/Abstract property
Comment: The link you provided was pretty useful. Thanks


How to find the IP of the source of an SSH reverse tunnel?

Question: Using lsof -i I can see there is a reverse ssh tunnel set up on my server:
sshd       1321   remote    8u  IPv4 219299       TCP localhost.localdomain:mvs-capacity (LISTEN)

How can I find out the IP address of the machine that created this tunnel?
Thanks
Answer: lsof -nPp 1321
Answer: Run lsof -i | grep 1321 to see the other connections the pid has, one of which should be the ip of the machine that created the tunnel.
Answer: or you can use netstat -a
Answer: Try netstat -ntp | grep 1321 (replace 1321 with the pid of the process in question.). This will allow you to see the network connections.
Answer: To get only the ip address you can do this.
netstat -ntp | grep "27750" | awk '{print $5}' | awk -F ':' '{print $1}'

If you know that you only have one tunnel you can use this without knowledge of the pid.
netstat -ntp | grep "sshd: root" | awk '{print $5}' | awk -F ':' '{print $1}'

Comment: Remember that `netstat` is deprecated and may not be installed on modern Linux systems.


Evento ng-click do AngularJS não funciona quando configurado em um elemento vindo de uma requisição assíncrona

Question: Tenho uma página chamada listaDT.php que contém um DataTable (https://www.datatables.net/). Utilizei a interface do plugin DataTable para carregar dinamicamente o conteúdo do DataTable. A última coluna da tabela contém apenas checkboxes. Eu quero que estes checkboxs disparem o evento $scope.atualizarPedido() que implementei no controller OpcoesCtrl, mas não consigo, nada é exibido no console da caixa de ferramentas do browser, talvez porque os checkboxes estão sendo carregados dinamicamente, pois quando utilizo um elemento da própria página listaDT.php como trigger do evento $scope.atualizarPedido() minha implementação funciona como esperado.
Observação: os checkboxes estão dentro do contexto do controller OpcoesCtrl.
Pergunta: como utilizar os checkboxes para disparar o evento em questão?
Answer: O AngularJS compila seu template Angular (o que sem o Angular seria HTML estático) quando a página é carregada no navegador. É nesse momento que el reconhece as diretivas e faz as ligações internas para ouvir eventos em elementos que contenham diretivas.
Se você adiciona elementos à página posteriormente, isso vai ser "texto morto" - o Angular não vai "ver" nenhuma diretiva lá.
Execute "$compile" nos trechos de HTML que você carrega/constrói dinâmicamente, antes de adiciona-los à página - isso fara com que o ângular "enxergue" as diretivas lá,. Só que  não testei aqui como ficaria o escopo para isso, já que você tem que executar o $compile nos elementos antes de adiciona-los à sua posição final - é possível que isso não funcione.
Se tudo o mais falhar, use o bom e velho "onclick" do javascript nos elementos que você cria dinamicamente.
Comment: Obrigado. Sua explicação foi bastante didática. Vou testar o "$compile" e mais tarde volto com o resultado.


Notation for set-valued function that returns a non-fixed set length

Question: Sorry if it seems a silly question.
I have a function $f$ that returns a certain set of elements that are all in the same domain. The exact number of element depends on the input. For example $f(x) = \{0,1\}$ for $x = 42$ and $f(x) = \{0,1,2\}$ for $x = 3.14$. On this example, how do I write the domain of the output ?
I would expect something like $f:\mathbb{R} \longrightarrow \mathbb{N}^k$ or $f:\mathbb{R} \longrightarrow k^\mathbb{N}$ with $k \in \mathbb{N}$, but I thinks these notations are wrong... What is the right one ?
Answer: Note that $\mathbf N^k$ is the set of $n$-tuples (not $n$-subsets) of $\mathbf N$, if you want subsets, the usual notation for the so called powerset, the set of all subsets of $\mathbf N$ is $\mathscr P(\mathbf N)$. If you want restrict the range to finite subsets of $\mathbf N$, something like $\mathscr P_{\mathrm{fin}}(\mathbf N)$ or $\mathscr P_{<\aleph_0}(\mathbf N)$ might be understood. But as the is no general notation for that, before using something like that, I'd define it for the reader. That is write something like:

Let $\mathscr P_{\textrm{fin}}(\mathbf N) = \{A \subseteq \mathbf N : A \text{ is finite}\}$ denote the set of finite subsets of $\mathbf N$. Consider a function $f \colon \mathbf R \to \mathscr P_{\textrm{fin}}(\mathbf N)$ ...
Comment: So in my example the correct notation would simply be $f: \mathbb{R} \longrightarrow \mathcal{P}(\mathbb{N})$ ? Or $f: \mathbb{R} \longrightarrow \mathcal{P}_{fin}(\mathbb{N})$ more specifically ?
Comment: It depends if you want to allow for infinite sets. And, as I said above, in case of the latter, I'd define it in the text.


Which of these subsets are subgroups, and if they are, which are abelian?

Question: Determine which subsets $H$ are subgroups and if they are, which are abelian.

Let $G = \operatorname{GL}(2, \mathbb{R})$ and let $$H = \left\{A\in\operatorname{GL}(2,\mathbb{R})\ \middle\vert \det(A) = a^2-b^2\sqrt{2}, a,b\in\mathbb{Q},\textrm{ and at least one of }a,b\textrm{ is nonzero}\right\}.$$
My attempt: if we consider $AB$, where $A,B\in H$, the diagonal elements are irrational since the product of an irrational and rational is irrational, so $H$ cannot be a subgroup.
Let $G = \{(x,y)\mid x,y \in \mathbb{R}\}$. Then $G$ is a group under the operation $$(x,y)*(x',y')=(x+x',y+y').$$ Let $H = \{(x,y) \in G\mid xy \ge 0\}$. I'm not quite sure how to approach this one.
Let $G = \operatorname{GL}(2,\mathbb{R})$ and let $H = \{A \in G\mid A^2 = I\}$
My attempt: since $A^2 = I$ we know $A$ is an involution, so $\det(A)= -a^2 - (1-a)^2$, so for $A,B \in H$, $\det(AB)=\det(A)\det(B)$ but I'm not really sure how to show that $AB$ is in $H$.

Any help would be appreciated, thanks
Comment: In **(1)**, how do you conclude anything about diagonals? The definition of $H$ is in terms of determinants, not diagonals. In **(2)**, what is $(1,2)*(-2,-1)$? In **(3)**, what is the point of your reasoning about determinants? You _already_ know that $\det AB = (\det A)(\det B)$ for all matrices in $G$. What you should be concerned about here is whether $(AB)^2=I$.
Answer:
For $H$ to be a subgroup you know it has to be closed.  What do you know about $\operatorname{det}(AB)$?
The identity is going to be $(0,0)$.  Now consider the inverse of $(1,0)$ added to the element $(0,1)$.
Again this reduces to finding $A,B$ such that $A^2=B^2=I$ but $(AB)^2\not= I$.  If $(AB)^2=I$ then $(AB)^2=A^2B^2$, which is only true if $A$ and $B$ commute (why?).  Can you find some noncommuting involutions?
Answer: For problem one, here's a hint: if $H \subset G$ is a subgroup, and $\phi: K \to G$ is a map, then $\phi^{-1}(H)$ is a group. Conversely (sort of), if $L \subset H$ and $\phi(L)$ is not a subgroup, then $L$ is not a subgroup.
Consider $K = GL(2, \mathbb{R})$ mapping to $G = \mathbb{R}^\times$ via the determinant. You are reduced to checking whether the set of elements of the form $a^2 - \sqrt{2}b^2$ for $a, b \in \mathbb{Q}$, not both zero, is a group under multiplication.


Implementar um Layout no Android Studio

Question: estou querendo implementar um layout assim no Android Studio, procurei já no Google, mas não soube me referir a esse tipo de barra que quero fazer, ai fiz essa imagem. Acho que está bem auto explicativo na imagem, quando o usuário clickar vai abrir o texto daquela barra onde ele clickou e quando clickar novamente vai fechar minimizando a barra.
Comment: Procura por android expandable/collapsible views/layouts.
Answer: Eu acho que você esta procurando por algo assim
https://www.youtube.com/watch?v=jZxZIFnJ9jE
Answer: Pelo que entendi você está procurando uma recyclerview expandable, esse componente funciona bem para tal: https://github.com/thoughtbot/expandable-recycler-view

Implementar um Layout no Android Studio


Getting values of a stdObject in php

Question: I am using an API to get some values. When I print my variable returning an array from api it returns stdObject Class
This is how I request the data:
$graphObject = (new FacebookRequest( $session, 'GET', '/me?fields=id,first_name,last_name,tagged_places' ))->execute()->getGraphObject()->asArray();

This is how I am printing it:
echo '
' . print_r( $graphObject, 1 ) . '
';

This is what it returns:
    Array
(
    [id] => 111111
    [first_name] => Bob
    [last_name] => Stevensen
    [tagged_places] => stdClass Object
        (
            [data] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 111111
                            [created_time] => 1905-01-01T08:00:00+0000
                            [place] => stdClass Object
                                (
                                    [id] => 1111111
                                    [location] => stdClass Object
                                        (
                                            [latitude] => 36.1313
                                            [longitude] => -95.9373
                                        )

                                    [name] => Tulsa, Oklahoma
                                )

                        )

                    [1] => stdClass Object
                        (
                            [id] => 11111
                            [created_time] => 2014-05-30T21:41:11+0000
                            [place] => stdClass Object
                                (
                                    [id] => 111111
                                    [location] => stdClass Object
                                        (
                                            [city] => Okmulgee
                                            [country] => United States
                                            [latitude] => 35.623012460758
                                            [longitude] => -95.972782756346
                                            [state] => OK
                                            [street] => 104 S Morton Ave
                                            [zip] => 74447-5022
                                        )

                                    [name] => Ike's Downtown Pub & Eatery
                                )

                        )

I have found some examples of this stating the way to get a value out of this class object would be like this,
echo $graphObject->{'$STDCLASS'}->{'$FIELD I'M TRYING TO GET'};

I am swapping out these values trying to figure out what the object name is but I get this error:
Notice: Trying to get property of non-object in /file/path

What is the correct way to get the values from this stdClass Object I think maybe I am just not understanding the name of the Object Is it possible to tell from the code I have posted here?
Comment: you dont call it by literal 'stdClass', `$graphObject[0]->id` to access it
Comment: In terms of retrieving data, an object is just like an array except you need to use `$object->value` instead of `$object['value']`.  What data are you trying to retrieve?
Comment: I want to save each one of the values in to a DB. So in this case id created time place etc
Comment: So your saying something like this... `echo $graphObject->created_time;`
Comment: it depends, if `graphObject` has may items, then you need to loop it.
Answer: the object contains an array called Data you can access:
foreach ($graphObject->data as $data) {
    echo $data->id
}

This takes the object and should make it directly accessible
though on second thought .. you may also need to try echo $data['id']; as its not an object any more..
If that doenst work .. try :
$info = json_decode($graphObject,true);

and see if you can work the $info variable easier.
Comment: Tried to get it both ways and the first way and 2nd way I get these Notice: Trying to get property of non-object in /home4/originl0/public_html/sandbox/includes/header.php on line 173

Warning: Invalid argument supplied for foreach() in /home4/originl0/public_html/sandbox/includes/header.php on line 173

Getting values of a stdObject in php


How migrate rich text fields from outside Drupal without converting html tags to entities

Question: I'm working on a migration from a non-Drupal site into Drupal 9.
So far, I'm using migrate_plus, migrate_tools, and migrate_source_csv modules.
The data I'm importing has
 and other tags in some fields. When these import, the
 tags are visible on site pages after the migration completes.
The source is a tab delimited file.
Looking at the page code, these are rendering as html entities instead of tags: so
 is <br>
I've tried changing settings many different ways in the basic HTML filter these fields use. No change.
I added a plugin for each of these fields that is, I thought, supposed to call the basic_html filter. This also had no impact.
The two fields are field_perm_contact_info and body.
Here's the relevant portion of my import configuration yaml file...
process:
  type:
    plugin: default_value
    default_value: source
  field_source_id: srcid
  title: title
    field_source_country:
    plugin: entity_generate
    source: country
    value_key: name
    bundle: country
    entity_type: taxonomy_term
    ignore_case: true
  field_srcfax: fax
  field_main_link: mainlink
  field_manualyr: manual
  field_perm_contact_info:
    plugin: default_value
    default_value: basic_html
    source: permcontinf
  field_permpdfname: permpdf
  field_perm_scope: permscope
  field_perm_updated:
    plugin: format_date
    from_format: n/j/Y
    to_format: Y-m-d
    source: permupdated
  field_tpop: pop
  field_rev_dateleg:
    plugin: format_date
    from_format: n/j/Y
    to_format: Y-m-d
    source: revdate
  field_short_name: shortname
  field_source_iacp_id: srciacpid
  body:
    plugin: default_value
    default_value: basic_html
    source: srcnotes
destination:
  plugin: entity:node

My basic_html filter has
 in the allowed tags list.
If I open an imported node and and resave, boom, it looks fine.
So the question is, how to do the import so that the end result is rendered HTML, not tags displayed as html entities?
A good bit of googling hasn't gotten me to the answer to that yet.
Answer: One way is to set the value and format separately:
constants:
  text_format: basic_html
process:
  field_perm_contact_info/value: permcontinf
  field_perm_contact_info/format: constants/text_format
  body/value: srcnotes
  body/format: constants/text_format

Comment: Thanks, will give this a try... This page also provided clues: https://drupal.stackexchange.com/questions/281659/how-to-migrate-text-format    I wasn't thinking of the format as a separate setting.
Answer: I'm not familiar with the use of 'constant,' so the "set the value format separately" (thanks @Clive) for my two rich text fields looks like this in my yaml file...
  field_perm_contact_info/value: permcontinf
  field_perm_contact_info/format:
    plugin: default_value
    default_value: basic_html
  field_permpdfname: permpdf
  field_perm_scope: permscope
  field_perm_updated:
    plugin: format_date
    from_format: n/j/Y
    to_format: Y-m-d
    source: permupdated
  field_tpop: pop
  field_rev_dateleg:
    plugin: format_date
    from_format: n/j/Y
    to_format: Y-m-d
    source: revdate
  field_short_name: shortname
  field_source_iacp_id: srciacpid
  body/value: srcnotes
  body/format:
    plugin: default_value
    default_value: basic_html

The key concept is to handle the text field like two 'subfields' (this post also helpful), one of them being format.


Making an array equal by decreasing elements adjacent to each other

Question: I was doing this exercise in my computer science class for a warm up earlier, which was to find the minimum number of moves to make all the elements in an array equal to each other, where the only operation is to subtract one from an element in an array.
This made me curious about extensions to the problem; for example I immediately thought of an extension, how many moves will it take to make all the elements in an array equal to each other, where the only operation is to subtract one from two elements that are adjacent to each other.
For example:
Given array [4, 6, 4], we can decrease elements in index 0 and 1 to get [3, 5, 4], then [3, 4, 3], then [2, 3, 3], and then decrease elements in index 1 and 2 to get [2, 2, 2]. This would take 4 moves. However, how would we extend this kind of thinking to larger arrays, where we cannot trace this out by hand like I just did above?
Comment: At least, all cases where an array has an even number of elements but the sum of all elements is initially odd, don't have a solution. That's because every move subtracts 2 from the sum, so the sum remains odd; but any solution would have to have an even sum, computed as some fixed value times the number of elements (which is even).
Comment: Also all cases where the very first or the very last number is greater than its only neighbor. Any move would either preserve or increase the difference, there's no way to reduce it.
Comment: If we restrict the elements of the array to the non-negative integers, then there's a very simple O(nm) algorithm, where `n` is the number of elements in the array, and `m` is the minimum value in the array. All that's needed is to try each possible target value from `m` down to 0, and perform an O(n) check to see if it's possible to reduce all elements of the array to that target.
Comment: It seems that there will not be a solution in many cases. For example, consider `[3 2 3]`.
Comment: In summary, if the target value is known, the answer can be computed in O(n) time with O(1) extra space. For an odd length array, a single pass through the array reduces the last element to the target, and a second pass computes the answer. For an even length array, the minimum of the first and last elements *is* the target, and a single pass through the array computes the answer.
Answer: You can find whether this is possible (and minimum number of moves) in O(n) time, in a way that should generalize to larger array decreases.
The first step is to convert our array A to the first-difference array D, whose elements are D = [A[1]-A[0], A[2]-A[1], ..., A[n-1]-A[n-2]]. We are done when D is the all-zero array. Now, think about how the operations on A translate to changes in D. It's different when n is even and odd, too, so focus on one case at a time.

Odd length
When A has odd length, there are more cases where no solution is possible.
Suppose 'A' has 7 elements. There's 6 possible moves, so let's calculate what effect each has on D.
A = [a_0,    a_1,    a_2,    a_3,    a_4,    a_5,    a_6]
D =     [d_0,    d_1,    d_2,    d_3,    d_4,    d_5]

Moves available:
d_1 += 1
(d_0 -= 1, d_2 += 1)
(d_1 -= 1, d_3 += 1)
(d_2 -= 1, d_4 += 1)
(d_3 -= 1, d_5 += 1)
d_4 -= 1

Some observations:

The interactions between even and odd indices of D are completely disjoint (this is true for the even-length case too).
d_5 can only increase, d_0 can only decrease.

I found it helpful to think of this as a 'flow' from left to right in D:
d_0 --> d_2 --> d_4 --> SINK

SOURCE --> d_1 --> d_3 --> d_5

this makes things easier: there's only one way to try to make D all zero, so we can just try that.

If D[0] is negative, this is impossible. If it's positive, add D[0] moves to our counter, and add D[0] to D[2]
If D[2] is negative, this is impossible. If it's positive, add D[2] moves to our counter, and add D[2] to D[4]
If D[4] is negative, this is impossible. Otherwise, add D[4] to our counter. D[4] points to a sink, so we are done.

I haven't explained the process for the odd vertices, but it's the same logic-- there's at most one way to make D all zero, following the flow.

Even-length
The even-length array case is similar, except the flow-network has different endpoints.
A = [a_0,    a_1,    a_2,    a_3,    a_4,    a_5,    a_6,    a_7]
D =     [d_0,    d_1,    d_2,    d_3,    d_4,    d_5,    d_6]

Moves available:
d_1 += 1
(d_0 -= 1, d_2 += 1)
(d_1 -= 1, d_3 += 1)
(d_2 -= 1, d_4 += 1)
(d_3 -= 1, d_5 += 1)
(d_4 -= 1, d_6 += 1)
d_5 -= 1

d_0 --> d_2 --> d_4 --> d_6

SOURCE --> d_1 --> d_3 --> d_5 --> SINK

This means that the odd-indices can have any values without changing the solvability, while the even indices must become all zero with only positive transfers from left to right. Positive flow still moves in exactly one direction in both cases.
I've written a Python solution implementing the logic above. There's one caveat-- I haven't been able to rigorously test it against random input. There's no obviously correct brute-force solution to this problem, so there may be failing testcases that I missed.
def min_decreases_to_get_equal(nums: List[int]) -> Optional[int]:
    """Given an array of integers, returns the number of moves
    to make all elements equal, or None if impossible.
    A move is selecting two adjacent elements and dec. both by 1."""

    n = len(nums)
    assert n >= 2
    if n == 2:
        return 0 if nums[0] == nums[1] else None
    differences = [nums[i] - nums[i - 1] for i in range(1, n)]
    evens = differences[0::2]
    odds = differences[1::2]

    if n % 2 == 0:  # Even length case

        total_cost = 0
        m1 = len(evens)
        for i, x in enumerate(evens):
            if x < 0:
                return None
            elif x > 0:
                # Last element can't be decreased
                if i == m1 - 1:
                    return None

                total_cost += abs(x)
                evens[i + 1] += abs(x)

        m2 = len(odds)
        for i, x in enumerate(odds):
            if x < 0:
                total_cost += abs(x) * (i + 1)
            elif x > 0:
                total_cost += abs(x)
                if i < m2 - 1:
                    odds[i + 1] += x
        return total_cost

    else:  # Odd length case
        total_cost = 0
        m1 = len(evens)
        for i, x in enumerate(evens):
            if x < 0:
                return None
            elif x > 0:
                if i < m1 - 1:
                    evens[i + 1] += abs(x)
                total_cost += abs(x)

        m2 = len(odds)
        for i in reversed(range(m2)):
            x = odds[i]
            if x < 0:
                if i != 0:
                    odds[i - 1] -= abs(x)
                total_cost += abs(x)

            elif x > 0:
                return None

        return total_cost

Example tests:
[4, 6, 4] --> 4,
[3, 2, 3] --> None,
[0, 8, 8, 14, 8] --> 34,
[2, 5, 1, 6, 12, 11, 7, 0, 1, 1] --> 33

Answer: Let's start with the problem that we want to find out what is the smallest number of operations. If we know what is the largest number that equalizes all arrays? We can subtract that number from each other in the array to get the answer. Naively, you can solve this problem by searching for the smallest number in the array and loop checking from 0 to min(a[i]) then find the minimum operations.
My code in C++
// print -1 if not possible to equalize array
void solve() {
    int N;
    scanf("%d", &N);

    vector<int> a(N);
    int minimum=INT_MAX;
    for(int i=0; i<N; ++i) {
        scanf("%d", &a[i]);
        minimum=min(minimum, a[i]);
    }

    if(N==1) {  // Initially check when N=1 or N=2
        printf("0\n");
        return;
    }
    else if(N==2) {
        printf("%d\n", (a[0]==a[1] ? 0 : -1));
        return;
    }

    vector<int> temp=a;  // temporary array for storing array before operation
    for(int target=minimum; target>=0; --target) {
        a=temp;
        bool check=true;  // check array equal?
        int operation=0;  // count number operations
        for(int j=0; j<N-1; ++j) {
            int subtract=a[j]-target;
            operation+=2*subtract;
            a[j]-=subtract;
            a[j+1]-=subtract;
            if(a[j]<target || a[j+1]<target) {  // all element should equal to target
                check=false;
                break;
            }
        }

        if(check==true) {
            printf("%d\n", operation);
            return;
        }
    }
    printf("-1\n");  // not possible
}

But the above method will be slow when N is large.
For this problem, the Greedy Algorithm can be used to solve it. Now let's look at the situations when this array can't be equalized. If you want to make an array with a[i-1] != a[i] to be equal, what do you have to do? Assume we're iterating over an array and come into the following cases.
First, if a[i-1] > a[i] , then we have to perform operation at the left-hand in order to equal make it to the right-hand side, that is, a[i-2] and a[i-1] must be executed. For example 8 8 7 to 7 7 7.
Please note that if i equals 1, it needs the initial element of an array. It will be unable to operate.
Second, if a[i-1] < a[i] , then we have to perform operation at the right-hand in order to make it equal to the left-hand side, that is, a[i] and a[i+1] must be executed. For example 5 6 6 to 5 5 5.
Please note that if i equals N-1, it is the last element of an array. It will be unable to operate. Naturally, the prior ones have been equalized.
After that, we can use Greedy to keep the array equal. We'll traverse over the array one by one, checking for the conditions listed above. If it can do it, it ought to. Continue until you are unable to do so or discover that this array is stuck at the very first or final position. This one will be quicker than the previous one.
Here is my code.
// print -1 if not possible to equalize array
void solve() {
    int N;
    scanf("%d", &N);

    vector<int> a(N);
    for(int i=0; i<N; ++i) {
        scanf("%d", &a[i]);
    }

    if(N==1) {
        printf("0\n");
        return;
    }
    else if(N==2) {
        printf("%d\n", (a[0]==a[1] ? 0 : -1));
        return;
    }

    if(a[N-2]a[1]) {
        printf("-1\n");
        return;
    }

    long long operation=0;
    bool check=true;  // check if the array has changed
    while(check) {
        check=false;
        for(int i=1; i<N; ++i) {
            if(a[i-1]<a[i]) {
                if(i==N-1) {
                    printf("-1\n");
                    return;
                }
                check=true;
                int subtract=a[i]-a[i-1];
                operation+=2*subtract;
                a[i]-=subtract;
                a[i+1]-=subtract;
                if(a[i]<0 || a[i+1]<0) {
                    printf("-1\n");
                    return;
                }
            }
            else if(a[i-1]>a[i]) {
                if(i==1) {
                    printf("-1\n");
                    return;
                }
                check=true;
                int subtract=a[i-1]-a[i];
                operation+=2*subtract;
                a[i-2]-=subtract;
                a[i-1]-=subtract;
                if(a[i-2]<0 || a[i-1]<0) {
                    printf("-1\n");
                    return;
                }
            }
        }
    }
    printf("%lld\n", (a[N-1]>=0 ? operation : -1));  // array already equal but may less than zero
}

This may be accomplished in a variety of ways, and there is a better approach than the one I've presented. However, I believe that this is sufficient to go through test cases 1 <= N <= 105 and 0 <= a[i] <= 109.


Preparing Bayesian conditional distributions for Gibbs sampling

Question: I was looking at the Gibbs Sampler when I stumbled upon the following example:
Suppose $y = (y_{1}, y_{2}, \ldots, y_{n})$ are iid observations from an $N(\mu, \tau^{-1})$
Furthermore, suppose there exists prior information on $\mu$ and $\tau$ indicating that they are independent and that $\mu$ follows an $N(\mu_{0}, \sigma_{0}^{2})$ distribution while $\tau$ follows a $\text{Ga}(\alpha_{0}, \beta_{0})$ distribution.
For this example,
$$ p(\mu, \tau|y_{1}, y_{2}, \ldots, y_{n}) \propto f(y|\mu, \tau)p(\mu, \tau)$$
Also,
$$ p(\mu|\tau, y) \sim N(\frac{n\bar{y}\tau+\mu_{0}\tau_{0}}{n\tau+\tau_{0}}, (n\tau+\tau_{0})^{-1}) $$
where $\tau_{0} = (\sigma_{0}^{2})^{-1}$
and
$$ p(\tau|\mu, y) \sim \text{Ga}(\alpha_{0}+\frac{n}{2}, \beta_{0}+\frac{S_{n}}{2}) $$
where $S_{n} = \sum_{i=1}^{n}(y_{i}-\mu)^{2}$
Because it is not easy to compute directly from this distribution, the Gibbs sampler can be used provided the conditional distributions are known.
Could anybody demonstrate how (provide the derivations for) the conditional distributions ($p(\mu|\tau, y)$ and $p(\tau|\mu, y)$) given above?
EDIT:
For example, to achieve $p(\mu|\tau, y)$, is the following valid?
$$ p(\mu|\tau, y) \propto  p(\tau, y|\mu)p(\mu)$$
If so, what form will $p(\tau, y|\mu)$ have?
Answer: Ok, what you need to do is compute the joint posterior up to a constant, i.e. $f(y_1,...,y_n|\mu,\tau)p(\mu,\tau)$.  Then to compute the conditional posterior $\pi(\mu|\mathbf{y},\tau)$ you just treat the $\tau$ terms as fixed and known, so that some of them can be cancelled out.  Then you do the same thing with $\mu$ to get $\pi(\tau|\mathbf{y},\mu)$.
So what I mean is, the joint posterior is given by:
\begin{equation}
\pi(\mu,\tau|\mathbf{y}) \propto \tau^{\frac{n}{2}+\alpha_0-1} \exp\{-\frac{\tau}{2} \sum_{i=1}^{n}(y_i-\mu)^2-\frac{\tau_0}{2}(\mu-\mu_0)^2-\beta_0\tau\}.
\end{equation}
Now, to get the conditional posterior $\pi(\tau|\mathbf{y},\mu)$ you just remove the $\mu$ terms that just multiply the expression.  So we could re-write the joint posterior as:
\begin{equation}
\pi(\mu,\tau|\mathbf{y}) \propto \tau^{\frac{n}{2}+\alpha_0-1} \exp\{-\frac{\tau_0}{2}(\mu-\mu_0)^2\}\exp\{-\frac{\tau}{2} \sum_{i=1}^{n}(y_i-\mu)^2-\beta_0\tau\}.
\end{equation}
Now, since we are treating $\mu$ as fixed and known, for the conditonal posterior $\pi(\tau|\mu,\mathbf{y})$ we can remove the first exponential term from the equation and it will still be true (owing to the $\propto$ sign rather than the equals sign).  It's important that you get this: the conditional posterior says given that we know $\mu$ what is $\tau$, so $\mu$ is known (and hence fixed).  So the kernel for the conditional posterior for $\tau$ becomes (after some re-arranging):
\begin{equation}
\pi(\tau|\mu,\mathbf{y}) \propto \tau^{\frac{n}{2}+\alpha_0-1}\exp\{-\tau(\frac{1}{2} \sum_{i=1}^{n}(y_i-\mu)^2+\beta_0)\},
\end{equation}
which is the kernel for the Gamma distribution with the parameters you state.
Now, for $\pi(\mu|\tau,\mathbf{y})$ you do the same thing, but it's a bit trickier because you have to complete the square.  After cancelling the relevant terms not involving $\mu$ you get:
\begin{equation}
\pi(\mu|\tau,\mathbf{y}) \propto \exp\{ -\frac{\tau}{2} \sum_{i=1}^{n} (y_i-\mu)^2 - \frac{\tau_0}{2}(\mu-\mu_0)^2\}.
\end{equation}
If you multiply out the squared brackets and take the relevant summations, then remove all terms not involving $\mu$ (as they are all just multiplying the kernel by a constant) this becomes:
\begin{equation}
\pi(\mu|\tau,\mathbf{y}) \propto \exp\{ -\frac{1}{2}[\mu^2(n\tau+\tau_0) - 2\mu(\tau n\bar{y} - \tau_0\mu_0)]\}.
\end{equation}
If you complete the square here you get the kernel for a Gaussian with the mean and variance you state.
Hope that helps.
Comment: Yeah, so what you have is $a\mu^2 + b\mu$.  But the $c$ term is constant with respect to $\mu$, so you can add or subtract it as you please without losing the validity of the expression.  If you have $\exp\{ a\mu^2 + b\mu + c\} = \exp\{c\}\exp\{ a\mu^2 + b\mu\}$ then you can remove and add in the $\exp\{c\}$ as you like, since it is fixed.  Does that make sense/help?
Comment: So to clarify, if you write it in the form $a(\mu + h)^2$, you will end up with an extra constant term at the end, but that's ok because we just need something proportional to what we had.
Comment: Hello.  For the uninformative priors you want $\alpha_0 = 1$, not $0.00001$.  You can't determine what the informative priors should be the way you said (or in any way like that).  In practice you would choose $\alpha_0$ and $\beta_0$ so that the shape of the prior reflected your beliefs.  For simulation purposes, I think they just mean try some different values of $\alpha_0$ and $\beta_0$ that will give you a less flat prior and see how your posterior changes.
Comment: Thank you so much! That's a superb answer. I really appreciate it.
Comment: :-) no problem.
Comment: Sorry, but I have just one more question. In relation to the completing the square section, is the variable we are completing with respect to $\mu$?
If so, how do we get the expression in the general form:
$$ a\mu^{2} + b\mu + c = 0 $$
It seems that every term will contain $\mu$ or $\mu^{2}$ which leaves no constant term.
Comment: Oh, of course! I should have spotted that. The proportionality aspect really is responsible for quite a lot.
Thanks again!
Comment: Sorry to labour this question, but I've posted what I believe is a reasonably similar question about data augmentation. Unfortunately, it hasn't received very much attention. Perhaps you have some experience in this area.
If you would like to view the question, it can be found at: http://stats.stackexchange.com/questions/43488/mcmc-and-data-augmentation
Thanks!
Comment: Hello, I'm a bit busy this evening but if it hasn't been answered by tomorrow morning I'll have a look then.  No guarantees I'll know the answer but I'll do my best!
Comment: Hi.
There's no rush (or obligation to even look at it, of course). I just figured I'd mention it because you seem to be quite proficient in this area. I appreciate your reply though. Thanks!
Comment: Apologies for dragging this post up again, but, recently, I have been required to code the above example in a computer lab. Firstly, I was required to run the sampler with **uninformative** priors on the above parameters (i.e. $\mu_{0} = 0$, $\tau_{0}^{2} = \alpha_{0} = \beta_{0} = 0.00001$). After this, I was required to run the sampler with **informative** priors on the above parameters. Without any further information, how do I determine what form the informative priors should take? Perhaps they can be inferred from the initial uninformative sampler's priors?
Comment: Hello. Yes, I figured that the only to develop an informative prior would be to have some previous information about the process, but I decided to ask just in case. Most probably, it will be like you said: choosing some different values for $\alpha_{0}$ and $\beta_{0}$ with a view to observing how the posterior changes. As always, thank you very much!
Comment: By the way, I've posted another Monte Carlo based question which hasn't received much attention. As always, there's no obligation at all to check it out, but if you feel inclined, you might be able to provide some assistance. The question can be found at: http://stats.stackexchange.com/questions/44193/deriving-priors-for-mcmc-implementation . I'm abusing this thread (and your attention) now, so I best leave it at that. Thanks again!
Comment: Can you help me see this question https://stats.stackexchange.com/questions/498646/how-to-built-gibbs-sampler-of-mixture-bayesian-regression-in-r? Thank you.


How can I get lat/lon from an address?

Question: I have these modules
addressfield
geofield
geocoder

Is there any function to which I can pass an address like Stree, zipcode city, Country and it returns a lat/lon from that address?
I have searched in the code of geofield and geocoder but unable to find any helper function.
Comment: https://www.drupal.org/project/geolocation
Answer: Using google geocoding with geocoder module, you may use another geocoding provider, i think this requires a google map token now given google's new rules :
// @return Geometry Returns a geoPHP geometry object. Generally a Point.
$point = geocoder('google', $address);
$lat = $point->coords[1];
$lon = $point->coords[0];

I did this long time ago, please check.

How can I get lat/lon from an address?


Access JSON chunk exported from Gatsby Static Query

Question: I have a React Component in a Gatsby app that is using the useStaticQuery hook to pull in data from the GraphQL layer. This component gets used in my application, but it also gets used as part of a JavaScript embed/widget that is created in a separate Webpack configuration.
I don't want the widget to depend on Gatsby, so I've shimmed the relevant bits of Gatsby, but I still need to pass in data to the shim I've created for useStaticQuery. I found that my Gatsby app is generating a file at public/static/d/2250905522.json that contains a perfect representation of the query data, and I'd like to use it like so:
// This file gets substituted when importing from `gatsby`

import queryResult from "../public/static/d/2250905522.json"

export const useStaticQuery = () => queryResult.data

export const graphql = () => {}

This works, but I haven't figured out where this is coming from or how to determine the file name in a way that is deterministic/stable. How is Gatsby determining this file name, and what internals might I use to do the same?
Edit: I found this routine in the Gatsby codebase that appears to be using staticQueryComponent.hash to determine the number. staticQueryComponent is being destructured from store.getState() where store is associated with Redux, but I'm still not sure where the hash is being determined yet.
Edit 2: Found another mention of this in the documentation here. It sounds like hash is a hash of the query itself, so this will change over time if the query changes (which is likely), so I'm still looking for the routine used to compute the hash.
Answer: Gatsby is using murmurhash with a seed of "abc" to calculate the hash of the full text of the query (including whitespace). This occurs in babel-plugin-remove-graphql-queries.
Since the reused components are isolated from Gatsby, the graphql tagged template literal can be shimmed in order to get the original query for hashing:
// webpack.config.js
module.exports = {
  resolve: {
    alias: {
      gatsby: path.resolve(__dirname, "gatsby-shim.js"),
    },
  },
}

// gatsby-shim.js
import { murmurhash } from "babel-plugin-remove-graphql-queries/murmur"
import {
  stripIgnoredCharacters,
} from "graphql/utilities/stripIgnoredCharacters"

const GATSBY_HASH_SEED = "abc"

const hashQuery = (query) =>
  murmurhash(
    stripIgnoredCharacters(query),
    GATSBY_HASH_SEED
  ).toString()

export const graphql = query => hashQuery(query.raw[0])

This results in the query hash being passed into useStaticQuery, which can be shimmed similarly to retrieve the cached query from disk.
Also worth noting, newer versions of Gatsby store the StaticQuery result data in public/page-data/sq/d/[query hash].json.
If you're looking to do something similar, I've written up a much longer blog post about the details of this process and the solution I arrived at here.
Comment: Hi, is there any chance you can share what is in gatsby-shim.js? I am needing to do something very similar to what you have described to export a Nav component into a legacy site. I hope you don't mind but I am going to peek at your profile and ask you over email too.
Answer: Due to changes in the babel-plugin-remove-graphql-queries, coreyward's (awesome) answer should be updated to:
const { stripIgnoredCharacters } = require('graphql/utilities/stripIgnoredCharacters');
const murmurModule = require('babel-plugin-remove-graphql-queries/murmur');
const murmurhash = typeof murmurModule === 'function' ? murmurModule : murmurModule.murmurhash;

const GATSBY_HASH_SEED = 'abc';

function hashQuery(query) {
  const result = murmurhash(stripIgnoredCharacters(query), GATSBY_HASH_SEED).toString();
  return result;
}

module.exports = hashQuery;

The changes are:

fix the way murmurhash is imported. Credit to github user veloce, see: https://github.com/birkir/gatsby-source-graphql-universal/pull/16/files
Change to using stripIgnoredCharacters in order to match the updated way that gatsby internally hashes queries by first stripping whitespace and comment lines for efficiency.


Yielding each value from a list

Question: I need to assign each value of a list to a variable. I then call that variable from another program.
This is my code:
inputList = """["vanilla","vanillas","vanill","vanil","vanila"]"""

def singleListSplitter(inputText):
    try:
        inputList = ast.literal_eval(inputText)
        clean_inputList = [item.strip() for item in inputList]

        #print clean_inputList

        for item in clean_inputList:
            yield item
            print item

    except Exception as e:
        print "Error: ",e

singleListSplitter(inputList)

On running the script, I don't see any output in the console with yield. The print works as expected. What do I need to change to get each individual value?
UPDATE 1
Based on the comments and responses, I tried:
value = list(singleListSplitter(inputList))
print value

and got a list in response.
What I want really want here are 5 strings (from the list) that I can use elsewhere.
Comment: Your last line of code will return a generator, it should not print anything from within the list.  Can you show how you are iterating through the list?  When I iterate through your generator, I get both the item, and the print statement.
Comment: Yep, the anonymous user above is right. Generator is an example of lazy evaluation (google it, it's helpful in any language). It is not "holding" values like a list, but rather it is "producing" them when asked for next element. Even though it is backed by a list (clen_inputList), it still won't expose the value unless specifically asked to do that.
Comment: I guess the proposed answer of @jbch solves your problem, you "got a list in response" in which you can find the values. Furthermore why you don't just return clean_inputlist in the first place? No need for a generator here if you call list() later on anyways.
Comment: "What I want really want here are 5 strings (from the list) that I can use elsewhere." ... you *can* use those elsewhere, by *using the list*. It's hard to understand exactly what you want.
Answer: When you use yield in a function, what you have is a generator function.
Generator functions are a bit different from regular function; they do not run when you call them, instead they return a generator object, which is a type of iterator - something you can iterate over, for example in a for loop.
To run the code in the function you need to actually iterate over the generator object.
An easy way to do that is to call list on the generator object.
list(singleListSplitter(inputList))
But if you are not using the values yielded by your function, there is no reason to use yield in the first place, you can just remove it and you'll have a regular function which prints your results.

Yielding each value from a list


Combine 2 counts into a sum in hive sql from union table

Question: I'm having a hard time combining the sum of counts as a result of a union table in hive sql
SELECT pulocation AS locID,count(pulocation) AS puCount FROM task1
  WHERE  distance > 0.5 AND distance < 1
  GROUP BY pulocation
UNION
SELECT dolocation,count(dolocation) AS doCount FROM task1
  WHERE  distance > 0.5 AND distance < 1
  GROUP BY dolocation

will give me result of this table
_u2.locid   _u2.pucount
1           18
1           24
3           3
3           4
4           4693

I tried to put this table to create a new table with combination of the counts but with no success.
SELECT _u2.locid, SUM(_u2.pucount)
FROM (
SELECT pulocation AS locID,count(pulocation) AS puCount FROM task1
  WHERE  distance > 0.5 AND distance < 1
  GROUP BY pulocation
UNION
SELECT dolocation,count(dolocation) AS doCount FROM task1
  WHERE  distance > 0.5 AND distance < 1
  GROUP BY dolocation)
GROUP BY u2.locid

I tried using '_u2.' or 'u2.' but result in this error
org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: ParseException line 14:0 Failed to recognize predicate 'GROUP'. Failed rule: 'identifier' in subquery source

What I basically want is this table
_u2.locid   _u2.pucount
1           42
3           7
4           4693

Answer: Try this as:
SELECT t.locid, SUM(t.pucount)
FROM ((SELECT pulocation AS locID, count(pulocation) AS puCount
       FROM task1
       WHERE  distance > 0.5 AND distance < 1
       GROUP BY pulocation
      )
      UNION ALL
      (SELECT dolocation, count(dolocation) AS doCount
       FROM task1
       WHERE  distance > 0.5 AND distance < 1
       GROUP BY dolocation
      )
     ) t
GROUP BY t.locid

Comment: though not perfect, but it helps me. idk why hive produce error when have brackets. i put a proper answer. thanks for helping. I add the 'AS' before 't' just to clarify. but it works without it
Answer: After the help from previous answer,
SELECT t.locid, SUM(t.pucount) AS count
FROM (
  SELECT pulocation AS locID,COUNT(pulocation) as pucount
  FROM task1
    WHERE  distance > 0.5 AND distance < 1
    GROUP BY pulocation
  UNION
  SELECT dolocation,count(dolocation) as doCount
  FROM task1
    WHERE  distance > 0.5 AND distance < 1
    GROUP BY dolocation) AS t
GROUP BY t.locid
ORDER BY count DESC
LIMIT 10

Answer: This is what you need

SELECT locID, sum(totCount) as totCount
FROM (
SELECT pulocation AS locID,count(pulocation) AS totCount
FROM task1
WHERE  distance > 0.5 AND distance < 1
GROUP BY pulocation
UNION ALL
SELECT dolocation AS locID,count(dolocation) AS totCount FROM task1
  WHERE  distance > 0.5 AND distance < 1
  GROUP BY dolocation
) t1
GROUP BY locID


Is it necessary to practice staying in time while improvising?

Question: I've  beatboxed for about 10 years and never thought about staying in time while improvising, and it sounds great. I can just make a beat and it sounds great without having any clue if what i just beatboxed was a 16 note or something else.
Now, in the last 6 or some months I've started to learn about improvising on piano. The instructions say that I have to change chords in my left hand for every bar in 4/4 time. This however, requires me to have an idea of where I am in time. I can achieve that through counting, but then I can't think about where I want to go with the melody and it's also just kinda annoying having to count constantly.
In addition, I don't currently feel like I actually have to have an idea of where I am in time, because I can just play a note and change chords when it seems right and it sounds great.
This leads me to my question. Will it bite me in the ass and hinder future development by not trying to stay in time while improvising and just play on instinct?
Comment: "it sounds great" ... if you record yourself and listen to the playback? Sounds great to you and how many others who are not your family and friends, and who are musicians?
Comment: As an experienced beatboxer you will have aquired the ability to be in time without counting. I bet you hear and feel when  a measure or four measures of a blues have passed. There are 2 ways of making music: aware/cognitive and unconsciously/intuitive. I estimate both approaches.
Comment: Not an answer, but test your time-keeping skills and find out how good or bad it is. Use a metronome click that clicks, only once or twice per bar. Or once every two bars. Can you play with that?
Comment: if it's not in time then it'll be hard to perform it. it's okay on your own
Comment: *"have to change chords in my left hand for every bar in 4/4 time"* - this is generally bad advice for improvising - you change the left hand chord when the melody requires it.  It may be part of a course on learning improvising, so as an introduction can help a new improviser "find the beat" - you're not new to improvising, you're new to improvising on the piano.  Take this "requirement" with a pinch of salt and move on.
Answer: While playing by yourself, you do what you want. In time, out of time, seems no-one cares! The potential problems will come when you play with others. I've played with many like you appear to be, and it's not hard work - it's almost impossible!
So, the decision will be yours. If you only ever want to play alone, probably for your own amusement, then take no notice, and carry on!
If you feel that you may eventually play with others - which is what most musos seem to prefer, then the 'discipline' of timekeeping is paramount. You won't necessarily have to know or understandd what a semiquaver is, as you can probably feel your way through, but understanding what a bar is, and how it affects what gets played, and its place in the whole scheme of things, is important. It's basically being able to count to four, in a steady way. That means others playing with you will have something regular to play their parts simultaneously.
Answer: There are many other good answers here but I wanted to add one thing:
Get a Looping Pedal!
Besides actually playing with real people, nothing will improve your improvising, timing, and ability to experiment more than laying down some chords or riffs, trying it 3-4 times until you get the timing perfect, then playing other stuff over that, then trying to loop that perfectly over it, etc.
You can also practice improvising over chord-changes that go through 2 (or more) keys, unusual time-signatures, and more.  It really is an invaluable practice-tool, especially in these times of social-distancing.
Some loop pedals can be found for very cheap, especially used ones on ebay or craigslist.
Edit:
This advice is meant as a supplement to more traditional advice.  You should definitely learn to count time as well as practice with a metronome.  Learn scales.  Start with the basics.  But once you feel fairly comfortable then a looping pedal can be an entertaining and useful way to continue your progress.
Comment: All very well, but if OP can't keep time even on the first take, how is that going to help with further takes? A good idea, but in theory.
Comment: @Tim At the very least, the loop's length is fixed in time, and whatever is in the loop will be repeating exactly at the loop's frequency. That's quite a bit of robust rhythm, already. And the OP will be forced to make the looped groove match rhythmically with that loop's length if they want the loop to sound good.
Comment: @cmaster-reinstatemonica - sometimes I get the loop slightly out of sync. Fair enough, I know. But OP seems to not have a good sense of rhythm, so with a potentially dodgy rhythm anyway, and not syncing at the end to the next beginning, how will it help? I sometimes have the pleasure of playing with folk who are quite capable of throwing in a bar of 5/4 or 3/4 in a 4/4 piece - andd are blissfully unaware. Can't see how using a looper would help them either, if you understand where I'm coming from.
Comment: @Tim  Well, a 4/4 + 4/4 + 5/4 sequence is a valid time measure as well... Yes, I understand what you are saying. It's probably not best to start with fancy time measures. But I guess, you'd start with a loop on only one or two bars anyways, and then any fancy time measures will feel weird enough for the OP to avoid. After all, this is a learning exercise, and I believe that the fixed loop length would nudge the OP in the right direction. (Fancy times *can* be beautiful, though: I know a rock song that uses a 4*3/16 + 4/16 time, and it's totally awesome!)
Comment: @cmaster-reinstatemonica - point missed ! These guys aren't doing it on purpose - they don't even know what 5/4 is! Whole songs in 4/4 can have weird timings that they don't notice aren't fitting! And 'fixed length loop' will be fixed by someone who can't count too well. That's not helping anything!
Comment: Tempted to downvote because from my experience, people who play mostly with looper pedals tend to have a very weird feel of time. It may technically speaking be much closer to an exact click than the tempo a good live drummer would develop in a band, and yet feel lop-sided in ways that I personally find just unmusical. But I don't downvote because this seems to be an æsthetic that some people actually like, to whatever.
Comment: @leftaroundabout - looper pedals simply regurgitate what's been played. Good or bad. And there's an art to kicking the pedal exactly on time for the loop to be accurate. This is a disastrous solution for anyone without impeccable timing - which it seems OP doesn't possess. So, unless the included drum track is incorporated, it's not a good idea.
Comment: Those are fair points, @Tim.  I've edited the answer to indicate that this advice is meant to supplement more traditional advice and that they should still learn the basics of counting.
Comment: There's good reason why there are so many loopers on Craigslist, et al. Most are there because their present owners can't time the switching well at all. So, sell it on! I struggle myself sometimes, and I've been playing for 60+ yrs. Seems like there will always be a good pre-loved(?) market for loopers...
Answer: This is something I struggled with when I played improv trumpets solos in my school's jazz band years back. I had always practiced at home without any metronome and I would just play around chord changes that I made up in my head rather than listening to an external source and improvise.
What did this do?
Well the biggest thing I noticed was that it was really hard to know when to start or when to stop a phrase, or when to lay into a specific note. If you listen to really good soloists, they will be counting and will have specific licks timed with matching background information from other instruments. This was something I could not do because I never practiced counting.
On the bright side, as a trumpet soloist, all I had to do to play a "decent" solo was listen to the rhythm (since I'm not comping chords or making important, independent changes), but It would have been nice to be able to do cool things, like switch keys or add some mode mixture if I were counting out when to do those things.
To answer your question, yes it will bite you, but yes it should also be instinct. But it can only become instinct after you practice it deliberately many times.
Answer: As others have said, it's important to train yourself to respect rhythm if you want to be able to jam with others. It's also important to be able to anticipate planned chord changes correctly.
However, starting with counting is probably not what you need. You already seem to have a feel for rhythm (otherwise your beatboxing wouldn't sound great), though not formalized, and not really connected to your piano play. And that's exactly what you need to do: Connect the way you are improvising on the piano with how you build a rhythm.
The piano is a great instrument to learn this. It basically allows you to play with yourself. You just need to take advantage of that.
So, here is what I would do:

Decide on a time to use

Create some grove in your left hand that is in time. I.e. the 1 is always heavy, the 3 not so much. Do some chord-like figure (only the fundamental needs to be present, and it should definitely be played on the 1), and only change chords on the 1.

Improvise some melody on top of that. Or chords. Or whatever comes to mind. Make it interact with the groove in a positive way. Both in rhythm and in harmony.

With the groove in place, it will be natural for your melody to fall into place with the rhythm, and you don't need to count to do that. You only need to feel the 1 and the 3. That's what you can do, that's what the groove will help you keep up while you concentrate on the melody. And you will feel when your melody has broken the rhythm, just as much as you will hear it when your melody has violated the harmony. And you will learn to recover from these mistakes, to turn the error into a stressful sound that resolves in an interesting way. But for all that to happen, some simple groove needs to be present.
Don't be too complicated with your groove at first. You need to be able to hold the groove without really thinking much about it. The classic 12-bar blues is a really good starter. Simple, but with all the material to build some real emotional solos.
Answer: Rhythm is a part of music.  A very important part in today's popular styles.  And, while rhythm CAN be free, mostly we prefer it when it's organised into a repetitive 'groove'.
I suspect your beatboxing IS 'in time', you just haven't formalised the concept.
This 'one chord per bar' thing sounds like the instruction for an elementary exercise in improvisation.   Fine, as far as it goes.  But it's certainly not a general rule. Several different chords in one bar, one chord over several bars, chord changes at irregular intervals - all are common.    But when a sequence of chord changes IS set up, music very often sticks to it for the next chorus!  Same chords in the same places in the timeline.  So, you need to know where you are rhythmically if you're aiming for something more structured than completely free 'stream of consciousness' style improvisation.
Answer: "Is it necessary to practice staying in time while improvising?"
Nothing is "necessary" in this context.  Improv is improv, even time and tempo fluctuate during improvisation, as well as in orchestrated pieces.  The real question is whether you are in control of what you do.  In my youth I often heard young musicians respond to their own playing after a solo with "I didn't expect that", or "Wow, that sounded cool".  Improv from an experienced player should not be a complete surprise.  Sometimes we go in directions we didn't intend to in response to other player's input but the fact is improvising draws on examples that are already in the player's consciousness, and variation on themes already present in the music.
That being said a bigger issue, and a more important question is not one of keeping time but keeping track of where you are in the song as you improvise.  This is critical.  At a high level of development a musician might be able to recall the melody of the tune in their mind as they play over it.  At the very least you should be able to remember the basic structure of the tune.  Are you in the A section or B section, etc.
If you are truly exploring creative ideas free form then there is no reason to be concerned about where you are since you are likely composing as you go.  But to be a player in a group you really do need to be able to keep time by yourself and know where you are in a piece.  Experienced musicians can sometimes recall tempos without the help of a metronome.  Two examples are (1) my classical bass teacher in high school (who was perhaps a savant) could tap 84 bpm on a metronome and it would read 84 +/- a couple beats, and (2) a marching band director for a bagpipe group.  He could march to 78 bpm right on the nose every time.  It was in his muscle memory.  This is an expected skill of an experienced musician (to some degree).  As my big band conductor used to say "everyone counts", and that was meant to be taken as direction.
I'd say it is very important to learn to stay in time on your own as well as recall the structure of a tune and know where you are at to the beat.  There are way to practice this.
(1) try listening to a metronome and tap to it, close your eyes and mute the metronome.  Then after some time un-mute it and see how close you match it.
(2) learn a tune you really like and see if you can recall it from memory in your mind without playing.
(3) play with recorded pieces, even if you don't know the piece just try to keep up in key by adding a small supportive part.
Comment: Part of keeping track *is* keeping time, surely.
Answer: It may be annoying now to count, because you need to go through the training process, but eventually it will become instinctive and you won't need to count.
While doing the training actually count beats out loud. This can difficult at first, especially when one of the parts starts to use syncopated rhythms. But eventually it will come to you.
Keep in mind that with piano you are doing multiple rhythms simultaneously. Look into the idea of composite rhythm and incorporate it into your practice. One technique to get over the initial hurdle of playing multiple rhythms independently is to find the composite rhythm and coordinate it between two hands (or multiple fingers.) Doing so will get your hands synchronized and at least hitting the right keys at the right time.
After that you can work at making the separate rhythms sound like independent parts. Two ways to work towards independent parts is to play each one with some contrasting element, like left hand quiet, right hand loud or left hand staccato, right hand legato. When that kind of separation is achieved you can then return to playing the expression and articulation as notated, or if improvising let your hands work like two different players.
Give this all lots of practice time! It can feel kind of weird when you first achieve independent hands. It's like there some other person controlling part of you. At least for me it felt like that. Then you try to embrace it as exactly what you are supposed to do... oh, yes, ideally you want to be able to count the beat out loud while all this rhythmic independence is going on!
Answer: Definitely a problem if ever you want to play alongside others. If everyone in a band picked their own timing then complete chaos would result.
May I suggest you practise by introducing a spoken count into your beat-boxing. So:
One ****, Two ****, Three ***, Four ****, One ****, Two ****, Three ***, Four ****, etc.
Also playing along with a metronome is a great discipline.  This is essential if you ever need to play to a click-track. These are used frequently in recordings.
A click track is a series of audio cues used to synchronize sound recordings, sometimes for synchronization to a moving image. The click track originated in early sound movies, where optical marks were made on the film to indicate precise timings for musical accompaniment. It can also serve a purpose similar to a metronome, as in the music industry, where it is often used during recording sessions and live performances
https://en.wikipedia.org/wiki/Click_track#:~:text=A%20click%20track%20is%20a%20series%20of%20audio,film%20to%20indicate%20precise%20timings%20for%20musical%20accompaniment.
If you can't follow a metronome then you can't follow a click-track.
Answer: It will bite you in the butt and hinder further development if you are ever told to improvise on an established chord progression such as the 12-bar blues. Mess up and make the initial tonic chord section more than the standard 4 bars long, and listeners may no longer treat you so kindly. Shorten the first time the IV chord is used to 1 bar long instead of 2, and risk listeners thinking that you messed up a perfectly good chord progression. Make the chord progression 11 bars long instead of 12, and listeners will notice, perhaps unfavourably.
Answer: Unless you plan to play solo and like rubato an awful, awful lot, yes you need to stay in time.
I would suggest using a metronome, beatboxing over that and then playing the piano over that.  As has been suggested, if it makes it easier, beatbox into a looping pedal.
If you can't play in time, few people will want to play with you. In our band, having to set tempo for a band member who can't play in time is called "hauling the train." Because it's that exhausting.
James Brown explains it best. For most music, all instruments are drums.

But if you have good time and apply your beatbox rhythms to your piano playing you will be very much in demand.


Why is this an essential singularity?

Question: I have the following complex function: $$f(z)=\frac{\cos\left(\frac{\pi z}{2}\right)\sin\left(\frac{1}{z}\right)}{(z^2-1)(z-2)}$$
I kind of shown that $z=\pm 1$ and $z =2$ are simple poles. However I don't know how to show that $z=0$ is an essential singularity. How do I even find the Laurent series of $sin\left(\frac{1}{z}\right)$ around $0$?
I know started from the Taylor expansion $$\sin(z)=\sum_{n=0}^{\infty}\frac{(-1)^kz^{2k+1}}{(2k+1)!}$$ and then I wrote it for $\sin\left(\frac{1}{z}\right)$ $$\sin\left(\frac{1}{z}\right)=\sum_{n=0}^{\infty}\frac{(-1)^k}{(2k+1)!z^{2k+1}}$$ but then I don't know how to find the Laurent series of it, shouldn't it be from $-\infty$ to $\infty$? All I can do here seems to be $$\sin\left(\frac{1}{z}\right)=\sum_{n=0}^{\infty}\frac{(-1)^kz^{-(2k+1)}}{(2k+1)!}$$ which has negative exponents only?
Can you help me?
Comment: If $f(z) = \sum_{n=-\infty}^0 a_n z^n$ then we can also write $f(z) = \sum_{n=-\infty}^\infty a_n z^n$ where $a_1=a_2=a_3=\ldots = 0$. Thus if you only find negative exponents this just means that all the positive are zero.
Comment: @Winther, that makes sense.
Answer: $z = 0$ is an essential singularity because if you develop the function
$$\sin \frac{1}{z}$$
In powers of $z$, then ALL the terms show a pole at $z = 0$, and there is no way to remove them.
Hence it's indeed essential.
P.s. The Lurent series of $\sin$ is the actual Taylor series.
Comment: So what is the difference between a Laurent series and a Taylor series? Cause I thought the first was an extension of the second, including negative powers! But in this case there is no positive power at all, is there?
Comment: So in general how does someone say that a function has an essential singularity? Do you have to look at the Taylor/Laurent series and see where it is not defined?
Comment: @Euler_SalterWell the Taylor series only work when your function is holomorphic, the Laurent series works still for isolated singularities.

When your $f(z)$ is holomorphic the Taylor series and the Laurent series are the same, and with Cauchy's theorem you can see that. If you want to be as good as possible you have to calculate those things on your own! ^^
Comment: @Euler_Salter Yes, that is the point. Laurent Series (or Taylor's) will tell you everything about a singularity.

Take $f(z) = e^{1/z}$. Can you see why $z = 0$ is an essential singularity?
Comment: well we should have $f(z) =  e^{z^-1}= \sum_{n=0}^{\infty} \frac{(z^{-1})^n}{n!} =  \sum_{n=0}^{\infty} \frac{1}{n!z^n}$? Okay maybe I understand. So this is again an essential singularity because at every term we have that the element of the series is undefined at $z=0$?
Comment: So does it mean that we will never have an essential singularity for a function of the type $f(z) = \frac{1}{P(z)}$ where $P(z)$ is a polynomial?
Comment: @Euler_Salter Yes, essential singularities occur when all your terms provide a function which is infinite at that point. It's not like $\sin(x)/x$ where $x = 0$ is a removable singularity.
Comment: @Euler_Salter When you have a polynomial, you can always search for it's range of convergence and use Geometric Series to find eventual poles, removable singularities or whatever. Consider that you cannot use Taylor / Laurent series for polynomial because they are their same expansion. If you try to expand a Polynomial in series, you get the exact polynomial you started with.
Comment: @Euler_Salter Look at this, for example: http://math.stackexchange.com/questions/360215/difference-between-the-laurent-and-taylor-series
Comment: thank you! But then I have another doubt, how do I recognise a simple pole from a removable singularity?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/50061/discussion-between-euler-salter-and-alan-turing).
Answer: Since
$$
g(z)=\frac{\cos(\pi z/2)}{(z^2-1)(z-2)}
$$
is holomorphic in a neighborhood of $0$ and $g(0)=1/2$, this factor can be removed for discussing the singularity at $0$ of $f$. Thus we remain with
$$
h(z)=\sin\frac{1}{z}
$$
which is certainly holomorphic in $0<|z|<1$, so $0$ is an isolated singularity. It is not removable, so it is either essential or a pole. If the latter, there should exist a positive integer $n$ such that
$$
\lim_{z\to0}z^n\sin\frac{1}{z}
$$
exists (finite) and is not $0$.
However, if we approach $0$ along the real axis, we have
$$
\lim_{x\to0}x^n\sin\frac{1}{x}=0
$$
for every positive integer $n$. Hence the singularity is essential.

For the singularity at $1$, you should consider
$$
\lim_{z\to1}\frac{\cos(\pi z/2)}{z-1}=
\lim_{w\to0}\frac{\cos(\frac{\pi}{2}-w)}{-\frac{2w}{\pi}}=
\lim_{w\to0}-\frac{\pi}{2}\frac{\sin w}{w}=-\frac{\pi}{2}
$$
so $1$ is a removable singularity for $f$ and the same for $-1$.
If you want to see a different approach, let's look at $z=-1$. Granted that
$$
\frac{1}{(z-1)(z-2)}\sin\frac{1}{z}
$$
is holomorphic in a neighborhood of $-1$, we need to consider
$$
g(z)=\frac{\cos(\pi z/2)}{z+1}
$$
of which we want to find the Laurent series at $-1$; setting $z+1=w$, we have
$$
\cos\left(\frac{\pi}{2}w+\frac{\pi}{2}\right)=-\sin\frac{\pi w}{2}
$$
so
$$
-\frac{1}{w}\sin\frac{\pi w}{2}=
-\frac{1}{w}\left(\frac{\pi}{2}w-
  \frac{\pi^3}{2^3\cdot 3!}w^3+\dotsb\right)=
-\frac{\pi}{2}+\frac{\pi^3}{48}w^2+\dotsb
$$
so the singularity is removable.
Comment: first of all thank you for the long answer! Secondly, I have some questions: how did you deduce a priori that $z=0$ was not removable?
Comment: @Euler_Salter Since $\lim_{x\to0}\sin\frac{1}{x}$ doesn't exist even on the real line…
Comment: probably all these questions sound stupid, but I think I am not understanding the correlation between $\lim_{x\to 0} \sin\left(\frac{1}{z}\right)$ not existing and the singularity being not removable. The definition I found in the book of removable singularity is when there are no negative powers of $(z-a)$ which in this case is $z$
Comment: @Euler_Salter The function $f$, holomorphic in $0<|z-a|<r$, has a removable singularity at $a$ if and only if $\lim_{z\to a}f(z)$ exists (finite).
Comment: okay I didn't know it. I know I am asking you a lot, but can you expand on why there exists $n$ etc.. ? Are you calling $n$ the order of the pole?
Comment: @Euler_Salter Yes, of course.
Comment: and for the singularity at $z=1$, why do you consider the fraction with cosine at the numerator, and not only $\frac{1}{z-1}$?
Comment: @Euler_Salter Because at $z=1$, $\cos(\pi z/2)=0$.
Comment: true. But I thought that we looked at singularities where the function is not defined. But $\cos(\pi z\2)$ is defined at $z=1$, whereas $\frac{1}{z-1}$ is not
Comment: Is it correct to say that $\frac{\cos(\frac{\pi z}{2})}{z+1}$ has a rem. sing. at $z=-1$ because $\frac{\cos(\frac{\pi z}{2})}{z+1} = \sum_{n=0}^{\infty}(-z)^n \sum_{n=0}^{\infty} \frac{(-1)^k(\frac{\pi z}{2})^{2k}}{(2k)!} = \sum_{n=0}^{\infty} \frac{z^{3k}\pi^{2k}}{2^{2k}(2k)!}$  has no negative powers?
Comment: @Euler_Salter I added a different approach for $z=-1$, I hope you'll be OK now; however, the computation with limits is very similar to that with power series and can be easier.
Comment: Another way to see that $\sin(1/z)$ has an essential singularity at $0$ is to notice that it vanishes at certain points arbitrarily close to $0$, namely at $z=1/(\pi n)$ for all natural numbers $n$. That can't happen at a pole, because a function with a pole tends to $\infty$ there. And if it happens at a removable singluarity, then the function has to be identically $0$, which $\sin(1/z)$ isn't. So the only possibility left for the isolated singularity at $0$  is an esential singularity.

Why is this an essential singularity?


QSqlTableModel.insertRecord() is very slow

Question: I am using PyQt to insert records into a MySQL database. the code basically looks like
self.table = QSqlTableModel()
self.table.setTable('mytable')
while True:
  rec = self.table.record()
  values = getValueDictionary()
  for k,v in values.items():
    rec.setValue(k,QVariant(v))
  self.table.insertRecord(-1,rec)

The table currently has ~ 50,000 rows in it.
I have timed each line and found that the insertRecord function is taking ~5 seconds to execute, which is unacceptably slow. Everything else is fast.
For comparison, I also made a version of the code that uses
QSqlQuery.prepare("INSERT INTO mytable (f1,f2,...) VALUES (:f1, :f2,...)")
query.bindValue(":f1",blah)
query.exec_()

In this case, the whole thing takes only ~ 20 milliseconds, so the delay is not in the database connection as far as I can tell.
I'd really prefer to use the QtSql stuff instead of the awkward MySQL commands. Any ideas on how to add a bunch of rows to a MySQL database with QtSql instead of raw comands and with reasonable speed?
Thanks,
G
Answer: Things to try:

set your EditStrategy to QSqlTableModel.OnManualSubmit
mass insert rows with insertRows

and see if it helps...
Answer: you should use begin before and commit after the loop, or turn off the autocommit feature from MySQL ..
this will give you usually a performance increase of 50% or more ..


Meaning of latent features?

Question: I'm trying to understand matrix factorization models for recommender systems and I always read 'latent features', but what does that mean? I know what a feature means for a training dataset but I'm not able to understand the idea of latent features. Every paper on the topic I can find is just too shallow.
Edit:
if you at least can point me to some papers that explain the idea.
Comment: Here is simple example that might help you http://www.quuxlabs.com/blog/2010/09/matrix-factorization-a-simple-tutorial-and-implementation-in-python/
Answer: Latent means not directly observable. The common use of the term in PCA and Factor Analysis is to reduce dimension of a large number of directly observable features into a smaller set of indirectly observable features.
Comment: @JackTwain the correct PCA analogy is that the latent features are the eigenvectors. The principal components are the weights assigned to each observation for the principal eigenvectors. In other matrix factorisation models the latent features play the role of the eigenvectors. This may sound pedantic, but the mistake creates no end of confusion for people.
Comment: so the reduced dimensions are then the latent features? In the case of PCA, the eigen vectors of the covariance matrix, i.e the principal components, right?
Comment: Correct @AlexTwain
Comment: Can you provide me with a tutorial/paper that mentions that? I'm not able to find any systematic tutorial/paper!
Comment: Well the wiki page is pretty good, you can follow the references there if you really want http://en.wikipedia.org/wiki/Latent_variable
Answer: In the context of Factorization Method latent features are usually meant to characterize items along each dimension. Let me explain by example.
Suppose we have a matrix of item-users interactions $R$. The model assumption in Matrix Factorization methods is that each cell $R_{ui}$ of this matrix is generated by, for example, $p_u^T q_i$ — a dot product between latent vector $p_u$, describing user $u$ and a latent vector $q_i$, describing item $i$. Intuitively, this product measures how similar these vectors are. During training you want to find "good" vectors, such that the approximation error is minimized.
One may think that these latent features are meaningful, that is, there's a feature in user's vector $p_u$ like "likes items with property X" and corresponding feature in item's vector $q_i$ like "has property X". Unfortunately, unless it's somehow enforced, it's hard to find interpretable latent features. So, you can think of latent features that way, but not use these features to reason about the data.
Comment: I've read papers where the latent features (say the "user vector") are used to predict some target variable(s), let's use gender as an example. It "works" in that a predictive model can be built this way. My question is what is the difference between the "user vector" and, say, averaging the "item vectors" for all the items a user has "visited"? IOW, would you expect the predictive model mentioned above to be better or worse with one vs the other? Thanks (if you ever see this).
Comment: @thecity2, you can average user's items, and this might actually be useful when you're dealing with newcomers for whom you don't have precomputed user vectors (though it should be hard to run a few optimization iterations to compute it). There's also an issue with plain averaging: the more items user has consumed – the closer to zero their average item vector is likely to be (because of typical L2 regularizer, and maybe other nasty properties of high-dimensional spaces). Finally, having a separate vector is more flexible: your model can learn such averaging.
Comment: That said, there're attempts to use user's history to model user's vector. For example see the paper "Build Your Own Music Recommender by Modeling Internet Radio Streams"
Answer: Here your data is ratings given by various users to various movies. As others have pointed out, latent means not directly observable.
For a movie, its latent features determine the amount of action, romance, story-line, a famous actor, etc. Similarly, for another dataset consisting of handwritten digits, the latent variables may be angle of edges, skew, etc.
Answer: I would say that factors are more representative than principal components to get a perception of 'latency'/hiddenness of a variable. Latency is one of the reasons why behavioral scientists measure perceptual constructs like feeling, sadness in terms of multiple items/measures and derive a number for such hidden variables which cannot be directly measured.

Meaning of latent features?