postgresql: Fast way to update the latest inserted row

Question: What is the best way to modify the latest added row without using a temporary table.
E.g. the table structure is
id | text | date

My current approach would be an insert with the postgresql specific command "returning id" so that I can update the table afterwards with
update myTable set date='2013-11-11' where id = lastRow

However I have the feeling that postgresql is not simply using the last row but is iterating through millions of entries until "id = lastRow" is found. How can i directly access the last added row?
Comment: If you have an index on the `id` column, Postgres (or any other DBMS) will not *iterate through millions of rows* - it will do an index lookup which is quite fast. But the real question is: why can't you just include that date value with the original insert statement?
Comment: Your current approach is correct and one of the fastest (if you have index on `id` field)
Comment: After testing some time i see that both versions are fast. So you can work with the "returning id" (which is postgresql specific) or with the solution i accepted
Answer: update myTable date='2013-11-11' where id IN(
       SELECT max(id) FROM myTable
)

Comment: @mvb13 It will not work with concurrent inserts. You must never rely on numbers from a sequence to be ordered.
Comment: I tested this on my database running on slow hardware with over 100.000.000 entries and it works fast
Comment: That is true. In my case it is always straight forward (insert -> maybe modify) so there is no problem.
Answer: Just to add to mvb13's answer (since I don't have enough points to comment directly yet) there is one word missing. Hopefully, this will save someone some time from working out the correct syntax LOL.
update myTable set date='2013-11-11' where id IN(
  SELECT max(id) FROM myTable
);


What exactly is Cross-Validation?

Question: Based on my understanding from google and other posts, like this What is cross-validation for? and What is cross-validation? . I understand that (k- fold) cross validation means spliting the data into ($k-1$) training and 1 testing set. In other words, it is used for finding the model accuracy.
So, is that mean if I do cross-validation, then I don't need to split my data into training and testing dataset? Also, say if I do (in r):
model = train(target~., data = data, method = "glmnet",
  trControl = trainControl("cv", number = 10),
  tuneLength = 10
)

this code will find me the best model in those 10 trials, and then when I do the prediction, I am using the best model?
Answer: Cross-validation is a special form ob splitting data into training and testing data, in which this splitting does not only occur once but a number $n$ of times.

Also, say if I do (in r)

There is a very powerfull package that can be loaded into R, called caret. caret delivers the very powerful function train that is used in your sample code. caret does indeed take a lot out of the work of finding the best set of parameters (out of a grid of possible combinations) for machine learning; including via cross validation. You will not have to split the data by hand but splitting will occur.

this code will find me the best model

it will find the best parameter combination from a given grid of parameter combinations by trying out. Before using a powerful tool like train you should understand its options well, also understand, how to influence which parameter grid is being tried out.
Fortunately caret comes with great explanations. Start here: https://topepo.github.io/caret/model-training-and-tuning.html or better start at the beginning of that book.

What exactly is Cross-Validation?


neural network using R (neural net package)

Question: I want to forecast sales of retail companies.
I am using the neural net package neural net.
My code:
<code>    nn <- neuralnet(f,data=train_,hidden=c(14,12,4),linear.output=F,threshold = 0.01,
        stepmax = 1e+08, rep = 10, startweights = NULL,learningrate.limit = NULL,
        learningrate.factor = list(minus = 0.6, plus = 1.15),
        learningrate=NULL, lifesign = "none",
    algorithm = "rprop+", err.fct = "sse", act.fct = "logistic",
exclude = NULL,constant.weights = NULL, likelihood = FALSE)
</code>
My model is not even as good as a linear regression.
What can I do to improve accuracy of the model ??
Data: 2'300 Quaters (for e.g. Q1 2003) and 18 variables (for e.g. inventories)
Answer: I'm not sure about the specifics of this package, but I did some meddling with neural nets using keras.
From what I understand from the function parameters you are using a default learning rate, how about trying to set one? I would vary it between 0.01 and 0.0001 and check the results.
Also, did you try a different activation function, such as one linear?
Finally, how did you choose the number of layers? Since this is a regression problem I guess you are not limited to 4 nodes on your output layer. I would loop over a few variations and check results.
I'm not very experienced in Neural Networks though, so please correct me if I'm wrong.
Comment: thanks for your comment, I will try the changes and see if it improves the accuracy!
Comment: the smaller the learning rate the more accurate your model will be. It will just take longer the smaller your learning rate becomes.
Comment: do you mean I should use for e.g. learningrate.factor = list (minus=0.99, plus=1.01) ? @nak5120


How to get CSS to target new nodes being inserted?

Question: I am customizing nodes for a blog entree's so they have a certain aesthetic look to it. However, I ran into a problem.
I can enter custom CSS code to style the nodes for already existing ones and set them with classes, but if someone is going to create a new node on the site, the blog CSS doesn't appear because I have to go in to each one and constantly hand-code it.
Obviously this is time-consuming and not the right way to go about it, because anyone who creates a blog would have to wait for me to style it for them. Is there a way where I can make a CSS code that will keep the look and feel every time someone creates a new blog entree?
Comment: Sounds like you're inserting the same CSS into each node manually. That's can't be true right?
Comment: No, that's what I was doing.
Answer: I'm not sure I get the scenario.
What if you apply your css to both old and new classes?
Example
<code>.old_nodes .content, .new_nodes .content {
   color:red;
}
</code>
This will give same style to both new and old nodes.
Comment: I figured it out. I had to install code per node module and use content type styling so each new entry would come with its set prebuilt style.
Comment: From my experience, code per node requires manual action for each node. Happy you figured out, @Shawn !


title_callback not working for certain user in hook_menu

Question: I am developing a module to manage Human Ressources.
I implement hook_menu with a title_callback like this:
<code>$items['intranet/hr/%user'] = array(
  'title callback' => 'user_page_title',
  'title arguments' => array(2),
  'page callback' => '_hr_redirect_to_personal_data',
  'page arguments' => array(2),
  'access callback' => 'hr_check_menu_access',
  'access arguments' => array(2),
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'navigation',
);
</code>
Users with certain role and the user to whom the HR data belongs can access to this menu, and should see the name of the concerned user.
It works perfectly if the logged user has a role, but the title of the menu is "Home" for the user to whom the HR data belongs.
I don't understand what's happening as I am implementing hook_menu() the same way the user module does for the user profile page.
If I inspect the menu with the devel menu, the title is correct for every user.
Any idea on what I am doing wrong ?
Thanks!
Answer: I get it !
In my configuration, the path intranet/hr is a view which is not accessible to every user, that's why the children element is not accessible and I have "Home" as the menu title.
Even if I don't know how to change this behaviour, at least I know why it is happening :-)


nmap output in csv format sorted by last octet in ip address

Question: I have this command which works well to give me a list of ip address, MAC address, and Mac Vendor
sudo nmap -sn 192.168.0.0/24 | awk '/Nmap scan report for/{printf $5;}/MAC Address:/{print " "substr($0, index($0,$3)) }' | sort

All I want to do is to add a comma as a delimeter between each of the three fields and sort the ip address column by the last octet of the ip address.  By changing the command as follows I can get a comma between 1rst and 2nd column and can sort by ip address.  Now I just need a comma between 2nd and 3rd column.  How to add the last comma?
sudo nmap -sn 192.168.0.0/24 | awk '/Nmap scan report for/{printf $5;}/MAC Address:/{print ","substr($0, index($0,$3)) }' | sort -t . -k 4,4n

Answer: I think you're looking for the "OFS" setting of awk (Output Field Separator, I think).
echo "one two three" | awk '{ OFS=", "; print $1,$2,$3}'
one, two, three

Also, your question would be more suitable for PowerUser or some other Stack Exchange site.
Comment: Thanks Bob, did not quite work.  I will post in a different forum.


Tap and hold: a pain in the uiBUTTon

Question: Excuse the bad pun, I'm creating a custom tab bar in my iPhone app using UIButtons. Everything works beautifully except that when I tap and hold a button, it doesn't select it until I release it. It's really bugging me, because a standard UITabBarItem is selected on touch down and it just feels wrong.
I've set the IBAction to "Touch Down" and my code is pretty simple. Am I doing something wrong?
<code>-(IBAction)tab1Pressed:(id)sender
{
    if (self.tab1.selected == NO) {
        self.tab1.selected = YES;
        self.tab2.selected = NO;
    }
}
</code>
Comment: It is actually quite a nice capitalization pun.
Answer: Got a solution! Added a UILongPressGestureRecognizer to each UIButton, instead of using IBActions. Worked like a charm!
In viewDidLoad:
<code>tapAndHold = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapAndHold)];
[tapAndHold setMinimumPressDuration:0.01];
[self.myTabBarButton addGestureRecognizer:tapAndHold];
[tapAndHold release];
</code>
Comment: Whoops, don't think there's any reason to make that an instance variable. First line should be: UILongPressGestureRecognizer *tapAndHold etc.
Answer: You should use another event for your button. The default one is "touch up inside". The action is triggered when you release the button.
Using "touch down" should do what you want.
Comment: ...although the question does say, "I've set the IBAction to 'Touch Down'", so that may not be the problem here...
Comment: So strange. Why would "touch down" not be working? It just behaves exactly like "touch up inside". I would try subclassing but I would have no idea where to start.
Answer: You can try subclassing a UIView and implementing touchesBegan:withEvent: method.
Comment: Wait, do you mean I could try subclassing UIButton and implementing touchesBegan:withEvent: with my tab changing method?
Comment: No, a UIView. you can also do custom drawing in its drawRect method.

Tap and hold: a pain in the uiBUTTon


The ratio of true vs. false hypothesis

Question: I am currently reading a paper Why Most Published Research Findings Are False, which claims that many findings published in research papers are actually false.
In the introduction the author defines the following:
Let R be the ratio of the number of "true relationships" to "no relationships" among those tested in the field. (Relationships referring to/being used synonymously used for hypothesis).
Later he postulates that the pre-study probability of a relationship being true is R/(R +1).
I am wondering why the probability of a relationship tested to be true (pre-study) should be R/R-1?
Shouldn't it be true relationships/(true + no relationships)?
Comment: Let $T$ be the number of true relationships and $N$ the number of no relationships.  Then $R = T/N$.  Try substituting $T/N$ for $R$ in $R/(R+1)$ and see if you can simplify...
Comment: @Heinrich , is *R/R-1* a typo ?
Answer: The answer by @jbowman is correct:
Let $T$ be the number of true relationships and $N$ the number of no relationships. Then $R = T/N$. Try substituting $T/N$ for $R$ in $R/(R+1)$ and see if you can simplify...

The ratio of true vs. false hypothesis


Quais as linguagens de programação que dão suporte a Linux e Windows?

Question: A questão já esta no título, contudo para deixar mais claro:

Quais as linguagens em que eu escrevo um único código, e rode tanto em Linux como Windows?

Exemplo

C. Exceto alguns comandos como system("cls"); system("clear");.
Java. Maquina Virtual para interpretar.

Obs

Linguagens que executem alguma tarefa ou janela no sistema operacional.
Comment: Acho que a pergunta está um pouco ampla. Apenas pela pergunta, php, javascript também serviriam como resposta, mesmo sendo web, até C#.
Answer: Essencialmente todas. Na verdade, é uma exceção ter linguagens que rodem apenas em um deles e não no outro, em geral linguagens pouco conhecidas. A maior exceção talvez seja o Delphi. Mesmo assim é possível usar o Lazarus que usa linguagem quase idêntica, mas que exige muitas mudanças em vários casos.
A linguagem em si tem pouco a ver com o sistema operacional. Ela pode ter mais restrição no processador que roda, já que a linguagem ou precisa gerar um código nativo para um processador específico ou precisa ter um interpretador ou máquina virtual para aquele processador. Existem algumas linguagens que confundem sua estrutura básica com o que deveria ser biblioteca. Aí obviamente complica mais.
Biblioteca
Claro que a biblioteca básica da linguagem precisa ser capaz de realizar certas operações que dependem do sistema operacional. Quase todas possuem abstrações ou pelo menos bibliotecas específicas que permitem fazer todas as principais tarefas nos dois sistemas operacionais. Eventualmente será necessário fazer alguma adaptação para as especificidades. As bibliotecas que conseguem abstrair 100% usam um método de "mínimo denominador comum",  que não dá bons resultados.
Algumas se destacam mais por possuírem melhores abstrações e uma quantidade maior de APIs atendidas, sejam na biblioteca padrão ou bibliotecas reconhecidas que se tornam quase padrão. C e C++ com algumas bibliotecas específicas são conhecidas por atenderem muito bem ambos.
Implementações
Linguagens interpretadas e rodando em máquinas virtuais costumam ir muito bem também nos dois, isto inclui C#, VB.NET, Java, PHP, Python, Ruby, Perl, JS, Lua, só para ficar nas mais conhecidas. O que importa é ter o ambiente onde elas rodam funcionando bem nos dois sistemas operacionais.
Há uma certa subjetividade em qual atende melhor as duas plataformas ao mesmo tempo. Mas todo código que pretende rodar em mais do que uma plataforma precisa ser escrito pensando nisto.
Note que estamos falando de implementações de linguagens porque duvido que alguém faça uma linguagem que seja especificada para rodar em uma só plataforma, não faz sentido.
Coloquei no GitHub para referência futura.
Comment: Ainda estão dando manutenção para o Kylix?
Comment: @GiancarloAbelGiulian não, há muitos anos. Na verdade nunca foi dado suporte de fato, nunca funcionou como deveria e como ninguém usava, foi abandonado logo em seguida. De qualquer forma, apesar de ter uma base de linguagem igual, as aplicações não conseguiam ser reaproveitadas de fato, precisava de todo um retrabalho.
Comment: Foi o que pensei de imediato, praticamente todas as modernas.
Comment: Muito bom, creio que a frase que mais se destaca "Todo código que pretende rodar em mais do que uma plataforma precisa ser escrito pensando nisto."
Comment: Delphi é em cima de Object Pascal, que [tem suporte a Linux](http://wiki.lazarus.freepascal.org/Kylix).


views with multiple contextual filters - should return data only when both or any one filter is present

Question: Views of content is having two contextual filter. For some reason node object is available to views so it is passing through url's 7th argument.
1.Content: Has taxonomy term ID
Configuration: Php Code
$nid = arg(7);
$node = node_load($nid);
if($node && isset($node->field_tags)) {
      $related = field_get_items('node', $node, 'field_tags');//dpm($related);
      foreach($related as $tag) {
          $view_par[] = $tag['tid'];
          //dpm($tag);
      }
return implode(',', $view_par);
}
else{
return 0;
}

2.Content: Nid (Ref: entity-reference-and-nested-arguments-in-views)
$nid = arg(7);
$node = node_load($nid);
$Related_ids = array ();
    $Related = field_get_items ('node', $node, 'field_some_er')    // Get the entity reference scope
    if ($related && is_array ($related) && sizeof ($related)> 0) {
      for ($i = 0; $i <count ($related); $i++) {
        $ Related_ids [] = $related[$ i]['target_id'];
      }
    }
    return implode ('+', $related_ids) // It returns the values of the field entity reference

Relationships:
Content: Taxonomy terms on node (Require this relationship :TRUE)
Content entity referenced from field_er_in_content (Require this relationship :TRUE)

With above configuration/modifying how to retrieve views's data only when
1. Any one of the filter should be present i.e either field_tags(term reference field) or field_some_er (entityreference field)
2. Both filter could be present.

but should not retrieve when both value is absent. Is there something can be done using common variable like found flag that can be shared to both php code and break the view operation.
Answer: Perhaps this is what you're looking for:
https://www.drupal.org/node/1871388
Otherwise, it looks like you might want to set up what your contextual filters do when the arguments  are not available:
https://www.drupal.org/node/1578574
Comment: nid is always present in URL but view should run only when any one of the two filter present. These two are fields of node whose nid is always passed through URL.


speeding up numpy.dot inside list comprehension

Question: I have a numpy script that is currently running quite slowly.
spends the vast majority of it's time performing the following operation inside a loop:
terms=zip(Coeff_3,Coeff_2,Curl_x,Curl_y,Curl_z,Ex,Ey,Ez_av)
res=[np.dot(C2,array([C_x,C_y,C_z]))+np.dot(C3,array([ex,ey,ez])) for (C3,C2,C_x,C_y,C_z,ex,ey,ez) in terms]
res=array(res)

Ex[1:Nx-1]=res[1:Nx-1,0]
Ey[1:Nx-1]=res[1:Nx-1,1]

It's the list comprehension that is really slowing this code down.
In this case, Coeff_3, and Coeff_2 are length 1000 lists whose elements are 3x3 numpy matricies, and Ex,Ey,Ez, Curl_x, etc are all length 1000 numpy arrays.
I realize it might be faster if i did things like setting a single 3x1000 E vector, but i have to perform a significant amount of averaging of different E vectors between step, which would make things very unwieldy.
Curiously however, i perform this operation twice per loop (once for Ex,Ey, once for Ez), and performing the same operation for the Ez's takes almost twice as long:
terms2=zip(Coeff_3,Coeff_2,Curl_x,Curl_y,Curl_z,Ex_av,Ey_av,Ez)
res2=array([np.dot(C2,array([C_x,C_y,C_z]))+np.dot(C3,array([ex,ey,ez])) for (C3,C2,C_x,C_y,C_z,ex,ey,ez) in terms2])

Anyone have any idea what's happening? Forgive me if it's anything obvious, i'm very new to python.
Comment: You should write the list comprehension as an array operation
Comment: If you can rewrite this operation using n-dimensional tensors and einstein summation notation it will be trivial to vectorize the operation in numpy. At the very least please write the dimension of each object. For example "Coeff_3" appears to be of shape (1000,3,3).
Comment: How so? I'm not really sure how to do it/
Answer: As pointed out in previous comments, use array operations. np.hstack(), np.vstack(), np.outer() and np.inner() are useful here. You're code could become something like this (not sure about your dimensions):
 Cxyz = np.vstack((Curl_x,Curl_y,Curl_z))
 C2xyz = np.dot(C2, Cxyz)
 ...

Check the shape of your resulting dimensions, to make sure you translated your problem right. Sometimes numexpr can also to speed up such tasks significantly with little extra effort,
Comment: This seems to work. I've stacked all my vectors and used einstein summation as suggested by Option and it has gone from 15 cycles per second to 77 cycles per second. Thanks!


Transformation of the functional equation $f(x+y)=f(x+1)f(y)$

Question: Is there a way to reduce the following functional equation
$$
f(x+y)=f(x+1)f(y),\qquad x,y>0,
$$
to the equation
$$
f(x+y)=f(x)f(y),\qquad x,y>0,
$$
whose solutions are known?
Thanks in advance.
Comment: For  the  same  $f$ ,  no.
Answer: Let $g(x)=f(x+1)$ then $g(x+y)=f(x+(y+1))=f(x+1)f(y+1)=g(x)g(y)$
Comment: For $ f :R \to R$ ,if $ f$ (or $ g$) is assumed to be continuous then $g(x)=A^x$ for some constant  $A > 0 $,( or $ g=0$  for all $ x)$. But there are many other discontinuous solutions for $g$.
Comment: I think measurability of _f_  (or _g_) suffices. Do you agree?


When are bitwise operations appropriate

Question: I am aware of the basic premise of what bitwise operation are (although would appreciate a "for dummies" explanation); however I am unaware of when it is appropriate to use this technique.
My understanding is that older CPU architectures could perform bitwise operations faster then other operations and hence it was advantageous to know how to use them. Given this is no longer the case; is it still appropriate to perform them and if so, for what purpose and under what conditions? (I am specifically interested in the C# context but am happy to receive general answers)
Comment: Do you mean shifts and such like, or all the logical operations too?
Comment: No shifts. I do understand logical operations.
Answer: Bitwise operations are a great way to quickly check for a flag that may be set on a variable.
The following example highlights the benefits of using bitwise operations on a Flag enumeration as well as storing a bitstuffed field into a database. The bitstuffed field can then easily be checked to see if it contains a single value or subset of values from the Flag enumeration.
Example:
A User database table with a tinyint field called Permission. The field is populated using a value created with the enumeration which values are 2^n.
[Flags]
public enum Permission : byte
{
    None = 0,
    ManageUsers = 1 << 0,
    CreateOrders = 1 << 1,
    PurchaseEquipment = 1 << 2,
    CancelOrders = 1 << 3,
}

Apart from bitwise operations being used to specify values in the enumeration (done at compile time), you can use the enumeration to check if the Permission field in the database contains any subset of the possible values. From the database side you gain the ability to stuff values into a single field - eliminating the need to have a column for each permission and in the code side you gain an easy way to check for a value.
Example bitstuffing (Grant ManageUsers and CreateOrders):
Permission userPermissions = Permission.ManageUsers | Permission.CreateOrders;

Example permission check:
public bool HasPermissions(Permission userPermissions, Permission permissionsToCheckFor)
{
    return permissionsToCheckFor == Permission.None ?
        false :
        (userPermissions & permissionsToCheckFor) == permissionsToCheckFor;
}

Comment: Thats an awesome example. Thank you very much. :-)
Comment: @Maxim-Gershkovich isn't it a draw back that you will not immediately see what the userPermissions will be if you lookup the value in the database with a client
Comment: I agree with @HCP. Bitwise operators cause unnecessarily unreadable code when there are many other ways to encode this information.

1. speed/size optimization is the only true reason to use it, and unless you are doing embedded systems, I'd argue that there are very few legitimate reasons to need this kind of speed-up on most of today's systems.  The trade-off for readability and debug-ability would be well worth it for the speed in most large projects.
Comment: According to [MSDN](http://msdn.microsoft.com/en-us/library/vstudio/ms229058(v=vs.100).aspx):
The size savings might be significant if:

    1. You expect the enumeration to be used as a field in a very frequently instantiated structure or class.
    2. You expect users to create large arrays or collections of enumeration instances.
    3. You expect a large number of instances of the enumeration to be serialized.
Comment: @m1m1k, given this example, how else would you _encode this information_? Surely you aren't suggesting a bit column for each permission? This example does not serve for **speed/size** optimization technique. It simply shows an easy way of managing permissions. That is it. Also, your reference to MSDN _is quoting irrelevant points_ that are not related to `Flag` enums at all! Finally, bitwise operations are as much a _core programming concept_ as [short circuit operations](http://stackoverflow.com/q/13313135/498969). Both core concepts that are easy to follow and understand.
Comment: @m1m1k I just realized that you downvoted my answer too. My answer addressed the immediate question which is essentially "Is it still appropriate to use bitwise operations given today's technology improvements?" and this answer shows how it is still relevant today.
Answer: The issue is not so much that bitwise operations are faster than integer operation (although they usually are), it's that they are different operations for different purposes.
Conceptually bytes and shorts and ints are really tiny arrays of bits and bitwise operators are boolean array operators.  In C# nowadays bitwise operators are mostly used for [Flags] enumerations and in calculations for GetHashCode but there are endless ways that arrays of bits can be used.
Comment: +1. Practical example where I used bitwise opeartions - Base64/Base32 encoding/decoding code (data is considered to be array of bits encoded 6 or 5 bits at a time). More generally code for compression/decompression commonly uses bitwise opeartions treating data as on hige array of bits.
Answer: You are correct that just because language gives you bitwise operation, you should not use them just because you can.  I've seen people use bitwise operators when working with simple booleans and that's not what they are for.
Bitwise operators are useful when working with data structures where pieces of data are not aligned with byte boundary.  Generally, this is done when bandwidth (or general memory footprint) is very important.  I work on RTP video streaming software and bitwise operations are used both in reading/constructing RTP transmission packets as well as for reading video codec streams, which are often encoded using bits, not bytes.
Answer: They can be really useful in embedded control situations when space is at a premium.  For example, a single byte of data can represent 8 i/o bits, and masks can be used to retrieve the bits of interest from an i/o port (e.g. if PIN0 = 1, PIN1 = 2, PIN2 = 4, PIN3 = 8 and so on, then:

To get the value of PIN0, we can say PORT0 & PIN0 == 0.
To set PIN1 to 1, we can cay PORT0 |= PIN1.
To set PIN2 to 0, we can say PORT0 &= ~PIN2.

Away from embedded control, I rarely see this approached used these days.  In the C# world it's much more common to see individual boolean fields for each value of interest, since the overhead is really not a big deal with modern hardware (though you may run into a case or two where bitwise operations are used to keep many such flags in a single variable).
There is also an interesting application in graphics.  A neat trick for cursors or bounding boxes is to add them by XOR'ing the cursor shape with the image below.  Performing the same operation again will result in the original image.
Answer: One way I find myself using bitwise operators from time to time is to generate subsets of a given string/array using a binary mask, it goes like this: (sorry, c++ code)
string s = "abcde";
for(int i = 0; i < 1<<s.size(); i++) {
  string tmp;
  for(int j = 0; j < s.size(); j++) if(i & 1<<j) tmp.push_back(s[j]);
  cout<<tmp<<endl;
}

You may want to check this insightful contests-oriented programming tutorial: A bit of fun: fun with bits

When are bitwise operations appropriate


How to prepare an old child guitar?

Question: Our daughter got an old child guitar (80 cm / 31") as a present from her grandparents. It's horrible to play, so I have to try making it as good as possible.
Somethings to note:

The neck is really dry. I almost get splinters.
The tuning pegs are quite hard to turn. I'm assuming the gears are not the best.
The frets have rough edges
The strings are super dry and rough
The strings are a bit far from the neck close to the body, but not close to the head.

Some questions:

Can I oil the fret board?
What type of strings are easiest to play for a child?
Can I file the edges?
Can I use a saw or something to make a deeper cut into the "string holder" on the body (last image).

Any other tips?
Comment: "dry" is not the same as "smooth" vs. "rough" .  If there are splinters, those need to be sanded out before considering any refinishing.
Answer: An inexpensive guitar with a zero fret!

yes, file the ends of the fretwires if they're protruding. Work from the fingerboard towards the back, otherwise you may pull the wire out.
change the strings for nylon - they'll be kinder on young fingers.
if there's a truss-rod, adjust it to get the strings more parallel to the fingerboard.
wire wool on the back of the neck may produce a better finish.
fingerboard itself shouldn't be a problem.
yes, the bridge slots can be undercut, but after everything else is adjusted. If you go too low, it may need another bridge, or paper strips underneath. The same can happen at the nut, but replacing is more complex.
after all, place the bridge in the right place for intonation. The 12th fret harmonic needs to be the same note as 12th fret fretted. Slide back or forth as needed.
attatch a strap or cord so she can 'wear' the guitar.
if the strings are still too tight, tune down a tone.
Answer: First question: are you an experienced guitarist  (and / or luthier)?  If not,  you are likely to make things worse rather than better.
Next question: do you have any reason to suspect this is a quality instrument?  I know it's nice to restore a "family heirloom,"  but unless you get an appraisal and find it is a collectible, you are almost certainly better off hanging it on the wall and buying your child a brand-new  small-size guitar.  She will be far less frustrated when learning on a working instrument.

How to prepare an old child guitar?


How to get the full object from firebase using a URL parameter

Question: I'm trying to create two views in an ionic app. But when I go from view 1 to view 2 with URL parameter I only get an empty object back from Firebase so my second view doesn't show anything. Totally lost here.
Routing:
    .state('app.trials', {
    url: "/trials",
    views: {
      'menuContent' :{
        templateUrl: "templates/trials.html",
        controller: 'TrialsCtrl'
      }
    }
    })

  .state('app.trial', {
    url: "/trials/:trialId",
    views: {
      'menuContent' :{
        templateUrl: "templates/trial.html",
        controller: 'TrialCtrl'
      }
    }
    })

View 1: /trials - shows all the trials, this is working.
<ion-list>
<ion-item ng-repeat="(trialId, trial) in trials | orderBy:'title'" href="#/app/trials/{{trialId}}">
{{trial.title}} | {{trialId}}
</ion-item>
</ion-list>

Factory for view 1:
.factory('Trial', function ($firebase, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL);
var trials = $firebase(ref.child('trials')).$asArray();

var Trial = {
all: trials,
get: function (trialId) {
  return $firebase(ref.child('trials').child(trialId)).$asObject();
}
};

return Trial;
})

Controller for view 1 (TrialsCtrl):
.controller('TrialsCtrl', function ($scope, Trial) {
  $scope.trials = Trial.all;
  console.log($scope.trials);
})

View 2: /trial - should show the trial that has been selected in /trials.
<ion-content class="has-header">

{{trial.title}}

</ion-content>

Controller for view 2 (TrialCtrl):
.controller('TrialCtrl', function($scope, $stateParams, Trial) {
  $scope.trial = Trial.get($stateParams.trialId);
  console.log($scope.trial);
})

Result from console in view 2:
{$$conf: Object, $id: "3", $priority: null, $save: function, $loaded: function…}$$conf:   Objectbinding: fdestroyFn: function d(a){n.isDestroyed=!0,i.off("value",k),h=null,m(a||"destroyed")}inst: clisteners: Array[0]promise: Object__proto__: Object$id: "3"$priority: null$value: null__proto__: Object

So this object does not contain all the items in the trial object as requested by $stateParams.trialId...
How to get the full object and show the selected trial info in view 2?
Answer: Found the problem:
In view 2 /trials i was referring to {{trialId}} where I should have referred to {{trial.$id}}.
Changing this solved it.


Radical identity

Question: Let $x\in\{\pm1\}$ hold true.
Is it true that for every $\epsilon\in(-1,1)$ we have $x=\frac{x+\epsilon}{\sqrt[2k]{(x+\epsilon)^{2k}}}$ at every $k\in\Bbb Z\backslash\{0\}$?
Answer: First of all, we have the equivalence;
$$\tag{1} x\in\{\pm1\} \Leftrightarrow x=sign(x).$$
The RHS can be transformed into
$$\tag{2}\frac{x+\epsilon}{\sqrt[2k]{(x+\epsilon)^{2k}}}=\frac{x+\epsilon}{|x+\epsilon|}= sign(x+\epsilon)$$
Due to (1) and (2), the question becomes : does the following sentence is true
$$\forall x, \ \forall \epsilon, \ \ sign(x)=sign(x+\epsilon) \ ?$$
The answer is evidently false : it suffices to take $x=-1$ and $\epsilon=2$ ; in this case, the LHS is $-1$, whereas the RHS is $+1$.
Remark : the interpretation of $\forall k\in\Bbb Z\backslash\{0\}$ somewhat puzzles me, in particular due to its position at the rear of what has to be proven.
Comment: $x\in\{\pm1\} \implies x\neq-\frac12$. I updated something else ($\epsilon\in(-1,1)$).
Comment: You are right !!!... I correct my counter example...

Radical identity


finding the mass and number of atoms

Question: A small cube of iron is observed under a microscope.  The edge of the cube is $4.00 \times 10^{-6}$ cm long.  The atomic mass of iron is 55.9 u, and its density is 7.86 $g/cm^{3}$.
a) Find the mass of the cube.
b) Find the number of iron atoms in the cube.
My work:
$d = \frac{m}{v} \implies m = d \times v$
$m = (6.4 \times 10^{-17} cm^3) \times (7.86 \frac{g}{cm^3})$
$m = 5.0304 \times 10^{-16}$ g
Is this correct?  Also how do I find part b?
Comment: Looks right to me. For b. you simply need to conver the atomic mass of iron to mass in grams, and devide it. That'll give you the number of iron atoms needed to reach that mass.
Answer: Your answer to part $(a)$ is correct. For part $(b)$, find the number of moles of iron available with you first:
$$\text{No. of moles}=\dfrac{\text {weight of substance in grams}}{\text{molecular mass of substance in amu}}$$
Hence in the no. of moles($n$) is:
$$n=\dfrac{5.0304×10 ^{−16}  \text{ g}}{55.9 \text { amu}}$$
$$\implies n\approx 9.0054 \times 10^{-18}$$
$$\implies \text {no. of iron atoms in the cube}=\text {no. of moles}\times \text{Avogadro's number}$$
$$\implies\text {no. of iron atoms in the cube}=n\times 6.023\times 10^{23}$$
$$\implies\text {no. of iron atoms in the cube}\approx 5.424 \times 10^6$$

finding the mass and number of atoms


Turtle python library not importing

Question: I am pretty new with python and programming. I started using the turtle library but when I installed the library with pip, this error showed:
ERROR: Command errored out with exit status 1:
     command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-sr9ppuq0/turtle/setup.py'"'"'; __file__='"'"'/tmp/pip-install-sr9ppuq0/turtle/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-sr9ppuq0/turtle/pip-egg-info
         cwd: /tmp/pip-install-sr9ppuq0/turtle/
    Complete output (6 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-sr9ppuq0/turtle/setup.py", line 40
        except ValueError, ve:
                         ^
    SyntaxError: invalid syntax
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

When I imported the python library, I got this error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/turtle.py", line 107, in <module>
    import tkinter as TK
ModuleNotFoundError: No module named 'tkinter'

please help. And I am also on a linux system.
Comment: That `turtle` module you're trying to install via `pip` is NOT the turtle graphics module you're probably looking for.  You don't want it, and it's not going to run on any modern system anyway (last updated in 2009).  The *real* `turtle` is part of Tkinter, no separate installation required.  Since Tkinter apparently didn't come pre-installed on your system, you will need to use your system's package manager to get it - it will be called something like "python-tk", I think.
Comment: After installing python-tk through apt, it still shows the same error.
Answer: Have you tried python -m pip install PythonTurtle, i think that's the newest installation name
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: After installing the python library using that command, `import turtle;` still shows the same error
Comment: This isn't a helpful answer. The OP is trying to use the built-in turtle module and this is likely to be confusing for beginners as it is actually suggesting installing a third party package with a similar name from PyPI

Turtle python library not importing


Use port 80 with Symfony Server

Question: I'm trying to set the port 80 while using the built-in Symfony Server on MacOS instead of defaulting to 8000. But keep getting this error:
<code>[ERROR] PHP-FPM failed to start: pool www] please specify user and group other than root  FPM initialization failed
</code>
Running then with "sudo" the "server:start --port=80" command seems to work but I only got a page with "File not found." displayed.
Any idea how I can use this port number?
Answer: By default, the CLI web server needs PHP-FPM to work (see https://symfony.com/doc/current/setup/symfony_server.html#enabling-php-fpm). It's the same problem as you describe:

Otherwise the server will start without PHP-FPM and will show a Page not found page when trying to access a .php file in the browser.

Concerning the sudo, Symfony CLI web server should be able to run fine without root privileges.
Maybe your issue is related to https://stackoverflow.com/questions/24404655/how-to-run-php-fpm-as-root/26045162#26045162.
Otherwise, if you want to avoid the Symfony CLI, you can also run your environment in Docker (for instance using https://github.com/dunglas/symfony-docker).

Use port 80 with Symfony Server


Requesting specific data returns all the associated entities without using the Include()

Question: I am creating a simple web API (MVC) and I am currently using Entity Framework Code First approach. I have the following entities:
Authors, Courses, Institutions
I have set up a relationship in such a way that an author can have N number of courses and N number of institutions. I am writing the following method on the API:
public class PlutoController : ApiController
{
    private readonly PlutoDbContext _context;

    public PlutoController()
    {
        _context = new PlutoDbContext();
    }

    [HttpGet]
    public IHttpActionResult GetAuthors()
    {
        var authors = _context.Authors
            .Where(a => a.AuthorID == 1).ToList();

        return Ok(authors);
    }
}

However, a call to the api returns authors and its associated courses and institutions.
[
{
    "Courses": [
        {
            "CourseSections": [],
            "Tags": [],
            "CourseID": 1,
            "AuthorID": 1,
            "Title": "C# Advanced",
            "Description": "C# Advanced Description",
            "Price": 69,
            "LevelString": "Advanced",
            "Level": 3
        },
        {
            "CourseSections": [],
            "Tags": [],
            "CourseID": 2,
            "AuthorID": 1,
            "Title": "C# Intermediate",
            "Description": "C# Intermediate Description",
            "Price": 49,
            "LevelString": "Intermediate",
            "Level": 2
        },
        {
            "CourseSections": [],
            "Tags": [],
            "CourseID": 3,
            "AuthorID": 1,
            "Title": "Clean Code",
            "Description": "Clean Code Description",
            "Price": 99,
            "LevelString": "Intermediate",
            "Level": 2
        }
    ],
    "Institution": [
        {
            "InstitutionId": 1,
            "AuthorId": 1,
            "InstitutionName": "University of Windsor"
        },
        {
            "InstitutionId": 2,
            "AuthorId": 1,
            "InstitutionName": "Boston University"
        },
        {
            "InstitutionId": 4,
            "AuthorId": 1,
            "InstitutionName": "Arizona State University"
        }
    ],
    "AuthorID": 1,
    "Name": "Bill Gates"
}]

In this, i can see that we are doing some eager loading which is not what i want. How do i just get only the author details?
Here are my generated models:
Author
namespace PlutoAPI.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class Authors
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Authors()
        {
            Institution = new HashSet<Institution>();
            Courses = new HashSet<Courses>();
        }

        [Key]
        public int AuthorID { get; set; }

        [Required]
        [StringLength(255)]
        public string Name { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Institution> Institution { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Courses> Courses { get; set; }
    }
}

Courses:
namespace PlutoAPI.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class Courses
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Courses()
        {
            CourseSections = new HashSet<CourseSections>();
            Tags = new HashSet<Tags>();
        }

        [Key]
        public int CourseID { get; set; }

        public int AuthorID { get; set; }

        [Required]
        [StringLength(255)]
        public string Title { get; set; }

        [Required]
        [StringLength(8000)]
        public string Description { get; set; }

        public short Price { get; set; }

        [Required]
        [StringLength(50)]
        public string LevelString { get; set; }

        public byte Level { get; set; }

        public virtual Authors Authors { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<CourseSections> CourseSections { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Tags> Tags { get; set; }
    }
}

Institution
namespace PlutoAPI.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("Institution")]
    public partial class Institution
    {
        public int InstitutionId { get; set; }

        public int? AuthorId { get; set; }

        [Required]
        [StringLength(50)]
        public string InstitutionName { get; set; }

        public virtual Authors Authors { get; set; }
    }
}

Comment: I presume [`LazyLoadingEnabled`](https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.infrastructure.dbcontextconfiguration.lazyloadingenabled?view=entity-framework-6.2.0) is set to true on your context?
Answer: What problem you are having is LazyLoading (not eager loading). To disable it.
public partial class YourDBContext : DbContext
{
    public YourDBContext(): base("name=YourDBContext")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }
}

Comment: That worked for me!! Thanks :) but I don't understand how is this not eager loading. Doesn't eager loading mean loading all the entities in one query?
Comment: Eager loading means loading related entities at the time load the main entity. But you need to use Include() to do that. In your case, since you don't use it, it doesn't load related entities when you ToList(). However, when you "return" it, the serializer start accessing those properties and EF start loading those properties.


Benefits of hosting servers at data centers?

Question: There are several Data Center Network Designs, and I'm working on a research paper on this topic.
To start with I'd like to know why to use data centers? Obviously besides the amount of space 10k servers take and some other obvious reasons.
Then, what are the benefits of using data centers for hosting servers?
How does scalability, fault tolerance and bandwidth usage fits in?
Comment: When you write your paper I suggest you proof read it a lot more than you did that question.
Comment: When you say paper, this is a university assignment? If so, we'd best serve by pointing you at some good starting points for your research.
Comment: it s not an homework but a research paper.
Answer: Data centers provide economies of scale.  They can also provide hosting in more appropriate locations to help achieve business continuity or performance goals.  Use of a data center might help meet a legal or regulatory requirement, or solve other specific business challenges.

How does scalability, fault tolerance and bandwidth usage fits in?

A data center may give you more scalability than you can build yourself, and will probably do it more cheaply.  I don't understand the point of your question re fault tolerance and bandwidth usage though.  Is this a homework assignment?
Answer: It all comes down to the cost of hosting @ home vs hosting at their facility. Think of it in terms of redundancy and pricing.
Good Data centers will often provide

more than one Internet Service Provider, in case one fails or degrades performance
you get more bandwidth at a lower price
data centers have the proper amounts of cooling, "not residential cooling system"
good data centers will have 24/7 staff
will help you meet infrastructure demands that come with contracts
data centers are shaped to fit their purpose and reduce the chance of damage (broken water pipe flooding the office) caused by human events or natural ones
If it's a large provider with
multiple data centers you can make a
deal with them to host at their
other locations, thus increasing
geographical redundancy

Keep in mind that bad data centers also exist, they barely meet infrastructure demands and are run by incompetent staff.
Answer: Redundancy and reliability.
Conditioned air and power.
Usually redundant conditioned air and power.
Normally you will have multiple network providers and possibly peering arrangments.
So the cost of connectivity will probably a lot lower than at a non data centre site.
This means it is cheaper to get multiple network links for both redundancy and extra bandwidth and you are more likely to do so.
You will probably be able to provision extra network services faster should the need arise.
Data centres don't necessarily help you with scale, although obviously you can probably put more   servers in a data centre than you can in a home or small commercial site.


Postgres syntax error while using insert on conflict

Question: Given a table
CREATE TABLE balances
(
    username   varchar(255)     NOT NULL,
    currency   varchar(255)     NOT NULL,
    balance    numeric          NULL,
    CONSTRAINT balances_pkey PRIMARY KEY (username, currency)
);

After attempting
CREATE OR REPLACE FUNCTION merge_balance(username varchar(255), currency varchar(255), to_add numeric) RETURNS void
AS $$ BEGIN
    INSERT INTO balances(username, currency, to_add)
    ON CONFLICT balances_pkey DO UPDATE SET balance = OLD.balance + to_add
END; $$ LANGUAGE plpgsql;

I get
ERROR:  syntax error at or near "ON"

My PostgreSQL version (running in a container postgres:11.5)
SELECT version();
                                                             version
----------------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 11.5 (Debian 11.5-3.pgdg90+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit
(1 row)

Those ;,$ things are so annoying and now I get this one =_=
Has anybody solved such a problem? Thanks!
Answer: Consider:
create or replace function merge_balance(
    p_username varchar(255),
    p_currency varchar(255),
    p_to_add numeric
) returns void
as $$
begin
    insert into balances (username, currency, balance)
    values(p_username, p_currency, p_to_add)
    on conflict (username, currency) do update set balance = old.balance + p_to_add;
end; $$ language plpgsql;

Rationale:

you need a VALUES() clause to enumerate the values to insert; it is also a good practice to surround list the target columns - for this, you would better not have function arguments that have the same name as the table columns

the conflict target must be surrounded with parentheses - you can use a constraint name, but I find it is clearer to use the column names
Comment: even better, I didn't look at the column names :-(
Comment: But there is no `old` reference available in an `insert .. on conflict()` clause
Comment: Maybe, but there is no syntax error anymore. Btw I had to remove `;` after `END`
Answer: Shouldn't it be
INSERT INTO balances VALUES(username, currency, to_add)
   ON CONFLICT balances_pkey DO UPDATE SET balance = OLD.balance + to_add

Answer: You cannot use "old" as you are attempting. What you are doing is referencing the pseudo row OLD generated by DML statements for triggers. Even if could reference it would be NULL as all old columns are null on insert. This is not what you want the result would be null. But you do need to alias the table to avoid ambiguity on the update clause. Also it is not necessary to specify limits on the function header. Try:
create or replace
function merge_balance(
         p_username varchar
       , p_currency varchar
       , p_to_add   numeric
       )
  returns  void
  language sql
as $$
    insert into balances as bal (username, currency, balance)
    values (p_username, p_currency, p_to_add)
        on conflict (username, currency)
        do update
           set balance = bal.balance + excluded.balance;
$$;

See full example here.

As an after thought I guess you could use old.balance by using old as the table alias.
insert into balances as old (username, currency, balance) ...

But that doesn't seem like a good idea, at least to me.,
Comment: Why not to write `set balance = p_to_add + excluded.balance;` there?
Comment: self reply: in that case the value is update incorrectly, I put 5, than 5 again and it's not updated
Comment: That is because p_to_add and excluded.balance refer to the same value. When a conflict occurs Posrgres builds a pseudo-row of what was being inserted (similar in concept to OLD and NEW pseudo-rows in DML triggers). This pseudo-row is aliased, thus referenced by, EXCLUDED. Since p_to_add was being inserted into the balance column it is built into excluded.balance. So they are the same value. I of course could have written bal.balance + p_to_add, just seems when dealing with on conflict my autopilot goes to excluded.


Symfony2 form submit on related entity error

Question: I have a problem when submitting a from with a related entity. I get the following error message when submitting the form:
Catchable Fatal Error: Argument 1 passed to
My\ReportBundle\Entity\Clearance::setProjectProject() must be an instance of
My\ReportBundle\Entity\Project, null given, called in
/var/www/Symfony/src/My/ReportBundle/Controller/DefaultController.php on line 85 and
defined in /var/www/Symfony/src/My/ReportBundle/Entity/Clearance.php line 272

The form builder code looks like this:
namespace My\ReportBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class ClearanceType extends AbstractType
{

public function buildForm(FormBuilder $builder, array $options)
{
    $builder
        // Fields from the clearance entity removed ...
        // here is the problematic entry
        ->add('projectProject','entity',
         array('class'=>'My\ReportBundle\Entity\Project', 'property'=>'projectId'))
      ;
     }

      public function getName()
     {
         return 'my_reportbundle_clearancetype';
      }

And the controller contains this code:
     public function newclearanceAction()
     {
    $request = $this->getRequest();
    $id = $request->query->get('projectId');
    $em = $this->getDoctrine()->getEntityManager();
    $project = $em->getRepository("MyReportBundle:Project")->find($id);

    $clearance = new Clearance();
    $clearance->setProjectProject($project);
    $form = $this->createForm(new ClearanceType(), $clearance);

    if ($request->getMethod() == 'POST'){
            $form->bindRequest($request);

            if($form->isValid()) {
                    $em = $this->getDoctrine()->getEntityManager();
                    $em->persist($clearance);
                    $em->flush();
                    return $this->
                    redirect($this->generateUrl('MyReportBundle_project_list'));
            }
         }
         return $this->render('MyReportBundle:Clearance:new.html.twig',
                 array('form'=>$form->createView()));

I don't have any idea how to fix this.
Thanks for any help!
Answer: when you post the form are you setting projectId in the query string?
If not try:
$request = $this->getRequest();

$em = $this->getDoctrine()->getEntityManager();
$clearance = new Clearance();

if($request->getMethod() != 'POST'){
    $id = $request->query->get('projectId');
    $project = $em->getRepository("MyReportBundle:Project")->find($id);
    $clearance->setProjectProject($project);
}
$form = $this->createForm(new ClearanceType(), $clearance);

The error is coming because you are not getting a project when you try and find one by id, thus when you try and set the project you are passing a null value through.
Comment: That was my problem! Thanks a lot :-)


What happens to the limits of integration of a double integral when it is negated?

Question: How are limits of integration of a double integral affected when that integral is negated?
I understand that $\int_a^b(1)dx = -\int_b^a(1)dx$. How would this identity translate to a double integral, say $\int_a^b\int_c^d(1)dydx$?
Answer: You flip the sign for every switch in limits.
$$\int_a^b \int_c^d dy\,dx = -\int_a^b \int_d^c dy\,dx = - \int_b^a \int_c^d dy\,dx = \int_b^a \int_d^c dy\,dx$$
Comment: @DerekEhle: If you got the answer, I can delete my own one. :-)
Answer: When the region of integration is a square $[a..b]\times [c..d]$ then the double integral can be evaluated independently. I mean: $$\int_a^b\int_c^d dxdy=\int_a^b dx\int_c^ddy$$


PHP: getting 1 instead of 0 using count()

Question: I'm adding a view counter to my website.
In the code, I check if there's an IP with the id of the post.
for example when post id is 26, and there's no IP with id 26 in my IP table, it should return 0 but it returns 1 instead.
  $userIp = $_SERVER['REMOTE_ADDR'];
  $checkIp = $db->prepare("SELECT user_ip FROM user_ip WHERE word_id = '$idToShow'");
  $checkIp->execute();
//This happens
  if (count($checkIp) > 0) {
    echo count($checkIp);
    echo " ". $idToShow;
  }
//instead of this
  else {
    $insertIP = $db->prepare("INSERT INTO user_ip (user_ip, word_id) values('$userIp', '$idToShow')");
    $insertIP->execute();
    $updateView = $db->prepare("UPDATE words set views = views + 1 WHERE id = '$idToShow'");
    $updateView->execute();
  }

Comment: what is the value of $idToShow
Comment: I have a list of words, $idToShow is the id of the word that should be showing. (for example 26)@RAUSHANKUMAR
Comment: Isn't `$checkIp` your PDOStatement object or similar? At least it isn't a result set...
Answer: Assuming you are using PDO
Here you are using prepared statements for querying database, but you are not fetching the result that has been returned by a database
use
$result = $checkIp->setFetchMode(PDO::FETCH_ASSOC);
if(count($result) > 0){
  .............
}
else{
  ..........
}

Even simpler you can use
$checkIp->rowCount()

this returns number of rows effected by your query
Answer: $checkIp->execute(); is always returns boolean value, so your condition is wrong here. check the docs here http://php.net/manual/en/pdostatement.execute.php use like this
$userIp = $_SERVER['REMOTE_ADDR'];
$checkIp = $db->prepare("SELECT user_ip FROM user_ip WHERE word_id = '$idToShow'");
$result=$checkIp->execute();
if (!$result) {
    echo count($checkIp);
    echo " ". $idToShow;
}else {
    $insertIP = $db->prepare("INSERT INTO user_ip (user_ip, word_id) values('$userIp', '$idToShow')");
    $insertIP->execute();
    $updateView = $db->prepare("UPDATE words set views = views + 1 WHERE id = '$idToShow'");
    $updateView->execute();
}

Answer: The execute() method runs the query returns a boolean value for if the query successful or not.
You can use rowsCount() to count the rows or you can fetchAll() and then count the results.
You should use something like this
$checkIp->execute();
if ($checkIp && $checkIp->rowsCount() > 0) {
    // ...
}

OR
$checkIp->execute();
$ips = $checkIp->fetchAll();
if (count($ips) > 0) {
    // ...
}

http://php.net/manual/en/pdostatement.execute.php
http://php.net/manual/en/pdo.prepare.php
Answer: Instead of this
if (count($checkIp) > 0)

Use
if(isset($checkIp->user_ip) && !empty($checkIp->user_ip))

Answer: As in PHP doc the execute retunr TRUE or False
$checkIp->execute();

so your
(count($checkIp)

just count the var content  that in this case contai just a value
Answer: $checkIp is an object and will always (assuming your prepare was successful) return a non-zero count. What you want (assuming you are using mysqli) is $checkIp->num_rows. If you are using PDO, you want $checkIp->rowCount().


Function won't run on command

Question: The game starts on the main menu, and once pressing the enter key while hovering over start, the fade function should run, followed by the black_screen function, then finally the game function. However, the main_menu function runs, and on the keypress event, only the play sound in the statement runs.
import os
import pygame
import pygame_menu
from pygame import mixer
from pygame.locals import *
import sys

# Initialization

pygame.mixer.init()
pygame.init()

# Center the Game Application
os.environ['SDL_VIDEO_CENTERED'] = '1'

# Game Resolution
width=800
height=600
screen=pygame.display.set_mode((width, height))

# Text Renderer
def text_format(message, textFont, textSize, textColor):
    newFont=pygame.font.Font(textFont, textSize)
    newText = newFont.render(message, 0, textColor)

    return newText

# Colors
white=(255, 255, 255)
black=(0, 0, 0)
gray=(50, 50, 50)
red=(255, 0, 0)
green=(0, 255, 0)
blue=(0, 0, 255)
yellow=(255, 255, 0)
AMP_PINK=(242, 145, 233)

# Game Fonts
hamberger = "./assets/fonts/hamberger.ttf"

# Sounds
menukeys = mixer.Sound("assets\sounds\keypress.wav")

mixer.music.load("assets\sounds\strolling.wav")
mixer.music.play(-1)

# Game Framerate
clock = pygame.time.Clock()
FPS=60

def game():
    main_menu()
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()

        screen.fill((0,255,0))
        pygame.display.update()

def black_screen():
    blacc = pygame.Surface((width,height))
    blacc.fill((0,0,0))
    pygame.display.update()
    pygame.time.delay(2)
    game()

def fade():
    global width, height
    fade = pygame.Surface((width,height))
    fade.fill((0,0,0))
    for alpha in range(0, 300):
        fade.set_alpha(alpha)
        screen.blit(fade, (0,0))
        pygame.display.update()
        pygame.time.delay(6)
        black_screen()

# Main Menu
def main_menu():

    menu=True
    selected="start"

    while menu:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                pygame.quit()
                quit()
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_UP:
                    mixer.Sound.play(menukeys)
                    selected="start"
                elif event.key==pygame.K_DOWN:
                    mixer.Sound.play(menukeys)
                    selected="quit"
                if event.key==pygame.K_RETURN:
                    #Starts the game
                    mixer.Sound.play(menukeys)
                    if selected=="start":
                        fade()
                    if selected=="quit":
                        mixer.Sound.play(menukeys)
                        pygame.quit()
                        quit()

        # Main Menu UI
        screen.fill(AMP_PINK)
        title=text_format("SNATCHED", hamberger, 90, black)
        if selected=="start":
            text_start=text_format("START", hamberger, 75, white)
        else:
            text_start = text_format("START", hamberger, 75, black)
        if selected=="quit":
            text_quit=text_format("QUIT", hamberger, 75, white)
        else:
            text_quit = text_format("QUIT", hamberger, 75, black)

        title_rect=title.get_rect()
        start_rect=text_start.get_rect()
        quit_rect=text_quit.get_rect()

        # Main Menu Text
        screen.blit(title, (width/2 - (title_rect[2]/2), 80))
        screen.blit(text_start, (width/2 - (start_rect[2]/2), 300))
        screen.blit(text_quit, (width/2 - (quit_rect[2]/2), 360))
        pygame.display.update()
        clock.tick(FPS)
        pygame.display.set_caption("Snatched - Main Menu")

#Initialize the Game
main_menu()
pygame.quit()
quit()

Comment: The function and the pygame.Surface inside that function are both called `fade`
Answer: The name fade isused twice. The function and the pygame.Surface object inside that function are both called fade.

Function won't run on command


Estimating integral of periodic function

Question: To explain my problem, let me first start with an easier version:

Let $\Sigma: \mathbb R \to \mathbb C$ be a periodic (continuous) function, $\Sigma(t+T)=\Sigma(t)$.
Then the integral
$$ I_1 = \int_0^T \mathrm dt \int_0^T \mathrm d\tau\, \Re\left\{ \Sigma(t-\tau)^\ast \Sigma(t) \right\} $$
is non-negative.
This can be easily seen by substituting $\tau \rightarrow x=t-\tau$, then we get
$$\int_0^T \mathrm dt \int_{t-T}^t \mathrm dx\, \Sigma(x)^\ast \Sigma(t) = \int_0^T \mathrm dt \int_0^T \mathrm dx\, \Sigma(x)^\ast \Sigma(t) \geq 0 \;.$$

I claim:
Also the integral
$$ I_2 = \int_0^T \mathrm dt \int_0^T \mathrm d\tau\, \Re\left\{ \mathrm e^{-\alpha\tau} \Sigma(t-\tau)^\ast \Sigma(t) \right\} $$
is non-negative for $\alpha > 0$.
My reasoning:

For $\alpha \to 0$, $I_2 \to I_1 \geq 0$.
For $\alpha \to \infty$, $I_2 \to 0$ from above (because the $\mathrm e^{-\alpha\tau}$ gives the strongest weight to $\tau \sim 0$ where the $\Sigma^\ast \Sigma$-part is non-negative)
I would be surprised if the integral became negative for some intermediate $\alpha$, but I can't prove that it doesn't.
Also I have done some numerics and not found a counterexample.

Does someone either have a counterexample, or know how to prove $I_2 \geq 0$?
In the best case, can the whole thing be extended to $\int_0^\infty \mathrm d\tau$?
Answer: Found an answer myself, leaving it for posterity. Everything becomes relatively easy once we write $\Sigma(t)$ as a Fourier series,
$$ \Sigma(t) = \sum_k s_k\, \mathrm{exp}\left(\mathrm i k \frac{2\pi t}{T} \right) \;. $$
(Sorry for calling that function "$\Sigma$"...)
I'll write down the $\int_0^\infty \mathrm d\tau$ case, but $\int_0^T$ works just as well:
\begin{align}
  I_2 &= \sum_{k,\ell} s_k^\ast s_\ell \int_0^T \mathrm dt \int_0^\infty \mathrm d\tau\, \Re\left\{ \mathrm e^{-\alpha\tau} \mathrm e^{-\mathrm i k \frac{2\pi(t-\tau)}{T}} \mathrm e^{\mathrm i \ell \frac{2\pi t}{T}} \right\} \\
  &= \sum_{k,\ell} s_k^\ast s_\ell \int_0^T \mathrm dt \cos\left( (\ell-k) \frac{2\pi t}{T} \right) \int_0^\infty \mathrm d\tau\, \mathrm e^{-\alpha\tau} \cos\left( k \frac{2\pi\tau}{T} \right) + 0 \\
  &= T^3 \alpha \sum_k \frac{|s_k|^2}{4k^2\pi^2 + T^2\alpha^2} \geq 0
\end{align}


how to iterate over 2 data frames for column.length - 1

Question: I have dataframe_old that I want to transform into dataframe_new so that I can use it later on. Dataframe_old. I was able to create the structure dataframe_new so that I only have to fill in all the cells by searching the dataframe_old for each row/column pair. Column 1 has the key for each field id and value but I'm always out of bounds. I need to do something like "iterate" until column-1 but my attempts did not yield good results.
These are the 2 dataframes I work with
import pandas as pd
import numpy as np

data_old = {'seq': [100,100,100,100,1002,1002,1002,1003],
        'fieldID':['name','income','married','age','name','dollar','date','age'],
        'fieldValue':['George',100,'yes',38,'Martiness','5000','01/01/2000','45']
       }

data_new = {'seq': [100,1002,1003],
         'name': ['','',''],
         'income': ['','',''],
         'married': ['','',''],
         'age': ['','',''],
         'dollar': ['','',''],
         'date': ['','','']
        }

df_old = pd.DataFrame(data_old)
df_new = pd.DataFrame(data_new, index = data_new['seq'])

I created a function to help me look up values
def find_value(sequence, field_identifier):
    '''
    search for values of fields from the original
    export by using the sequence number and field id
    '''
    try:
        df_func = df_all.loc[(df_all['seq'] == sequence) & (df_all["fieldID"] == field_identifier)]
        field_value = df_func.at[0, "fieldValue"]
    except:
        field_value = ""

    return field_value

Now I'm trying to combine everything but this ends up with out of bounds
for row in df_new.iterrows():
    cnt_col = 0
    first = True

    for column in df_new:
        if first:
            first = False
            continue
        else:
                fieldID = df.columns[cnt_col]
                seq = index

                df_new.loc[app, fieldID] = find_value(app, fieldID)

                cnt_col += 1

This is what my expected result would be
data_expected = {'seq': [100,1002,1003],
                 'name': ['George','Martiness',''],
                 'income': [100,'5000',''],
                 'married': ['yes','',''],
                 'age': [38,'','45'],
                 'dollar': ['','',''],
                 'date': ['','01/01/2000','']
        }

df_expected = pd.DataFrame(data_expected)

I tried to search the web but I'm stuck on this part and just can't get it to work.
Comment: you just try to fill df with dictionary data?
Comment: no, I used the dictionary to create an example dataframe to show my problem. The actual data is a very large csv file.
Answer: IF you don't have multiple fieldID per seq:
df_old.pivot(index="seq", columns="fieldID", values="fieldValue").reset_index().fillna('')

Outputs:
fieldID   seq age        date  ... income married       name
0         100  38              ...    100     yes     George
1        1002      01/01/2000  ...                 Martiness
2        1003  45              ...

IF you do have multiple fieldID, and you wish to keep them all- this will agregate them into list:
df_old.pivot_table(index="seq", columns="fieldID", values="fieldValue", aggfunc=list).reset_index()

Outputs:
fieldID   seq   age  ... married         name
0         100  [38]  ...   [yes]     [George]
1        1002   NaN  ...     NaN  [Martiness]
2        1003  [45]  ...     NaN          NaN

Comment: this worked! I also spend the morning finding the trouble maker rows and it turns out the drop_duplicates does not affect fieldValues with white space differences like "1234 test AVE   " and "1234 test AVE         " is not removed. But when I pivot the data it is flagged as a duplicate and throws an error.

Another way it worked was to use the strip function

`df_old['fieldValue'] = df_old['fieldValue'].str.strip()`

but I think using the subset is more robust going forward as the fieldValues per ID and Seq really should be unique anyway.

I finally grasped the problem, thank you!
Comment: thank you Grzegorz, I actually tried the pivot before without luck. It seems the aggfunc was the parameter I missed. The fieldID's per seq should be unique but it seems they are not. I used the drop_duplicates before but it seemed to now work for all entries. Even after using it the output shows a single value in the aggregated values which is the correct one and therefore tells me it is a duplicate. Either way, I know where to continue which is a big help!

this was the line I thought would take care of it but didn't
`df_old.drop_duplicates(subset=None, keep="first", inplace=True)`
Comment: No worries. Glad it worked :) I think to make your ```drop_duplicates``` work in this case - I would do: ```df_old.drop_duplicates(subset=["fieldID", "seq"], keep="first", inplace=True)``` (so it will track duplicates based only on the columns listed in ```subset```)
Answer: You can try this:
d = (df_old.groupby('seq')
       .apply(lambda x: dict(zip(x['fieldID'],x['fieldValue'])))
       .to_dict())
pd.DataFrame.from_dict(d, orient='index')

Comment: thank you. I marked the answer as helpful but I don't have enough points so it does not show. Your solution worked as well in the example and also gave me a data frame for the entire dataset I'm working with. Unfortunately, it removed most of the data from the dataset. I suspect this is due to the duplicate index problem I'm investigating now.


AjaxPro não acessível no IIS

Question: Tenho uma aplicação simples com WebForms, criei alguns métodos que irei acessar por Ajax via AjaxPro DLL.
Utilizei o atributo [AjaxPro.AjaxNamespace("Teste")] na classe e o [AjaxPro.AjaxMethod] no metodo.
Fiz o registro da classe no AjaxPro AjaxPro.Utility.RegisterTypeForAjax(typeof(Teste))
No javascript defini a chamada do metodo Teste.MetodoTeste().value
E no web.config defini a configuração do AjaxPro desta maneira:
<add verb="POST,GET" path="/ajaxpro/*.ashx" name="AjaxPro" type="AjaxPro.AjaxHandlerFactory,AjaxPro" />

No próprio Visual Studio, quando eu executo a aplicação, utilizando o IIS Express, o método é chamado corretamente e consigo pegar o retorno tranquilamente.
A questão é, por que quando eu publico a aplicação no IIS Local o sistema não localiza mais o AjaxPro?
Recebo vários erros:

Failed to load resource: the server responded with a status of 404
  (Not Found)

e

Index.aspx:66 Uncaught ReferenceError: Teste is not defined(…)

no console do navegador.
Comment: Você não esqueceu de registrar o tipo da sua classe para o `AjaxPro`?
Exemplo:  `Utility.RegisterTypeForAjax(typeof(Teste), Page)`
Comment: Eu registrei, desculpe esqueci de dizer. Porem foi diferente da sua sugestão: AjaxPro.Utility.RegisterTypeForAjax(typeof(Teste));
Comment: A DLL foi enviada na hora de publicação?
Comment: Sim, a Ajaxpro.dll está na pasta bin do projeto no diretorio virtual que o IIS criou.
Answer: Problema resolvido!
No web.config a configuração do ajaxpro estava da seguinte maneira:
<add verb="POST,GET" path="/ajaxpro/*.ashx" name="AjaxPro" type="AjaxPro.AjaxHandlerFactory,AjaxPro" />

Fiz um ajuste na tag path e a aplicação passou a funcionar no IIS Local e no IIS Express:
<add verb="POST,GET" path="*.ashx" name="AjaxPro" type="AjaxPro.AjaxHandlerFactory,AjaxPro" />

AjaxPro não acessível no IIS


Add a vector as legends in Matlab

Question: I have a vector whose entries I want to be the titles of the graphs which of my plot. How do I do that? I know that I can only add 1 legend to a plot.
n=[2 4 6 8 10];
legend(int2str(n));

and it should appear as 5 different legends named "2", "4"....,"10".
I'm not really familiar how to change the vector n into a string vector.
Thanks
Answer: An easy and intuitive may (in my opinion) would be to create the string corresponding to each element of the vector with sprintf. In my example I use a for-loop to generate curves, but the idea would the same if the curves were generated elsewhere. You can customize the text as you want of course. The code is based on as many curves as there are elements in n.
Example:
clear
clc

x = 1:10;

y = rand(1,10);
n=[2 4 6 8 10];

%// Initialize the cell containing the text. For each "n" there is a cell.
LegendString = cell(1,numel(n));

%// Plot every curve and create the corresponding legend text in the loop.
hold all
for k = 1:numel(n)

    plot(x,n(k)*y)
    LegendString{k} = sprintf('n = %i',n(k));
end

%// Display the legend
legend(LegendString)

Output:

Hope this is what you meant.
For a one-liner you can use arrayfun with num2str (thanks to @Divakar for the suggestion):
arrayfun(@(n) ['n = ',num2str(n)],n,'Uni',0)

Which gives a cell array that you can use directly in the call to legend.
Comment: Nah, feeling too lazy! :)
Comment: One-liner `arrayfun(@(n) ['n = ',num2str(n)],n,'Uni',0)`?
Comment: haha I never think about `arrayfun` good idea! You can post it as an answer I'll +1
Comment: You're welcome! Be sure to try  @Divakar's suggestion as well its a nice and clean one-liner.
Comment: Feel free to add that code into the answer though! Comments get deleted.
Comment: Oh I dit not know that I'll add it. Thanks!

Add a vector as legends in Matlab


Range of a centered, reduced sample drawn from a bounded domain

Question: Assume you draw $N$ values from a bounded set, say $[0, 1]$ without loss of generality.
If I am right, the centered values $X-m$ will remain in range $[{1\over N}-1, 1-{1\over N}]$ (by considering the most imbalanced 0/1 cases). And the standard deviation in range $[0,{1 \over 2}]$ (even $N$) or $[0,{1\over 2}\sqrt{1-{1\over N^2}}]$ (odd $N$) (by considering the most balanced 0/1 cases).
But what is the range of the centered-reduced values ${X-m\over s}$ ? How can I address this ?
Comment: I'm having trouble understanding your scenario.  Do you mean $N$ samples, or one sample of size $N$?  Are you assuming a probability distribution on [0,1]?

And I'm not sure what you're saying about the mean being in $[1/N, (N-1)/N]$.  Is this some sort of confidence interval? It doesn't seem correct though - what if $N=1$ (in which case the interval is empty)? Or $N=2$ (in which case it is the singleton $\{1/2\}$)?

After that, I got really lost.
Comment: Any set of $N\lt \infty$ numbers is automatically bounded between their minimum $a$ and maximum $b$.  When $s$ is defined, $b-a\gt 0$. Let $z$ be any value of $(X_i-m)/s$.  Then $z$ also equals $(X_i'-m')/s'$ where $X_i'=(X_i-b)/(a-b)$, $m'$ is the mean of the $X'$, and $s'$ is their SD.  Notice that the $X'$ lie in the range $[0,1]$.  That's why boundedness is irrelevant.
Comment: I mean N values drawn from the range [0 1]. This is not a probability-related question, the distribution does not mater. I just need safety bounds to represent the centered/reduced values. Oooops, you are quite right, the mean m is obviously in range [0 1] and I wanted to express the range of X-m, which I did erroneously :(
Comment: Since $(X-m)/s$ is invariant under changes of scale, the fact that the set is bounded is irrelevant. At this point it looks like you are pursuing Chebyshev-like inequalities, depending on what assumptions you make about the distribution of the samples.
Comment: Given $N$ arbitrary numbers $Xi$ in range $[0, 1]$, I want to know the smallest and largest values that ${Xi-m}\over s$ can reach. Either they are unbounded or they are in a finite range that should be just a function of $N$.
Answer: I think I understand now.  You want to know what the maximum and minimum possible values of $(X-m)/s$ can be.
My feeling (I haven't worked this out analytically) is that this will be maximized when all of the observed values are the same except for one.  Suppose without loss of generality that  have $N-1$ observed values of 0, and one observed value of $1$.  In this case, the mean will be $1/N$, the median $m$ will be $0$, and $s=1/\sqrt{N}$. The maximum value of $$\frac{X-m}{s}$$ is therefore $\sqrt{N}$.
Comment: +1 That $\sqrt{N}$ is the best possible bound follows immediately from Chebyshev's Inequality applied to the empirical CDF of the data.
Comment: Sorry, by $m$ I didn't mean the median but the arithmetic mean.
Comment: Hmm.  I was sure that I'd read the word "median" somewhere, but it must have been a different question.  My mistake!
Comment: Assuming $Z$ zeroes and $N-Z$ ones, the average is ${N-Z\over N}$ and the variance ${Z(N-Z)\over N^2}$; the range is [${0-m\over s}, {1-m\over s}$], i.e. [$-\sqrt{{N-Z\over Z}}, \sqrt{{Z\over N-Z}}$]. The smallest lower and largest upper bounds are obtained for $Z=1$ and $Z=N-1$ respectively, showing that the range $[-\sqrt{N-1}, \sqrt{N-1}]$ can be reached, just like you said (I am using the biaised $s$).
Answer: Let the data be $X_1, X_2, \ldots, X_n$ and, noting that all the $X_i$ are interchangeable, we may without loss of generality extremize $f(X_1, \ldots, X_n) = (X_1 - \bar{X})/\text{sd}(X)$ assuming $\text{sd}(X)\ne 0$ (which implies $n\gt 1$).  Because $f$ is unchanged under translations and rescalings of the $X_i$, we may assume $\bar{X}=0$ and $\text{sd}(X)=1,$ whence $f(X) = X_1.$  This is a constrained linear program defined on $\mathbb{R}^n$:
Optimize
$$X_1$$
subject to
$$X_1 + X_2 + \cdots + X_n = n\bar{X} = 0$$
$$X_1^2 + X_2^2 + \cdots + X_n^2 = n(\text{sd}(X))^2 = n.$$
Introducing Lagrange multipliers $\lambda,$ $\mu,$ and $\nu$, the critical points must lie on solutions to
$$\lambda(1,0,\ldots,0)+\mu(1,1,\ldots,1)+2\nu(X_1,X_2,\ldots,X_n)=(0,0,\ldots,0).$$
It is immediate that for any solution $X_2=X_3=\cdots=X_n=-\mu/(2\nu)$.  Let this common value be $Y$.  Because the mean is zero,
$$X_1 = (1-n)Y.$$
Because the sum of squares of the $X_i$ is unity, we find
$$n = X_1^2 + X_2^2 + \cdots + X_n^2 = \left((1-n)Y\right)^2 + Y^2 + \cdots + Y^2 = n(n-1)Y^2,$$
yielding $Y = \pm \sqrt{1/(n-1)}$ and extreme values
$$f^{*}(X_1, X_2, \ldots, X_n) = X_1^{*} =\pm (1-n)\sqrt{1/(n-1)} = \pm\sqrt{n-1}.$$
This shows that the values of $f$ necessarily lie between  $-\sqrt{n-1}$ and $\sqrt{n-1}$ and reach those extrema if and only if all but one of the $X_i$ have the same value and the remaining one has a different value.  When $n\gt 2,$ $f^{*}$ can attain any value in between these extremes because $f$ is a continuous function on the connected set $\mathbb{R}^n - \{(t,t,\ldots,t)\ |\ t\in\mathbb{R}\}$.  When $n=2,$ $f^{*}$ either equals $1$ or $-1$ but cannot attain any value in between.
Comment: I just discovered that this result is known as Samuelson's inequality: http://en.wikipedia.org/wiki/Samuelson's_inequality.
Comment: Excellent, thanks. Imposing the value of the mean and deviation was the good idea.
Comment: Thank you.  According to Stigler's Law of Eponymy, it would be unlikely for Samuelson to be the original discoverer--and indeed, the Wikipedia article points to Laguerre a half century earlier.  One tiny additional result in my answer is that all possible values between the bounds can actually be attained.


is it possible to delete the object after it returned?

Question: I want to delete some object after it returned function
for example
def  A():
    imgA = img_generator()
    return imgA

def  B():
     for i in range(1000000):
          imgB = A()

if I want to delete the memory usage of A()'s imgA. how should I do it?
Comment: What is the [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)?
Comment: When exactly do you think that you want `imgA` to be deleted? When do you think that it is being deleted in the code you posted?
Comment: first: you can use `return img_generator()` and you don't have this variable. Second: Python doesn't duplicate object when you send it from function but it send rather reference - so if you really delete object in `imgA` then you also delete object in `imgB`. So there is no need to delete `imgA`
Comment: Python's garbage collection is pretty smart so normally you don't have to worry about these kind of things
Answer: The reference of imgA is been overwritten each time in the for loop, so only one instance of imgA is in memory at the same time. For deleting memory usage of variables you can do 2 things: use del imgA or assing it to None like this imgA = None. The difference is that in the first case, the variable is completely removed from the namespace and sent to the Garbage Collector and the second case, the variable is still alive but its content is sent to the Garbage Collector. However in python you shouldn't worry about those things since it's handled automatically for you.


database connection error & Database was not shutdown normally

Question: I need some solution for my wordpress site database error. I have face this DB error last one month. I don't know what is the reason for this Database connection error. Please review my error.log provide your succession.
2018-06-19 15:59:15 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2018-06-19 15:59:16 4297 [Note] Plugin 'FEDERATED' is disabled.
2018-06-19 15:59:16 4297 [Note] InnoDB: Using atomics to ref count buffer pool pages
2018-06-19 15:59:16 4297 [Note] InnoDB: The InnoDB memory heap is disabled
2018-06-19 15:59:16 4297 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2018-06-19 15:59:16 4297 [Note] InnoDB: Compressed tables use zlib 1.2.8
2018-06-19 15:59:16 4297 [Note] InnoDB: Using Linux native AIO
2018-06-19 15:59:16 4297 [Note] InnoDB: Using CPU crc32 instructions
2018-06-19 15:59:16 4297 [Note] InnoDB: Initializing buffer pool, size = 1.0G
2018-06-19 15:59:16 4297 [Note] InnoDB: Completed initialization of buffer pool
2018-06-19 15:59:16 4297 [Note] InnoDB: Highest supported file format is Barracuda.
2018-06-19 15:59:16 4297 [Note] InnoDB: The log sequence numbers 50223779105 and 50223779105 in ibdata files do not match the log sequence number 50225310342 in the ib_logfiles!
2018-06-19 15:59:16 4297 [Note] InnoDB: Database was not shutdown normally!
2018-06-19 15:59:16 4297 [Note] InnoDB: Starting crash recovery.
2018-06-19 15:59:16 4297 [Note] InnoDB: Reading tablespace information from the .ibd files...

Answer: First check uptime of server on which you have hosted DB may be your server is restarting due to some reason, if uptime is ok then you need to check if there is any HDD or memory issues, check for bad blocks or ram errors
you can try repairing mysql DB/tables by using "mysqlcheck --auto-repair -o --all-databases"
You should add a cron job to backup your data on daily basis, incase mysql recovery fails you can restore


dissecting a hypercube to simplexes

Question: I read that an n-cube (hypercube) can be dissected into $n!$ n-simplexes.  In case of 2D, I can see that a square can be dissected into two 2-simplexes (traingles).  Incase of cube, how we can fit six, tetrahedron inside it ?
Answer:
Please see also this YouTube video: https://www.youtube.com/watch?v=ffnVCEAcOns

dissecting a hypercube to simplexes


UPDATED: Express.js req.body is an empty object & req.body.name is undefined

Question: I am not sure what I'm doing wrong here, but I'm not getting anything from req.body or req.body.name.  I'm just trying to get text from an input field in a React component.  Here's my POST request:
    //posting notes to backend and storing in db
module.exports = (app,bodyparser,mongoUrl) => {

    let MongoDB = require('mongodb').MongoClient;
    app.use(bodyparser.urlencoded({extended: false}));
    app.use(bodyparser.json());

    app.post('/notes',function(req,res){
        //posting the note just fine, just not receiving the note text (says undefined)
        //not getting note text for some reason?? only returning the date...

        //send response to append note to page
        //store note data in db

        let noteData = {
            text: req.body.name,
            date: new Date().toDateString()
        };
        console.log(req.body);
        MongoDB.connect(mongoUrl,function(err,db){

                let notesCollection = db.collection('notes');
                notesCollection.insert(noteData);
                db.close();
        });

        res.status(201).send(noteData);

    });

}

And my React Component:
class NewNote extends Component {
//this is for creating a new note only
//need post request for this one
//need to clear textarea upon submit or cancel
    render(){
      return (

            <form action="/notes" method="POST" encType="multipart/form-data">
              New Note:
                <input type="text" name="name" className="form-control" rows="5" id="newNote" placeholder="Write your note here..."></input>
                <button id="done" type="submit" className="btn btn-primary pull-right">Done</button>
                <button id="cancel" className="btn btn-warning pull-right">Cancel</button>
            </form>

      )
    }

}

And my package.json file:
{
  "name": "quick-notes-app",
  "version": "1.0.0",
  "description": "my first full-stack javascript app",
  "main": "./routes/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon --exec babel-node ./routes/server.js --ignore public/",
    "dev": "webpack -wd",
    "lint": "eslint ./"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/CandiW/quick-notes-app.git"
  },
  "author": "CandiW",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/CandiW/quick-notes-app/issues"
  },
  "homepage": "https://github.com/CandiW/quick-notes-app#readme",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.3",
    "mongodb": "^2.2.35",
    "randomcolor": "^0.5.3",
    "react": "^16.3.2",
    "react-dom": "^16.3.2"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-eslint": "^8.2.3",
    "babel-loader": "^7.1.4",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "eslint": "^4.19.1",
    "eslint-plugin-react": "^7.7.0",
    "nodemon": "^1.17.3",
    "webpack": "^3.11.0"
  }
}

This is my server.js file where I've required the body-parser module:
const express = require('express');
const path = require('path');
const bodyparser = require('body-parser');
const notes = require('./notes.js');
const myNotes = require('./mynotes.js');
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;

let app = express();
let database = "mongodb://localhost:3000/";

    app.use(express.static('public'));
    app.use(bodyparser.urlencoded({extended: true}));
    app.use(bodyparser.json());

function quickNotesApp(port){
    // eslint-disable-next-line no-console
    console.log("listening on port " + port);

    notes(app,bodyparser,database);
    myNotes(app,bodyparser,database);

    app.listen(port);

}

quickNotesApp(3000);

Please excuse my comments in the code :) I'm using them to keep track of my to-do's and what each component does.  You all can see my github repo for my app here: Quick-Notes-App
Update 5/2/2018:
I have made some changes to how I'm using body-parser and how I'm using it in my POST request (I've updated the original code samples I attached).  At this point, I'm still receiving the same text: null when I return the array of docs from my database and when I console.log req.body its still an empty object.  Wondering if anyone has any thoughts on if React.js is the issue?  For example, we have to use className instead of class in our React Components.  I'm not finding anything readily to answer that question.  I have also uninstalled and reinstalled express, body-parser, and all the rest of my dependencies to no avail.
Update 2 - 5/2/2018
For anyone who might find this useful, I found this Medium article on how to combine a Node.js backend with a React.js frontend.  I think I'm going to try this out and see if it helps.
Comment: Can you please share your package.json
Comment: Sure - I'll edit the post here in a second
Comment: Can you please share also index.js of server side code.
Comment: It's there now!
Comment: you have to add `app.use(bodyParser.json());` like my below ans.
Comment: if not work let me know, thanks.
Comment: Thanks! I'll go try it out :)
Comment: I have given ans. below with your full index.js
Answer: npm i --save body-parser
const body_parser = require('body-parser');
app.use(body_parser.json());
app.use(body_parser.urlencoded({extended: true}));

Comment: i was using typescript and considered importing bodyParser like this and it worked
Comment: It'll be better if you add an explanation for why your code works.
Answer: Add this also app.use(bodyParser.json());
const express = require('express');
const path = require('path');
const notes = require('./notes.js');
const myNotes = require('./mynotes.js');
const bodyparser = require('body-parser');
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;

let app = express();
let database = "mongodb://localhost:3000/";
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json());

function quickNotesApp(port){
    // eslint-disable-next-line no-console
    console.log("listening on port " + port);
    app.use(express.static('public'));

    notes(app,database);
    myNotes(app,database);

    app.listen(port);

}

quickNotesApp(3000);

Comment: Ok - this didn't work.... Here's what it looks like in the database: `{"_id":"5ae872c5347b9e23901bf419","text":null,"date":"Tue May 01 2018"}`  As you can see, the `text` is `null`.
Comment: I have made some changes and edited my original question to reflect those updates.  In short, I'm still receiving the same `"text": null`.


In EJB 3.0 , PostConstruct not called

Question: I want to have a scheduled job run once every hour, the scheduled job is defined in EJB 3.0 stateless session bean (the bean class is annotated with @Stateless). I am restricted to EJB 3.0 so I cannot use @Singleton/@Schedule. The issue is that @PostConstruct annotated method to initialize the timer defined in that EJB 3.0 session bean is never called.
My timer method that is supposed to run once every hour is annotated with @Timeout in the stateless session bean.
Reading other questions it says in EJB 3.0, session beans are lazily created, ie. unless the bean is called from code outside the bean class, PostConstruct annotated method is never called.  How do I call the bean from outside the bean and make sure I call only one time when the Tomee EJB container is deployed?
The bean just runs a method once every hour. There is no need to call any method in the bean either locally or remotely.
Comment: Singleton and Schedule annotations are not available in ejb 3.0.
Answer: It's possible to create a stateless container that has minSize and maxSize set to 1.  The result should be that TomEE will eagerly fill your pool to the minimum size and not exceed the desired maximum size.
You probably don't want that setup for all your stateless beans, however, so you'll also need to explicitly declare a stateless container that uses default settings.
<Container id="Default Stateless Container" type="STATELESS">
</Container>

<Container id="pizza" type="STATELESS">
    maxSize = 1
    minSize = 1
</Container>

I've called the second container pizza rather than something descriptive like singletons just so it's clear the name is not any kind of magic -- use any name you like.  Note the order of the container declarations is significant.  When there are two stateless containers, TomEE will by default put all the stateless beans in the first container unless you specify otherwise.
To ensure your bean goes into the second container you'll want to an openejb-jar.xml file in the META-INF/ folder of that bean's jar.  For example, if the bean class is com.example.Peperoni then you could put it into the pizza container like so:
<?xml version="1.0"?>
<openejb-jar>
    <ejb-deployment ejb-name="Peperoni"
         deployment-id="Peperoni"
         container-id="pizza"/>
</openejb-jar>

In EJB 3.0 , PostConstruct not called


Unit test - Moq abstract class with SetOwinContext

Question: I am trying to Moq to test abstract class method.
var mock = new Mock<BaseStudentController>();
mock.CallBase = true;
var ta = mock.Object;
var result = await ta.ActivateStudent"email@example.com", true);

This successfully mocks the base class, and it hits the method in my abstract class.
Problem:
However, my abstract class is also expecting Request.GetOwinContext. I am not sure how i can moq it along with my above request.
Answer: You should set up ControllerContext before calling ActivateStudent
ta.ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() };
ta.Request.SetOwinContext( /* mock IOwinContext here */);

Sample owin context mock:
var owinMock = new Mock<IOwinContext>();
owinMock.Setup(o => o.Authentication.User).Returns(new ClaimsPrincipal());
owinMock.Setup(o => o.Environment).Returns(new Dictionary<string, object> { {"key1", 123} });
var traceMock = new Mock<TextWriter>();
owinMock.Setup(o => o.TraceOutput).Returns(traceMock.Object);

Comment: No, you should setup all these things (used by controller). See updated answer
Comment: The idea is the same - just setup everything you need. Added example for `Environment` and `TraceOutput`. As for `UserManager` you'd better ask a new question and it will be easier to help if you'll show the code were it is used.
Comment: Thanks understood your point. I have already spent time on SetOwinContext() but literally not sure how i can mock it? Any idea
Comment: tried `new Mock().Object`? just set up required behavior.
Comment: Thanks, give me few minutes, i check and revert whether it solves my issue or not.
Comment: @ Aleksey L. It mocks OwinContext but gives null for all (Authentication, Environment, Request, Resposnse, TraceOutput). Shouldn't new Mock().Object auto populates these objects when mocked?
Comment: Btw, if you'd use [fakeiteasy](http://fakeiteasy.readthedocs.io/en/stable/quickstart/) instead of moq it would auto populate these properties with fakes
Comment: Well, i have mocked Request and Response. owinMock.Setup(o => o.Request).Returns(new Mock().Object);
            owinMock.Setup(o => o.Response).Returns(new Mock().Object); I couldn't find way to mock Environment and TraceOutput.
Comment: Also, i have TestUserManager dervived from UserManager and TestRoleManager dervied from RoleManager class. How i can mock them as well in my above requirement? I come with this so for             var userStore = new Mock>();
            var userManager = new TestUserManager(userStore.Object);
 but not sure how i can hook it up with my code. Kindly advise
Comment: Thanks a lot. I have created another question. http://stackoverflow.com/questions/38628372/how-do-i-mock-usermanager-and-rolemanager-for-unit-test


Jquery File Upload not working with Gravityforms

Question: I am trying to implement  JQuery File Upload plugin with Gravity Forms wordpress plugin. I have created a form with file upload input for which Gravity form generated field id like input_1_33. I am using this id for file upload jquery plugin.
<code>jQuery(function () {
 var url = 'http://localhost/wp-content/themes/testtheme/fileupload/';
 jQuery('#input_1_33').fileupload({
                    replaceFileInput:false,
                    url: url,
                    dataType: 'json',
                    done: function (e, data) {
                        jQuery.each(data.result.files, function (index, file) {

                            jQuery('<p/>').text(file.name).appendTo('#files');
                        });
                    },
                    fail:function(e, data){

                    },
                    progressall: function (e, data) {
                        var progress = parseInt(data.loaded / data.total * 100, 10);
                        jQuery('#progress .progress-bar').css(
                            'width',
                            progress + '%'
                        );
                    }
                }).prop('disabled', !jQuery.support.fileInput)
                    .parent().addClass(jQuery.support.fileInput ? undefined : 'disabled');
  });
</code>
No error was generated in browser console and file is not uploaded
Answer: I've created a plugin that integrates this with Gravity Forms.
You can find it on the WordPress plugin directory - https://wordpress.org/plugins/ajax-upload-for-gravity-forms/
And see a demo of it here - http://demo.itsupportguides.com/ajax-upload-for-gravity-forms/
Comment: @SrikanthKolli you should not use the deprecated plugins this plugin was deprecated
Comment: Thanks for sharing. Great!