Basic function manipulation and simplification question for $f((x-f(x))^2)$

Question: I've run into a bit of a wall trying to understand why the following two equations are equivalent:
$$f((x-f(x))^2) = f(x^2)-f(x)^2$$
I'm running into this with calculating population variance in statistics, which is an area I understand, but I'm just not seeing the math here. I know at least for this application these two equations are equivalent, but am not familiar enough with function manipulation to see the logic behind it. The farthest I get is to go ahead and square the first function to get the following:
$$f(x^2-2xf(x)+f(x)^2)$$
...how do you continue to manipulate the terms and result in $f(x^2)-f(x)^2$?
Comment: That won't hold for most arbitrary functions. Can you give us more information about $f$, what it's supposed to represent, or a formula if there is one?
Answer: Just a guess, but perhaps $f$ is the expectation operator and $x$ is a random variable? If you're trying to understand why
$$E[(X-E(X))^2] = E(X^2)-E(X)^2\;,$$
then this post might help. Another derivation can be found here.
Comment: Since random variables are functions, the expectation operator is a function that acts on functions! You should think of it as an operation similar to integration. It's the linearity properties of integration that we are using to justify the derivation (and the same rules of integration have to be followed in stats, so stats isn't special :)
Comment: Ok, so I'm making a mistake in assuming that the expectation operator E(x) is similar to any function f(x)? I was thinking they both act on an "x" domain and are therefore functions of x, in this case E(x) being the integral of x*f(x) where f(x) is a probability density function. Since this ultimately puts the concepts in the form of f(x), g(x), etc., I was thinking this generalized them to be true for all functions...unless stats is special.


What does the music notation "/ / / /" mean in a music drum score?

Question: I have a drum score sheet music with 4/4 time signature in which the following portion is present.
.

Now, I am unable to understand the symbols in the bar:

Also, what to repeat for the second Repeat 1 bar?

P.S.

I have removed the actual score to avoid copyright violation.
Please also note the bar numbers.
The actual sheet music is from this link: http://www.drumeo.com/blog/break-sticks-play-along/
Comment: This is fine, but for future reference you shouldn't need to blank anything out when the excerpt is just a few bars.  Given that this is for educational and analytical purposes, and you've sourced it, it falls well within Fair Use.
Comment: The 4 slashes represent Free Fills or Solos
Comment: There should be a legend defining the meaning of each of symbols.
Comment: @davidstrachan: Okay the actual sheet music is from this link: http://www.drumeo.com/blog/break-sticks-play-along/
Answer:
Counting Verse 1 from bar 5. Bar 5 & 6 are repeated 7 times to lead to bar 21. = 16 bars
Bar 21 is repeated 6 times Then  the 4 slashes / are played  solo or freeform = 8 bars.
These 8 bars are then repeated to come to bar 37
Comment: That's the only possibility. But I don't agree with the strange notations for the two repetitions. Is this the standard way to do so?
Comment: I have not seen this before, but I assume the author's software has no function for repeat signs and is just using text instead.
Answer: I'm just going to keep it really simple: The measure in question is to be played 'free' or 'fill'. You can do whatever feels right musically to you, then continue on as you were playing before.


Getting Drupal to work with Mercury Mail Server on Local Machine

Question: I've successfully set up Mercury Mail Server on my local machine using the XAMPP stack to send mail through a remote SMTP Server by following the configuration directions posted at:
https://www.zoe.vc/2008/mercury-mail-transport-system-fur-externe-mail-konfigurieren/
If mail is sent to either local or external email addresses via a regular mail client, e.g. Thunderbird, Mercury Mail processes the mail appropriately and the mail arrives in the expected mail boxes.
However, sending mail through my local Drupal 7 site does not work.

For example, the site includes a set of rules built with the Rules module that are configured to send mail to a set of email address when triggered.
Drupal reports that it successfully sends mail to the targeted addresses when the rules are fired.
But Mercury Mail doesn't show any evidence that the mail is being processed -- and the mail never shows up in at the addressed mailboxes.

In summary, mail from Drupal is not getting to the server, but Drupal thinks that it has been successfully sent.  Note, as per the directions from zoe.vc, the [mail function] configuration in php.ini is setup as:
<code>[mail function]
; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury
SMTP = localhost
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = email@example.com

; XAMPP IMPORTANT NOTE (1): If XAMPP is installed in a base directory with spaces (e.g. c:\program filesC:\xampp) fakemail and mailtodisk do not work correctly.
; XAMPP IMPORTANT NOTE (2): In this case please copy the sendmail or mailtodisk folder in your root folder (e.g. C:\sendmail) and use this for sendmail_path.

; XAMPP: Comment out this if you want to work with fakemail for forwarding to your mailbox (sendmail.exe in the sendmail folder)
;sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

; XAMPP: Comment out this if you want to work with mailToDisk, It writes all mails in the C:\xampp\mailoutput folder
sendmail_path = "C:\xampp\mailtodisk\mailtodisk.exe"

; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =

; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header = Off

; Log all mail() calls including the full path of the script, line #, to address and headers
;mail.log = "C:\xampp\php\logs\php_mail.log"
</code>
I've spent countless hours trying to figure this one out.  Any help getting this to work via   drupal so that I can continue development will be greatly appreciated. Thanks in advance.
Answer: When I used to test sending mail from a localhost (I don't remember the mail server program though), I used to use the SMTP Authentication Support module for its configuration.

This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.
Comment: Thank you for pointing this out. I installed and enabled the module. The local Drupal site can now send mail to the local Mercury Mail Server.  Alternatively, could have used the module to communicate with an external SMTP server without using the MMS at all. Thanks.


Mudar de form em forms

Question: Bom dia,
Eu gostaria de saber como posso mudar de formulario para outro formulario em c#, eu tentei porém ficam tanto o antigo como o novo a aparecer.
new form1().Show();

Answer: Bom dia os meus dias de c# já lá vão mas penso que esta seja a resposta:
new nomedonovoforms().Show();
this.Hide();

Comment: Consegui Agradeço

Mudar de form em forms


I updated silverlight and now VS 2010 won't load Silverlight project

Question: I updated Silverlight because IE was continuously bugging me to update it to new version. And so I did. But after doing it my silvelright application gives me this message:

When I click this link and try to install Silverlight Developer runtime, it says its already installed. What do I do now?
Answer: Let's try restarting in a clean boot, uninstalling Silverlight, checking program files to make sure there is no Silverlight folder, run Windows Installer CleanUp Utility, and then download Silverlight.
Here is the step by step process May be it'll help you.


How many treble keys should I have for accordion? - Additional question

Question: I have asked a similar question yesterday. Thanks so much for the answers.
I am a beginner for accordion (have some knowledge on Electronic Organ, and 63 years old now). Particularly, I see a trade-off in selecting whether 26 or 34 treble keys? My friend told me no big difference between them in playing songs, and the 26-key one is smaller and lighter. But I think it has 8 keys (4 white and 4 black) less than the 34-key one. And I am concerning about due to 4 white keys less, the 26-key accordion covers a narrow note range, so it can't play as many music/songs as a 34-key accordion does, which is different to what my friend said. Appreciated if you could give some more advices on my concern, so that I know which one I should buy.
Thanks,
Steve.
Comment: Your previous question already has answers covering your exact query here. Please read existing answers before writing new questions
Comment: Also, instead of writing thanks under good answers, please just use the upvote button - it's worthwhile reading our [about] page to understand how this site works.
Answer: I don't know which accordion you are looking at, but the 26-key accordions that I see online tend to start at B below middle C. I would find that annoying, but I could transpose to fit (I make my own sheet music). I think a lot of music would have to be adjusted, though, because it's common to go a little lower than that. Going down to G below middle C is common in the music I've seen.
This all depends on how comfortable you are adjusting music to your needs. You could play any song after making adjustments to it by transposing or adapting.
As a beginner, changing a song to fit might be difficult for you. Perhaps a friend or teacher could help, though?


Hadoop namenode needs to be formatted after every computer start

Question: I have searched for this problem and while there are a number of similar examples I can't find a common solution or one that works for me. I have installed Hadoop and am running in pseudo distributed mode. It works fine, and I can start and stop it a number of times and get it running fine. However, if I re-start the computer and start Hadoop the namenode doesn't start. I need to format it every time, which means I lose all the work I have done and need to start again.
I am following Hadoop: The Definitive Guide v3.
My core-site.xml says:
<configuration>
    <property>
        <name>fs.default.name</name>
        <value>hdfs://localhost/</value>
    </property>
</configuration>

My hdfs-site.xml says:
<configuration>
    <property>
        <name>dfs.replication</name>
        <value>1</value>
    </property>
</configuration>

Is there a way of configuring Hadoop so that I don't need to re-format the namenode every time I restart the computer?
Thanks.
Answer: Looks like you are not overriding the hdfs configurations dfs.name.dir , dfs.data.dir, by default it points to /tmp directory which will be cleared when your machine restarts. You have to change this from /tmp to another location in your home directory by overriding these values in your hdfs-site.xml file located in your HADOOP configuration directory.
Do the following steps
Create a directory in your home directory for keeping namenode image & datanode blocks (Replace with your login name)
mkdir /home/<USER>/pseudo/

Modify your hdfs-site.xml file in your HADOOP_CONF_DIR(hadoop configuration direcotry) as follows
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property>
  <name>dfs.name.dir</name>
  <value>file:///home/<USER>/pseudo/dfs/name</value>
</property>
<property>
  <name>dfs.data.dir</name>
  <value>file:///home/<USER>/pseudo/dfs/data</value>
</property>
<property>
    <name>dfs.replication</name>
    <value>1</value>
</property>

</configuration>

Format your hdfs namenode & start using
Comment: B/w, no need to create the directory. The directory will be created automatically during 'hdfs namenode -format'
Comment: Cool. I remember, earlier hadoop versions 0.20, we had to manually create directory. In latest version hadoop community added automatic directory creation feature. Thanks for the comment !!


how to redirect another page with select list value on button click in oracle apex?

Question: i have select list values.after any change in select list and click on Button (it have to redirect the page number i have mentioned with select list value changed).
what i have done so far.
take another item P213_CLASS_TYPE_VAL
create DA on select list
Select :P213_CLASS_TYPE into :P213_CLASS_TYPE_VAL from dual;
item to submit : P213_CLASS_TYPE,P213_CLASS_TYPE_VAL
item to return : P213_CLASS_TYPE_VAL;

Button Action: Redirect to Page in this Application
Page 218
Set Item
Name                   Value
P218_GET_CLASS_TYPE    &P213_CLASS_TYPE_VAL.

the issue we face is, some it redirect with changed item value and some time redirect with previous item value
Answer: You don't need a dynamic action to redirect to another page, that is a common mistake and unnecessarily complicates things.
The easiest way to do this is to have the button submit the page and create a branch to page 218 where you pass the value of P213_CLASS_TYPE_VAL.
On page 213: Button with action: "Submit Page"
On page 213:
Branch to page 218 with:

Server-side condition: "When Button Pressed" = your button.
Behavior: Page or URL(Redirect), page 281 and Set Items P218_GET_CLASS_TYPE to &P213_CLASS_TYPE_VAL.

That's all there is to it.
Comment: When you use a DA to pass data to another page the values never reach the session. But when you submit the form, the data is sent it to the session. You can validate the session using the button located in the bottom bar.


Como buscar todas as associações em uma árvores de relacionamentos no Laravel?

Question: Estou tendo um dilema.
Tenho tabelas que se relacionam, tipo:
internal_clients->subsidiaries->departments->job_titles->users
Tenho também seus Respectivos models.
Minha dúvida é:
Como faço para pegar todos os dados associados aos users desde o topo da cadeia (internal_clients) ?
Estou tentando seguir a documentação do Laravel utilizando o hasManyThrough.
Porém na doc explica somente a forma de se fazer em uma cadeia de 3 tabelas. Ensinam a colocar uma tabela (model) intermediária como segundo parâmetro do método hasManyThrough(ClasseBase::class, ClasseIntermediaria:class).
Porém, no meu caso que tem várias tabelas entre users e internal_clients, como eu faria isso ? Qual seria a tabela intermediária ?
Eu gostaria de fazer uma consulta que retornasse qual o internal_client, subsidiary, department e jobTitle do user (associados aos users).
Estou tentando fazer dessa forma:
Model InternalClient
public function users()
 {
    return $this->hasManyThrough(User::class, InternalClient::class);
 }

Controller UserController
 public function allRelations($internalClientId)
 {
     $internalClient = InternalClient::find($internalClientId);

      $users = $internalClient->users;

      return response()->json($users, 201);
 }

O id da InternalClient chega no controller acima.

Quando eu acesso a rota, me é retornado o erro abaixo:

Resumindo: Gostaria de saber se existe uma forma de pegar todos os dados (de todas as tabelas que estão nessa árvore hierárquica) que estão associados ao Usuário.
Obrigado!
Comment: É difícil te ajudar sem entender primeiro a lógica dos relacionamentos, porque o que vc está tentando fazer no seu código é pegar todos os `internal_clients` que se relacionam com `users`. De uma forma geral, dada sua estrutura relacional, a melhor opção seja usar `join` mesmo
Comment: Estou tentando fazer uma lógica mais ou menos assim: https://paste.laravel.io/fa0089c6-7e18-415e-8f63-f86af867d324
Comment: `$internalClients->departments->sections->jobTitles->users` da a entender que **internalClients** tem um **departments** que tem um **sections** que tem um **jobTitles** que pode ter vários **users**, seria a única forma disso funcionar
Comment: Se sua realidade não igua à acida vc vai precisar fazer **join** mesmo https://laravel.com/docs/7.x/queries#joins
Comment: Na verdade seria: "interbalClients" pode ter vários "departments" que pode ter vários "sections" que pode ter vários "jobTitles" e que pode ter vários "users". Como vc colocou negrito no comentário ?  ?
Comment: Então sua melhor alternativa é realmente usar **Join**
Comment: E with ? Me recomendaram fazer com with e está me parecendo ficar um código mais limpo.
Answer: O problema é que você está tentando acessar vários níveis de relacionamento usando o hasManyThrough, que na verdade somente consegue relacionar através "trough" um único subnível. Veja que p erro está informando que não existe id fk na tabela internal client, quando na verdade, por esta linha que você postou internal_clients->subsidiaries->departments->job_titles->users, parece-me que o relacionamento (fk) está em job_titles.
Com o que você postou de informações, abstraindo os modelo de dados mentalmente, eu diria que você consegue um relacionamento do tipo hasManyTrough apenas em departments usando job_title.
Então realmente terá que ir de join entre as várias tabelas que se ligam de internal_clientes até users.
Mas faz assim, cria um método no modelo de internal_clients que monte um scope para que vc possa utilizar:
function scopeUsers($query) {
    return $query->join("subsidiaries", "fk-de-subsidiaries-em-internal-clients", "=", "pk-em-subsidiaries")
                 ->join("departments", "fk-de-departments-em-subsidiaries", "=", "pk-em-departments")
                 ->join("job_titles", "fk-de-job_titles-em-departments", "=", "pk-em-job_titles")
                 ->join("users", "fk-de-users-em-job_titles", "=", "pk-em-job_titles");
}

Pode ser que não esteja 100% aderente ao seu modelo pois você não o postou aqui.
Para verificar a documentação sobre o Joins - https://laravel.com/docs/7.x/queries#joins
Para verificar a documentação sobre escopos (scopes) - https://laravel.com/docs/7.x/eloquent#query-scopes
Comment: Estou seguindo um conselho aqui de utilizar o with(). Parece que está dando certo até agora. Estou terminando pra ver, Ademir.
Comment: Se solucionar de forma diferente, poste sua resposta para que outros possam decidir a melhor solução em situações semelhantes, valeu
Answer: Tentei fazer com with. Porém retornava toda a cadeia de relacionamentos. Veja:
public function allRelations($internalClientId)
{
   $internalClients = InternalClient::with('departments.sections.jobTitles.users')->find($internalClientId);
   return response()->json($internalClients , 201);
}

O retorno era esse:
https://paste.laravel.io/b3c80b26-f37f-4e56-9f60-5535379f73d9
Então tentei fazer com os Joins, conforme a resposta do outro rapaz (Por isso vou aceitá-la). Veja:
public function allRelations($internalClientId)
{
     $internalClients = InternalClient::join('departments', 'departments.internal_client_id','=','internal_client_id')
     ->join('sections', 'sections.department_id','=','departments.id')
     ->join('job_titles', 'job_titles.section_id','=','sections.id')
     ->join('users', 'users.job_title_id','=','job_titles.id')
     ->select(
              'users.id AS user_id',
              'users.name AS user_name',
              'users.surname AS user_surname',
              'users.email AS user_email',
              'departments.id AS department_id' ,
              'departments.name AS department_name',
              'sections.id AS section_id',
              'sections.name AS section_name',
              'job_titles.id AS job_title_id',
              'job_titles.name AS job_title_name'
              )
      ->where('internal_client_id',$internalClientId)
      ->groupBy('users.id')
      ->get();

       return response()->json($internalClients, 201);
}

E a saída foi essa:
[
  {
    "user_id": 1,
    "user_name": "GLEISIANE",
    "user_surname": "ROUCAS",
    "user_email": "firstname.lastname@example.com",
    "department_id": 2,
    "department_name": "FISCAL",
    "section_id": 1,
    "section_name": "CONTABIL - SETOR 1",
    "job_title_id": 1,
    "job_title_name": "AUXILIAR CONTÁBIL"
  },
  {
    "user_id": 2,
    "user_name": "ANDREWS",
    "user_surname": "RIBEIRO",
    "user_email": "firstname.lastname@example.com",
    "department_id": 2,
    "department_name": "FISCAL",
    "section_id": 1,
    "section_name": "CONTABIL - SETOR 1",
    "job_title_id": 1,
    "job_title_name": "AUXILIAR CONTÁBIL"
  }
]

Queria fazer com o with, sei que dá, mas infelizmente não consegui. Então resolvi fazer logo com o Join para não atrasar o trabalho.


Como usar "while not in" no Python?

Question: Eu tentei fazer um loop com o while para verificar se uma condição foi satisfeita. Se o usuário digitar 0, 1 ou 2 o programa deveria parar de perguntar ao usuário qual número ele vai escolher. Caso o usuário escolha um número diferente de 0, 1 ou 2, o programa irá perguntar para o usuário qual número ele quer escolher.
lista = [0, 1, 2]
usuario =''
while usuario not in lista:
    usuario = input('Escolha um número entre 0 e 2: ')

O comportamento que eu observei não foi o que eu esperava. Ao invés do programa parar de pedir para o usuário escolher um número quando ele digitar um número contido na lista, ele continuou a pedir para o usuário escolher um número. Eu achei que se o usuário escolhesse um número da lista o programa deveria parar. Alguém sabe dizer onde estou errando?
Também tentei fazer esse loop desta forma, mas tive o mesmo problema:
lista = [0, 1, 2]
usuario =''
while usuario != lista:
    usuario = input('Escolha um número entre 0 e 2: ')

P.S: Estou usando um Windows 7; Python 3.6.5 e o PyCharm.
Answer: O erro é que a função input sempre retorna um texto e você está verificando se um texto pertence a uma lista de inteiros. Esta condição jamais será satisfeita.
print('1' in [0, 1, 2])  # False

Se você quer verificar se um inteiro pertence a uma lista de inteiros, precisa fazer a conversão:
while usuario not in lista:
    usuario = int(input('Escolha um número entre 0 e 2: '))

Assim, usuario também será um inteiro e quando o usuário entrar com um valor da lista, a condição será satisfeita.
Como comentado, isso pode gerar uma exceção ValueError caso o usuário entrar com algo que não seja um número. Para prevenir isso, basta utilizar o try/except:
while usuario not in lista:
    try:
        usuario = int(input('Escolha um número entre 0 e 2: '))
    except ValueError:
        print('Por favor, entre com um número')

Ainda, se o objetivo é apenas fazer a leitura de um valor entre 0 e 2, você não precisa definir uma lista para isso, basta fazer a condição 0 <= usuario <= 2. Por exemplo:
while True
    try:
        usuario = int(input('Escolha um número entre 0 e 2: '))
        if not 0 <= usuario <= 2:
            raise ValueError('Número deve estar entre 0 e 2')
        break
    except ValueError as error:
        print(error)

Comment: Era isso mesmo, obrigada.
Answer: Uma solução simples, e que evita os erros já mencionados como ValueError no caso de tentar converter um caracter não numerico para int, seria validar se o input é um digito, ou seja, se o que o usuário digitou converte para inteiro.
lista = [0, 1, 2]

while True:
    usuario = input('Escolha um número entre 0 e 2: ')
    if usuario.isdigit() and int(usuario) in lista:
        break

Comment: É uma boa solução também. Neste caso, `usuario` ficaria sendo uma *string*, o que dependendo do problema pode ser interessante.
Comment: Sim, sim... Mas até ai é tranquilo né, uma vez validado que é digito, em seguida ja pode fazer a conversão sem medo de ser feliz.
Comment: Pode ser até reduzido para `if int(usuario) in lista: ...`, visto que pela pergunta e a resposta aceite do Anderson não ser preciso que tratar/prevenir exceções devido ao input poder ser letras
Answer: O problema é que usuario vai voltar como uma string, tenta escrever
 while usuario not in lista:
      usuario = input('Escolha um número entre 0 e 2: ')
      if(regex(usuario)
           usuario = int(usuario)
      else
         print('Digite um Numero')

Comment: é, isso vai acontencer sempre que o usuario digitar algo que não é passivel de conversão para um inteiro, como uma letra ou um espaço vazio. Uma solução é usar uma expressão regular para ver se o input é um numero.
Comment: Eu tentei isso, mas ele retorna um erro: "ValueError: invalid literal for int() with base 10: ' '"

Como usar "while not in" no Python?


How to make people interested in what we're teaching?

Question: I've seen so many music teachers just give theory lessons and then have the student practice the ideas on their instrument. I think – with a lot of people want to study music like guitars, pianos these days – seems too... boring.
For example: A classical guitarist student (which age is 10) is getting bored because the teacher is always giving the student theory lessons and practicing a new song every meeting.
So, how can a teacher make them not bored and teach them the theory and technique for their instrument and how would a teacher help their student enjoy what they're learning?
Comment: I voted for this as the answer is primarily opinion-based.  This type of question is not new and if the answer to it were simple, the education system would be vastly different than what it is today.  In part, students and culture change with time, so the answers we create and our roles as teachers must also change through necessity of preservation.
Comment: I didn't teach classical guitar, but I did teach both acoustic and electric guitar lessons and I found the students were most interested when I asked them to bring in songs they liked and worked through those with them. It might be different with classical, but for pop and rock my students practiced a lot when learning their favorite songs. Then you can work in some theory related to the songs they already like.
Answer: In general, you should find out what the student wants from the lessons and tailor your teaching to what they want from lessons. Teaching all students the exact same way tends to be counterproductive.
If they are very serious about creating their own music, encourage improvisation as much as possible and reinforce it by showing the theory behind what they play and show them how analysis can be applied to any piece to help them create music. If a student just wants to play their instrument as a hobby, see what artist/composers they like and help them understand what's going on and the musical ideas behind them. If a student is serious about playing their instrument and wants to play professionally or attend music school for their instrument, show them what they need to know and explain how it will help them prepare for the future with some examples of how techniques and ideas are used.
If you know what they want from lessons you can do a lot to keep them interested in their lessons and you can teach them a lot easier. If they are being forced to take lessons, there really is not much you can do. You can try and make it fun for them, but unless they want to learn it is rather hard to keep them interested.
Another thing to note is even the most eager student can get "burned out" of lessons. If you know a student is starting to not practice as much as they normally do, it may be time to adjust their lessons and take them in a different direction for a little bit to rekindle their interest in lessons. Either focusing on a different topic or approaching a topic a different way can help a lot refocus the student to their lessons.


How can I reconstruct a network so that it maintains the same attributes and same shape but the nodes are in different locations?

Question: I currently have a network that is similar in node count and edge count to the following:
 set.seed(12)
 net <- sample_gnp(20, 1/4)
 V(net)$a <- sample(c(0, 1), vcount(net), replace = TRUE, prob = c(0.3, 0.7))
 V(net)$b <- sample(c(0, 1), vcount(net), replace = TRUE, prob = c(0.5, 0.5))
 V(net)$color <- V(net)$a + 4
 plot(net)

This creates a distinct network with a unique shape. Is there a way that I can only move the 20 nodes in this network randomly and maintain the shape? I want the network to look the same visually but with different nodes (node A at coordinate (a, b) is replaced by node G and they have the same number of edges). So ideally I want the graph to make a change like the following: (Same proportion of yellow to blue nodes but you can tell that they've moved around while simultaneously maintaining the shape)
Comment: Not sure what you are looking for. Would it work for you to get all nodes and edges at the same place, but different labels on the nodes?
Comment: @G5W, I want to keep the nodes and edges at the same place but all the attribute values are randomly reassigned (I want the attributes to stick together for this so all the attributes for node A will remain together as a group and the new node that gains these values will be exactly like node A just in a different position)
Comment: @G5W I edited my question to better demonstrate what I was trying to do.
Answer: The idea is to add the layout as additional node attributes, which are kept constant.
  l <- layout_nicely(net)
  V(net)$x <- l[,1]
  V(net)$y <- l[,2]

The other attributes are reshuffled following the same pattern in order to keep the attribute bundle intact.
  pattern <- sample(1:vcount(net))
  net2 <- net
  V(net2)$a <- V(net2)$a[pattern]
  V(net2)$b <- V(net2)$b[pattern]
  V(net2)$color <- V(net2)$color[pattern]

Now if you plot the result, you will hopefully end up with the desired output.
  par(mfrow = c(1,2))
  plot(net)
  plot(net2)

Answer: I am not sure what you are looking for, but here are a couple of other options.
Rotate the graph
LO = layout_nicely(net)

LO2 = LO
alpha=pi/4
LO2[,1] =  cos(alpha)*LO[,1] + sin(alpha)*LO[,2]
LO2[,2] = -sin(alpha)*LO[,1] + cos(alpha)*LO[,2]

par(mfrow=c(1,2))
plot(net, layout=LO)
plot(net, layout=LO2)

Flip side to side
LO3 = LO
alpha=pi/4
LO3[,1] = -LO3[,1]
plot(net, layout=LO)
plot(net, layout=LO3)


Ways to write "50"

Question: A really good friend of mine is an elementary school math teacher.  He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems.  Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher.  Now he LOVES math, and I can certainly show him a lot of expressions.  I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed.  Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out.  Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work.  I appreciate the answers but I need more compact expressions.
Comment: I voted to reopen. Perhaps this should be Community Wiki. It is tagged as big list - to say that there are lots of possible answers rather validates the list - the number of interesting answers is probably rather smaller, and voting will distinguish the cases. Given that there was a debate about my question on the number 50, I think there should be a proper debate about this one. Maybe there should be a "birthday fun facts" tag related to recreational mathematics. Such fun facts can have serious content, and some of us enjoy them.
Comment: See this question for a different take on $50$ http://math.stackexchange.com/questions/225518/properties-of-the-number-50
Comment: $e^{2\pi i}+7^2,$ $\frac{1}{\pi}\int_{-10}^{10}\sqrt{100-x^2}dx.$
Comment: $25\nabla\cdot\nabla|x|^2$
Comment: What a wonderful idea. This is certainly something I'd love to get for my birthday. :) For my mother's 75th I had cake decorated with an epicycloid with 75 cusps. Not that she's into math, but she sees the beauty in geometrical shapes.
Comment: @RghtHndSd That still means it's too broad, though.  (I would also argue that it is too localized, if that were still a thing.)  There are lots of good questions which do not fit the format of this site.  But, again, the decision is up the the community.
Comment: @AlexanderGruber Thanks - I appreciate that. I do see your point, but think a little fun every so often isn't out of place, and several of the answers are well in the spirit of the question.
Comment: Could someone explain to me how this is different from any other community wiki? If your response is that "49+1,48+2,47+3..." are all possible answers, then I say that those are all very bad answers, and to any community wiki one can always find many many very bad answers.
Comment: There's surely a contour integral/residue type expression.
Comment: "Raleigh quotient" expression for matrix with maximum eigenvalue of 50
Comment: See also this list [here](http://calculus-geometry.hubpages.com/hub/Fun-Facts-and-Mathematical-Properties-of-the-Number-50)
Comment: How about $100\sin(\pi/6)$ for the second one? [sine is negative on the interval $(\pi, 2\pi)$.]
Comment: I would totally troll your math teacher and write $$7^2$$ while saying "happy 50th birthday"
Comment: @MarkBennet I made the question CW and protected to repel trolls.  However, I do think the question should be closed for broadness, though I do not feel strongly enough to act unilaterally.
Comment: I am surprised not to see $3^2+4^2+5^2$
Comment: Do you know what his favourite expression/identity/theorem is? Maybe you find something using that. (If somebody were to do that for me, I'd like to see $e^{i\pi}+1=0$ integrated.)
Comment: @MarkBennet that is a great link.  I might just type him up a booklet with all those fun facts too.
Comment: He likes the summation formulas because he understands them.  I could certainly explain integrals to him too.
Comment: @AlexanderGruber: I certainly see the case to be made for broadness - there are many possible good answers and some might say too many. However from a more pragmatic viewpoint, I believe this is a good question and I don't see a way to ask it where it isn't too broad.
Comment: $50$ $\text{ }$
Comment: Is there any special significance to the number *50* that I'm not aware of? Also - I can offer *L*, the from the Roman numbering system.
Comment: $\lfloor e^4-e^{1.5}\rfloor$
Comment: $\lfloor\exp(H_28)\rfloor$
Comment: I would like to just mention that since the idea was about a cake topper or something for a birthday cake that perhaps I should limit the "size" of the expression.  Something compact like summations or products are useful because they can fit on a rectangular cake.  Hopefully that helps narrow the field from here on in. Also, stuff like Roman Numerals are really not the place here, easy fractions like 100/2 are not really what I was after.
Comment: @Arthur Fischer, I edited the question.
Answer: $$\frac{2^{\frac{(2\cdot2)!}{2+2}}+22+2^{2^2}-\sqrt 2^2}{2^{2-\frac{2}{2}}}$$
Comment: I think it is 2 much.
Comment: This answer currently has 22 upvotes. Don't ever let that change.
Comment: @RghtHndSd 2 good 2 be 2rue?
Comment: @teadawg1337 Don't worry. As of right now, the counter's at $22 + \lim_{n\to \infty}(\varphi(2)+\dfrac {2\pi i}{n})^n$.
Comment: That is an awesome one.
Comment: @teadawg1337 Damn, it changed. But I just upvoted it to $2^{2^2+2^{2-2}}$ so I think it's OK again.
Comment: People, it is over 22 upvotes now. Let's make it 222.
Comment: @RghtHndSd 42nd upvote. Let's get it to 50.
Comment: Upvoted to $\displaystyle\left\lfloor 2\sum _{s=2}^{222}\frac{s}{2222}\cdot 2\right\rfloor-2$
Comment: @Krishnabhadra First, we take $2^{\frac{(2\cdot 2!)}{2+2}}$, which is $2^{\frac{24}{4}}$, finally resulting in $64$ (because $\frac{24}{4}=6$, and $2^6=64$). $64+22+2^{2^2}$ (which is $16$) is $102$, $102-\sqrt{2}^2$ (which is $2$) becomes $100$. $2^{2-\frac{2}{2}}$ becomes $2^{2-1}$, which is $2^1$, which is $2$, which is $\frac{100}{2}$, resulting in $50$.
Comment: @Krishnabhadra My pleasure, and Merry Christmas!
Comment: For non math geeks, can someone explain this? How the result is 50 here?
Comment: @ConorO'Brien [but how (2.2!) = 24?](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=(2.2!))
Comment: It's not $2.2!$, its $2\cdot 2!$, or, alternatively, $2\times 2!$
Comment: Oh. now everything clear. Thanks @ConorO'Brien
Comment: 50! there you go.
Answer: We can use only two famous numbers in mathematics, $\large\pi$ and $\large e$, to produce number $50$.
$$\bbox[8pt,border:3px #FF69B4 solid]{\color{red}{\Large \lfloor e^\pi \rfloor + \lfloor \pi^e \rfloor + \lfloor \pi \rfloor + \lfloor e \rfloor = 50}}
$$
Click the box to see Wolfram Alpha's output to confirm the result
Answer: $$50 = 2\cdot(2\varphi - 1)^4$$
where $\varphi$ is the Golden Ratio.

$$50 = \sum_{i=0}^{+\infty} (0.98)^i$$
(Geometric series)

$$50  = \left(\left(\frac{5^5-5}{5}+5^0\right)\cdot\left(5-5^0\right)\right)^{0.5}$$
$$50 = 0.5 \cdot (5+5)^{\frac{5^0}{0.5}}$$
$$50 = 5\cdot\left(\frac{5}{0.5}+5^0\right)-5$$
(Using only the digits "5" and "0")

$$50 = \frac{3^{3!}-3^{3-3^0}}{3^{3-3^0}}-30$$
(Using only the digits "3" and "0")

$$50 = \frac{(10i)^2\log(i^i)}{\pi}$$
(Using imaginary unit $i$)

$$50 = 3 + 47$$
$$50 = 7 + 43$$
$$50 = 13 + 37$$
$$50 = 19 + 31$$
(As sum of two prime numbers)

$$50 = (7+11)\frac{11}{11-7}+\frac{7+11}{11-7}-11+7$$
(Using only the two next prime numbers of $5$)

$$ 50 = 7+3+ (7-3)\cdot(7+3)$$
(Using only the previous and next prime numbers of $5$)

$$50 = 3\cdot(2^3+3^2)-(2\cdot 3)^{3-2}+3+2$$
(Using only the two previous prime numbers of $5$)

$$ 50 = (1^6-2^5+3^4-4^3+5^2-6^1)^2\cdot(4^1 - 3^2 + 2^3 - 1^4)$$
$$ 50 = 3 - (1^9-2^8+3^7-4^6+5^5-6^4+7^3-8^2+9^1)$$
(Using bases/powers in reverse order)
Comment: I love the bases/powers in reverse order and i think he will get a kick out of that.
Comment: I particularly like the ones using only the digits 5 and 0.
Answer: No fancy math here, but if you want to emphasize how old your friend is getting, nothing says it better than implying he's halfway to the century mark:
$$100\over2$$
Comment: @Ooker & Venus, When I turned 50, my (older) brother sent me a birthday email with instructions to "party like you're a pair of 25-year-olds."  Or maybe it was to party *with* a pair of 25-year-olds....
Comment: Or 25 x 2, if you want to say: "hey, your body is just like 25 and your mind is better than that, twice."
Comment: @Ooker Or vice versa :-)
Answer: Quoting Wikipedia

Fifty is the smallest number that is the sum of two non-zero square
  numbers in two distinct ways: $50 = 1^2 + 7^2 = 5^2 + 5^2$.

So you could write something like
\begin{align}
50 = \min_{n\in \mathbb{N}}\{n =p_i^2+p_j^2=p_k^2+p_l^2 \quad | \quad p_i,p_j,p_k,p_l\in\mathbb{N} \quad \wedge\quad p_k \not =p_i \not = p_l \}
\end{align}
I like it, because it doesn't involve some sort of scaling and is not obvious (at least not for me).
Comment: I have a proof of this theorem, but there is not enough space on this cake.
Comment: He's going to need a **long** cake for this!!
Comment: Why not just write $1^2 + 7^2 = 5^2 + 5^2$. When people ask "what the heck?" you can give them a math lesson.
Answer: We also have
\begin{align*}
50 &= 11+12+13+14 \\
&= (8+4)+(8-4)+(8\cdot 4)+(8/4) \\
&= 4^2 + 4^2 + 3^2 + 3^2\\
&= 6^2 + 3^2 + 2^2 + 1^2\\
&= (7+i)(7-i) \\
&= (10-\color{red}{5})(10-\color{red}{0})\\
&= 10(\color{red}{5}+\color{red}{0})\\
&= \sqrt{30^2+40^2}\\
&= \sqrt[3]{170^2+310^2}\\
&= \sqrt[3]{146^2+322^2}\\
&= \sqrt[3]{50^2+350^2}\\
\end{align*}
Finally $50= 2 + 4 + 8 + 12 + 24$ and $\frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \frac{1}{12} + \frac{1}{24} = 1$.
Comment: This is a great great list.
Answer: I hope he doesn't calculate it by adding all numbers ;)
\begin{align}
50 = \sum_{k=0}^{100} (-1)^k k
\end{align}
And a last one, involving only $4$s and $9$s:
\begin{align}
4^9 \mod 49 + \sqrt{49}
\end{align}
Answer: Whenever one of my friends has a birthday, I find out how old they get and then I visit their number on Wikipedia
For your friend, I would write something like this:

50 is the smallest number that is the sum of two non-zero square numbers in two distinct ways: $1^2 + 7^2$ and $5^2 + 5^2$. It is also the sum of three squares, $3^2 + 4^2 + 5^2$. It is also a Harshad number and a nontotient and a noncototient. 50 is the aliquot sum of 40 and 94. 50 is also the atomic number of tin and fifth magic number in nuclear physics.

While many of the things on Wikipedia are not Mathematical expressions, and some of it is way too long to write on a cake, I am certain that this will brighten his day if you tell him this stuff!
As for a mathematical expression, I'd go with either $3^2 + 4^2 + 5^2$ because I find it simple but elegant, or fill the cake with stuff like "Harshad number, 5th magic number in nuclear physics, nontotient", etc. and see if he can figure out how old he is.
Answer: binary code : 50 is given by 110010
Answer: $\displaystyle \left(4!-5!-4\right)\int_0^1\frac{\operatorname{Li}_{-1}(t) }{t}\mathbb{d}t$Although this next one may be too big to fit on a cake, it's certainly beautiful:$\displaystyle \frac{\pi\operatorname{Li}_1(\frac12)(\Gamma(5)+1)}{\left[\Gamma(\frac32)\right]^2\left(\frac{\Gamma'(1)}{\Gamma(1)}-\frac{\Gamma'({\frac12})}{\Gamma({\frac12})}\right)}$Here's another one that may or may not fit on a cake:$\displaystyle\frac{\displaystyle\left(1+2\sqrt{4!+5!}\right)\left[\prod_{n=1}^3\Gamma\left(\frac{n}3\right)\right]^2}{\displaystyle{e}^{2\operatorname{Li}_1(\frac12)}\operatorname{Li}_2\left(\frac{\Gamma'(1)}{\Psi(1)}\right)}$
Comment: Ironically, when I am reading this it says "answered 50 seconds ago"
Comment: To whoever just downvoted, $\displaystyle \left(\operatorname{Li}_n(1) =\zeta(n)\right) \land \left(\zeta(0)=-\frac{1}{2}\right)\Rightarrow\left(\operatorname{Li}_0(1) =-\frac{1}{2}\right)$. See Equation 86 [here](http://mathworld.wolfram.com/RiemannZetaFunction.html) for proof that $\displaystyle \zeta(0)=-\frac{1}{2}$
Comment: This looks like stuff Ramanujan would have written.
Comment: Someone is downvoting everything in here. Don't take it personally.
Comment: what's $Li$? I've never seen that notation.
Comment: @OriaGruber $\operatorname{Li}$ is the [polylogarithm](http://mathworld.wolfram.com/Polylogarithm.html)
Comment: @MackTuesday I'm flattered, but the last two expressions have terms that simplify and cancel out to result in the number 50. Nothing special, just really fancy notation :)
Answer: I went to visit him while he was lying ill at the hospital.I had come in taxi cab number $50$ and remarked that it was a rather dull number. "No" he replied, "it is a very interesting number. It's the smallest number expressible as the product of $25$ and $2$  in two different ways."
https://mathoverflow.net/a/2197/15296
Comment: Hilariously, 50 is the smallest number expressible as the sum of two squares in two different ways, as noted in another answer, which is where I thought you were going with this at first!
Answer: $$
\begin{align}
&50 = \frac{5}{24} \zeta(-7)\\
&50 = \frac{ 1600 \sqrt{2} }{3 \pi ^3}\int_0^{\infty } \frac{x^2 \log ^2(x)}{x^4+1} \, dx
\end{align}
$$
Comment: Well, OK, but then you can take any real-valued expression, multiply it by the appropriate number so that it gives 50... I mean it _does_ answer the question but it is not as elegant as an expression which would be specific to 50. (this comment also applies to other answers)
Answer: $$-\frac{12!! - 3^{10}}{705 \text{ mod } 101}-\int_0^3 4x^3\;dx = 50$$
Or, if the double factorial is too weird:
$$\frac{9! - 2^{15}}{10000000_2}-\sqrt[5]{243}^2 = 50$$
Answer: The Complex Answers
I'd suggest $4.471527458208!=50$, but this isn't readily solvable. You suggested summations, and I thought "Hey! Why not nested summations?" The product of my "why not" statement:
$$\sum _{n=0}^4\sum _{i=n}^7n=50$$
If you're okay with floor functions:
$$\left\lfloor\prod _{n=1}^5\frac{\pi +e}{7}n\right\rfloor=50$$
A slightly more complicated one:
$$-1\left(\sum _{n=-3}^{11}-n\right)-10=50$$
If you want to complicate that (for a bit of fun), try, using Euler's identity for $-1$ and $n-2n$ for $-n$:
$$e^{i\pi}\left(\sum _{n=3e^{i\pi}}^{11}n-2n\right)-10=50$$
The Somewhat Easy Answers
Using only 5's and 0's:
$$5.5\frac{505}{5}-5.55=50$$
Something kind of neat, using a pattern 1...7,1:
$$1\cdot 2+3\cdot 4+5\cdot 6+7-1=50$$
Where $x_n$ denotes $x$ in radix $n$:
$$302_4=50$$
$$200_5=50$$
$$32_{16}=50$$
$$62_8=50$$
Set Theory
If $\alpha=\#A$ states that $\alpha$ is the cardinal of $A$, then:
$$\#\{x\in\mathbb{N}:5<x\leq55\}=50$$
Answer: Prime factorisation
Simple and elegant: $50=2\times5^2$
Answer: Compute the smallest positive integer $n$ such that the first two digits of $n^2$ is $\frac{n}{2}$.
Answer: How about this
$$50=12+18+20$$
Reference on this page
Now, this would have your teacher scratch his head a little bit initially, but worth a shot! :)
Answer: Some solutions:
$$\dfrac{50(-1)^{-i}}{i^{i^{2}}}=50$$
$$50=\sum_{n=1}^{10}(2n-1) \mod 10$$
$$50=1212_3$$
$$\left(4+\frac{4}{4}\right)\dfrac{\binom{4}{4-\frac{4}{4}}}{0.4}=50$$
Answer: You could go Roman with $$\Huge{L}$$
Or with $$\begin{array}{c} \\ \\ \end{array}$$
$$\begin{array}{ccccccccccccc} \Huge{X}&&&&&&&&&&&&\Huge{X}\\ \\ \\ \\
&&&&&&\Huge{X}\\ \\ \\ \\ \Huge{X}&&&&&&&&&&&&\Huge{X} \end{array}\\ $$
Answer: $$50 = \int_{\ln 1}^{3!+2^2}\frac{\Gamma(\frac{1}{2})^4}{6\sum_{1}^{\infty}\frac{1}{n^2}}\sqrt{3^2+4^2}dx$$
can make it more complicated but it wont fit on a cake :)
Comment: Well, but the integrand is constant in $x$ (it's just $5$), so it's not very interesting.
Comment: Where are you going to get the candles?

Ways to write "50"


More link not displaying in content pane

Question: I've got a Content Pane View which I display multiple times on one page (it shows a grid of Employees and takes a Department as a parameter, so I show the View 4 times on a page, sending each one a different Department parameter).
Each view on this page shows only a subset of the results (it only shows 6 Employees from each Department). I want to add a More link at the bottom of each view that links to a page that shows all results for that Department.
However, in the View configuration (Content Pane variant) I enable the More link to show, but it doesn't show.
Any ideas why the More link wouldn't show? I've definitely got enough content and I've even tried setting the configuration so that it'll show the More link even if there isn't more data.
Are More links disabled when displaying the view in a content pane?
Answer: I had the same problem.
I solved it by creating a page view as well as an original block view.
Hope this helps
Answer: You can use this module to define more link for each pane
Views Panes More Link

Adding the ability to define a custom "More Link" link for View Panes.
Just go to the view pane settings and you will find a new fieldset
  which will allow you to define the new custom "More Link".


How do I get list of Process Names running, in VB.NET?

Question: I am trying to find out if an instance of an application (not vb.net) is already running - because I will want to start it but I don't want to start it if it is already running. I have found a solution to check if a process is running:
Dim proc As Integer = Process.GetProcessesByName(ProcessName).GetUpperBound(0) + 1

and return True if >=1 (or just the process number).
My problem is, this is a third-party application, and its process name is not just a name but it contains a version number (which I may not know at run time), and it also seems to add a *32 (so probably a *64 if it is installed in x64 ?).
I need to get a list of running processes, by name, and test if "processname" is a substring of the name.
But I haven't been successful in getting a list of names, only process id's.
Answer:
I need to get a list of running processes, by name, and test if "processname" is a substring of the name.

You could use:
Dim procExists as Boolean = Process.GetProcesses().Any(Function(p) p.Name.Contains(processName))

This will look through all of the processes, and set the procExists value to True if any process which contains processName exists in the currently executing processes.  This should handle the existence of the unknown version number as well as the *32 that may occur if you're running on a 64bit OS (that's the WOW64 flag saying that it's a 32bit process running on a 64bit OS).
Comment: @Reed Copsey: Should it not be 'p.ProcessName.Contains' instead of p.Name.Contains? And I'm not sure if .Any is caseINsensitive. Otherwise some additional .ToUpper would be helpful to search for the processname?
Comment: I have tried this but "Any" doesn't work. Thank you for explaining the *32.
Comment: @emptyheaded Just add "Import System.Linq" at the top of your file, and Any should work.  It's a LINQ extension method (http://msdn.microsoft.com/en-us/library/bb534972.aspx)
Answer: You can loop through the running processes like this:
For Each p As Process In Process.GetProcesses()
   Debug.WriteLine(p.ProcessName)
Next

Answer: another way:

    Dim psList() As Process
    Try
        psList = Process.GetProcesses()

        For Each p As Process In psList
            Console.WriteLine(p.Id.ToString() + " " + p.ProcessName)
        Next p

    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
    Console.ReadKey()

Answer: Just tried the answer posted of Reed Copesy and this seems to be changed, what worked for me is:
Dim procExists as Boolean = Process.GetProcesses().Any(Function(p) p.ProcessName.Contains(processName))

Also is possible to retrieve the array by name and check directly if is contained on the process array:
Process.GetProcessesByName(processName).Length > 0

Thanks!


Qual o erro deste codigo?

Question: Qual o erro deste código?

( ! ) Parse error: syntax error, unexpected '$obj' (T_VARIABLE),
  expecting function (T_FUNCTION) in C:\wamp\www\php\index.php on line
  53

<?php

class Aluga {

public $nome;
public $snome;
public $cpf;
public $rg;
public $tel;
public $email;
public $status;
public $datainicio;
public $datafim;
public $qntpessoas;

function __construct($nome,$snome,$cpf,$rg,$tel,$email,$datainicio,$datafim,$qntpessoas){

$this->nome = $nome;
$this->snome = $snome;
$this->cpf = $cpf;
$this->rg = $rg;
$this->tel = $tel;
$this->email = $email;
$this->status = 0;
$this->datainicio = $datainicio;
$this->datafim = $datafim;
$this->qntpessoas = $qntpessoas;
}

function enviarDados(){

    $sql = 'INSERT INTO `alugueis`(`nome`, `snome`, `cpf`, `rg`, `tel`, `email`, `status`, `datainicio`, `datafim`, `qntpessoas`) VALUES (?,?,?,?,?,?,?,?,?,?)';

    $pdo = new PDO("mysql:host=localhost;dbname=test;","root", "");

    $stmt = $pdo->prepare($sql);

    $stmt->bindValue(1, $this->nome);
    $stmt->bindValue(2, $this->snome);
    $stmt->bindValue(3, $this->cpf);
    $stmt->bindValue(4, $this->rg);
    $stmt->bindValue(5, $this->tel);
    $stmt->bindValue(6, $this->email);
    $stmt->bindValue(7, $this->status);
    $stmt->bindValue(8, $this->datainicio);
    $stmt->bindValue(9, $this->datafim);
    $stmt->bindValue(10, $this->qntpessoas);

    $stmt->execute();
}

$obj = new Aluga("1","2","3","4","5","7","8","9","10");
$obj->enviarDados();

?>

Answer: Você esqueceu de fechar a abertura da classe, falta um } no final.
<?php

class Aluga {
    public $nome;
    public $snome;
    public $cpf;
    public $rg;
    public $tel;
    public $email;
    public $status;
    public $datainicio;
    public $datafim;
    public $qntpessoas;

    function __construct($nome,$snome,$cpf,$rg,$tel,$email,$datainicio,$datafim,$qntpessoas){
        $this->nome = $nome;
        $this->snome = $snome;
        $this->cpf = $cpf;
        $this->rg = $rg;
        $this->tel = $tel;
        $this->email = $email;
        $this->status = 0;
        $this->datainicio = $datainicio;
        $this->datafim = $datafim;
        $this->qntpessoas = $qntpessoas;
    }

    function enviarDados(){
        $sql = 'INSERT INTO `alugueis`(`nome`, `snome`, `cpf`, `rg`, `tel`, `email`, `status`, `datainicio`, `datafim`, `qntpessoas`) VALUES (?,?,?,?,?,?,?,?,?,?)';
        $pdo = new PDO("mysql:host=localhost;dbname=test;","root", "");
        $stmt = $pdo->prepare($sql);

        $stmt->bindValue(1, $this->nome);
        $stmt->bindValue(2, $this->snome);
        $stmt->bindValue(3, $this->cpf);
        $stmt->bindValue(4, $this->rg);
        $stmt->bindValue(5, $this->tel);
        $stmt->bindValue(6, $this->email);
        $stmt->bindValue(7, $this->status);$stmt->bindValue(8, $this->datainicio);$stmt->bindValue(9, $this->datafim);$stmt->bindValue(10, $this->qntpessoas);

        $stmt->execute();
    }
}

$obj = new Aluga("1","2","3","4","5","7","8","9","10");
$obj->enviarDados();
?>

Comment: vlw msm xDD sou bem noob nisso kk' eu tava tao focado no "$obj" q acabei n olhando se faltava algo
Comment: @Lucas Acontece ^^. Se possível marque a resposta como aceita. =)
Comment: Marcado :) Mas aki, vc sabe me dizer tem algum risco de sql injection nesse codigo? :P
Comment: @Lucas O risco sempre vai ter, mas usando PDO já diminui bastante as possibilidades. Dê uma olhada também [nesta pergunta](http://pt.stackoverflow.com/q/3864/6454) =)

Qual o erro deste codigo?


O que é e para que serve PCA, LDA, ICA?

Question: Estou realizando uma pesquisa sobre Detecção e Reconhecimento facial para futura implementação, minha pesquisa chegou ao algoritmo de Viola Jones e lendo mais cheguei aos conceitos de:

PCA - Análise de Componentes Principais
LDA - Análise Discriminante Linear
ICA - Análise de Componentes Independentes

Fiquei na dúvida o que é, como é, para que é a utilização disso?
Em uma imagem, eu preciso executar o algoritmo de Viola Jones e depois as análises de componentes ou é ao contrário?
Answer: Antes de tudo, o algoritmo de Viola-Jones foi explicado nesta outra resposta. Aliás, essa resposta trata especialmente da diferença entre detecção e classificação (o segundo termo tem relação com os demais conceitos que vc elenca na sua pergunta).
Detecção vs Reconhecimento
Estes termos são comumente confundidos, principalmente quando se trata dos domínios de problema da Visão Computacional envolvendo imagens de faces. Detecção trata de encontrar (localizar, saber se tem ou não, etc) um objeto em uma imagem. No caso desse domínio de problema, estamos falando de encontrar/localizar faces (humanas) em imagens. Reconhecimento trata de saber a quem uma face pertence, ou seja, reconhecer quem é o indivíduo após ter feito a detecção (isto é, localizado a região da face na imagem toda). Os termos são facilmente confundidos porque "reconhecer" poderia ser entendido como "perceber que ali há uma face", mas na literatura ele é utilizado no sentido de identificação.
PCA
PCA (de Principal Component Analysis) é uma técnica estatística que busca encontrar os padrões (de alteração) mais fortes em uma massa de dados.
Em uma analogia bastante simples, o PCA faz para uma massa de dados mais ou menos o que a derivada faz para uma função: fornece uma (ou mais) medida(s) de variação. Imagine a parábola que descreve o movimento de um projétil lançado pra cima. Se esse movimento é descrito por uma função quadrática da velocidade do projétil, isto é, o espaço no tempo (em km por hora, por exemplo), a sua derivada é a aceleração porque ela é a variação da velocidade. Lá no ponto mais alto do traçado a velocidade do projétil é zero, mas a aceleração é a mesma (aceleração da gravidade) pois o projétil desacelera na subida, pára e acelera na descida. Um satélite lançado ao espaço tem aceleração apenas enquanto sai da órbita terrestre, pois depois a aceleração se torna nula e a velocidade constante.
Pois então, a grosso modo o PCA encontra/calcula os vetores (direção e sentido) que denotam os principais eixos de variação dos dados produzidos por uma função com muitas variáveis (duas ou mais). O primeiro componente sempre indicará o eixo com maior variação, o segundo componente o segundo eixo com maior variação, e assim por diante (até no máximo a quantidade de variáveis).
A figura a seguir, retirada do artigo da Wikipedia sobre o método, ilustra exatamente isso. Nesse exemplo, os dados são caracterizados por duas variáveis (ou features) e por isso são plotados em um gráfico bidimensional. Como é possível perceber, há um padrão observável na distribuição desses pontos, pois muito embora ele não seja realmente linear há um espalhamento diagonal de baixo pra cima e da esquerda para a direita. Esse é o principal eixo. O segundo eixo é o espalhamento na diagonal oposta (de baixo pra cima, mas da direita para a esquerda), muito menor conforme se percebe pela magnitude do vetor desse componente PCA.

E pra que isso serve? Bom, pra começar esses dois vetores representam muito bem (e com dois únicos "valores" - lembre-se que cada vetor tem três propriedades: direção, sentido e magnitude, ou módulo) como os dados se comportam. Por isso, eles poderiam por si só ser usados para representar um conjunto de dados e compará-lo a outro conjunto de dados diferente. Mas, no caso do reconhecimento de faces, o PCA é usado com o intuito mais comum dessa técnica: reduzir as dimensões do problema.
No exemplo anterior da Wikipedia, o problema tinha duas dimensões (dois eixos para os dados). Processar esses pontos não é tão custoso porque o número de dimensões é baixo. Mas ainda assim, usando PCA poderia-se jogar fora o segundo componente e utilizar apenas o primeiro para projetar os pontos originais nesse novo "eixo", reduzindo as dimensões do problema de 2 para apenas 1. Sim, nesse exemplo ilustrativo isso poderia ser desnecessário, mas imagine em um problema com centenas ou milhares de dimensões. O processamento de imagens é um problema complexo porque mesmo uma pequena imagem de 10x10 tem 100 pixels, cada um deles com 3 valores em uma imagem colorida (RGB)! Utilizando-se PCA é possível reduzir as dimensões do problema de forma considerável apenas mantendo-se os componentes mais relevantes para representar uma face.
O algoritmo Eigenface faz justamente isso: aplica PCA em um conjunto de imagens de treinamento e as reduz às suas principais variações de cor para cada indivíduo, para então identificar/classificar uma nova imagem com base em comparação de distância (euclidiana mesmo) nesse "espaço de eigenfaces" (o "ponto" mais próximo nesse espaço é a face/indivíduo desejado). A figura a seguir ilustra algumas Eigenfaces da página da Wikipidia do link anterior.

LDA
O PCA apenas encontra os principais eixos de variação de uma massa de dados em qualquer dimensão. Ele não discrimina se esses dados pertencem a uma mesma classe ou não, logo esse método é muito útil para redução de dimensão do problema mas não para a classificação (leia mais sobre classificação nesta outra pergunta).
O LDA (de Linear Discriminant Analysis) faz uma abordagem diferente que considera a existência de classes para os dados. Ele projeta a distribuição de probabilidade dos dados nos eixos, conforme ilustra a figura a seguir (reproduzida deste artigo), e por isso não somente mantém como destaca uma separação linear dos dados se ela existir.

Nesse sentido, esse método pode ser utilizado diretamente para produzir um classificador (um sistema treinado a partir de dados de exemplo que é capaz de predizer a qual classe - no caso de faces, a qual indivíduo - um novo dado de entrada pertence). É muito comum, aliás, utilizar PCA para fazer uma redução de dimensão do problema (e torná-lo mais fácil de processar computacionalmente) e então utilizar LDA para classificar os dados.
Conclusão
Eu realmente não sou especialista nesses métodos (usei PCA no doutorado algumas vezes, mas nunca usei LDA), então a minha resposta pode conter algum pequeno erro. Eu também tentei tornar palatável o assunto com base no que eu conheço dele, mas lembre-se que eu fiz simplificações para isso (e quando for estudar pra valer, leia direitinho a respeito de conceitos como autovetores/eigenvectors, matrizes de covariância), e distribuição de probabilidade.
Tem muito material bacana que vc pode utilizar para aprender tudo isso muito bem. Sobre PCA eu sugiro esse tutorial bastante visual, e também esse tutorial no próprio site do OpenCV (que é focado no uso de PCA em imagens de forma geral, não necessariamente em faces - observe como é possível calcular a orientação principal dos objetos na imagem). Sobre LDA eu sugiro esse vídeo bacana (além do artigo já referenciado na imagem anteriormente).
Como você vai perceber eu não falei sobre ICA, e o motivo é que eu realmente não conheço absolutamente nada desse método. Eu suponho que seja alguma alternativa ou complemento aos outros dois, mas posso estar enganado. Talvez alguém complemente com uma nova resposta.
E na sua pergunta final ("Em uma imagem, eu preciso executar o algoritmo de Viola Jones e depois as análises de componentes ou é ao contrário?"), você precisa sim primeiro executar o algoritmo de Viola-Jones e depois PCA e/ou LDA. A ideia é que primeiramente você detecte (encontre) a região com a face, recorte (crop) a imagem para utilizar somente essa área e então aplique os demais algoritmos. Dessa forma vc economiza processamento e facilita os demais algoritmos (a imagem usada é menor e só tem o que realmente importa).
Comment: Da vontade de criar outra conta apenas para poder votar mais uma vez. Ótima resposta, como sempre.
Comment: Muito bom, vou utilizar dessa resposta para me aprofundar nos meus estudos. TCC logo ta aí :P
Comment: Prezado Luiz Vieira e autor da pergunta, tenho uma dúvida com relação a bases de dados com muitos NA's. Tenho uma base de dados, com variáveis ambientais (tipos de solos, vegetação, clima, etc), atributos químicos dos solos ( P, K, C, pH, Ca, Mg etc., e físicos areia, silte e argila), coletados em artigos publicados em jornais. Muitos autores não coletaram todos os dados que usei, e quando preciso fazer uma PCA ela só roda com a base completa. Essa é a informação que tenho por verdade até hoje. Vocês sabem como incluo um comandos no código, para rodar minha análise com todos os dados? Obrigado
Comment: @HerlonNadolny Se eu entendi corretamente o que vc quis dizer, o seu problema é que vc tem samples com dados faltantes (por exemplo, pra algum dos samples vc não tem uma ou duas das tais variáveis ambientais). Nesse caso, você não tem escolha: ou você (i) exclui a variável completamente da sua análise (caso muitos samples não tenham o dado), ou (ii) exclui os samples que não têm o dado (se forem poucos, mas pode ser um problema ao enviesar o seu modelo); ou (iii) você dá um jeito de estimar o valor faltante com base nos demais. Geralmente a galera tenta a última abordagem primeiro. Boa sorte.

O que é e para que serve PCA, LDA, ICA?


Find the CDF of $\ X $ where $\ X = \sqrt{A^2 + B^2} $

Question: Say $\ A,B \sim U(0,1) $ and $\ X = \sqrt{A^2 + B^2} $
and I want to find the the value $\ t$ of $\ X $ for which $\ P(X \le t) = 0.5 $
I understand I need to find the CDF of $\ X $ first and that $\ A, B $ distributed uniformly in the unit square. But I can't see how to find the CDF of $\ X $ ?
Answer: It is very easy. Do a drawing and calculate the area $\sqrt{a^2+b^2}<r$ in the unit square $[0;1]\times [0;1]$ then set this probability as 0.5 and solve in $r$
... of course you have to assume independence between $A,B$

Thus the solution is
$$\frac{\pi r^2}{4}=\frac{1}{2}$$
$$r=\sqrt{\frac{2}{\pi}}$$


No peers defined in the channel that have the ledger query role. Failed to execute the transaction

Question: No peers defined in the channel that have the ledger query role. Failed to execute the transaction: Error: No peers defined in the channel that have the ledger query role.
When I remove particular chaincode in the start.sh file, It is working fine. I'm adding one more chaincode to the channel, when deploying the chaincode it is showing 200. But when I try to query the chaincode, I'm getting this error.
Here is the error message that I'm getting

I checked with the config.yaml file. Everything good. Working fine with other chaincodes.
Answer: The client-side error you are seeing has nothing to do with chaincode. It is a failure to identify any peers (with the ledger query role) in your connection profile for the channel name you have specified, only if you are not using service discovery to locate network nodes. You probably need to check:

Which connection profile you are specifying when calling gateway.connect().
Exactly which channel name you are specifying in your client application when calling gateway.getNetwork().
That this channel name is defined in your connection profile.
There are peers defined for this channel in your connection profile.
The peer definitions don't explicitly disable the the ledger query role.

The error message you are seeing only exists in the v1.4 legacy Node client SDK, which is no longer supported. If at all possible, I would recommend using Fabric v2.4 (or later) and the newer Fabric Gateway client API.


Combinatoric Birthday Paradox

Question: There is likely a closed form solution for this problem but it's had me puzzled for days. This is about a variant on the classic birthday paradox. To recap, the birthday paradox is where given only 23 students the probability that two have the same birthday is > 0.5.
The variant is this: If each student has two (or K) special days, what is the probability that given N students each student has at least one special day that is unique to them.
I stumbled across this problem while working on a related cryptographic algorithm.
Another way of phrasing this is in terms of a lottery: If a lottery drawing consists of 5 random numbers (with repetition) drawn from a set of 100 numbers, after N drawings what is the probability that each drawing had at least one unique number among it's 5.
Explicitly, given these variables:
$C = $ the size of the set of choices (e.g. 100 for the lottery or 365 for the special days)
$K = $ # of random choices for each event (e.g. 5 for the lottery, 2 for the special days)
$N = $ # of events that have taken place (e.g. lottery drawings, or number of students)
Here is what I'm trying to solve for:
$P(C, K, N) = $ the probability that after N events, where each draws K random items from a set of C items, each event has at least one item that was not drawn in any other event.
Note that $P(C, 1, N)$ provides the solution to the classic birthday paradox.
To be clear, repetition is allowed. That is, a student could have the same special day twice, or the lottery drawing could be (5, 5, 78, 10, 5). In that event, if at least one of those numbers was never seen before, it counts as unique.
The best I've come up with is this:
Given a function, $Q(C, K, N)$ that computes the probability that the $N^{th}$ event has at least one unique value:
We would get these values in the student scenario:
$$ Q(2, 365, 0) = 1 - \frac{0}{365}\frac{0}{365} = 1.00000 $$
$$ Q(2, 365, 1) = 1 - \frac{2}{365}\frac{2}{365} = 0.99996 $$
$$ Q(2, 365, 2) = 1 - \frac{4}{365}\frac{4}{365} = 0.99987 $$
And similarly for the lottery drawing:
$$ Q(5, 100, 0) = 1 - \frac{0}{100}\frac{0}{100}   = 1.00000 $$
$$ Q(5, 100, 1) = 1 - \frac{5}{100}\frac{5}{100}   = 0.99999 $$
$$ Q(5, 100, 2) = 1 - \frac{10}{100}\frac{10}{100} = 0.99999 $$
This generalizes to:
$$ Q(C, K, N) = 1 - (\frac{N * K}{C})^K $$
If $Q$ computes the probability of any given student having at least one unique day than the probability of N events all having at least one unique day is just multiplying all of the probabilities together:
$$P(C, K, N) = \prod_{n=0}^N 1 - (\frac{n * K}{C})^{K}$$
This looks promising because for the case where $K = 1$, this simplifies to:
$$\prod_{n=0}^N \frac{C - n}{C}$$
which is the formula for the traditional birthday paradox.
The problem is that this proposed formula, beyond $K=1$, isn't actually correct, as verified by a monte-carlo simulation I've been running to compare it against.
I can't seem to wrap my head around what the problem is though. I've tried about a dozen different ways to approach the problem. It seems that there may be no closed form solution, unfortunately.
Comment: Firs I think you swapped C and K in your examples. My question is, why $Q(\_,\_,1)\neq 1$? If there is a single vent the surely it's result is unique
Comment: Treating the 0th event as the first event just made the math simplify ever so slightly. If you replace N with (N - 1) in the formula you'll get your expected result. As it is currently written, the 1st event is the 1st one with existing choices to worry about.
Comment: In your student example you can't be sure that $Q(2,365,2)=1-(4/365)^2$. That would be true if there were 4 different items already drawn, but that number could be 3 as well, in case the second student has one special day in common with the first.
Answer: I think the formula is more like that:
$$ P(C,K,N)= \left(\prod_{n=0}^{N-1}\frac{C-n}{C}\right)\left(\frac{C-N+1}{C}\right)^{(K-1)*N} $$
Intuitively, you have to choose the $N$ draw that will be unique. There are $C$ possibilities among $C$ for the first $C-1$ among $C$ for the second and so on (hence the  $\prod_{n=0}^{N-1} \frac{C-n}{C}$).
Ten you have to choose the other draws. You cannot pick the unique one (unless the one the is in the same event as you) hence there is $C-N+1$ choices possible among $C$ and there are $(K-1)*N$ such draw (hence the $\left(\frac{C-N+1}{C}\right)^{(K-1)*N}$).
Answer: I'm rewriting this answer completely because I found the error in my previous attempt. As before I'm dealing only with the $K=2$ case (students' special days).
Let $d$ be the number of students who still have both items unique to them, $s$ be the number of those who have only one unique item and $u$ the number of items which are shared by two or more students.
If $p(s,u,d)$ is the probability of having such numbers, then we have the following recursive relation:
\begin{equation}
\begin{split}
p(s,u,d)&=p(s-1,u,d) \left(1-{s+u+2d-1\over C}\right){1+2u\over C}+\\
&+p(s,u,d-1) \left(1-{s+u+2d-1\over C}\right)\left(1-{s+u+2d-2\over C}\right)+\\
&+p(s-2,u-1,d+1)\cdot 2{2d+2\over C}\left(1-{s+u+2d-1\over C}\right),\\
\end{split}
\end{equation}
where $C$ is the number of days in one year. This must be supplemented with the appropriate starting values:
\begin{equation}
\begin{split}
&p(0,0,1)={C-1\over C},\ \ p(1,0,0)={1\over C},\ \ p(0,0,0)=0,\\
&p(s,u,d)=0\ \ \hbox{if $s<0$ or $u<0$ or $d<0$},\\
&p(s,u,d)=0\ \ \hbox{if $u>s/2$}.\\
\end{split}
\end{equation}
With respect to my previous solution there is one more complication, due to the presence of variable $u$, but now all results are fine: I've checked them with an explicit calculation in the case $C=5$. To get the probability $p_{tot}$ that given $N$ students all of them have at least one unique item, one has to sum up all the relevant $p(u,s,d)$. For instance:
$$
p_{tot}(3)=p(3,0,0)+p(3,1,0)+p(2,0,1)+p(2,1,1)+p(1,0,2)+p(0,0,3).
$$
This probability falls below $50$% for $31$ students: $p_{tot}(31)=0.489694$.

Combinatoric Birthday Paradox


How do I attach files to nodes?

Question: I need to add files to multiple value file field using drupal rest api (restws module).
return format of restws is something like this :
"field_files": [

    {
        "file": {
            "uri": "http://drupal/file/445",
            "id": "445",
            "resource": "file"
        }
    }
],

but when I send it to http//drupal/node/<node_id> restws returns not acceptable.
Can anyone suggest which format I must use to send data to?
and second question : How can I upload files using restws module ?
Comment: Never tried restws module but you can try to json_encode your string and try to add .json to the URL ...
Comment: I've worked with drupal services module without problems, but for some reasons I've switched to restws, I can edit a node with one file but solution not working when node have more than one file.
Answer: For my first question:
I'm sending data with this format and it works now
{
  "field_files":[

    {
      "fid": "445"
    },

    {
      "fid":"446"
    }
  ]
}

Where fid is the id of an existing and accessible file.
For my second question, I've written module extending restws classes that user can submit data like the way user submits for services rest api.
Idea behind my module is that user submits data and module checks validation data and if data is valid saves file using drupal file_save_data function.

How do I attach files to nodes?


Why does the Winter Asian Games not held every four years?

Question: The Summer Asian Games are held every four years, but the Winter Games is not.
It was held 1986, 1990, 1996, 1999, 2003, 2007, 2011 and 2017.
Is there any specific reason for this?
Answer: As you listed, it was held from 1999 to 2011. But the next Games after 2011 was held in 2017 which is one year before the PyeongChang Winter Olympic Games. It would gather more attention about winter sports.
After 2017 Games, there was no city that would want to hold the Winter Asian Games due to financial reasons.
Recently, Trojena, a city being built in Saudi Arabia is selected to be a host city for the 2029 Winter Asian Games.
Comment: Harbin will host the Winter Asian Games before Trojena (2025). Also, what about before 1999? (1996 was 6 years after 1990, and 1999 was 3 years after 1996)


Show that $n$ is a prime number

Question:
Let $n\in\mathbb{N}$, $n\geq2$ and $(G,.)$ an abelian group of order $n$, with the property that for any $a\in G$, the number of endomorphisms of $G$ with $f(a)=a$ is equal to $n+1-ord(a)$, where $ord(a)$ is the order of $a$. Show that $n$ is a prime number.

My approach is to suppose that $n$ is not prime, so there is a decomposition for $n=p_1p_2...p_k$, where $p_1,\dots ,p_k$ are prime numbers and from Cauchy's theorem there is an $a\in G$ such  that $ord(a)=p_i$. Now $f(e)=f(a^{p_i})=(f(a))^{p_i}=e$, and so the number of endomorphisms $f$ is $n+1-1=n$.
However, from the hypothesis, the number of $f$ is $n+1-p_i$, and so $n+1-p_i=n$ $\Rightarrow p_i=1$. As we chosen $p_i$ arbitrarily, we get that all the numbers $p_i,i\in{0,1,...,k}$ are $1\Rightarrow n=1$, false with $n\geq2$.

Is my proof correct?
Comment: The problem seems ill-formed- wouldn't $f(e)=e$ always hold for any endomorphism fixing an element (regardless of the primality of $|G|$)?
Comment: @Cardioid_Ass_22 but that needs to hold for all elements.
Answer: You haven't used the hypothesis that the group is abelian.
I corrected some points of grammar & punctuation, though, too, like not starting a sentence with a mathematical symbol, adding a space after each comma, etc.
Comment: Thanks! How should I use the fact that the group is abelian?
Comment: A mathematical magazine. It doesn`t matter as it has no proof.
Comment: You're right, it doesn't, epistemologically, @JacobDenicula. (Try to use ' instead of ` on this site for technical reasons.) If it has no proof, it has no proof. But to see whether it's likely to be correct, it helps to know from whence it came.
Comment: Based on what I understand, you don't need that hypothesis. This is a bad sign though. I'm inclined to think I'm wrong. Where is the problem from, @JacobDenicula?
Comment: Using that apostrophe `does this` when used either side of a string of symbols.

Show that $n$ is a prime number


Haskell List Comprehension - Not all data getting transferred

Question: I have Network data structure like this:
data Network = Empty | Node Double [Network] [Network]

Where the Double represents the node label, the first list is the parents, and the 2nd list is the children of a given node. Assume all edges are directed from root to leaves, and there are no cycles.
I have an edge data structure like this:
data Edge = Edge (Network, Network)

where the edge is directed from a->b for Edge (a,b)
I have written a function meant to make a list of all the tree edges of the network. To further define this point, every and all parent (incoming) edges to a node that has multiple parents (a reticulation node) are not tree-edges. I am considering the outgoing edge from a reticulation node, and all other edges in the network, to be a tree edge.
I attempted to use list comprehension for this task like such:
getTreeEdges :: Network -> [Edge]
getTreeEdges (Node label ps cs) = nub (getTreeEdgesHelp (Node label (Empty:[]) cs))
getTreeEdgesHelp :: Network -> [Edge]
--leaf node case, children is empty list
getTreeEdgesHelp n@(Node _ ps []) = [Edge (p, n) | p <- ps ]
--reticulation node and root case, there is more than one parent or parent is empty(root)
getTreeEdgesHelp (Node _ ps cs) | ((length ps) > 1||ps==(Empty:[])) = (concat (map getTreeEdgesHelp cs))
--interal node case
getTreeEdgesHelp n@(Node _ ps cs) = ([Edge (p, n) | p <- ps ])++( concat (map getTreeEdgesHelp cs))

As you can see, the list comprehension is used to store the parent edges for leaves and for internal edges, while the root and reticulation nodes skip over adding edges to the list and just recurse. Leaves end the recursion.
The problem I have is that the edges stored do not contain all of the expected information. More specifically the parent information of the parent nodes disappears. The other information remains, the label and the children are unaffected.
So for example, say I store the edge (a,b). The network b is stored exactly correctly. The network a has itself (the root node) and all the descendant nodes present and labelled properly, but they all lack any entry for their parents, the parents to every node is [].
Here is an example of a given input, output, and expected output with newick format (a,b)c for a node c that has children a and b. I also include the parent(s) of a given node in square brackets after the label. For full disclosure, here is how I define Show for the Network and the Edge.
instance Show Network where
  show Empty = "_"
  show (Node a ps []) = (show a)++"["++printlabels ps++"]"
  show (Node a ps [x,y]) = "("++show x++","++show y ++ ")"++(show a)++"["++printlabels ps++"]"
  show (Node a ps [x]) = "("++show x++")"++(show a)++"["++printlabels ps++"]"
printlabels :: [Network] -> [Char]
printlabels [] = " "
printlabels (Empty:_) = "root"
printlabels ((Node label _ _):ns) = (show label)++","++(printlabels ns)

Here is an example tree I have generated. Because the labels are rather long, I have substituted out letters to label the internal nodes and integers to label the leaves.
(((4.0[c],((0.0[f])f[e,h],(1.0[g],2.0[g])g[e])e[c])c[h],(0.0[f])f[e,h])h[d],3.0[d])d[root]

Is the representation of the following graph.

Running the function described above gives:
[(d,h),(h,c),(c,4.0),(c,e),(f,0.0),(e,g),(g,1.0),(g,2.0),(d,3.0)]

with
instance Show Edge where
  show ( Edge ((Node labelu _ _), (Node labelv _ _)) ) = "("++(show labelu)++","++(show labelv)++")"

When I query a single edge, say the one at position 5 (e,g) and rewrite Show for Edge to
instance Show Edge where
  show ( Edge (u, v) ) = "("++(show u)++"=1, 2="++(show v)++")"

I get (((1.0[ ],2.0[ ])g[ ],0.0[ ])e[ ]=1, 2=(1.0[g],2.0[g])g[e]) whereas the expected result would be (((1.0[g],2.0[g])g[e],(0.0[f])f[e,h])e[c]=1, 2=(1.0[g],2.0[g])g[e])
Another error I have noticed is that 0.0 is given as the sibling to g which is not true. As a commenter pointed out, I am not changing any nodes when trying to get tree edges, I am just assigning the nodes to an appropriate edge pair and storing that in a list. You can also see the network I have input has correct parentage and structure.
What could be going on here? I am new to Haskell, am I using list comprehension wrong?
Comment: FWIW, it's very unusual to store a pair inside a data constructor. `data Edge = Edge Network Network` would be much more common. They're not exactly the same, and in almost all cases you'd prefer the version without the extra pair. It's one less pointer to chase to get the information you're looking for.
Comment: What's the purpose of `Empty`? You aren't matching on it with any of your functions, and an empty list would do just as good a job of representing no parents or no children as `[Empty]`.
Comment: @KaariLandry That change won't fix any problems you're having. It was just general Haskell style advice. That's why I threw it in a comment instead of making an answer - it doesn't help with your question.
Comment: Can you give input, expected output, and actual output of the simple `(a, b)` example you mention? It is not clear to me what the structure looks like and I get the feeling the problem is in the way you construct the structure and not in the code shown here, because you don't change the nodes at all in this code.
Comment: How is `nub` defined?
Comment: @MarkSaving http://zvon.org/other/haskell/Outputlist/nub_f.html
Comment: @chepner The `Empty` is a relic of previous code for a Tree this was built off that didn't use lists. Right now, Empty only marks the root and it is used in some pattern matching in `getTreeEdges`, but it is unnecessary and `[]` is just as suitable as you point out.
Comment: @Carl Yes, I see your point about avoiding using a pair. I don't particularly see what it changes but I will try it without the pair nonetheless and update if anything changes.
Answer: Your data structure is very unusual for a pure language and will prove extremely hard to work with. Although the graph you are representing is acyclic, the data structure you are using to represent it is cyclic: the child of a parent is the node again. Which means that when you modify something, you need to modify it cyclically: if I change a node, I must also change the corresponding child's parent, and the parents of each of its children, etc. This is very complicated and subtle to do.
This challenge is unique to pure languages: changing cyclic data structures is not a problem with mutable data structures -- you can just change it in one place and everywhere it is referenced can "see" the change.
Best would be to find an acyclic representation of your graph.  For example: a graph is a list of edges. If you need it you could also include a Set of nodes (thus degree 0 nodes can be represented). Refer to nodes only by their labels, looking them up in the list whenever you need information about them.
An alternative approach is an inductive graph
(implemented in the fgl library).
Comment: @KaariLandry copying with modifications is the only way to "change" anything in a pure functional language like haskell. The trick is designing a data structure that makes it easy. ;)
Comment: @KaariLandry You might like [How do you represent a graph in Haskell?](https://stackoverflow.com/q/9732084/791604).
Comment: Yes, I have been making changes to the network by copying the entire network with the changes. I didn't really know what the alternatives were so I appreciate you pointing me in some other directions on how to represent a graph. I was just following my instincts and am not a natural programmer.


Unity Stream Audio Slider(Seek Bar)

Question: In Unity, I'm using the following code to stream audio from the server, but I don't know how to add a seek bar(slider to change the playing duration) to it. Any help would be much appreciated.
<code>   IEnumerator GetAudioClip()
     {
         using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG))
         {
             DownloadHandlerAudioClip dHA = new DownloadHandlerAudioClip(url, AudioType.MPEG);
             dHA.streamAudio = true;
             www.downloadHandler = dHA;
             www.SendWebRequest();
             while (www.downloadProgress < 0.01)
             {
                 Debug.Log(www.downloadProgress);
                 yield return new WaitForSeconds(.1f);
             }
             if (www.isNetworkError)
             {
                 Debug.Log("error");
             }
             else
             {
                 audioSource.clip = dHA.audioClip;
                 audioSource.Play();
             }
         }
     }
</code>
Comment: Set audioSource.time according to slider value. this should work
Comment: @Jaimin thanks, but can you give an example.
Answer: Here is the basic example which shows what you need. Make changes according to your preference.
<code>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.Networking;

public class Test : MonoBehaviour
{
    private float _audioLength;
    private string url = "test url";

    public Slider slider;
    public AudioSource audioSource;

    private void Start()
    {
        slider.maxValue = 1f;
        slider.onValueChanged.AddListener(OnSliderValueChange);
        StartCoroutine(GetAudioClip());
    }

    private void OnSliderValueChange(float f) => audioSource.time = f * _audioLength;

    private void OnDisable() => slider.onValueChanged.RemoveAllListeners();

    private IEnumerator GetAudioClip()
    {
        using (var www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.UNKNOWN))
        {
            yield return www.SendWebRequest();

            if (www.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.Log("error");
                yield break;
            }
            ((DownloadHandlerAudioClip)www.downloadHandler).streamAudio = true;
            var audioClip = ((DownloadHandlerAudioClip)www.downloadHandler).audioClip;
            yield return null;
            audioSource.clip = audioClip;
            _audioLength = audioClip.length;
            audioSource.Play();
        }
    }
}
</code>
Add slider in inspector and you good to go.

Unity Stream Audio Slider(Seek Bar)


can't create database with mysql for wordpress

Question: I am trying to create a user with the following command. I am getting the below error.
CREATE DATABASE wp-test;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-isdi' at line 1.

I am trying to install wordpress, and after following all the steps I am getting below error.

This either means that the username and password information in your wp-config.php file is incorrect or we can't contact the database server at localhost. This could mean your host's database server is down.
Comment: `CREATE DATABASE` is used for creating database. not user.
Comment: CREATE DATABASE IF NOT EXISTS wp-test; like that or maybe use backtick `wp-test`
Answer: It's the best practice to use underscore instead of hyphens in database and table names because hyphens are not valid identifier in this condition you need to use backticks around the database name.
Example:
CREATE DATABASE `wp-test`;

Comment: Solved it, thanks but now while creating a user I am getting this

`ERROR 1396 (HY000): Operation CREATE USER failed for 'suraj'@'localhost'
`

This is how I am trying `CREATE USER suraj@localhost IDENTIFIED BY 'password';`
Comment: @Suraj: for ERROR 1396, check this question, there are so many solution here.. http://stackoverflow.com/questions/5555328/error-1396-hy000-operation-create-user-failed-for-jacklocalhost
Comment: @Suraj: one case study regarding CREATE USE: http://bugs.mysql.com/bug.php?id=28331
Comment: I get this whole creating the user.

`ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE USER suraj@localhost IDENTIFIED BY 'password'' at line 2
`
Answer: try this sql command to create user
CREATE USER 'suraj'@'localhost';GRANT USAGE ON *.* TO 'suraj'@'localhost' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

and give user all the privileges..
Comment: I get this error now. `ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE USER suraj@localhost IDENTIFIED BY 'password'' at line 2
`
Comment: @Suraj: did u check manual? https://dev.mysql.com/doc/refman/5.5/en/create-user.html
Comment: okk try this.....CREATE USER 'suraj'@'localhost'
  IDENTIFIED BY 'new_password' PASSWORD EXPIRE;
Comment: or you can check reference from http://dev.mysql.com/doc/refman/5.7/en/create-user.html


Automatically start ASP.MVC project when running test project

Question: I'm trying to set up a test project for my ASP website. For some tests I want to use selenium to perform end-to-end tests.
Therefor my website has to be running so the tests can access the site.
How can I start my website project when I run tests?
Comment: I'm guessing you don't have this registered with IIS and you want to start it locally with the IIS express in the compiler?
Comment: @mutt Thats right. I have a web project and a test project in my solution. I want to start the web project to start in Visual Studio via IIS Express when the tests run.
Answer: Please reference the following links.  I believe it is possible, but will be a little tricky.  These are detailed and provide information on doing this programmatically.
Starting and stopping IIS Express programmatically
https://www.reimers.dk/jacob-reimers-blog/testing-your-web-application-with-iis-express-and-unit-tests

The idea is that you would need to start it and navigate to your particular local app in your browser.
Then you will need to get the window handle of the open browser window
Then instantiate your Driver object and use the window handle for that instantiation to get Selenium to execute on the open window.
Comment: Thanks for the links. I'll see if this works for me.


Why does BitConverter.ToInt32 read one byte at a time if the data is not aligned at the given offset?

Question: Sorry for the confusing title, but I can't think of a better way to explain it.
While browsing the source code of BitConverter recently, I came across a strange segment of code:
public static unsafe int ToInt32(byte[] value, int startIndex)
{
    fixed (byte* pbyte = &value[startIndex])
    {
        if (startIndex % 4 == 0) // data is aligned
            return *((int*)pbyte);
        else
        {
            if (IsLittleEndian)
            {
                return (*pbyte) | (*(pbyte + 1) << 8)  | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
            }
            else
            {
                return (*pbyte << 24) | (*(pbyte + 1) << 16)  | (*(pbyte + 2) << 8) | (*(pbyte + 3));
            }
        }
    }
}

How can casting pbyte to an int* (line 6) violate data alignment in this scenario? I left it out for brevity, but the code has proper argument validation so I'm pretty sure it can't be a memory access violation. Does it lose precision when casted?
In other words, why can't the code be simplified to:
public static unsafe int ToInt32(byte[] value, int startIndex)
{
    fixed (byte* pbyte = &value[startIndex])
    {
        return *(int*)pbyte;
    }
}

Edit: Here is the section of code in question.
Comment: Operations on data aligned on data size boundary are faster and on some CPUs access to non-aligned words/dwords/float/doubles is access viaolation... (comment as I don't have good link handy).
Comment: @AlexeiLevenkov Still, you create two additional branches, multiple bitwise operations, *and* dereference `pbyte + 1`, `pbyte + 2`, etc. (3 of which are not going to be "aligned") just so you can avoid that non-alignment. Seems pretty overkill to me.
Comment: Not sure about your comment - there are CPUs that you flat out can't access unaligned `int` - http://stackoverflow.com/questions/1237963/alignment-along-4-byte-boundaries - so what alternative implementation do you suggest compared to reading byte-by-byte?
Answer: I'd bet that this has to do with this part of §18.4 in version 5.0 of the C# specification (emphasis mine):

When one pointer type is converted to another, if the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined if the result is dereferenced.

Bytewise copying in the "unaligned" case is done to avoid relying on explicitly undefined behavior.


Secondary Menu Tab (local task)

Question: I was wondering if there is any good documentation out there on building second level tabs using the menu system. Here is some of the menu code in my module:
  $items['admin/settings/cvminterviews'] = array(
    'title' => 'Interview Scheduler',
    'description' => 'Overview',
    'file' => 'cvminterviews_admin_overview.inc.php',
    'page callback' => 'cvminterviews_overview_page',
    'access arguments' => array('administer cvminterviews'),
  );

  $items['admin/settings/cvminterviews/overview'] = array(
    'title' => 'Overview',
    'description' => 'Overview',
    'file' => 'cvminterviews_admin_overview.inc.php',
    'page callback' => 'cvminterviews_overview_page',
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10
  );

  $items['admin/settings/cvminterviews/interviewers'] = array(
    'title' => 'Interviewers',
    'description' => 'Interviewers',
    'file' => 'cvminterviews_admin_interviewers.inc.php',
    'page callback' => 'cvminterviews_interviewers_overview_page',
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

  $items['admin/settings/cvminterviews/interviewers/import'] = array(
    'title' => 'Import Interviewers',
    'description' => 'Import Interviewers',
    'file' => 'cvminterviews_admin_interviewers_import.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_interviewers_import_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

I would like to have

admin/settings/cvminterviews/interviewers/import

Be a secondary tab to:

admin/settings/cvminterviews/interviewers

but the above code doesn't seem to do anything with it. Any thoughts?
Answer: I needed to add the following to my code:
  $items['admin/settings/cvminterviews/interviewers/interviewers'] = array(
    'title' => 'Interviewers',
    'description' => 'Interviewers',
    'file' => 'cvminterviews_admin_interviewers.inc.php',
    'page callback' => 'cvminterviews_interviewers_overview_page',
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

The important part is to make this the exact same callbacks as the 'admin/settings/cvminterviews/interviewers' menu item, but with one more level, and assign the MENU_DEFAULT_LOCAL_TASK type.

Secondary Menu Tab (local task)


Can I use t-test to compare two groups whose event is rare (less than 1 per thousand)?

Question: Background
We ran a test marketing campaign at my company to see if our new customer segmentation has an impact on the response rate to our offer.
We have created two groups to run this test marketing campaign:

Group 1: 2,000 people randomly selected among existing clients.
Group 2 : 10,000 people that were selected following the new segmentation process.

For each of this group, we obtained the following number of people who responded to the campaign:

Group 1: 3 people out of 2,000
Group 2: 5 people out of 10,000

So we are dealing with a really rare case type of problem.
My goal is to understand it there is a significant difference between the response rate of group 1 and group 2.
Questions
1) Can I run a t-test with such a rare case type of problem?
I suspect that this is not possible because the data is highly skewed (see this paper: http://advan.physiology.org/content/34/3/128)
2) Which test (possible to be ran with R) should I use to compare the mean of my two groups?
3) Is there a rule of thumb to determine if the t-test is not appropriate?
Any help appreciated!
Comment: You should not in general use t-tests on count data like this; there are tests suitable for comparing binomial proportions.
Answer: Fisher's exact test on this table:
<code>                     Group
                --------------
                |   I  |  II  |
          ------|------|------|
Response  | Yes |    3 |    5 |
          |  No | 1997 | 9995 |
          ---------------------
</code>
The t-test will fail very far from 50-50.  The chi-square test will fail with sparse counts.  Fisher's will work (in R, this is fisher.test).


Solving double integral $\iint_A \frac{\tan(x+y)}{x+y}dxdy$

Question: I have to solve this double integral $$\iint_A \frac{\tan(x+y)}{x+y}dxdy$$ where $A=\{(x,y)\in\mathbb{R}^2| x+y\le 1;y>0;x>0\}$.
I tried with a linear substitution given by: $$\cases{x+y=t\\x-y=u}\Rightarrow\cases{x=\frac{t+u}{2}\\y=\frac{t-u}2}$$
but then I am not able to solve the integral nor to find the extremes.
Do you know some other substitution or some new way to manipulate the integrand?
Answer: Your substitution is going to work well if you find out the limits.
To limit $t$ is easy: $t=x+y\le 1$, and $x,y>0$ gives $t=x+y>0$. Hence, $0<t\le 1$.
To limit $u$: use that $2x=t+u>0$ and $2y=t-u>0$. What are bounds for $u$?

 $-t<u<t$.


Omega 3.x base theme missing after Drupal upgrade

Question: After upgrading Drupal to 7.4.3, i am missing my Omega 3.x base theme in the ui. My subtheme is still present, but the layout is all messed up. Any idea's?
Answer: Where did you put your base theme?
It should be in the same folder as your theme "sites/all/themes". If you put it in the top themes folder, beside Bartik, Seven, etc, it was in the wrong place and this folder is overwritten when you update.
If his is the case you can probably just download it again and put it in the correct folder "sites/all/themes".
Comment: It was added in the sites/all/themes folder, as is my subtheme. Just for testing, when i add the omega 4.x to that same folder, omega 4 shows up in the theme settings page. I also added the files for omega 3 again, but no results there.
Comment: Also important the site was hacked and they forced the Zen base theme to the site, so maybe that has something to do with it, but normally all infected files are removed.