How do extract the string before the colon?

Question: How do extract the string before the colon. I don't want the string after the colon.
Sample input:
asfmqwdbd/ilcp:dftqclk_rep

Desired result:
asfmqwdbd/ilcp

My code:
if (m/^(\S+))
  $inst_name = $1;

Comment: `m/^([^\s:]+)/` - if you meant *before the first **colon***
Comment: Can ypu please edit your question? Your example does not contain a semicolon `;`. Did you mean colon `:`?
Comment: Shouldn't the desired result be `asfmqwdbd/ilcp`?
Answer: Assuming that semicolon (;) was a typo in the question and you actually meant colon (:) this would be the correct regex:

anchor at beginning of line (^)
capture one-or-more non-colon characters (([^:]+))
match must end on a colon (:)

#!/usr/bin/perl
use warnings;
use strict;

while (<DATA>) {
    print "$1\n" if /^([^:]+):/;
}

exit 0;

__DATA__
asfmqwdbd/ilcp
asfmqwdbd/ilcp:dftqclk_repasfmq
asfmqwdbd/ilcp;dftqclk_repasfmq

Test run:
$ perl dummy.pl
asfmqwdbd/ilcp

Answer: Assuming from your question you want the output like this
"asfmqwdbd/ilcp"
for this you can use "^([\S]+):" and then use $1.
Answer: I think you are looking for
$ echo "asfmqwdbd/ilcp:dftqclk_repasfmq" | perl -pe 's/(\S+):.*/$1/ '
asfmqwdbd/ilcp

or
$ perl -le ' $x="asfmqwdbd/ilcp:dftqclk_repasfmq"; $x=~s/(\S+):.*/$1/; print $x '
asfmqwdbd/ilcp

$


Show that $N_{L/\mathbb{Q}}(O_L^*)=\{1\}$ and deduce that $[O_L^*:O_K^*]=3$ if $p=3$ and $[O_L^*:O_K^*]=1$ if $p\ne3$

Question: I'm studying for the Algebraic Number Theory exam and I can't solve the problem from last year's exam. Here is the question:
Consider the real quadratic field $K=\mathbb{Q}(\sqrt{10})\subset\mathbb{R}$, and the quadratic field $L=K(\sqrt{-p})\subset\mathbb{C}$ where $p$ is a prime number.
(a) Prove that $\eta=3+\sqrt{10}$ is a fundumental unit of $K$, i.e. $O_K^*=<-1,\eta>$.
(b) Show that $O_K^*$ has a finite index in $O_L^*$.
(c) Show that $[O_L^*:O_K^*]$ divides 6.
(d) Show that $N_{L/\mathbb{Q}}(O_L^*)=\{1\}$ and deduce that $[O_L^*:O_K^*]=3$ if $p=3$ and $[O_L^*:O_K^*]=1$ if $p\ne3$
So far I was able only to prove that $\eta$ is a fundamental unit (by looking at the norm and solving the Pell equation). I also think that the rank of the unit group $O_L^*$ is $2+1-1=2$, but I can't move any further.
Thank you very much!
Answer: Hint for part (b): the question says that $\mathcal O_K^* \subseteq \mathcal O_L^*$ is finite index, which implies $ \mathcal O_L^*$ should be rank 1. I guess you are calculating it using Dedekind's unit theorem, so it looks like you have counted the number of real and complex embeddings of $L$ incorrectly. Note that $\sqrt{-p}$ can never be embedded into $\mathbf R$.
Comment: Thank you! I see, so there should be 4 complex embeddings and 0 real ones, so the rank is $0 +4/2 -1=1$... But how to compute the index? Should I look for a fundamental unit in $O_L^*$ ?


Detecting trend divergence between two time-series datasets

Question: Is there a relatively simple to implement method out there for detecting the early stages of divergence between two time series ?  To take a simple example from the financial area, a common one is detecting the start of divergence between asset price and an associated "indicator" or "oscillator" chart in order to identify the begginings of a trend reversal.
Answer: If you create a percentage difference between the two variables then evaluate with a plot like a simple time series or cusum chart (CUSUM Control Charts) should give you what you are after.
Comment: Also, thanks @Nikolas Rieble for the fixed link description.


Q-value for FDR correction in R stats package

Question: I used FDR correction (i.e., Benjamin-Hochberg tests) from the R 'Stats' package, but I'm confused of the q value used in the package. The notations in the 'p.adjust' function does not include the default setting for q values, which makes me feel a little less confident. For example, here is my original p-value list:
 p_raw <- c(8.133371e-04, 2.471103e-01, 3.343610e-03, 2.505031e-03, 2.887362e-06, 5.736712e-19, 8.955674e-03, 1.199260e-02, 7.698829e-04, 3.301545e-02, 1.126950e-03, 9.405598e-03)

Here is my R code for adjusting p-values:
p_adjust <- round(p.adjust(p_raw,method="BH"),3)

Here is the output for p_adjust:
0.002 0.247 0.006 0.005 0.000 0.000 0.013 0.014 0.002 0.036 0.003 0.013

I tried to calculate q values using the formula p_adjusted = (i/m)*q where i is the rank and m is the number of tests but did not get consistent q values for each p_adjust output. I wonder if anyone knows how the R 'Stats' package calculates this and what q value is the package using?
Comment: Type in `p.adjust` with no parentheses and press Enter to see the source code of the function.
Comment: Thank you! This is helpful. I will update what I found in the formal answer.
Answer: P-values never use set significance levels as part of their computation.
In fact, the lack of reliance on any binary cutoff is part of the attraction of p-values.
In the case of p_adjust <- p.adjust(p, method="BH"), the elements with p_adjust < q for any value of $q$ are exactly the same elements that the original Benjamini-Hochberg (1995) method would choose as significant in order to control the FDR below $q$.
So the adjusted p-values and the original BH method are exactly equivalent.
Note that it is not sufficient to simply compute p_raw * m/i to get adjusted p-values, because those values are not generally monotonic in the original p-values.
It is necessary to apply an extra step to enforce monotonicity.
For a bit more background, see
https://support.bioconductor.org/p/49864/
and
What's the formula for the Benjamini-Hochberg adjusted p-value?
Comment: The links are helpful. Thank you for the answer!
Comment: What if I have performed a backwards stepwise variable selection? How do I apply the p-value adjustment then?
Answer: Thanks for COOLSerdash's prompt, I looked up the source code for p.adjust in stats package. Here is the part that's informative:
BH = {
    i <- lp:1L
    o <- order(p, decreasing = TRUE)
    ro <- order(o)
    pmin(1, cummin(n/i * p[o]))[ro]

Basically, stats uses a formula of m/i * raw_p to calculate the adjusted p instead of the traditional i/m * q. Therefore, there is no default q value in the R stats package FDR correction.
According to the R documentation of this p.adjust function, the original Benjamin-Hochberg (1995) paper was cited to support their method. The original paper used the p_raw <= i/m * q correction exactly as the procedure mentioned in this page. Therefore, just multiply the equation by m/i we get p_raw * m/i <= q. I assume the package uses p_raw * m/i to calculate adjusted p value and then it's upon us to decide what q value to use as criteria. I think it's commonly 0.05 or 0.1.


building a complex frontpage

Question: I've built all my site apart from the frontpage which right now shows:
No front page content has been created yet.

The frontpage will be the most complex page of all, containing a lot of boxes (blocks) which will be presenting lists of items.
I've got 2 solutions for this problem and I'd like to know which one is best.
solution 1 - blocks

create the ~10 blocks that the frontpage needs
make them translatable
use description prefix "front -" for easier identification in admin/structure/block
configure "Only the listed pages": <front>
somehow remove the "No front page content has been created yet" message

This solution seems very tunable. The CM will be able to do whatever he wants with the individual view blocks of the frontpage.
On the other hand there will be too many blocks in the administration page (but only 1 for all languages).
solution 2 - node

create a node
the node should be of a type which has fields for configuring the fetching and displaying of items. e.g fields:

int: number of news to fetch
int: number of events to fetch
bool: should display teaser
html: teaser content
etc

in admin/config/system/site-information set that node as Default frontpage

The drawback of this is that I should implement the fetching and display, and if the CM wants to change something that the content type does not support I'll need to implement it.
On the other hand I'll have full flexibility in HTML if I provide a separate template just for this content type.
So, is there a definite winner between those 2? Also note that, for various reasons, I don't want to use panels.
Comment: This is like the PERFECT use case for Panels - I'm not sure why you wouldn't want to use it.  But if you are REALLY set in your ways, then go with the blocks.  I'm not going to put this as an answer yet as someone else might be able to give you other ideas/suggestions.
Comment: @Chapabu: Feel free to add it as an answer.
Answer: I know you said you didn't want to use it, but this is a PERFECT use case for Panels.  I'm not a huge Panels user and will generally steer clear of it if I can, but sometimes you have to step outside of your comfort zone and just use the best tool for the job.
There's a video here that focuses on using Views and Panels for a home page layout.

In this Drupal video tutorial we take a brief look at panels. I show
  you how to recreate a home page that relies on views content panes. As
  a result, we create a two column home page panel which pulls in recent
  content from across all content types and shows which users are
  online.

But if you are REALLY set in your ways, then go with the blocks.  You can always put the blocks into Panels at a later date.
Answer: I have done this with blocks before, you can create a template file called page--front.tpl.php and do whatever you want there. Then make use of functions like views_embed_view to embed a view:
<?php print views_embed_view('case_studies','block_1'); ?>

Or use a block:
<?php print module_invoke('search', 'block_view', 'search'); ?>

My current project has a dynamic page calling all sorts of content elements and I am doing it with panels this time, consider using it.
Comment: Thanks. Have used `blocks` and will consider `panels` in the future if the frontpage becomes more complex.
Comment: I can confirm now that panels is awesome, a bit fiddly and I am sure there is a lot more I could do with it.

building a complex frontpage


'Endless Runner' Game Background in AS3

Question: I'm wanting to make an 'endless runner' game. So, I need a random scrolling background to act as the obstacles, platforms, ground, and background in general. It needs to be random though and not the same background repeated over and over.
The background I'm wanting to do is too complexed for tiles (or at least I don't think so). It will be a similar complexity to this game: http://www.mochigames.com/game/flood-runner-3/
How would I go about coding this?
Answer: There're lots of tutorials out there, you can try google firstly with "side-scrolling game" or "platformer game":
http://as3gametuts.com/2011/11/11/platformer-1/
http://www.youtube.com/watch?v=k38YrVxXkSM
etc...
And in my opinion, Circus Engine
is a great engine for platformer game in as3.

'Endless Runner' Game Background in AS3


Como adicionar em um array Jquery itens de uma IENUMERABLE em .Net MVC?

Question: Como faço para adicionar itens de uma IEnumerable<T> em um array JavaScript?
View:
@using Colecao.ViewModels
@model ConfiguracoesViewModel

    @foreach (var equipamento in @Model.Equipamentos)
    {
              //Gostaria de adicionar esses itens em um array JS.
    }

Comment: Tá confuso de entender. Você quer passar um `IEnumerable` de uma Action para o seu JS? Ou o `IEnumerable` está no seu JS?
Comment: Entendi, tu tens algum código feito? Isso pode ajudar pra entender melhor o que você tem e o pessoal te ajudar da melhor maneira. Caso tenha, clica em [edit] e adiciona esses detalhes.
Comment: Em JavaScript não há `IEnumerable`...
Comment: Eu passo o IEnumerable para a view! e no JS gostaria de manipular os itens da IEnumerable ,adicionando em um array .
Comment: @HansMiller como estás a passar para a view? podes colocar o código ou como aparece na view?
Answer: Você pode fazer da seguinte forma:
var equipamentos = @Html.Raw(Json.Encode(Model.Equipamentos));

Como utilizar?
Você pode utilizar normalmente como se fosse um json qualquer.
Digamos que o meu model de equipamentos esteja assim:
public class Equipamentos
{
    public string Nome { get; set;}
    public string Modelo { get; set;}
}

A sua utilização será da seguinte forma:
alert("Nome: "+ equipamentos[1].Nome + " | Modelo: "+ equipamentos[1].Modelo);

Comment: Como posso manipular essa variavel dentro da minha funcao JS?
Comment: Como um array qualquer, só que as propriedades vão depender do seu model.
Comment: @HansMiller, vou editar a pergunta adicionando como utilizar
Comment: Blz! só uma duvida aonde eu ponho esta funcao?

var firstname.lastname@example.com(Json.Encode(Model.Equipamentos));
Comment: @HansMiller, coloca dentro da sua tag ``.
Comment: como ficaria  o foreach em JQUery para adicionar ao Array?
Comment: @HansMiller, mover o model pra um array ou mover `json` do model pra um array??
Comment: var equipamentos = @Html.Raw(Json.Encode(Model.Equipamentos));

como mover cada item que esta dentro da coleção equipamento para um array[].
Comment: @HansMiller, equipamentos já é um array. Um array de equipamento. Caso queira refazer a lista, pode fazer `$.each(dispositivos,function(key, value){ console.log(key + " | " + value.Nome + " - " + value.Numero );});`


Erro para referencia serviço no Angular

Question: Bom dia,
Estou com o problema pra referenciar um serviço no angular. Segue erro:

ERROR in c:/Projetos/LivroAngular2/src/app/lista-pessoa-vip/lista-pessoa-vip.component.ts
  (2,10): Module
  '"c:/Projetos/LivroAngular2/src/app/lista-pessoa-vip/pessoavip-service.service"'
  has no exported member 'PessoavipService'.
ERROR in c:/Projetos/LivroAngular2/src/app/lista-pessoa-vip/lista-pessoa-vip.component.ts
  (2,10): Module
  '"c:/Projetos/LivroAngular2/src/app/lista-pessoa-vip/pessoavip-service.service"'
  has no exported member 'PessoavipService'.

Obrigado!
Comment: Olá, seria legal vc informar o que vc está fazendo, com qual código, colocar o exemplo do código, uma pergunta somente com o erro não ajuda a galera a ajudar =(
Answer: Tem que chamar ele la no ngModules. fazer o import dele la.
Comment: Obrigado Gilmar, solucionei o problema com a sua ajuda.
Comment: Marca como solucionado por favor :)

Erro para referencia serviço no Angular


How to update the field at particular date of month in database

Question: I want to give recharge to users at a particular date in every month. I want to use npm package cron to do
that but not getting the way to complete.Do I have to use middleware or any specific route for that.Someone give me a idea to complete that part.I am using node and mongodb.
Answer: I am not able to understand the problem, if it is finding an npm library or the logical approach, I will try to answer both here.

NPM library, try https://www.npmjs.com/package/node-cron, even though there are very good libraries out there, I suggest going native using OS cron to schedule the jobs

Logical Approach:- you need to write the respective logic of finding eligible users to whom you want to process recharge and then asynchronously or synchronously (depends on your business requirement) process recharges, now this job needs to be scheduled if you are using native OS cron help (you will find many tutorials to do same), or if you are using npm library then create a scheduler app which calls your actual app rest will be taken care by the library.
Comment: I want to give 1000 words limit  to  users at a particular date of month . So, how can I do that using npm library.


Windows 7 Print Spooler keeps serial ports locked also when stopped

Question: I have a program (environment is Windows 7 Enterprise 32bit) that scans available serial ports to detect a specific device.
But on many machines a printer driver is configured on one of the serial port (this does not means that there is actually a printer connected to that port).
In this case, my scan program can't open that port to search the device.
On Windows XP, stopping the spooler before starting the scan was enough to unlock serial ports allocated by the printer drivers. On Windows 7, this is not working anymore. If I have a printer configured on COMx and I stop the spooler, COMx can't be opened.
I've checked process locks with ProcExp: ports results allocated by spoolsv.exe process when spooler is running, and results NOT allocated by anyone when the spooler is stopped.
Any idea about how to momentarily unlock ports allocated by printers?
A workaround I found is to change port of every serial printer to FILE: before the scan and back to the COMx when the scan finished, but I wonder if there is a simpler solution.
Comment: Have you tried a utility like Unlocker?  See if you can remove the locking handle rather than killing spooler.  (Wait, would that even work on a locked COM port?  well, it's a thought, at least.)
Comment: Unlocker does not work with serial ports. But ProcExp (Process Explorer) can search specific names locked amongst all processes' handles. And it found no lock on serial ports when spooler is stopped.
Answer: I had a similar problem which was solved by changing the port name from COM1 to COM4 in the serial port advanced properties (via the device manager).
Everything then worked fine. Some programs still see the renamed port as COM1, but now they can access the port.


On IIS port 80 is timing out, but 443 returning the page immediately over port 80

Question: I have a self hosted site running on IIS.  Worked perfectly.  Used win-acme to generate a cert.  My bindings are 80 first and 443 second.  My cert ran out and has failed to renew.  It's failing because port 80 (http) is timing out.  The weird part is that when I try to connect over https (443), it fails to connect, but then instantly loads the http site with a warning that the connection is not secure!  Therefore can't be firewall related.
Nothing has changed on the host, apart from the cert running out.  Any ideas anyone, I've run out and am now considering trying to beat it into line with a big stick!
Thanks in advance
Jim
Comment: Show your exact site bindings please (which are more than just ports). Besides, to prove "instantly loads the http site", see into IIS log files for log entries on port 80 please. Without those you cannot say "Therefore can't be firewall related" yet.
Comment: It may also be caused by the cache. You can try clearing the cache and trying again.
Answer: Too smart/confident for my own good!  Knew the router was 100% as I'd set it up myself.  Turns out somebody had been on there and deleted the port 80 NAT entry.  Sigh...


How to post an image link to Facebook feed using graph API

Question: I'm trying to post a picture to a feed using the graph API but this does not work if my image url does not have an image filename extension such as .png
(I have a URL to a png without the .png file extension as the image is created dynamically on the server)
This does seem to work when I manually post the link on my Facebook wall. Facebook wraps the URL like this:
http://external.ak.fbcdn.net/safe_image.php?d=AQAsdfyQsdfXvV5h59OP&w=90&h=90&url="my image url"
Does anyone know how I can post the URL of an image to the picture field of a feed post?
Answer: Facebook downloads and caches any image posted on the wall. It is then distributed on their CDN (content delivery network).
The reason is simple: load times. If someone posts an image from a slow server on FB, this could make experience of Facebook slow. So they copy all that.
So

maybe Facebook still has an old copy. Try with a fresh URL.
can facebook access the URL, or only your user?
Comment: Facebook does not seem to accept an image URL sent to the feed in the picture field if it doesn't have an image filename extension.
Comment: Sam - Did you get an answer for this?
I'm having the same issue. I'm afraid Facebook don't accept it?
I get an exception

"OAuthException: FBCDN image is not allowed in stream: http://vthumb.ak.fbcdn.net/hvthumb-ak-ash4/410445_146214702334395_12224595508739_3750_715_t.jpg"
Comment: I read that it can be done by using "object_attachment" parameter instead of "picture", but can't seem to specify the photo ID, seems like they allow it only for user album photos
https://developers.facebook.com/blog/post/526/


What's an Elmer Cipher

Question: What's an Elmer Cipher? Where can I find a reference on this cipher algorithm?
Comment: I am tempted to make a Looney Tunes-welated pun hewre, however I am not cwever enough to.
Comment: Where did you hear of this Elmer Cipher?  It might help to know what you're looking for other than its apparently obscure name...
Comment: I was asked to use this Cipher to encrypt something. And was told that this is an Asymmetric Cipher. Couldn't find any results googling...could have been misspelt.
Comment: Is this for work or school?  Ask your instructor or client for clearer instructions, and unless this is actually a research project they should be willing to give a clearer idea of what they want.
Comment: It is very similar to a Henway.
Answer: I'm going to guess that it was supposed to be El Gamal. It fits the rest of your description (i.e., it's an asymmetric/public-key cipher).
Comment: I've heard of that but this is spelt as "Elmer"
Answer: Maybe it's a misheard LM Hash?
Or maybe this is what you're after ;)

What's an Elmer Cipher


How to remove overlay hashtag and trailing menu from the parent overlay

Question: Lets say for example we have activated contextual links & overlay modules and when clicking the edit button for the node, which is all the way bottom of the page, it open on overlay. Now when we look at the address bar the link now looks something like this http://localhost:8888/node#overlay=node/25/edit%3Fdestination%3Dnode
The problem with overlay is that it pushes the parent overlay to scroll all the way to the top and when I decide to "cancel" editing I have to scroll all the way to bottom again just to reach the node teaser. So I need to remove the this part from the link above #overlay=node/25/edit%3Fdestination%3Dnode
Now I guess it is being caused by jquery bbq feature. And looking into overlay module and her js files I find it very scary and dont know how to avoid this.
I need some help on where to look into this for starters like me.
Thank you very much.
Answer: You could replace the hash:
window.location.replace(window.location.origin + window.location.pathname)


Supremum of $f(x_1,\dots,x_n)=\sum_{i=1}^n a_i x_i-\sum_{i=1}^n x_i \log x_i$

Question: Let $a_1,\dots,a_n\in\mathbb{R}$. Find supremum of:

$f(x_1,\dots,x_n)=\sum_{i=1}^n a_i x_i-\sum_{i=1}^n x_i \log x_i$

in the following set:

$D=\{x_1,\dots,x_n\ge0 , \sum_{i=1}^n x_i=1\}$. Note: we define $x_i \log x_i=0$ when $x_i=0$

It's easy to see that $f\in C^1(D)$. However, I've been struggling to present $D$ as zeros of a function in order to use lagrange multipliers.
The natural function to pick is $g(x)=1- \sum_{i=1}^n x_i$. However , this function disregard the constraint that $x_1,\dots,x_n\ge0$.
Comment: I think you should treat nonnegativity $x_i\geq 0$ for all $i$ as an abstract set constraint $x \in A$ (for $A$ the convex set of all nonnegative vectors) so then you just have one Lagrange multiplier $\lambda$ for minimizing $f(x) + \lambda g(x)$ subject to $x \in A$.
Comment: @Michael What do you mean? If I disregard nonnegativity, I get a set which is not compact.
Comment: There are various Lagrange multiplier results, it is not clear what one you are wanting to use.  A convenient choice is to use Lagrange multipliers with abstract convex set constraints, as I suggest above.  If you do not know that, then just define additional constraints $h_i(x)$, and additional Lagrange multipliers $\mu_i$, to enforce $x_i\geq 0$.  That will "formally" get you the same answer, but is not quite good, since your $f(x)$ is not defined for all $x \in \mathbb{R}^n$.
Comment: @Michael How can I define such a constraint?
Comment: It is not clear what your phrase "such a constraint" refers to. My first comment shows how to define the abstract set constraint. Notice that the problem formulated in my first comment is separable over the individual $x_i$ variables.
Comment: @Michael I meant non-negativity constraints. If I use lagrange multipliers without addressing the non-negativity constraints, the set will not be compact and thus, maximum will not necessarily be obtained in that region. So I need to explain why is the maximum obtained. How can it be done?
Comment: What set do you require to be compact?  It seems you are trying to plug into an unstated theorem, I cannot follow.  And who said anything about not addressing the non-negativity constraints?
Comment: @Michael I'm trying to use the method of lagrange multipliers. Please see here - https://en.wikipedia.org/wiki/Lagrange_multiplier#:~:text=The%20Lagrange%20multiplier%20theorem%20states,gradients%20of%20the%20constraints%20(at)
Comment: But you agree that $f(x)$ is not defined over all $\mathbb{R}^n$, correct?  So, how are you going to use the method there?  And again, who said anything about neglecting the nonnegativity constraints?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/109617/discussion-between-bulgali-and-michael).
Comment: You gave a mysterious comment in chat "f(x) is indeed defined over $\mathbb{R}^n$."  It is not clear how you are evaluating the $\log()$ function at negative numbers.  What is the value of $\log(-1)$? I also disagree with your comment in your question "It is easy to see $f \in C_1(D)$," since the derivatives at $x_1=0$ are not defined.
Answer: Your objective function is $f:[0, \infty)^n \rightarrow\mathbb{R}$ rather than $f:\mathbb{R}^n\rightarrow\mathbb{R}$ and so the results on the Wikipedia link that you provide do not directly apply.
A more general Lagrange multiplier statement for functions defined on arbitrary domains is this:

Assume:

$X\subseteq\mathbb{R}^n$ is an arbitrary set (possibly nonconvex).

$f:X\rightarrow \mathbb{R}$ and $g:X\rightarrow\mathbb{R}$ are arbitrary functions  (possibly nonconvex and nondifferentiable).

Theorem: Fix $\lambda \in \mathbb{R}$. If $x^* \in X$ solves the following problem:
\begin{align}
\mbox{Minimize:} & \quad f(x) + \lambda g(x) \\
\mbox{Subject to:} & \quad x \in X
\end{align}
Then $x^*$ also solves this problem:
\begin{align}
\mbox{Minimize:} & \quad f(x)   \\
\mbox{Subject to:} & \quad g(x) = g(x^*)\\
& \quad x \in X
\end{align}
This statement is Theorem II.3 (on page 13) in these notes and the proof is easy:
http://ee.usc.edu/stochastic-nets/docs/network-optimization-notes.pdf

So for your problem define $X = \{(x_1, ..., x_n) : x_i\geq 0\quad \forall i \in \{1, ..., n\}\}$ and $f:X\rightarrow\mathbb{R}$ and $g:X\rightarrow\mathbb{R}$ as you already do. For your problem, given any $\lambda \in \mathbb{R}$, it is easy to minimize $f(x) + \lambda g(x)$ subject to $x \in X$. The problem separates over each of the $n$ variables. You can get an analytical solution $x^*_{\lambda}$ (in terms of $\lambda$) that you can adjust to ensure $g(x^*_{\lambda})$ matches the desired constraint.


View picture added to a custom taxonomy actor

Question: This is a follow-up question of :
wordpress add an image to a taxonomy actor
I have successfully added the support into my functions.php. But how do I view the image on my site as it has definitely saved it to a certain taxonomy actor.
https://www.screencast.com/t/u6p5xmiDXgz4
https://www.screencast.com/t/ZmZ6b7cwRm
But as of present I have been unable to work out how to view the attached picture to my website.
<code>    <?php echo apply_filters( 'taxonomy-images-queried-term-image', '' ); ?>
    <?php print apply_filters( 'taxonomy-images-queried-term-image', '' ); ?>
</code>
Answer: Please check table 'prefix_termmeta', you can found term_meta value with given 'term_id'.
Or let me know what function/Plugin have been used to add images to Custom Taxonomy?
Comment: WP Term Images is the plugin I am using, and I have also added image support within my functions.php.  in register taxonomy actor/movies 'supports'   => array( 'title', 'editor', 'comments', 'thumbnail', 'custom-fields' ),
Comment: Please check Plugin : https://wordpress.org/plugins/wp-term-images/
http://prntscr.com/i7hui8
Comment: typed exactly as was in the pic, no errors and no picture :( thanks for trying


Is there a way to affect the position of an img but not the source in an anchor element?

Question: Is there a way to position an img separately from the source (text) in an anchor element? For instance, in the picture, I want the word "dot" to be aligned further right than the arrow but stay on top of the arrow.
current

what I want

I know I could make them as separated anchors but I want the color of the word to change when you hover on the arrow as well and if they are separate, the a:hover doesn't work together.
I tried changing the position under .left img to be different but it moves the img and the source.
HTML code:

        dot

CSS code:
.leftarrow {
    position: absolute;
    left: 0;
    top:0;
}

.leftarrow a{
    position: absolute;
    left: 0;
    font-size: 1.5em;
    color:gray;
    text-decoration: none;
}

.leftarrow a:hover{
    color: black;
}

.leftarrow img{
    position: absolute;
    left: 0;
    top: 15px;
    width: 50px;
}

Answer: Try this, using Pseudo-Elements. It could definitely be more optimized than this though.

a {
margin-left: 100px;
}

span:after {
  content: "";
  background-image:url('https://www.flaticon.com/svg/static/icons/svg/271/271218.svg');
  display: inline-block;
  background-size: 30px 30px;
  height: 30px;
  width: 30px;
  position: absolute;
  z-index: 1;
  left:90px;
  top: 15px;

}
a:hover {
  color: red;
}

    dot

Answer: First: wrap the dot into a  or
 for better control,
Second: use a more powerfull display mode (e.g: flex or grid)
here is a sample:

a {
  vertical-align: middle;
  text-decoration: none;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  color: black;
  width: fit-content;
  margin: 0 auto;
}

a:hover {
  color: red;
}

div {
  font-size: 32px;
}

img {
  width: 100px;
}

dot

Comment: @CamMeyer I updated my snippet. I think it is what you want now.
Comment: Thank you! I ended up just putting dot in a span and then was able to keep the absolute positioning and only affect the left attribute of the span.
Comment: Thanks @mahdi! I will try this. I just edited my question to clarify. I want the word to stay above the arrow but be shifted to the right so that it is off centered.


Transaction Manager bean in jboss 7

Question: We are deploying MDB in jboss 7 using IBM MQ as messaging provider. We are migrating (MDB EAR) from IBM WAS Application server to Jboss keeping messaging in IBM MQ.
As part of migration we need to change transaction manager from IBM Web sphere App server to JBoss specific transaction manager.
As you can see below wsTxManager bean specific to web sphere. We need Jboss specific bean. Can you any one help me on this.?
<bean id="wsTxManager"
        class="org.springframework.transaction.jta.WebSphereTransactionManagerFactoryBean" />

    <bean id="txManager"
        class="org.springframework.transaction.jta.JtaTransactionManager">
        <property name="userTransactionName">
            <null />
        </property>
        <property name="transactionManager" ref="wsTxManager" />
    </bean>

Logs:
7c11372: display name [org.springframework.context.support.ClassPathXmlApplicationContext@77c11372]; startup date [Tue Feb 20 17:21:42 SGT 2018]; root of context hierarchy
[2018-02-20 17:21:42,674] [default-threads - 12] [INFO ] [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from URL [vfs:/content/our_app.ear/our_app.jar/beanRefContext.xml]
[2018-02-20 17:21:42,976] [default-threads - 12] [INFO ] [org.springframework.context.support.ClassPathXmlApplicationContext] - Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@77c11372]: org.springframework.beans.factory.support.DefaultListableBeanFactory@406aa4b4
[2018-02-20 17:21:42,981] [default-threads - 12] [INFO ] [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@406aa4b4: defining beans [businessBeanFactory]; root of factory hierarchy
[2018-02-20 17:21:43,000] [default-threads - 12] [INFO ] [org.springframework.context.support.ClassPathXmlApplicationContext] - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@66b1b69e: display name [org.springframework.context.support.ClassPathXmlApplicationContext@66b1b69e]; startup date [Tue Feb 20 17:21:43 SGT 2018]; root of context hierarchy
[2018-02-20 17:21:43,000] [default-threads - 12] [INFO ] [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [app-ejb-context.xml]
[2018-02-20 17:21:43,034] [default-threads - 12] [INFO ] [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@406aa4b4: defining beans [businessBeanFactory]; root of factory hierarchy
[2018-02-20 17:21:43,045] [default-threads - 29] [INFO ] [org.springframework.context.support.ClassPathXmlApplicationContext] - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7e92809d: display name [org.springframework.context.support.ClassPathXmlApplicationContext@7e92809d]; startup date [Tue Feb 20 17:21:43 SGT 2018]; root of context hierarchy

Answer: It should work with JBoss:
<bean id="containerTransaction" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>java:/TransactionManager</value>
    </property>
</bean>
<bean id="jtaTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
    <property name="transactionManager">
        <ref local="containerTransaction"/>
    </property>
    <property name="userTransactionName">
        <value>java:jboss/UserTransaction</value>
    </property>
</bean>

Comment: But we don't have java:/TransactionManager,java:jboss/UserTransaction JNDI configured in our JBoss. Is that ok?
Comment: Yes it is ok. java:/TransactionManager "means", that you use the transaction manager from JBoss and jboss/UserTransaction is a link for the UserTransaction.
Comment: We placed above mentioned beans in our app-ejb-context.xml file . But after deploying we are getting below log messages continuously. I added log info in question itself, please check.
Comment: Dear @awagenhoffer, at the end of the logger   [DEBUG] [org.springframework.transaction.jta.JtaTransactionManager] - Resuming suspended transaction   ----
Can we try to stop this resumption?
Comment: Could you post debug log?
Comment: It is normal, if you have for example an inner transaction. Are there any errors in log?
Comment: Thanks @awagenhoffer,

Transaction Manager bean in jboss 7


Poisson goodness-of-fit of small sample

Question: Please note that I have no background in statistics - this is for personal interest.
The post is inspired by a question at work.
We were given data by another department asserting that for a continuously advertised position there were zero applications in 6 consecutive days, followed by 7 applications on the 7th day. The validity of the data was questioned.
I wondered what the probability was of getting this exact result on seven consecutive days, assuming a homogeneous Poisson distribution. The below may or may not be correct.
$P(X=k) = \frac{{e^{-\lambda}}\lambda^k}{k!}$
So,
$P(X=0) = {\frac{{e^{-\lambda}}\lambda^0}{0!}}={e^{-\lambda}}$
$P(X=7) = {\frac{{e^{-\lambda}}\lambda^7}{7!}} =  {\frac{{e^{-\lambda}}\lambda^7}{5040}}$
$P(X=\{0,0,0,0,0,0,7\}) = \frac{{(e^{-\lambda})}^6{e^{-\lambda}}\lambda^7}{5040} = \frac{e^{-7\lambda}\lambda^7}{5040}$
Finding the value of $\lambda$ that gives the maximum likelihood for $P(X=\{0,0,0,0,0,0,7\})$,
${\frac{\partial}{\partial\lambda}}\frac{e^{-7\lambda}\lambda^7}{5040}$
$ = {\frac{1}{5040}}\frac{\partial}{\partial\lambda}{e^{-7\lambda}}\lambda^7$
Using the product rule,
${\frac{d}{dx}}(uv) = v{\frac{du}{dx}} + u{\frac{dv}{dx}}$ , where $u = {e^{-7\lambda}}$, $v = {\lambda^7}$, $x = \lambda$ gives:
${\frac{d}{d\lambda}}({e^{-7\lambda}}{\lambda^7}) = {\lambda^7}{\frac{d}{d\lambda}}{e^{-7\lambda}} + {e^{-7\lambda}}{\frac{d}{d\lambda}}{\lambda^7}$
Using the chain rule,
${\frac{dg}{dx}} = {\frac{dg}{du}}{\frac{du}{dx}}$ , where $g = e^{u}$, $x = \lambda$, $u = -7\lambda$ gives:
${\frac{d}{d\lambda}}e^{-7\lambda} = {\frac{d}{du}}e^u{\frac{d}{d\lambda}}-7\lambda$
$ = {-7e^{-7\lambda}}$
So,
${\frac{d}{d\lambda}}({e^{-7\lambda}}{\lambda^7}) = {-7e^{-7\lambda}}{\lambda^7} + {7e^{-7\lambda}}{\lambda^6}$
$ = {7e^{-7\lambda}}{\lambda^6}(1 - \lambda) = 0$
$\lambda = \{0, 1\}$
So, with a maximum probability at $\lambda = 1$,
$P(X=\{0,0,0,0,0,0,7\}) = \frac{e^{-7}1^7}{5040} = \frac{1}{5040e^7} \approx \frac{1}{5527031}$
This seemed like pretty slim odds, but on reflection, it wasn't telling me much.
Out of an infinite number of possible outcomes, the chosen outcome had a 1 in 5.5 million chance of occurring.
My question - is there a good test to use to give an indication of how well this data fit a homogeneous Poisson process? What would the results of such as test actually tell me?
Answer: Good efforts and nice thinking. Just a few notes about your method and your conclusion.
Estimating $\lambda$ could have been done by using the mean which is also an estimator of lambda. $7applications / 7days=1$
This is indeed pretty slim, but some data more "usual" could get pretty slim odds too. The probability of a specific event is rarely the good approach to test an hypothesis. The event [0,2,1,1,1,2] would have a very very small probability too, but it does not appear as abnormal.
The best would have been to consider the range of "what could have been seen as very weird data" and compute the probability to get an event in this whole event list. But how to build this dataset is a tricky question.
One could also point out some real world effect there. On what basis can we say that this should follow a poisson law ? I am personally a late applicant, maybe many others are. Under this track, what you could do is to check if poisson law is a good fit for this data. Maybe this is what you wanted to do since the beginning. You could then continue your self-study journey by looking at how to do a goodness of fit test to check that ! I think it would be rejected. Edit : I reread your question, this is what you are specifically asking, I hope other comments would interest you anyway.
A last comment, more qualitative, is that by estimating the best $\lambda$ fitting your data, you overestimate the probability of these datas. If lambda was in reality a bit less or more, the probability of your single event would go down. This is (very very broadly) the idea of degree of freedom that you may encounter while doing a goodness of fit test.

Poisson goodness-of-fit of small sample


How to wait for snapd auto-refresh to complete?

Question: On Google Compute Engine, I have a startup-script that uses gsutil and gcloud, which are part of the google-cloud-sdk snap that is preinstalled on the ubuntu-minimal-1804-lts public image, which is the base image for the image that I am using. But when I ran the startup script today, it failed 4 out of 8 times because snapd decided to auto-refresh at the same time that the startup-script is run.
Within the startup-script, how can I wait until snap's auto-refresh has completed?
Here are the commands I ran to determine that snapd was updating at the same time as my startup-script:
$ snap changes --abs-time
ID   Status  Spawn                 Ready                 Summary
3    Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Auto-refresh snaps "core", "google-cloud-sdk"

$ snap tasks 3 --abs-time
Status  Spawn                 Ready                 Summary
…
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:45Z  Ensure prerequisites for "google-cloud-sdk" are available
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:46Z  Download snap "google-cloud-sdk" (82) from channel "stable/ubuntu-18.04"
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:47Z  Fetch and check assertions for snap "google-cloud-sdk" (82)
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:48Z  Mount snap "google-cloud-sdk" (82)
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:48Z  Run pre-refresh hook of "google-cloud-sdk" snap if present
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:48Z  Stop snap "google-cloud-sdk" services
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:48Z  Remove aliases for snap "google-cloud-sdk"
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:48Z  Make current revision for snap "google-cloud-sdk" unavailable
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Copy snap "google-cloud-sdk" data
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Setup snap "google-cloud-sdk" (82) security profiles
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Make snap "google-cloud-sdk" (82) available to the system
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Automatically connect eligible plugs and slots of snap "google-cloud-sdk"
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Set automatic aliases for snap "google-cloud-sdk"
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Setup snap "google-cloud-sdk" aliases
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Run post-refresh hook of "google-cloud-sdk" snap if present
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Start snap "google-cloud-sdk" (82) services
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Clean up "google-cloud-sdk" (82) install
Done    2019-05-16T18:08:34Z  2019-05-16T18:08:49Z  Run configure hook of "google-cloud-sdk" snap if present

$ journalctl -u google-startup-scripts
…
May 16 18:08:39 my-instance startup-script[1469]: INFO startup-script-url: + gsutil cp gs://my-bucket/app.tar.gz /opt/my-bucket/app.tar.gz
May 16 18:08:41 my-instance startup-script[1469]: INFO startup-script-url: /snap/google-cloud-sdk/41/usr/bin/python2: relocation error: /lib/x86_64-linux-gnu/libnss_dns.so.2: symbol
__resolv_context_get, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference

On another instance, gsutil failed with a different message:
ERROR: (gsutil) /snap/google-cloud-sdk/41/usr/bin/python2: command not found

Answer: I have been trying to reproduce your issue, by creating an instance with the 'ubuntu-minimal-1804-lts' image as you state
gcloud compute instances create \
--image-family ubuntu-minimal-1804-lts \
--image-project ubuntu-os-cloud \
--machine-type n1-standard-1 \
--boot-disk-size=15 \
--boot-disk-type=pd-ssd \
--zone=europe-west1-c \
--tags=allow-incoming-ssh \
--metadata=startup-script-url="gs://testinggrounds/startup.sh" \
ubuntu-test

and then reboot it several times
for i in {1..7}; \
do \
gcloud compute instances reset ubuntu-test --zone europe-west1-c; \
sleep 120s; \
done

but I did not manage to get this problem that you state.
Searching around for the error that you get, I found this thread where the user reporting the issue presents a highly similar problem which might be the same as you have found. The problem is supposed to be fixed, as reported by the team behind it. Can you check if the date for your Ubuntu 18.04 image is prior to the date opening of this thread I shared? Maybe by using a newer image your problem gets solved.
I saw that you said this suddenly appeared not too long ago, so probably it is not the version, but it does not hurt to check.
If this was not the case, then I would propose to just delay the execution of the startup script or try to make it run after other snapd services.
[Unit]
Description=Google Compute Engine Startup Scripts
After=local-fs.target network-online.target network.target rsyslog.service
After=google-instance-setup.service google-network-daemon.service
After=cloud-final.service multi-user.target
After=snapd.seeded.service
After=snapd.service
Wants=local-fs.target network-online.target network.target cloud-final.service
Wants=snapd.seeded.service

[Service]
ExecStartPre=/bin/sleep 20
ExecStart=/usr/bin/google_metadata_script_runner --script-type startup
KillMode=process
Type=oneshot
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin

[Install]
WantedBy=multi-user.target

This file is located at /lib/systemd/system/google-startup-scripts.service. I added the After=snapd.service and ExecStartPre=/bin/sleep 20 to try and delay the execution of the service. Your file should look exactly like the one above without my additions.
If it still doesn't work, you can try to add other snap services with the After= directive, as there are a few more in the systemd services folder:
$ ls /lib/systemd/system/ | grep snap

snapd.autoimport.service
snapd.core-fixup.service
snapd.failure.service
snapd.seeded.service
snapd.service
snapd.snap-repair.service
snapd.snap-repair.timer
snapd.socket
snapd.system-shutdown.service

Hope it helps!
Comment: Thanks for all the research. In your linked issue, zmarano claimed that the issue is fixed, but I was already running an image that was the newest at the time he wrote that comment (`--image-project ubuntu-os-cloud --image ubuntu-minimal-1804-bionic-v20180705`). But today I am unable to reproduce the issue unfortunately (`snap changes` shows everything is Done already within the startup-script).
Answer: I ended up running snap changes until everything was Done by putting this at the top of my startup-script:
# Returns 0 if snapd is not updating google-cloud-sdk
# (nothing has happened, or all changes are Done, Hold, Error)
# Returns 1 if snapd is updating google-cloud-sdk
# (there is at least one chnage that is Doing, Abort, Undo, or Undoing)
# Echos the offending line
# https://serverfault.com/questions/967674/how-to-wait-for-snapd-auto-refresh-to-complete
function isSnapIdle {
  # For the format of snap changes, see:
  # see https://github.com/snapcore/snapd/blob/8ae45c207f3c488f0ab0dc3615661df9b0854b20/overlord/state/change.go
  # and https://github.com/snapcore/snapd/blob/8ae45c207f3c488f0ab0dc3615661df9b0854b20/cmd/snap/cmd_changes.go#L124
  local line
  local changes
  if changes=$(snap changes google-cloud-sdk); then
    :
  else
    # When snap is upgrading itself, snap changes can fail
    echo "snap changes gave error $? $changes"
    return 2
  fi
  while read line; do
    local state=$(echo "$line" | awk '{print $2}')
    if [ "$state" = Do ] || [ "$state" = Doing ] || [ "$state" = Abort ] || [ "$state" = Undo ] || [ "$state" = Undoing ]; then
      echo "$line"
      return 1
    fi
  done < <(echo "$changes" | tail -n +2)
  return 0
}
function waitUntilSnapIdle {
  local lastSnapChange=
  local snapChange
  while ! snapChange=$(isSnapIdle); do
    if [ "$snapChange" != "$lastSnapChange" ]; then
      echo >&2 "Waiting for snapd to finish installing: $snapChange"
    fi
    lastSnapChange="$snapChange"
    sleep 1
  done
  echo >&2 "Snapd does not appear to be installing google-cloud-sdk"
}

waitUntilSnapIdle

Answer: I was encountering the same issue and pin pointed the cause to snap's auto updates as well! In my case waiting for snap refresh takes way too much time and the number of jobs is still manageable for a single human so I just reduced the allowed refresh window to the calmer part of the work week.
Try for instance:
# Allows snap refreshes on Monday at 10AM and also on Friday at 3PM
sudo snap set system refresh.timer=mon,10:00,,fri,15:00


Call TDataSet.Locate in one line

Question: In RAD Studio wiki you can find documentation on using TDataSet.Locate method.
Following C++ snippet comes from there:
TLocateOptions Opts;
Opts.Clear();
Opts << loPartialKey;
Variant locvalues[2];
locvalues[0] = Variant("Sight Diver");
locvalues[1] = Variant("P");
CustTable->Locate("Company;Contact", VarArrayOf(locvalues, 1), Opts);

I'd like to do this call to Locate all in one line, as you can do in Delphi. Something like this or even simpler:
CustTable->Locate("Company;Contact", VarArrayOf(new Variant[2]{Variant("Sight Diver"), Variant("P")}, 1), TLocateOptions() << loPartialKey );

Compiler says E2121 Function call missing ).
Is it possible?
Answer: According to your comments, the problem is the second parameter, and specifically the open array that VarArrayOf receives.
According to the documentation, the OPENARRAY macro could be helpful. You'd call VarArrayOf like this:
VarArrayOf(OPENARRAY(Variant, ("Sight Diver", "P")))

So the call to Locate will become:
CustTable->Locate("Company;Contact",
                  VarArrayOf(OPENARRAY(Variant, ("Sight Diver", "P"))),
                  TLocateOptions() << loPartialKey );

Comment: There is also `ARRAYOFCONST`. And take a look at this question: http://stackoverflow.com/questions/4635085/how-to-translate-array-of-param-to-c
Comment: I knew of `ARRAYOFCONST`, it is for `TVarRec`... but didn't know of `OPENARRAY`... great @David!!

Call TDataSet.Locate in one line


How to minimize my big query for showing counts using SQL

Question: I am taking counts from CTE but common is Status(working,pening) and Divisions
but my query is becoming big because left join is same but just status and division are different. I have wrote 10 left join count but by passing status and divisions.
Below is my whole sql query
declare @createdBy int=79

;with cte as (
select max(w.WorkingNo)WorkingNo
from
working w
join workingdealhistory wd on wd.WorkHistoryId=w.workingNo and
w.status  IN ('WORKING','PENDING')     and w.mhlId>0  and w.IsActive=1
join TreasureTrove t on t.CandidateId=w.CandidateId and t.DepartmentId=2
group by w.CandidateId,w.status
)

select distinct m.potentialHospitalNo
,m.hospital
,ph.clientname
,cdiwr.working cdiworking
,cdipn.pending cdipending
,himwr.working himworking
,himpn.pending himpending
,cmurwr.working cmurworking
,cmurpn.pending cmurpending
,odmwr.working odmworking
,odmpn.pending odmpending
,traumawr.working traumaworking
,traumapn.pending traumapending
,ph.ClientId
from PotentialHospitlMaster m (NOLOCK)
Inner JOIN HospitalStatus HS (NOLOCK) On m.potentialHospitalNo=HS.ClientId
inner join potentialhospital ph on ph.potentialhospitalno=m.potentialhospitalno

    --this is status='working' and division='CDI'
LEFT join(select COUNT(w.WorkingNo)working, MHLId from cte c inner join
working w on w.WorkingNo=c.WorkingNo
inner join WorkingDealHistory WH on w.WorkingNo=WH.WorkHistoryId
inner join potentialhospital phs on phs.potentialHospitalNo=w.MHLId where w.Status='working' and wh.Division='CDI' group by w.MHLId) as cdiwr on cdiwr.MHLId=ph.potentialHospitalNo

    --this is status='pending' and division='CDI'
LEFT join(select COUNT(w.WorkingNo)pending, MHLId from cte c inner join
working w on w.WorkingNo=c.WorkingNo
inner join WorkingDealHistory WH on w.WorkingNo=WH.WorkHistoryId
inner join potentialhospital phs on phs.potentialHospitalNo=w.MHLId where w.Status='pending' and wh.Division='CDI' group by w.MHLId) as cdipn on cdipn.MHLId=ph.potentialHospitalNo

    --this is status='working' and division='HIM'
LEFT join(select COUNT(w.WorkingNo)working, MHLId from cte c inner join
working w on w.WorkingNo=c.WorkingNo
inner join WorkingDealHistory WH on w.WorkingNo=WH.WorkHistoryId
inner join potentialhospital phs on phs.potentialHospitalNo=w.MHLId where w.Status='working' and wh.Division='HIM' group by w.MHLId) as himwr on himwr.MHLId=ph.potentialHospitalNo

  --this is status='pending' and division='HIM'
LEFT join(select COUNT(w.WorkingNo)pending, MHLId from cte c inner join
working w on w.WorkingNo=c.WorkingNo
inner join WorkingDealHistory WH on w.WorkingNo=WH.WorkHistoryId
inner join potentialhospital phs on phs.potentialHospitalNo=w.MHLId where w.Status='pending' and wh.Division='HIM' group by w.MHLId) as himpn on himpn.MHLId=ph.potentialHospitalNo

--this is status='working' and division='CMUR'
LEFT join(select COUNT(w.WorkingNo)working, MHLId from cte c inner join
working w on w.WorkingNo=c.WorkingNo
inner join WorkingDealHistory WH on w.WorkingNo=WH.WorkHistoryId
inner join potentialhospital phs on phs.potentialHospitalNo=w.MHLId where w.Status='working' and wh.Division='CMUR' group by w.MHLId) as cmurwr on cmurwr.MHLId=ph.potentialHospitalNo

--this is status='pending' and division='CMUR'
LEFT join(select COUNT(w.WorkingNo)pending, MHLId from cte c inner join
working w on w.WorkingNo=c.WorkingNo
inner join WorkingDealHistory WH on w.WorkingNo=WH.WorkHistoryId
inner join potentialhospital phs on phs.potentialHospitalNo=w.MHLId where w.Status='pending' and wh.Division='CMUR' group by w.MHLId) as cmurpn on cmurpn.MHLId=ph.potentialHospitalNo

--this is status='working' and division='ODM'
LEFT join(select COUNT(w.WorkingNo)working, MHLId from cte c inner join
working w on w.WorkingNo=c.WorkingNo
inner join WorkingDealHistory WH on w.WorkingNo=WH.WorkHistoryId
inner join potentialhospital phs on phs.potentialHospitalNo=w.MHLId where w.Status='working' and wh.Division='ODM' group by w.MHLId) as odmwr on odmwr.MHLId=ph.potentialHospitalNo

--this is status='pending' and division='ODM'
LEFT join(select COUNT(w.WorkingNo)pending, MHLId from cte c inner join
working w on w.WorkingNo=c.WorkingNo
inner join WorkingDealHistory WH on w.WorkingNo=WH.WorkHistoryId
inner join potentialhospital phs on phs.potentialHospitalNo=w.MHLId where w.Status='pending' and wh.Division='ODM' group by w.MHLId) as odmpn on odmpn.MHLId=ph.potentialHospitalNo

--this is status='working' and division='Trauma'
LEFT join(select COUNT(w.WorkingNo)working, MHLId from cte c inner join
working w on w.WorkingNo=c.WorkingNo
inner join WorkingDealHistory WH on w.WorkingNo=WH.WorkHistoryId
inner join potentialhospital phs on phs.potentialHospitalNo=w.MHLId where w.Status='working' and wh.Division='Trauma' group by w.MHLId) as traumawr on traumawr.MHLId=ph.potentialHospitalNo

--this is status='pending' and division='Trauma'
LEFT join(select COUNT(w.WorkingNo)pending, MHLId from cte c inner join
working w on w.WorkingNo=c.WorkingNo
inner join WorkingDealHistory WH on w.WorkingNo=WH.WorkHistoryId
inner join potentialhospital phs on phs.potentialHospitalNo=w.MHLId where w.Status='pending' and wh.Division='Trauma' group by w.MHLId) as traumapn on traumapn.MHLId=ph.potentialHospitalNo

where  m.IsActive=1 and HS.UpdatedStatus='MSA Sent' and HS.CreatedBy=@createdBy

Is there anything which we can minimize query by using group by or anything.
Comment: You can probably simplify this to one query of aggregates using conditional aggregates, e.g. `COUNT(CASE WHEN w.Status = 'Working' AND wh.Division = 'CDI' THEN 1 END) AS CDIWorking, COUNT(CASE WHEN w.status = 'Pending' AND wh.Division = 'HIM' THEN 1 END) AS HIMPending, ` and so on. I can't suggest a full query I am afraid as I really don't understand your current query, or what purpose you think your current cte serves.
Comment: [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) alert! If you see you are repeating an almost identical query then stop. This should be a single join with conditional aggregation.
Comment: single left join how this case happend confused agian. @GarethD
Comment: i am using cte data with left join can you post your answer. @Stu
Answer: I've taken a bit of a stab at your schema, and I think you could do it with something like:
DECLARE @createdBy INT = 79;

WITH cte AS
(
    SELECT  w.CandidateId, w.status, WorkingNo = MAX(w.WorkingNo)
    FROM    working AS w
            JOIN workingdealhistory AS wd
                ON  wd.WorkHistoryId = w.workingNo
                AND w.status IN ('WORKING', 'PENDING')
                AND w.mhlId > 0
                AND w.IsActive = 1
            JOIN TreasureTrove AS t
                ON  t.CandidateId = w.CandidateId
                AND t.DepartmentId = 2
    GROUP BY
            w.CandidateId, w.status;
)
SELECT  DISTINCT
        m.potentialHospitalNo,
        m.hospital,
        ph.clientname,
        cnt.CDIworking,
        cnt.CDIPending,
        cnt.HIMworking,
        cnt.HIMPending,
        cnt.CMURworking,
        cnt.CMURPending,
        cnt.ODMworking,
        cnt.ODMPending,
        cnt.Traumaworking,
        cnt.TraumaPending
        ph.ClientId
FROM    PotentialHospitlMaster AS m
        INNER JOIN HospitalStatus AS HS
            ON m.potentialHospitalNo = HS.ClientId
        INNER JOIN potentialhospital AS ph
            ON ph.potentialhospitalno = m.potentialhospitalno
        LEFT JOIN
        (
            SELECT  w.MHLId,
                    CDIworking = COUNT(CASE WHEN w.Status = 'working' AND wh.Division = 'CDI' THEN w.WorkingNo END),
                    CDIPending = COUNT(CASE WHEN w.Status = 'pending' AND wh.Division = 'CDI' THEN w.WorkingNo END),
                    HIMworking = COUNT(CASE WHEN w.Status = 'working' AND wh.Division = 'HIM' THEN w.WorkingNo END),
                    HIMPending = COUNT(CASE WHEN w.Status = 'pending' AND wh.Division = 'HIM' THEN w.WorkingNo END),
                    CMURworking = COUNT(CASE WHEN w.Status = 'working' AND wh.Division = 'CMUR' THEN w.WorkingNo END),
                    CMURPending = COUNT(CASE WHEN w.Status = 'pending' AND wh.Division = 'CMUR' THEN w.WorkingNo END),
                    ODMworking = COUNT(CASE WHEN w.Status = 'working' AND wh.Division = 'ODM' THEN w.WorkingNo END),
                    ODMPending = COUNT(CASE WHEN w.Status = 'pending' AND wh.Division = 'ODM' THEN w.WorkingNo END),
                    Traumaworking = COUNT(CASE WHEN w.Status = 'working' AND wh.Division = 'Trauma' THEN w.WorkingNo END),
                    TraumaPending = COUNT(CASE WHEN w.Status = 'pending' AND wh.Division = 'Trauma' THEN w.WorkingNo END)
            FROM    working AS w
                    INNER JOIN WorkingDealHistory AS wh
                        ON w.WorkingNo = wh.WorkHistoryId
                    INNER JOIN cte AS c
                        ON c.CandidateId = w.CandidateId
                        AND c.status = w.status
                        AND c.WorkingNo = w.WorkingNo
            GROUP BY
                    w.MHLId
        ) AS cnt
            ON cnt.MHLId = ph.potentialHospitalNo
WHERE   m.IsActive = 1
AND     HS.UpdatedStatus = 'MSA Sent'
AND     HS.CreatedBy = @createdBy;

N.B. I've removed NOLOCK as putting this everywhere is a bad habit to kick. Also, I am deeply suspicious of most queries that use DISTINCT across a large number of columns like this. More often than not the duplicates are a symptom of an error with the query, and DISTINCT is just a nasty plaster trying to cover up the real issue. You should work out where duplicates are coming from and look to remove either early or at least in a deterministic fashion.
Comment: Are you not included cte query because that are top records? i have to include cte query with the above yours answer?. @GarethD
Comment: To be honest I struggled to work out exactly what you are trying to achieve with your CTE as I don't fully understand your schema, so I left it out. I've modified the query above slightly, but it may not be exactly what you need, but hopefully gives you a good enough start for a way to get a number of different counts without repeating the same query over and over again
Comment: Agenda of cte is to take max workingno because multiple working will inserting of same id need to take max workingno data, if keep cte and base cte can you update answer will help more. @GarethD
Comment: Your answer is very helpful thanks can please post by using cte will good for me. @GarethD
Comment: okay i am accepting you answer because you almost given idea to achieve thanks sir. @GarethD


Getting parent route parameters in Angular 2 (router v3.0.0-alpha.6)

Question: Looking to set up a site using one of Google's recommended practices for multi-regional and multilingual websites, particularly the model of utilizing subdirectories with gTLD's (ex. www.stackoverflow.com/en/questions/ask, www.stackoverflow.com/fr/questions/ask, etc).
Depending on the top-level subdirectory I'd like to set default language and fetch the appropriate JSON data. To futher explain, when a user navigates directly to www.mywebsite.com/en/home the default language will be set to en and my content service will fetch the en.json file.
In the example above my routes would be configured like so:
export const routes: RouterConfig = [
  { path: ':country',          component: Home },
  { path: ':country/home',     component: Home },
  { path: ':country/about',    component: About },
  { path: ':country/contact',  component: Contact }
];

I'm trying to figure out how to grab the :country route parameter (if URL is www.mywebsite.com/en/about/ I'm trying to get the :country route parameter value of en) when in the Home, About, or Contact component. Here's a couple of things I've tried:
export class Home implements OnInit {
    constructor(
        private route: ActivatedRoute
    ) {}

    private sub: any;

    ngOnInit(){
       this.sub = this.route.params.subscribe(params => {
         let country = params['country'];
         console.log(country) // undefined :(
       });
    }
}

I've also tried using route.snapshot like so:
export class Home implements OnInit {
    constructor(
        private route: ActivatedRoute
    ) {}

    ngOnInit(){
        let country = this.route.snapshot.params['country'];
        console.log(country) // undefined :(
    }
}

Also have tried working with this solution to no avail: Angular 2 access parent routeparams from child component
If anyone has an idea of another approach please share!
Comment: You've mentioned 'parent route parameters' in your question title. Are these the only routes that you have defined in your app or are they children in another `RouterConfig`
Answer: I am not sure why this didn't work for you, but I just tried and the following code works for me:
import {Component, OnInit}              from '@angular/core';
import { Router, ActivatedRoute }       from '@angular/router';

@Component({
  selector: 'home',
  template: '
Home: {{country}}
'
})

export class HomeComponent implements OnInit {

  country: string;

  constructor(
    private route: ActivatedRoute,
    private router: Router) {

    this.country = '?';

  }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       let country = params['country'];
       this.country = country;
       console.log(country);
     });
  }

}

When I navigate to the root page, it displays Home:, the /en page displays Home: en and the /fr page - Home:fr. It works similarly for the "about" page.
The full source is here.
Update: here is also live demo (plunker).
Resources:

Angular guide - Routing & Navigation
Routing plunker example
Angular Router post by Victor Savkin
Comment: I have the same issue but in Angular 2 Final version. Pls help


Bayesian optimizations of hyper-parameters - magical curve based on two data points?

Question: I am trying to understand how Bayesian optimizations of hyper-parameters works in practice.
Question 1:
How shape of this curve (solid blue line in the middle) is calculated given Gaussian kernel. I understand that the kernel is a way to measure distance between points on $x$-axis. I read there is an underlying Gaussian process etc, but what are the formulas to get this shape? How come that after just 2 iterations I have this non-trivial curves with multiple extrema?

Question 2:
How does it work with different kernels? How measuring distance on $x$-axis implies shape of the curve in this post?
Comment: The chapter on Gaussian processes in *Bayesian Data Analysis* 3rd ed. is helpful. See also *Gaussian Processes for Machine Learning* by Rasmussen and Williams.
Answer: Definition
A Gaussian Process (GP) is a Gaussian distribution over functions:
$$f(x) \sim GP(m(x), k(x, x^\prime))$$
where $m(x)$ is the mean function and $k(x, x^\prime)$ is a kernel function. The solid blue line in the middle on your pictures is the mean $m(x) = \mathbb{E}[f]$, while the two lines around it are functions that are one standard deviation away from the mean: $\mathbb{E}[f] \pm \sigma[f]$.
Each iteration is an evaluation of an outcome for some $x$. These are the blue dots on your pictures, after two and three evaluations. As you can see, the standard deviation collapses at these points, because their outcomes have been calculated, i.e., there's nothing to vary. All other points are still unknown, but GP models what their probable value is, given the evaluated points. Intuitively, the further you go from the points, the larger the variance.
How is GP calculated?
Initially, $m(x)$ is a constant, usually zero (though it depends on the prior settings, in your case it might be 50%). Each new evaluation gives a lot of information, because it fixes one more point for $m$ and changes the shape of the whole curve. The exact formula is derived from Multivariate Gaussian Theorem (e.g., discussed here).
Intuitively, let's look at the transformation at step 3 on your picture, which evaluates $x_3=200$. At step 2, $m(x_3)$ is roughly $70\%$, because that's kind of average of known values $f(x_1)$ and $f(x_2)$, but with huge variance: any value between $55\%$ and $95\%$ is within one standard deviation. Basically, everything beyond $x > 150$ is a big unknown area. Evaluation of $f(x_3) = 85\%$ makes it certain: $m(x_3)$ is about the same as $m(x_2)$, but slightly better, which makes $m(x)$ monotone between $x_2$ and $x_3$. The variance around $x_2$ and $x_3$ is small, however the value at $x=150$ can be both much better or much worse.
Note that at each step, $m(x)$ is smooth, because that's exactly what GP models. Hope this clarifies why the shape of $m(x)$ makes sense.
How the kernel affects GP?
It makes the variance larger or smaller by assuming the likelihood of big changes of $f$ on a small interval. In other words, it controls what a small interval of $x$ is. Remember that GP models the smooth functions over $x$, but changing the measure of $x$ changes how "wigly" the functions of $x$ are allowed to be.
For example, here's the effect of changing the width parameter of the Gaussian kernel, from $0.1$ to $1$ to $10$ (the gray area is the variance):

The first one allows a lot of variation in $f$ by making the distances between $x$'s very large. The last one is the opposite. The exact formula again follows the Multivariate Gaussian Theorem.
Highly recommend the lectures by Nando de Freitas available on YouTube (the first one is here) to get a better understanding of GP. Hyperparameter tuning via Gaussian Optimization is also discussed in this question.


How to decide on the MLE when pmf is 0?

Question: Suppose you have $\theta=\{1,2\}$ and the sample of (0,1,2) with the task of finding MLE:
\begin{array} {|c|c|c|}
\hline
x & p(x|\theta=1) & p(x|\theta=2) \\
\hline
0 & 1/2 & 1/4 \\
\hline
1 & 0 & 1/4 \\
\hline
2 & 1/3 & 0 \\
\hline
\end{array}
I can't compare $\prod_i p(x_i|\theta)$, because of the zeroes. Even though I can compare probability for a single observation, I'm still having trouble quantifying the difference. $p(x=1|\theta=2)>p(x=1|\theta=1)$ for x=1, but can I do a similar comparison for the whole vector?
Edit
The original question is

One observation is taken on a discrete random variable X with pmf f(x|θ), where θ∈{1,2,3}. Find the MLE of θ.

This is followed by a 4x5 table which includes zeroes in every column. I think the idea behind this question is that we have a distribution that doesn't describe population well. Do we just say that the method of MLE is not applicable here?
Comment: You should include the sample in your question. As whuber said, the likelihood is trivially zero for both parameter values ... which simply means neither parameter value can have produced the values $(0,1,2)$ (But neither conditional distribution seems to sum to 1 either. Is something missing?) Or are you supposed to treat each value as a single sample (giving three MLEs for three different samples)??
Comment: I have changed the terminology. This question is similar to the one in my textbook. There is a sample of (0,1,2), in which case the conditional probabilities don't have to sum up to 1.
Comment: Notice that the quotation begins "*one* observation." Thus, it's really a set of questions: what is the MLE when you observe $0$?  What is it when you observe $1$?  What is it when you observe $2$?
Comment: @Glen_b put another way, each parameterization is equally likely e.g. impossible given the sample of 0, 1, 2. So both $\theta=1$ and $\theta=2$ are the non-unique MLEs.
Answer: Now we have the original question, the mystery is no mystery.
In that question, a single observation will be consistent (to greater or lesser degree) with some of the $\theta$ values and inconsistent with others (the ones that have no chance of giving that observed value).
So for example, if we look at your probability distributions, and possible samples of a single observation:
$x=0:\, $ the ML estimate is $\theta=1$  (since $\frac{1}{2}>\frac{1}{4}$)
$x=1:\, $ the ML estimate is $\theta=2$
$x=2:\, $ the ML estimate is $\theta=1$
So whichever outcome is observed the ML estimate is obvious. This (possibly in table form) is what the original question is looking for.
If instead of one observation, you have a sample of several (as in your version of the question), then a value of $\theta$ will be "ruled out" (have likelihood 0) by any observation in the sample having 0 probability under that $\theta$. If, as above, at least one sample value has likelihood zero under every value of $\theta$, all $\theta$ values have likelihood 0, as was previously suggested in comments.
Comment: I'm at a loss to understand how I failed to be clear. None of the $\theta$ values listed can produce a sample {1, 2, 3}. Forget statistics and imagine instead this experiment: I have an ordinary 6-sided die, and a coin with sides labelled "1" and "2". One of the two devices is to be selected and tossed. You will work out the chances for me after I observe the result, but you have to be elsewhere right away, so I will send you the result (just before I leave on vacation). I write outcome on a postcard and send it to you. When you get the card, it says "8". Which is more likely to give 8?
Comment: I'm using my formulation of the question. So, are all $\theta$ values ruled out or can we choose any one of them, since they are equally likely?
Comment: You saw the die and the coin, they were definitely marked correctly. If I asked you to bet (at good odds, I'll give you 3-1 if you guess correctly) on one of them being the one that generated the "8", would you say "oh, they're equally likely, it doesn't matter which I choose"? Or would you say something more like "What? No that simply can't happen! Something weird is going on! The situation cannot be as it was described. Was there another die or something?"
Comment: In my post I talk about how the distribution may not describe the population well. Consider the setting where the die is 8-sided, but we have pmf for a regular die. Using common sense you would choose the die, even though under your model none of the devices could have generated 8.
Comment: Either I misunderstand the circumstances you're describing or your final comment makes no sense to me. How does the observation of '8' make a six-sided die a better choice than the coin? Neither can possibly give an 8. Maybe it was instead a draw from a deck of cards. Maybe using both and summing the result was an (unmentioned at the time) possibility. Maybe it was meant to be a "2" but somehow ended up looking like an 8 on the postcard. Maybe there was some other mistake. All we know is that if it *is* 8, none of the offered options is *at all* plausible.
Comment: I'm guessing you'd be the kind of person who wouldn't question his model when faced with data outside the support of the distribution. I think one possibility is to accept one of the existing parameter values as an interim solution.
Comment: I'm not sure what basis you have for the assertion about what kind of behavior I'd exhibit in that circumstances. Having faced exactly that situation, I know from observing myself I *certainly* question the model in that circumstance. One situation that does occasionally occur in data I analyze is using a model for positive data when once in a while a negative observation can occur. That doesn't mean I would never use such a model in that situation, but if I do use one (for some kind of approximate inference), I use it in the knowledge that the model cannot possibly be correct ... (ctd)
Comment: (ctd) ... on its face. [One shouldn't conflate "the model has zero likelihood" with "the model is useless". Note that your question was purely about the former, not the latter. It is, however, important to understand what the effect of the model will be on ones inferences; in the case I mentioned before, the model would be used for prediction, and it leads to bias in both mean and variance; nonetheless it is in some situations not unreasonable, in that the problem is at the left end and the object of primary interest (an upper one-sided prediction limit) often isn't much impacted by it.]
Answer: If $P(x=1|\theta = 1) = 0$, then (0,1,2) is impossible, since it has a 1 in it. If $P(x=2|\theta = 2) = 0$, then (0,1,2) is impossible, since it has a 2 in it. So, your likelihood calculation is telling it like it is. It is impossible to get that sample, given your probability distributions and thetas.

How to decide on the MLE when pmf is 0?


Placing two Pie Charts from lessR side by side in one figure

Question: The lessR package can do some pretty nice things, and it makes donut plots simpler than any other package. How does one place two pie charts next to each other in a single plot? I know it can do a trellis for multi-panels, but in the example here that doesn't seem to be an option.

d <- data.frame(
  gender = c("M","M","M","M","M","F","M","M","M","M","M","M","F","M","M","M","F","M","M","M"),
  ethnic_grp = c("WHITE","ASIAN","ASIAN","MULTIETH","MULTIETH","BLACK","NSPEC","ASIAN","ASIAN", "WHITE", "HISPA", "NSPEC","MULTIETH","ASIAN","ASIAN","ASIAN","HISPA","ASIAN","BLACK","MULTIETH")
  )
#chart 1
PieChart(ethnic_grp, fill = "viridis",
         main = NULL, quiet=TRUE)
#chart 2
PieChart(gender, fill = "heat",
         main = NULL, quiet=TRUE)

Rather than produce them in sequence, I'd prefer something like:

I have used ggplot2 to recreate this, but it requires far more work to create these plots that way.
Comment: If you use `ggplot2`, then you can also use the package `patchwork` to place multiple plots together.  If you often want to make the same kind of plot in `ggplot2`, then you can write your own wrapper function.
Comment: One unrelated note to your problem: pie charts are usually not a good type of visualization. A bar chart might be more appropriate here.
Answer: You can do that easily with the add parameter in PieChart. It is pretty straightforward.
First of all, you'll need to use the par function to define the grid i.e number of rows and columns you need based on the number of plots you have.
In your case, you'll need par(mfrow = c(1, 2)) which will plot two plots adjacent to each other.
The whole code looks like this:
library(lessR)
d <- data.frame(
  gender = c("M","M","M","M","M","F","M","M","M","M","M","M","F","M","M","M","F","M","M","M"),
  ethnic_grp = c("WHITE","ASIAN","ASIAN","MULTIETH","MULTIETH","BLACK","NSPEC","ASIAN","ASIAN", "WHITE", "HISPA", "NSPEC","MULTIETH","ASIAN","ASIAN","ASIAN","HISPA","ASIAN","BLACK","MULTIETH")
)

par(mfrow = c(1, 2))
#chart 1
PieChart(ethnic_grp, fill = "viridis",
         main = NULL, quiet=TRUE,  add = PieChart(gender, fill = "heat",
                                                  main = NULL, quiet=TRUE))

Notice, that instead of plotting two charts separately, you'll need to add the other plots inside the add parameter of the first chart.
The output looks like this:


python string adding backslash before single quotes

Question: I have a string that contains quotes like this:
string = "\"This is my mom's vase\", said Kevin."

Problem is when I use it as a string in python it adds a backslash before single quotes, as seen here:
>>> string
'"This is my mom\'s vase", said Kevin.'
>>>

Why is this happening and what can I do about it?
Comment: https://stackoverflow.com/a/71558069/13944524
Answer: The Explanation
What you're seeing is the representation of your string as produced by the repr function. repr outputs strings in such a way that they're valid python literals; in other words, you can copy/paste the output of repr(string) into a python program without getting a syntax error:
>>> string
'"This is my mom\'s vase", said Kevin.'
>>> '"This is my mom\'s vase", said Kevin.'  # it's valid python code!
'"This is my mom\'s vase", said Kevin.'

Because your string contains both single quotes ' and double quotes ", python has to escape one of those quotes in order to produce a valid string literal. The same way you escaped your double quotes with backslashes:
"\"This is my mom's vase\", said Kevin."

Python instead chooses to escape the single quotes:
'"This is my mom\'s vase", said Kevin.'

Of course, both of these strings are completely identical. Those backslashes are only there for escaping purposes, they don't actually exist in the string. You can confirm this by printing the string, which outputs the string's real value:
>>> print(string)
"This is my mom's vase", said Kevin.

The Solution
There's nothing to solve! What are you still doing here? Scroll up and read the explanation again!
Comment: BTW if a string contains single-quotes but no double-quotes, the repr will be inside double-quotes, for readability. E.g. `'mom\'s'` -> `"mom's"`
Answer: It's just escaped in the REPL. If you print it out, it will show there is no slash added:
print(string)
# output: "This is my mom's vase", said Kevin.

Comment: And "the repl" just means "the command-line where you try things out".  http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop
Comment: And they are escaped because in the command line strings are enclosed with single quotes
Answer: I found the solution, it has nothing to do with repr(string), as @Aran-Fey mentions, it has to do with API and Jsons response.
The correct approach is that you are not returning strings or jsons dumps, but response which http protocols interprets as you mention: \" (backslaches every string).
The solution is to make a http response as follows:
from flask import request, jsonify, make_response
from flask_restful import Resource
from flask_api import status

class employeeHiring(Resource):
    def post(self):
    #YOUR CODE ....
    return make_response(jsonify({'status': 'success', 'my Dict': dict}), status.HTTP_201_CREATED)

Comment: I think you're answering a different question
Comment: Oh, you're answering your own question that you [posted as an answer](https://stackoverflow.com/a/56861443/4518341). Please don't post questions as answers. Instead, you can ask a new question and [answer it yourself](/help/self-answer).


Nodejs - Convert a '{a:1}'-style string (generated by `util.format()`) into an objects

Question: util.format() generates '{a:1}'-style strings which are not valid JSON. (Note that keys are not surrounded by double quotes.) How to convert this kind of strings back into objects?
Answer: Use eval if it's definitely trustworthy:
eval('(' + str + ')');

Comment: Oh no, I would try to avoid `eval`.
Comment: @powerboy: Er... why? (Given the additional details, by the way, there is no way you *can* avoid it.)
Answer: Unless you have a very good reason not to, you should be using JSON.stringify() to convert an object to a string and JSON.parse() to reconstitute an object back from a string.
Comment: `JSON.stringify()` does not handle Regex, Date, Error, etc.
Comment: @powerboy Certainly true.  So what are you ultimately trying to do?  stringify and un-stringify any JavaScript object?
Comment: More specifically, stringify a JS object, send it over the wire, and the client pretty-print it.
Comment: @powerboy Then I think you're stuck with `eval` or developing your own equivalent.


Unity control object via socket Udp C#

Question: I have an object in unity and I want to control movement via udp using Visual Studio 2012 (C#). I've test send and receive chat and already successful.
And I've test script for move object ongui and its successful too. And now I want to control object transform or translate from command string that I got from udp receive but the object not moved.
Here is my code on receive
private  void ReceiveData()
{

    client = new UdpClient(port);
    while (true)
    {

        try
        {
            // Bytes empfangen.
            IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
            byte[] data = client.Receive(ref anyIP);

            // Bytes mit der UTF8-Kodierung in das Textformat kodieren.
            string text = Encoding.UTF8.GetString(data);

        switch (text)
        {

        case "loc+x" :
        {
            satelit.transform.Translate (speedloc,0,0 * Time.deltaTime);
            break;
        }

        case "loc-x" :
        {
            satelit.transform.Translate (-speedloc,0,0 * Time.deltaTime);
            break;
        }

        }

            // Den abgerufenen Text anzeigen.
            print(">> " + text);

            // latest UDPpacket
            lastReceivedUDPPacket=text;

            // ....
            allReceivedUDPPackets=allReceivedUDPPackets+text;

        }
        catch (Exception err)
        {
            print(err.ToString());
        }
    }
}

The string that I send is received but the object can't move.
Comment: "did not work" is not a problem description. do the switch statements in question run or not?
Comment: sory my english is poor
Answer: first, you have to check the value of "speedloc". If it's null or zero, your object won't move anyway.
also, I suggested that you should change this line from
satelit.transform.Translate (speedloc,0,0 * Time.deltaTime);

to
satelit.transform.Translate (new Vector3(speedloc,0,0) * Time.deltaTime);

Unity control object via socket Udp C#


Prove increasing convex function has increasing differences

Question: Let $v: \mathbb{R} \to \mathbb{R}$ be an increasing, convex function.
For any $t>0$ I want to show that for all $x_{1} \leq x_{2}$ we have: $$v(x_{1}+t) - v(x_{1}) \leq v(x_{2} +t) - v(x_{2})$$
This of course can be illustrated heuristically if $v$ is twice differentiable. But I am trying to show this from the definition of a convex function and by the fact that $v$ is increasing, but I am just moving in circles. I am pretty sure this result is true, and I need it to finish a proof I am working on.
Any suggestions will help.
Comment: Hello, I was considering a similar question. Does this imply that the second derivative of $v$ is increasing?
Answer: Since $x_1 \le x_1+t,x_2 \le x_2+t$, from the definition of convexity we have
$$ v(x_1+t) \le \left(\frac{x_2-x_1}{x_2-x_1+t}\right)v(x_1) + \left(\frac{t}{x_2-x_1+t}\right)v(x_2+t) $$
and
$$ v(x_2) \le \left(\frac{t}{x_2-x_1+t}\right)v(x_1) + \left(\frac{x_2-x_1}{x_2-x_1+t}\right)v(x_2+t).$$
Adding up the inequalities gives the desired inequality.
Comment: I think this is a great and succinct answer. However, before I accept and upvote, I am wondering if you can explain the steps you took to get to this solution? I worked for a while on this problem and could not get here, so I want to understand how you reached this point.
Comment: Nevermind, I see the logic. Thanks for your help.
Comment: I'm sorry, i made mistake for edit. Original answer is also correct. It is good answer.
Answer: [This inequality is true for any convex function, increasing or not.]
I'm going to assume that $x_2\le  x_1+t$. The reasoning in the remaining case is similar. First consider the three points $x_1\le x_2\le x_1+t$. We have
$$
x_2={x_1+t-x_2\over t}x_1+{x_2-x_1\over t}(x_1+t),
$$
so by the convexity inequality for $\nu$,
$$
\nu(x_2)\le {x_1+t-x_2\over t}\nu(x_1)+{x_2-x_1\over t}\nu(x_1+t).
$$
Similarly,
$$
\nu(x_1+t)\le {x_2-x_1\over t}\nu(x_2)+{x_1-x_2+t\over t}\nu(x_2+t).
$$
Now add these two inequalities, clear $t$ from the denominator, and simplify.


$\forall x\exists y(P(x)\longrightarrow Q(y))\longrightarrow\exists y\forall x(P(x)\longrightarrow Q(y))$ universally valid?

Question: I tried to come up with an interpretation that makes it false, but I cant, and I cant come up with a proof by contradiction either.
If someone could point me towards the general direction, that would be great.
Comment: @B.Swan Although that's a good instinct in general, in this specific case they happen to be equivalent.
Comment: So an illustration would be the difference between continuity and uniform continuity (for a fixed $\epsilon \gt 0$).
Comment: This particular formula is valid. Note that both formulae are equivalent to $\exists xP(x)\to\exists yQ(y)$.
Comment: No, the first means for any $x$ you can find some $y$. The second means you can find a $y$ that is set for all $x$.
Comment: So its not universally valid? Could I get some tips on how to prove this formally?
Comment: If $\exists x(P(x))$ then for such an $x$, there must be a $y$ so that $Q(y)$ is true, and hence $P(x')$ implies $Q(y)$ for all $x'.$ Now check the case $\lnot\exists x(P(x))=\forall x(\lnot P(x)).$ In that case we can take any $y$ to get because $\text{false }\implies\text{ anything}.$
Comment: @RobertShore That would be correct if $x$ and $y$ are the same,but $x,y$ are unrelated.
Answer: In general, you can't permute $\forall$s and $\exists$s. However, this is a special case, and the implication you've described does hold for this very specific instance - roughly, because the two quantifiers don't really interact very much. Let's see why.
The key is to realize that $$P(x)\rightarrow Q(y)$$ is only saying "either $Q(y)$ holds or $P(x)$ fails." For example, if there is a single $a$ such that $Q(a)$ holds, then $\exists y\forall x(P(x)\rightarrow Q(y))$ is true (set $y=a$). More generally, this should suggest that the two statements in question (especially the second) are actually a lot simpler (and weaker) than they first appear.
At this point you should try to simplify each statement: under what conditions on $P$ and $Q$ is each statement true? You can then just compare these simpler expressions.
A good starting point: we've argued above that $\exists y\forall x(P(x)\rightarrow Q(y))$ is true if $\exists y(Q(y))$ is true; what is the other way for $\exists y\forall x(P(x)\rightarrow Q(y))$ to hold (that is, what needs to happen in order for $\exists y\forall x(P(x)\rightarrow Q(y))$ to be true if there is no $y$ such that $Q(y)$)?
Comment: Yes, @TimWeah. This is one of those cases where we have to avoid treating $\rightarrow$ as an intuitive meaning "implication," but rather as its propositional calculus meaning.
Comment: So it is universally valid? AKA it is true under all interpretations?
Comment: @TimWeah Yes, that's exactly what I'm saying.
Answer: Typically, when you compare a $\forall x \exists y \ \varphi(x,y)$ with the one where the quantifiers are swapped, i.e. $\exists y \forall x \ \varphi(x,y)$ you have:
$\exists y \forall x \ \varphi(x,y) \Rightarrow \forall x \exists y \ \varphi(x,y)$
$\forall x \exists y \ \varphi(x,y) \color{red} \not \Rightarrow \exists y \forall x \ \varphi(x,y)$
However, in this case the two statements are equivalent, since you don't really have any relationship between $x$ and $y$
That is: $\forall x\exists y(P(x)\to Q(y))$ is equivalent to $\exists y\forall x(P(x)\to Q(y))$
To show this, you can use the Prenex Laws:
Prenex Laws
Where $\varphi$ is any formula and where $x$ is not a free variable in $\psi$:
$ \forall x \ \varphi \to \psi \Leftrightarrow \exists x (\varphi \land \psi)$
$  \psi \to \forall x \ \varphi  \Leftrightarrow \forall x (\psi \to \varphi)$
$ \exists x \ \varphi \to \psi \Leftrightarrow \forall x (\varphi \to \psi)$
$  \psi \to \exists x \ \varphi  \Leftrightarrow \exists x (\psi \to \varphi)$
So:
$\forall x\exists y(P(x)\to Q(y)) \Leftrightarrow$
$\forall x(P(x)\to \exists y \ Q(y)) \Leftrightarrow$
$\exists x \ P(x)\to \exists y \ Q(y) \Leftrightarrow$
$\exists y (\exists x \ P(x)\to  \ Q(y)) \Leftrightarrow$
$\exists y \forall x (P(x)\to  \ Q(y)) $


Send JSON data to PHP and use it

Question: I have an issue with sending json data with ajax to a php file and then use it to upload to the server.
If I'm making echo of the variable $email_info->Name the returned data value is empty.
I've tried json_decode but it doesn't do it.
This is the code I have,
Jquery:
$( document ).on('click', '#send_touch', function(){

    new_email = [];

    new_email.push({
    Name: $('#name').val(),
    Phone: $('#phone').val(),
    Email: $('#email').val(),
    Interested_in: $('#interested_in').val(),
    User_id: $('#email_user_id').val()
    });

    new_email = JSON.stringify({Email: new_email}, null, "\t");

        $.ajax({
            url: "core.php",
            type: "post",
            data: { NewMail: new_email
                  },
            success: function(data){
                alert(data)
            },
            error: function(){
            }
     });

});

PHP:
if ($_POST['NewMail']) {

 $timeStamp = time();

 $new_email = json_decode($_POST['NewMail'], true);

 $email_info = $new_email->Email[0];

 // New Email
 mysql_query("INSERT INTO " . $dbPrefix . "touches (date, user_id, name, phone, email, interested_in, seen, status) VALUES ('".safeSQL($timeStamp)."', '".safeSQL($email_info->User_id)."', '".safeSQL($email_info->Name)."','".safeSQL($email_info->Phone)."', '".safeSQL($email_info->Email)."', '".safeSQL($email_info->Interested_in)."', '0', '1')") or die("Query failed: " . mysql_error());

 echo $email_info->Name;

}

If I make an echo on the PHP side for $_POST['NewMail'] I get returned this:
{
\"Email\": [
    {
        \"Name\": \"John Doe\",
        \"Phone\": \"1234567\",
        \"Email\": \"email@example.com\",
        \"Interested_in\": \"Text here..\",
        \"User_id\": \"1\"
    }
]
}

How can I fix this?
Comment: You need to stop using `mysql`. It is outdated. Move to `PDO` or `mysqli` which means "mysql improved". That should tell you it's better. I prefer PDO. I don't know what you "safeSQL" is, but scratch that and use prepared statements instead. Prepared statements guarantee your queries can't be attacked via sql injection.
Answer: Replace this part in PHP :
$new_email = json_decode($_POST['NewMail'], true);

by this :
if (get_magic_quotes_gpc()) {
    $_POST['NewMail'] = stripslashes($_POST['NewMail']);
}
$new_email = json_decode($_POST['NewMail'], true);

This should fix the issue.
Comment: NOTE!!! magic quotes ought to be off anyway!! If magic quotes are on, this is not really the solution! See http://php.net/manual/en/security.magicquotes.php. Magic quotes are totally removed in php 5.4
Comment: I think his problem is that (magic quotes) are turned on, Check out what he got after echo'ing $_POST['NewMail'].
Comment: Right, then the solution is to turn them off, not write code to deal with them.
Comment: I am not stick at leaving magic quotes = on , but there is no effective way to turn it off in the script. He can only turn it off through php.ini only if he have access to this config file.
Comment: Thanks, this actually helped me to get to my answer. Just realized that I have magic quotes turned 'on' on my server.
Comment: @Kim You are welcome. well, you own a server, keep in mind also that using "get_magic_quotes_gpc()" you can handle this for old versions of php if you don't have access to php.ini. Anyway, I'm glad your problem is solved. :)
Comment: And yes I'm planning to turn magic_quotes 'off'. But there are many many sites that will be affecting with changes on the server. But if I turn it off, could it break some code that are there in general on the server? (Maybe a dumb question)
Comment: @Hossam Yeah, I'm glad it's solved aswell :) Now I can keep on developing again! (Yihoo)
Comment: Probably, yes, depending on the other codes used in the server. But it is better to turn it off anyway as @m59 recommends, then check if there are new problems appeared. It will usually affect any php code handling user values entered in forms.
Answer: I had magic_quotes turned 'on' on my server.
I realized it when testing Hossams code:
if (get_magic_quotes_gpc()) {
    $_POST['NewMail'] = stripslashes($_POST['NewMail']);
}

So finally this got to work with this code:
if ($_POST['NewMail']) {

$timeStamp = time();

if (get_magic_quotes_gpc()) {
    $_POST['NewMail'] = stripslashes($_POST['NewMail']);
}

$new_email = json_decode($_POST['NewMail'], true);

$email_info = $new_email['Email'][0];

// New Email
mysql_query("INSERT INTO " . $dbPrefix . "touches (date, user_id, name, phone, email, interested_in, seen, status) VALUES ('".safeSQL($timeStamp)."', '".safeSQL($email_info['User_id'])."', '".safeSQL($email_info['Name'])."','".safeSQL($email_info['Phone'])."', '".safeSQL($email_info['Email'])."', '".safeSQL($email_info['Interested_in'])."', '0', '1')") or die("Query failed: " . mysql_error());

var_dump($email_info['Name']);

}

And I got the array with $email_info['Name'] instead of $email_info->Name
Answer: you need to specify to jquery that your sending data is a JSON type. Please configure the type of data in the ajax options. For example:
$.ajax({
       url: "core.php",
       type: "json", //here comes the data's type
       data: { NewMail: new_email
       },
       success: function(data){
        alert(data)},
        error: function(){
        }`

Comment: It doesn't hurt to specify that, but jQuery shouldn't be having trouble determining the data type automatically. I believe it because he used `stringify` rather than sending the object normally. Actually, I feel pretty sure setting it as json and then sending a string (like he is doing) will be bad.
Comment: Check this out please, http://stackoverflow.com/questions/8926805/how-to-use-json-decode-to-extract-an-inner-information

Send JSON data to PHP and use it


Probability of tossing a coin twice & MATLAB?

Question: I'm watching this video at 21:20 min. The guy gave an example for tossing a coin four times. At 23:49 min, he said we can plot the probability of tossing a coin (e.i. $n$) for a large number in MATLAB by using this formula
$$
px(k) = \dbinom{n}{k} p^{k}(1-p)^{n-k}  \qquad, k=0,1,...,n
$$
Ok now I want to plot his example but I'm facing problems. For his example, $n=4 , k = 0,1,2,3,4$ (what does $k=0$ mean here?). This is my code in Matlab
<code>clear all
clc
outcome = 2; % outcome # of a coin (Head & Tail)
n = 4; % tossing #
k = 0:n; % # of getting head or tail
p = 1/n^outcome; % the total probability of all outcomes (1/16)
i = 0; % iterator for the loop

for i = 0:size(k,2)
    Px = nchoosek(n,k(i)) * p^k(i) * (1-p)^(n-k(i));
end

plot(k, Px)
</code>
What's wrong with my approach?
Comment: In the formula you gave (for Bernoulli trials), the parameter $p$ is the probability of a single outcome. For tossing a coin, this should be 1/2. In your code, it should be 1/outcome.
Comment: @HughDenoncourt, I'm still getting error. How can I apply the formula in case $k =0$?
Answer: This is the binomial distribution (you can look it up just about anywhere).  $k$ is the number of successes (heads in this case), and it is certainly possible to get no successes in four attempts.  The $p$ is the probability of success for each trial (it's assumed that each coin-flip has the same probability of success as all the others) and should be 1/2.
Comment: @CroCo plug it in? You get $\binom40\cdot p^0\cdot (1-p)^{4-0} = (1-p)^4$. In matlab, `nchoosek(4,0)*p^0*(1-p)^(n-0)`. They're all well-defined.
Comment: I can visualize the problem by drawing a tree of tossing the coin 4 times and one of the case is getting (TTTT), so in this case $k=0$ (I'm assuming $k$ to be the number of getting Head) but How can I apply the formula in case $k=0$?
Comment: I found the problem. it was the first step of my loop. It should starts from 1 not 0.