Uniform distribution and ordered statistics

Question: Let $X_1,....,X_{n-1}$ be $(n-1)$ random variables following a Uniform distribution. If we note $X_{(1)},..,X_{(n-1)}$ the associated ordered statistics, I would like to prove that :
$$U_i=X_{(i+1)}-X_{(i)} $$
follows a uniform distribution. I would like to know if there's a simple demonstration of that fact or if anyone has pointers.
Comment: The $U_i$ do not follow uniform distributions, but their *joint* distribution is uniform.
Answer: As detailed in (the simulation Bible) Devroye's Non-uniform Variate Generation (1985), Chapter V, Section 2, the vector $(S_1,\ldots,S_{n})$ is jointly uniform:

Theorem 2.1 $\quad$ If $U_{(1)}\le\cdots\le U_{(n)}$ are the Uniform $\mathcal U(0,1)$ order statistics of an $n$-sample, and the$$S_i=U_{(i)}-U_{(i-1)}\qquad(1\le i\le n+1)$$ where by convention $U_{(0)}=0$ and $U_{(n+1)}=1$, are the uniform spacings, then $(S_1,\ldots,S_{n})$ is uniformly distributed over the simplex
  $$\mathcal A_{n-1}=\left\{(x_1,\ldots,x_{n});\ 0\le x_i\,,\ \sum_{i=1}^{n} x_i\le 1\right\}$$

[The proof follows from the order statistics $U_{(1)}\le\cdots\le U_{(n)}$ being distributed as$$n!\,\prod_{i=1}^n \mathbb{I}_{(0,1)}(u_{(i)})\times\mathbb{I}_{u_{(1)}\le\cdots\le u_{(n)}}$$$n!$ being the number of permutations of $\{1,...,n\}$ and from the change of variables from the $U_{(i)}$'s to the $S_i$'s being of Jacobian determinant equal to one]
and

Theorem 2.2 $\quad$ The vector $$(S_1,\ldots,S_{n+1})$$ is distributed as
  $$(\varepsilon_0,\ldots,\varepsilon_n)\Big/\sum_{i=0}^n\varepsilon_i$$where the $\epsilon_i$'s are iid $\mathcal E(1)$.

The above is also the constructive definition of a Dirichlet $$\mathcal D\overbrace{(1,\ldots,1)}^\text{$n+1$ terms}$$ distribution and the consequence is that $S_i$ is distributed as a Beta $\mathcal B(1,n)$ random variable. Not marginaly uniform then (if conditionally so).
Comment: Thanks a lot! What I don't quite get is the statement in the first theorem saying that the order statistics are uniform over the simplex. Why is it so ?
Comment: Do you mean you do not understand Devroye's proof (p.207)?
Comment: Yes, actually just the first line. Do you have some pointers for proving his statement?
Comment: Would it correct to say that,  according to theorem 2.2 and this link https://math.stackexchange.com/questions/1832712/understanding-the-flat-uniform-dirichlet-distribution-density-over-a-simplex, the joint distribution of (S_1,..., S_n+1) is the uniform distribution on the n simplex ?


How do you redirect from one directory to another and maintain the proper basepath?

Question: I need to redirect all /eula traffic to /tos
RewriteRule ^/eula/$ /tos [R=301,NC]

but this rule doesnt seem to work -- mostly because the basepath is being treated as the root when really theres another parent directory; what's happening with the above rule is >
/my/docs/eula -> /tos

which is not right, it should be doing this >
/my/docs/eula -> /my/docs/tos

How do I write the rule for this, without having to specify what the parent dir is?
Answer: RewriteRule ^(.*)/eula$ $1/tos [R=301,NC]
Comment: i did just that! =/ and it didnt work which is why this is driving me crazy. What about /eula/ its a directory... dunno it looks like it's adding the back slash, so maybe the rule isnt being processed in the right order


How to convert vtkPolyData to itkImage?

Question: I've set of vtk polygonal data files for segmented vessels:-

How to (voxelize) convert it to itk image with specific (size, origin and spacing)?
Answer: This is not a trivial problem. It is not possible to do that given your raw contours. If you can convert your contours to a closed surface, then you can use vtkVoxelModeller to create a vtkImage. Then you can create an itk image using vtkITKImageFilter.
Alternatively, you can fit a closed geometry to your contours and create voxels based on the parameterization of your geometry:
http://www.mit.edu/~adalca/files/papers/nerve_segmentation.pdf
Comment: There are lots of ways of constructing a surface from point clouds. I won't list them in detail, since this has already been answered in: http://stackoverflow.com/questions/838761/robust-algorithm-for-surface-reconstruction-from-3d-point-cloud
Comment: But, how to convert those contours to a closed surface?

How to convert vtkPolyData to itkImage?


Parametrizing algebraic variety.

Question: I am to find a parametrization of the variety $V:=V(x^2-yz,y^3-z^5) \subseteq \mathbb{C}^3$.
I've come up with $\{(t^4,t^5,t^3)\in \mathbb{C}^3\mid t\in \mathbb{C}^3\}=:T$.
It is clear that $T\subseteq V$ but I'm not so sure about the other inclusion.
I've tried to prove that $(y/x)^3 = z$ using some substitutions valid in the Variety, but to no avail.
Is the found parametrization correct?
Answer: Let $(x,y,z) \in V$. We have $y^3 = z^5$ and so we can write $(x,y,z)$ as $(x,t^5,t^3)$ for some $t \in \mathbb C$. But since $x^2 = zy$ we can say $x = \pm t^4$. So $(x,y,z) = (\pm t^4, t^5, t^3)$. This means you need two parametrizations for your curve, defined by $\phi_{\pm}(t) = (\pm t^4, t^5, t^3)$.
I don't think you can find a unique parametrization. An idea of proof could be the following : such parametrization gives you a birational morphism between the closure of $V$ in $\mathbb P^3$ and $\mathbb P^1$. In particular, the genus of the curve would be $0$. But your curve is a smooth intersection of two surfaces of degree $2$ and $5$, so if your curve was smooth its genus would be $16$. But your curve is singular, so one needs to study the singularity for finding the genus, if it's still nonzero then single parametrization cannot exist. Curves with a parametrization "almost everywhere" (i.e an isomorphism $ U \to V$  where $ U,V$ are Zariski open in $C$, resp. $\mathbb P^1$) are called unicursal.
Comment: @DarthGeek : I was a bit tired this morning : my argument works perfectly without any assumptions on $z$. I edited my answer.
Comment: I was more tired than expected : you need two parametrization, $T$ and $T' = \{ (-t^4,t^5,t^3\}$. We have $ V = T \cup T'$ and $T \cap T' = (0,0,0)$.
Comment: So $\{(\pm t^4,t^5,t^3)\in\mathbb{C}^3\mid t\in \mathbb{C}\} \subseteq V$, but how would one prove that $V\subseteq \{(\pm t^4,t^5,t^3)\in\mathbb{C}^3\mid t\in \mathbb{C}\}$?
Comment: This is exactly what I wrote : I took $(x,y,z) \in V$. If $z = 0$ then $(x,y,z) = (0,0,0) \in T$. Else $(x,y,z) = (\pm t^4,t^5,t^3)$ but both are in $T$.
Comment: Why is $(-t^4,t^5,t^3)$ in $T$?if there is $u$ such that $(u^4,u^5,u^3) = (-t^4,t^5,t^3)$ doesn't that mean that $t = u = 0$?
Comment: @DarthGeek : I have edited my answer. I think you can't have only one parametrization but I didn't do the computations (if you want I can try to do it but I don't know when I'll have time).
Answer: Let $(x,y,z)\in V$ and let $t = \dfrac{y^2}{z^3}$. Then
$$t^3 = \frac{y^6}{z^9} = \dfrac{z^{10}}{z^9} = z, \qquad t^5 = t^2z = \frac{y^4z}{z^6} = \frac{y^4}{z^5} = \frac{y^4}{y^3} = y.$$
Also, $x^2 = t^8$ so $x = \pm t^4$ so $(x,y,z) = (\pm t^4,t^5,t^3)$.

Parametrizing algebraic variety.


Sublinear function is positively homogeneous.

Question: We let $\mathbb{E}$ be a Euclidean space and assume $f:\mathbb{E} \to \mathbb{R}$ satisfies
$$f(\lambda x + \mu y) \leq \lambda f(x) + \mu f(y) $$ for all $x,y \in \mathbb{E}, \lambda,\mu \in \mathbb{R}_+.$
I want to show that this is equivalent to the usual definition of sublinearity, i.e.
$$ f(x+y) \leq f(x)+f(y), \quad f(\lambda x) = \lambda f(x)$$
The first inequality follows easily, however I'm having trouble proving that the function is positively homogeneous. So far I've proved $f(0)=0$ and thus $f(\lambda x) \leq \lambda f(x)$. How do i obtain the reverse inequality?
Answer: Note the following:
\begin{equation}
\begin{split}
f(x)&=f\big{(}\frac{1}{\lambda}(\lambda x)+0\big{)}\\
&\leq \frac{1}{\lambda}f(\lambda x)+f(0)\\
&=\frac{1}{\lambda}f(\lambda x)\\
&\Rightarrow \lambda f(x)\leq f(\lambda x)
\end{split}
\end{equation}


What constitutes a legal block in volleyball in regard to it not counting as the first hit?

Question: Today in a match the setter set the ball too low for me to spike it, so I just dinked it over.  The bottom of the ball was lower than the top of the net at the point where I made contact.  When the defender made contact, again, the bottom of the ball was lower than the top of the net (the top of the ball was over the top of the net though).
I felt that this wasn't technically a block and that he shouldn't have been allowed to hit it a second time, but I wasn't sure so I just let it go.  Was this a legal block or should it have been our point when he hit it a second time in a row?
Edit:
I don't think I was clear about the part where, after I hit the ball, the ball travelled over the net onto the other team's side of the court.  The other player did not reach over the net so there is no issue there.  It's just an issue of whether or not their first contact was a block or a hit.  I believe it was not a block but I can't find a specific ruling to address it.
Comment: hi just want to ask is it violation regarding the blocker ... block the ball didn't over then he hit again same person without the blocker of opponent is it double the same person the one who block then he hit again under ... without blocker from the opponent
Comment: @pebbles It's difficult to understand what you're trying to explain.  If it's a legal "block" then the blocker may immediately contact the ball again.  If it wasn't a legal block (i.e. if no part of the blockers body was above the net) then it's considered the 1st hit and the blocker may not contact the ball again until someone else contacts it first.  Hope that answers your question, but like I said I'm not quite clear what it is you are trying to ask.
Answer: You are carefully describing the position of the ball in the moment of your attack hit and in the moment of the defensive contact. However, it is not important. The decisive criterion in this case is not the point of contact with the ball, but the position of the blocker's body. If any part of the blocker's body (usually but not necessarily hands) is higher than the top of the net, it is considered a block.
See Rule 14.1.1 Blocking (emphasis mine):

Blocking is the action of players close to the net to intercept the ball coming from the opponent by reaching higher than the top of the net, regardless of the height of the ball contact. Only front-row players are permitted to complete a block, but at the moment of the contact with the ball, a part of the body must be higher than the top of the net.

See also a similar case (3.46) in the FIVB Casebook:

After an attack the ball touched the head of a blocker, who reached with his hands over the net. The contact with the ball was lower than the top of the net. After this hit, the team played three more times and at the third hit, the referee whistled and called "four hits".
  Has this decision been correct?
Ruling
  The decision was not correct. Even if the contact of the blocker with the ball was lower than the top of the net, the action was a block because a part of his body was higher than the top of the net.
Rules 9.1, 14.1.1, 14.4.1
Comment: One other question this raises for me:  When it says only "front row players" does it mean that it is a foul for a person in the back row to complete a block or simply that it's not considered a block if they do?  Furthermore does front row refer to the "player's position" or the "position the player is in" (hope that makes sense)?
Comment: 1. Only front-row players are allowed to complete a block. When a back-row player _touches the ball_ while blocking, it is a fault. 2. "Front/back-row player" are standard terms used many times in the rules (there are many limitations based on the position, but that would be a different question), they depend on the rotational order (position at the moment of service); and in this specific case, nothing else would make any logical sense ;-) [no "player currently in back row" is logically/physically able to intercept the ball above the net, isn't he/she?]
Comment: Perfect!  In this case, none of his body was above the net so it was not a block.  Thanks!
Answer: As your "dink" :) was your team's third hit, the opponent can then reach over the net to make a block. Reason being, once the third hit is made it's a free-ball, and the opponent is then granted ability to reach over and make contact. Of course, contact with the net is still illegal, but as far as I can tell by your description - the opponent's play was legal. Side-out if you were serving, point to them (assuming rally scoring).
The following rules apply according to the Fédération Internationale de Volleyball:

11   PLAYER AT THE NET
11.1 REACHING BEYOND THE NET
11.1.1
  In blocking, a player may touch the ball beyond the net, provided that he/she does not interfere with the opponent's play before or during the latter's attack hit.
11.1.2
  After an attack hit, a player is permitted to pass his/her hand beyond the net, provided that the contact has been made within his/her own playing space.

Source: FIVB, rule 11, page 29
Comment: Welcome to Sports SE! Thanks for your response. Do you have a rule citation to back up your response?  Why are refs lenient on this rule? If refs are lenient on this rule, why is it a rule?
Comment: Hi edmastermind29, thank you :) In fact, I misread the OP's post originally. I have completely re-written my response. I'll look into a source for the rule. My reason for saying it was a "lenient" call, is that in the heat of the game, this call is often left up to the ref's discretion of whether it should be made or not.
Comment: +1 Okay, I understand. This is no different from other sports when refs miss calls. Thanks for adding a source :)
Comment: @edmastermind29 - Exactly. =]
Comment: Does the complete rule 11 apply to the OP's question? Perhaps you can add a quote, in addition to people downloading 3,5 MB.
Comment: @Jacob Jan Tuinstra -- You're required to do a download? For me it's just an online .pdf, strange.  11 PLAYER AT THE NET
11.1 REACHING BEYOND THE NET
11.1.1 In blocking, a player may touch the ball beyond the net, provided that
he/she does not interfere with the opponent's play **before or during** the
latter's attack hit.
14.1, 14.3
11.1.2 After an attack hit, a player is permitted to pass his/her hand beyond
the net, provided that the contact has been made within his/her own
playing space.
Comment: Thanks @NicholasVielbig.  See my edit though, as I must not have been completely clear about what happened.
Comment: @BVernon, I would have to find a rule that directly addresses this. But in general, from my playing experience, if the ball had gone below the net (and therefore, was not contacted using blocking form, i.e. vertical arms), then that would be considered the opponents first of three hits for their possession. Often times in this scenario you will see the blocker sort of hit it safely on his side (very high), and a bump set to spike occurs.


When to use a multivariate normal distribution?

Question: I was reading Bayes Point Machine example from infer.net:
http://research.microsoft.com/en-us/um/cambridge/projects/infernet/docs/Bayes%20Point%20Machine%20tutorial.aspx
The problem is when we have some input features that we want to classify. The classification goal is to learn a weight vector. Output is classified using this condition:
 W x attributes >= 0   (then class = true or 1, otherwise it's false or zero)

My question is: why for the weight vector we should use a VectorGaussian which is a multivariate normal distribution, and why the elements of weight matrix can't be just modeled using independent normal priors?
I implemented it using independent normal priors with mean zero and variance 1, and there is a dramatic change in the results.
Answer: The VectorGaussian in the example has an identity covariance matrix, which means the elements of the weight vector already have independent normal priors with mean zero and variance 1.  I suspect what you have actually done is replace the definition of w to be of type VariableArray<double> instead of Variable<Vector>.  This doesn't change the statistical model, but it does change how inference will be performed.  In this case, the inference is less accurate since the approximate posterior is being factorized over all elements of w.
Answer: I just borrowed a piece of data from your link

double[] incomes = { 63, 16, 28, 55, 22, 20 };
double[] ages = { 38, 23, 40, 27, 18, 40 };
bool[] willBuy = { true, false, true, true, false, false };

Clearly, the data are collected from 6 subjects, and each (income, age) pair of data are correlated in the sense that the data is from the same subject.
It's a good idea to think your data structure as a spreadsheet, each row representing data from a subject (person), and each column being a feature of interest. Then the data from each row are correlated since they are from that same subject. That is, the features are correlated! It makes no sense at all to assume independence.


how to maintain duplicate data between documents sync on firebase?

Question: I have a question about firestore and cloud function.
let say i have 2 collection:
products and reuse_shopping_carts.
and  my reuse_shopping_cart document contain many products with all it's properties (id,name,price,href).
now i want that if i change the price of a specific product in products collection , a cloud function will run on all reuse_shopping_cart documents and in every document that contains the specific product it will change is price.
someone can explain me how?
or what is the right approach to do it?
i know i can store in the reuse_shopping_cart only the product id and fetch the updated product data at client, but for a list of 100 product in one reuse_shopping_cart it's will require 100 separate query for every time i want to read the shopping list, and changing price of a product is mach more rare, so i think it's a better approach.
if you think differently i will happy to hear...
thank you!
Comment: If price changes are less common than reads of shopping carts, then your duplication of the price into the shopping cart will save you on IO operations. In fact, I'm not even sure you should update the price in all shopping carts, since the price may have been determined when the user added the item to the cart. For all options, see my answer here: https://stackoverflow.com/questions/30693785/how-to-write-denormalized-data-in-firebase
Comment: Hi Frank, in normal shopping cart you right, but this is reuse shopping cart that stay forever for the user and it's a start point for a new shopping cart so the price need to be changeable over time. i read about "Transactions and batched writes" in the firebase doc but it's limited to a maximum of 500 documents... so it's a problem because after some time i will have more the 500 reuse shopping list. any advice?
Comment: Ah OK. In that case it makes sense. The options in my linked answer remain the same, and your approach of updating them from Cloud Functions sounds valid to me.
Answer: You can structure your reuse_shopping_carts document like this:
products: (map)
  (product id)
    name:
    value:

For example:

Then to find which documents to update when the price changes you can query like this:
firebase.firestore().collection('reuse_shopping_carts').where(`products.${productId}.price`, '>=', 0)


listen tcp 127.0.0.1:9090: bind: address already in use

Question: How does one finds which service is using port?
# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.6 (Maipo)
# netstat -natpv | grep 9090
tcp6       0      0 :::9090                 :::*                    LISTEN      1/systemd
#

Please advise.

# systemctl status cockpit.service
● cockpit.service - Cockpit Web Service
   Loaded: loaded (/usr/lib/systemd/system/cockpit.service; static; vendor preset: disabled)
   Active: inactive (dead) since Mon 2019-06-10 12:43:51 EDT; 4 days ago
     Docs: man:cockpit-ws(8)
 Main PID: 15922 (code=exited, status=0/SUCCESS)

Jun 10 12:41:48 X.X.X systemd[1]: Starting Cockpit Web Service...
Jun 10 12:41:48 X.X.X systemd[1]: Started Cockpit Web Service.
Jun 10 12:41:48 X.X.X cockpit-ws[15922]: Using certificate: /etc/cockpit/ws-certs.d/0-self-signed.cert
Jun 10 12:42:05 X.X.X cockpit-session[16311]: pam_ssh_add: Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)
Jun 10 12:42:07 X.X.X cockpit-ws[15922]: logged in user session
Jun 10 12:42:07 X.X.X cockpit-ws[15922]: New connection to session from 10.52.208.221
Jun 10 12:42:21 X.X.X cockpit-ws[15922]: WebSocket from 10.52.208.221 for session closed
Jun 10 12:42:36 X.X.X cockpit-ws[15922]: session timed out
# lsof -i :9090
COMMAND PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
systemd   1 root   75u  IPv6 7761202      0t0  TCP *:websm (LISTEN)
#

Comment: run `sudo lsof -i :9090`
Comment: Could be that `Cockpit` is setup on your system ? https://www.redhat.com/en/blog/linux-system-administration-management-console-cockpit
Comment: @krisFR I thought so too, but it is not
Comment: @AlexD `lsof` shows me `systemd` (I already knew that)
Comment: So what is your question then?
Comment: grep your systemd configs for Listen directive.
Comment: @AlexD haha) i just stumble upon this too! thanks!
Answer: systemctl list-sockets should show exact unit name and the related service.
LISTEN                          UNIT                            ACTIVATES
[::]:9090                       cockpit.socket                  firstname.lastname@example.com

Answer: not ideal, but better then nothing:
# systemctl | grep listening
dm-event.socket                                                                                loaded active     listening    Device-mapper event daemon FIFOs
iscsid.socket                                                                                loaded active     listening    Open-iSCSI iscsid Socket
iscsiuio.socket                                                                                loaded active     listening    Open-iSCSI iscsiuio Socket
lvm2-lvmpolld.socket                                                                                loaded active     listening    LVM2 poll daemon socket
systemd-initctl.socket                                                                                loaded active     listening    /dev/initctl Compatibility Named Pipe
systemd-shutdownd.socket                                                                              loaded active     listening    Delayed Shutdown Socket
virtlockd.socket                                                                                loaded active     listening    Virtual machine lock manager socket
virtlogd.socket                                                                                loaded active     listening    Virtual machine log manager socket
#

in my case it was cockpit.socket (not cockpit.service)
Answer: You cloud either use ss or netstat for this problem.
sudo ss -ntpulo

or
sudo netstat -ntpul

Both show the Network tcp and udp protocols and it's programs_name as long list and at the end you could grep the stdout like:
sudo ss -ntpulo | grep 9090

Also remember netstat comes with package called net-tools so if it's not found on your system just install:
# Ubuntu/debian
sudo apt install net-tools

# centos
yum install net-tools

P.S: I like netstat, it has nicer output :)


What is the relationship between the chords in the bridge of Frank Ocean's Sweet Life?

Question: The chords in the bridge to Frank Ocean's Sweet Life are:
||: C#maj9 | C#m7 | Bmaj7 | A#m7 :||
Here's a link to a tutorial of the song that shows the chords:

And a link to the song (bridge at 3:03):

I am finding it hard to understand how these chords are related and what key this bridge is in? The rest of the song seems to be in Emaj. But these chords stand out like a sore thumb - yet somehow sound so good. How is that possible? Do they have share a relationship in the circle of fifths?
Answer: One thing to keep in mind is many pop music composers do not write with the idea of being able to justify their chord progressions with tonal harmony analysis. Sometimes they just hit a certain sequence they like and go with it.
That being said, in this case both the verse and the bridge of this song make use of a device that has been used in several American songbook standards, major 7th chords going down stepwise with a transitional chord or chords in between. "How High the Moon", "Midnight Sun" and the bridge of "Watch What Happens" all use this chord progression:
Gmaj7 |////|Gm7 |C7 |Fmaj7 |////| etc.
The verses and bridge both have this same sequence in different keys with a subtle difference, they use only one transitional chord instead of a ii-V. In the verses it is a V7sus4 (B7sus4) to the Emaj7 and in the bridge it is a iim7 (C#m7) to the Bmaj7. In essence it is almost the same chord because you can think of a B7sus4 like a F#m7/B.
The A#m7 is more in line with what I said in my first paragraph, just something that sounded and felt good to the composer. You can call it the relative minor of C#maj7. I don't hear it as being very functional, it just sounds good.
Another interesting thing to point out is the bridge is a modulation to the dominant (F# and E to C# and B) which is a very common modulation in classical music.
Comment: That A#m7 translates to C#6, so could be construed as such, albeit with a different root. Not sure if Lover falls into the same category  - it's too early here!
Comment: @Tim I did make a similar connection by saying it could be the relative minor of C#. "Lover" is more descending chromatics if I recall...
Comment: This is awesome, thanks for the explanation. I see the similarity now between the F#m7/B in the verse and the C#m7 in the bridge. In that way it's kind of like almost the same exact passing chord from the verse just in the modulated key of B. So you can impute the F# and C#m7/F# becomes F#7sus4. Aha! Like a ii-V-I. And yeah I guess the  A#m7 just sounds good (being the relative minor of C# probably doesn't hurt). Now I'm overthinking it maybe, but your explanation makes a lot of sense. Thank you!
Comment: That's right, ii and Vsus are very similar. it also occurred to me that the whole tune is sort of a ii-V-I except with a IImaj7 instead of a iim7!
Answer: What key is the bridge?
The bridge modulates; it's not in a single key. For a similar kind of chord motion (similar, but not identical), see the verse of Green Dolphin Street.
[It] sound[s] so good. How is that possible?
The bridge chords are, in effect, a transposition of the chords on the verse, plus C# is a closely enough related key to E, so the ear doesn't have to make too radical an adjustment with the first chord. (C# minor is the relative minor to E major; and C# major is just a hop, skip, and a jump from C# minor.)
Do they have share a relationship in the circle of fifths?
Not really. The C#maj9 to C#min7 is just a major-minor transition, so no circle of fifths needed. The other two chords are best seen as direct modulations. It all works by making use of step-wise motion and common-tones. To try to analyze them in terms of common  practice Tonal harmony rules would be misleading.
In general, jazz and popular music make use of common practice voice-leading principles (such as step-wise motion), but much less strictly (such as in the resolution [or even definition] of dissonances) than the music Tonality was developed to describe.


Não consigo quebrar de linha usando JavaScript

Question: Bom dia, estou com certas dificuldades em tentar quebrar uma linha usando [b]\n[/b] do javascript. O código está funcionando perfeitamente, o que acontece é que na hora de exibir, fica mais ou menos assim:
Meu nick: ViniciusnComo descobri o servidor: YouTubenEu quero jogar porque: Gostei do servidor
Tipo o \n não tá quebrando a linha, mas ele aparece ali no final de cada string que eu coloco, o que será que está acontecendo?

Comment: Eu tentei usar o  porém no meu fórum ele aparece a tag  ao invés de quebrar linha
Comment: Funcionou, muito obrigado nicematt!
Comment: use  em vez de \n
Comment: Já tentou `'\\n'`?
Comment: Ei agora não tá funcionando mais, ta aparecendo assim http://i.imgur.com/RwwmnRj.jpg
Comment: Eu coloquei as duas barras \\
Comment: ` `
Comment: Eu também não sei, parece q ele não tá lendo a primeira barra
Comment: http://stackoverflow.com/questions/8627902/new-line-in-text-area?answertab=active#tab-top
Answer: Não vejo muito sentido em querer usar quebra de linha em input. Neste caso, o adequado seria uma textarea.
Basta usar \n para quebrar as linhas, veja funcionando:

var nick = 'XYZ';
var descobriu = 'por acaso';
var motivo = 'achei legal';

$('#message').val('[b]Meu nick:[/b] ' + nick + '\n[b]Como descobri o servidor:[/b] ' + descobriu + ' \n[b]Eu quero jogar porque:[/b] ' + motivo);
#message {width:80%}

<textarea id="message"></textarea>
Comment: Então, substitui pra textarea só que no meu forum não funciona de jeito nenhum o **\n** ele aparece como uma string
Comment: Pode ser que o problema esteja na parte da exibição, eu respondi em cima do código que está na pergunta, que só mostra a entrada dos dados. Pode ser que seu fórum tenha alguma conversão na hora de gravar os dados, mas sem ver o código, é complicado. Se não achar solução para exibir ou salvar corretamente os dados, abra uma pergunta sobre a exibição, mas ponha a parte do código que mostra os dados com problema na tela.
Answer: Em vez de colocar em um input, defina um

depois você usa a sua chamada alterando o id do elemento:
 $('paragrafo').val('[b]Meu nick:[/b] ' + nick + '
[b]Como descobri o servidor:[/b] ' + descobriu + ' \n[b]Eu quero jogar porque:[/b] ' + motivo);

Comment: Já tinha sanado essa duvida, mesmo assim vou dar um gostei na sua resposta caso alguém tenha a mesma pergunta que eu.
Comment: beleza! Abraços.


Evento click JQuery no seletor .class

Question: Criei várias div recorrendo a jQuery onde atribui às mesmas a classe de CSS numero:
for(...)
textoHTML += "
"+sorteado+"
 \n";
...
textoHTML += "
"+sorteado+"
 \n";
$( "#quadro" ).html(textoHTML);

Quero poder clicar nesta div e recuperar o número sorteado.
Mas ainda não sei como fazer, é com o innerHtml? this?
Porém, parece que o evento de clique do rato não está funcionando:
$( "numero" ).click(function() {
   console.log("Clicou no número");
});

Com o código acima nada acontece. Pode ter algo a ver com o facto de que a classe de CSS numero da div criada não está originalmente no DOM?
Answer: As sua intuição estava correcta, é usando o this e o innerHTML.
O que está a faltar:

Precisa de um ponto no selector do jQuery para classes
    '.numero'
     ↑
(ponto aqui)

Elementos criados dinamicamente precisam de ser delegados no caso de estar a amarrar o .click() antes do ciclo for ter corrido.
Se não estiver a amarrar o .click() antes do ciclo for ter corrido, pode usar o click como tem na pergunta, juntando o ponto à classe de CSS.
$('#quadro').on('click', '.numero', function () {

Pode usar o this dentro da função click
Pode usar this.innerHTML dentro da função.
Aqui vai é ficar a faltar um parseInt() para converter a string num numero no caso de querer usar aquele valor como numero. Se for só para mostrar e não precisa de fazer cálculos com o numero então pode usar só var numero = this.innerHTML; ou até innerText, em vez de innerHTML.

Exemplo pode ser visto aqui:
var textoHTML = '';
for (var sorteado = 0; sorteado < 30; sorteado = sorteado + 2) {
  textoHTML += "
" + sorteado + "
 \n";
  textoHTML += "
" + (sorteado + 1) + "
 \n";
}
$("#quadro").html(textoHTML);

$('#quadro').on('click', '.numero', function () {
  var numero = parseInt(this.innerHTML);
  alert(numero);
});

Comment: Obrigado pelo refactor à la @Zuul (TM)
Comment: Sergio, em algumas vezes trabalhando com o ".on" dessa forma: " $("#div").on('click',function(){ " não funcionou pra mim e somente usando " $(document).on("click","#div",function(){ " funcionou. Você sabe o motivo disso? Acha que vale abrir uma questão sobre isso?
Comment: @JoaoPaulo, dê uma olhada nesta resposta: http://pt.stackoverflow.com/a/5199/129
Comment: Quando vc usa o ID ele pega somente o primeiro elemento "[Selects a single element with the given id attribute](http://api.jquery.com/id-selector/)". Quando vc adiciona o evento no document e usa o seletor interno ID ele consegue mapear todos os elementos, mas "pesa" ficar adicionando tantos eventos no document.
Answer: Caso tenha problemas relacionados à elementos que não estavam originalmente no DOM, você pode utilizar o método .on() do jQuery. Exemplo:
$( ".numero" ).on( "click", function() {
    //codigo
});

Até um tempo atrás era utilizado o método .live() para isso, mas este já está obsoleto.

Evento click JQuery no seletor .class


Uniqueness of solution of $y' = f(x,y)$ : $|f(x,y)-f(x,z)|\leq h(x) |y-z|$

Question:
We assume the initial value problem : $y=f'(x,y),y(0)=0,0\leq x\leq a, |y|\le b$ where $a,b >0$. We assume that the function $f(x,y)$ is continuous and :
  $$|f(x,y)-f(x,z)|\leq h(x) |y-z|$$
  where $h:(0,a]\to \mathbb R$ integratable function.
Prove that this problem has a unique solution.

Thoughts :
First of all, let's assume a number $0<a_1 <a $. Then, let's assume the set :
$$D=\{(x,y) \in \mathbb R^2: 0\leq x\leq a,|y|\leq b\}$$
Despite not having a relation like $|x| \leq a$, can we say that $f(x,y)$ is continuous over $D$ which means that it has a solution in it ?
If we also do a Mean Value Theorem for $f(x,y)$ with respect to $y$ handling it as a single variable function over a subset of its domain, $(z,y)$ :
$$f_y(x,y)|_{y=ξ} = \frac{f(x,y) - f(x,z)}{y-z}$$
$$\Leftrightarrow $$
$$f(x,y) - f(x,z) = f_y(x,y)|_{y=ξ} \cdot (y-z)$$
Taking absolute values :
$$|f(x,y) - f(x,z)| = |f_y(x,y)|_{y=ξ}| \cdot |y-z|$$
Now, let's commute :
$$f_y(x,y)|_{y=ξ} \equiv g(x)$$
So, we get :
$$|f(x,y) - f(x,z)| = |g(x)| \cdot |y-z|$$
which has the same form as our initial given condition, but without the $\le$ sign (which means we haven't bound it). I can't seem though how to proceed from here or if I need to do something else. I also don't get where I'll be using that the function $h(x)$ is integretable.
Please, provide me some help or a thorough solution, I'll be greatly appreciating it since I am stuck on this problem for a few days.
Comment: What is $f'(x,y)$?
Answer: You can not assume that $f$ has partial derivatives. There may even not exist local Lipschitz constants, as there are unbounded integrable functions.
What you need to do is to take 2 solutions to the same initial value problem and consider the evolution of their distance. Using
$$
y(x)=0+\int_0^xf(s,y(s))\,ds,\;and\;z(x)=0+\int_0^xf(s,z(s))\,ds,
$$
you get
$$
\|y(x)-z(x)\|\le\int_0^xh(s)\|y(s)-z(s)\|\,ds.
$$
This you can now try to solve using the Grönwall lemma or similar considerations.

For instance, define $H(x)=\int_0^xh(s)\,ds$ and consider $$\phi(x)=\max_{s\in[0,x]}e^{-2H(s)}|y(s)-z(s)|.$$ Then
$$
\|y(x)-z(x)\|\le\int_0^xh(s)e^{2H(s)}\phi(x)\,ds=\frac12(e^{2H(x)}-1)\phi(x)
$$
which implies
$$
ϕ(x)\le\frac12\phi(x)
$$
which is only possible for $\phi(x)=0$.
Comment: Thanks a lot for your answer. Elaborate please on how I can proceed.


Dúvida sobre "resorteio" de valores iguais

Question: Fiz um exercício de sorteio utilizando dicionário:
from random import randint
from time import sleep
from operator import itemgetter

jogo = {'jogador 1': randint(1,6), 'jogador 2': randint(1,6), 'jogador 3': randint(1,6), 'jogador 4': randint(1,6)}
ranking = {}
print('Valores Sorteados')
for k,v in jogo.items():
    print(f' {k} tirou {v} no dado')
    sleep(1)

ranking = sorted(jogo.items(), key=itemgetter(1), reverse=True)
for k, v in enumerate(ranking):
    print(f'{k+1}º lugar: {v[0]} com {v[1]}')

Contudo, às vezes os jogadores apresentam valores iguais, como é o caso do exemplo abaixo. O jogadores 3 e 2 possuem o mesmo valor (4), mas apenas o jogador 3 se encontra em 2º lugar.
1º lugar: jogador 4 com 5
2º lugar: jogador 3 com 4 <-
3º lugar: jogador 2 com 4 <-
4º lugar: jogador 1 com 2

Como faço para realizar um novo sorteio apenas entre os jogadores com valores iguais para disputarem o 2º e 3 º?
Ex:
1º lugar: jogador 4 com 5
2º lugar: jogador 3 com 4
3º lugar: jogador 2 com 4
4º lugar: jogador 1 com 2

2º lugar: jogador 3 com 4  -> RESORTEIO -> jogador 3 com 2
3º lugar: jogador 2 com 4  -> RESORTEIO -> jogador 2 com 6

1º lugar: jogador 4 com 5
2º lugar: jogador 2 com (4 na 1º tentativa, 6 no resorteio)
3º lugar: jogador 3 com (4 na 1º tentativa, 2 no resorteio)
4º lugar: jogador 1 com 2

Comment: isso vai dar trabalho, não seria mais fácil gerar os jogadores um a um, e na hora de atribuir o valor aleatório ver se já existe e atribuir outro em seguida?
Answer: Até seria possível pedir para o código ficar repetindo os sorteios de todos os jogadores, ou só dos jogadores com mesmo número, mas considere a seguinte abordagem no lugar disso:

iniciamos uma sequência numérica com os valores possíveis para o jogo:
# valores possíveis = [1, 2, 3, 4, 5, 6]
valores = list(range(1, 7))

embaralhamos essa sequência:
import random
random.shuffle(valores)

definimos o número total de jogadores
max_jogadores = 4

criamos um dicionário com base nesse parâmetro, pegando sequencialmente os elementos da sequência de valores. Esse é o ponto-chave: como a sequência é composta de elementos únicos e está embaralhada, podemos simplesmente atribuir cada elemento da sequência a cada jogador em ordem, sem nos preocuparmos com repetições.
jogo = {f'jogador {i+1}': valores[i] for i in range(max_jogadores)}

Output (no meu caso, varia a cada execução):
{'jogador 1': 3, 'jogador 2': 5, 'jogador 3': 6, 'jogador 4': 2}

Um detalhe interessante é que a linha  jogo = ... vai causar um IndexError caso o número de jogadores seja maior do que os valores disponíveis na sua lista. Pode parecer ruim, mas caso isso acontecesse com a sua ideia original, o código ficaria silenciosamente em um loop infinito ao tentar atribuir valores únicos a um número de jogadores superior ao número de valores possíveis.


Dynamically load and execute Python modules in isolation

Question: This is an extension to the question posed here on dynamically execution of python modules
Dynamic module import in Python
While the consensus seems to be to use import or importlib to accomplish the dynamic loading/execution of python modules, this solution tends to break down when you have additional imports defined inside of the dynamically loaded module.
Take the original example
myapp/
    __init__.py
    commands/
        __init__.py
        command1.py
        command2.py
    foo.py
    bar.py

If command1.py imports command2.py then when you try to dynamically load command1.py using importlib or import it will fail with
ModuleNotFoundError: No module named 'command2'
Now I can get around this by adding commands directory to sys.path but that will pollute the global namespace. This can get even more problematic if there are multiple commands folder with different pip third party library dependencies. One command may depend on a different version of pip installed library than another command.
So in essence, I am looking for a way to dynamically load/execute a python module in isolation. Any ideas on how to achieve this?
Comment: `exec(f.read())`
Comment: How is exec different than importlib? Wouldn't it run into the same problems?
Answer: Since myapp is your project's root folder, not myapp/commands, you should do:
from commands import command2

in command1.py, so that the interpreter will be able to load command2.py.


RSS Reader: UITableView displays data very slowly

Question: I'm loading data from an rss feed and displaying the titles in a UITableview.
I'm using BlockRSSParser, to quickly get the required fields - Here
I'm using NSLog to track when the data is received. It takes around 20 secs before the UITableView displays the data, after receiving it.
Here's my code:
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTitle:@"Loading..."];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://blog.stackoverflow.com/feed/"]];
    [RSSParser parseRSSFeedForRequest:req success:^(NSArray *feedItems) {
        [self setTitle:@"Blogs"];
        [self setDataSource:feedItems];
        [self.tableView reloadData];
        RSSItem *item = [dataSource objectAtIndex:2];
        NSLog(@"loaded cell %@", [item title]);

    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

Notice the comment in this code. It gets executed quickly and shows me one of the title of the blog post.
But then for the next 20 secs, nothing is displayed before the following method finally kicks in:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];

    RSSItem *item = [dataSource objectAtIndex:indexPath.row];
    NSLog(@"loaded cell %@", [item title]);

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:item.title];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:item.title];
    }

    // Configure the cell...
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSString *theTitle = [item title];
    cell.textLabel.text = theTitle;

    return cell;
}

The comment in this code is executed after 20 secs. What is the reason behind this large delay?
I have tried using different feed urls from different sites. Still the same output.
Comment: I would say that calling tableview reloadData  at viewdidload it's not a good idea, do reloadData and the request somewhere at viewdidapear or viewdidlayouts.
Answer: You need to execute all UI-related tasks on the main-queue. Sample code below might need some adjustments to get the variables into the block.
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTitle:@"Loading..."];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://blog.stackoverflow.com/feed/"]];
    [RSSParser parseRSSFeedForRequest:req success:^(NSArray *feedItems) {

        dispatch_async(dispatch_get_main_queue(), ^{
            [self setTitle:@"Blogs"];
            [self setDataSource:feedItems];
            [self.tableView reloadData];
        });

        RSSItem *item = [dataSource objectAtIndex:2];
        NSLog(@"loaded cell %@", [item title]);

    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

Comment: As I said: all UI-related tasks have to happen on the main-queue. UIKit is not thread-safe. The documentation emphasizes this everywhere. However, the people who made it obviously put some effort into making it still do what you want - just a lot slower.


There is no Baire bijection between $\mathbb R$ and the set of functions $\mathbb Z\to\mathbb R$ modulo shifts

Question: Let $X$ denote the set $\mathbb{R}^\mathbb{Z}$ (the set of all functions from integers to reals),
and $\sim$ the equivalence relation on $X$ defined by:
$f \sim g$  iff there is a $z \in \mathbb{Z}$ such that for all $z' \in \mathbb{Z}: f(z'+z) = g(z')$.
Consider the quotient set $X/\sim$.
Some years ago, Mike Oliver made the remark that no bijection between $X/\sim$ and $\mathbb{R}$ could possibly be a Baire function.
I could do with a hint (or two) on how to prove that.
Comment: My apologies - my browser had/has some trouble with the MathJax preview.
Answer: Forget about $\mathbb{R}^\mathbb{Z}$; just look at $2^\mathbb{Z}$.
Hint 1: any set $A\subseteq 2^\mathbb{Z}$ which has the Baire property and which is $\sim$-saturated (in the sense that $x\in A$, $x\sim y$ implies $y\in A$) must be either meager or comeager.
Hint 2: if $f : 2^\mathbb{Z}\to \mathbb{R}$ is Baire-measurable and constant on every $\sim$-equivalence class, think about what $f^{-1}(U)$ could be, where $U$ ranges over open sets.  Maybe do something with a countable basis for $\mathbb{R}$...
I hope this is enough of a hint.


Entityreference multiple choice

Question: I have an entityreference field on users and I can't find a way to select more than one value. I want to make like a multiple select, but with the entityreference.
I use the EntityReference module, here is my form item :
<code>$form['maj_planning']['suivi_par'] = array(
  '#type' => 'entityreference',
  '#title' => t('Suivi par'),
  '#required' => FALSE,
  '#default_value' => $entity->suivi_par,
  '#era_entity_type' => 'user',
  '#era_bundles' => array(),
  '#era_cardinality' => 1,
  '#era_query_settings' => array(
    'limit' => 15, // Default is 50.
    'property_conditions' => array(),
    'field_conditions' => array(),
  ),
);
</code>
How can I achieve this ?
Answer: Try this in your .theme file:
<code>function MyTheme_user_form_user_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   $form['maj_planning']['suivi_par']['#multiple'] = TRUE;
}
</code>
Comment: In what content type can I choose unlimited ? My entityreference is on users, and my content types doesn't make sense about a search on users (I have blog page, page, slideshow, webform)
Comment: check my update please.

Entityreference multiple choice


visual studio 2010 using crystal reports and the results between 2 reports are not the same

Question: In a VB.net 2010 desktop application that uses crystal reports, I am trying to compare the results of 2 reports where summary data should be the same between the 2 reports. When I run the same queries in access 2013, I get the same detailed results. However when I run the reports, the report called YTD sometimes has different total amounts. Thus I am trying to determine what could be causing the amount on the YTD report to change.
This report is not using formula fields, parameter fields, running total fields, special fields, unbound fields. There are 2 group name fields. The grand total amount in the report footer section does a sum on the MainData.Amount area. When I look at the database fields, the 'MainData' contains all the rows that the dataset select statement contains.
Thus could there be a selection of some data in the crystal report that I do not see? Thus can you tell me what I could try to solve this issue?
Answer: In the Crystal Report, unhide or unsuppress all detail sections. Then add the field you are performing the Grand Total for into the detail section (if it is not already there). Then rerun the report.
This way, you will see every detailed record that Crystal is using to calculate the Grand Total. Perform your own manual addition of all detailed row values to verify if it adds up to the grand total in Crystal (no reason why it shouldn't)
This should give you the clues needed to determine if Crystal is including everything you want it to. If it is not, doublecheck your query and also the report filters screens.
Another piece of advice (if you aren't doing this already): when designing your report in crystal, if you've already written the query in MS Access, then you probably already know exactly which SQL you want, so when designing the report, use the same SQL statement as the datasource, as opposed to dragging tables in the report designer and drawing joins.
Comment: items: 1. you are saying to put a sum in the detail section like sum(purchase amount) or in a different area like group footer? 2. This is an existing report and the first time I am using crystal reports. 3. How do I 'doublecheck your query and also the report filters screens'? How can I find the query in the crystal report? The vb app does a datasource fill and I am assuming this supplied the data to crystal report. I have look at database expert and just see a reference is 1 table. 4. The vb app is only using 1 table to obtain the data from.


problem in website viewing

Question:
Fatal error: Call to undefined function omega_theme() in /home/itcom/public_html/sites/all/themes/libra/template.php on line 27

Whenever I browse my site, I get this message, and I am not able to login to the site. Clean URLs are not enabled in this site.
I would like to know how I can change the default current theme from code, and any other solution to rectify this problem.
Answer: The Libra theme is a sub-theme of the Omega theme, but seemingly the Omega theme is not present (otherwise, omega_theme() would be defined). Make sure that you have placed the Omega theme in /home/itcom/public_html/sites/all/themes/omega and try again.
Answer: I guess somewhere in your template.php file in your enabled theme you're making a call to omega_theme() function. If your theme is a subtheme of omega, you should let drupal know about that by putting this base theme = omega in your .info file in your theme folder. Also, omega theme should be present in your drupal themes folder.
Answer: Can you confirm that you uploaded the Omega theme properly. The first time I used Omega, I took the "Omega" directory only from the parent "Omega" folder and had similar issues but you need the entire folder that has "starterkits", "alpha" etc... See my screen capture to confirm your directory structure is correct.

problem in website viewing


Check if disk lies within an ellipse

Question: I have an ellipse in normal form centered at the origin and want to check whether a disk with given center point and radius is contained completely in the ellipse without touching it.
If I could compute the shortest distance between a point and the ellipse then I can just check if this distance is larger than the disk radius. How would I calculate this distance and are there other ways to solve this problem?
(Related to this question.)
Comment: http://www.spaceroots.org/documents/distance/distance-to-ellipse.pdf
Answer: Supposing that the disk's equation is given by:
$$(x-x_0)^2 + (y-y_0)^2 \le r^2 \ \ \ (\star)$$
And that the interior of the ellipse has the equation:
$$\frac{(x-x_1)^2}{a^2} + \frac{(y-y_1)^2}{b^2} < 1 \ \ \ (\star \star)$$
Check whether $(\star) \implies (\star \star)$
Answer: First, the center $P_0 =(x_0, y_0)$ has to be inside the ellipse $\frac{x^2}{a^2} + \frac{y^2}{b^2} =1$ and this means
$$\frac{x_0^2}{a^2} + \frac{y_0^2}{b^2} < 1$$
Now, let's determine the closest point $(P_1 = (x_1, y_1)$ on the ellipse to $(x_0, y_0)$. At such a point the tangent to the ellipse, which is given by the ecuation
$$\frac{x_1 x }{a^2} + \frac{y_1 y }{b^2} =1$$
has to be perpendicular to the segment $P_0 P_1$. Hence, we need to have
$$ \frac{x_1(x_1- x_0)}{a^2} + \frac{y_1(y_1- y_0)}{b^2}=0$$
Thus we get the system in the unknowns $(x_1, y_1)$
\begin{eqnarray}
\frac{x_1^2}{a^2}& +& \frac{y_1^2}{b^2} =1\\
\frac{x_0 x_1}{a^2} &+& \frac{y_0 y_1}{b^2} =1
\end{eqnarray}
which has two solutions (possibly equal). From them we get the one $P_1$ for which the distance is shortest ( for the other one it will be the longest).
Answer: Disk equation is given by:
$$(x-h)^2 + (y-k)^2= R^2 $$
And ellipse :
$$\frac{(x-H)^2}{a^2} + \frac{(y-K)^2}{b^2}= 1 \ \ \  $$
Calculate a value of x or y intersection after eliminating one of them.
To be within the ellipse the quadratic equation should have imaginary roots, discriminant should be $<0$ or zero for contacting ellipse and circle.

Check if disk lies within an ellipse


Store block from YAML file and append it in a existing YAML file using Python

Question: I have most of the code where I read each file and dump to a new file.
My next step is to store car1 (from mom, file2) and add it under dad block as car2, file1).
------
File 1
------
dad:
  car1:
    model: [toyota-venza]
    awd: true
    option:
      nav:
        backup_camera: true
        version: 1.35
    mileage: 54,025
    year: 2000
age:
  ...

------
File 2
------
mom:
  car1:
    model: [toyota-camry]
    awd: false
    option:
      nav:
        backup_camera: false
        version: []
    mileage: 20,241
    year: 2013
age:
  ...

Where the new file will look like this... containing car1 and car2 for dad.
dad:
  car1:
    model: [toyota-venza]
    awd: true
    option:
      nav:
        backup_camera: true
          version: 1.35
    mileage: 54,025
    year: 2000
  car2:
    model: [toyota-camry]
    awd: false
    option:
      nav:
        backup_camera: false
          version: []
    mileage: 20,241
    year: 2013

Comment: By what criteria do you mean to match `car2`? Is it always the first key of the first key? Your input file is no [valid YAML](http://www.yamllint.com/), your `version` is misleadingly indented
Comment: For car 2, I guess I would want the block that contains car2. Yes, it should be the first key of the first key. Sorry for the bad indent...
Comment: Your examples are not valid YAML. Your `version` is indented two spaces with regards to its sibling key `backup_camera` and that is not allowed.
Answer: Assuming that you kind find the car information by using key 'car1', you can search the toplevel mapping for a value with that key:
import ruamel.yaml as yaml
from ruamel.yaml.comments import CommentedMap
import glob

dad = CommentedMap()
dad['dad'] = d = CommentedMap()

for idx, file_name in enumerate(sorted(glob.glob('car*.yaml'))):
    data = yaml.load(open(file_name), Loader=yaml.RoundTripLoader)
    for k in data:
        if 'car1' in data[k]:
            new_key = 'car{0}'.format(idx+1)
            d[new_key] = data[k]['car1']
            d.yaml_add_eol_comment('# from {0} in {1}'.format(k, file_name),
                                   key=new_key, column=30)

print(yaml.dump(dad, Dumper=yaml.RoundTripDumper))

gives you:
dad:
  car1:                       # from dad in car1.yaml
    model: [toyota-venza]
    awd: true
    option:
      nav:
        backup_camera: true
        version: 1.35
    mileage: 54,025
    year: 2000
  car2:                       # from mom in car2.yaml
    model: [toyota-camry]
    awd: false
    option:
      nav:
        backup_camera: false
        version: []
    mileage: 20,241
    year: 2013

Assuming the data in files car1.yaml and car2.yaml. I used ruamel.yaml¹ here, to use ordered maps on which you attach comments.
You can do this with PyYAML, but you will loose the guaranteed ordering, and the comments:
import yaml
import glob

dad = dict()
dad['dad'] = d = dict()

for idx, file_name in enumerate(sorted(glob.glob('car*.yaml'))):
    data = yaml.load(open(file_name), Loader=yaml.SafeLoader)
    for k in data:
        if 'car1' in data[k]:
            new_key = 'car{0}'.format(idx+1)
            d[new_key] = data[k]['car1']

print(yaml.dump(dad, Dumper=yaml.SafeDumper))

¹ This was done using ruamel.yaml of which I am the author.
Comment: dad = CommentedMap()
dad['dad'] = d = CommentedMap()
Comment: sorry, I can't seem to get the package to install because I have Centos 5.1.  What is the equivalent of dad and d if I used pyyaml?
Comment: @user3203920 how did you install? Using `pip install ruamel.yaml`? I'll make a PyYAML downgraded version and edit the post.


Test case removing original file while uploading a file through test case

Question: This is my test case
public function testSelfieFileUpload()
{
    $path = public_path().'/uploads/sample1.jpg';
    $name = 'sample1.jpg';
    $file = new UploadedFile($path, $name, 'image/png', filesize($path), null, true);
    $response = $this->post($this->endpoint, ['file' => $file], $this->setHeaders());
    $response->assertStatus(200)
        ->assertJsonFragment(array("status" => "success"));
}

But the problem is that it is deleting the original file from the folder i.e sample1.jpg
Help me out. Am i missing something here? Although the test case is running fine.
Comment: Did you use **unset** for those file?
Comment: what's unset..? if you mean delete. then i am not explicitly doing that
Comment: If you want to remove file that was storing before you have to remove it using PHP unset function
Comment: No i don't want to delete it. My source file is getting deleted that's troubling me.
Comment: Ah, ok. I think UploadedFile just moving those file. So I guess there is some additional parameter that allow you to copy file instead of moving it. Not sure that - just my guess
Comment: That's what i want to know. If there is something that i am missing. Till then i am on hunt.
Answer: When having the same problem, after looking in the source code, I couldn't find a flag that fixes it.
As I workaround, I created a copy when running the test, which gets deleted but it's no longer a problem.
$temporaryFilePath = $this->createTempFile($this->testFilePath);
$file = new \Illuminate\Http\UploadedFile($path, $name, $mime, filesize($path), null, true);
//do your test logic

...

private function createTempFile($path) {

    $tempFilePath = $this->basePath . 'temp.xlsx';
    copy($path, $tempFilePath);

    return $tempFilePath;
}

You might want to refine this depending on your needs.
Comment: In Laravel 8, $file = new \Illuminate\Http\UploadedFile($path, $name, $mime, null, true);
Answer: This works for me.
You have to store in both public_path and storage_path the same file:
 $filename = storage_path('app/pdfstest/COVID 19.pdf');

 $pdf = new UploadedFile($filename, $name, 'application/pdf');

 $response = $this->post('/gallery', [
   'user_id' => $this->user->id,
   'doc' => [$pdf],
   'from_tab' => 'test'
 ]);

 $temp_pdf = file_get_contents(public_path('pdfstest/COVID 19.pdf'));
 Storage::put('pdfstest/COVID 19.pdf', $temp_pdf);


Local domains vs "relay domains"

Question: I have a vague notion but I'm not clear on the difference between local domains and "relay domains"
I believe that local domains are "localhost" and any other aliases you set the server up to mean "self".
I believe "relay" domains are "everything else?"  Like if a DNS has foobar.com point to this server, then foobar.com is a relay domain?  I am not sure about this point.
In the exim setup file - (exim4.template.conf) What does it mean "fallback MX or mail gateway for domains" - what is fallback mx?  Does it mean your server is like a DNS server of sorts?
Answer: Local domains are any domains which are on the server and mail to those addresses is delivered to a local mailbox (or a local alias), eg. email@example.com and email@example.com both deliver to john's mailbox on the server, no separation.
A virtual domain is similar, but there will be separation (eg. /var/spool/mail/example2.com/john is a mailbox).
A relay domain is one which your mailserver will deliver to as though it is local, without authentication. Eg. you could configure the server to delay to example3.com even though it's not local.
If any of that is wrong, I'd be happy to be shown the error of my ways.
Answer: Fallback MX is nothing but the Secondary Mail Exchanger (MX) or Mail Server. In case if Primary MX goes down, Exim will deliver mails to Secondary MX.
Comment: And so I should have __another__ mailserver up and running, like qmail?
Comment: It depends upon how crucial mailing services are for your organization. If you want your mailing services to be up all the time, it's better to have fall-back MX.

Local domains vs "relay domains"


Fazer busca em uma matriz(lista de lista)

Question: Escrever uma função chamada busca que receba uma matriz (cada linha da matriz tem quatro entradas, representando as informações referentes a nome, registro, setor e telefone) e faça uma busca por setor. Essa função deve retornar o nome, o registro e o telefone dos funcionários daquele setor.
def busca(setor):
    matriz = [["Adalberto Ferreira", "566", "Contabilidade", "(21)84564-5248"],
              ["Juliana Vasconcelos", "465", "RH", "(21)3555-4552"],
              ["Flavia Amorim", "565", "Contabilidade", "(21)2134-4845"]]
    nome = matriz[0][0], matriz[1][0], matriz[2][0]
    registro = matriz[0][1], matriz[1][1], matriz[2][1]
    setor = matriz[0][2], matriz[1][2], matriz[2][2]
    telefone = matriz[0][3], matriz[1][3], matriz[2][3]
    if setor == matriz[1][3]:
        return [nome[1][0], registro[1][1], telefone[1][3]]
    else:
        return [[nome[0][0], registro[0][1], telefone[0][3]], [nome[2][0], registro[2][1],
                telefone[2][3]]]

Eu cheguei a esse código mas ele apenas retorna uma parte da string, não a string completa.
Answer: Não faça a busca usando índices fixos. E se a matriz tiver mais que 3 registros? E se tiver menos?
Em vez disso, faça um loop pela matriz e guarde os funcionários do setor em uma lista:
def busca(setor_busca):
    matriz = [["Adalberto Ferreira", "566", "Contabilidade", "(21)84564-5248"],
              ["Juliana Vasconcelos", "465", "RH", "(21)3555-4552"],
              ["Flavia Amorim", "565", "Contabilidade", "(21)2134-4845"]]
    dados = []
    for nome, registro, setor, fone in matriz:
        if setor == setor_busca:
             dados.append([nome, registro, fone])
    return dados

print(busca('Contabilidade'))

Repare que no for eu já posso atribuir cada elemento das sub-listas em variáveis, o que facilita na hora de manipulá-las.
Há outros problemas no seu código: você sobrescreve o valor do parâmetro setor, e no return você está na verdade pegando um único caractere de cada string.

Se quiser, também pode fazer com list comprehension, bem mais sucinta e pythônica:
def busca(setor_busca):
    matriz = [["Adalberto Ferreira", "566", "Contabilidade", "(21)84564-5248"],
              ["Juliana Vasconcelos", "465", "RH", "(21)3555-4552"],
              ["Flavia Amorim", "565", "Contabilidade", "(21)2134-4845"]]
    return [  [nome, registro, fone] for nome, registro, setor, fone in matriz  if setor == setor_busca]

Outro detalhe é que a matriz com todos os dados poderia ser criada fora da função e passada como parâmetro, assim a função fica mais genérica e funciona para quaisquer outros dados:
def busca(matriz, setor_busca):
    return [  [nome, registro, fone] for nome, registro, setor, fone in matriz  if setor == setor_busca]

matriz = [["Adalberto Ferreira", "566", "Contabilidade", "(21)84564-5248"],
              ["Juliana Vasconcelos", "465", "RH", "(21)3555-4552"],
              ["Flavia Amorim", "565", "Contabilidade", "(21)2134-4845"]]
print(busca(matriz, 'Contabilidade'))

# posso reusar a função para outra matriz
outra_matriz = # outra matriz com dados diferentes
print(busca(outra_matriz, 'outro setor'))

Answer: Apenas para exemplificar, eu peguei a mesma matriz e separei apenas os nomes de cada perfil, pelo visto, eu também não sabia, mas quando você abre o segundo colchete para acessar o elemento da matriz o interpretador como se você tivesse fazendo fatiamento já que você está trabalhando com strings, então o correto é indicar que é pra pegar a string inteira, usando dois pontos(:). Eu rodei o seu código e acho que você ainda não vai ficar satisfeito com o resultado, mas esse é o problema.
if setor == matriz[1][3]:
        return [nome[1][0:], registro[1][1:], telefone[1][3:]]
    else:
        return [[nome[0][0:], registro[0][1:], telefone[0][3:]], [nome[2][0:], registro[2][1:],
                telefone[2:][3:]]]


What does the XX-citizens tag mean?

Question: For many countries we have both XX and XX-citizens tags (e.g., usa and us-citizens), but I am not sure what the difference is. It seems to me that the idea is if you are an expat, or planning on being an expat, in the US, then you would use the usa and if you are a citizen of the US and are an expat, or planning on being an expat, in a country other than the US then you would use the us-citizens. If you are an expat in the US but planning on moving to another country then it seems odd to use the us-citizens since you are not. This also happens if you are a US citizen expat living in the UK looking to move back to the US. In this case it seems you would tag the question with both uk-citizens and usa, which seems wrong.
I think it is important to differentiate between the country you are, or planning on being, an expat in from your "home" country. I am just not sure the country you are a citizen of is the right description. The problem is that "citizen" has a specific meaning to an expat. A tag like xx-residents might be better, but it still has very specific connotations.
Comment: Closely related: http://meta.expatriates.stackexchange.com/q/6/28
Answer: The tag-wiki entries explain this.  Borrowing from usa:

Use this tag for questions about living in the United States of America as an expatriate. For questions relating to living abroad as a US citizen, use us-citizens.

Further expanding on your question:

If you are an expat in the US but planning on moving to another country then it seems odd to use the us-citizens since you are not.

That's true.  If you are an expat in the US, then moving to, say, France, there would be no reason to use us-citizen, unless you had actually obtained US citizenship.  You would instead use xx-citizen, for whichever country you are a citizen, as this is what is relevant to your question when moving to France.  It will be rare that a question about moving to France will be affected by your previous residency rather than by your citizenship.
In cases where you have dual citizenship, it is appropriate to use multiple xx-citizen tags.
Comment: Also if you have a spouse with a different nationality to your own and you would be moving together, multiple tags would be appropriate
Answer: I believe the idea was country-name for questions about moving to that country, and code-citizens for questions about citizens from that country going elsewhere
So, usa would be for people moving to the USA, while uk-citizens is for questions for UK citizens going elsewhere
For example, the tag wiki for usa is currently

Living in the United States of America as an expatriate.

While for uk-citizens it's

For questions pertaining to citizens of the United Kingdom of Great Britain and Northern Ireland
Comment: @StrongBad: That's irrelevant. What matters is not where you're coming from, but where your citizenship resides. Taxes, visas, etc, have nothing to do with what countries you have visited or lived in. They have to do with your citizenship.
Comment: I agree with the idea, but it is flawed. Not everyone leaving the UK for the US is a UK citizen (in a legal passport carrying way) and in fact some are US citizens.

What does the XX-citizens tag mean?


Why task "promote this server to a domain controller" shows despite the server being already added to a domain?

Question: In Windows Server 2019 / server manager, a warning shows:

post-deployment configuration / configuration required for ADDS at server_name / promote this server to a domain controller

I already added server_name to the domain, my domain controller server (DC) is also my DNS, and I added its address to server_name; I installed ad-domain-services so I can manage users and computers of the domain from server_name.
Why the warning shows ? How to deactivate it (it is persistent) ?
Comment: It looks as though you asked it to install the Active Directory Domain Services role?  If you've changed your mind about wanting the machine to be a domain controller, remove the role.
Comment: @HarryJohnston I did it all from powershell. The role was added, I believe after adding the ADDS tools. So I should not have added the ADDS, but went through a ps-session to the DC to manage everything.
Comment: OK.  So you were able to add the tools, but you accidentally added the role as well?  Hopefully it will just be a matter of removing the role to get rid of the alert about it.
Answer: You've joined the server to the domain but you haven't made the server a Domain Controller for the domain. Adding the AD DS Role does not make the server a Domain Controller for the domain. If you do not intend for the server to be a Domain Controller for the domain then remove the AD DS role.
If you only want to manage the domain from the server then you only need to add the AD DS Role Administration Tools.
Answer: This also happens if you finish the DC promo using the command line instead of the Wizard. Just hit Promote the Server to a Domain Controller and then cancel the rest. The warning will disappear once it knows the promotion has finished.


Why are my graphics degraded when I load my Form at runtime

Question: I have made a winform application for use within the company I work for( web site was not an option)
The user base of this application has increased and of course it has become a pain to upgrade everyone...even more now since users are now disallowed form installing their own applications.
I came up with the idea of keeping the application stored on a database to be loaded upon execution.
It all works fine, but it seems that the graphics have a pre-windows7 (on win7 machines) look to them. Why would that be happening?
      System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(assemblyPath);
      Type type = assembly.GetType(typeName);
      Form form = (Form)Activator.CreateInstance(type);
      Application.Run(form);

Comment: Do you call `Application.EnableVisualStyles` before any controls are created, prior to loading the assembly?
Comment: On a related note, when you mention that users don't have permissions to install their own applications and upgrading it a problem you might want to look at ClickOnce. It works well in low privilege environments.
Comment: that seems to have done it...thank you
Answer: Call Application.EnableVisualStyles before any controls are created, prior to loading the assembly.
Comment: Fascinating that you were able to deduce that from "graphics degraded".
Comment: @CodyGray Thank you kind sir. The give-away was *but it seems that the graphics have a pre-windows7 (on win7 machines) look to them*


Como compilar Java com ícones

Question: Anteriormente, postei uma dúvida de como compilar meu projeto em "Runnable Jar" com ícones.
E conseguir fazer isso com label e buttons. Agora minha dúvida é como fazer isso em iconImage. Tentei o seguinte:
setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\Utilitários\\Desenvolvimento\\Eclipse JEE Kepler SR2 (x64)\\- Projetos\\Pizzaria\\src\\Icones\\fatcow-hosting-extra-icons-2\\16\\pizza.png"));

Porém não funcionou, alguém poderia me ajudar?
Answer:
Sua imagens deve esta em uma pasta do pacote de fontes exe.: src/images/img.png
Seguindo o passo 1, quando gerar o .jar da app não vai precisar de pasta externa;
Segue código:
URL imageURL = getClass().getResource("/images/confirmar.png");
ImageIcon imageIcon = new ImageIcon(imageURL);
frame.setIconImage(imageIcon.getImage());

Espero que lhe ajude.

Como compilar Java com ícones


Is integration with respect to spherical measure equivalent to manifold integration over sphere?

Question: Let $S$ be an $n$--sphere $\mathcal{S}^n(0,R)\subset\mathbb{R}^{n+1}$, $\Theta\subset\mathbb{R}^n$ an open subset and let $\phi:\Theta\subset\mathbb{R}^n\longrightarrow S\subset\mathbb{R}^{n+1}$ be a diffeomorphism onto "most of the sphere", i.e. $S\backslash\phi(\Theta)$ is of spherical measure zero. I'm talking about measure described in this article
https://en.wikipedia.org/wiki/Spherical_measure
Let's also assume that this spherical measure is scaled in such a way that measure of $S$ is equal to its "surface area" or an $n$-dimensional volume.
We can integrate a real function $f:S\longrightarrow \mathbb{R}$ over $\phi(\Theta)$ which is an $n$-dimensional manifold using a formula
$$\int_{\phi(\Theta)}f=\int_{\Theta}f(\phi(\theta))\sqrt{\big|\det D\phi^TD\phi\big|}\mathrm{d}l^n(\theta)$$
where $l^n$ is a Lebesgue measure in $\mathbb{R}^n$. (Is this correct? The square root of the determinant of Gram matrix of $D\phi$ serves the same role as the usual Jacobian determinant in case when the codomain is of higher dimension, I think.) I'd like to know if the integral of $f$ over $S$ with respect to spherical measure is equal to the above integral, that is if
$$\int_Sf\mathrm{d}s^n=\int_{\phi(\Theta)}f\mathrm{d}s^n=\int_{\phi(\Theta)}f$$
where $s^n$ is the spherical measure (appropriately scaled, like we assumed) and the rightmost integral is the integral defined above (the integral over a manifold).
Answer: "Yes, they are the same up to overall scale." If $\phi$ is a regular parametrization of the sphere $S^{n}$, the round metric on the sphere pulls back to
$$
g(X, Y)_{p}
  = D\phi(p)X \cdot D\phi(p)Y
  = X \cdot D\phi(p)^{T} D\phi(p)Y,
$$
whose volume form is, as you say, $\sqrt{\left|\det D\phi^{T} D\phi\right|}$ times Lebesgue measure in Euclidean $n$-space. If the image of $\phi$ has measure-zero complement, the integral of a measurable function $f$ over the image of $\phi$ is equal to the integral over $S^{n}$.
As you note, you need to take care with overall scale: Most mathematicians take "the sphere" to be the unit sphere $S^{n}$ centered at the origin of Cartesian $(n+1)$-dimensional space, whose $n$-dimensional volume is
$$
\frac{2\pi^{\frac{n+1}{2}}}{\Gamma(\frac{n+1}{2})}.
$$


Contextual filter by taxonomy term not using language

Question: We have a site with 3 different languages and each language is detected by sub-domain. One of the taxonomies we use is representing types of products and have terms in all 3 languages inside:
CategoryQ (se)
   CategoryW (se)

CategoryE (no)
   CategoryR (no)

CategoryT (da)
   CategoryY (da)

I faced with problem regarding contextual filters and taxonomy terms. I have view with contextual filter accepting term name and displaying nodes related to this term:
Content: Has taxonomy term ID (with depth)

Also added validation and "Filter value type" set to "Term name converted to Term ID".
All worked fine until we discovered that we have couple of terms that have same names in all languages (we are not translating terms, all terms are added separately for each language - BL requirement):
CategoryG (se)
   CategoryY (se)

CategoryG (no)
   CategoryX (no)

CategoryG (da)
   CategoryZ (da)

Processing contextual filter Drupal takes first term tid he found in database (with lowest tid) and use that constructing view's query. In our case Drupal takes SE term instead of NO. So basically there is no language control in contextual filter at all. Is it possible to somehow add this control with hooks or some modules maybe?
Answer: Temporary solution for was to create patch file to override views module functionality a little bit. Patch can be found under issue on drupal.org
https://www.drupal.org/node/2466001#comment-9795191.


Detecting jQuery UI version in module

Question: I am developing a module in Drupal 7.56 that is going to rely on jQuery UI 1.12.1. I want my module to check to see if that version is installed on the site, if it is not I am going to use drupal_add_js() to add the correct version. I don't want to just add the js file if it already exists in the system.
I do not have access to the site the module is going to be installed on. I want this module to be used on many different sites and don't want the module to add the js if it is already there.
What is the best way to do this?
Comment: `drupal_add_js` doesn't exist in Drupal 8
Comment: Ok... the question was originally tagged 8.
Answer: If you call drupal_add_js() without parameters it will return an array of all the JavaScript already installed. You can iterate over the elements to look for the jQuery UI version you need. For example
  $installed_js = drupal_add_js();
  foreach ($installed_js as $file => $details) {
    if (preg_match('/jquery\.ui/', $file)) {
      $version = $details['version'];
      break;
    }
  }
  list($major, $minor, $update) = explode('.', $version);
  if ($major != '1' && $minor != '12' && $update != '1') {
    // Add drupal_add_js call here
  }

You might need a more robust regex to check for a wider variety of possible filenames but the above code should work in principle. I should also point out, it's not totally robust - if for some bizarre reason the file was named blah.js, this approach would not find it, so your module's jQuery code should also check to make sure the right version is loaded.

Detecting jQuery UI version in module


Proving a sum is divergent under certain conditions

Question: Suppose $\{a_k,b_k\}$ are sequences that satisfy:
i) $\sum_k a_k=\infty,\,a_k \to 0$.
ii) $\sup_k b_k \to \infty$ and $b_k$ is bounded from below. Also, $|b_{k+1} -b_{k}| <C$ for some $C>0$.
I have been trying to prove (or disprove) that $\sum_k a_k b_k = \infty.$ My rough line of reasoning is that : Since $\sum_k a_k=\infty$, we have for a given $\epsilon$, $\exists\,m$ such that $\sum_{k=n}^{n+m} a_k >\epsilon$. Then,
$$
\sum_{k=n}^{n+m} a_kb_k > \big(\sum_{k=n}^{n+m} a_k\big) \{\sup_{k\in [n,n+m]} b_k -mC  \}
$$
Since $b_k \to \infty$ along a subsequence, I think we can make sure the difference term in the curly brackets stays positive. I have been trying to formalize the argument but have not been able to do so.
Answer: In fact it is not true that $\sum_k a_kb_k=\infty$. To obtain a counterexample, consider $a_k=1/k$. Now $b_k$ will spend most of its time at $b_k=-1$, interspersed with intervals where it climbs up to a new peak and returns to $-1$ for a very long time. Since the conditions don't impose any bound on how long $b_k$ can stay at $-1$ before increasing again to the next peak, by making it wait long enough we can even arrange for $\sum_k a_kb_k=-\infty$ (or any value in between).
Comment: Thanks for the answer.


Error instantiating View Controller

Question: When I try to instantiate my ViewController with the code below (in the viewDidLoad part) I get a Thread 1: EXC_BAD_ACCESS when running the app on the self.present line. (I'm a beginner to coding)
EDIT: So I provide my entire code here to see where it goes wrong. I shifted the code to viewDidLoad of my Second View Controller now. Now the app starts up, however when I press the "enter" Button, I get a "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" error..

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var progressBarView: ProgressBarView!

    @IBOutlet weak var progressBarView1: ProgressBarView1!

    override func viewDidLoad() {
        super.viewDidLoad()
// updaten van de progressbar
        progressBarView.progress = CGFloat(percProgress())
        progressBarView1.progress = CGFloat(0.5)

// een constante maken die de daystogocalc Int van de berekening verderop in een String cast
        let daysToGoCalcString = String(daysToGoCalc())

// updaten van het label daysToGo
        daysToGo.text = "Still \(daysToGoCalcString) days to go"

// updaten van het label textPercentage
        let textPercentage = NSString(format: "%.0f", (percProgress() * 100))
        percentageDays.text = String(textPercentage) + "%"

    }

    @IBOutlet weak var daysToGo: UILabel!

    @IBOutlet weak var percentageDays: UILabel!

    @IBOutlet weak var firstGoalLabel: UILabel!

    @IBAction func unwindToGoals(unwindSegue: UIStoryboardSegue) {

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // Automatische datumberekening
    let today = Date()
    let calendar = Calendar.current
    // Dagnummer van het jaar
    var todayNumber: Int {
        get {
            return calendar.ordinality(of: .day, in: .year, for: today)!
        }
    }
    // FLOAT MAKER: onderstaande maakt een Float van het dagnummer (nodig voor de Progress Bar uiteindelijk)
    var todayFloat: Float {
        get {
            return Float(todayNumber)
        }
    }
    // KWARTAAL PROGRESSIE: deze functie checkt eerst in welk kwartaal je zit, en vervolgens de voortgang in dat kwartaal in een float
    func percProgress() -> Float {

        if todayNumber < 91 {
            return todayFloat / 90
        }
        else if todayNumber < 182 {
            return (todayFloat - 90) / 91
        }
        else if todayNumber < 274 {
            return (todayFloat - 181) / 92
        }
        else {
            return (todayFloat - 273) / 92
        }
    }

    // Bereken aantal dagen te gaan in kwartaal
    func daysToGoCalc() -> Int {

        if todayNumber < 91 {
            return 90 - todayNumber
        }
        else if todayNumber < 182 {
            return 181 - todayNumber
        }
        else if todayNumber < 274 {
            return 273 - todayNumber
        }
        else {
            return 365 - todayNumber
        }
    }

}

// SECOND VIEW CONTROLLER

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        firstGoaltext.delegate = self
        firstGoalStart.delegate = self
        firstGoalEnd.delegate = self

        secondGoaltext.delegate = self
        secondGoalStart.delegate = self
        secondGoalEnd.delegate = self

        thirdGoaltext.delegate = self
        thirdGoalStart.delegate = self
        thirdGoalEnd.delegate = self

        fourthGoaltext.delegate = self
        fourthGoalStart.delegate = self
        fourthGoalEnd.delegate = self

        fifthGoaltext.delegate = self
        fifthGoalStart.delegate = self
        fifthGoalEnd.delegate = self

        // INSTANTIATE VIEWCONTROLLER
        let storyboard1 = UIStoryboard(name: "Main", bundle: nil)
        var firstController: UIViewController {
            get {
                return storyboard1.instantiateViewController(withIdentifier: "myViewControllerIdentifier")
            }
        }

        self.present(firstController, animated: true, completion: nil)

    }

    @IBOutlet weak var firstGoaltext: UITextField!
    @IBOutlet weak var firstGoalStart: UITextField!
    @IBOutlet weak var firstGoalEnd: UITextField!

    @IBOutlet weak var secondGoaltext: UITextField!
    @IBOutlet weak var secondGoalStart: UITextField!
    @IBOutlet weak var secondGoalEnd: UITextField!

    @IBOutlet weak var thirdGoaltext: UITextField!
    @IBOutlet weak var thirdGoalStart: UITextField!
    @IBOutlet weak var thirdGoalEnd: UITextField!

    @IBOutlet weak var fourthGoaltext: UITextField!
    @IBOutlet weak var fourthGoalStart: UITextField!
    @IBOutlet weak var fourthGoalEnd: UITextField!

    @IBOutlet weak var fifthGoaltext: UITextField!
    @IBOutlet weak var fifthGoalStart: UITextField!
    @IBOutlet weak var fifthGoalEnd: UITextField!

    @IBAction func enter(_ sender: Any!) {

        let vc1 = ViewController()
        vc1.firstGoalLabel.text = firstGoaltext.text
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        firstGoalStart.resignFirstResponder()
    }

}

extension SecondViewController : UITextFieldDelegate {

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

}

What I am doing wrong here?
Comment: Does the identifier match the corresponding identifier in InterfaceBuilder?
Comment: @vadian Yes it does. Storyboard ID in the InterfaceBuilder and Identifier are both "myViewControllerIdentifier"
Comment: first it should not be in viewDidLoad
Comment: Would it be possible to include your stacktrace?
Answer: Try running the code snippet in "viewDidAppear" instead of "viewDidLoad"

Error instantiating View Controller


thread stack access from callback after exit

Question: The following code has a callback registered for some clean-up actions.
As soon as a stop is requested, the callback is invoked from main and the thread exits.
The callback then waits a few ms and accesses the vector on the thread stack which seems invalid since the thread no longer exists.
valgrind and g++ -fsanitize=address do not report any problem and the output of size() is always as expected.
This makes me wonder if it is correct to access the vector on the thread stack as long as request_stop in main has not returned.
The output is:
thread finished 140037635319488
call back from: 140037639857984, size 1234
main finished 140037639857984

Note that the vector is accessed after the thread has finished its last line.
Question: is this code undefined behavior?
Some relevant quotes from the C++ standard might be helpful
#include <iostream>
#include <thread>
#include <vector>
#include <stop_token>
#include <chrono>

using namespace std::chrono_literals;

void thread_func(std::stop_token st)
{
    std::vector<int> v;

    std::stop_callback cb{st, [&v]
        {
            std::this_thread::sleep_for(1000ms);
            for (int i=0; i<1234; ++i)
                v.push_back(i);
            std::cout << "call back from: " << std::this_thread::get_id()
                      << ", size " << v.size() << '\n';
        }};

    while (!st.stop_requested())
    {
        // ...
    }
    std::cout << "thread finished " << std::this_thread::get_id() << '\n';
}

int main()
{
    std::stop_source src;
    auto t = src.get_token();

    auto thr = std::jthread{thread_func, t};
    std::this_thread::sleep_for(500ms);

    bool b = src.request_stop();

    std::cout << "main finished " << std::this_thread::get_id() << '\n';
}

Answer: If the callback is being run from another thread (in your case the main thread in the request_stop() call), then the destructor of std::stop_callback blocks until that call is finished and destroys the stored callable only afterwards.
Because you declared v before cb, the vector will be destroyed only after the destructor of cb returns during the stack unwinding when thread_func returns after the stop request. The thread only exits after the stack unwinding.
Comment: @Tootsie When the thread function exits its stack is unwound and all destructors of automatic storage duration variables in its scope are called in reverse order, just as for any other function. `cb`'s destructor is specified to block until the callback has been executed. The standard library will implement that e.g. with a mutex. The thread is done only after all of the stack is unwound and all destructors have finished executing.
Comment: I understand the order of destruction of `v` and `cb`, but that happens long after the thread has reached its last line (cout << thread finished). So what exactly is keeping the thread stack alive after that?


How to find a file that contains the specified string in FreeBSD?

Question: I'm searching for the way to find a file that contains specified string text.
It should be fast as possible but its not that important.
I was reading the manual, and I've build something like that: grep my_string * -r and it works at all, but if there are many directories to search.
Are there any other ways to find a file that contains specified string in FreeBSD?
Comment: @Fox FreeBSD will dig into the devices as well, but will most likely spit out a warning and move on.
Comment: The `-x` option will prevent `find` from descending into directories with device numbers different from the starting point of the find, so devices will be skipped.
Comment: there aren't many ways that could make searching for string faster, than grep. and if you want to search multiple directories, just list them ... `grep -r string dir1 dir2 dir3`, or just grep the string on the whole drive `grep -r string /` (this could take a long time though and i'm not sure if freebsd grep will dig into devices by default)
Comment: @RoyceWilliams Good point!
Answer: Did you mean:
grep -rl my_search_pattern    my_dir1 my_dir2 my_dir3 my_another_file


Web page change frequency

Question: I want to know I often I need to crawl certain webpages, to make sure I have the newest content as fast as possible.
The naïve approach to this, is to simply calculate the average over a certain period of time. However, different web pages are updated at different rates, so this wouldn't be a good fit.
I did some googling, and apparently, the Poisson distribution is a good fit for this kind of estimation. My question is, how should I calculate lambda? And it should be constantly updated, correct?
Edit:
John's answer helped me out; for further reference, check this article: Estimating Frequency of Change
Thank you
Comment: Why the Poisson? That is used for modelling counts.
Answer: Assuming what you want to do is:

Build a model of the number of updates over a time interval t, under the assumption that the number of updates follows a Poisson distribution (reasonable assumption).
Use the estimate of $\lambda$ from the model to scholastically decide whether or not to check for an update right now, based on the time since the last update

then, you can estimate $\lambda$ for a given webpage as $\sum_{k\in K} \frac{t_k}{|K|}$, where $K$ is the set of all updates you've seen on the page, and $t_k$  is the length of time that passed between update $k$ and immediately preceding update.
Of course, if $\lambda$ drifts with time, or the frequencies of updates are conditionally related to each other (which is possible for certain types of sites), then this might not be very useful. It does seem to be a standard technique for this kind of thing though, so perhaps it will be fine.

Web page change frequency


Sampling from distribution parametrized by $ \log(1-p) $ given $ \log (p) $

Question: The context for the problem is that I'm working with a modified genetic algorithm where the fitness score of each chromosome is given by a log-probability $ \log(p) \in (-\infty, 0) $. Thus, I have a categorical distribution parameterized by (unnormalized) log-probabilities. These scores are large in magnitude, so I want to be able to sample from this distribution without needing to first exponentiate and normalize, as exponentiating would lead to numerical over/underflow errors during program execution. I know that I can sample proportional to $ p $ without exponentiation by using the Gumbel-max trick.
However, what's giving me trouble is how, given this set of log-probabilities $ \log(p) $ , I would be able to sample from a distribution parameterized by $ \log(1 - p)$ . The motivation for this is that I want to "kill off" lowest-scoring chromosomes in the population, hence driving up overall population fitness. It is not possible to directly convert $\log(p)$ to $\log(1 - p)$ by logarithm rules, and as such I'm struggling to find some kind of transformation that will allow me to do this.
How should I go about thinking of a solution to this? Is this sort of thing even possible?
Comment: What distribution are you sampling from?
Comment: @Sycorax Thanks for the clarifying question -- it is not a standard distribution, and I've just added some edits to my question for some more context.
Answer:
It is not possible to directly convert $\log(p)$ to $\log(1−p)$ by logarithm rules...

Au contraire mon ami, it is indeed possible.  Since $p \geqslant 0$ you have $p = \exp(\log p)$ (allowing computation for infinities) so you can express the required quantity as:
$$\begin{align}
\log(1-p)
&= \log(1 - \exp(\log p)) \\[6pt]
&= \log(1 - \exp(-(-\log p))) \\[6pt]
&= \text{log1mexp}(-\log p). \\[6pt]
\end{align}$$
Thus, if you already have the value $a = \log p$ you can get the desired quantity as:
$$\log(1-p) = \text{log1mexp}(-a).$$
This transformation can be implemented in R using the log1mexp function in the VGAM package (also see Mächler 2012 for some discussion of computational issues for this function).  Incidentally, this function is closely related to the hyperbolic functions in trigonometry.
Comment: Hi Ben, thanks for your answer and the link to the paper. This seems like a sensible approach -- however, the issue is that it exponentiates the log-probabilities during computation. I'm dealing with fairly large log-probabilities (i.e. abs($\log (p) ) > 1000$ ), and I begin hitting numerical overflow errors for abs($\log (p) ) > 750 $.

Ideally, I wouldn't have to exponentiate at all (as is the case for the Gumbel Max Trick).


Derangement without replacement

Question:
Each of $n \geq2$ people puts his or her name on a slip of paper (no two have the same
  name). The slips of paper are shuffled in a hat, and then each person draws one (uniformly
  at random at each stage, without replacement). Find the average number of
  people who draw their own names.

Does this match the pattern of derangements? I can't wrap my head around the fact that this does not allow replacement.
EDIT 2:
Adding to the comment of @drhab.
The probability that the first person draws his own name is $\frac1n$.
By symmetry, anyone could be the first person.
So,
$$P[X_i] = \frac1n.$$
And summing over $n$ (linearity of expectation), I get $1$.
Is my approach correct? I am not super confident. I am trying to self-study probability using Blizstein's lectures and book, and I keep getting stuck in most of the questions.
Comment: Your edit 2, following the hint given by drhab below, is correct. Interestingly enough, you get the same answer regardless of whether you allow replacements (i.e. the possibility that the same name is drawn twice or more). Of course, the _distribution_ is different (for instance, without replacement it is _impossible_ that exactly $n-1$ persons draw their own name, whereas with replacement it is merely improbable), but the expectation is, apparently, the same.
Comment: I am retracting my downvote and close vote and encourage others to do the same. OP added detail and this is now an acceptable question.
Answer: Hint:
For $i=1,\dots,n$ let $X_i$ take value $1$ if person $i$ draws his own name, and let it take value $0$ otherwise. Then if $X$ denotes the number of persons that draw their own names: $$X=X_1+\cdots+X_n$$
Now find $\mathbb EX$ by means of linearity of expectation and symmetry.
Answer: A derangement is a permutation of a set of distinct objects such that no object ends up in its original position. In this case, shuffling the names and having each person draw one is a permutation. A derangement would be no person drawing their own name.
The average number of people who draw their own name can be found the following way:
Consider the $(m+1)$th person out of $n$. What is the chance they draw their own name, given their name one of the $n-m$ still in the hat? What is the chance their name has not already been one of the first $m$ drawn out of the hat? Multiply these together and you get the probability the $(m+1)$th person draws their own name. Then sum the products over all $n$ people and you get the average number who draw their own name.

Derangement without replacement


8.40 proof Axler: How to understand

Question: At the start of the proof of minimal polynomial, $T \in \mathcal{L}(V)$ is defined with $dim V=n$. So that the list $I,T,T^2,...,T^{n^2}$ is not linear independent in $\mathcal{L}(V)$, because the vector space $\mathcal{L}(V)$ has dimension $n^2$. I don't really see why the list is not linear independent.
Comment: There are $n^2 + 1 > n^2$ terms in the list (don't forget to count $I$). Surely that makes the list linearly dependent?
Comment: What specifically are you doubting? Is it the assertion that $\dim V = n \implies \mathcal{L}(V) = n^2$?
Comment: I edited the question, i'm wondering why the list is not linear independent.
Comment: Oh I didn't notice that, thanks for pointing out!
Answer: If $\{v_1,\ldots,v_n\}$ is a basis of $V$, define, for each $i,j\in\{1,2,\ldots,n\}$, $E_{ij}\colon V\longrightarrow V$ such that $E_{ij}(e_i)=e_j$ and that $E_{ij}(e_k)=0$ if $k\ne i$. Then $\{E_{ij}\mid i,j\in\{1,2,\ldots,n\}^2\}$ is a basis of $\mathcal L(v)$ and therefore $\dim\mathcal L(V)=n^2$. So, any set of elements of $\mathcal L(v)$ with more than $n^2$ elements is linearly dependent.

8.40 proof Axler: How to understand


gnuplot date with dashes then time

Question: I am still struggling.  It just seems either create nothing or
a plot with everything jammed into a single period.
The line data is supposed to be
YYYY-MM-DD,HH:MM,HH:MM,n.nn,kwh.
where the hours and  minutes are start and end times.
I just want the start  ( or end ) time, not the interval.
And to plot the date time and usage in kwh ( the n.nn) value
My sample plot script is.
#Sat Oct  1 03:28:14 PM EDT 2022
# plot usage 15 minute intervals
# first line ( without the #
#2021-09-08,00:00,00:14,0.69,kWh,
# last line
#2021-10-06,23:45,23:59,0.21,kWh,
set terminal png size 1920,1280

#set timefmt "%m/%d/%Y"
set timefmt "%Y-%m-%d,%H:%M"
#set timefmt "%Y-%m-%d"

set xlabel "Date"
set xrange ["2021-09-08,00:00":"2021-10-06,23:45"]
#set xrange ["10/07/2019,00:00":"09/07/2022,23:59"]  # no errors and no data x range is  10:9

set ylabel "Interval usage KWH"
set datafile separator ","
set title "AEP Interval"
set output "Interval.png"
plot "aepo_electric_interval_data_Service_1_2021-09-08_to_2021-10-06.csv" using 1:4

This generates
$ ./intervalPlot
"./intervalPlot" line 24: Can't plot with an empty x range!
I tried using 1:3 and using 1:2... no joy
Answer: You were close. I see two minor problems:

You need to tell gnuplot what to do with the time format. In this case you want to use it for the x-axis coordinate, so the command is set xdata time.
There is a missing keyword using.

    set timefmt '%Y-%m-%d %H:%M'
    set xdata time
    plot "interval.csv" using 1:4 with linespoints

Also, if that really is a csv file, you may also need to give the field separator character (tab, I suppose?).
set datafile separator tab

gnuplot date with dashes then time