Arclength defined parametrically

Question: curve defined parametrically
I'm pretty sure the values of dx/dt and dy/dt are already given in the question so its just a matter of plugging into the arclenght formula for curves defined parametrically. My only concern is that this simplifies to the [t] from 1 to 0. with the final answer being simply 1. This can't seem to be right.
the last bit that was cut off by the picture is just d0`
Comment: Why cannot that be correct? Also, you better include the text of the problem here (use mathjax to write equations). Links can go invalid, and it will also help for people with screen readers.
Comment: Well it could be correct, it is just that the current professor is constantly throwing 8 mph change-ups and then with this hits us with 99 mph fastballs. It is just difficult to know if i truly have a handle on this when my answers turn out wrong due to a simple trick. I will make sure all of my future post are presented with mathjax as well thank you.
Answer: You need to compute over a range $$L=\int_{t_1}^{t_2} \sqrt{\left(\frac{dx}{dt}\right)^2+\left(\frac{dy}{dt}\right)^2}\,dt$$ where $$x=\int_0^t f(\theta)\, d\theta\qquad \text{and}\qquad y=\int_0^t g(\theta)\, d\theta$$ Now, using the fundamental theorem of calculus $$\frac{dx}{dt}=f(t)\qquad \text{and}\qquad \frac{dy}{dt}=g(t) $$ So, for your case, using $\sin^2(a)+\cos^2(a)=1$, you properly end with $$L=\int_{t_1}^{t_2} dt=t_2-t_1$$ and you are very correct.
You could easily show that, if $$x=\int_0^t \cos\left(\phi(\theta)\right)\, d\theta\qquad \text{and}\qquad y=\int_0^t \sin\left(\phi(\theta)\right))\, d\theta$$ you would have the same result since $$\frac{dx}{dt}=\cos\left(\phi(t)\right)\qquad \text{and}\qquad \frac{dy}{dt}=\sin\left(\phi(t)\right) $$  $$\left(\frac{dx}{dt}\right)^2+\left(\frac{dy}{dt}\right)^2=1$$ for any function $\phi(\theta)$.
Answer: This problem is almost trivial in the complex plane. Consider that
$$z=\int_0^t \cos(\pi\theta^2/2) d\theta+i\int_0^t \sin(\pi\theta^2/2) d\theta=\int_0^t e^{i\pi\theta^2/2}d\theta$$
Now, in the complex plane arc length is given by
$$s=\int |\dot z| du$$
and in the present case $\dot z=e^{i\pi\theta^2/2}$ and $|\dot z|=1$, and therefore
$$s=\int_0^1 dt=1$$

Arclength defined parametrically


Using Euler and polynomials

Question: I want to show that $\sum_{k=-N}^{N}e^{ikx}=\frac{\sin((N+\frac{1}{2})x)}{\sin(\frac{x}{2})}$ for $N\in \mathbb{N}$
Any tips on how to proceed?
I tried doing it in two ways:
First using the sum of polynomials formula:
($1+r+r^2+...+r^n=\frac{1-r^{n+1}}{1-r}$) while letting $r=e^{ix}$
but the calculation got too tedious.
Second by replacing $e^{ix}$ with Euler's formula directly, I get:
$\sum_{k=-N}^{N}e^{ikx}=1+2\sum_{k=1}^{N}\cos(kx)$
which isn't anywhere close the required result.
Comment: Possible Duplicate of [This](http://math.stackexchange.com/questions/17966/how-can-we-sum-up-sin-and-cos-series-when-the-angles-are-in-arithmetic-pro/1214626#1214626).
Answer: Creative telescoping is (almost) always the answer. You may notice that
$$\left(\sin\frac{x}{2}\right)\cdot\left(1+2\sum_{k=1}^{N}\cos(kx)\right) = \sin\frac{x}{2}+\sum_{k=1}^{N}\left[\sin\left(\left(k+\frac{1}{2}\right)x\right)-\sin\left(\left(k-\frac{1}{2}\right)x\right)\right]$$
and easily draw your conclusions.
Answer: You gave up too soon on the geometric series.  With $r = e^{ix}$,
$$\eqalign{ r^{-N} + r^{-N+1} + \ldots + r^N &= \frac{r^{N+1} - r^{-N}}{r-1}\cr
&= \frac{r^{N+1/2} - r^{-N-1/2}}{r^{1/2} - r^{-1/2}}\cr
&= \frac{e^{i(N+1/2)x} - e^{-i(N+1/2)x}}{e^{ix/2} - e^{-ix/2}}\cr
&= \frac{\sin((N+1/2)x}{\sin(x/2)}}$$
Comment: Thanks, had to multiply by $r^{-1/2}$, didn't see that one.

Using Euler and polynomials


Updating datafram columns with same row

Question: I have two dataframes, dfA: containing data and dfB: other is 1-row dataframe which contains header information. I need to update dfB and add all the columns that dfB has. The value of each row of those appended column should has the exact row from dfB (duplicates)
dfA:

colA
colB
colC

a0
b0
c0

a1
b1
c1

dfB:

colD
colE
colF

d0
e0
f0

the desired output should look like

colA
colB
colC
colC
colD
colE

a0
b0
c0
d0
e0
f0

a1
b1
c1
d0
e0
f0

I have tried

pd.concat([df,header_df],axis=1,join='outer')
but it only appends to the first row and leave the n other rows with null values like this:

colA
colB
colC
colC
colD
colE

a0
b0
c0
d0
e0
f0

a1
b1
c1
null
null
null
Comment: Use `pd.concat([df,header_df],axis=1).ffill()`
Comment: you can do a ffill() on ColC, ColD, ColE after you concat. Alternate, you can modify dfB to be of same length as dfA by using repeat
Answer: You can use the DataFrame's fillna method after your concat step - to "forward fill" the values from the first row into all the subsequent rows
df = pd.concat([df,header_df],axis=1,join='outer')
df = df.fillna(method='ffill')

Updating datafram columns with same row


Dump Microsoft SQL Server database to an SQL script

Question:
Possible Duplicate:
Dump Microsoft SQL Server database to an SQL script

Is there any way to export a Microsoft SQL Server database to an sql script?
I'm looking for something which behaves similarly to mysqldump, taking a database name, and producing a single script which will recreate all the tables, stored procedures, reinsert all the data etc.
I've seen http://vyaskn.tripod.com/code.htm#inserts, but I ideally want something to recreate everything (not just the data) which works in a single step to produce the final script.
Thanks in advance
Answer: this is a duplicate: Dump Microsoft SQL Server database to an SQL script


Kubernetes auth, how can allow public access to a sub-route of an ApiService?

Question: I have a Kubernetes OIDC-enabled cluster. Also, I have created an ApiService to access my app service using the control plane. I do not have any CRD.
apiVersion: apiregistration.k8s.io/v1
kind: APIService
metadata:
  name: v1alpha1.wallet.example.org
spec:
  groupPriorityMinimum: 1000
  group: wallet.example.org
  insecureSkipTLSVerify: true
  service:
    name: my-svc
    namespace: default
    port: 3000
  version: v1alpha1
  versionPriority: 15

It is exposed under kubeAPI and I can access my service using Bearer.
The problem is, that I need public access to some of my REST endpoints in the service. How can I tell Kubernetes to skip this URL to being authenticated via OIDC?
I don't talk about Ingress, LB, or NodePort

Updated:
I've added the ClusterRole & ClusterRolebinding :
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: wallet-role
rules:
- apiGroups:
  - "wallet.example.org"
  resources:
  - "*"
  verbs:
  - "*"
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: wallet-rb
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: wallet-role
subjects:
- kind: Group
  name: system:unauthenticated
  apiGroup: rbac.authorization.k8s.io
- kind: Group
  name: system:authenticated
  apiGroup: rbac.authorization.k8s.io
- kind: Group
  name: system:anonymous
  apiGroup: rbac.authorization.k8s.io

Also have replaced wallet.example.org with * too. But no difference.
Response is:
{
    "kind": "Status",
    "apiVersion": "v1",
    "metadata": {},
    "status": "Failure",
    "message": "Unauthorized",
    "reason": "Unauthorized",
    "code": 401
}

Answer: Try using this RBAC definitions:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: wallet.example.org
rules:
- nonResourceURLs:
  - /apis/wallet.example.org/*
  verbs:
  - get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: wallet.example.org
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: wallet.example.org
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: system:anonymous

You can then test access using:
kubectl --as=system:anonymous get --raw /apis/wallet.example.org/v1alpha1

Comment: I wasn't aware of the ```- nonResourceURLs:``` thanks.
Comment: even when it works. I've no success yet.
Comment: Try using User "system:anonymous" instead of Group. It works for me. Also check if you have "--anonymous-auth=true" apiserver flag enabled.
Comment: I've changed the Authorization Mode from ```AlwaysAllow``` to ```RBAC``` and now it seems it's working. I've accepted the answer, please make an upvote to 0. thanks.


Line representation - implicit form

Question: I am going through one of the the scan conversion techniques and it mentions  the implicit equation of line as follows:
$$F(x,y) = ax + by + c = 0 .$$
The text also mentions that $F(x,y)=0$  if the point is on the line without any proof. I am looking for a proof.
Answer: In learning coordinate geometry, we usually start with plugging some $x_{i}$ into $ax+by+c=0$ to find an unknown $y_{i}$ with known $a, b, c$.  Then we observe that these ordered-pairs $(x_{i},y_{i})$ are always collinear in Cartesian plane.  Here, the process are reversed.  A point $(x',y')$ satisfying $F(x',y')=0$ where $F(x,y)=ax+by+c$.  Usual text seldom provides a proof.  If so, we need to define what is a straight line on Cartesian plane. Teacher may use dynamic software to illustrate the idea by varying a point on the graph and checking the relation.
Comment: Geogebra which is a freeware.
Comment: What software did you use to illustrate the image above ? It is very well demostrated.
Comment: There are more issues here: The text also mentions that F(x,y) is positive for points below the line and negative for points above the line. Now if take the points P(-1,3) and P(-1,1), I am getting a something totally opposite. Lets take P(-1,3), I am getting F(-1,3)  > 0 and for P(-1,1) , F(-1,1) < 0. Any explanations ?
Comment: Need to rearrange $F(x,y)=0$ into $y=-\frac{ax+c}{b}$, if $y'>-\frac{ax'+c}{b}$, then the point is above the graph.  If $b=0$, check $x', -\frac{by'+c}{a}$ instead (right or left).
Comment: The text did not mention anything about the derivative here that you are suggesting. Should it not work with the just mapping the example coordinate points I mentioned ? Could you explain the purpose of taking derivative here ?
Comment: Lazy notation: $(x',y')$ is a point for testing.  If you don't like it, use $(x_{1},y_{1})$.
Comment: Thanks,    I do not understand why do we have re-arrange to proof F(x,y) > 0 or F(x,y) < 0. The example for F(x,y) = 0 with a sample line in the form ax + by + c map very well with the sample coordinate point. Should not the remainings work in the same manner.
Comment: @sajis997 Have you learnt **slope-intercept form** in your school curriculum?  That's what I transformed to and it is convenient for graph sketching, illustrating inequalities and linear programming.
Comment: While proving the proof for F(x,y) = 0, you did the following : 1. ax + by + c = 0 as the standard equation of line in implicit form is F(x,y) = ax + by + c. 2. You defined some values for the constants a, b ,c and a sample point and then plot the point to proof the case, no re-arrangment was necessary. Why not follow the same steps to proof F(x,y) < 0 and F(x,y) > 0
Comment: Look back to your **very very earlier** comments: **$F(x,y)$ is positive for points below the line and negative for points above the line**  which is not sufficient coz you need to check the sign of $a$ and $b$.  What I'd tried to express $y=g(x), b\neq 0$ for easy identification.
Comment: Exactly, F(x,y) > 0 for points below the line. Then I picked a point (-1,1) and plotted it (By the way - (-1,1) is below the line from your example line) . To my surprise I found F(x,y) = 3x + 2y + 1 < 0. This is where the confusion starts. Then you suggested to re-arrange, but I did not understand why do I have to re-arrange.
Comment: The graph $y=g(x)$, generally whatever well-defined function $g(x)$, divides the Cartesian plane in two regions one is $y>g(x)$ (the region above the graph) and $y<g(x)$ (the region below the graph) and of course $y=g(x)$ is the boundary among the two regions.

Line representation - implicit form


Suspicious Exchange message queues filling up disk space

Question: So i came across my HD space getting full too quickly and after doing some inspecting with wireshark and powershell. It seems my email server is being used as a relay for spam.

I closed port 25 on my firewall suspecting the spam was external but the queue kept filling up.
I ran wireshark and filtered ports 25,587 and 465 to see if any other device on the network was sending emails to my server but i did not see any external traffic coming into the server.
Ran TCP dump on the only 2 linux machines i have for the same ports and did not see any traffic as well.

right now im currently running virus scans on my exchange server to see if it somehow got infected. But the queue keeps sending emails to some domain called "desmondelliottprize.org.uk"
Is there any way i can block messages to a domain in ECP from sending or reaching the queue?
I need to figure out what is spamming my server but in the mean time i figure i block it temporarily while i get it fixed so my IP doesn't get blacklisted.
Answer: If anyone has a similar issue in the future.
i ran get-queue in EMC which provided me the "NextHopDomain". So in order to stop these messages from reaching and spamming the queue, i created a mail flow rule to reject/delete any messages containing that domain in the sender/recipient address. That seemed to stop the queue from filling up. But now im going to be running virus scans on my server. But other than that, it helped for now.

Now the queue is clean
Answer: Thanks for your sharing, and i'm glad you have resolved your issue.
In addition, you could configure spam filter policies when your environment is in exchange online, refer to this article and hope this help. If you are in exchange on premise, transport rule is also a good choice:)
It is helpful to other people who encounters the same issue with you if you mark the helpful reply as best answer.


Proving whether a complex function is analytical help!

Question: I am currently struggling to prove whether a complex function is analytical. I understand that I must employ the Cauchy-Riemann relations to do this. However, the answer I get is one that I can't reconcile with what I am told the answer is. This is the function;
$f(x+iy) = |x^2 - y^2| + 2i|xy|$
With this, I believe that I need to do Cauchy-Riemann with four different functions, namely,

$f(x+iy) = x^2 - y^2 + 2ixy$
$f(x+iy) = y^2 - x^2 - 2ixy$
$f(x+iy) = x^2 - y^2 - 2ixy$
$f(x+iy) = y^2 - x^2 + 2ixy$

Which makes me arrive at;

$u_x = 2x = v_y = 2x$,
$u_y = -2y = -v_x = -2y$

$u_x = -2x = v_y = -2x$,
$u_y = 2y = -v_x = 2y$

$u_x = 2x = v_y = -2x$,
$u_y = -2y = -v_x = 2y$

$u_x = -2x = v_y = 2x$,
$u_y = 2y = -v_x = -2y$

respectively.
Now, I think the answer is that the function is only analytical at x = 0, as I think that is the way only all of these equations can be solved simultaneously. But the prescribed solution is not this and I can't really see why.
Thanks :D
Comment: Cheers for the response. So you are saying its the function as a whole is not analytical anywhere then?
Answer: You have in the complex plane four open regions where the CR equations are satisfied. These corresponds to yours functions $1$ and $2$ in the regions $U_1=\{ x+iy|x^2-y^2>0\;  and\; xy>0 \}$ and $U_2=\{ x+iy|x^2-y^2<0\;  and\; xy<0 \}$ respectively.
Edit: Answering your additional questions.

" functions 3 and 4 do not satisfy CR (not even at 0?)"

For analicity in a point $z_0$ we need CR equations be satisfied on open set that contains $z_0$. As no such a set exist for $z_0=0$, your function is not analitic there.

"but they do correspond to the initial function, right? Like I expanded the absolute values correctly? "

Yes. All yous considerations where correct.

"You're also saying functions 1 and 2 satisfy CR in those certain regions, I still can't see how to arrive at that."

It's just your own calculations. For cases 1 and 2, where the absolute values are the identity or minus identity, the equations are satisfied. In cases 3 and 4 no. Note that case 1 is: $|x^2-y^2|=x^2-y^2$ and $|xy|=xy$, that is: $x^2-y^2>0$ and $xy>0$. Also case 2 is: $|x^2-y^2|=-(x^2-y^2)$ and $|xy|=-(xy)$, that is: $x^2-y^2<0$ and $xy<0$.
Comment: Yeah that's the prescribed solution. So let me get something clear, functions 3 and 4 do not satisfy CR (not even at 0?) - but they do correspond to the initial function, right? Like I expanded the absolute values correctly? You're also saying functions 1 and 2 satisfy CR in those certain regions, I still can't see how to arrive at that. Apologies for the loaded response, hopefully you can push me in the right direction.
Comment: Thanks man this has made it all very clear to me now. I would upvote your response and give you rep but I am unable to as I am under 15 rep myself hahaha
Comment: haha it's ok. Your welcome.


Main effect not significant, but confound is

Question: I am a little bit stuck with my data analysis.
What does it mean if your main effect is not significant (.442) but becomes even less significant when you add your control variable (.718)
Furthermore, it seems that the contol variable has a marginal significant effect on the dependent variable (p=.104)
Many thanks in advance!
Comment: Assuming the analysis was conducted correctly, it seems like the main effect simply wasn't statistically significant. I don't think it really "means" much of anything -- neither the main effect nor the confounder was significantly associated with the response. Disappointing as that may be, it happens! Also, opinions differ on this point, but I tend to shy away from talking about "marginal significance" (especially with a p-value that far from the conventional .05 level). Report the p-value and report the effect size, and let the reader draw his/her own conclusions about the importance.
Answer: If your control variable was measured prior to the predictor of interest, what you have observed usually occurs when the control variable has an effect in the same direction on both the predictor and the outcome. E.g., if prior academic achievement positively affects both admission into a scholarship program and future achievement, then the effect of the scholarship program on future achievement will be smaller conditional on prior achievement. In addition, if the control variable is highly associated with the predictor and less associated with the outcome, your increase in p-value may be due to colinearity or conditioning on a near-instrument, both of which don't change the effect of the predictor but increase it's variance.
If you control variable was measured after the predictor of interest, you may be blocking the effect of the predictor on the outcome. In the same scenario, imagine you instead control for an intermediate outcome, like depressed feelings. Part of the effect of the scholarship on future achievement may occur through the effect of the scholarship on lowering depressed feelings, which improve achievement. Controlling for depressed feelings will block part of this effect, decreasing the predictor's effect.
Answer: It means that your quantitative analysis may not yield the results, there could be an error, or the sample was not a good one.
Comment: You can triangulate the analysis by using another method of analysis for comparison purposes


Codeigniter 2.1 $this->input->set_cookie($some_var); NOT WORKING

Question: I started creating a custom library that i would load for checking if user is logged in and also for registering users. Registration not started yet, but that's not important...
here's the problematic part.. it WON't set cookies:
<code>$this->load->helper('cookie');
$some_value= 'asd';
$some_cookie_array = array(
                          'name'   => 'some_name',
                          'value'  => $some_value,
                          'expire' => 86500,
                          'secure' => TRUE
                          );
$this->input->set_cookie($some_cookie_array);
</code>
here is the full code for now:
codepad.org/FILlq2qR
This is how i call the library and check if user is logged in:
<code>$this->load->library('user_management');
$login_data = $this->user_management->login();
var_dump($login_data);
</code>
Any help is more than welcome!
Cheers!
Comment: Might i add that I'm still new at CI
Answer: Someone on the CodeIgniter Forum helped. The reason was that I was using <code>'secure' => TRUE</code> which is only for https.
Comment: I had enabled CSRF protection, but was not using CI's form helper (manually setting the hidden field). CSRF wasn't working for me because of my cookie settings were set to 'secure' => TRUE. Your tip helped fix that!


How to select model based on Cross Validation?

Question: I always thought we select the model with the lowest cross validation , since cross validation is the estimate of prediction error.
However, there is the "one standard error" rule according to "Elements of Statistical Learning", which choose the most parsimonious model whose error is no more than one standard error above the error of the best model.
Question: what is the rationale of the "one standard error" rule  ? And why not choose the model with lowest CV ?
Answer: An Introduction to Statistical Learning puts the rationale pretty succinctly on page 214:

The rationale here is that if a set of models appear to be more or less equally good, then we might as well choose the simplest model—that is, the model with the smallest number of predictors.

Note that the one-standard-error rule is recommended in cases for which the relation of cross-validated error to number of predictors is "quite flat." It also takes into account the following:

Furthermore, if we repeated the validation set approach using a different split of the data into a training set and a validation set, or if we repeated cross-validation using a different set of cross-validation folds, then the precise model with the lowest estimated test error would surely change.

So why not choose the simplest useful model in such a case? The one-standard-error rule is a rule of thumb, a way to get a reasonably simple model. I am not aware of any further basis for this choice based on first principles.
This Cross Validated question goes into a good deal more detail on this issue.
Comment: A few reasons to pick the simplest model: the fewer variables used, the less problem missing data is likely to be, the smaller the data record needed for prediction, the lower the data collection burden, the easier it may be to describe the model. None of these are hard and fast rules.
Comment: Great answer. Just trying to understand what's the difference between "using a different split of the data into a training set and a validation set" and "using a different set of cross-validation folds" ? Don't they mean the same thing, i.e. different values of $k$  in k-fold CV give different results?
Comment: A training-validiation split take the data and splits (once) into Tv.  Crossvalidation takes the data and splits into TTTTt, TTTtT, TTtTT, TtTTT and tTTTT.   Different results (from the original training-validation or cross-validation sets) will result from different random number seeds to start.


How do I get masonry to run again once twitter widgets have rendered?

Question: I am using the Masonry API and Masonry Views modules to get a view to render nicely, it works well.
I'm using oEmbed Core to render the URL provided by the user into an embedded tweet for a specific node type.  That also works fine.
When the tweet shows up in the view however, my blocks get overlapped because the twitter widget is rendering after masonry has run.  How do I rerun masonry once the tweet has fully rendered?
Answer: I went through the twitter documentation and found a way to call functions on twitter widget events:
<code>// Load the twitter widgets script
window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);

  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };

  return t;
}(document, "script", "twitter-wjs"));

// Bind an event to rerun the masonry layout when a tweet is rendered
twttr.ready(
  function (twttr) {
    twttr.events.bind(
      'rendered',
      function (event) {
        jQuery(function($) {
          $('.view-content.masonry').masonry();
        });
      }
    );
  }
);
</code>


Existe APIs de interface gráfica para Grafos no android?

Question: Procurei muito pela internet mas não achei nada correspondente em português e em inglês achei algumas coisas mas sem resolução sobre isso.
 Alguém tem algum conhecimento sobre a existência de uma API de interface gráfica para representar e manipular grafos (de nodos e arestas) no Sistema Operacional Android?
Ou alguma sugestão de alternativa? (tal api deve ser open source).
Answer: Para realizar a plotagem dos grafos no Android, você pode usar essas bibliotecas:

MPAndroidChart - Poderosa biblioteca para visualização de grafos e gráficos
AChartEngine - Biblioteca gráfica para aplicações Android
HoloGraphLibrary - Biblioteca para plotagem de gráficos / grafos
EazeGraph - Biblioteca para plotagem de gráficos / grafos
AndroidCharts - Biblioteca simples e fácil para manipular gráficos
AndroidPlot - Biblioteca para plotagem de gráficos
WilliamChart - Biblioteca felxível para gráficos com suporte a animções
HelloCharts - Biblioteca de gráficos e grafos com suporte a redimensionamento, scroll e animações
MPAndroidChart - Biblioteca poderosa para visualização de grafos e gráficos com suporte a animações e várias outras funcionalidades.

Se você quiser manipular o grafo em si, ou seja, criar,remover e editar nós e arestas, você pode usar essas bibliotecas escritas em Java. Algumas delas já fornecem recursos para plotagem dos grafos.

JGraphT
JUNG
G
yWorks
BFG
GEF
gmgraphlib
Scene Graph
JGraph

Fontes:

https://guides.codepath.com/android/Must-Have-Libraries#drawing
https://stackoverflow.com/questions/6162618/java-graph-library-for-dynamic-visualisation


Invert values in Pandas data frame

Question: is there a way I can invert values in a dataframe using Pandas? I am using data representing customers feedback. It is captured as a value from 1 to 5, 5 being the best feedback and 1 the lowest. I would like to invert it so that 1 becomes the highest score, so basically all the 5s become 1s, 4 becomes 2 and 3 stays 3. Is there a way I can achieve that? Many thanks in advance.
Comment: `df['col_name'] = 5 - df['col_name']`?
Answer: df['Feedback'] =6- df['Feedback']

Answer: The map function is used for substituting each value in a Series with another value. So, you should try:
df['col_name'] = df['col_name'].map({5:1, 4:2, ...})
Comment: Please consider explaining your answer. Answers with no explanation are usually tagged as low quality posts for review.

Invert values in Pandas data frame


Duplicated mails when send to distribution group

Question: I have at least a user that have a old problem with duplicated mails, when it receives from a distribution group.
For example, when a User 1 from the inside domain, send a mail to a Distribution Group A of the same domain, where a User 2 is, this last user will receive two mails.
The first one is the original, where it cames as expected. The second one, is the original one, forwarded with the same heather, but with the list of the distribution group:

Note: this User 2 is classified as an administrator of this server.
Server Specs:

Windows SBS 2008
Exchange 2007

UPDATE 1:
Windows SBS 2008 is installed in my smart host, who is connected with my remote mail server, where i can config through cpanel. Forwarding at cpanel, means forward to another email account and it saves a copy at original destination.
In my remote mail server i have those forwardings:
User 0 -> Group A
User 1 -> Group A
User 3 -> Group A
User 4 -> User 2
User 5 -> User 2
And in my smart host:
Group A -> User 2, User n, ...
Comment: Just to clarify, which user is the administrator and when you say the "Last user will receive two emails" do you mean that all members of the group receive 2 emails?
Comment: thanks for the response, the administrator is the User 2
Answer: Being an administrator of the server makes no difference.
The group system is intelligent, so if a user is a member of one or more groups, then they only get one copy. The only time that multiple copies are received is when the second (or more) copy is being delivered outside of the group system - ie a forward from another account.
You need to look at the membership of the group, and then where this user gets email from - another account forwarded, delegate etc. That will be the cause.
That second header in your screenshot does not look like a header I have seen generated by Exchange/Outlook - suggesting the email is going out and then coming back in again.
Comment: Thank you for the response! But it was not supposed to receive mails from the distribution group without the distribution list in that mail? So i can assume that the first mail without that list, is the one forwarded from the user.
Comment: I have indeed some forwardings from three users to one distribution group being done in my remote mail server, coming from outside of the domain, and then it goes to my smart host where i have SBS 2008. There i have that distribution group with the same three users within others, like User 2.  In my smart host i dont have any forwarding from user to user, there i just have distribution groups. (i have also updated mu thread with this info!)
Comment: This has to be caused by what you are doing with the smart host. For whatever reason it is causing the emails to be forwarded back in again.
In most instances Exchange should do all of the email handling - once something else gets involved then you can see problems like what you have seen already.
Answer: I have discovered that this is not a simple forwarding, this is a journal report, who forward mails from a certain configured user to another, with a list of all the stackholders in each mail, and it can be created or disable through:
Exchange Management Console >> Organization Configuration >> Hub Transport >> Jounaling


Why $EN < \infty $ implies $ N < \infty $?

Question: Why $EN < \infty $ implies $ N < \infty $?  (It's part of Borel-Cantelli lemma's proof).
Comment: What is $E$ and $N$? (In particular, could any of them _fail_ to be finite and if so how?)
Answer: If $\mathbb{E}[N] < \infty$, then necessarily $\mathbb{E}[N^+] < \infty$ and $\mathbb{E}[N^-] < \infty$, where $N^+(\omega): = \max\{N(\omega),0\}$ and $N^-(\omega): = \max\{-N(\omega),0\}$, the positive part and negative part of $N$ respectively.  This is because of how expectation is defined, as the sum of the expectations of the positive part and negative part.  Now, If $N$ (and thus $N^+$) took the value positive infinity on a set of positive measure $A$, then $\mathbb{E}N^+ \geq \mathbb{E}[N^+ \chi_A] = \infty$.
So since the expectation of $N$ is finite, the set where $N$ is infinite must have zero measure, or in other words, $N < \infty$ a.s.  The same argument applies to $N^-$, implying that the $N > -\infty$ a.s. as well.
Comment: It is not true in general that $N \geq \chi_A$. But, $\mathbb{E}N < \infty \Rightarrow \mathbb{E}N^+ < \infty$, and $N^+ \geq \chi_A$. Maybe you should observe that.
Comment: a.s. is almost surely, see http://en.wikipedia.org/wiki/Almost_surely for full description.
Comment: Thanks.  BTW, what does "a.s." mean?
Comment: Thank you Andre, you are right.  I have edited my answer to include this.


The finite intersection of absorbing set is absorbing

Question: I got stuck proving the finite intersection of absorbing set is absorbing. Can anyone help?
Answer: What's the picture here? Take any point and connect it to $0$. Then a set is absorbing provided a small neighborhood of $0$ on that ray intersects the set, for every point in the vector space. So this means that any two absorbing sets will always intersect a little bit on every ray, which means that their intersection will always be absorbing.
Let's make this intuition precise. Suppose $S$ and $T$ are two absorbing sets in $V$, which is an $\Bbb{R}$-vector space. Take $x\in V$. Then we know there are $r_S$ (resp. $r_T$) such that for all $a\in\Bbb{R}$ with $|a|>r_S$ (resp. $a>r_T$) we have $x\in aS$ (resp. $x\in aT$).
This means that $x/a\in S$ for all $a > r_S$ and $x/a\in T$ for all $a > r_T$. Thus $x/a\in S\cap T$ for all $a > \max\{r_S,r_T\}$. Therefore, if we let $r = \max\{r_S,r_T\}$ then we will have for all $a > r$, that $x\in a(S\cap T)$. Note that $r_S,r_T$, and thus $r$ will depend on $x$, but that's okay -- this is a challenge-response definition, where for every $x$ we have to be able to provide an $r$ such that the criterion is satisfied. But we've done so, which means we've finished the proof.


Is it possible to use Google Cloud Endpoints built in authentication with Google+ Domains API?

Question: Google Cloud Endpoints has it's own authentication process in which the backend endpoint method is simply passed a com.google.appengine.api.users.User object.
https://cloud.google.com/appengine/docs/java/endpoints/auth
The Google+ Domains API specifies its own authentication process in order to get the com.google.api.client.auth.oauth2.Credential object. This allows for the building of the com.google.api.services.plusDomains.PlusDomain object.
https://developers.google.com/+/domains/authentication/
How would you integrate these two authentication processes? This is for a web app (Java Script) with a Google App Engine (Java) backend.
In an ideal situation, I would like to be able to retrieve the users bio/profile basic info via my JS app while the user is offline.
Use Case: I have a comment thread where each comment has an author persisted in the Google Datastore as a com.google.appengine.api.users.User object. However when I render the comment thread in my JS web app I would like to show a profile picture for each author. If I could make a call from the web app to retrieve the bio for each commenter I could save the backend a lot of work. The web app would have the user object as JSON. Which includes the user ID and email.
Comment: Can you add some details on your use case? Normally you would pass the user object to an endpoint, then, when user is identified, on endpoint use a service account acting on behalf of this user.
Comment: @NikitaUchaev I have the standard Endpoints authentication set up. Passing the user object as you said. Want to get a bio for the user. What do you mean "service account acting on behalf of this user"? Can you link some code or documentation?
Comment: @NikitaUchaev I see what you mean about the question being unclear. I updated the question. Hope that helps.
Comment: Have you considered using a custom authenticator?
Answer: So, your use-case is:

your users authenticate to your app, granting the basic userinfo.profile scope needed to get the com.google.appengine.api.users.User object properly received in your endpoints API
you persist these User objects to the DB, and when you retrieve them to display the thread they commented in, you'd like to make a call to the google+ API people.get method to retrieve their avatar image URL

The solution: if your users were presented with an oauth flow that had them  grant the scope required for the google+ API call (the profile scope) in addition to the regular endpoints "userinfo.profile" scope, it should be no problem to call the Google+ API, either from the JS client or from the Java back-end, using the Google API client libraries, after going through that flow to obtain the credentials.
In order to avoid re-authenticating them each time, you should serialize and store a credentials object from the language in question, or you could even simply keep track of the refresh token for their grant and go through the low-level OAuth dance to obtain a fresh access token (you'll probably want to do the former, as it does this for you).
As noted elsewhere on the web (in several other places as well), the userid from the User object is not the same as the Google+ profile id, so be aware of that when working with the endpoints method parameter User objects. You therefore won't be able to use the userid from the User object to call people.get.
Instead, you should store the Google+ profile ID of the user at the time that they first signed-in or at least went through the oauth flow that granted the necessary Google+ scope, alongside the User object you've already been using. You'll have to use the (de)serialized credentials objects or refresh/access tokens to call the Google+ API, once you retrieve the Google+ profile id from each user's data model in your storage (whatever solution you use, from Datastore to SQL, etc.)
Comment: Thank you for mentioning that the Google+ profile ID is not the same as the user's Google account ID.


Failed to convert webm audio file to mp4 using FFMPEG

Question: I have a webm audio file , I was trying to convert it into mp4 using ffmpeg. But it is failed to create the mp4. The info about the file is as follows.
fmpeg -i 54ebe077-96fc-4ace-9a38-f13c58807322.webm -hide_banner

Input #0, matroska,webm, from '54ebe077-96fc-4ace-9a38-f13c58807322.webm':
  Metadata:
    encoder         : Lavf56.40.101
    creation_time   : 2019-10-22T11:19:12.000000Z
  Duration: 00:00:24.16, start: 0.000000, bitrate: 41 kb/s
    Stream #0:0: Video: vp8, yuv420p, 640x480, SAR 1:1 DAR 4:3, 30 fps, 30 tbr, 1k tbn, 1k tbc (default)
    Stream #0:1: Audio: opus, 48000 Hz, mono, fltp (default)
At least one output file must be specifiedffmpeg -i  54ebe077-96fc-4ace-9a38-f13c58807322.webm -qscale 0 out.mp4

I was tried to convert it using the following command
ffmpeg -i  54ebe077-96fc-4ace-9a38-f13c58807322.webm -qscale 0 out.mp4

It throws errors
[opus @ 0x56489c7f9840] LBRR frames is not implemented. Update your FFmpeg version to the newest one from Git. If the problem still occurs, it means that your file has a feature which has not been implemented.
[opus @ 0x56489c7f9840] Error decoding a SILK frame.
[opus @ 0x56489c7f9840] Error decoding an Opus frame.
Too many packets buffered for output stream 0:1.
[aac @ 0x56489c82d640] Qavg: 59180.625
[aac @ 0x56489c82d640] 2 frames left in the queue on closing
Conversion failed!

How to fix this issue? I have played the file in VLC and I can hear the sound from the source file. But failed to convert it
Answer: Your ffmpeg is too old
Update your ffmpeg:

Download an already compiled ffmpeg
Or see compile instructions at FFmpeg Wiki

This was ticket #4641: Error decoding SILK frame. The fix is newer than the most current release branch (FFmpeg 4.3 as of writing this), so you have to get a build from the git master branch (either of the links above will do), or wait for FFmpeg 4.4.
If you can't update
If you can't update your ffmpeg the old workaround is to use libopus to decode:
ffmpeg -c:a libopus -i input ...

Comment: It is not working and i ogt it working using ffmpeg -acodec libopus -i 54ebe077-96fc-4ace-9a38-f13c58807322.webm -max_muxing_queue_size 9999 -strict experimental -movflags faststart foo.mp4
Comment: No need for `-strict experimental`. What error did you get when you tried my example? "Not working" is not descriptive.


What is the convolution of a normal distribution with a gamma distribution?

Question: Is there a closed form expression for the convolution of a normal distribution (ND) with a gamma distribution (GD)? There does not seem to be a direct method of solving this convolution.
Answer: Often, convolving something with itself gives a solution even when the more direct convolution of two different distributions has no obvious answer. To  convolve a ND and a GD, I used Pearson III and convolved two Pearson III distributions with themselves after reparameterization of those Pearson III distributions to be ND and GD using Mathematica.
$$\text{PDF}[\text{PearsonDistribution}[3,a,b,x,y,z],t]=\begin{array}{cc}
 &
\begin{cases}
 \dfrac{\sqrt{\frac{a}{z}} e^{-\dfrac{(a t+b)^2}{2 a z}}}{\sqrt{2 \pi }} & y=0\land a z>0 \\
 \dfrac{a \ e^{-\dfrac{a \left(t+\dfrac{z}{y}\right)}{y}} \left(\dfrac{a \left(t+\dfrac{z}{y}\right)}{y}\right)^{\dfrac{a z}{y^2}-\dfrac{b}{y}}}{y \Gamma \left(-\dfrac{b}{y}+\dfrac{a z}{y^2}+1\right)} & y^2>0\land a (t y+z)>0 \\
\end{cases}
 \\
\end{array}$$
Then ND from Pearson III is $$\text{PDF}\left[\text{PearsonDistribution}\left[3,1,-\mu ,x,0,\sigma ^2\right],t\right]=\dfrac{ e^{-\dfrac{(t-\mu )^2}{2 \sigma ^2}}}{\sigma\sqrt{2 \pi }}\,,
 \\
$$
And GD from Pearson III is $$\text{PDF}\left[\text{PearsonDistribution}\left[3,\beta ,1,x,1,\frac{\alpha }{\beta }\right],t-\frac{\alpha }{\beta }\right]=\begin{array}{cc}
 &
\begin{cases}
 \dfrac{\beta  e^{-\beta \ t} (\beta \ t)^{\alpha -1}}{\Gamma (\alpha )} & \beta  t>0 \\
 0 & \text{Otherwise} \\
\end{cases}
 \\
\end{array}\,.$$
Then ND*GD is $$f(s)=\text{Convolve}\left[\text{PDF}\left[\text{PearsonDistribution}\left[3,\beta ,1,x,1,\frac{\alpha }{\beta }\right],t-\frac{\alpha }{\beta }\right],\text{PDF}\left[\text{PearsonDistribution}\left[3,1,-\mu ,x,0,\sigma ^2\right],t\right],t,s\right]=2^{-\frac{\alpha }{2}} \beta ^{\alpha } \sigma ^{\alpha -2} e^{-\frac{(s-\mu )^2}{2 \sigma ^2}} \left(\frac{\sigma  \, _1F_1\left(\frac{\alpha }{2};\frac{1}{2};\frac{\left(\beta  \sigma ^2-s+\mu \right)^2}{2 \sigma ^2}\right)}{\sqrt{2} \Gamma \left(\frac{\alpha +1}{2}\right)}+\frac{\left(-\beta  \sigma ^2-\mu +s\right) \, _1F_1\left(\frac{\alpha +1}{2};\frac{3}{2};\frac{\left(\beta  \sigma ^2-s+\mu \right)^2}{2 \sigma ^2}\right)}{\Gamma \left(\frac{\alpha }{2}\right)}\right)\,.$$ That is, after a lot of simplifying. Note, $_1F_1(a;b;z)$ is the confluent hypergeometric function of the first kind.
Answer: For integral shape parameters there is a relatively simple form.
Without any loss of generality, we may suppose the Normal distribution is a standard Normal, because any shifting of it translates directly to a shift of the convolution; and we may incorporate all scale factors in the Gamma distribution (and then effect a rescaling at the end if needed).  This means we may limit the analysis to the standard Normal distribution $\Phi$ with density
$$\phi(z) = \frac{1}{\sqrt{2\pi}}\exp\left(-z^2/2\right)$$
and Gamma densities that are zero on negative values and otherwise are given by
$$\gamma_{a,\sigma}(t) = \frac{1}{\Gamma(a)\sigma^a} t^{a-1}\exp\left(-t/\sigma\right).$$
The convolution can be computed as
$$f(z; a, \sigma) = \left(\phi \star \gamma_{a,\sigma}\right)(z) = \frac{1}{\sqrt{2\pi}\Gamma(a)\sigma^a}\int_0^\infty  t^{a-1}\exp\left(-t/\sigma\right)\exp\left(-(z-t)^2/2\right)\,\mathrm{d}t.$$
The instances with integral $a$ promise to yield simple expressions.  Let's begin at $a=1,$ for which the calculation yields to the usual expedient of completing the square:
$$\begin{aligned}
f(z;1,\sigma) &= \frac{1}{\sqrt{2\pi}\sigma} \int_0^\infty \exp\left(-t/\sigma - (z-t)^2/2\right)\,\mathrm{d}t\\
&= \frac{\exp\left(-\left(z-\frac{1}{2\sigma}\right)/\sigma\right)}{\sqrt{2\pi}\sigma}\int_0^\infty \exp\left(-(t - (1/\sigma-z))^2\right)/2)\,\mathrm{d}t\\
&= \frac{\exp\left(-\left(z-\frac{1}{2\sigma}\right)/\sigma\right)}{\sqrt{2\pi}\sigma}\int_{-\infty}^{z-1/\sigma} \exp\left(-t^2/2\right)\,\mathrm{d}t\\
&=\exp\left(-\left(z-\frac{1}{2\sigma}\right)/\sigma\right)\Phi\left(z-1/\sigma\right).
\end{aligned}$$
That, at least, can be considered a "closed form."  We can exploit it to find other convolution densities.  Returning to the convolution integral, observe
$$\begin{aligned}
f^\prime(z;a,\sigma) &= \frac{1}{\sqrt{2\pi}\Gamma(a)\sigma^a}\int_0^\infty  \frac{\mathrm d}{\mathrm{d}z} t^{a-1}\exp\left(-t/\sigma\right)\exp\left(-(z-t)^2/2\right)\,\mathrm{d}t\\
&= \frac{1}{\sqrt{2\pi}\Gamma(a)\sigma^a}\int_0^\infty  t^{a-1}\exp\left(-t/\sigma\right)(t-z)\exp\left(-(z-t)^2/2\right)\,\mathrm{d}t\\
&= \frac{1}{\sqrt{2\pi}\Gamma(a)\sigma^a}\left[\int_0^\infty  t^{a}e^\left(-t/\sigma\right)e^\left(-(z-t)^2/2\right)\,\mathrm{d}t - z\int_0^\infty  t^{a-1}e^\left(-t/\sigma\right)e^\left(-(z-t)^2/2\right)\,\mathrm{d}t\right]\\
&= \frac{\sigma\Gamma(a+1)}{\Gamma(a)} f(z;a+1,\sigma) - z f(z;a,\sigma)\\
&= \sigma a f(z;a+1,\sigma) - z f(z;a,\sigma).
\end{aligned}$$
Solving for $f(z;a+1,\sigma)$ and writing $D=\mathrm{d}/\mathrm{d}z$ for the differential operator produces the fundamental recurrence
$$f(z;a+1,\sigma) = \frac{f^\prime(z;a,\sigma) + z f(z;a,\sigma)}{\sigma a} = \frac{D+z}{\sigma a} f(z;a,\sigma)$$
Repeating this $\lfloor a\rfloor - 1$ times gives
$$\begin{aligned}
f(z;a,\sigma) &= \frac{D+z}{\sigma (a-1)}\frac{D+z}{\sigma (a-2)}\cdots\frac{D+z}{\sigma(a-\lfloor a\rfloor+1)} f(z;a-\lfloor a\rfloor+1,\sigma) \\
&= \frac{\Gamma(a-\lfloor a \rfloor + 1)}{\sigma^{\lfloor a\rfloor-1}\Gamma(a)} (D+z)^{\lfloor a\rfloor-1} f(z;a-\lfloor a\rfloor+1,\sigma).
\end{aligned}$$
For integral $a$ it simplifes further to

$$f(z;a,\sigma) = \frac{1}{\sigma^{a-1}\Gamma(a)} (D+z)^{a-1} f(z;1,\sigma).$$

Just to see the patterns, let $\sigma=1,$ drop the "$z-1$" arguments from $\Phi$ and $\phi$ (reducing the visual clutter in the formulas) and use $\phi^\prime(z-1) = -(z-1) \phi(z-1)$ to compute
$$\begin{aligned}
f(z;1,1) &= e^{1/2-z} \Phi\\
f^\prime(z;1,1) &= e^{1/2-z}\left(-\Phi + \phi\right)\\
f(z;2,1) &= \frac{1}{1}\left(f^\prime(z;1,1) + z f(z;1,1)\right) = e^{1/2-z}\left((z-1)\Phi + \phi\right)\\
f^\prime(z;2,1) &= e^{1/2-z}\left(-(z-1)\Phi-\phi + \Phi + (z-1)\phi - (z-1)\phi\right)\\
&= e^{1/2-z}\left((2-z)\Phi - \phi\right)\\
f(z;3,1) &= \frac{1}{2}\left(f^\prime(z;2,1) + z f(z;2,1)\right) \\
&= \frac{1}{2}e^{1/2-z}\left((z^2-2z+2)\Phi + (z-1)\phi\right)\\
etc.
\end{aligned}$$
Generally, the form of these densities is
$$f(z;a,1) = e^{(1/(2\sigma)-z)/\sigma}\left[P(z;a,\sigma)\Phi(z-1/\sigma) + Q(z;a,\sigma)\phi(z-1/\sigma)\right]$$
where $P$ and $Q$ are polynomials in $z.$  The basic recurrence (for $\sigma=1$) translates to
$$\begin{aligned}
P(z;a+1) &= \left[(z-1)P(z;a) + P^\prime(z;a)\right]/a\\
Q(z;a+1) &= \left[P(z;a) + Q^\prime(z;a)\right]/a
\end{aligned}.$$
It is now immediate that

For positive integral $a,$ the density $f(z;a,\sigma)$ is $\exp(1/(2\sigma) - z)/\sigma)$ times a polynomial linear combination of $\Phi(z-1)$ and $\phi(z-1).$ The degree of $P$ is $a-1$ and the degree of $Q$ is $a-2$ (when $a\ge 2$).

Here are histograms of simulated values for $a=1,3,10$ overplotted with the graphs of $f(z;a,1)$ to demonstrate the agreement.

By comparing these to all the Wikipedia listings of continuous distributions supported on the real line we can establish that they are not among those lists.  Most of this is obvious, with the exception perhaps of the Pearson system of distributions.  But these can be ruled out since (by definition) the logarithmic derivative of a Pearson density is a rational function of its argument with at most one zero and two (complex) poles.  The recurrence relation for $f(z;a,\sigma)$ readily demonstrates that no such relationship holds.
Comment: +1 Nice work. I cannot follow everything exactly, but get the general idea. There are a lot of convolutions that are not listed on Wikipedia, for example see the [gamma-Pareto (type I) convolution](https://doi.org/10.1007/s10928-021-09779-4) and the other ones referenced in that paper.


Why my samba printer is not visible (after boot) until i restart smb?

Question: I've an old hp1100 and ubuntu 9.10 and now upgraded to lucid prerelease. I can't see my printer on network (using smb://mycomputer on nautilus or \mycomputr from xp).
As long as i will not restart smbd (on lucid: sudo restart smbd) my printer is not visible as network share. All file shares are always visible. My printer is visible and working after smbd restart
Any clue what might cause this ?
EDITED !SOLUTION!
Easiest way to workaround this (at least in ubuntu 11.04 where this issue is still not solved) is to edit upstart smbd file located at:
/etc/init/smbd.conf

and replace line:
start on (local-filesystems and net-device-up)

with:
start on (local-filesystems and net-device-up and started cups)

Answer: Most likely is that samba is coming up before cups, I suggest you report a bug to launchpad.
Comment: seems bug is already filled at: https://bugs.launchpad.net/ubuntu/+source/cups/+bug/494141
anyway thanks :)
Answer: I had the exact same problem this morning (Ubuntu 11.04 - You would think they would fix this by now...).  I determined the problem after some Googling.  Yes, Samba is starting before CUPS, which causes Samba to not display the printers until you manually do 'sudo reload smbd'.
I modified /etc/init/cups.conf, not /etc/init/smbd.conf (basically adding "or starting smbd" to the end of the line)
start on (filesystem
    and (started dbus or runlevel [2345])
    and stopped udevtrigger) or starting smbd

I like this solution because it works for people with only CUPS installed or people with only Samba installed (I think).  Hope this helps someone out there...
Answer: Better is not to tinker with the installed upstart files, but to add to /etc/rc.local
service cups restart
service smbd restart

But you would indeed think they would have fixed this by now -- but no, I installed Xubuntu for a neighbour last night and the same thing happened. It's nearly as bad as the old error of starting network-dependent services on a laptop (where there might not be a connection at any given time) and then having a 10-minute timeout...


How can I show label/title for marker permanently in Google Maps V3?

Question: I want to display Markers on Google map with title displayed under them as shown in picture:

Now this I read was possible in v2 using ELabel but is deprecated in v3. Is there any possible way to show some text under icons of markers in Google Maps V3?
Answer: Since at least October 2016, the official API provides a way to add permanently visible labels that are longer than one letter. See this reply by a Google project member.
var m = new google.maps.Marker({
  position: new google.maps.LatLng(lat, lng),
  label: 'Hello world',
});

By default, the result looks like:

Pretty unreadable. Fortunately the API also allows a MarkerLabel object instead of a plain string:
var m = new google.maps.Marker({
  position: new google.maps.LatLng(lat, lng),
  label: {
    color: 'white',
    fontWeight: 'bold',
    text: 'Hello world',
  },
});

Snippet above yields the following result:

However, the original question asked if the label could be located below the marker. The MarkerLabel docs mention this is possible with a custom icon and labelOrigin property. If we want to use the default icon, one is available at GitHub. Let us add the icon object:
var m = new google.maps.Marker({
  position: new google.maps.LatLng(lat, lng),
  label: {
    color: 'white',
    fontWeight: 'bold',
    text: 'Hello world',
  },
  icon: {
    labelOrigin: new google.maps.Point(11, 50),
    url: 'default_marker.png',
    size: new google.maps.Size(22, 40),
    origin: new google.maps.Point(0, 0),
    anchor: new google.maps.Point(11, 40),
  },
});

This results:

Pretty good! However, this whole approach has a shortcoming that the box in the original question does not have: readability with each map type. If the map type is changed from the satellite to the default the resulting label is hard to read:

An easy but not perfect way to avoid the low contrast in the both types is to set color: 'gray':

However, the gray color fails near urban areas. A better option would be to apply text-shadow CSS property to draw black linings for the white text. However, I cannot find a way to apply the property to the labels because few DOM elements created by Google Maps define a class:

The best option I came up to is to detect changes in the map type and update label color for each marker:
map.addListener('maptypeid_changed', function () {
  var typeToColor, type, color, k, label;

  typeToColor = {
    'terrain': 'black',
    'roadmap': 'black',
    'hybrid': 'white',
    'satellite': 'white',
  };

  type = map.getMapTypeId();
  color = typeToColor[type];

  for (k in markers) {
    if (markers.hasOwnProperty(k)) {
      label = markers[k].getLabel();
      label.color = color;
      markers[k].setLabel(label);
    }
  }
});

However, even this would fail on snowy or cloudy satellite imagery. I think it is still good enough in most of the cases. Nevertheless, it is nice to have the ability to display visible labels with the official API, without any plugins :)
Comment: One of the best answers I've seen, structured, descriptive, relevent screenshots and good solution. If u could give 2 up votes i would
Answer: I found the solution in an other post which worked perfectly for me.
Add numbering label to google map marker
Answer: You can't! But there's another part of maps API you can use to have permanently displayed text attached to your markers (without requiring any third party component), it's called infoWindow. Have a look at this for sample code & see it in action: https://developers.google.com/maps/documentation/javascript/examples/event-closure
If you dare using third party code, then here's something that is closer from the look & feel you want: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/docs/examples.html
Comment: As web developers, aren't we always using 3rd party code? No one's programming html forms with Assembly ;)
Comment: This was perfect, ty! We shouldn't need to pull in extra garbage when the api already provides it.
Answer: I use the following:
MarkerWithLabel.js
 ( the image is just a flag.png file)
Using javascript in my X.html document
it looks something like this....

Read up on license info for google maps API here : https://www.google.com/intx/en_uk/work/mapsearth/products/mapsapi.html
Comment: If you download the markerwithlabel.js and put it permanently on your own server and link to that path, it wont change unless you do so. And the google api is gna be reverse compatibel. So I wouldn't expect problems.
Answer: You should be able to use the same principle as in this example. Instead of listening to the mouse events you should create a new custom control for each marker and then position it below the marker. Hope it works out.
Comment: The example is a dead link


Central-limit theorem via sample size or sampling magnitude?

Question: I have a small application of the central limit theorem:

"Take a sample of 40 exponentially distributed random numbers and
  calculate their mean. Repeat 1000 times, record each measured mean and
  calculate the mean of those 1000 means."

Here's my Rcode:
nsim   = 1000
nsamp  = 40
lambda = 0.2

clt <- data.frame(m=numeric(nsim), s=numeric(nsim))

for(s in 1:nsim)
{
    clt$v[s] <- mean(rexp(nsamp, lambda))
    clt$s[s] <- sd(rexp(nsamp, lambda))
}

cat(mean(clt$v), "\n")
    cat(mean(clt$s), "\n")

I can observe that with increasing number of simulations (i.e. increasing the repetitions of the sampling event), the mean of means and mean of variance more closely agree with the theoretical values (1/lambda).
What I wonder is, does the Central-limit theorem only depend on the number of sampling events (1000) or is it just as much dependent on sufficiently large sample size (i.e. 40 in this example)?
Comment: What, in you own words, does the CLT actually say?  You might enjoy reading some of our [higher-voted threads on the CLT](http://stats.stackexchange.com/search?tab=votes&q=Central%20limit%20theorem).
Comment: I don't see the Central Limit Theorem here, only the Law of Large Numbers.
Answer: The CLT is generally considered a theoretical distribution. We don't actually generate 1000 (or 10,000 or 100,000) samples from it. Rather, we imagine what would happen if we were to replicate this experiment 1000 (or, technically, infinite) times.
The R code you post caps it at 1000, probably because by 1000 samples it will demonstrate the properties of the CLT. But, again, the CLT really says what would happen if you repeated it an infinite number of times.
So, to your question:

does the Central-limit theorem only depend on the number of sampling events (1000) or is it just as much dependent on sufficiently large sample size (i.e. 40 in this example)?

It depends on both (kind of). The number of sampling events actually is infinite (though the CLT properties hold with smaller distributions), and as the sample size increases, the more normal (and smaller the variance) the distribution of means becomes.
Comment: "*The CLT is generally considered a theoretical distribution.*" The CLT is not a theoretical distribution, but the normal distribution is ;)
Comment: "*the CLT really says what would happen if you repeated it an infinite number of times.*" That's a nice intuitive short-hand, popular in stats pedagogy, but that's not *really* how it works in terms of the pure math. Lookup *$(\epsilon,\delta)$-definition of a limit*.
Answer: The central limit theorem states that you should take samples of sufficiently large size (40 in your example), but it does not provide a limit on the minimum number of such samples, i.e., the statement holds regardless of the number of samples. See point #1 in this answer.
Comment: CLT nowhere says "sufficiently large sample", it says $n \to \infty$. See the second point of the answer you refer to.
Answer: It does not matter for law of large numbers

I observe that with increasing number of simulations (i.e. increasing the repetitions of the sampling event), the mean of means and mean of variance more closely agree with the theoretical values (1/lambda).

Your application and observation of the behaviour of the mean relates more to the law of large numbers than the central limit theorem.
For the mean of means, it is irrelevant how you create the average. If you average all your samples or first average groups does not matter, because the end result is the same.
Example
Say your sample is $1,2,3,4$ then you could group it and compute average of group averages, but the result is the same (if the group's sizes are equal).
$$\frac{(2+3)/2 + (4+1)/2}{2} = \frac{2+3+4+1}{4}$$

Also note that the mean of the estimated standard deviations may approach some value for larger nsim, but that doesn't need to relate to the simulations following approximately a normal distribution.
The behaviour that this value approaches some constant is due to the law of large numbers.
It matters for central limit theorem
The CLT relates to the distribution of a sample average. When you standardize this based on the population mean and deviation, then the final result approaches a Normal distribution under the right circumstances (independence, finite variance, etc.).
If your question would have been about the central limit theorem or about approximations with a normal distribution then the size of the samples matters (not the number of repetitions, although this may have an effect when you make a histogram).
There is already a question about this: Why does increasing the sample size of coin flips not improve the normal curve approximation?
It deals with the issue of the two different sizes (the sample size and the repetitions size), as well as with problems of drawing a histogram.
Comment: The sample size certainly does relate to the Law of Large Numbers. I think what you mean is that the _expected value_ of the sample does not rely on a large sample?
Comment: @CliffAB yes, in the first part I am talking about the application. The mean of means is computed in that code and the result of that computation doesn't change when the values of `nsim` and `nsamp` change while keeping their product the same.


Would it be possible for a kicker from a "non-traditional" background to be drafted by an NFL team?

Question: Almost all football players are drafted out of college, rather than high school, because the extra "seasoning" in college makes them league ready, or nearly so (this is not true in baseball).
But suppose there was a high school kicker, who could routinely kick field goals from the 50-year line or further? Would a major league team consider drafting him or her for that particular skill without the further practice in college on the theory that "kicking" ability is basically independent of what else happens on the field (there is normally no contact for the kicker.) Or are anti-kick defenses much better in the "pros" than in high school? According to NFL rules, this could take place only several years after the high school graduation, unless this person applied for, and was granted "special eligibility," so maybe this person maintains the skill in junior college or abroad.
And most people who are, say, 5' 5" and 170 pounds (like the Houston Astros' Jose Altuve) would not be considered "playable" on an NFL football field, particularly if female. But could "kicker" be an exception to this rule?
Comment: According to the [draft eligibility rules](https://www.nflregionalcombines.com/Docs/Eligibility%20Rules.pdf), four full NFL seasons must pass after a player's high school graduation to be eligible for the draft. This would nix any consideration of drafting any football player out of high school, kicker or otherwise...
Comment: @edmastermind29 - not sure where you got that link but I know that juniors or redshirt sophomores (Earl Thomas out of Texas) are eligible.  The rule has been 3 years for a long time but doesn't seem reflected in that doc.
Comment: @edmastermind29: OK, reworded the question to incorporate your comment. So maybe the answer is that no high school "paragon" that didn't go to college would have been "remembered," or had a chance to try out. Unless this person was also an academic whiz that somehow graduated college a year or two after high school.
Answer: Here are some examples of players that came from a "non-traditional" background to play in the NFL.
There are examples of players that didn't play college football, but played another sports such as Antonio Gates who played basketball in college.  Julius Thomas played only one year of college football after finishing his college basketball career.
There are also examples of players that played other sports such as rugby. Daniel Adongo played rugby before coming to the NFL.  Jordan Hayne is a top level rugby player that is trying to make it in the NFL.
Lawrence Okoye was a track and field athlete for Great Britain before entering the NFL.
As far as kickers, some of them played soccer before turning to football in their college careers or late in high school such as Steven Hauschka.
Comment: This is a good answer with good examples.  There are many rugby players worldwide being scouted.  I would assume with the level of athlete in top tier rugby that 20% of rugby players would be able to handle NFL.  Certainly a lot of teams are looking at rugby for cheap punters.
Answer: Many punters originated in Australian Rules Football, or even soccer.  Sav Rocca for example came to the States after a successful Aussie Rules career, at 33.  Other Aussie Rules players are listed in this article, including Ben Graham, Darren Bennet, and others.  This generally yields punters, not placekickers.
Havard Rugland ("Kickalicious"), a Norwegian adult (28 y.o. at the time), tried out for the Lions at placekicker in 2014 after a viral Youtube video.  He didn't make the team, but performed fairly well in preseason.
As pointed out by Ed, NFL Rules regarding draft eligibility prevent the specific concept in the question (a kicker coming out earlier than other players) from being implemented.  I'd also note that kickers and punters are not very well compensated compared to other players (often near minimum salaries - still nice chunk of change, but not world-moving money amounts) and are at a reduced risk of injury compared to other players, thus suggesting that they likely would be better off going to college and getting a degree rather than coming out early (simply because they could easily fail out, and need a backup plan).
Additionally, kickers and punters are not typically drafted highly - Sebastian Janikowski was one of four placekickers drafted in the first round, after all, and he was an incredible phenom in college.  The odds of a team being willing to take a risk on an 18 or 19 year old kicker seems low, particularly when most high school teams don't even kick very much.
Answer: Michael Weinreb wrote a great article for Grantland.com this fall about Scott Harding, who he calls the "most interesting man in college football." Harding has a background in Australian Rules Football and plays for Hawaii as both a punter and a wide receiver. There's no saying whether he'll be drafted by an NFL team this year (he's old for a rookie) but someone like him could definitely be.


Probability of a sum of two random variables

Question: I was reading a probability course, i have difficulties to understand one line of a proof.
X1's CDF is F(We don't know his law).
U1 follows an Uniform distribution U[0,t].
$ P(U_{1} + X_{1} \geq t) = \frac{1}{t} \int_{0}^{t} P(U_{1} + X_{1} \geq t | U_{1} = s)ds = \frac{1}{t} \int_{0}^{t} (1-F(u))du. $
Any ideas of how we obtain $\frac{1}{t} \int_{0}^{t} (1-F(u))du$ in the end?
Thanks in advance!
Comment: $$P(U_{1} + X_{1} \geq t | U_{1} = s)=P(s+ X_{1} \geq t | U_{1} = s)=P(X_1\geq t-s)=1-F((t-s)^-)$$ Now, integrate and use the change of variable $u=t-s$.
Comment: For the part $ P(U_{1} + X_{1} \geq t) = \frac{1}{t} \int_{0}^{t} P(U_{1} + X_{1} \geq t | U_{1} = s)ds $ Are we using the fact that $ P(U_{1} + X_{1} \geq t) = P(U_{1} + X_{1} \geq t | U_{1} = s) * P(U_{1} \geq s ) $ ?
Comment: @LionheartA. It is not true that $$\mathbb P(U_1+X_1\geqslant t)=\mathbb P(U_1+X_1\geqslant t\mid U_1=s)\cdot\mathbb P(U_1\geqslant s).$$
Comment: Lionheart: In the identity you suggest, what would be $s$ in the RHS? Note that the LHS does not depend on $s$.
Comment: @ Lionheart Please do not omit independence assumptions from your statements. The distribution of the sum of two random variable cannot be determined by their individual distributions in general.
Answer: By conditioning on $U_1$ we compute
\begin{align}
\mathbb P(U_1+X_1\geqslant t) &= \int_{\mathbb R} \mathbb P(U_1+X_1\geqslant t\mid U_1=s)f_{U_1}(s)\ \mathsf ds\\
&= \int_0^t\frac1t  \mathbb P(U_1+X_1\geqslant t\mid U_1=s)\ \mathsf ds\\
&= \frac1t\int_0^t \mathbb P(X_1\geqslant t-s)\ \mathsf ds\\
&= \frac1t \int_0^t \mathbb P(X_1\geqslant u)\ \mathsf du\\
&= \frac1t \int_0^t \left(1-\lim_{v\to u^-}F(v)\right)\ \mathsf du.
\end{align}
Note that $X_1$ was not assumed to be a continuous random variable, so $F$ need not be continuous - hence the use of the left limit of $F$.


Clearing stdout errors from google test ones

Question: Is there any way (aside from stdout redirection) to avoid my code's error and warning messages to be sent to stdout when using google tests?
I'd like to just get the tear-down and output from gtest instead of having my stdout log trashed with my program's manually generated warnings and exceptions that I need to test.
Answer: Assuming all your tests use fixtures, and all your output is <iostream>-based, you could do the following:
using namespace std;

class SomeTest : public testing::Test {
protected:
    virtual void setUp() {
        storedStreambuf_ = cout.rdbuf();
        cout.rdbuf(nullptr);
    }

    virtual void tearDown() {
        cout.rdbuf(storedStreambuf_);
    }
private:
    streambuf* storedStreambuf_;
};

This will suppress all output via cout during your test's run, it can be done the same way for cerr and clog.
In order to keep this DRY, you could write a common base class inheriting from testing::Test, and make all your fixtures based on that.
Comment: thanks, but I wrote "aside from stdout redirection", I wanted to know if there's any way to do it from gtest
Comment: Well I assumed you were only referring to "external" redirection via shell - my bad.
Comment: Thanks for posting this, it's a useful snippet anyway. +1


Retrieve selected option from autocomplete suggestions in textbox

Question: I have a textbox which has autocomplete enabled. Now, I want to retrieve selected option in the textbox from autocomplete suggestions and push it into another textbox. How can I code it in typescript? Is there any method for it?
Below is code for textbox having autocomplete suggestions :

    Primary Contact
    <input type="text" placeholder="Enter" matInput [formControl]="myControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let option of options" [value]="option">{{option}}</mat-option>
        </mat-autocomplete>
    </input>

Answer: mat-autocomplete has different events and in this case you are looking for:

@Output()
  optionSelected: EventEmitter<MatAutocompleteSelectedEvent>

So do:
<mat-autocomplete ... (optionSelected)="doSomething($event.option.value)">

With that you can assign the data you get in doSomething(), or do whatever you need to do.
STACKBLITZ
Answer: Use ngModel binding to myControl.

    Primary Contact
    <input type="text" placeholder="Enter" matInput [formControl]="myControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let option of options" [value]="option">{{option}}</mat-option>
        </mat-autocomplete>
    </input>

<input type="text" placeholder="displayTextbox" [(ngModel)]="myControl.value" >


How to use non positive definite covariance matrix in multivariate Gaussian distribution

Question: First of all sorry but I am a little bit of a newbie to advanced stats hence why my question may sound silly.
I am trying to perform a classification task where I assume that my data is generated by a multivariate Gaussian distribution. For that purpose I estimate the covariance matrices from my sample data, but for some of the variables I am getting a non positive definite matrix. Could anyone provide me with a sound explanation to this (I understand I have some non linearly independent variables in my data probably?) and maybe a workaround so I can proceed?
Comment: Could you explain what you mean by "proceed"?  What exactly is the matter with obtaining a singular covariance matrix?
Comment: Any data generated by *any* distribution--including Gaussians--only need have a positive *semidefinite* covariance.  You definitely can use your estimate to compute probabilities.  After all, your covariance estimate (along with an estimated multivariate mean) completely determines the distribution!
Comment: Hi @whuber, in order to "proceed" with my classification task I need to estimate probabilities that depend on these estimated covariance matrices. What I mean is I am using a multivariate Gaussian to calculate the probabilities of an observation given each class and then just using the argmax of that to classify, hence why I need those covariance matrices to work for the probability density function... Any idea how I could work around my data to avoid singular covariance matrices?
Comment: It's unclear how the singularity of a covariance matrix could prevent you from estimating a probability.
Comment: Any data generated by a multivariate Gaussian function must have a positive definite covariance matrix. I am reversing that, and estimating the covariance matrices from my data set, having as a starting point the assumption that my data is Gaussian. If my covariance matrix is not positive definite, I cannot use it to calculate probabilities with a multivariate Gaussian. But maybe I am missing something in this approach...?
Comment: Ok then maybe the problem is I am using native matlab functions to determine the pdf value at point x, but the truth is when I apply the Cholesky covariance decomposition (`cholcov` in Matlab) I get the result that my matrix has at least one negative eigenvalue... Should I approach this the hard coded way and ditch the prebuilt functions? BTW thanks a lot for your help @whuber, I needed this discussion to move forward!
Comment: The value of the PDF is not a probability--and therein lies your difficulty.  The approaches described in http://stats.stackexchange.com/questions/159313 and its duplicate might point you in a good direction.  The negative eigenvalue arises from floating point roundoff error, so you will want to deal with that, too.
Comment: I am aware of that (PDF vs. probability), but I need the pdf value to make my estimates. Thanks again for the help, I will check out the link and the roundoff error (which I believe may be the source of my problem here now)!
Answer: You might have a singular multivariate normal distribution. See Multivariate normal with singular covariance. Such a singular distribution do not have a density (in the full space ... ) Can a multivariate distribution with a singular covariance matrix have a density function?
But we can still work with it, for instance using the Moore-Penrose generalized inverse of the covariance matrix.
But, maybe the software you are using do not do so.  If you tell us with more details what you want to do, we can tell you ...


Dúvida sobre ContainsIgnoreCase em um textBox

Question: O problema está na seguinte descrição :

Erro  CS1061
"string" não contém uma definição para "ContainsIgnoreCase" e não foi
  possível encontrar nenhum método de extensão "ContainsIgnoreCase" que
  aceite um primeiro argumento do tipo "string" (há uma diretiva de uso
  ou referência de assembly ausente?)

Criei uma extension la no começo em um public static, mas não adiantou..
O que mais eu posso fazer?
Erro acontece no [Passo 2.1]
namespace MyMethod
{
    public static class MyExtensions
    {
        public static bool ContainsIgnoreCase(this string source, string search)
        {

           return source.IndexOf(search, StringComparison.CurrentCultureIgnoreCase) >= 0;

        }
    }
}

Uso
private void txtBuscarJogo_TextChanged(object sender, EventArgs
{
    var controles = _todosBotoes.Where(btnArcheAge => (btnArcheAge.Tag as String ??    btnArcheAge.Text).ContainsIgnoreCase(txtBuscarJogo.Text)).ToArray();
    //Passo 2.2
    mainPanel.Controls.Clear();
    //Passo 2.3
    mainPanel.Controls.AddRange(controles);
}

Comment: Também cuide a formatação do código, quanto mais difícil de ler, menos gente disposta a ajudar.
Comment: Não use imagens, cole o texto da mensagem de erro.
Answer: Só falta incluir o namespace na classe do Form. Aliás, o nome do namespace não está bom, tente colocar algo mais descritivo, como MyExtensionsMethods.
// Outros using
using MyMethod;

namespace SeuNamespace
{
    public partial class Form1 { }
}

Comment: Peça pro seu amigo embasar o que ele disse. Informação sem embasamento é opinião ou achismo e estes dois nada valem =D
Comment: Consegui galera !! ERA TÃO SIMPLES... era só colocar aquele namespace la no final do código... pois o form tem que vir primeiro de tudo. Muito obrigado jbueno e compania :)
Comment: caraca, tava sem erro nenhum quando inclui o mymethod, dei start pra testar, e meu programa todo deu erro ! :O, não sei se esbarrei em alguma tecla e apaguei alguma linha, mas meu form nem aparece mais. ERRO :  A classe Form1 pode ser criada, mas não é a primeira classe do arquivo. O Visual Studio requer que os designers usem a primeira classe do arquivo. Mova o código da classe de forma que ela seja a primeira classe do arquivo, e tente carregar o designer novamente.
Comment: Eu queria realmente entender aonde você queria chegar até concordo que o nome poderia ser melhor (poderia) até porque esse `namespace` deveria ter dois nomes separados por `.` sendo muito utilizado assim. acaba isso sendo também opinativo ...
Comment: É, eu acabei escrevendo superficialmente primeiro, mas dps dei uma melhorada.
Comment: @DárioSabaini Não faço ideia do que você fez. Tente um Ctrl + z
Comment: http://prntscr.com/f5lukh parece que eu apaguei algo, ou coloquei algo na ordem errada... mas não faço ideia do que seja
Comment: @DárioSabaini tem muita coisa nesse projeto?
Comment: @DárioSabaini O using precisa estar **antes da declaração da classe**
Comment: Pedi ajuda de um amigo ele disse que normalmente não é bom ter 2 namespace em um projeto. provavelmente foi onde eu to atrapalhado. coloquei o using MyMethod no começo mas mesmo assim não deu certo. vou continuar tentando
Comment: @DárioSabaini fala pro seu amigo que ele ta muito enganado, o que aconteceu com você é outro problema, imagine você pensar assim adicionando uma novo pacote no seu sistema, que tem um `namespace` diferente, informação inválida ...
Comment: @DárioSabaini Tem algo errado. O `using` não precisa estar no final do código. Fora isso, a questão está resolvida? Você precisa de algo mais?


Mapear duas vezes a mesma entidade

Question: Estou tentando mapear duas vezes a mesma entidade em outra
public class Conveniado
{
    public int Id { get; set; }

    public string Nome { get; set; }

    [InverseProperty(nameof(ProcedimentoAgregado.ConveniadoDe))]
    public virtual ICollection<ProcedimentoAgregado> ProcedimentoAgregadoConveniadosDe { get; set; }

    [InverseProperty(nameof(ProcedimentoAgregado.ConveniadoPara))]
    public virtual ICollection<ProcedimentoAgregado> ProcedimentoAgregadoConveniadosPara { get; set; }
}

public class Procedimento
{
    public int Id { get; set; }

    public string Descricao { get; set; }

    [InverseProperty(nameof(ProcedimentoAgregado.ProcedimentoDe))]
    public virtual ICollection<ProcedimentoAgregado> ProcedimentoAgregadoProcedimentosDe { get; set; }

    [InverseProperty(nameof(ProcedimentoAgregado.ProcedimentoPara))]
    public virtual ICollection<ProcedimentoAgregado> ProcedimentoAgregadoProcedimentosPara { get; set; }
}

public class ProcedimentoAgregado
{
    [Key]
    public Guid ProcedimentoAgregadoId { get; set; }

    [Display(Name = "Conveniado de")]
    public int ConveniadoDeId { get; set; }

    [Display(Name = "Procedimento de")]
    public int ProcedimentoDeId { get; set; }

    [Display(Name = "Conveniado para")]
    public int ConveniadoParaId { get; set; }

    [Display(Name = "Procedimento para")]
    public int ProcedimentoParaId { get; set; }

    [ForeignKey(nameof(ConveniadoDeId))]
    public virtual Conveniado ConveniadoDe { get; set; }

    [ForeignKey(nameof(ConveniadoParaId))]
    public virtual Conveniado ConveniadoPara { get; set; }

    [ForeignKey(nameof(ProcedimentoDeId))]
    public virtual Procedimento ProcedimentoDe { get; set; }

    [ForeignKey(nameof(ProcedimentoParaId))]
    public virtual Procedimento ProcedimentoPara { get; set; }
}

Ao rodar o udpate-database tenho o seguinte erro

Introducing FOREIGN KEY constraint 'FK_dbo.ProcedimentoAgregadoes_dbo.Procedimentoes_ProcedimentoParaId' on table 'ProcedimentoAgregadoes' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
  Could not create constraint or index. See previous errors.

Sempre resolvi isso usando o OnModelCreating do context
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<ProcedimentoAgregado>()
        .HasRequired(a => a.ProcedimentoPara)
        .WithMany(a => a.ProcedimentoAgregadoProcedimentosPara)
        .HasForeignKey(a => a.ProcedimentoParaId)
        .WillCascadeOnDelete(false);

    modelBuilder.Entity<ProcedimentoAgregado>()
        .HasRequired(a => a.ConveniadoPara)
        .WithMany(a => a.ProcedimentoAgregadoConveniadosPara)
        .HasForeignKey(a => a.ConveniadoParaId)
        .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
}

Ou
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

    base.OnModelCreating(modelBuilder);
}

Gostaria de saber se tem outra forma de resolver isso sem ser usando essas duas formas?
A estrutura do banco fica da seguinte maneira
Comment: Por que você precisa mapear duas vezes se é uma entidade e você já tem uma collection delas?
Comment: Pois é regra de negócio do sistema.
Comment: Mas deveria ser implementada nessa camada? Justamente por se tratar de regra de negócio?
Comment: E em qual camada teria que ser se não na entidade?
Comment: Se tratando de regra de negócio, não deveria estar na entidade, porque o papel dela é refletir a estrutura do banco, se for o caso de você ter uma tabela auxiliar com duas fks para a mesma tabela (Origem e Destino) você deveria ter uma Entidade específica para ela. Mas estou só especulando, adicione o diagrama da sua estrutura de dados
Comment: Mas em que momento a minha entidade não estaria refletindo a estrutura do banco?
Eu uso Migrations pelo EF, a minha estrutura do banco é o que está no mapeamento das minhas entidades.
Answer: Existe uma forma mais "limpa" de se mapear a classe, você pode utilizar uma classe Map do tipo EntityTypeConfiguration da Fluent API do EF, nela você pode especificar tudo de uma vez relacionado a classe que será configurada, no seu caso acredito que ficaria parecido com isso:
public class ProcedimentoAgregadoEntityConfiguration: EntityTypeConfiguration<ProcedimentoAgregado>
{
    public ProcedimentoAgregadoEntityConfiguration()
    {
            this.ToTable("ProcedimentoAgregadoes");

            this.HasKey<Guid>(s => s.ProcedimentoAgregadoId);

            this.HasMany(x => x.ConveniadoPara).HasForeignKey(x => x.ConveniadoParaId).WillCascadeOnDelete(false);

            this.HasMany(x => x.ProcedimentoPara).HasForeignKey(x => x.ProcedimentoParaId).WillCascadeOnDelete(false);

           //também defina as propriedades required para evitar erros

    }
}

E então no seus model builders você pode colocar:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new ProcedimentoAgregadoEntityConfiguration());
/...
}

Se quiser saber como utilizar e o que é Fluent API existe um site muito bom para isso.
Também existe um tópico focado somente em separar as configurações das entidades em classes separadas.
OBS: não recomendo usar modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(), pois pode surgir uma necessidade futura de cascade delete que fará você ter manutenção desnecessária nas classes antigas.

Editado conforme requisição do OP nos comentários:

Eu gostaria de não configurar isso por Fluent API e sim por Data Annotations.

Você pode configurar na própria model via Data Annotation através da identificação [ForeignKey("IdForeignKey")] acima da model relacionada a essa FK como você já fez.
Para evitar o cascade delete sem usar a Fluent API as únicas soluções são as que você apresentou (minha fonte para essa afirmação e uma fonte com todas Data Annotations para você comprovar), porém você pode setar seu intna própria model para Nullable, isso fará que o cascade delete seja setado como false pelo EF, porém não posso dizer se no seu caso essa seja a melhor solução, já que, se você não quiser inserções nulas teria que implementar algumas validações adicionais antes do comando de inserção ser executado.
No caso da model apresentada ficaria assim:
public class ProcedimentoAgregado
{
    [Key]
    public Guid ProcedimentoAgregadoId { get; set; }

    [Display(Name = "Conveniado de")]
    public int? ConveniadoDeId { get; set; }

    [Display(Name = "Procedimento de")]
    public int? ProcedimentoDeId { get; set; }

    [Display(Name = "Conveniado para")]
    public int? ConveniadoParaId { get; set; }

    [Display(Name = "Procedimento para")]
    public int? ProcedimentoParaId { get; set; }

    [ForeignKey(nameof(ConveniadoDeId))]
    public virtual Conveniado ConveniadoDe { get; set; }

    [ForeignKey(nameof(ConveniadoParaId))]
    public virtual Conveniado ConveniadoPara { get; set; }

    [ForeignKey(nameof(ProcedimentoDeId))]
    public virtual Procedimento ProcedimentoDe { get; set; }

    [ForeignKey(nameof(ProcedimentoParaId))]
    public virtual Procedimento ProcedimentoPara { get; set; }
}

Comment: eu gostaria de não configurar isso por Fluent API e sim por Data Annotations. O seu exemplo é bem dizer o mesmo do meu onde uso o OnModelCreating, só que vc separou em um arquivo.
Comment: desculpe a demora para responder amigo, vou editar a resposta com uma alternativa usando Data Annotations
Comment: @PabloTondolodeVargas editado

Mapear duas vezes a mesma entidade


some elementary questions about cardinality

Question: I know little about set theory and while reading some Algebra proof I had difficulty on some details. So my questions are :

If $X$ is an infinite set and $Y$ is the set of all finite subsets of $X$, they have the same cardinality. How can I prove it ?
If $X$ is infinite, then it has the same cardinality of the product $X \times  \mathbb{N}$, where $\mathbb{N}$ is the set of natural numbers. This seems pretty obvious, specially if you think separately when $X$ is countable and when it's not, but I cant prove this in a rigorous way.
Consider only infinite sets now. I know that if $X$ is countable, then it has the same cardinality as $X \times X$. Is this true in general (I mean, I know there is bijection between $\Bbb R$ and $\Bbb R^2$, but probably there is a counterexample that proves this is wrong for an arbitrary infinite set, or if not, I cannot prove it either) ?

Thank you so much for the help !
Answer: All these, and more, depend on an axiom called The Axiom of Choice. This axiom enforces infinite set to be very well-behaved, and the answer on all your questions become "yes".
If we do not assume the axiom of choice then the answers change, namely some of them become "sometimes" and others "no".
None of these propositions are trivial, especially without some background in set theory. It is even less trivial if you are not used to proving things from axiomatic systems like ZFC.
Let me answer your questions backwards.

The axiom of choice is equivalent to the assertion "For every infinite $X$, $X\times X$ has the same cardinality as $X$". In particular this means that if we assume the axiom of choice then this is true for every infinite set, but if we assume that this axiom does not hold, then we are guaranteed a counterexample to exist.
The second question regarding $X\times\mathbb N$, again if we assume the axiom of choice the answer is "yes". One of the consequences of this axiom is that if $X$ is infinite then $X$ has a countably infinite subset. Combine with the above we have that $$|X|\leq|X\times\mathbb N|\leq|X\times X|=|X|$$ Therefore equality ensues.
This again amounts to the axiom of choice and the first answer. Assuming that $X\times X$ has the same cardinality as $X$, we can prove by induction that $|X^n|=|X|$ , and by the second answer we have that $|\bigcup X^n|=|X\times\mathbb N|=|X|$ again.
This is not exactly what we are looking for because this is the set of sequences rather than subsets, but now we can simply send every sequence $\langle a_i\mid i=0,\ldots,k\rangle$ to the set $\{a_i\mid i=0,\ldots,k\}$. Observe that in the sequences there might be repetitions which are removed when we take the set, but we still can get every finite subset.
Well, this is a surjection, so it does not quite yet prove that the set of all finite subsets of $X$ has the same cardinality as $X$, but another wonderful property following from the axiom of choice is that we can inverse surjective functions, namely there is an injection from the set of finite subsets into the set of finite sequences, and this is what we wanted.

One last remark is that the counterexamples without the axiom of choice are not very natural, at least for a modern person. However they exist and have their place in mathematics.
Comment: For (2) it is not provable from the negation of choice that a counterexample exists. However (1) and (3) are both statements that are equivalent to the axiom of choice, and therefore from the negation of choice we can engineer counterexamples.
Comment: Could you clarify your sentence "If we do not assume the axiom of choice then the answers change, namely some of them become 'sometimes' and others 'no'."? By 'no' do you mean that the claims are not always true, or never true? You said that if we assume ~AC, then there exists a counterexample to OP's claim #1. Do there also exist counterexamples to claims #2 and #3?
Answer: The results described below freely use the Axiom of Choice.

Theorem: If $X$ and $Y$ are infinite sets, then the cardinality of $X \times Y$ is the maximum of the cardinality of $X$ and the cardinality of $Y$.  For a proof see e.g. Theorem 8 and the following discussion in these notes.

This result answers your third question and also your second question, because every infinite set contains a countably infinite subset.
As for your first question: one way to do it is to write the set $Y$ of all finite subsets of your infinite set $X$ as a countable union of sets $Y_n$ for $n \in \mathbb{N}$, where each $Y_n$ is the set of subsets of $X$ having at most $n$ elements.  There is a natural surjection $X^n \rightarrow Y_n$ which shows that $\# Y_n \leq \# X^n = \# X$.  Thus $Y$ is a countable union of sets each having cardinality at most $X$, so $Y$ has cardinality at most $X$ (you can think of this in terms of $\# X \times \# \mathbb{N} = \# X$, for instance).  On the other hand, the subset $Y_1$ of one element subsets of $X$ is naturally in bijection with $X$ itself, so also $\# X \leq \# Y$.  It follows from Cantor-Bernstein that $\# X = \# Y$.
Comment: what do you mean by e.g. Theorem 8? @Pete L. Clark
Comment: I need your papers that talk about the Axiom Of Choice and its different versions as you mentioned in your notes, if you do not mind, thanks in advance  @Pete L. Clark
Comment: And also if you do not mind, I want the notes previous to the above notes. @Pete L. Clark


distribution of r.v. when it's broken down in binomials

Question: there is a result I remember being right but I couldn't find it by googling.
Assume A and B indendepent random variable.
I know that when B is fixed (knowing B), A behaves like a binomial law of parameter (p, B).
It follows that A behaves in general like a binomial law of parameter (p, E(b))
Is that true ? is there a "name" for this property ?
Comment: The claim is not true, but perhaps you're recalling that the sum of binomial rvs with the same $p$ but different $n_i$ is binomial? https://en.wikipedia.org/wiki/Binomial_sum_variance_inequality
Comment: Except in degenerate cases, it is impossible for such a mixture of Binomials to have a Binomial distribution.
Answer: This property is not true. This should be clear even from just reading the statement of the property, since $\mathbb{E}[B]$ need not be an integer.
However, a simple example can also illustrate the point -- let $B$ be a discrete random variable that takes value 0 with probability 0.5 and 1000 with probability 0.5. Whenever $B=0$, then $A=0$. Whenever $B=1000$, then $A\sim\mathrm{Binom}(p, 1000)$. So more than 50% of the time, $A$ takes value 0. Clearly then it is not distributed as $A\sim\mathrm{Binom}(p, 500)$ for arbitrary $p$.


How to automatically backup snapshots/images in Google Compute Engine

Question: I have Google Compute Engine instances and I want to do automatic snapshot/image backups.
It should be like a schedule job that every 5 hours it makes a snapshot/image to my instances.
I read that it is possible to do with Cron job but I can't understand how to do it.
Could you please help me to understand how to do automatic snapshot/image?
Thanks in advance.
Answer: You can create an .sh script to make the snapshot with the gcloud command. This is the script we are using:
# Settings
GCLOUD_PROJECT="my-project"
SERVICE_ACCOUNT_JSON="location to service account json"
DISK_NAME="my-disk"
GCE_ZONE="europe-west1-d"
DATETIME=`date "+%Y-%m-%d-%H-%M-%S"`

# authenticate first
export CLOUDSDK_PYTHON_SITEPACKAGES=1
gcloud auth activate-service-account --key-file $SERVICE_ACCOUNT_JSON --project $GCLOUD_PROJECT

# sync => empty filesystem buffers
sync

# make the actual snapshot
gcloud --project $GCLOUD_PROJECT compute disks snapshot $DISK_NAME --zone $GCE_ZONE --snapshot-names $DISK_NAME-$DATETIME

This will create a new incremental snapshot every time you run (for example create a cron to run it at night). The next thing you need to do is to decide how many snapshots you want to keep. We are keeping 5 snapshots and created the next script to delete the snapshots older then the 5 most recent snapshots. We run this script 30 mins after the first one to make sure that the creation of the snapshot is finished.
# Settings
GCLOUD_PROJECT="my-project"
SERVICE_ACCOUNT_JSON="location to service account json"
DISK_NAME="my-disk"
GCE_ZONE="europe-west1-d"

# authenticate first
export CLOUDSDK_PYTHON_SITEPACKAGES=1
gcloud auth activate-service-account --key-file $SERVICE_ACCOUNT_JSON --project $GCLOUD_PROJECT

# list snapshots
snapshot_list=($(gcloud --project $GCLOUD_PROJECT compute snapshots list --sort-by NAME --regexp "$DISK_NAME-.*" | tail -n +2 | awk '{print $1}'))

keep_index=$(expr ${#snapshot_list[*]} - 5)

for i in $(seq 0 $keep_index);
do
    gcloud --project $GCLOUD_PROJECT compute snapshots delete ${snapshot_list[i]} -q
done

Comment: Thank you. It seems to be useful for me. Could you please explain how to connect the sh file with cron? I mean, I created this sh file but how do I tell Google to run it every X hours? Should I run this script in gcloud?
I am new to Google Cloud and I am confused where to start... This code helps but how to do the other steps you described, could you please decribe more?
Comment: gcloud is the command line tool for running jobs in the Google Cloud Platform. It should already be installed on Linux instances started in GCP. Simply type gcloud on the command line to test it. To authorise your jobs you will need to create a service account with the correct priviliges. You can create one in the console under IAM.
Comment: Regarding the cron, you can add a new cron with the command "crontab -e". You will need to add a line like this: 0 */5 * * * /command/to/run  If you want to know the details about possibilities and options of cron then there are many guides on the internet.
Answer: Google has now introduced the Snapshot Scheduler. You can find it in the snapshot section -> Create Snapshot Schedule.
Once you have the schedule you can create a new disk and select the schedule or edit an existing this and assign the scheduler.


dynamically update lilypond variables (using scheme?)

Question: I have a bunch of organ scores with 4 voices (sopMusic, altoMusic, tenorMusic, bassMusic). Each of those voices consists of two alternating snippets of music. For example, under sopMusic we would find \sopranoOne and \sopranoTwo, both of which contain a couple measures of music.  A simplified example would look like this:
sopMusic = {
    \global
    \voiceOne
    \sopranoOne
    \sopranoTwo
    \sopranoOne
    \sopranoTwo
}
altoMusic = {
    \global
    \voiceTwo
    \altoOne
    \altoTwo
    \altoOne
    \altoTwo
}
tenorMusic = {
    \global
    \voiceOne
    \tenorOne
    \tenorTwo
    \tenorOne
    \tenorTwo
}
bassMusic = {
    \global
    \voiceTwo
    \bassOne
    \bassTwo
    \bassOne
    \bassTwo
}

Typically I enter the correct number of repetitions in the soprano, and then copy/paste for the alto, tenor and bass parts. But this would be better done programmatically. Can somebody give me a function that will produce the altoMusic, tenorMusic, and bassMusic automatically given the sopMusic as an input?
Comment: Have you read https://lilypond.org/doc/v2.23/Documentation/notation/using-music-functions?
Answer: Maybe something like this fits the bill?
%%% Predicate for number or #f
#(define (number-or-false? x) (or (number? x) (not x)))

%%% arrange music saved in alist @param part in order @param repetitions (a list of assoc keys). Optionally
%%% the voice number can be specified using @param voicenumber
unfoldRepetition =
#(define-music-function (repetitions voicenumber part) (list? (number-or-false? #f) list?)
   (make-music 'SequentialMusic
               'elements
               (if voicenumber
                   (cons (context-spec-music (make-voice-props-set (1- voicenumber))  'Voice)
                         (map (lambda (x) (ly:assoc-get x part)) repetitions))
                   (map (lambda (x) (ly:assoc-get x part)) repetitions))))

%%% DEFINING MUSIC
% This defines associated lists, which is nice to access from Scheme. We use 1,2 as keys, but this could be any symbol, e.g. one,two
soprano.1 = {
  c''4 d'' c'' d''
}

soprano.2 = {
  b'4 c'' b' c''
}

alto.1 = {
  g'2 f'
}

alto.2 = {
  e'2 d'
}

tenor.1 = {
  e'2 d'
}

tenor.2 = {
  a2 b
}

bass.1 = {
  c2 g
}

bass.2 = {
  a2 g
}
%%% DONE DEFINING MUSIC

%%% Define a list of repetitions
#(define repetitions '(1 2 1 2))

% Test for one voice without specifying voice number
\unfoldRepetition #repetitions #soprano

% Test for multiple voices with voice number (although not necessary)
\new ChoirStaff <<
  \new Staff << \unfoldRepetition #repetitions 1 #soprano \\ \unfoldRepetition #repetitions 2 #alto >>
  \new Staff { \clef bass << \unfoldRepetition #repetitions 1 #tenor \\ \unfoldRepetition #repetitions 2 #bass >> }
>>

%%% DEFINE A choir score FACTORY:
choirScore =
#(define-scheme-function (S A T B) (list? list? list? list?)
   (define-music-function (reps) (list?)
     #{
       \new ChoirStaff <<
         \new Staff << \unfoldRepetition #reps 1 #S \\ \unfoldRepetition #reps 2 #A >>
         \new Staff { \clef bass << \unfoldRepetition #reps 1 #T \\ \unfoldRepetition #reps 2 #B >> }
       >>
     #}))

%% Test
myChoirFactory = \choirScore #soprano #alto #tenor #bass

\myChoirFactory #repetitions
\myChoirFactory #'(1 2 1)