uncountable number of Penrose tiling

Question: I am interested in Penrose tiling, though I am not an expert, so I apologize in advance.
It is known that that the number of different Penrose tilings is uncountable. This may be implied from de Bruijn method, of inducing these tilings from a cross section of a regular (cubic) tiling in 5 dimensions (But maybe I am mixing here between the two areas, since it is not clear for me from de Bruijn method if the size of the tiles themselves vary for each cross-section). However, in Martin Gardner's book "Penrose Tiles to Trapdoor ciphers" (or PDF of first two chpters), the author describes a way of Conway to prove – in another way – that the number of different Penrose tilings is uncountable.
However, this method is completely unclear for me. Here is the description of Gardner for Conway's method:

Conway's proof of the uncountability of Penrose patterns (Penrose had earlier proved it in a different way) can be outlined as follows. On the kite label one side of the axis of symmetry $L$, the other $R$ (for left and right). Do the same on the dart, using $l$ and $r$. Now pick a random point on the tiling. Record the letter that gives its location on the tile. Inflate the pattern one step, note the location of the same point in a second-generation tile and again record the letter. Continuing through higher inflations, you generate an infinite sequence of symbols that is a unique labeling of the original pattern seen, so to speak, from the selected point.
[…] Not all possible sequences of the four symbols can be produced this way, but those that label different patterns can be shown to corespond in number with the number of points on a line.

How does this method induce a bijective function to the points on the line?
Comment: The first 3 pages of [this paper](http://ect.bell-labs.com/who/emina/papers/wsp.pdf) outline the proof much more clearly.
Answer: The set of tilings (which I'll call $T$) corresponds in number to the points on a line, so this essentially claims that $\lvert T\rvert=\lvert\mathbb R\rvert=\mathfrak c$. Instead of actually establishing a bijection, you can also establish two injections.
Upper bound on the cardinality
$\lvert T\rvert\le\lvert\mathbb R\rvert$ is easy: interpret $L,R,l,r$ as digits $0,1,2,3$ and the whole infinite sequence as a decimal fraction. Since the digit $9$ does not occur, you don't have to worry about things like $0.99\!\ldots=1$ so you know that every infinite sequence corresponds exactly to one real number. So you have an injective map from $T$ to $[0,1)\subset\mathbb R$.
Uncountability of sequences
$\lvert T\rvert\ge\lvert\mathbb R\rvert$ is harder. You could interpret rational numbers as fractions with base $4$, so every digit would correspond to one of the letters. You could also do the following preprocessing:
$$f(x):=\begin{cases}
L,g(x)   &\text{if } x\in[0,1) \\
R,g(1/x) &\text{if } x\in[1,\infty) \\
l,g(-x)  &\text{if } x\in(-1,0) \\
r,g(-1/x)&\text{if } x\in(\infty,-1]
\end{cases}$$
This will map any $x$ to the range $[0,1]$ which can then be used as input to the second function $g$ that represents that number in base $4$ and thus turns it into a sequence. You could write $1=0.333\!\ldots_4$ or tweak the definition of $f$ a bit (e.g. using $1-g(1/x)$ in the second case) to ensure that you only translate numbers from the range $[0,1)$ so that you can concentrate on the digits after the point.
Uncountability of point labels
So at this point, you have an injective function from $\mathbb R$ to infinite sequences in these four letters. But now you have a technical problem:

Not all possible sequences of the four symbols can be produced this way

You have to work out the exact conditions of which sequences can and which can not be produced in this way. My guess is that you can show that there are only countably many forbidden sequences, so the remaining sequences would still be uncountably many.
Uncountability of tilings
As Daniel reminded me in a comment, what we have worked to so far (at least if you manage to show the countability of the sequences which are not tilings) demonstrates that there are uncountably many sequences describing a pattern seen from a given tile. But there are infinitely many tiles from which you could label the pattern and it would still be the same pattern that should be counted only once.
Two sequences denote the same pattern if they agree after some point $k$. So you can generate alternate labels for the same pattern by subsequently modifying elements of the sequence, starting at the first. You have four options for the first sequence item, and for each of them four for the second, and so on. You could explore all possible sequence modifications in a breadth first search, therefore there are only countably many (i.e. $\lvert\mathbb N\rvert=\aleph_0$) of these.
So why does that not break the uncountability of $T$? I'm not sure how you feel, but (at least at the moment) a counter-argument works best for me. Suppose there were only countably many tilings in $T$, represented by any suitable sequence for each. Then you could use the common $\mathbb N^2$ iteration: Take the original label of the first tiling, then the original label of the second tiling followed by the first modification of the first tiling, then the original label of the thirs tiling followed by the first modification of the second tiling followed by the second modification of the first tiling, and so on. In the end you'd enumerate all point labels, so there could only be $\lvert\mathbb N^2\rvert=\lvert\mathbb N\rvert=\aleph_0$ of these. This is a contradiction to the uncountability of label sequences we showed before.
Now that I think about it, this only shows $\lvert T\rvert>\aleph_0$ but one would need the continuum hypothesis to deduce $\lvert T\rvert=\mathfrak c$ from this. So if anyone has a better explanation (which still works on an intuitive level) of why $\mathfrak c/\aleph_0=\mathfrak c$ feel free to edit this post, comment, or provide your own answer.
Comment: @MvG: Thanks for extended answer. However, the set of the sequences which are not tilings (using Soljanin notation) is the set of the sequences of 0 and 1 which contain the sequence 11. I am pretty sure that this set is uncountable also, right? (just take the sequences that start with 11, and you may have any sequence you'd like).
Comment: (...cont.) For instance if $s=00100010010100001\ldots$ then $d(s)=(2,3,2,1,4,\ldots)$. If $s$ begins with a $1$ then we set $n_0=0$. It's clear that $d(s)$ completely determines $s$, and every possible sequence of positive natural numbers is associated to an admissible $s$. The set of all sequences of positive naturals is uncountable, and so then must the sequence of admissible sequences.
Comment: There is a slight caveat in this which Gardner seems to ignore. If you choose a different point in your tiling, it will correspond to a different sequence of symbols. We should really be quotienting out by the relation that two sequences are equivalent if and only if they are eventually equal for all terms past some $k$th term. One can show that these equivalence classes are independent of the choice of starting point, and only rely on the tiling. Because these equivalence classes are countable, this does not affect the final counting argument.
Comment: Thanks. The article of Soljanin suggests that the set of Penrose tilings has the same cardinality of the set of all sequences $\{x_n \}$ composed of $0$ and $1$ s.t. if $x_n=1$ then $x_{n+1}=0$. So the problem reduces to prove that this set has cardinality $\aleph$.
Comment: @Daniel: Thanks for reminding me! I had thought about that at some point, but forgot about it while reading the paper you suggested.
Comment: @Daniel: That modding out of equivalence classes is a bit harder than I anticipated at first. It made me realize that I don't understand division of cardinals, so I posted [a new question](http://math.stackexchange.com/q/920468/35416) for that.
Comment: @David: I guess you are right. But once I get [my question about the division of cardinals](http://math.stackexchange.com/q/920468/35416) answered, we could use that together with the fact that for every allowed sequence, there is at most a countable number of forbidden ones. That is again easy to show. Of course, if after reading that paper you gain a new understanding which doesn't rely on division of cardinals, feel free to post your own answer, summing up your understanding.
Comment: @David Yes you are right, the set of admissible sequence, and disallowed sequences are both uncountable. You've already shown that there are an uncountable set of disallowed sequences, so it remains to show the complement is uncountable. Let $s$ be a sequence of $0$s and $1$s such that no consecutive pair of $1$s occurs in $s$ and suppose also that no infinite string of $0$s occurs (just to make life easier). Then $s$ has an associated sequence $d(s)$ of positive natural numbers $n_0,n_1,n_2,\ldots$ corresponding to the number of consecutive $0$s that occur between all $1$s.
Comment: @ Daniel: a beautiful argument! thank you.
Comment: @Daniel: With all the things you contributed, do you want to write your own answer? These things shouldn't stay hidden in the huge list of comments.
Comment: @David Just to pique your interest: There is actually a subset of the admissible sequences called the *Sturmian* sequences which have the neat property that if you take the positive first difference between the elements of the derived sequence $d(s)$, then you end up with another admissible sequence, and this process can be continued indefinitely. There are very good reasons to think of these sequences as $1$-dimensional versions of the Penrose tilings (for instance they have an expansion-substitution rule and can be defined in terms of cut and project rules).
Answer: Here is a nice general statement:
Claim: If $T$ is an FLC, aperiodic, repetitive tiling, then there are uncountably many tilings (taken up to translation) which are locally isomorphic to $T$.
Any given Penrose tiling $T$ is FLC, aperiodic and repetitive, and any other tiling $T'$ is a Penrose tiling if and only if $T$ and $T'$ are locally isomorphic.
Some explanation of these terms is in order.

By a tiling I mean a covering of some Euclidean space $\mathbb{R}^d$ by tiles - each of which are bounded subsets of $\mathbb{R}^d$ and are the closures of their interiors - which do not intersect on anything more than their boundaries.
A tiling is finitely locally complex, or FLC, (with respect to translations) if, for any given radius $R$, there are only finitely many $R$-patches. By an $R$-patch I just mean some set of tiles of $T$ given as precisely the set of tiles intersecting some ball of radius $R$. You should be able to easily convince yourself that a sufficient condition for FLC is that the tiles of $T$ are polygonal, meet face-to-face, and that there are only finitely many patches consisting of two tiles meeting along a common face (up to translation).
A tiling is aperiodic, here, if there does not exist some non-zero vector $x$ such that $T=T+x$.
A tiling is repetitive (with respect to translations) if, for any given $R$, there exists some $R'$ such that every $R$-patch, up to translation, can be found in every $R'$-ball. Of course, assuming that the tiles can't be arbitrarily small, this easily implies that the tiling is FLC. In this case repetitivity asks that, in addition to only having finitely many $R$-patches, these $R$-patches can also be found relatively densely within the tiling (this is a nice notion of "order" of the tiling: being repetitive and aperiodic is special!).
We say that $T$ and $T'$ are locally isomorphic if every $R$-patch of $T$ is an $R$-patch of $T'$, and vice versa. In other words, if you lived in either $T$ or $T'$, then you would not be able to rule one of them out using only local information to any given finite radius. Note that if a tiling is admitted by some local matching rules, so that tiles meet in some agreed way, then of course the same is true of any locally isomorphic tiling (so if your definition of a Penrose tiling is anything which can be constructed from Penrose tiles, then it is clear that any tiling locally isomorphic to a Penrose tiling is also a Penrose tiling).

Proof of claim: Let $T$ be given, satisfying the conditions of the claim. First, let's pick a control point in the interior of each translation-class of tile. We shall only consider tilings for which a control point corresponding to the central tile lies on the origin.
Of course, any locally isomorphic tiling corresponds to some sequence of $1$-patch centred at the origin, followed by a $2$-patch centred at the origin, followed by ..., where the $n$-patch centred at the origin is an extension of the $(n-1)$-patch. Conversely, given such a sequence, it isn't too hard to see that it must be locally isomorphic to $T$ (by repetitivity, every finite sub-patch of $T$ must be found in the tiling defined by such a sequence). Let's count the number of such sequences.
Suppose that for each $n$-patch $P$ there exist at least two distinct ways of extending it to some $(n+c_P)$-patch, for some $c_P>0$. Since there are only finitely many $n$-patches by FLC, there exist at least two distinct ways of extending any given $n$-patch to an $(n+c_n)$-patch, where $c_n>0$ is just the maximum of the $c_P$ ranging over $n$-patches $P$. We see that the number of sequences is at least as large as the set of countable sequences over a two-element set, and $|2^{\mathbb{N}}|$ is uncountable. Note that there are only countably many control points in any given tiling, so the number of tilings taken up to translation must still be uncountable.
So we see that we just need to show that any given $n$-patch of $P$ has at least two distinct extensions. Suppose not. Then there exists some $P$ which can be only extended in some unique way. By repetitivity, there exist at least two distinct control points $x$ and $y$ in $T$ whose $R$-patches are translates of $P$. But since $P$ can only be extended uniquely, we must have that $T-x$ and $T-y$ are equal, so $T = T + (y-x)$, which contradicts aperiodicity.

Let me just note a couple of things following that proof. Firstly, of course, aperiodicity is necessary to have uncountably many locally isomorphic tilings. What we seem to see from the proof is that, in fact, we only need the slightly stronger condition (let's call it (C)) that every translation-class of finite patch has at least two distinct extensions. Actually, this doesn't quite follow from this proof, because a consistent sequence of patches of the tiling need not be locally isomorphic to the original (but it will be "locally derivable" from it: all of its finite patches are finite patches of $T$). So replacing repetitive with (C) and locally isomorphic with locally derivable still allows for the same simple proof.
As an example of an aperiodic tiling not satisfying (C), take a periodic square tiling, but then colour one unique square differently to all of the others (or add a "notch" to it, if you want to force everything geometrically). Then this tiling is FLC and aperiodic but doesn't satisfy (C). And, of course, there are only countably many tilings which are locally isomorphic (or even derivable) to it.
[Edit: I guess that I've only shown that there are at least $|2^{\mathbb{N}}| = |\mathbb{R}|$ translation-classes of tilings in the above proof. But you should easily be able to see that there can only be at most $|\mathbb{N}^{\mathbb{N}}| = |\mathbb{R}|$. Indeed, a locally isomorphic tiling with control point at the origin is described by a finite sequence of choices of central $n$-patch, with $n \in \mathbb{N}$.]
Finally, let me note that the Penrose tilings satisfy the conditions of the claim. This follows easily from their description as either a substitution (or hierarchical) tiling, or as a cut-and-project tiling.
Answer: Background
Ok, the first thing we need here, which is actually a common, but sometimes hard to prove, property for a substitution tiling, is that the substitution (or expansion rule) is recognizable. What does recognizable mean? It means that the substitution has an inverse - this can be made precise if we place a metric on the space of all tilings (See my answer to this question) - but for our purposes we'll just say that a recognizable tiling is a tiling where there is a way of taking a tiling, deleting some edges and deflating so that we again end up with a tiling by the same prototile set, and if we compose this process with the substitution then it acts as the identity on the tiling.
What is it that recognizability affords us? Well it means that if we have a tiling $\mathcal{T}$ and we choose some tile $T$ in $\mathcal{T}$, there is a well defined, what is known as a, $1$-supertile $T_1$ containing $T=T_0$, and because we can continue the process, also a $2$-supertile $T_2$, $3$-supertile $T_3$, etc. The $1$-supertile is just the new expanded tile that $T$ is a subset of when we delete the edges during the inverse substitution process.
That the Penrose tilings are recognisable is a non-trivial problem that requires proof. There may be an elementary way which is special to the Penrose tiling, but there is also a theorem of Mossé, and generalised by Solomyak$^{[1]}$, which says that any aperiodic, locally-finite, primitive substitution tiling of $\mathbb{R}^n$ is recognizable (the Penrose tilings satisfy these properties).
The Proof
Now that we know every tile $T$ in a Penrose tiling $\mathcal{T}$ has a well defined sequence of $n$-supertiles $T_n$, we can associate to every pair $(\mathcal{T},T)$ that sequence. We'll call it $s(\mathcal{T},T)$. The first thing we need to show is that for all $T,T'\in\mathcal{T}$, we have that there exists a $k\geq 0$ such that $$\sigma^k(s(\mathcal{T},T))=\sigma^k(s(\mathcal{T},T'))$$ where here $\sigma(a,b,c,d,\ldots)=(b,c,d,\ldots)$ is the shift function on sequences. This is easy to see though because if $T$ and $T'$ are tiles in a fixed Penrose tiling $\mathcal{T}$, then they are both contained in some ball $B$ in the plane. I claim (and you should prove) that $B$ is fully contained in some $k$-supertile $\hat{T}$. It follows from recognizability that $T_{k}=\hat{T}=T'_{k}$ and so $T_l=T'_l$ for all $l\geq k$, hence $\sigma^k(s(\mathcal{T},T))=\sigma^k(s(\mathcal{T},T'))$.
The next thing we need to figure out is when a sequence $s$ is actually associated to a Penrose tiling. As discussed in Soljanin's paper$^{[2]}$, If we assign one tile the symbol $0$, and the other the symbol $1$, then it can be shown that the only admissible sequences (those associated to a Penrose tiling) are those which do not have the substring $11$ appearing in the sequence. Let's call the set of admissible sequences $A=\{s\mid 11 \mbox{ does not appear in }s\}$.
A non-trivial question to ask is, given an admissible sequence, is its associated Penrose tiling unique? The answer is yes, and the proof is quite obvious. An admissible sequence tells you exactly how to lay down tiles to build your tiling. It's essentially a set of instructions for building a Penrose tiling. The tile $T_0$ is what you place at the origin, $T_1$ is the $1$-supertile you cut up and extend away from $T_0$, and so on. The caveat here is that it's possible these supertiles will only extend off in one direction and not cover the entire plane. I won't go into details as to why this isn't a problem, but just note that we can always fix this problem using a technique known as collaring (See Anderson and Putnam's paper$^{[3]}$ for more details).
So, we have a well defined bijection $A\to\{(\mathcal{T},T) \mid \mathcal{T} \mbox{ is a penrose tiling}, T\in \mathcal{T}\}$. From our discussion about choosing different tiles as the 'seed tile' $T_0$ for a specific tiling, we then also get a bijection $A/{\sim}\to\{\mathcal{T} \mid \mathcal{T}\mbox{ is a Penrose tiling}\}$ where two sequences $s,s'$ are related by $\sim$ here if there exists a $k$ such that $\sigma^k(s)=\sigma^k (s')$, so $A/{\sim}$ is the set of classes of eventually equal admissible sequences.
Counting Argument
Claim: $A$ is uncountable.
Proof: Let $s$ be in $A$ (and also just to make life easier assume that there is no $k$ such that $\sigma^k(s)\neq 000\ldots$ - in the end this only accounts for a single equivalence class so we can ignore it). Then $s$ has an associated sequence $d(s)$ of positive natural numbers $n_0,n_1,n_2,\ldots$ corresponding to the number of consecutive $0$s that occur between the $1$s which appear in $s$. For instance if $$s=00100010010100001\ldots$$ then $$d(s)=(2,3,2,1,4,\ldots).$$
If $s$ begins with a $1$ then we set $n_0=0$. It's clear that $d(s)$ completely determines $s$, and every possible sequence of positive natural numbers is associated to an admissible $s$. The set of all sequences of positive naturals is uncountable, and so then must the sequence of admissible sequences $A$.
Claim: $A/{\sim}$ is uncountable.
Proof: Let $s$ represent an equivalence class in $A/{\sim}$. Let $F$ be the set of all finite strings of $0$s and $1$s. There is an injective function $[s]_{\sim}\to F$ given by assigning to $s'\in[s]_{\sim}$, the shortest initial substring that can be replaced in $s'$ to recover the sequence $s$. As $F$ is countable, it follows that $[s]_{\sim}$ is countable for all $s\in A$.
Now, suppose that $A/{\sim}$ is not uncountable, then it is countable and so $A$ can be written as a countable disjoint union of countable sets. This would imply that $A$ is countable which contradicts the previous claim. It follows that $A/{\sim}$ must be uncountable.
Conclusion: As a corollary we conclude that $\{\mathcal{T} \mid \mathcal{T}\mbox{ is a Penrose tiling}\}$ is uncountable.

$[1]$ B. Solomyak. Nonperiodicity implies unique composition for self-similar translationally finite tilings. Discrete Comput. Geom. 20 (1998), 265–279.
$[2]$ E. Soljanin. Writing Sequences on the Plane. IEEE Trans. Inf. Thy. 48 (2002), 1344-1354
$[3]$ J. E. Anderson and I. F. Putnam. Topological invariants for substitution tilings
and their associated $C^*$-algebras. Ergodic Theory Dynam. Systems, 18(3) (1998), 509-537.
Comment: I actually have another question: since the $d(s)$ seq' for the SUN and the STAR patters are resp. 2,3,3,3... and 0,3,3,3,... can one induce from these patterns the fact that these are the only tilings with 5-rotational symmetry (just by looking on the $d(s)$'s?
Answer: It's hard to imagine there is an infinite number of tilings even though any finite stretch of tiling is contained (infinitely many times) in every tiling.
But think of it like this:
Any finite number of digits is in pi
Any finite number of digits is in √2
But all the digits of pi are not in √2, no matter where you start.
I still find it hard to imagine: in every tiling, every stretch of tiles is circled by a stretch of obtuse rhombi. So even if I don't know where I am in the bigger stretch of rhombi, I know I'm contained in one. And another one above that. And another one above that. Ad infinum.
I might be at any place in the complete tiling, but I know I'm encircled by an infinite number of rhombus-stretches. So how are they different?
The thing you don't know, is that every tiling is symmetrical, that every tiling has a symmetrical center.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

uncountable number of Penrose tiling


How can I autoplay media in iOS >= 4.2.1 Mobile Safari?

Question: I cannot seem to get audio media to play in Mobile Safari on iOS 4.2.1 in any situation other than the handler of a click event performed by the user.  Even then, if player.play() is called in any asynchronous fashion (ajax, setTimeout, etc) it doesn't work.
I've tried calling player.load() before player.play(). I've tried triggering a click event on a dom element whose handler calls player.play(). I've tried using both audio and video tags.
All the loopholes that worked prior to iOS 4.2.1 seem to be closed. Any ideas?
Comment: I understand it's by design. However, prior to 4.2.1 there were several loopholes that allowed circumvention. FWIW, I'm not actually trying to autoplay audio on page load. The audio source urls I'm using are unstable and cannot be cached, so I'm making an ajax call inside the click handler to resolve the audio source.  This in itself is enough to trigger iOS's defense mechanisms apparently.
Comment: I spent about an hour today shuffling code around because I had the `play()` function within an asynchronous function (Ajax call).  Even in a click handler, with an actual click, it still didn't work.  So: beware, I guess.  I wish Apple would publish the specific criteria we need to follow.
Comment: Pretty sure that's by design. Some of your users may be on cell plans that charge by data usage, and they don't want your media to auto-play.
Comment: possible duplicate of [Autoplay an Audio File on Mobile Safari](http://stackoverflow.com/questions/2841966/autoplay-an-audio-file-on-mobile-safari)
Answer: Starting from iOS 4.2.x, the download of media will not be started if there isn't a user-input event, like touchstart.
So the answer is no, there is no method to autoplay media by JavaScript or something else.
Comment: azure_ardee - see this http://developer.apple.com/library/safari/#documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW1
Comment: Any official links from Apple saying this? Just to satisfy the higher ups ;) Thanks!
Comment: @ArdeeAram This link from Apple explains how video with audio not muted can't be autoplayed without user interaction. https://developer.apple.com/documentation/webkit/safari_tools_and_features/delivering_video_content_for_safari
Answer: There is one way to play the video/audio file automatically on 4.2.1. Create an iframe and set its source to the media file's URL and append the iframe to the body. It'll be autoplay.var ifr=document.createElement("iframe");
ifr.setAttribute('src', "http://mysite.com/myvideo.mp4");
ifr.setAttribute('width', '1px');
ifr.setAttribute('height', '1px');
ifr.setAttribute('scrolling', 'no');
ifr.style.border="0px";
document.body.appendChild(ifr);
Comment: works fine for audio, but video player is not loaded on the iPhone
Comment: I can confirm that this works on the iPad, but it seems to force a reload of a sound each time that it it played. Are there any workarounds that allow it to cache the sound, so that it gets played instantly.
Comment: GREAT! It works! Tested on iOS 4.3.5 (iPod Touch 4). No loop, BTW.
Comment: Also, if you create 2 iframes, only the last one really plays.
Answer: As others have said here and according to Apple documentation, MobileSafari does NOT support the autoplay attribute in the video tag. However, in iOS 6 it DOES work. This appears to be a bug which Apple fixed in iOS 6.0.1 (and presumably in iOS 6.1).
Don't rely on autoplay working in iOS 6 if you happened to stumble across it working in iOS 6.0.
-Michael
Answer: As a workaround, I tried tying the load()/play() code to a click event, and then triggering the click event programmatically.  This approach worked in Desktop Safari, but not Mobile Safari.
Answer: This worked on the iPad until last nights 4.2 upgrade:
$(function() {
    var Beep = document.createElement('audio');
    Beep.setAttribute('src', 'beep-23.mp3');
    Beep.load();
    Beep.play();
}

My Beep.play(); still works for a click event, but the initial Beep.play() stopped working...
Answer: How about this?
Create an audio sprite with Sound Manager 2, preload & cache it from the first user interaction, and then play as and when needed.
Would that work?
Comment: It works!!! Only the first sound needs to be linked to a user interaction, any subsequent sounds following can be played automatically.
Comment: Unfortunately, this requires you to stop the sound, and then play so won't work. The answer above is right. There is no way :/
Answer: Autoplay is supported (in my tests) with an iPhone 5 (iOS 6) using the headphone jack.
Answer: On my 3rd-gen iPad running IOS 6, autoplay of HTML5  tags has suddenly begun working!  (I've had IOS 6 installed for a couple of weeks, and am pretty sure I tested this feature right away, but only noticed it working tonight.)  I don't recall seeing any notice of this from Apple, although I did see that mobile Safari had been granted the ability to support file uploads via
<form><input type="file" .../></form>

-- another feature I needed but which Apple had withheld.
Comment: Surprised by the downvotes. This was an accurate and useful answer because autoplay did work in iOS 6. Helpful to me since it explained why I was pulling my hair out transitioning from 6.0 to 6.0.1 (see [Micheal Johnston's answer](http://stackoverflow.com/a/13483720/1110547) for more specifics).
Answer: Please Try this Code it is working both version, you need to add the audio control dynamically in page. it is working.
var isiPad = false;
if (navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i)) {
    isiPad = true;
}
$(function() {
    if (isiPad) {
        var audioElement2 = document.createElement('audio');
        audioElement2.setAttribute('src', 'img/bgsound.mp3');
        audioElement2.controls = true;
        audioElement2.loop = true;
        audioElement2.load();
        audioElement2.play();
    }
});


Excel 2016 VBA Automatic Time Insertion

Question: I have looked around for an answer on the web but have not found any help regarding what I am attempting to do. I want the time to automatically be entered into the corresponding cell in column B when the column A cell is modified, the same applies for Columns C and D. I do not want the time to update, which is the issue that I am currently encountering. Below is the code I currently have:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Target.Column = 1 Then
    Target.Offset(, 1) = Time
ElseIf Target.Column = 3 Then
    Target.Offset(, 1) = Time
End If
Application.EnableEvents = True
End Sub

This coding works, but it updates the time in columns B and D, which is what I do not want. What could I add to stop the updating of the time?
Thank you <3
Comment: Try `Target.Offset(, 1).value = Now()`
Comment: what do you mean by *I do not want the time to update*? do you mean that only if the B (or D) cell was empty, only then you want to insert the time?
Comment: I wanted it so that the initial time would be inserted and afterwards would not be updated from modifying the cells within the A and C columns. Miqi180's answer fixes what I had and it works the way I want it to.
Answer: If I understand your question correctly, you only want to update the time if no time is already shown in the adjacent column? In that case this should work:
Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    If Target.Column = 1 Or Target.Column = 3 Then
        If Target.Offset(, 1) = vbNullString Then Target.Offset(, 1) = Now()
    End If
    Application.EnableEvents = True
End Sub

This is in line with Gary's Student's answer, but adds the conditional and simplifies the code a bit.
Comment: Thank you Miqi180! Your answer is what I was looking for and works great, thanks again! <3

Excel 2016 VBA Automatic Time Insertion


Running many multiple regressions at once in R

Question: I want to run time series regressions (Fama-French three factor with my new factor). I have following tables.
Table01

    Date     Port_01  Port_02 --------- Port_18
    01/1965     0.85    0.97               1.86
    02/1965     8.96    7.2                0.98
    03/1965     8.98    7.9                8.86

Table 02

    Date        Market   SMB    HML     WXO
    01/1965      0.85    0.97    0.86    0.87
    02/1965      8.96    7.2     0.98    0.79
    03/1965      8.98     7.9    8.86    0.86

Table 01 is my Y variable and Table 02 is my independent variables. I want to regress 18 portfolios on factors on Table 02. I want the intercepts to be stored in a vector (N x 1). and residuals to be stored in a matrix (T x N), check the image. I know how to run regression individually. But It there must be a better way to do. Please help me. Thanks in advance.
Comment: Are you asking for code? If so, this is the wrong site.
Comment: @Arun Jose.Yes it would be great to know the codes. if this site is not suitable for that, then what would be? please help me. Thanks
Answer: In short, yes, there's an easy way to do the calculations for many regressions with the same X-matrix but different $y$'s, especially if you have software that gives you access to the calculations it does.
More specifically, typically regressions are done these days using QR decomposition. Similar manipulations are available for other methods (such as a regression that was done via a Choleski decomposition on an $X^\top X$ matrix, for example, or for other decompositions of the $X$ matrix).
With the least squares normal equations you seek to solve $X^\top X\, \hat\beta=X^\top y$
A $QR$ decomposition would write $X=QR$ where $Q$ is an orthogonal matrix and R is upper triangular.
So this gives $R^\top Q^\top Q R \hat\beta = R^\top Q^\top y$
But $Q^\top Q=I$, so this reduces to solving
$R^\top R \hat\beta = R^\top Q^\top y$
Premultiplying by $(R^\top)^{-1}$, this can be further reduced to solving $R \hat\beta = Q^\top y$
Now $R$ and $Q$ are the same for every regression, it's only $y$ that changes, and because $R$ is upper triangular, the sequence of back-substitutions to solve for it is very fast and simple.
The $QR$ decomposition itself is relatively expensive but you only need to do it once.
Other regression quantities may be similarly obtained. For example, the variance-covariance matrix of parameter estimates is (apart from a scaling factor of $\hat{\sigma}^2$) the same for each regression.
Many packages will happily give you the QR decomposition and some will give it as a by product of a regression. (In R, the qr function performs QR decomposition and lm returns the QR decomposition of the X matrix in the regression in a compressed form -- the Q matrix is not explicitly given, but exists in an implicit form. See the help on both for more information.)
I wouldn't generally suggest explicitly forming $R^{-1}Q$ in general; solving the system once you have $Qy$ is relatively pretty fast, if you do it sensibly (i.e. using a solver that takes advantage of the triangular matrix -- rather than trying to form an inverse of $R$ for example).
Comment: In R, you can just pass a matrix of dependent values to `lm` and the function will use what you have outlined here. I would have suggested it, but OP was asking about "time series regressions".


Generalized Additive Model interpretation with ordered categorical family in R

Question: I am having a difficult time interpreting the gam.plots produced by the plot() function in the package mgcv in R—specifically, plots from an ordered regression model using the family ocat. I know how to interpret the plots when i'm doing a usual gaussian or glm-family gam. It is specifically the ordinal regression that is tricky for me.
Here is an example of the gam.plot that is produced based upon the code in the R documentation (https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/ocat.html):

The documentation says: "Family for use with gam, implementing regression for ordered categorical data. A linear predictor provides the expected value of a latent variable following a logistic distribution. The probability of this latent variable lying between certain cut-points provides the probability of the ordered categorical variable being of the corresponding category."
At the same time it also says that the link function is the identity function.
I don't know if it makes any sense to transform the response in some way? If not, how should I interpret these plots?
Maybe I should also add that when I fit a cummulative-link model in R using the clmm() function from the ordinal package the regression models use a 'logit' link function, and require you to exponentiate the b-coeffecients to get interpretable results. I suspect this is not the case with gams.
Answer: In these models, the linear predictor is a latent variable, with estimated thresholds $t_i$ that mark the transitions between levels of the ordered categorical response. The plots you show in the question are the smooth contributions of the four variables to the linear predictor, thresholds along which demarcate the categories.
The figure below illustrates this for a linear predictor comprised of a smooth function of a single continuous variable for a four category response.

The "effect" of body size on the linear predictor is smooth as shown by the solid black line and the grey confidence interval. By definition in the ocat family, the first threshold, $t_1$ is always at -1, which in the figure is the boundary between least concern and vulnerable. Two additional thresholds are estimated for the boundaries between the further categories.
The summary() method will print out the thresholds (-1 plus the other estimated ones). For the example you quoted this is:
> summary(b)

Family: Ordered Categorical(-1,0.07,5.15)
Link function: identity

Formula:
y ~ s(x0) + s(x1) + s(x2) + s(x3)

Parametric coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)   0.1221     0.1319   0.926    0.354

Approximate significance of smooth terms:
        edf Ref.df  Chi.sq  p-value
s(x0) 3.317  4.116  21.623 0.000263 ***
s(x1) 3.115  3.871 188.368  < 2e-16 ***
s(x2) 7.814  8.616 402.300  < 2e-16 ***
s(x3) 1.593  1.970   0.936 0.640434
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Deviance explained = 57.7%
-REML = 283.82  Scale est. = 1         n = 400

or these can be extracted via
> b$family$getTheta(TRUE) ## the estimated cut points
[1] -1.00000000  0.07295739  5.14663505

Looking at your lower-left of the four smoothers from the example, we would interpret this as showing that for $x_2$ as $x_2$ increases from low to medium values we would, conditional upon the values of the other covariates tend to see an increase in the probability that an observation is from one of the categories above the baseline one. But this effect is diminished at higher values of $x_2$. For $x_1$, we see a roughly linear effect of increased probability of belonging to higher order categories as the values of $x_1$ increases, with the effect being more rapid for $x_1 \geq \sim 0.5$.
I have a more complete worked example in some course materials that I prepared with David Miller and Eric Pedersen, which you can find here. You can find the course website/slides/data on github here with the raw files here.
The figure above was prepared by Eric for those workshop materials.
Comment: Just to clarify: Since, as RNB pointed out, the latent variable follows a logistic distribution, the linear predictor represents the log odds of belonging to a higher category, correct? For example, as $x_1$ increases, we would see a roughly linear increase in the log odds of belonging to a higher category.


What does this note - B# - mean?

Question: I'm confused as to how I should play the second note below, B#. Does it mean it's C? It is possible? In which case, why is it written like this, and not just C?

Sonata quasi una Fantasia, First movement (Moonlight Sonata, Beethoven, OP.27 No 2) -- https://www.8notes.com/scores/1754.asp
Comment: Although there is no context given for this tiny snippet, it looks like this is in C# minor and the harmony is a G#7 chord, which is the dominant in that key. We always spell any type of G triad with the letters GBD.
Comment: It needs actually a C with a natural sign on it. C# is in the key.
Answer: In a key where there are already some sharps (or flats) in the key sig., as here, every time one of those notes is played, it has to be sharp (or flat). In E, or C#m, the key here, every other note is natural - E, A, and B. So if a note sounding like a C needs to be played, it can't just be written as a C, because the player would automatically sharpen it, to play C#.
So there are two ways to write this actual note: C natural or B sharp. It will depend on the technical nature of things, like what would that note have been before it needed to change. If, for example, the harmony underneath produced an augmented chord, where E, G#, B became E, G# B# that would be how it was written. If, on another tack, the chords underneath went from A maj. to Amin., then the changed note would not be C# any more, but C natural.Thus spelling the chord properly, even though it's only one note out of that chord.
On the face of it, it seems unnecessary, but from a technical point of view, it is correct. Lots of players would probably be just as happy reading a C natural, but the next glitch MAY be that any subsequent C# in the bar would then have to have an accidental written in, which is extra stuff to read.
Comment: also, FWIW, in some tunings/temperaments/on some instruments, C is actually slightly different from B# etc, see http://en.wikipedia.org/wiki/Sharp_%28music%29 & http://en.wikipedia.org/wiki/Flat_%28music%29
Comment: "the next glitch MAY be": in fact, the next glitch probably is, because the B sharp is the leading tone of the dominant chord, which is almost always followed by the tonic chord, the root of which is a half step higher than the leading tone.  The next most likely chord is the submediant, the third or which is a half step higher than the leading tone.  It is in fact extremely unlikely for there not to be a C sharp following closely after this B sharp.
Comment: @phoog I don't know, I've seen plenty of examples where B goes up to C natural in C# minor, like in the melody of the first movement of Beethoven's Moonlight Sonata. In fact I only really see B sharp in the accompaniment in the first movement of that sonata, the melody uses C natural instead for the same note, at least in all the editions I've seen.
Comment: @Caters but this answer is about where the third of the dominant chord goes (whether it was preceded by a B natural or not).  The C naturals in the melody are not thirds of the dominant chord but rather the melodic upper neighbor of B natural (V/iii), or, harmonically,  ♭VI/iii over a B natural pedal.
Comment: Compared with C natural it is a lot easier to read the way it is written as a B♯, because you can directly read it as a major third from the note below. If it was written as a C natural it would be annoying at least for me.
Comment: "also, FWIW, in some tunings/temperaments/on some instruments, C is actually slightly different from B#": there's no way Beethoven ever imagined this piece would be played on a keyboard with separate keys for B sharp and C.  The 12-tone keyboard had been standard for centuries by the time he wrote this piece.  Whether or not his temperament was equal, it certainly did not admit different frequencies for enharmonically equivalent notes.
Answer: The note is the same key as C.
It is written as B# instead of "C natural" to indicate note's "role" according to rules of classical (musical) harmony.
My guess is this portion of musical piece is written in Cis-moll, and the arrpegio being played is dominant chord (G# B# D# F#). Because in minor tonalities Dominant chord always has VIIth tone (B is VIIth tone in Cis-moll) raised by halftone (so it sounds like dominant chord), you get B# instead of C natural.
This thing is kinda a big deal in classical music and music in era of romantic music (Franz Liszt, Franz Schubert, etc... not sure if Liszt is ) because the same chord can be perceived differently (when played in chord sequence) depending on tonality of the sequence/part where it is played.
Unless you're speaking of atonal music, you can't normally just set sharps/flats/naturals randomly. Hence the B# instead of C natural.
That's the gist of it.
Comment: *The note is the same key as C.* Notes and keys are different things. *This thing is kinda a big deal in classical music and music in era of romantic music* Nothing here is specific to romantic music.
Comment: @BenCrowell - you'll find it's the same piano key, that white one to the left of the two black ones...
Comment: In an English answer *Cis-moll* should read *c sharp minor*.
Comment: @BenCrowell "Notes and keys are different things." That's nitpicking. We aren't talking about math or programming here. "Nothing here is specific to romantic" You missed "classical". B# instead of C indicates this is dominant chord in minor tonality according to rules of traditional harmony.
Comment: The B♯ is much easier to read than C♮, because you can see right away that it is a major third above the G♯. When I play something like this on the piano I read it as a arpeggiated G♯7 chord. That would be disturbed if the B♯ was written as a C♮. Thus a C♮ would slow down the reading process a little bit.
Answer: Add disclaimer Some people apparently couldn't understand what I was getting at with this answer, or don't understand humour or whatever, and therefore flagged the answer. I assure you that any misspellings found here are entirely enharmonic in nature, and thus don't matter. Or do they? If you think so, you've got the point I'm making.

It is knot a C. True – if ewe whir asked two play that note on piano (ore indeed most other western instruments), you'd use thee same key/fingering as ewe wood four C♮, butt its still knot thee same note: conceptually. Think off it like to words witch happen two bee pronounced thee same way, butt mien completely different things, are written differently, end even when spoken can bee distinguished, buy thee context.
(End, they are knot really spoken inn exactly thee same way; pronunciation always varies a little. That's also true four music; good singers ore players off e.g. string instruments use knot exactly thee 12edo pitches a piano wood produce, butt adjust there intonation two best match thee context. Normally, thee result is something between 5-limit just intonation end Pythagorean tuning.)
How that works is discussed inn other questions on this sight end elsewhere. Inn this particular case, B♯ occurs quiet naturally as thee third off thee dominant G♯7, leading up two thee C♯ tonic. OTOH, a C wood appear weird end out off context, sins it actually effects thee tonic itself with an accidental. Sow even four an experienced pianist, though heed physically execute thee same movement, C wood bee thee wrong instruction at that point, like it wood bee confusing four a newsreader if he had two reed out thee text off this answer.
Comment: Could you tone down the misspellings here? I see what you're trying to do, and based on the voting, so do several other people, but we got some complaints as well. Not sure if the complainants thought you were trolling or just didn't get the intent or what, but it _is_ sort of hard to read, and I think your point is made after a few instances.
Comment: Your enharmonic spellings are delightfully disorienting
Answer: Yes a B# is just a C, but it is written that way because that note is function like a "B" instead of a "C". If you look at the notes you have G#, B#, and F#. Look familiar? It's a G#  dominant 7th (5th is omitted, but thats not unheard of).
A more focused question on this idea can be seen in this question as to why notes get alternative names.
Comment: @RosieF B# maps to C on a piano. On other instruments that's not always true, but again we are just talking about piano.  This answer states it's spelled that way for functional reasons which several other answers Also do.
Comment: No, not really, because, as several commenters indicate, this B# is *not* just a C.
Comment: @Dom is there any instrument where there are separate ways to play B sharp and C?  In my experience alternate fingerings are usually discussed in terms of which one is higher or lower, not which one belongs to which enharmonic spelling of a note.  Besides, whether B sharp should be lower or higher than C depends on the tuning system and the context.
Comment: @phoog fretless string instruments  can play in different temperaments which leads to this.
Comment: @Dom my point is, if I recall correctly, that players, including fretless string players, are not going to play the note at a given frequency because it's written as a C natural or B sharp but based on what sounds good.
Comment: @phoog - if that note is written as B#, it's B# that will be played for the appropriate key. Violins, et al, will play B#, and not C, as, just like you say, B# will be more in tune. The opposite is valid too. A piece using C will get played as a C, not a B#. Us mere mortals who have pianos, or fretted instruments, just have to make compromises..!
Comment: @Tim well I'm a singer, so I know what it is not to be constrained by frets or keys, and from my perspective it's more a question of "this is low because it's the third of a major chord" or "this is high because it's the root of ♭VI" (of iii, in this case) rather than "this is a B#" or "this is a C" in some specific tuning system.  Furthermore, especially in a chromatic piece like this, it's likely that not every B# will be pitched the same nor that every C natural will be pitched the same.
Comment: @phoog - understand what you're saying. I've sung for many decades, but never really consider whether to sing a touch higher/lower when considering what relevance a particular note has. I just sing - in tune. I think that's what we do, automatically. It's only in analysis that the intonation becomes revealed - sort of academically. (This B# being the M3 of V/vi). And that in itself will be affected by what instruments are played. Piano/guitar don't play JI, so we must sing in 12tet, otherwise we sound out of tune - not the other way round. Acapella is a different kettle of fish.
Comment: @Tim in tune according to what temperament?  I sing in a group that does mostly renaissance music, and I tend to push the basses into just intonation.  We did a concert with a small chamber organ a couple of seasons ago, but the organist only joined us for the last two rehearsals.  To my surprise, it was tuned in equal temperament.  (There had been an identical organ in my graduate program that was mostly tuned in some meantone temperament.)  We had to adjust very quickly!  Analysis helps to bring people along when they don't have the same sense of "in tune" as one another.
Comment: @phoog - exactly! Not surprised any organ would not be 12tet. Otherwise it would sound good in some keys, and abysmal in others! As I said, accompanied by 12tet tuned instrument/s, the sweet just intonation has to go out of the window. But the moment it's acapella, harmonies go harmonious again! And I believe singers change without too much conscious thought - after all, there's nothing else they *can* do!
Comment: @Tim this organ is designed for the performance of renaissance and baroque music, which explains why most organs of this type are not tuned in ET.
Answer: If it was written as C, it would be actually C# ... because you have four sharps on left (those ####) and they basically mean that:

F = F#
G = G#
C = C#
D = D#

Which is E major or C# minor. Instead, they write it as B# because they want you to play actual C.
It could be also written as a C with a natural sign ♮ ... the natural sign would "cancel out" the sharp # on C.
Answer: I would just like to clarify a couple things that I don't think have been fully articulated.
First is that there is a distinction to be understood between the concepts of "note" and "pitch".  A note is a symbol in a score.  It represents a pitch to be sounded.  Enharmonic equivalence is idea that the same pitch can be represented by different note names.  For example, the notes D# and Eb represent the same black key on the piano.  What we see here is that the pitch which we are accustomed to name by the note C is named by the note B# instead.  They are enharmonic equivalents.
With regard to the second part of the question, "why?": there is a reason that notes in a scale are spelled the way they are: every note in a major or minor scale has a specific function and a specific relationship to the other notes in the scale.  The spellings express these relationships and functions.  The function of the seventh scale degree is usually to produce a high degree of harmonic tension which urgently wants resolving.
A principle that goes along with this is that notes which introduce tension are generally resolved in specific ways.  The seventh scale degree is often called "the leading tone" because in most cases it resolves up to the eighth (tonic) scale degree.  It would be quite out of place to spell this note as C natural; the implications of that spelling are quite contrary to the harmonic function.
Comment: "a note is a symbol in a score": not necessarily.  The word can also denote a tone played or sung at a specific pitch or for a specific duration, or both.  Some people prefer to define "note" and "pitch" more precisely as terms of art for the purpose of theoretical discussion, but it is not incorrect to use these words with their common senses.
Answer: It's nothing whatsoever to do with imaginary problems in writing a C natural!  It's about spelling a major 3rd above G# correctly, and making the interval LOOK like a 3rd, not a 4th.
Answer: That looks like C# minor which gets its leading tone (B) raised by a semitone. You are correct in thinking that B# and C are played at the same place but for the purposes of music theory they are not the same notes. They are what is called enharmonic equivalents ie two notes with different names played at the same place.
Answer: The main notes of a tonal scale comprise 7 pitches, each consistently designated by its own letter. So a piece in C major would generally use the pitches C-D-E-F-G-A-B-C. A piece in C# major would use C#-D#-E#-F#-G#-A#-B#-C#. It would be incorrect to designate these as C#-D#-F-F#-G#-A#-C-C#, as there would be two "flavors" of F and of C, but no "flavor" of E or of B. The piece in your example appears to be the "Moonlight Sonata", which is in C# minor. The pitch below the C# is thus written as a B#.
Answer: It is, believe it or not, simplifying sight reading.  Those three notes at the start form a major dominant seventh (G♯ is the dominant to C♯ minor, and the raised third and natural seventh makes it a major seventh chord).  In particular when those three notes were stacked in a single chord, the chord shape would make its function recognizable.
Now the notes are not in a single chord, but they are still fingered as a functional unit.  Once sightreading progresses to a state where you don't recognize single notes but functional phrases and chords, it is much more helpful if the score reflects the function of notes rather than the particular key to press since that is more useful for letting the fingers act in patterns associated with the current scale rather than "phonetically" key by key.
That is not a universally accepted rationale: there are "piano keyroll" notations that are much more tightly coupled to the physical keyboard layout.  Those notations are worse suited for recognizing patterns and musical content.  For lute and then guitar, tablature notations (which again focus on physical note actuation rather than musical function of a note) remain popular as opposed to "proper" note notation.
But for most keyboard instruments (with several wind instruments also having a diatonically inspired layout of note control, partly employing transposing notation to have the central scale be C major), there is no customary notation that would be closer to the keys than standard scores with functional scales like those used by singers.  And while the note spaces without accidental use follow the white keys of the piano, they are not synonymous with them.
So using the same key for the notes written as B♯ and C is really not more strange than using the same key for the notes written as F♯ and G♭.
Answer: *I'm confused as to how I should play the second note below, B#. Does it mean it's a C? Is it possible? In which case, **why is it written like this, and not just C?***
In short, the B is raised a (1/2) step to B# as an adjustment to the Harmony of the song. To understand, let's harmonize the C# minor scale using triads.

As the key signature indicates, the key of C# minor has four sharps: (F#, C#, G# and D#).
Here are the first seven tones of the C# Natural Minor Scale:
C# - D# - E - F# - G# - A - B
and the Harmony:
i. C# Minor: C# - E - G#
ii. D# Diminished: D# - F# - A
III. E Major: E - G# - B
iv. F# Minor: F# - A - C#
v. G# Minor: G# - B - D#
VI. A Major: A - C# - E
VII. B Major: B - D# - F#

Notice that the chord on the fifth (Dominant) scale degree is Minor (G# Minor).
= = =
In Music Theory, the seventh scale tone (B Natural) of the diatonic (natural) minor scale is raised a half-step in order to get a major chord on the Dominant (fifth) scale degree. Here is the scale now:
C# - D# - E - F# - G# - A - B#
The Dominant Chord is now Major:
(V.) G# Major: G# - B# - D# or (5 - #7 - 2)
This (B#) also gives us a Leading Tone into the Octave and the Harmonic Minor Scale. By Leading Tone, I mean that the ascent into the Octave is now a 1/2 step (B# -> C# ) from the (previously) whole step (B natural -> C#). Also:

NOTE: We now have a third pair of (1/2) steps in the scale

D# ->  E (2 -> 3)
(5 -> 6) G# -> A
B# -> C# (7 -> 1)
Additionally, an Authentic Cadence (V/V7 -> I) as a resolution, in Minor, can sound very dramatic as chord tones resolve.
*IMPT: having a (B#) as the seventh degree of the scale creates these changes to the harmonized C# Minor Scale:

III+: E Augmented: E - G# - B#
V. G# Major: G# - B# - D#
vii. B# Diminished: B# -D# - F#

~
Answer: This piece is in the key of either E major or C# minor. The melody line goes G# - B# - F#, spelling out a G#7, a dominant chord of the III (mediant) of the scale, a secondary dominant to the submediant (VIm or C#m in this case). This harmony would be normally a G# minor having B instead of B#, but due to its secondary dominant nature it will have its third sharpened.
Comment: looks like Beethoven sonata op.27 no.2 'quasi una fantasia'
Comment: In fact it's not the secondary dominant but the normal run of the mill primary dominant, since the piece is in C sharp minor.
Comment: Indeed, and the way to sharpen a note is to raise it by an augmented unison. This leaves the letter part of its name unchanged; that part is still B. So the result of sharpening B is B#. To write C instead of B# would be to put it on the wrong degree of the scale.
Comment: @phoog you're right, I don't know why I wrote secondary back then.
Answer: To further confuse things, the notes may only be enharmonic (same pitch) in equal temperament. In some other temperament, they may be slightly different pitches.
Comment: This is incorrect.  In any 12-tone temperament, and in many temperaments with more tones, they can only be the same pitch.  They can only be different in an untempered context (instruments or voices that can alter tuning during performance) or in a temperament that has separate B♯ and C (for example, a keyboard with an extra key for B♯).
Comment: @awelotta this is a piano piece. Keyboards with more than 12 tones per octave were a relic of the distant past in Beethoven's day. And even rarer than a keyboard with split sharps is one with extra keys between B and C or between E and F.  (So even in a keyboard with seventeen keys per octave there isn't going to be a separate key for B sharp and C natural, which is why I said "in many temperaments with more tones.")  But the idea that Beethoven ever imagined this piece to be played in a temperament with more than 12 tones is farfetched at best.
Comment: Is he not referring to temperaments with more than 12 tones? Though the clarification is important.

What does this note - B# - mean?


Getting actual array of results using Mongoid

Question: With a regular ActiveRecord/SQL setup in Rails, in console when I execute commands *.where, *.all etc., I get back the actual array of record items.  However, after switching to Mongoid, I instead get back a criteria.  How do I get the actual results?
This is what I get now...
ruby-1.9.2-p180 :001 > App.all
 => #<Mongoid::Criteria
  selector: {},
  options:  {},
  class:    App,
  embedded: false>

Answer: When you query a model in Mongoid, it returns a criteria object (as you've stated), it doesn't actually run the query until you request data from the criteria.
All you need to do is iterate over the results, using each or map or any of the array methods, like this:
App.all.each do |app|
  puts app.name
end

Alternatively, if you just want the array, you can just call to_a on the criteria:
App.all.to_a

Answer: App.all.entries works as well.


Programmatically changing ansible_ssh_user during a play

Question: I'm currently creating a common ansible playbook for Ubuntu.
During the hardening process I disable the root user and create a new sudo user for running future playbooks (called ansible).
The first time I run this playbook I have ansible_ssh_user set as root the second time I have to manually change the ansible_ssh_user var to ansible.
Is there a way for ansible to track which hosts have had this step completed and connect with the newly created ansible user or even to fallback to a second username attempt. I would like this process to be unattended if at all possible.
Edit:
I'm trying to correct the user when establishing a new connection. For example. I ran the hardening playbook one one server. Now I want to run it to provision a new server and make some updates to the existing ones. Therefore I have two usernames root and ansible. I would like the script to try both instead of setting a host var, are host vars my only option here?
Answer: Use metadata that your inventory script can query and then select the user based on the group of the target box.
For instance, using AWS, set a hardened tag after you set up the ansible user, then when you run other plays, you can use the ansible user on hosts that have the hardened tag set. This will appear automatically as a group using the AWS inventory.


Rooted Tree and Greedy Algorithms

Question: In a Rooted Tree, we have a message on Root. in each step, each node that has a one copy of message, can transfer this message to at most one of it's childeren. we want to use minimum step and send the message to all nodes. for each node v, d(v) and c(v) shows the distance v to it's deepest leaf and number of it's childs. i propose two greedy algorithm, but i couldent find any prove or counterexample.
1) each node that recive a message, in each step send a message to one of childeren taht has a maximum d(v).
2)  each node that recive a message, in each step send a message to one of childeren taht has a maximum c(v).
anyone could help me?
Answer: Both the greedy algorithms are wrong. Possible counterexamples are:

A tree in which the maximum depth $max[d(v_i)]$ is smaller than maximum no. of children $max[d(c_i)]$.
A tree in which the maximum depth $max[d(v_i)]$ is greater than maximum no. of children $max[d(c_i)]$.

A possible algorithm that comes to mind is the following:
Start with the lowest level. Since these are leaves, give them a score of $s_i = d(v_i)$. In fact all leaves get this score. Now move a level up and give a score of $s_i = c_i + max\{s_{j_1},s_{j_2},\ldots ,s_{j_{c_i}}\}$. After you given scores to all vertices, the min. time it takes to transmit message to all is the score of the root.
Answer: Actually 1) can be used to find a counter-example to 2), and vice-versa.
Take tree $T$ with the root having two child subtrees  $T_1, T_2$.  $T_1$ is a node with many leaf children (say 10), and $T_2$ is a path of small length (say 2).  You want to send the message to $T_1$ first, as $T_2$ will finish first even if receives the message second.  Thus 1) won't work.
To show that 2) won't work, set $T_1$ as a node with two leaf children (a cherry), and $T_2$ as a path of large length.  You want to send the message to the path first, even though its root has less children than $T_1$.
What I suggest is some kind of dynamic programming algorithm.
For some internal node $v$, denote by $time(v)$ the minimum number of iterations needed to pass all messages to the $v$ subtree.
Say $v$ has children $v_1, \ldots, v_k$.  If you can find out how to compute $time(v)$ as a function of $time(v_1), \ldots, time(v_k)$, you can pass the message to the most time-consuming child (that hasn't had the message yet) at every iteration.
Comment: would you please say sth about Time Complexity ?
Comment: Well, assuming computing $time(v)$ can be done in $O(k)$ steps ($k$ being the # of children of $v$), the whole $time$ computation should be feasible in $O(n)$ time.  Afterwards, at each iteration, each node must find its worst child, so each node might get investigated, resulting in a time $O(n)$ per iteration.  Though I'm pretty the tree can be preprocessed after the computation of $time$ to get something better (per iteration).
Comment: i couldent underestand why the first wont work, as you say "You want to send the message to T1 first, as T2 will finish first even if receives the message second. Thus 1) won't work."
Comment: Say that $T_2$ is a path with vertices $p_1p_2p_3$, and $T_1$ is a tree with one root $r$ and leaves $r_1, \ldots, r_{10}$.  Suppose you send to $T_2$ (hence at $p_1$) at step 1.  At step 2, the root sends to $r$.  Meanwhile, the root of $p_1$ sends the message to $p_2$.  At this point, $r$ hasn't passed to anyone.  At step 3, $p_2$ passes to $p_3$ and everything is done at $T_2$ - everyone got the message.  During the same step, $r$ passes to say $r_1$.  We need to wait 9 more steps for $T_1$ to finish, while $T_2$ isn't doing anything. But try starting by passing to $r$.
Answer: The result of createSchedule is a list of rounds. Each round is described by nodes receiving message from their parent that round. Each parent can only send one message per round.
<code>public class Scheduler {

@Override
public List<Collection<Node>> createSchedule(Node root) {
    List<Collection<Node>> result = new ArrayList<>();

    // map will hold pairs of <nodeId, count of iterations required for subtree of node>
    HashMap<Integer, Integer> countOfIterationsRequiredForNode = new HashMap<Integer, Integer>();

    // map will hold pairs of <nodeId, children ordered by sending order>
    HashMap<Integer, Node[]> nodesInSendingOrder = new HashMap<Integer, Node[]>();

    // computes the count of required iterations for root and each node in its subtree
    computeRequiredIterationsAndChildOrder(root, countOfIterationsRequiredForNode, nodesInSendingOrder);

    // in 0 iterations only root has got the message
    result.add(Collections.singletonList(root));

    // prepare the schedule
    int iterationCounter = 0;
    while (result.size() > iterationCounter) {
        Collection<Node> nodesToStartSendingInIteration = result.get(iterationCounter);
        for (Node n : nodesToStartSendingInIteration) {
            int offset = 1;
            if (nodesInSendingOrder.get(n.getId()) == null) {
                // no children to send this message to
                continue;
            }
            for (Node childNode : nodesInSendingOrder.get(n.getId())) {
                // add each children into iteration where it belongs
                int iterationWhenChildrenGetsMessage = iterationCounter + offset;
                if (result.size() <= iterationWhenChildrenGetsMessage) {
                    result.add(new HashSet<Node>());
                }
                result.get(iterationWhenChildrenGetsMessage).add(childNode);
                offset++;
            }
        }
        iterationCounter++;
    }

    return result;
}

/**
 * @param parentNode {@link Node} for which we are computing required iterations count
 * @param countOfIterationsRequiredForNode help structure to store computed iterations count
 * @param nodesInSendingOrder help structure to store optimal children ordering
 */
private void computeRequiredIterationsAndChildOrder(Node parentNode, final HashMap<Integer, Integer> countOfIterationsRequiredForNode,
        HashMap<Integer, Node[]> nodesInSendingOrder) {

    if (parentNode.getChildren().isEmpty()) {
        // leaf. no more iterations are required after this node receives the message
        countOfIterationsRequiredForNode.put(parentNode.getId(), Integer.valueOf(0));
        return;
    }

    // children need to be processed before computing this node
    for (Node childNode : parentNode.getChildren()) {
        computeRequiredIterationsAndChildOrder(childNode, countOfIterationsRequiredForNode, nodesInSendingOrder);
    }

    nodesInSendingOrder.put(parentNode.getId(), parentNode.getChildren().toArray(new Node[] {}));
    Arrays.sort(nodesInSendingOrder.get(parentNode.getId()), new Comparator<Node>() {

        @Override
        public int compare(Node node1, Node node2) {
            Integer iterationsNode1 = countOfIterationsRequiredForNode.get(node1.getId());
            Integer iterationsNode2 = countOfIterationsRequiredForNode.get(node2.getId());
            return iterationsNode2.compareTo(iterationsNode1);
        }

    });

    // nodes are ordered by required number of iteration, descending order
    Node[] orderedChildren = nodesInSendingOrder.get(parentNode.getId());

    // compute required iterations depending on children
    int extraIterationsForParentNode = 0;
    int extraIterationsBeforeReachingLastSibling = orderedChildren.length - 1;
    for (Node child : orderedChildren) {
        Integer iterationsChild = countOfIterationsRequiredForNode.get(child.getId());
        extraIterationsForParentNode = Math.max(extraIterationsForParentNode, iterationsChild - extraIterationsBeforeReachingLastSibling);
        extraIterationsBeforeReachingLastSibling--;
    }

    countOfIterationsRequiredForNode.put(parentNode.getId(), Integer.valueOf(orderedChildren.length + extraIterationsForParentNode));

}
</code>
}

Rooted Tree and Greedy Algorithms


What does the term "regularization" refer to specifically?

Question: Initially I thought that "regularization" referred to specific methods to reduce overfitting by putting a penalizer term in the cost function that uses a norm eg. L1, L2 norm.
But recently I've seen people use the the term "regularization" to refer to any method that reduces overfitting eg. I've heard people call random dropout in neural networks as a regularization method.  So which usage of the term is correct?
Comment: I would say that "regularization" is any method that constrains parameters and keeps them from floating freely. As @AryaMcCarthy notes, dropout sets some parameters to zero (just as the Lasso does). As such, one could even call feature selection a kind of regularization. But I'm definitely not an expert, so I'd rather not post this as an answer.
Comment: Well, [dropout can be framed as regularization under your first definition](https://arxiv.org/abs/1307.1493).
Comment: I think there's a connection to adding constraints *based on some inductive bias for posing your optimization problem* -- i.e. Tikhonov and norm-based regularization methods are just scalarizations (i.e. of the form $\text{objective} + \lambda \lVert \cdot \rVert$) of a multi-objective problem, which is also the framing used in the paper Arya links. I've heard of regularization used in all the contexts OP mentions, but in this light, I got a little stuck on the distinction between "constraint" and "regularization."
Answer: I agree with the comment that regularization is a way to constrain parameters. In that regard, not only are $L_1$ and $L_2$ penalties regularization, but neural network dropout is regularization, since it forces certain parameters to be zero. Likewise, convolutional neural networks could be argued to perform regularization by forcing some parameters to be equal and others to be zero.
Even if the terminology is a bit loose, the field of machine learning seems to do okay. Many fields are loose with terminology, too. For instance, ask a musician to explain the difference between a "riff" and a "lick".


dnslint and redadmin, why and when?

Question: A pretty small query really - dnslint and repadmin - what really differentiates these tools in terms of troubleshooting replication? When and why would you use either one.
Answer: REPADMIN is specifically for diagnosing Active Directory replication problems between domain controllers.
DNSLINT is more specifically for testing DNS name resolution issues, although the results of this test can also be useful in troubleshooting replication.
I use both tools to proactively test my domain controllers on a routine basis, and also like to run them after promoting a new DC in order to verify that it is configured properly for DNS resolution and AD replication.
Have you taken the time to read any of the TechNet articles about both of these tools?

http://technet.microsoft.com/en-us/library/cc770963%28v=WS.10%29.aspx
http://support.microsoft.com/kb/321045
http://support.microsoft.com/kb/321046

dnslint and redadmin, why and when?


Como usar o login do Facebook na plataforma universal do Windows?

Question: Estou tentando montar o login do Facebook em um aplicativo de forma que funcione utilizando o aplicativo ou o website de acordo com o tutorial:
http://facebooksdk.net/docs/windows/config/
Tem uma questão similar, mas que não me atende por limitar a solução apenas ao aplicativo pelo que entendi:
Utilizando Login do Facebook no Windows Phone 8.1 1
Acabei de adionar o arquivo xml com o id da minha aplicação no Facebook. Também adicionei o protocolo e coloquei este código no meu código principal:
        protected override void OnActivated(IActivatedEventArgs args)
        {
            base.OnActivated(args);

            // You can setup a event handler to be called back when the authentication has finished
            Session.OnFacebookAuthenticationFinished += OnFacebookAuthenticationFinished;

            var protocolArgs = args as ProtocolActivatedEventArgs;
            LifecycleHelper.FacebookAuthenticationReceived(protocolArgs);
        }

        private void OnFacebookAuthenticationFinished(AccessTokenData session)
        {
            // here the authentication succeeded callback will be received.
            // put your login logic here
        }

Porém, tentando adicionar o Facebook.client não consegui e provavelmente por isso, as funções acima não estão sendo reconhecidas para que eu possa fazer o override.
Alguém sabe o que pode estar faltando? Como concluir esse objetivo?
Answer: Na pergunta não ficou claro qual ferramenta está utilizando para comunicação com Facebook, então vou deduzir que está utilizando facebook-csharp-sdk. Outra opção interessante é Facebook Service - UWPCommunityToolkit
Api e configuração dos aplicativos que interagem com facebook mudam constantemente, na presente data para que uma aplicação uwp possa utilizar login do facebook são necessárias algumas configurações:

Cadastrar-se como desenvolvedor na página https://developers.facebook.com/apps
Adicionar um aplicativo
Baixe o fonte aqui (para gerar o SID exigido pelo app facebook)
Na guia Configurações - Básico

As únicas informações digitadas serão Nome da Aplicação, Email de contato, SID da Windows Store (veja como pegar o SID para debug no código fonte disponível no final da resposta)

Clique +Adicionar plataforma e escolha Aplicativo Windows informe o SID da Windows Store (pode ser gerado SID para teste, veja como no fonte no final da resposta)
Na opção PRODUTOS escolha Login do facebook e configure conforme imagem:

Depois do aplicativo criado e configurações adicionadas, adicione o Id do aplicativogerado pelo facebook na aplicação.
//somente para teste não informe diretamente no app em produção
private const string AppId = "XXXXXXXXXXXXX";

Feito isso, seu aplicativo já será capaz de utilizar o facebook como ferramenta de login (testado com facebook api versão v2.8).

Código Fonte:
  https://github.com/rubgithub/FacebookLogin-UWP
Referências:
https://github.com/facebook-csharp-sdk/facebook-csharp-sdk
http://docs.uwpcommunitytoolkit.com/en/master/services/Facebook/
https://stackoverflow.com/questions/33098187/facebook-login-windows-10-uwp-desktop
http://dotnetbyexample.blogspot.com.br/2015/06/custom-oauth-login-to-facebook-for.html


Sending mail to detailed groups?

Question: Ok, I need a bit of help with this one.
I have a website where I created a newsletter using Simplenews - works just fine, I'm sending some welcoming text + attached views of new things on site. But now I need to make something more with it.
I want to create new type of newsletter, that would be sent irregularly - or manualy as some would say. That is not a problem. Question appears here: I want admin to be able to create groups of users (manually again adding mails to the group etc.) for example, let's say I want to have two new groups for start:

group a
group b

And from time to time, admin needs to send a mail to all the email addresses in the selected group. How can I achieve that? Is even Simplenews a good idea in this situation? Or maybe there's some better tool?
Thanks in advance
Comment: do you know about OG?
Comment: You mean Organic Groups? Only heard about it, but newer used it. I believe I should check it?
Comment: I checked Organic Groups and I'm rather sure it's NOT what I'm looking for. I must be able to create/manage at least few groups of subscriptions (based on email address, not registered users) and be able to send mass mail to selected group manually.
Answer: I guess Simplenews Roles modules can help you for creating the groups.
You can assign users to a specific role and then based on this roles you can send Simplenews.
For Eg.
User 1 and User 2 can be assigned to role A
And
User 3 and User 4 can be assigned to role B
Now you can use role A and B for sending Simplenews.
I guess this helps.
Answer: Simplenews exactly has this feature:

First create groups here "admin/config/services/simplenews/add"
Edit new content type and in "Publishing options" check "Use as
simplenews newsletter"

Sending mail to detailed groups?


Cycling through a string, and separate by words?

Question: I'm trying to reverse a given string, and I've already fully reversed it, but now I need to reverse each word by itself so that they're readable.
e.g. input: Reverse this string.
current output: .gnirts siht esreveR
desired output: string. this Reverse
Is there some way I can run my string reversing function again on each particular word?
Comment: @ShivanRaptor I want to cycle through the string with a for loop and when it reaches non-whitespace text, store that character and every character after until the next whitespace.  Then I can reverse it and place it in in a new string, and repeat this with the other words.  I don't know how to have it stop when it reaches a non-whitespace character or when it reaches a whitespace character though.
Answer: If you have a reverse function which accepts start and end offsets for the string:
void rstr(char *s, int start, int end) {
  /* ... */
}

int main(){
  char str[] = "this is a sentence of words";
  int i, p;
  rstr(str, 0, strlen(str));
  for (p = i = 0; i <= strlen(str); i++) {
    if (str[i] == ' '  || i == strlen(str)) {
      rstr(str, p, i);
      p = i + 1;
    }
  }
  printf("%s\n", str);
  return 0;
}

Answer: run your reverse alroithm again on each of the results of strtok
    char* token = strtok(str, ' ');

    while (token)
    {
       reversedWord = YourReverseAlgorithm(token);
        token = strtok(0, ' ');
    }

each call to strtok gives you the token of the original string up to the delimitting character, which in your case is ' '. Simple conscise, and works.


Alterar cores da escala de um gráfico bolha no R

Question: Estou com dificuldade de criar uma escala de cores para meu gráfico
nome<-c("a","b","c","d")

anos<-c(15,8,25,9)
renda<-c(14,5,3,25)
final<-c(30,15,42,12)

tudo<-cbind(nome,anos,renda,final)

tudo<-as.data.frame(tudo)

attach(tudo)
teste<-ggplot(tudo, aes(x=anos, y=renda, size=final)) +
  geom_point(alpha=0.6, aes(colour =final))

teste +
  geom_label_repel(aes(label = nome),
                   size = 3,
                   data = tudo,
                   box.padding   = 0.25,
                   point.padding = 0.5,
                   segment.color = 'grey50',
                   show.legend = FALSE) +
  theme_classic()

As minhas perguntas são as seguintes:

Gostaria de criar uma escala de cores da variável final para que fosse do azul para os menores valores para o vermelho para maiores valores
Gostaria também de saber se é possível colocar os títulos sem a caixa ao redor de cada nome
Gostaria de saber também se é possível inserir mais valores nas escalas do gráfico no eixo x e no eixo y, colocando para variar de uma em uma unidade
Gostaria de saber também porque o gráfico está tirando de ordem os eixos
Answer: Vou começar pela última pergunta:

Gostaria de saber também porque o gráfico está tirando de ordem os eixos

Apesar do resultado abaixo,

os eixos não estão com valores fora de ordem. Note que ao rodar a função str nos teus dados, todas as tuas colunas estão classificadas como fatores, com exatamente a mesma ordem apresentada no output abaixo:
str(tudo)
'data.frame':   4 obs. of  4 variables:
 $ nome : Factor w/ 4 levels "a","b","c","d": 1 2 3 4
 $ anos : Factor w/ 4 levels "15","25","8",..: 1 3 2 4
 $ renda: Factor w/ 4 levels "14","25","3",..: 1 4 3 2
 $ final: Factor w/ 4 levels "12","15","30",..: 3 2 4 1

Para remediar isso, crie seu conjunto de dados da seguinte maneira:
nome  <- c("a","b","c","d")
anos  <- c(15,8,25,9)
renda <- c(14,5,3,25)
final <- c(30,15,42,12)

tudo  <- data.frame(nome, anos, renda, final)

str(tudo)
'data.frame':   4 obs. of  4 variables:
 $ nome : Factor w/ 4 levels "a","b","c","d": 1 2 3 4
 $ anos : num  15 8 25 9
 $ renda: num  14 5 3 25
 $ final: num  30 15 42 12

Agora sim, anos, renda e final estão como variáveis numéricas.

Gostaria de criar uma escala de cores da variável final para que fosse do azul para os menores valores para o vermelho para maiores valores

Sim, com scale_color_gradient(low = "blue", high = "red"). Basta informar a cor dos valores baixos (low) e dos valores altos (high).

Gostaria também de saber se é possível colocar os títulos sem a caixa ao redor de cada nome

Sim. Use geom_text_repel em vez de geom_label_repel.

Gostaria de saber também se é possível inserir mais valores nas escalas do gráfico no eixo x e no eixo y, colocando para variar de uma em uma unidade

Sim. Use scale_x_continuous(breaks = seq(8, 25, 1)). Com isso, informamos ao ggplot2 que as quebras (breaks) do eixo x devem começar em 8, terminar em 25 e aumentar de 1 em 1. De modo análogo, scale_y_continuous(breaks = seq(3, 25, 1)) resolve o problema para o eixo y.
Juntando tudo num gráfico só, temos o seguinte:
nome<-c("a","b","c","d")
anos<-c(15,8,25,9)
renda<-c(14,5,3,25)
final<-c(30,15,42,12)

tudo <- data.frame(nome,anos,renda,final)

teste <- ggplot(tudo, aes(x=anos, y=renda, size=final)) +
  geom_point(alpha=0.6, aes(colour = final))

teste +
  geom_text_repel(aes(label = nome),
                   size = 3,
                   data = tudo,
                   box.padding   = 0.25,
                   point.padding = 0.5,
                   segment.color = 'grey50',
                   show.legend = FALSE) +
  theme_classic() +
  scale_color_gradient(low = "blue", high = "red") +
  scale_x_continuous(breaks = seq(8, 25, 1)) +
  scale_y_continuous(breaks = seq(3, 25, 1)) +
  scale_size(guide = "none")

A função scale_size(guide = "none") precisa ser colocado para que a legenda com o tamanho dos pontos não apareça. Se ela for necessária, basta retirar esta função ao final do comando.
Comment: Use `scale_x_continuous(breaks = seq(0, 25, 1), limits = c(0, 25))` e `scale_y_continuous(breaks = seq(0, 25, 1), limits = c(0, 25))`.
Comment: Muito obrigado , resolveu meu problema, só mais uma coisa, como faço para os eixos iniciarem no valor 0 ?


Wordpress suddenly not recognising CSS

Question: I originally referenced the CSS in the  section of header.php:
<link href="<?php echo get_bloginfo('template_directory'); ?>/style.css" rel="stylesheet">

After it stopped working, I tried enqueuing it in functions.php:
function add_styles_scripts()
{
    wp_register_style( 'style',  get_template_directory_uri() .'/style.css');

    wp_enqueue_style( 'style' );
}

(Above I've left out the rest of the CSS/JS files that were already enqueued, for simplicity.)
Wordpress does see the CSS file as it recognises the notes in the head as my custom theme:
/*
Theme Name: onesquad
Author: Erin Culleton
Description: One Squad
Version: 0.0.1
Tags: One Squad
*/

but it only displays the raw html, and Chrome devtools doesn't find any trace of it either.
It's located in the root folder of my theme.
Could it be a database problem? I have no idea where to even start looking.
Many thanks.
******EDIT******
index.php:
<?php get_header(); ?>

<?php

    if ( have_posts() ) : while ( have_posts() ) : the_post();

        get_template_part( 'content', get_post_format() );

    endwhile; endif;

?>

<?php get_footer(); ?>

Answer: You need to call the function in a hook. Please find the code below :
function add_styles_scripts()
{
    wp_register_style( 'style',  get_template_directory_uri() .'/style.css');

    wp_enqueue_style( 'style' );
}
add_action( 'wp_enqueue_scripts', 'add_styles_scripts', 100 );

Hope it helps you.
Answer: In case you are using a child theme, add Template to the styles, it must be the parent of your current theme.
Like this:
/*
Theme Name: onesquad
Author: Erin Culleton
Description: One Squad
Version: 0.0.1
Tags: One Squad
Template: parenttheme
*/

Comment: Thanks for the tip, I'll do this from now on. It hasn't changed the situation though unfortunately :(
Comment: how does your header.php and index.php look like?
Comment: When this problem started, I had a `content.php` and a very short `index.php` - I reverted to putting the actual content in the `index.php` and getting rid of the `content.php` file to see if that would help. It didn't. But now that I have switched them back, so that I could show you a shortened version of my `index.php` and not my entire site's contents, everything seems to be working again (though I still don't know why it stopped working...). My apologies for the trouble, but thanks for your help!! :)
Comment: However... Now it only shows the header and footer, and nothing from `content.php`. I'm assuming there's something wrong with the code in the middle of my `index.php`. Any idea what it could be? (contents of `index.php` in original post, after ***edit***)
Comment: Also, if I try to change the name of `content.php` to `front-page.php` (as it is a static front page, so actually no Loop necessary), then all the CSS disappears - I believe this is where my troubles started :/ I think I will start a new topic with this info as the problem has shifted. Thanks again :)
Answer: I was missing the head notes and header/footer hooks in the front-page.php, causing it not to load properly, I assume. All CSS and content now back.

Wordpress suddenly not recognising CSS


Find $\int_{|z|=R} \frac{1}{(z-b)(z-a)^m} dz$

Question: I have to find $\int_{|z|=R} \frac{1}{(z-b)(z-a)^m} dz$ for $|a| <R < |b|$ I would use Cauchy formula but first what can I do with $\frac{1}{(z-b)(z-a)^m}$? I dont remember it.
Comment: Does $$\int_{\lvert z\rvert = R} \frac{f(z)}{(z-a)^m}\,dz$$ remind you of something?
Answer: Here $\dfrac{1}{(z-a)(z-b)^m}$ has pole of order $m$ at $z=a$ inside $|z|=R,$ therefore,
by Cauchy's integral formula
\begin{align}
\int_{|z|=R}\dfrac{1/(z-b)}{(z-a)^n}dz&=\frac{2\pi i}{(m-1)!}\frac{d^{m-1}}{dz^{m-1}}\left(\frac{1}{z-b}\right)_{z=a}\\&=(-1)^{m-1}2\pi i\frac{1}{(a-b)^{m}}.
\end{align}


Probability that a runner arrives before the other

Question: Two athletes arrive at the finish line of a race in moments $X, Y$ independent. The first comes at a casual time $X$ between $16$ and $17$. The second comes at a  casual time $Y$ between $16.15$ and $17$. Find:
$-$ The probability that $X \le Y$
$-$ The probability that $|Y-X|\le 0.15$
SOLUTION:
$$X[16;17]$$
$$Y[16.15;17]$$
$$P(X \le Y) = \frac{60\cdot45-\frac{45^2}{2}}{60\cdot45} = \color{red}{0.625}$$
$$P(|X-Y|\le0.15)= \frac{60\cdot45-\frac{30^2}{2}-\frac{45^2}{2}}{60\cdot45} = \color{red}{0.458}$$
The results should be corrected, but i don't understand how he came to the following formulas (this solution is That of Professor), and i'd like to know if there is another method to solve these two questions. Thanks
Comment: Are the distributions $X\&Y$uniform or what does **random moment** and **casual time** mean?
Comment: @mathreadler reading the question, i think that they are uniform
Comment: They look correct to me if we assume that $X$, $Y$ are uniformly distributed and that $16.15$ actually means $16$ minutes and $15$ seconds.
Comment: Then the density functions will be constant and you have two dimensions or variables, $x_1 \& x_2$, what to do then is to find the areas to perform the integration over in this two dimensional space (and to recall from calculus what the integral of a constant is).
Comment: @Leo163 tes they're right, but I don't understand how he obtained these formulas
Answer: Consider the first $\mathbb{P}[X\leq Y]$. You know $X\sim\mathcal{U}(16,17)$ and $Y\sim\mathcal{U}(16.25,17)$. If the second athlete comes at $y\in[16.25,17]$ ,then $\mathbb{P}[X\leq y]=y-16$. The pdf of $Y$ is $1/(3/4)$. Hence $\mathbb{P}[X\leq Y]=\int_{16.25}^{17}(y-16)\frac{1}{3/4}dy$.
Comment: what is the *pdf*?
Comment: https://en.wikipedia.org/wiki/Probability_density_function
Comment: ....ohhh gotcha


Perdendo Session após requisição

Question: Bom galera, estou com um problema que até agora não consegui resolver. Ele só começa a ocorrer depois de uma requisição ajax, sendo que nela eu gero um documento e retorno a url em um json, para ser pego no javascript, ser atribuído a um link e ser feito o download.
Como ocorre: após gerar o primeiro relatório, se o usuário tentar criar outro logo em seguida, a aplicação meio que chama o Application_Start novamente, e assim, perdendo a "linkagem" que tinha da session. O engraçado é que no browser (estou utilizando o Chrome), a session continua aparecendo nos Cookies.
Outra fato interessante, é que quando eu clico no link pra fazer o download, ele também chama novamente o Application_Start...
NT: Utilizo ASPNET MVC 5
Exemplo de como crio as Sessions:
    [HttpPost]
    [AllowAnonymous]
    public ActionResult LoginRequest(string login, string pass)
    {
        string loginCache = "usuario";
        string senhaCache = "123123";

        if (login == loginCache && pass == senhaCache)
        {
            System.Web.HttpContext.Current.Session["Nome"] = "Admin";
            System.Web.HttpContext.Current.Session["Email"] = loginCache;

            return Json(
                new
                {
                    sucesso = true,
                    href = "GerarRelatorio/Index"
                }
            );
        }
        else
        {
            return Json(
                new {
                    sucesso = false,
                    msg = "Login e/ou Senha estão incorretos."
                }
            );
        }

Exemplo de como estou retornando a url:
        var newCaminhoContent = Path.Combine(urlDownloadFolder, arquivoModel.Nome);

        var urlDownloadHTML = ( newCaminhoContent.Substring(newCaminhoContent.IndexOf(@"Content")) );

        return Json(new
        {
            hasError = false,
            msg = "O arquivo foi gerado com sucesso!",
            href = urlDownloadHTML,
            nome = arquivoModel.Nome,
            ext = arquivoModel.ExtensaoString
        });

Exemplo de como pego a url no javascript:
$.post(
    AppConfig.baseUrl + "/GerarRelatorio/Gerar",
    {
        cm: cm,
        tr: tr
    },
    function (data, status) {

        console.log(data);

        try {
            if (data.hasError === false) {

                getTimeToShowLink(data);

                //var win = window.open(AppConfig.baseUrl + data.href);
                //win.focus();

                //$('#modal-status').modal('hide');
            }
            else {
                $('#div-modal-loading').hide();
                $('#div-modal-msg').html(data.msg);
            }
        }
        catch (e) {
            console.log(e);
        }
        finally {
            //$btn.button('reset');
            $('#modal-status').modal('hide');
        }
    }
);

function getTimeToShowLink(data) {

    $('#btn-download')
       .attr('href', AppConfig.baseUrl + data.href)
       .attr('download', data.nome)
       .show()

    var tempo = 10;
    var sec = 0;

    var interval = setInterval(function () {

        sec = pad(++sec % 60);

        if (parseInt(sec) <= parseInt(tempo)) {
            $("#div-msg-download").html(
                'Se o download não começar automaticamente em até ' + (tempo - sec) + ' segundos, clique aqui...');
        }
        else {
            $('#div-msg-download').html('Clique aqui para fazer o download...');
            clearInterval(interval);
        }

    }, 1000);
}

Comment: Pelo que entendo, você está chamando a aplicação em cors. Entendemos que o js está na máquina do cliente e que o cookie da sessão não é enviado no momento da requisição ajax, por isso, o sistema entende que é outro client requisitando...
Comment: Bom, mas você sabe como essa situação poderia ser corrigida?
Comment: Depende de várias coisas, mas pode tentar tirando a concatenação do endpoint, se o endereço for o mesmo claro. Seria possível?
Comment: Como eu poderia fazer isso?
Comment: Por exemplo, aqui: AppConfig.baseUrl + "/GerarRelatorio/Gerar", ficaria assim: "/GerarRelatorio/Gerar".
Porém, mais uma vez. Depende de como seu ambiente foi configurado, de como sua lógica foi construída...
Comment: Entendi... Irei testar aqui.
Answer: Bom galera, só precisei mudar o httpRuntime pra fazer funcionar. Aparentemente a aplicação por algum motivo, atualizava o web.config e isso fazia com que o pool do IIS reiniciava toda vez que era feito uma nova requisição, chamando múltiplas vezes o método Application_Start.
Antes:
<httpRuntime targetFramework="4.6.1" />

Depois:
<httpRuntime fcnMode="Disabled" targetFramework="4.6.1" />

Isso meio que impede o web.config de ser atualizado, evitando o App pool de reiniciar o website.

Perdendo Session após requisição


Marketplace V2 License API returned user as licensed (active) in organization not included

Question: During the install flow of my Marketplace V2 application, I only granted access to one of the organizations (orgUnits) in the google account. The more menu (nine dots) correctly seems to exclude my app from users not in the granted organization BUT when I do a user license query (https://developers.google.com/apps-marketplace/v2/reference/userLicense/get) for those users who are not in the granted organization, I am still getting 'ACTIVE' rather than 'UNLICENSED'.
LT
Comment: Any insights from google folks? Further testing showed that for those users in org units which have not been granted access, if we try to set the user in the Service Account as one those users and make API calls then this is not allowed. So if this license API doesn't work as I'm expecting, then the only way it seems to programatically find out if a user has access is to make a test call with a Service Account with that user.
Answer: On further testing, the "enabled" field which is described in the documentation (https://developers.google.com/apps-marketplace/v2/reference/userLicense#resource) as:
enabled   boolean   The domain administrator has activated the application for this domain.
Seems to return the enabled status of the app for the org unit that the user is in rather than the entire domain. So this field actually gives the answer I want in terms of whether the app is enabled for the user (or more precisely enabled for the org unit that the user is in).
LT


Qt Creator Error when trying to split a QString

Question: I have a string that I am trying to split on the first instance of the delimiter, in this case "~". These are the calls I am making:
QString line = "hello~world~how~are~you";
QStringList list = line.split("~", Qt::SplitLimit::KeepEmptyParts, Qt::CaseSensitive);

Ideally I would get:
list.at(0); = "hello"
list.at(1); = "world~how~are~you"

However this throws an error.
.... error: 'Qt::SplitLimit' has not been declared
.... In function 'int qMain(int, char**)':

I am using Qt Creator version 6.4.2 with Microsoft Windows 10 and I am trying to code in C++. I am using the CMake build system. I have included QtCore in the project, so that shouldn't be the issue.
I do not know if this is the best way to split a QString so if anyone has a better suggestion I would gladly try it.
In the meantime I think I will just fully split it. Use the first entry, and then re-append the rest together.
Comment: Where have you found `SplitLimit`? Shouldn't that be `SplitBehavior`, see https://doc.qt.io/qt-6/qt.html#SplitBehaviorFlags-enum
Comment: Yes thanks. That was the issue. I should have looked at the docs closer. Not sure if I should just delete this question. Coding late at night and your mind just starts making things up.
Answer: The second parameter to split method is of type Qt::SplitBehavior and as mentioned in the comment it is an old fashioned enum not C++11 enum class.
QStringList QString::split(const QString &sep, Qt::SplitBehavior behavior = Qt::KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

So you should use:
QStringList list = line.split("~", Qt::KeepEmptyParts, Qt::CaseSensitive);

But, QString's split method splits the string into substrings wherever sep occurs, and returns the list of those strings. You can't partially split the string using split method.
To split only on the first occurrence of delimiter use indexOf method as follows:
auto idx = line.indexOf('~');
auto part= line.mid(0, idx);
auto rest = line.mid(idx+1);
qDebug() << part;
qDebug() << rest;

Output:
"hello"
"world~how~are~you"

Comment: nothing wrong with `Qt::SplitBehavior::KeepEmptyParts` even if `SplitBehavior` isn't an `enum class` since c++11