Why are vector fields defined to be sections of the disjoint union of the tangent spaces? Isn't that overly complicated?

Question: It is usual to define the tangent bundle $TM$ as the disjoint union of all tangent space and then to define vector fields as sections of
\begin{align}
TM=\bigsqcup_{p\in M}T_pM=\bigcup_{p\in M}T_pM\times\{p\}&\to M\\
(v,p)&\mapsto p
\end{align}
(I am reading John Lee's book, where tangent vectors are introduced as derivations, such that $T_pM\cap T_qM\neq\emptyset$.)
Why don't we simply define $TM=\bigcup_{p\in M}T_pM$ and say that a vector field is a map $\omega\colon M\to TM$ with $\omega_p\in T_pM$ for all $p\in M$.
Isn't this the essential property of a vector field: That is assigns to all $p\in M$ an element of $T_pM$?
An analogous question arises for Differential forms.
An attempt to clarify the question: I have to prepare a talk about the Maxwell equations in terms of differential forms and I have an audience who does neither know what a manifold is, nor what a tensor ist. I have 30 minutes for a crash course in this stuff. This means that I have to leave out as much information as possible, but I want everything I say to be correct. So one question I asked myself is: Do I miss out on something if I don't explain what disjoint unions and sections are and simply give them my definition above? Is there a good reason to define the tangent bundle as the disjoint union of tangent spaces instead of the ordinary union (besides wanting to introduce the notion of sections)? But this are questions I already asked myself before having to give this talk.
Comment: What is your question? What you just described is EXACTLY the definition of a section. So it sounds like you are saying "why don't we simply define....", and then you describe the same definition that you said is overly complicated.
Comment: If your manifold is inside of a larger manifold, such as being a submanifold of $\mathbf R^n$, so you can picture the tangent spaces as being inside the larger manifold, they might overlap.  Consider the union of the tangent lines at all points on the circle.  There is a lot of overlapping, which we don't want in the tangent bundle of the circle (the tangent bundle is a cylinder: rotate those tangent lines by 90 degrees to avoid intersecting tangent lines).
Comment: It seems like you are taking issue with the "disjoint" part? What other thing could $\bigcup_{p \in M}$ possibly mean in this context?
Comment: @AlexProvost The normal union.
Comment: Does your use of "normal" in "normal union" mean "ordinary" or "perpendicular"?  Please make a better effort at explaining what you are trying to say.
Comment: The "standard union" is often mistaken as an union of subsets of a fixed set. Here, the tangent space is defined to be an union of different vector spaces that does not live in the same fixed space; they are disjoint. So, this is a disjoint union. Also, a map that assigns to a point $p$ a vector $v_p$ in $T_pM$ is exactly the definition of a section of $TM$.
Comment: @AlexProvost As an undergraduate who has for the most part only read John Lee's books on differential geometry, I unfortunately don't understand your comment. What do you mean by "intrinsical"?
Comment: When you wrote "normal union" (before changing it after my later comment and others to "ordinary union") I thought you might be making a reference to a normal bundle in some way.  That is a type of vector bundle and you are asking about tangent bundles, which is another type of vector bundle. In geometry "normal" can mean "perpendicular" or "orthogonal".
Answer: There are two major issues here.
First of all, the only way for the union to not be disjoint and make any sense at all is if the tangent spaces are assumed to live in a common universal set, which isn't generally the case.
Secondly, even if you embed the tangent spaces in a common universe, e.g. by embedding the manifold inside some Euclidean space, then you lose crucial information by taking a regular union, since the line between tangent vectors and points becomes blurred and points living in distinct tangent spaces may get identified. For example, consider the tangent bundle of the circle embedded in $\Bbb{R}^2$, as in the following picture:
By taking a regular union, you get the subset of $\Bbb{R}^2$ consisting of all the points in red as your tangent bundle. But then all the points which lie on multiple lines "forget" which tangent space they belong to. For example, the point $(1,1)$ lies on the tangent space at $(1,0)$ as well as the tangent space at $(0,1)$. Therefore you lose the canonical surjection $\bigcup_p T_pM \to M$ which is used, among many other things, to endow the tangent bundle with a manifold structure. Disaster!
Finally, to adress the part where you mention vector fields: it is important to note that such objects are not mere set-theoretic sections of the map $\bigcup_p T_pM \to M$; they are continuous or smooth sections. And in order for this to make sense, we need a topology/smooth structure on the tangent bundle.
Comment: "Disaster!" Made my day :D I am not sure that I understand your first point: Do you mean that $\bigcup_{p\in M}T_pM$ is not well defined if the tangent spaces don't live in a common universe? Isn't $\bigcup_{p\in M}T_pM$ a common universe?
Comment: But I understand what you mean by the "disaster" (and the final part about vector fields) and I think that's a very good point :) Thank you!
Comment: @Filippo If it's clear from the context that all the $T_pM$ are disjoint as they should be, then sure, you can write $\bigcup_p T_pM$. You just don't want to give anyone the idea that a single tangent vector can live in two distinct tangent spaces simultaneously. The disjoint union formalism (appending the index $p$ to each copy of $T_pM$) just makes it simpler to define the relevant maps set-theoretically/categorically. (The disjoint union is the coproduct in the category of sets as well as topological spaces.)
Answer: There are lots of good answers here, all of which elucidate certain parts of the situation. But there's one important point that hasn't been mentioned -- in the definition of tangent spaces that I use in my Smooth Manifolds book, the zero derivation is an element of $T_pM$ for every $p\in M$, so if you don't use disjoint union in the definition of the tangent bundle, the tangent spaces will all intersect. See also this answer.
Comment: What a nice surprise to get an answer from the author whose books enabled me to learn differential geometry :) I was aware of the fact that the tangent spaces intersect, but I didn't know why that is a problem. But now I see that this has to do with the fact that the map $\pi\colon TM\to M$ is needed to allows us to endow $TM$ with a manifold structure.
Answer: Suppose $M \subset \mathbb{R}^n$ is a submanifold. Then one may define its tangent bundle to be the union of all the tangent vector spaces  $T_pM$ to $M$ at points $p$. The problem is what is to be understood as "union" here.
Suppose you define it to be the union as subsets of $\mathbb{R}^n$.
For example, if $M = \mathbb{R} \subset \mathbb{R}$, then at each point the tangent space is $\mathbb{R}$, so all the tangent subsets are equal to the same subspace of $\mathbb{R}$, namely $\mathbb{R}$, and so is their union.
Now suppose $M = \mathbb{S}^1 \subset \mathbb{R}^2$. Then any vector line $D$ can be seen as the tangent space of a point of the circle. So here, the usual union as subsets of $\mathbb{R}^2$ will be the union of all vector lines of $\mathbb{R}^2$, which is $\mathbb{R}^2$.
These constructions are "extrinsic" as they depend not only on $M$ but also on the ambient space $\mathbb{R}^n$. For example, if one says $M \subset \mathbb{R}^n \simeq \mathbb{R}^n\times\{0\} \subset \mathbb{R}^m$, then one can define a "different $TM$", depending on the viewpoint (even if they will be isomorphic).
But in these two examples, if you take a random element of the union, you don't know at which point it is tangent. You lose a lot of geometric sense.
The idea to avoid this is to take a disjoint union, namely
$$TM = \bigcup_{p\in M} \{p\}\times T_pM.$$
An element of this union is of the form $(p,v)$ with $v \in T_pM$, so each element has in its construction more data than in the previous example.
For the first example, this construction gives $T\mathbb{R} = \bigcup_{p\in\mathbb{R}} \mathbb{R} = \mathbb{R}\times \mathbb{R}$, and any tangent vector is of the form $(x,t)$ where $t$ is tangent to $x$.
For the circle, it gives $T\mathbb{S}^1 = \bigcup_{\theta \in \mathbb{S}^1} \{\theta\} \times T_{\theta}\mathbb{S}^1$, etc.
For an abstract manifold, there is no "ambient space", so the usual union of the tangent spaces cannot be defined as an union of subspaces of the same fixed set. Therefore, it would have been a bad construction as we would not have been able to extend it. But the disjoint-union allows us to define, for a general manifold $M$ that is not embedded in a Euclidean space,
$$T_pM = \bigcup_{p\in M}\{p\}\times T_pM,$$
where $T_pM$ is an intrinsic notion in $M$, depending only on the differential structure.
In addition, this construction shows that there is a natural structure of fiber-bundle on the tangent space $TM$ (this is a more general concept), and this construction automatically gives a smooth function $\pi : TM \mapsto M$ that is just the projection $(p,v) \mapsto p$.
If one wants to define a vector field by the idea that "at each point $p$ it has a tangent vector to $p$", then it can be rigorously defined using this construction as a continuous map $X : M \to TM$ such that $X(p) = (p,v_p)$. This is equivalent to saying that $X$ is a (continuous) section of $\pi$, that is $\pi\circ X = \mathrm{id}_M$.
Usually we require the vector field to be smooth, which means $X$ is smooth (a smooth section).
Edit: It is a common problem for geometers, when they have to give a talk to non-specialists, to give a clear presentation while the audience has no idea of the principal objects we use, such as manifolds, vector bundles, etc. My experience is this: do not lose time giving overly complicated definitions if what is really important is the geometric sense. Just say that a manifold is a geometric notion that can extend the definition of surfaces, etc. Define tangent vectors visually. Say that a tangent field is a field of tangent vectors without talking about bundles. Same for covectors. If you have to talk about operators in bundles, just talk about how they act on vectors. You will gain a lot of time and the audience will probably understand many more things than if you had given some overly complicated rigorous statements.
Comment: First of all, thank you for the elaborated answer and the advice for my presentation :)
Comment: Unfortunately, I don't understand the fourth paragraph at all. Could you please explain that part to me a bit more? For example, I don't understand what you mean by "defining different TM".
Answer: This is just rewriting what has been written a few times, but when $M\subset \Bbb R^N$, then
$$TM = \{(x,v): x\in M, v\in T_xM\}\subset M\times\Bbb R^N.$$
There's your universe. For an abstract manifold, of course, this makes no sense, because there is no sensible thing to substitute for $\Bbb R^N$.
Comment: Why doesn't the definition $TM = \{(x,v): x\in M, v\in T_xM\}$ make sense in the case of an abstract manifold? That's exactly the way John Lee defines the tangent bundle.
Comment: In addition, if we define tangent vectors to be derivations, wouldn't $\text{Hom}\left(C^{\infty}M,\mathbb R\right)$ be a sensible substitute for $\mathbb R^N$? That is, $TM\subset M\times\text{Hom}\left(C^{\infty}M,\mathbb R\right)$.
Answer: Here's an explanation that will fit into the time allotted for your crash course:
Physicists will sometime say that two vectors are the same if they point in the same direction and have the same base point.
As the abstraction that mathematicians have adopted for vectors doesn't include the base point, "$\times \{p\}$" is how they label each vector with its base point. By the way, this is also probably how computer programmers would go about it too.


Problem involving cross ratio identity

Question: Let $z_1, z_2, z_3, z_4$ be distinct complex numbers. Assume that they lie on the same circle, in that order. Prove that $$|z_1 - z_3||z_2 - z_4| = |z_1 - z_2||z_3 - z_4| + |z_2 - z_3||z_4 - z_1|$$
So let F be a fractional linear map which sends $z_2, z_3, z_4$ to $1,0,\infty$ respectively. Note that since any fractional linear map is just a combination of translations, inversions and multiplications, it has to maintain the order of $z_1, z_2, z_3$ and $z_4$ if these points lie on the same circle. So neccesarily, $F(z_1) \in  ]1, \infty[$. Is what I have done useful so far, if so, how do I continue?
Thanks in advance
Answer: $\sf Hint$:
$$\large |\color{Green}{z_1-z_3}||\color{Teal}{z_2-z_4}|=|z_1-z_2||z_3-z_4|+|\color{DarkBlue}{z_2-z_3}||\color{Purple}{z_4-z_1}|;$$
$$\large (z_1,z_2;z_3,z_4):=\frac{(\color{Green}{z_1-z_3})(\color{Teal}{z_2-z_4})}{(\color{DarkBlue}{z_2-z_3})(\color{Purple}{z_1-z_4})},~~~~~(z_1,z_3;z_2,z_4)=?$$
Comment: @user50945 How about this: divide the whole equation by $|z_2-z_3||z_4-z_1|$; it becomes $$|(z_1,z_2;z_3,z_4)|=|(z_1,z_3;z_2,z_4)|+1.$$ As Mobius transformations preserve cross-ratios, this equation is equivalent to $|(z,1,0,\infty)|=|(1,0;z,\infty)|+1$ for $z\in(1,\infty)$, which you can check by hand.
Comment: If I am not mistaken, $(z_1,z_3;z_2,z_4)$ = $-(z_1,z_2;z_3,z_4)=$
Comment: @user50945 That is indeed mistaken.
Comment: Sorry, $(z_1,z_3;z_2,z_4)= 1 - (z_1,z_2;z_3,z_4)$
Answer: For any 4 points $z_{1},z_{2},z_{3},z_{4}$ we have $$(z_{2}-z_{1})(z_{4}-z_{3})+(z_{3}-z_{2})(z_{4}-z_{1})=(z_{3}-z_{1})(z_{4}-z_{2})$$
Applying the triangle inequality we get $$|z_{2}-z_{1}||z_{4}-z_{3}|+|z_{3}-z_{2}||z_{4}-z_{1}| \geq |z_{3}-z_{1}||z_{4}-z_{2}|$$
We have equality if $(z_{2}-z_{1})(z_{4}-z_{3})$ and $(z_{3}-z_{2})(z_{4}-z_{1})$ have the same direction.
Let $$\alpha=\textbf{arg}\left(\frac{z_{2}-z_{1}}{z_{4}-z_{1}}\right)\text{  and  }\beta=\textbf{arg}\left(\frac{z_{4}-z_{3}}{z_{3}-z_{2}}\right)$$
In a cyclic quadrilateral $$\alpha=-\beta(\text{Property of cyclic quadrilaterals})\\\rightarrow\alpha+\beta=0$$
$$\rightarrow\frac{z_{2}-z_{1}}{z_{4}-z_{1}}\cdot\frac{z_{4}-z_{3}}{z_{3}-z_{2}}=\text{a  positive real number}$$
Therefore,
$$|z_{2}-z_{1}||z_{4}-z_{3}|+|z_{3}-z_{2}||z_{4}-z_{1}| = |z_{3}-z_{1}||z_{4}-z_{2}|$$
Answer: Hint: There is a theorem in geometry that says that the product of the diagonals of an inscribed quadrilateral is the sum of the products of the opposing sides.

Here is a proof using trigonometry. I will look for a simpler proof, if no one else does first.
$\hspace{3.6cm}$
Using cross-products to find the area of the quadrilateral yields
$$
\begin{align}
\text{Area of quadrilateral}
&=\frac12(ad+bc)\sin(\phi)\\
&=\frac12(e_1f_1+e_1f_2+e_2f_1+e_2f_2)\sin(\theta)\\
&=\frac12ef\sin(\theta)\tag{1}
\end{align}
$$
Using the Law of Cosines to find $f$ yields
$$
\begin{align}
f^2&=a^2+d^2-2ad\cos(\phi)\\
&=b^2+c^2+2bc\cos(\phi)\\
a^2+d^2-b^2-c^2&=2(ad+bc)\cos(\phi)\tag{2}
\end{align}
$$
Using the Law of Cosines to find $a,b,c,d$ yields
$$
\begin{align}
a^2&=e_1^2+f_2^2+2e_1f_2\cos(\theta)\\
b^2&=e_2^2+f_2^2-2e_2f_2\cos(\theta)\\
c^2&=e_2^2+f_1^2+2e_2f_1\cos(\theta)\\
d^2&=e_1^2+f_1^2-2e_1f_1\cos(\theta)\\
a^2-b^2+c^2-d^2&=2ef\cos(\theta)\tag{3}
\end{align}
$$
Putting together $(1)$, $(2)$, and $(3)$ yields
$$
\begin{align}
e^2f^2&=e^2f^2\cos^2(\theta)+e^2f^2\sin^2(\theta)\\
&=\frac14(a^2-b^2+c^2-d^2)^2+(ad+bc)^2\sin^2(\phi)\\
&=\frac14(a^2-b^2+c^2-d^2)^2+(ad+bc)^2-(ad+bc)^2\cos^2(\phi)\\
&=\frac14(a^2-b^2+c^2-d^2)^2+(ad+bc)^2-\frac14(a^2+d^2-b^2-c^2)\\[4pt]
&=(a^2-b^2)(c^2-d^2)+(ad+bc)^2\\[8pt]
&=(ac+bd)^2\\[9pt]
ef&=ac+bd\tag{4}
\end{align}
$$

Problem involving cross ratio identity


Template Argument Deduction Broken in Clang 6 for Temporary Objects

Question: Template argument deduction appears to be broken in Clang 6 for temporary objects.
g++ 8.1.0 compiles and runs the example correctly.
Clang 6.0.0 and 6.0.2 both error at the indicated line with this message:
error: expected unqualified-id
    Print{1,"foo"s,2};  /********** Broken in Clang **********/

All Other lines work correctly.
The behavior is the same in both cases whether -std=c++17 or -std=c++2a is used.
The Clang c++ Status Page indicates that template argument deduction was implemented as of Clang 5 (P0091R3, P0512R0).
Is this a bug? Are there workarounds (e.g. compiler flags, not code changes)?
example:
template<class ...Ts>
void print(Ts...ts){ (( cout << ... << ts )); }
template<class ...Ts>
struct Print {
    Print(Ts...ts){ (( cout << ... << ts )); }
};

int main(){
    Print{1,"foo"s,2}; /********** Broken in Clang **********/
    Print<int,string,int>{1,"foo"s,2};
    auto p1 = Print{1,"foo"s,2};
    Print p2{1,"foo"s,2};
    print(1,"foo"s,2);
}

Answer: This is Clang bug 34091.
Luckily, it is already fixed, and the trunk build of Clang compiles this without issue.
As far as I know, however, there is currently no way to work around this without code changes, short of upgrading to the next Clang release whenever that comes out.


Discrete maths proposition, proof for multiplication

Question: i have this multiplication table for ℤ5,
<code>  *   [0] [1] [2] [3] [4]
-------------------------------
 [0]  [0] [0] [0] [0] [0]
 [1]  [0] [1] [2] [3] [4]
 [2]  [0] [2] [4] [1] [3]
 [3]  [0] [3] [1] [4] [2]
 [4]  [0] [4] [3] [2] [1]
</code>
How do i get the identity for multiplication and the multiplicative inverses for all the elements? i know that the identity is [1]. am i right?
Comment: Yes, you are. So the multiplicative inverse of $[2]$, say, is whatever $[k]$ satisfies $[2][k]=[1]=[k][2]$; what $[k]$ is that?
Comment: so are you implying that whatever gives a result of = [1] is the inverse?
Comment: Once you know that $[1]$ is the multiplicative identity, that's the definition of multiplicative inverse.
Comment: @BrianM.Scott ok thank you!
Comment: You're welcome!
Comment: Did you find an inverse of $[0]$ by the way?
Answer: The identity may be determined by trying to find a column in which each entry is identical to the element representing the corresponding row.
Equivalently, you may also look for a row having a similar property.
Once you have the identity, you can use Brian's method to figure out the inverse for each element.


Is $f(y) = \frac{\sin y}{y}$ a continuous function?

Question: Is $f(y) = \frac{\sin y}{y}$ a continuous function?
I am not sure about the point at $y=0$, the denominator cannot be zero but the numerator is also zero! The limit at $y=0$ exists but what about the original function?
Comment: Do you mean $f(x)=\sin x/x$ (rather than $f(x)=\sin y/y$)?
Comment: The RHS of the function definition $f(x) = \frac{\sin x}{x}$ is undefined at $x = 0$. However, if you assign a value $1$ to $f(0)$, it will turn it to a continuous function. Since $1$ is the only value which can turn $f(x)$ to a continuous function, when we say $f(x) = \frac{\sin x}{x}$, we usually assume $f(0) = 1$ and work with this extension of $f$ from $\mathbb{R} \setminus \{0\}$ to $\mathbb{R}$.
Comment: What's the domain of $f$?
Comment: Hint: What is the Taylor expansion of $f(x)$?
Answer: The definition says that $f : D \to \mathbb{R}$ is continuous if for all $a \in D$ (the domain of $f$),
$$ \lim_{x \to a} f(x) = f(a). $$
So if we're considering continuity at $0$ then first of all $0$ must be in the domain of $f$ and then we're asking if
$$ \lim_{x \to 0} f(x) = f(0). $$
So you see that we need to say what $f(0)$ is before we can make a decision about whether or not $f$ is continuous at $0$.
So there are two reasonable functions we can consider:
$$ f : \mathbb{R} \to \mathbb{R} \text{ defined by } f(x) = \begin{cases}
\frac{\sin x}x & x \ne 0 \\
1 & x  = 0
\end{cases} $$
or
$$ f : \mathbb{R} \setminus \{0\} \to \mathbb{R} \text{ defined by } f(x) = \frac{\sin x}x. $$
Both of these functions are continuous. The first is continuous at $0$ because we've defined $f(0)$ as $\lim_{x \to 0} \frac{\sin x}{x}$. The second is also continuous at every point in its domain for the simple reason that $0$ is not in its domain.


Monitor open files limits, etc

Question: We've been hitting the max open files limit on a few services recently. There are also a bunch of other limits in place. Is there a way to monitor how close processes are to these limits so we can be alerted when it's time to either up the limits or fix the root cause? On the same note, is it possible to view a log of these events so we know when a crash occurs it's because of hitting one of these limits?
Answer: Assuming a linux server.
see global max open files:
cat /proc/sys/fs/file-max

see global current open files:
cat /proc/sys/fs/file-nr

change global max open files:
sysctl -w fs.file-max=1000000 or edit sysctl.conf

see limit on current user:
ulimit -Hn   (hard limit)
ulimit -Sn   (soft limit)

change limit on user:
edit /etc/security/limit.conf to set limits for a webserver for example
apache2 soft nofile 4096
apache2 hard nofile 10000

You can have a script go through /proc and gives you some statistics:
for pid in $(pgrep apache2); do ls /proc/$pid/fd | wc -l; done

Answer: Yes, you can. /proc/<pid>/fd lists all open file descriptors. Memory usage can be seen in /proc/<pid>/{maps,smaps}. Just browse thorugh /proc/<pid> a bit and google files you don't understand :)

Monitor open files limits, etc


custom UIcollectionViewCell, using view to control color changes

Question: I was going thru the tutorial here: http://pinkstone.co.uk/how-to-build-a-uicollectionview-in-ios-8/
And saw a part that looked great because it makes something simple, use of views to show color changes of selected/unselected items.-
(void)awakeFromNib {

    // background color
    UIView *bgView = [[UIView alloc]initWithFrame:self.bounds];
    self.backgroundView = bgView;
    self.backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue"]];

    // selected background
    UIView *selectedView = [[UIView alloc]initWithFrame:self.bounds];
    self.selectedBackgroundView = selectedView;
    self.selectedBackgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pink"]];
}

The author showed that this is a simple approach that eliminates the need to manage the state of the cells.
Q. I want to change the color using this method during the highlight process. However, didHighlightItemAtIndexPath is in the CollectionViewController and I'd like to have it use the same process.
Basically what it does is change from one color to another based on selected/unselected.  I'd like to use the add a color to indicate the in between state of being highlighted/unhighlighted.
I checked all the methods that are in cell that use UIView, and there is nothing for highlighted/unhighlighted.
Any ideas on an approach that has the advantages of using cell methods?  Can I call a custom method from the viewcontroller method and load a view there?
You might think of this as a "press and hold" that changes the color when it's being held.
Answer: A UIView wouldn't know anything about it's selected or unselected state since it's a very elemental component and not specific to controls that allow selection.  The UICollectionViewCell does have a selected property though, so that would be the right place to change these characteristics.  Looking at the docs it seems like either tapping into setSelected or selectedBackgroundView would give you a good opportunity to customize the L&F of selected cells.  There's also a highlighted state in case you might also be looking for that.


Sorting strings containing numbers in a user friendly way

Question: Being used to the standard way of sorting strings, I was surprised when I noticed that Windows sorts files by their names in a kind of advanced way. Let me give you an example:
Track1.mp3
Track2.mp3
Track10.mp3
Track20.mp3
I think that those names are compared (during sorting) based on letters and by numbers separately.
On the other hand, the following is the same list sorted in a standard way:
Track1.mp3
Track10.mp3
Track2.mp3
Track20.mp3
I would like to create a comparing alogorithm in Delphi that would let me sort strings in the same way. At first I thought it would be enough to compare consecutive characters of two strings while they are letters. When a digit would be found at some position of both the strings, I would read all digits following them to form a number and then compare the numbers.
To give you an example, I'll compare "Track10" and "Track2" strings this way:
1) read characters while they are equal and while they are letters: "Track", "Track"
2) if a digit is found, read all following digits: "10", "2"
2a) if they are equal, go to 1 or else finish
Ten is greater than two, so "Track10" is greater than "Track2"
It had seemed that everything would be all right until I noticed, during my tests, that Windows considered "Track010" lower than "Track10", while I thought the first one was greater as it was longer (not mentioning that according to my algorithm both the strings would be equal, which is wrong).
Could you provide me with the idea how exactly Windows sorts files by names or maybe you have a ready-to-use algorithm (in any programming language) that I could base on?
Thanks a lot!
Mariusz
Comment: Sorry, but I didn't even know what phrase to search for before. This is the reason why I duplicated this question unwittingly. Now I know that this way of sorting is called 'natural sorting', so I can search for some more information about it by myself.
Comment: Dupe of many other questions including: http://stackoverflow.com/questions/34518/natural-sorting-algorithm
Comment: Look this http://stackoverflow.com/questions/31538293/sorting-listfileinfo-in-natural-sorted-order
Comment: Duplicate of http://stackoverflow.com/q/248603/24874 (has some good answers)
Answer: Jeff wrote up an article about this on Coding Horror. This is called natural sorting, where you effectively treat a group of digits as a single "character". There are implementations out there in every language under the sun, but strangely it's not usually built-in to most languages' standard libraries.
Comment: Thanks for the clue. I managed to find a Windows API function StrCmpLogicalW (http://msdn.microsoft.com/en-us/library/bb759947.aspx) which is what I was looking for.
Comment: Here's PHP's implementation: [natsort](http://php.net/manual/en/function.natsort.php)
Answer: The mother of all sorts:
ls '*.mp3' | sort --version-sort
Answer: The absolute easiest way, I found, was isolate the string you want, so in the OP's case, Path.GetFileNameWithoutExtension(), remove the non-digits, convert to int, and sort.  Using LINQ and some extension methods, it's a one-liner.  In my case, I was going on directories:
Directory.GetDirectories(@"a:\b\c").OrderBy(x => x.RemoveNonDigits().ToIntOrZero())

Where RemoveNonDigits and ToIntOrZero are extensions methods:
public static string RemoveNonDigits(this string value) {
    return Regex.Replace(value, "[^0-9]", string.Empty);
}

public static int ToIntOrZero(this string toConvert) {
    try {
        if (toConvert == null || toConvert.Trim() == string.Empty) return 0;
        return int.Parse(toConvert);
    } catch (Exception) {
        return 0;
    }
}

The extension methods are common tools I use everywhere.  YMMV.
Answer: Here's a Python approach:
import re

def tryint(s):
    """
    Return an int if possible, or `s` unchanged.
    """
    try:
        return int(s)
    except ValueError:
        return s

def alphanum_key(s):
    """
    Turn a string into a list of string and number chunks.

    >>> alphanum_key("z23a")
    ["z", 23, "a"]

    """
    return [ tryint(c) for c in re.split('([0-9]+)', s) ]

def human_sort(l):
    """
    Sort a list in the way that humans expect.
    """
    l.sort(key=alphanum_key)

And a blog post with more detail: https://nedbatchelder.com/blog/200712/human_sorting.html


Getting list of attributes inside a JSON

Question: Is it possible to get list of attributes of a particular JSON map with a JSONPath expression? For example:
{"foo": 1, "bar": 2} => ["foo","bar"]
Comment: Here's a [link](http://stackoverflow.com/questions/208016/how-to-list-the-properties-of-a-javascript-object) that may help you.
Answer: You can use the following code:
Object.getOwnPropertyNames({"foo": 1, "bar": 2})

Here's a link for further information.
Comment: English link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames
Answer: Loop through each json object get all the keys and push then into an array. You can try this:

var data=[{"foo": 1, "bar": 2},{"foo1": 1, "bar1": 2}];
var array=[];
$.each(data, function(key, value){
  var item;
   item=Object.keys(value);
  array.push(item);
});

console.log(array);


Understanding Smirnov words in analytic combinatorics

Question: I am trying to understand a generating function in the explanation of Smirnov words in this book, in page $204-205$.
It is said that
"
Smirnov words. Following the treatment of Goulden and Jackson [303], we
define a Smirnov word to be any word that has no consecutive equal letters. Let $W = SEQ(A)$
be the set of words over the alphabet $A = {a_1,. . . , a_r}$ of cardinality $r$, and $S$ be the set of Smirnov words
Let also $v_j$ mark the number of occurrences of the $j$th letter in a word.One has $$W(v_1,v_2,...,v_r)=\frac{1}{1-z(v_1+v_2+..+v_r)}$$ "
Here , I understood that for example $v_1$ marks the number of occurences of $a_1$ in a word. Am I right here ?
Now, lets come to my main question.By thinking my foregoing deduction as true ,i.e , $v_1$ denotes the number of occurences of $a_1$, assume that our alphabet is $A={a,b}$ and by giving any occurrence to these letters, i can obtain the number of any words of desired size. Am I also right here ?
So , i think that lets say that $a$ can occur two times and $b$ can occur maximum three times. Then $$W(x^2,(x+x^2+x^3))=\frac{1}{1-z\bigg((x^2)+(x+x^2+x^3)\bigg)}$$
Then , I want to learn the number of all words of length $3$ using $a,b$, it must be $2^3=8$ , but when i look at the coefficient of $[z^3x^3]$ in wolfram, it is $1$
Is there any deficit part in the book ? I think that it should have been indicated that "Let also $v_j$ mark the number of occurrences of the $j$th letter in a word from one to desired repetition".
Am I right here ? Should we always start from $x^1$ up to $x^k$ where $k$ is the number of maximum consecutive identical letter.
Comment: Well, $W$ is not defined as a function of $z,$ so I don't understand.
Comment: @ThomasAndrews "The variable z marking length, being redundant, is best omitted in this calculation." it is at the bottom of the page
Comment: @epi163sqrt i read your [answer](https://math.stackexchange.com/questions/4728370/understanding-smirnov-words-in-analytic-combinatorics/4728478#4728478). Am i wrong here ?
Answer: Let us focus on the two letter alphabet case. I will use $A$ and $B$ to refer to the letters themselves, while $a$ and $b$ are the variables for the generating function. We have two generating functions of interest:

Generating function
Meaning

$W(a,b)=\frac1{1-(a+b)}$
$[a^mb^n]W(a,b)=\text{# words with $m$ $A$'s and $n$ $B$'s}$

$S(a,b)= W\left(\frac{a}{1+a},\frac{b}{1+b}\right)$
$[a^mb^n]S(a,b)=\text{# Smirmov words with $m$ $A$'s and $n$ $B$'s}$

Let us check that $S(a,b)$ works properly.
$$
S(a,b)=\frac{1}{1-\frac{a}{1+a}-\frac b{1+b}}=\frac1{1-ab}+\frac{a}{1-ba}+\frac b{1-ab}+\frac{ba}{1-ba}
$$
Note that $\frac1{1-ab}=1+ab+abab+ababab+\dots$, which represents all Smirmov words like the empty word, $AB$, $ABAB$, $ABABAB$, and so on. Next, $\frac{a}{1-ba}=a+bab+babab+\dots$, representing $A$, $ABA$, $ABABA$, and so on. Similarly, $\frac b{1-ab}$ represents $B, BAB,BABAB,\dots$, while $\frac{ba}{1-ba}$ represents $BA, BABA, BABABA,\dots$. You can check that these four groups represent all possible sequecne of $A$ and $B$ with no instances of $AA$ and $BB$, so $S(a,b)$ works as intended.
Next, suppose that you want to count words where there are at most $p$ instances of $A$ in a row, and at most $q$ instances of $B$ in a row, for some integers $p$ and $q$. The authors say that if you substitute $a+a^2+\dots+a^p$ and $b+b^2+\dots+b^q$ into $S(a,b)$, then this does exactly what you want. For example, let $p=2$ and $q=3$. Then you can find the number of words with $3$ $A$'s and $4$ $B$'s, such that no instances of $AAA$ or $BBBB$ occur, by extracting
$$
[a^3b^4]S(a+a^2,b+b^2+b^3)=28.
$$
See Wolfram|Alpha computation. Indeed, the 28 valid words are listed below:
<code>AABABBB AABBABB AABBBAB ABAABBB ABABABB ABABBAB ABABBBA
ABBAABB ABBABAB ABBABBA ABBBAAB ABBBABA BAABABB BAABBAB
BAABBBA BABAABB BABABAB BABABBA BABBAAB BABBABA BABBBAA
BBAABAB BBAABBA BBABAAB BBABABA BBABBAA BBBAABA BBBABAA
</code>
If you just wanted to count the number of valid words of a given length, instead of with a given frequency of each letter, you need to replace both $a$ and $b$ with a generic variable, say $x$. In that case, you find
$$
[x^7]S(x+x^2,x+x^2+x^3)=63,
$$
so there are $63$ words of length $7$ with no instances of $AAA$ or $BBBB$.
However, there is no utility in considering $W(a+a^2,b+b^2+b^3)$. The authors never claimed there was any utility to this, only for substituting in $S$. The problem is, since $W(a,b)$ enumerates all sequences of $a$ and $b$, there would be ambiguity when you expand $W(a+a^2,b+b^2+b^3)$, so some words would be double-counted, and the coefficients lose any useful meaning.
The problem is best illustrated with a single-letter alphabet.
$$
\begin{align}
W(a+a^2)&=\frac1{1-(a+a^2)}
\\&=1 + (a+a^2)+(a+a^2)^2+\dots
\\&=1+a+aa+\color{red}aa + \color{red}2aaa + aaaa+\dots
\\&=1+a+2a^2+\dots
\end{align}
$$
As you can see, the coefficient of $a^2$ is $2$, which is incorrect, because there is only one word of length $2$, namely $AA$. However, this word was counted twice. This problem does not occur when substituting in $S(a,b)$, because $S$ was carefully constructed to not allow repeated instances, so no ambiguity.
Comment: hi Mike, i realized the overcounting when we deal with $W(a+a^2)$, so to reach the correct result, i added the variable $z$ as i mentioned in my post. When you look for some thing, you should look at $[z^ka^k]$. Moreover, another user write some comments [here](https://math.stackexchange.com/questions/4056459/how-many-length-n-bitstrings-containing-3-consecutive-0s-and-4-consecuti/4191721#4191721). Can you please look at that, i think their comment is right
Comment: hımm, but how do we calculate the coefficient of $v_1^{n_1}v_2^{n_2}...v_r^{n_r}$ in $W(v_1,...,v_r)$, $W(v_1,...v_r)$ denotes generating function such that $$W(v_1,...v_r)=\frac{1}{1-(v_1+...+v_r)}$$ I think that $v_j$ means the sequence of possible values that $a_j$ can take maximum consecutively in a expended Smirnov word. For example, if it is allowed only maximum two consecutive $a's$ and three consecutive $b$ in a Smirnov word, then their generating functions according to their exponents are $v_1=x+x^2$ and $v_2=x+x^2+x^3$,respectively. See the next comment...
Comment: So , using multivariable generating function $W$, we can find the number of all words using $a$ and $b$ (not have to be Smirnov). For example, if you look at the coefficient of $z^kx^k$ where $k$ represent the length of the word in the expansion of $$W(v_1,v_2)=\frac{1}{1-((x+x^2)+(x+x^2+x^3))}$$ I have found an answer written by @epi163sqrt [here](https://math.stackexchange.com/questions/4056459/how-many-length-n-bitstrings-containing-3-consecutive-0s-and-4-consecuti/4191721#4191721) which use Smirnov words. I think it corrects my intuition.
Comment: In my intuition, for example the number words of length $2$, $$((x+x^2)+(x+x^2+x^3))((x+x^2)+(x+x^2+x^3))$$ $(x+x^2)(x+x^2)$ means $xx+xx^2+x^2x+x^2x^4$, then they mean $aa,aaa,aaa,aaaa$, respectively. For another exapmle , $$(x+x^2+x^3)(x+x^2)$$ will give us $xx,xx^2,x^2x,x^2x^2,x^3x,x^3x^2$ means $bb,baa,bba,bbaa,bbba,bbbaa$ ,respectively
Comment: When you expand them like that you will obtain all possible words using $a,b$ .Moreover, $z^2x^2$ will show you $aa,ab,ba,bb$ as we desired
Comment: because of addding variable $z$, i think that we can find all words  like @notasalmon fish did
Comment: moreover, can you please help to understand how $$W(v_1,v_2)=S(v_1/(1-v_1),v_2/(1-v_2)$$ I did not think it before @notasalmonfish asked in their comment. These two are generating functions but how their coefficient become equal ? (I understand the logic that if you expand the smirnov words you obtain all words but not in the form of generating fnctions)
Comment: @MikeEarnest: Very nice update! (+1)
Comment: how can we expand $S(x+x^2,x+x^2+x^3)$ without using $S(a,b)=W(a/(1+a),b/(1+b))$ but just using the generating function of $$S((x+x^2)/(1-(x+x^2),(x+x^2+x^3)/(1-(x+x^2+x^3))$$
Comment: @MikeEarnest thanks for your nice answer and helps,but i can only accept one answer, so i could only upvoted. have a nice day :))
Comment: @goodboy I completely understand. epi163sqrt is one of the premium experts for generating functions on this website.
Answer: Here we consider a binary alphabet $\mathcal{A}=\{a,b\}$ and derive a generating function of Smirnov words following closely the example III.24 given in Analytic Combinatorics by R. Sedgewick and P. Flajolet.
Binary words over $\mathcal{A}$:
The set $\mathcal{W}$ of all binary words over the alphabet $\mathcal{A}$ is
\begin{align*}
\mathcal{W}=\{&\varepsilon,a,b,aa,ab,ba,bb,\\
&aaa,aab,aba,baa,abb,bab,bba,bbb,aaaa,\ldots\}
\end{align*}
where $\varepsilon$ denotes the empty word of length $0$. A generating function $W(z;a,b)$ for the set of all binary words is the geometric series
\begin{align*}
\color{blue}{W(z;a,b)}&=1+(a+b)z+(a^2+2ab+b^2)z^2\\
&\qquad\qquad+(a^3+3a^2b+3ab^2+b^3)z^3+a^4z^4+\cdots\\
&=\sum_{n=0}^{\infty}(a+b)^nz^n\\
&\,\,\color{blue}{=\frac{1}{1-(a+b)z}}
\end{align*}
Smirnov words over $\mathcal{A}$:
The set $\mathcal{S}$ of all binary Smirnov words, i.e. all binary words with no consecutive equal characters over $\mathcal{A}$ is
\begin{align*}
\mathcal{S}=\{&\varepsilon,a,b,ab,ba,aba,bab,\\
&abab,baba,ababa,babab,ababab,bababa,\ldots\}\tag{1}
\end{align*}
Of course we see in (1) at a glance there are precisely two non-empty Smirnov Words of length $n, n\geq 0$. One of them starting with $a$, the other with $b$. A generating function $S(z)$ which counts the number of Smirnov words in the binary case is simply
\begin{align*}
S(z)&=1+2z+2z^2+2z^3+2z^4+\cdots\\
&=1+\sum_{n=1}^{\infty}2z^n\\
&=1+\frac{2z}{1-z}
\end{align*}
Looking at (1) we can also derive a generating function $S(z;a,b)$. Here the exponent of $a$ resp. $b$ indicates the number of occurrences of $a$ resp. $b$. We prefer to derive $S(z;a,b)$ from $W(z;a,b)$ which also provides information how this can be reached in the general case with alphabets of size $r\geq 2$.
The key observation is that a binary words can be transformed to a Smirnov word by replacing all consecutive characters by just one of them and on the other hand we can obtain all binary words by starting with the set $\mathcal{S}$ of Smirnov words and by replacing each occurrence of a character by one or more occurrences of this character. This transformation is done by
\begin{align*}
a\quad\to\quad a+a^2+a^3+a^4+\cdots&=\frac{a}{1-a}\\
b\quad\to\quad\  b+b^2+b^3+b^4+\cdots\ &=\frac{b}{1-b}\\
\end{align*}
We therefore have the following relationship between $S(z;a,b)$ and $W(z;a,b)$
\begin{align*}
\color{blue}{S\left(z;\frac{a}{1-a},\frac{b}{1-b}\right)=W(z;a,b)}\tag{2}
\end{align*}
For instance the Smirnov word $abab$ corresponds via (2) with the binary words
\begin{align*}
abab\quad\longleftrightarrow\qquad &abab,\\
&aabab,abbab,abaab,ababb,\\
&aaabab,abbbab,abaaab,ababbb,\\
&aaaabab,abbbbab,abaaaab,ababbbb,\\
&aabbab,aabaab,aababb,abbaab,abbabb,abaabb,\\
&\ldots
\end{align*}
We have the following relationship
\begin{align*}
a\quad\to\quad \frac{a}{1-a}\qquad\qquad \frac{\frac{a}{1+a}}{1-\frac{a}{1+a}}=a\tag{3}
\end{align*}
Thanks to (2) and (3) we can also derive the generating function $S(z;a,b)$ from $W(z;a,b)$ via
\begin{align*}
\color{blue}{S(z;a,b)=W\left(z;\frac{a}{1+a},\frac{b}{1+b}\right)}\tag{4}
\end{align*}
and we derive from (4)

\begin{align*}
\color{blue}{S(z;a,b)}&=W\left(z;\frac{a}{1+a},\frac{b}{1+b}\right)\\
&=\frac{1}{1-\frac{az}{1+az}-\frac{bz}{1+bz}}\\
&=\frac{(1+az)(1+bz)}{(1+az)(1+bz)-az(1+bz)-bz(1+az)}\\
&\,\,\color{blue}{=\frac{1+(a+b)z+abz^2}{1-abz^2}}\tag{5}\\
&\,\,\color{blue}{=1+(a+b)z+2abz^2+ab(a+b)z^3+2a^2b^2z^4+\cdots}\tag{6}
\end{align*}

We see the generating function $S(z;a,b)$ in (6) corresponds nicely with the set $\mathcal{S}$ in (1) giving for each even length $2m$ two Smirnov words with $m$ $a$'s and $m$ $b$'s and for each odd length $2m+1$ two Smirnov words with either one more $a$ than $b$'s or vice versa.
Note: As requested by a comment we can also show the validity of (2) algebraically. We consider (5) in the form
\begin{align*}
\frac{1+az+bz+abz^2}{1-abz^2}
\end{align*}
and have according to (3) to substitute each occurrence of $az$ with $\frac{az}{1+az}$ and each occurrence of $bz$ with $\frac{bz}{1+bz}$. This type of substitution is indicated in the parameter representation in (4).
We obtain from (5)
\begin{align*}
&\color{blue}{S\left(z;\frac{a}{1-a},\frac{b}{1-b}\right)}\\
&\qquad=\frac{1+\frac{az}{1-az}+\frac{bz}{1-bz}+\frac{az}{1-az}\,\frac{bz}{1-bz}}
{1-\frac{az}{1-az}\,\frac{bz}{1-bz}}\\
&\qquad=\frac{(1-az)(1-bz)+az(1-bz)+bz(1-az)+abz^2}{(1-az)(1-bz)-abz^2}\\
&\qquad=\frac{1}{1-(a+b)z}\\
&\qquad\,\,\color{blue}{=W(z;a,b)}
\end{align*}
and (2) follows.
Comment: @NotaSalmonFish: No, your interpretation is sound. We should try to reduce the amount of comments. That's we I've deleted some of my old comments which have already been taken into account. :-)
Comment: nice answer, i have already upvoted two hours ago :), i want to ask something: can you explain the meaning of $S(z;a,b)$. I understand that it means the generating function of Smirnov words such that variables "a" and "b" can repeat once. If my understanding is true, then $S(z;a^3,b^2)$ means the number of words such that a's will repeat exactly trice and b's will repeat eaxctly twice ,e.g, $S(z;a^3,b^2)=aaabb,bbaaa,..$, and $S(z;a+a^2+a^3,b+b^2)$ means the words such that a's can repeat once or twice or trice consecutively and b's can repeat once or twice consecutively. Am i right ?
Comment: @NotaSalmonFish: Many thanks for upvoting. The notation $S(z;a,b)$ means that we consider a generating function of Smirnow words in the variable $z$. The parameter $a,b$ are used to indicate we are using binary words built from characters of the alphabet $\mathcal{A}=\{a,b\}$.
Comment: thanks for replying, then  my former interpretation for $S(z;a^3,b^2)$ is true ,as well, right?
Comment: wow, what a work, i wish there were an option to upvote more than once..), but i could not see how you determined the generating function for multivariable. As @goodboy write, i derived the generating function for unlimited repetiton using the generating function of $$S(z)=1+mz\sum_{n \geq 0}(m-1)^nz^n = \frac{1+z}{1-(m-1)z}$$ For example, what would happen if there were three variable, is there are logic behind writing generating function for $S(z,a/(1-a),b/(1-b),c(1-c),..$
Comment: @epi163sqrt thank you very much, it would be nice if i can see how you reach the generating function in the note, so as notasalmonfish said, i can see the derivations for three or more variable. Can you please explain your work for generating function in the note. why is it in the form of $1+a+b+ab/ (1-ab)$
Comment: @epi163sqrt thanks for your helps, i accept your beautiful and detailed answer, but when you have time for answering, please help me to understand the case that i wrote in last comment. I wonder how you find the generating function in the note and how other multivariables can be found. Have a nice day:))
Comment: @goodboy: You're welcome. I've extended the note somewhat which might clarify your question.
Comment: @epi163sqrt  why did you delete your comments about my questions in comments ? Is there anythink wrong in my interpretations about the transformation of $S(z;a,b)$?
Comment: can you please also show  how $S(z;a/(1-a),b/(1-b)) =W(z;a,b)$ using generating functions. I see the idea that by expanding all smirnov words in S with non-empty sequence, we obtain $W$ namely , all words. But @notasalmonfish put and generating function form in its comment in your post answer such that $$W(z)=S(z+z^2+z^3+..)=1+\sum_{n \geq 1}m(m-1)^{n-1}(z+z^2+z^3+..)^n$$. I want to see similar form for MGF where each term are restricted according to desired size. For example, can we see the generating function illustration for $S(z;a/(1-a),b/(1-b) )=W(z;a,b)$
Comment: I intuitively see that $S(z;a/(1-a),b/(1-b))=W(z;a,b)$ but not see it using generating functions. In the example of @notasalmonfish , it is obvious for the extended version where each variable can expand infinitely, but what happen when they are restricted. I hope to see an observation like notasalmonfish
Comment: What is the meaning behind the notation $S(z;....)$?


Inverse of this function with two powers

Question:
I'm trying to find the inverse of the function:
  $$y=\frac{x^f + 1 - (1-x)^\frac{1}{f}}{2}$$
  where
  $f=10c^3+1$ and $x,y$ and $z$ lie in the interval $[0,1]$

I'm using this for mapping of MIDI note velocities and need to be able to convert back to the original value - but my math is failing me.
The function is basically a curved line from (0,0) -> (1,1) where c controls how much it bends away from the straight line.
See here for background
See here for Desmos Calculator showing how the curve behaves.

Sorry for incorrect previous posting, pretty sure the function is now correct.

Someone asked about the rationale... to be honest I can't remember where I got this function.  It's been in my software for 10+ years and works well but now I need the inverse.

Note: this function looks symmetrical about the line $y=1-x$ for the specified x range... but it's definitely not.
Comment: I think when $0<c<1$, the function does not have a unique inverse function, because it's not monotonous.
Comment: I wouldn't expect this function to have an inverse that can be expressed with elementary functions. This is just a hunch, though.
Comment: https://www.desmos.com/calculator/cnhvp4u9jh
Comment: There is no closed-form expression, as the equation can be put in the form of a polynomial for rational $c$.
Comment: This function looks fairly empirical. What's the rationale ?
Comment: Argh... I think I've mis-transcribed this function from the code.  I'll delete this question and post a new one.
Comment: OK, updated post with correct function. Sorry about that.
Answer: You are not going to find a simple expression which, when given a value $y=g(x)$, produces $x$ precisely.
That said, it seems that your function $g(x)$ is fairly smooth and well-behaved.
Accordingly, you should be able to solve $g(x)=y$ quite easily by Newton's method. (It is easy enough to differentiate).
If you think that this will be too slow in practice, you can calculate solutions in advance for the 100 values $y=0.00, 0.01,… 1.00$ and make a table of the corresponding $x$ values in your program. You can then look up those values when you need them, or interpolate between them, or even use the looked-up value as a starting point and do one step of Newton's method to refine the result. You do not, after all, need your result accurate to ten decimal places.
My guess, however, is that given what you have said about your function and its intended use, starting with an estimate $x=y$ and doing a fixed number (say, 6) of "Newton steps" from there will give you all the accuracy you could reasonably need.
Comment: Hi Martin,  Thanks for that.  Unfortunately my math isn't good enough to really understand this.  I've just been through the Wikipedia article for Newtons method and I think I basically understand the concept and I've worked out the derivative of my original function but the code I wrote seems to be improving the approximation towards zero, not the value it should be.  Not sure how to get the target value I want into Newtons method.  If you've got time, could you provide an example of one step of the method - or a basic reference on how to do this?  Thanks again.
Comment: Actually, ignore that ... I figured it out.  Thanks so much for your help.


convert the month number to date

Question: I am working on a task where I need the user to provide exact number of months it will take them to complete a task and then i need to convert that number to an exact date, so lets suppose a user enters 6, this should give me a date 6 months from now.
I tried the following code looking at different examples on line but I have a feeling the following examples treats the $monthNum as the actual month of a year rather than what I need it to do.
$monthNum = 5;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
echo $monthName;

I will really appreciate any assistance here.
Answer: You can try:
$time = new \DateTime('+5 months');

Answer: Demo here
Pop in your month in the modify() method.
$monthNum = 6;

$date = new DateTime();

$date->modify(" +{$monthNum} month");

echo $date->format("Y-m-d");

Outputs
2015-05-14
Answer: You can use strtotime:
$date = date("Y-m-d", strtotime("+5 months"));

Answer: in php 5.4+
echo (new DateTime())->modify('+6 months')->format('d M Y');

convert the month number to date


Replicating/Synchronizng multiple tables across different Databases on the same instance

Question: I have few tables that needed to be replicated/synchronized across several databases in our SQL Server 2008 cluster.
I know it's possible to replicate between multiple instances, but I'm looking for replication or synchronization in the same instance between specific tables of databases.
The replication/synchronization should happen every half-hour or so, but I don't mind it happening constantly.
I can't use DROP the target table and INSERT (copy) the source table since there are many constraints.
Reason for this is to not manage in the application layer and write to 2 different databases at the same time.
Example:
DB1 has T1, T2 and T3 - these are constantly being updated by the application, APP1 running on DB1.
DB2 needs to have an updated copy of T1 at all times, also, there is a different application, APP2 runs only on DB2.
Both DB1 and DB2 are located on the same instance, INST1.
Would it be possible to replicate T1, T2 and T3 from DB1 to DB2 ?
Comment: Why not create a view in DB2 that references the tables in DB1?
Answer: Firstly, SQL Server's replication features can be set up between different databases on the same instance.
Setting up and administering SQL Server replication might be more effort than you want to take on. There are lots of decisions to be made (what kind of replication? All of the columns or just some of them? All of the rows or just some of them? Do I want to index the target tables? Some kinds of replication require changes to the underlying data model. If you don't control the source code of the applications, is changing the data model even possible? etc, etc.), replication can break and it might not be noticed for a while, log files can grow unexpectedly.
With triggers, you have to maintain the trigger code in the case that the underlying tables change. What happens if the trigger stops working? How do you re-sync the tables? How long does that take? Etc, etc.
As mentioned in the comments, one alternative to replication is using views. Potentially, that means maintaining code in the case that the base tables (T1, T2, T3) change for whatever reason. Because of that, views would be my second suggestion.
My first suggestion would be to use the "synonyms" feature to simply refer to the original tables. If you use views or synonyms, the data will only be stored in one place (DB1), so there is no worry about synchronizing changes between copies of the data.
The possible negative here (for views or synonyms) is that DB2 will not actually contain the T1 data, so a backup and restore of DB2 (to a testing or dev server) would also need a backup and restore of DB1.
Comment: Thanks for your responses.
I was able to set Transactional Replication between DB1 and DB2 on the same node, but apparently - the defaults also synchronize the schema and other relations.

My goal is to just synchronize the data.

Also, in the future, DB2 might be offloaded to it's own instance so I guess I'll need to use SQL replication.

Now for a replication question, is it possible to define that only specific schema changes will be replicated and the data itself.

I would only like to that the columns will be updated on DB2 and the Data also. No relations, indexes or other changes.
Answer: If it's on the same instance a quick solution would be to create a synonym in each database to the data tables using three part name (database.schema.table view).  Then you refer to the table/synonym in the each database as a local resource and you have the option to switch to replication later just by keeping the table name the same.
Answer: I have a similar problem and a specific challenge with regard to the use of synonyms.  I have two databases on the same server that serve two seperate applications. DB1 includes information related to insurance agent information.  DB2 includes information related to direct mail and other marketing programs.
The Agent information in the AGENT table in DB1 is needed in DB2 so I can associate the Agent to our direct mail and other marketing programs.  This association needs to be defined using PK/FK relationships.  Problem #1: Using a view or table valued function in DB2 that references the AGENT table in DB1 does not allow me to reference the PK in the view/function as a FK in the associated tables in DB2.  Problem #2: If you define a synonym in DB2 off of the Agent table in DB1 you can't define a FK in the other tables in DB2 referencing the synonym.
If the Agent table in DB1 is the master and DB2 has an Agent table which is a subscriber to DB1, shouldn't I be able to define additional relationships, add a unique index, etc.. to the Agent table in DB2 for the application it's providing data for.
As an example, the application running off DB1 does not need to have the agent's county indexed. The application running off of DB2 does need to have the agent's county indexed.  How can I use replication and allow the subscriber to have unique relationships and indexes in DB2?
Answer: is it only from DB1->DB2 ? or you want changes which occur in DB2->DB1?
Have you thought about a solution that uses triggers?
Also there is nothing wrong with using sql server replication between the same instance from one database to another.


The diophantine equation $a^{a+2b}=b^{b+2a}$

Question: While working on the recent inequality question
$\qquad$Find the $least$ number $N$ such that $N=a^{a+2b} = b^{b+2a}, a \neq b$.
posted by Nirbhay, I decided to fool with the associated diophantine equation, and I did manage to solve it. Here is the problem, offered as a fun challenge:
Prove that the only positive integer pairs $(a,b)$ with $a<b$ which satisfy the equation
$$\large{a^{a+2b}=b^{b+2a}}$$
are $(a,b) = (16,32)$ and $(a,b) = (16,64)$.
Comment: Interesting, it's not difficult to see that $a$ divides $b$. Let $l$ be the quotient, $a$ and $l$ satisfies $a^{l-1}=l^{l+2}$. Then $l$ divides $a$.
Answer: Interesting equation. We can solve it using the following fact:
Lemma: Let $a, b, n$ be positive integers. If $a^n\mid b^n$, then $a\mid b$.
This results follows inmediately from the fundamental theorem of the Arithmetic.
Since $a<b$ we have $b+2a<a+2b$, so $a^{b+2a}\mid a^{a+2b}=b^{b+2a}$, then for the above lemma we deduce that $a\mid b$. Let's write $b=ak$, where $k$ is a positive integer greater than $1$. Replacing $b=ak$ into the equation gives us $$a^{a(2k+1)}=a^{a(k+2)}k^{a(k+2)}$$ $$\implies a^{k-1}=k^{k+2}.$$
Now, since $k^{k-1}\mid k^{k+2}=a^{k-1}$, we obtain, by the lemma again, that $k\mid a$. So let's write $a=kn$, where $n$ is a positive integer. Replacing $a=kn$ gives us $$k^{k-1}n^{k-1}=k^{k+2}$$ $$\implies n^{k-1}=k^3.$$
The last equation can be solved using inequalities which can be proved by induction. Namely, if $n\ge 9$, $n^{k-1}\ge 9^{k-1}>k^3$ for all $k\ge 2$. Therefore $n\le 8$.
If $n=8$, $8^{k-1}>k^3$ for every $k\ge 3$. If $k=2$ we get an equality, and this gives us $a=16$ and $b=32$.
A similar reasoning gives us no solutions for every $n\le 7$, except for $n=4$, where we find $k=4$, and thus $a=16$ and $b=64$. Hence, all the solutions are $(a,b)=(16, 32)$ and $(a, b)=(16, 64)$ as you stated.


MongoDB server crashed, showing the following error

Question: I have a MongoDB instance running in a VMWare VM with Ubuntu Server 12.04. Suddenly the server crashed, and when I try to reinitiate it I get the following error:
jonathanong@ubuntu:~/mongodb/solo$ /usr/bin/mongod --fork --port 27027 --dbpath ~/mongodb/solo --logpath ~/mongodb/solo/mongodb.log
Thu Jan 17 00:54:25   Assertion failure getcwd( buffer , 1000 ) src/mongo/db/cmdline.cpp 188
0xaffd31 0xac65cd 0x6878a8 0x55f070 0x565d39 0x7f2b226d176d 0x558149
 /usr/bin/mongod(_ZN5mongo15printStackTraceERSo+0x21) [0xaffd31]
 /usr/bin/mongod(_ZN5mongo12verifyFailedEPKcS1_j+0xfd) [0xac65cd]
 /usr/bin/mongod(_ZN5mongo7CmdLine5storeEiPPcRN5boost15program_options19options_descriptionES6_RNS4_30positional_options_descriptionERNS4_13variables_mapE+0x4a38) [0x6878a8]
 /usr/bin/mongod() [0x55f070]
 /usr/bin/mongod(main+0x9) [0x565d39]
 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed) [0x7f2b226d176d]
 /usr/bin/mongod(__gxx_personality_v0+0x471) [0x558149]
Thu Jan 17 00:54:25 terminate() called, printing stack (if implemented for platform):
0xaffd31 0x55840e 0x7f2b23036846 0x7f2b23036873 0x7f2b2303696e 0xac6776 0x6878a8 0x55f070 0x565d39 0x7f2b226d176d 0x558149
 /usr/bin/mongod(_ZN5mongo15printStackTraceERSo+0x21) [0xaffd31]
 /usr/bin/mongod(_ZN5mongo11myterminateEv+0x3e) [0x55840e]
 /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0xb5846) [0x7f2b23036846]
 /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0xb5873) [0x7f2b23036873]
 /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0xb596e) [0x7f2b2303696e]
 /usr/bin/mongod(_ZN5mongo12verifyFailedEPKcS1_j+0x2a6) [0xac6776]
 /usr/bin/mongod(_ZN5mongo7CmdLine5storeEiPPcRN5boost15program_options19options_descriptionES6_RNS4_30positional_options_descriptionERNS4_13variables_mapE+0x4a38) [0x6878a8]
 /usr/bin/mongod() [0x55f070]
 /usr/bin/mongod(main+0x9) [0x565d39]
 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed) [0x7f2b226d176d]
 /usr/bin/mongod(__gxx_personality_v0+0x471) [0x558149]
Thu Jan 17 00:54:25 Got signal: 6 (Aborted).

Thu Jan 17 00:54:25 Backtrace:
0xaffd31 0x558bb9 0x7f2b226e64a0 0x7f2b226e6425 0x7f2b226e9b8b 0x558413 0x7f2b23036846 0x7f2b23036873 0x7f2b2303696e 0xac6776 0x6878a8 0x55f070 0x565d39 0x7f2b226d176d 0x558149
 /usr/bin/mongod(_ZN5mongo15printStackTraceERSo+0x21) [0xaffd31]
 /usr/bin/mongod(_ZN5mongo10abruptQuitEi+0x399) [0x558bb9]
 /lib/x86_64-linux-gnu/libc.so.6(+0x364a0) [0x7f2b226e64a0]
 /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x35) [0x7f2b226e6425]
 /lib/x86_64-linux-gnu/libc.so.6(abort+0x17b) [0x7f2b226e9b8b]
 /usr/bin/mongod(_ZN5mongo11myterminateEv+0x43) [0x558413]
 /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0xb5846) [0x7f2b23036846]
 /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0xb5873) [0x7f2b23036873]
 /usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0xb596e) [0x7f2b2303696e]
 /usr/bin/mongod(_ZN5mongo12verifyFailedEPKcS1_j+0x2a6) [0xac6776]
 /usr/bin/mongod(_ZN5mongo7CmdLine5storeEiPPcRN5boost15program_options19options_descriptionES6_RNS4_30positional_options_descriptionERNS4_13variables_mapE+0x4a38) [0x6878a8]
 /usr/bin/mongod() [0x55f070]
 /usr/bin/mongod(main+0x9) [0x565d39]
 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed) [0x7f2b226d176d]
 /usr/bin/mongod(__gxx_personality_v0+0x471) [0x558149]

This is MongoDB 2.2.2 downloaded from mongodb-10gen: http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/
Any ideas?
Edit: So I just created a new VM from scratch and it's perfectly fine. So this isn't a show stopper for me since I plan to use managed hosting. Still, knowing the problem would be nice!
Answer: Looks like you're OK, but FYI: this just happened to me. Pretty much the same stack trace. The problem was that as I was restarting mongod, my current directory in this shell happened to be one which I had deleted a little while ago (in another shell). That was why getcwd was failing.
Comment: Same thing for me. :)
Answer: The first thing to look at is the provided line of code at the top of the crash:
https://github.com/mongodb/mongo/blob/v2.2/src/mongo/db/cmdline.cpp#L188
This is basically getting the current working directory.  An odd place to crash - it would suggest a fairly basic problem at the filesystem level - directory not found, or in some other way corrupt.
According to addr2line (see Parsing Stack Traces) the first relevant line (0x6878a8) points here:
https://github.com/mongodb/mongo/blob/v2.2/src/mongo/db/cmdline.cpp#L349
That again points to some sort of issue getting to the relevant mongod folder (probably /var/lib/mongodb or similar).  This time the relevant error is:

Cant chdir() while forking server process

Again pointing to a similar root cause in terms of accessing the filesystem/folder that the program is trying to use.
Answer: In my experience, I got such error: "SEVERE: terminate() called, printing stack" because of the locate problem. type:

export LC_CTYPE="en_US.UTF-8"

would probably fix the problem.
Comment: You may be getting **another** problem. No offense, but have you tried going to the source file mentioned in the stacktrace?


Is it possible to have sharp/flat notes in a music piece composed in the key of "A minor"?

Question: When I was reading sheet music of Niccolò Paganini's Caprice No. 24 in A minor, I saw some sharp and flat notes.

This raised some questions for me. Based on my researches, I also found out that the caprice is not written in A Harmonic minor scale or A Melodic minor scale.
Can a music piece written in A minor contain sharp/flat notes??
Is it possible that the caprice is out of scale in some parts??? While it is totally in A minor.
I also read this post, but was not clear enough.
I am new to music theroy and apologize if I used wrong technical terms.
Any thoughts would be really helpful.
Comment: The existence of this piece seems to be proof that the answer to this question is "yes."
Comment: It's not merely possible, it's very common! Raising the seventh degree in a minor key is extremely common (making G a G#, in the case of A minor).
Comment: Something like [the first 5 notes of Für Elise](https://musescore.com/classicman/scores/33816)?
Comment: The backside of the medal is [this question](https://music.stackexchange.com/q/11054/2600): Why have accidentals, even if they are not used?
Answer: Music can, and often will, have notes in it that exist outside of the scale of the current key. We call these outside pitches chromatic, and it's these chromatic pitches in the Paganini that led to your question. (In contrast, we would call music that only uses the members of the A-minor scale diatonic, which basically means "in the key.")
But in this example (and in countless others), these chromatic pitches do not up-end the sense of A as tonic or of A minor as the key. Instead, they're just flavoring notes.
Think of it as you do language. Imagine I say, in English:

The composer's oeuvre includes symphonies, operas, chamber music, and songs.

That statement is still in English; the existence of a single foreign word doesn't mean the sentence is no longer in English, nor does it really mean that it's simultaneously in two languages at once. It's the same with this music: there are occasional "foreign" tones, but it's still clearly in A minor.
I'll also say that music is not really written "in scales." Rather, scales are a convenient way for understanding collections and for helping instrumentalists build technique. So try to think less of a piece of music being "in a scale," and focus more on the tonic pitch of that key.
Comment: I actually interpret the B flat in Bar 5 as part of a temporary tonicization of D minor (rather like Bars 7-8 sequence and tonicize C major). I also find it easiest to interpret all D sharps in the theme as secondary dominants.
Comment: @Dekkadeci: You are correct about the B flat and bars 7 to 8; see my answer for details! I am not sure what you mean about the D sharp, but I have given my own explanation of that in my answer.
Comment: @Dekkadeci True, but to me these still never "up-end the sense of A as tonic or of A minor as the key." These are temporary moves in a clear A-minor environment.
Answer: "A minor" is a key. A piece being in a particular key means that the harmony will tend to resolve towards that note/chord, and mostly use notes from the associated scale. But almost all music involves borrowing notes from outside that scale.
"A natural minor", "A harmonic minor", and "A melodic minor" are scales. In particular, the harmonic and melodic minor scales (as common played in technical drills) are sort of artificial constructions. They exist to illustrate why certain alterations are common in minor keys. You don't "write a piece in" harmonic or melodic minor.
Comment: @Dekkadeci, respectfully, I would say Musescore user-submitted scores are far from a reliable source of music theory information.
Comment: Interestingly, I have seen multiple works on Musescore claiming to have been written in a harmonic or melodic minor key.
Comment: The melodic minor is a form, you employ it to avoid the augmented second that happens between the 6th and 7th scale degrees of the harmonic minor scale. It is purely a device that promotes better melody writing.
Answer: You've fallen, as we all have, into the trap that says 'this is in key X, so every note in it must be from the scale of X'.
Not so, by a long whatever-it-is!
The basic notes of any piece will consist of those from scale X, called the diatonic notes, and that leaves just five other notes which are non-diatonic. Otherwise called chromatic. That means coloured. They often get used to literally colour the melody, and stop it getting too predictable. When we hear those chromatic notes, our ears hear them and we think 'mm, they don't really belong, but nevertheless...'
Answer: Harmonic and melodic scales are artificial 'melodies', but many pieces do borrow these in a melody that comprises short scales. There is in fact really a small tendency for rising melodies to use raised 6th and 7th notes and for falling melodies to use the original unraised 6th and 7th. However, this is of course not a rule, nor is it theoretically the most euphonic. So it is no surprise at all to see the raised 6th and 7th in the falling scale in bar 2. In fact, a 7-6-5-1 melody is very common, just like a 5-6-7-1, and in the minor scale the 7th is almost always raised in such a melody. The 6th is usually raised as well, though if you do not it sounds fine too; it will sound different (strongly minor) but not unpleasant.
But there is a bigger misconception that I want to address. When a composer says that a piece is in A minor, it does not mean that the entire piece is in A minor, even in the composer's mind! And indeed it is not the case even in this short section that you have posted here. Change of key is also known as a modulation. Let us analyze this properly:
Bars 1 to 4 are indeed in A minor. Chords are I, V, I, V.
Bars 5 to 6 are in D minor. Chords are V, I. Note that the chord in bar 5 is A major as a chromatic change from A minor in bar 4. The B flat perfectly fits here as the 6th note in D minor. This is a very common modulation (to what is called the subdominant key).
Bars 7 to 8 are in C major! Chords are V, I. C major is the relative major for A minor, so it is a common target for modulation. How did the key get from D minor to C major? Well, one might argue that D minor is the pivot chord, being in the keys D minor and A minor and C major, so it facilitates the human mind from perceiving that the subdominant modulation was just a temporary one and that it is now jumping from the original key to the relative major.
Bars 9 to 12 are back in A minor, in my (subjective) opinion, and the chords are #VIIdim7, I, VIaug6, V, I. Here #VIIdim7 is a typical diminished 7th chord, and I feel that the melodic progression calls for the G# in the chord even though it is not in the melody, hence the "#VII" indicating the raised 7th from the minor scale. The (VIaug6, V) progression are in a single bar, as a quick move towards the final goal of I. Note that (VI, V, I) is a common progression, though here there is an additional note that fits into the melody because it is just a chromatic step away from and resolves to the next note E. Note that the general flavour will be unchanged if you omit the D#. (I have changed the chord identifications here based on Aaron's helpful feedback that my notation was not conventional.)
Bars 13 to 16 are again in A minor. Chords are uneventfully I, V, I, V.
After that, we have a repeat of the chord progressions, with bars 17 to 18 in D minor, bars 19 to 20 in C major, and bars 21 to 22 in A minor as we described above. And these bars also confirm the earlier analysis.
Finally bars 23 to 24 end the section in A minor, with chords II, V, I. This chord progression is also a common progression.
Most classical and romantic music are built around the chords I, V, IV, II, VI, III, in roughly that order of prominence, with the notes taken directly from the scale. (Note that some theorists use uppercase and lowercase to denote whether it is a major or minor chord, but I do not want to do that as I feel that the musical flavour arises from the scale and not just the chord itself. For instance, in the minor key what I write as chord II would be notated as ii(dim) in another convention, but the underlying flavour is still the same as the (II, V, I) in the major key, just that it sounds minor.)
As you can see above, we have indeed fully explained all the chords and accidentals used in this section of Paganini's piece; Not a single accidental was left unjustified!
Comment: @Aaron: Music practice and theory are inherently subjective, so I of course can't disprove your disagreement. However, let me try to explain why I think mine is correct. =) As a pianist and composer, when I imagine this piece in my mind, the F# and G# in bar 2 really invoke the feeling of chord V in A minor, not tonicize E major. The G# need not resolve to A because 7-6-5-1 is a very common melody in any key, no less than 5-6-7-1. About bar 5, I did not look ahead when hearing in my head and analyzing! [cont]
Comment: [cont] You can say that the first half is not A major simply because the Bb hasn't come yet, but once it came my mind immediately knew the A minor had chromatically shifted to A major in preparation for modulation to D minor. In particular we have an implicit chromatic C-C#-D. Your observation that it is a sequence of descending 5ths is in my musical opinion a consequence rather than an impetus for the melodic and chord progression. The evidence is that Bb cannot be explained if you are simply using descending 5ths. [cont]
Comment: [cont] I don't understand your objection to my labelling of F-D# as VIdim7. Chord VI is F-A-C-E, and diminishing the 7th removes the dissonance (which occurs here as it is in the minor key). That said, of all the chords this is the most ambiguous, so I'll just leave this labelling as a product of my musical intuition that perhaps other musicians may not share. Finally, I don't agree with your labelling of the first chord in bar 23; it just does not fit. All the notes there are simply the chord II, and if you wish you could use II7 or IIdim7 to accompany that melody.
Comment: Nice analysis. A few points of disagreement: 1) m2,4 tonicize E major, not participate in an A minor scale. If they did, the G#, being the leading tone, would pull toward A. 2) Although we know from looking ahead in the piece that m. 5 will eventually be A major, I don't think you can establish that yet. At best it's ambiguous, but more likely A minor because of what came before. 3) Bars 5 - 8 are better explained as a sequence of root movement by descending 5th: A-D-G-C. 4) The beginning of m. 11 is an Aug6 chord. A dim7 would contain Ebb. (cont.)
Comment: ... 5) Since I disagree about 1-4, it's worth saying that here I agree with you. 6) Bar 23 is not quite the same as the parallel earlier bar. This is the first occurrence of VIIo7.
Comment: Very cool to know your thinking. IMO, it really adds to the answer. There seems to be a terminology issue regarding the VI chord. Chord VI is indeed F-A-C-E, a.k.a Fmaj7. Flatting the E creates a minor seventh between F and Eb, creating an F7 chord. An VIdim7 (i.e., Fdim7) would be spelled F-Ab-Cb-Ebb. However, F to D# is the interval of an augmented sixth. The difference between F7 (with an Eb) and Faug6 (with D#) is that the Eb would resolve downward to D rather than upward to E. (cont.)
Comment: ... As far as bar 23, a iio7 chord is enharmonically equivalent to a viio7 chord, but the spelling is different. iio7 in A minor is spelled B-D-F-Ab; viio7 is spelled G#-B-D-F. The root of a diminished chord functions as a leading-tone; thus, G#dim7 leads to A minor, while Bdim7 would lead to the relative major.
Comment: @Aaron: Thank you for your kind remarks! Yes there is a terminology issue; I agree that the chord would be spelt as Fmaj7 explicitly, but I chose to go with the musical intuition behind the chord. For instance chord I would be major in a major key but minor in a minor key, following the scale. Chord VI also follows the scale of the key, and musicians extend the chord to create a slight dissonance by adding a seventh note, rather than by building from scratch from the base note. [cont]
Comment: [cont] Unfortunately, I have to completely disagree with you about the direction of resolution. Let's talk about the concrete chords in absence of a key. Fmaj7-Emaj has the bottom 3 notes resolving downward while the top note resolving upward. It is never the case that all notes resolve in the same direction; at least one must stay put or resolve in the opposite direction.
Comment: Concerning bar 23, I did not mean that Bdim7 leads to A minor. That's why I labelled the chord progression as II, V, I; here II leads to V. B-D-F → B-E-G# → A-E-A.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/112194/discussion-between-user21820-and-aaron). =)


Exception Title: Check if object is Null

Question: I created table N_Roles_Users in my database, I want to show it's value if username matches with existing login user.
I wrote this code below. But it is generating exception that check if object is Null.
// currentUser="UserA";
public List<string> GetUserRoles( string currentUser)
{
        N_Roles_Users allroles = new N_Roles_Users(); //N_Roles_Users is database table name.
        List<string> roleslist = new List<string>();
        List<char> temp = new List<char>();
        temp = allroles.user_name.ToList();
        List<char> tempa = new List<char>();
        tempa = allroles.role_name.ToList();

        for (int i = 0; i < temp.Count; i++) // Loop through List with for
        {
            if (currentUser == temp[i].ToString())
            {
                roleslist.Add(tempa[i].ToString());
                MessageBox.Show(tempa[i].ToString());
            }
        }

        return roleslist;
}

Can anyone guide me how to resolve this problem?
Comment: on which line you are getting the error
Comment: what is user_name ? it's any method or property ?
Comment: On which line is the exception generated? Please provide us with the stacktrace and exact exception type `System.InvalidOperationException` or maybe a `System.NullReferenceException` or what kind of exception?
Comment: on all lists. i removed list one by one to check that which list is creating this issue, but on each list this Exception generates. I executed queries to check it out that are values present in table or not. Values were present. I don't know what's wrong with it.
Comment: You make a new instance of `N_Roles_Users`, what is in the constructor? do you initialize everything?
Comment: @RameshRajendran It is Column Name in N_Roles_Users
Comment: @ZoyaSheikh . I think that column name return null (empty) values , so you get this error. please look my answer , check that condition or check that column has any values there ? ..
Comment: possible duplicate of [What is a NullReferenceException in .NET and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net-and-how-do-i-fix-it)
Comment: @RameshRajendran yes you are right, Now how to solve this?
Comment: See my answer . Check that condition : http://stackoverflow.com/a/18353979/2218635
Answer: temp = allroles.user_name.ToList(); is the line of exception i guess.

set allroles.user_name = "some value" before
this line
temp = allroles.user_name.ToList();

Happy Coding :)
Comment: Hello Zoya. What do you mean by shows nothing. Nothing is printed on console or what ?
Comment: yes, i wrote textbox1.Text=temp[1].ToString(); ... But nothing printed
Answer: Check this condition
// currentUser="UserA";
public List<string> GetUserRoles( string currentUser)
        {
        N_Roles_Users allroles = new N_Roles_Users();
        List<string> roleslist = new List<string>();
        List<char> temp = new List<char>();
         **if(allroles.user_name.ToList()!=null &&  allroles.user_name.ToList().Count!=0)
          {
         temp = allroles.user_name.ToList();
         }**
        List<char> tempa = new List<char>();
        tempa = allroles.role_name.ToList();

        for (int i = 0; i < temp.Count; i++) // Loop through List with for
            {
            if (currentUser == temp[i].ToString())
                {
                roleslist.Add(tempa[i].ToString());
                MessageBox.Show(tempa[i].ToString());
                }
            }
        return roleslist;
        }

Comment: if `user_name` is null you will still get an NRE here


Is it surjective because of $K \subset H$?

Question: Let $G$ be a group and $H,K$ normal subgroups of $G$ s.t. $K \subset H$. If I define the following map: $\phi:G /K \to G/H, gK \mapsto gH$ then the claim is that it is surjective. Is it because we have that $K \subset H$ and hence $G /H \subset G/K$?
Comment: This map is well-defined since $K \subset H$ and surjective by definition. In fact, we do not even require $K$ and $H$ to be normal subgroups, any subgroups $K \subset H$ would work and the corresponding map $\phi$ would still be surjective (although no longer a homomorphism between groups).
Comment: No it is not true that $G/H \subset G/K$.
Answer: The fact that the application is surjective is trivial, since taken $gH\in G/H$, then  $\phi(gK)=gH$. The tricky part is proving that this is actually a well posed application. And this can be done as follows:
$$aK=bK\Rightarrow ab^{-1}\in K\subset H \Rightarrow   ab^{-1}\in H \Rightarrow aH=bH \Rightarrow \phi(aK)=\phi(bK)$$
Now you have just to prove that is an homomorphism (trivial), find its kernel and then apply first isomorphism theorem.
Answer: More precisely, this is because of the $3^{ rd }$ isomorphism theorem: $H/K$ is a normal subgroup of $G/K$, and
$$(G/K)\big/(H/K)\simeq G/H.$$
What can be said of $G/H$ as compared to $G/K$ is that every $H$-coset is a union of $K$-cosets.
Comment: I just use this fact to proof this theorem, so I can't use it already..
Comment: Oh! I see. Note that at the end of your question, you do not have $G/H\subset G/K$,  but $G/H$ is a *quotient* of $G/K$.
Answer: Since we aim to get a map between coset sets, but we can't avoid using coset representatives, we need to ensure that $g'\in gK\Rightarrow \phi(g'K)=\phi(gK)$ (good definition). But this is indeed the case, because by $K<H$ (see $(*)$ step):
\begin{alignat}{1}
g'\in gK &\Rightarrow g^{-1}g'\in K \\
&\stackrel{(*)}{\Rightarrow} g^{-1}g'\in H \\
&\Rightarrow g'\in gH \\
&\Rightarrow g'H=gH \\
&\Rightarrow \phi(g'K)=\phi(gK) \\
\end{alignat}
About surjectivity, notice that, by $K<H$, it is $\#G/K=[G:K]=[G:H][H:K]>[G:H]=\#G/H$ and use the pigeonhole principle.
Finally, as long as you interpret $G/H$ and $G/K$ as quotient sets (not necessarily groups), the normality of $H$ and/or $K$ is not necessary for the map to be (well defined and) surjective.


Azure Virtual Machine log in denied - redeploy doesn't solve

Question: I can't log in into my WS2019 Azure Virtual Machine (via remote desktop). Every time I attempt to do so, I get this error:
Screenshot
The Local Session Manager service failed the sign-in.
The request is not supported.
Redeploying the machine doesn't help. I can't reset configuration because of:
VM has reported a failure when processing extension 'enablevmaccess'. Error message: "VMAccess Extension does not support Domain Controller.".
I can't seem to find any appropiate solution for it since I can't log in into my account nor into cmd (same password prints out a "Unable to authenticate" error.)
Answer: As per this page you should reset the domain password via special script:

Create a script in a notepad as script.ps1
         net user <Username> <Password>

Select the VM you want to change domain password
Go to extensions in the VM left panel
Click on +ADD at the top
Select custom Script Extension option

After selecting the Custom Script extension option.
Click on the Create option in the bottom of the page
Browse the script file saved on your desktop.
Then Click OK

Then the script gets uploaded and you will get a notification in
  notification bar.
You could also do this by using PowerShell (you need to host the
  script somewhere on webserver):

Set-AzureRmVMCustomScriptExtension -ResourceGroupName myRG -VMName myVM -Location vmLocation -FileUri "http://url/script.ps1" -Run 'script.ps1' -Name resetpassword

Answer: Sounds that you have a VM which is a domain controller so you don't have any local admin and it also sounds that your VM couldn't activate the windows license and the grace period has past. Correct?
In that case try to open your NSG and make sure the vNet have DNS servers that can resolve public domains. Then try rebooting the server and hope it can activate it against Microsoft's KMS.


Need a hand altering a theme

Question: I'm using a theme called Danland, and I want to change the Recent Posts block to show only post title and publication date. As it stands it shows 3 columns, one of which is post title, and the last two of which are blank when you are not logged in and say "edit" and "delete" when you are logged in. I also want to kill the table border.
I can't find the right css file to edit. Using firebug to ID the td and other tags to kill to get rid of the extra columns, but I can't find them in the theme files. Firebug IDs them as being in style.css, but there's nothing there. Where does this code live?
Comment: Link to site: www.naphikes.com
Comment: Hello. Could you please edit your question's title? I was tempted to vote to close as too broad, but it seems you have a legitimate question, just formatted it unfortunately.
Answer: Please go to views admin interface and check the views name as Recent post(display type block), views gives  you flexibility for adding any number of fields your content type has, also it will allow you to have custom classes to fields that you will be needing to theme.About classes and ids already there, they are coming from views theming you do not have to touch there all you have to do is add fields you want, while adding it will allow you to style it by adding wrapper divs or other html element.Once you finish with editing the view,check the block in firebug you will see your calsses and ids working there, then add css for it in your Danland theme .css file.
Key Points which may help you:

how to add/remove fields from view
how to add custom classes to the fields in views
Once done style it using your theme css file.

Need a hand altering a theme


Obter parâmetro da url via angularJS

Question: Bem, preciso obter um parâmetro da minha url assim que minha página é carregada.
localhost/123456
O parâmetro seria: 123456
Utilizando o $location, obtive a url completa, mas não conseguir obter o parâmetro que preciso para ser carregado no meu controller
 myApp.controller('Controller', function ($scope, traineeControlService, $location) {

var vm = this;
//getAll();

$scope.numberOfregistrationUser = {};

var searchObj = $location.url();

  console.log(searchObj);
}

Answer: Uma forma seria usar o ngRoute. Através do $routeProvider pode configurar as rotas do seu site, e com isso extrair os parâmetros das URLs e injectá-los directamente no seu controlador.
Ou seja:
var myApp = angular.module('app', ['ngRoute']); // adicione o ngRoute como modulo do seu modulo

myApp.config(function($routeProvider) {

    // indica que quando tiver uma URL do tipo http://localhost/[id], que deve utilizar este template e controlador
    $routeProvider.when('/:id', {

        templateUrl: '[caminho para a sua pagina HTML]',
        controller: 'Controller' // nome do seu controlador
    });
})

myApp.controller('Controller', function ($scope, traineeControlService, $routeParams) {

    var vm = this;
    //getAll();
    $scope.numberOfregistrationUser = {};
    // var searchObj = $location.url();

    console.log($routeParams.id);
}

O objecto $routeParams contém todos os parâmetros definidos na URL (note quando a URL e configurada, o uso do : para indicar que e um parâmetro que deve ser lido).

Obter parâmetro da url via angularJS


Graph/Network Clustering Models that Use Covariate Information

Question: I have been reading about Clustering Models on Graph/Network data.
For example, there seems to be a popular Clustering Model for Graph/Network data called Louvain Clustering (https://en.wikipedia.org/wiki/Louvain_method). This model attempts to find "highly correlated subgraphs within the network" - this is also called "Community Detection" (it seems like the terms "clusters", "communities" are interchangeable here).
I was looking at the steps involved in Louvain Clustering:

As seen in the above description, clusters are identified through the Louvain Method by only using "edge" information.
For example, suppose that we have network data on a group of friends - we can break this data into two general parts:
Node Data: In this example, each person can be considered as a "Node". Thus, "Node Data" can be considered as Age, Salary, Height, Weight, etc. In a certain sense, this "Node Information" is analogous to "Covariate Information" in regression problems (e.g. the height of an individual person (node) in graph network vs. the height of an individual person in a regression dataset).
Edge Data: In this example, the relationships between friends can be considered as "Edges". For instance, if John and Jack are friends - their friendship can be considered as an "Edge".
It seems that most Graph Clustering Models (e.g. Louvain, Leiden, Walktrap, Infomap) only use "Edge Information" and do not make use of "Node Information" at all.
We can see an example of this in R:
<code>#load libraries and data
library(igraph)
library(igraphdata)

data("karate")
#plot(karate)

#run clustering algorithm

set.seed(123)
gD = karate
lou <- cluster_louvain(gD)
LO = layout_with_fr(gD)
plot(lou, gD, vertex.label = NA, vertex.size=5,
    edge.arrow.size = .2, layout=LO)
</code>

In the above code, we see how clustering was performed in the complete absence of "Node Information" - clustering was performed only using "Edge Information".
This is in stark contrast to standard clustering methods such as "K-Means Clustering". For example, if we were to use K-Means Clustering on a data set such as the Iris Flowers Dataset, K-Means would make use of the covariate information such as the different lengths and widths of the flowers.
The reason I am bringing this up : In the case of Graph/Network Clustering, it seems likely that there could be valuable information within the "Node Data" (also called "Node Attributes") - but most Graph/Network Clustering Models seem unable to exploit this information.
My Question: Are there any Graph/Network Clustering Models that are able to make use of both "Node Information" and "Edge Information" at the same time?
Thanks!
Answer: There are many methods proposed to detect communities in attributed networks. The three main approaches are: 1) combining structure- and attribute-based information in a single representation (e.g. by adding to the graph some vertices representing attributes), then detecting communities based on this representation; 2) detecting communities by considering simultaneously structure and attributes (e.g. by jointly optimizing two criteria); and 3) detecting communities separately using structure and attributes, then combining the resulting partitions (akin to consensus-based clustering methods).
To get a more precise overview of the existing methods, you should look for recent surveys such as (Chunaev'20). I did not find any implementation of these methods integrated in any of the major network libraries such as igraph or networkx. However, some authors have published their source code online, so you can look for a suitable method in the above review and check whether its source code is available in the original publication. For instance, I-Louvain, an attribute-based variant of Louvain described in (Combe'15), is available online: https://www.dropbox.com/sh/j4aqitujiaifgq4/AAAAH0L3uIPYNWKoLpcAh0TPa.
Comment: Thank you so much! I will look into this!
Comment: +1 I have gotten a lot of value out of networkx. Note that if you cluster the nodes, you can represent the clusters nicely by drawing them as hyperedges using [hypernetx](https://pnnl.github.io/HyperNetX/build/index.html).


word frequency scatterplot in R (words as labels)

Question: I'm currently working on a paper comparing British MPs' roles in Parliament and their roles on twitter. I have collected twitter data (most importantly, the raw text) and speeches in Parliament from one MP and wish to do a scatterplot showing which words are common in both twitter and Parliament (top right hand corner) and which ones are not (bottom left hand corner). So, x-axis is word frequency in parliament, y-axis is word frequency on twitter.
So far, I have done all the work on this paper with R. I have ZERO experience with R, up until now I've only worked with STATA.
I tried adapting this code (http://is-r.tumblr.com/post/37975717466/text-analysis-made-too-easy-with-the-tm-package), but I just can't work it out. The main problem is that the person who wrote this code uses one text document and regular expressions to demarcate which text belongs on which axis. I however have two separate documents (I have saved them as .txt, corpi, or term-document-matrices) which should correspond to the separate axis.
I'm sorry that a novice such as myself is bothering you with this, and I will devote more time this year to learning the basics of R so that I could solve this problem by myself. However, this paper is due next Monday and I simply can't do so much backtracking right now to solve the problem.
I would be really grateful if you could help me,
thanks very much,
Nik
EDIT: I'll put in the code that I've made, even though it's not quite in the right direction, but that way I can offer a proper example of what I'm dealing with.
I have tried implementing is.R()s approach by using the text in question in a csv file, with a dummy variable to classify whether it is twitter text or speech text. i follow the approach, and at the end i even get a scatterplot, however, it plots the number ( i think it is the number at which the word is located in the dataset??) rather than the word. i think the problem might be that R is handling every line in the csv file as a seperate text document.
# in excel i built a csv dataset that contains all the text, each instance (single tweet / speech) in one line, with an added dummy variable that clarifies whether the text is a tweet or a speech ("istweet", 1=twitter).

comparison_watson.df <- read.csv(file="data/watson_combo.csv", stringsAsFactors = FALSE)

# now to make a text corpus out of the data frame

comparison_watson_corpus <- Corpus(DataframeSource(comparison_watson.df))
inspect(comparison_watson_corpus)

# now to make a term-document-matrix

comparison_watson_tdm <-TermDocumentMatrix(comparison_watson_corpus)
inspect(comparison_watson_tdm)

comparison_watson_tdm <- inspect(comparison_watson_tdm)
sort(colSums(comparison_watson_tdm))
table(colSums(comparison_watson_tdm))

termCountFrame_watson <- data.frame(Term = rownames(comparison_watson_tdm))
termCountFrame_watson$twitter <- colSums(comparison_watson_tdm[comparison_watson.df$istwitter == 1, ])
termCountFrame_watson$speech <- colSums(comparison_watson_tdm[comparison_watson.df$istwitter == 0, ])

head(termCountFrame_watson)

zp1 <- ggplot(termCountFrame_watson)
zp1 <- zp1 + geom_text(aes(x = twitter, y = speech, label = Term))
print(zp1)

Comment: So is the question how to generate the frequency data, or how to plot it?
Comment: the question would be how to plot it.
Comment: Whats wrong with plot(x,y). What exactly is your question?
Comment: instead of displaying the words (as in this example http://is-r.tumblr.com/post/37975717466/text-analysis-made-too-easy-with-the-tm-package), it displays numbers...
Comment: I voted to close as the OP never responded and the question lacks a MWE.
Answer: library(tm)
txts <- c(twitter="bla bla bla blah blah blub",
          speech="bla bla bla bla bla bla blub blub")
corp <- Corpus(VectorSource(txts))
term.matrix <- TermDocumentMatrix(corp)
term.matrix <- as.matrix(term.matrix)
colnames(term.matrix) <- names(txts)
term.matrix <- as.data.frame(term.matrix)

library(ggplot2)
ggplot(term.matrix,
       aes_string(x=names(txts)[1],
                  y=names(txts)[2],
                  label="rownames(term.matrix)")) +
  geom_text()

You might also want to try out these two buddies:
library(wordcloud)
comparison.cloud(term.matrix)
commonality.cloud(term.matrix)

Answer: You are not posting a reproducible example so I cannot give you code but only pinpoint you to resources. Text scraping and processing is a bit difficult with R, but there are many guides. Check this and this . In the last steps you can get word counts.
In the example from One R Tip A Day you get the word list at d$word and the word frequency at d$freq
Comment: hi, thanks for your help. ive actually already used the examples you gave me to do a worcloud. i can't deduce how to do a scatterplot form that though... ive added some code that ive done, so maybe what i wanna do becomes clearer. sorry to bother you all with my unclear request.


About validates_uniqueness_of in Rails

Question: i have a question, suppose that i have a model called Client, this model have a validation validates_uniqueness_of for attribute name, the problem is that the application is used by multiples users(use Client table), so lets say that a User 1 create a Client called Paul when other user try create a user with same same the validation will work, should however not.
I know if I did understand,
Thanks
Answer: You can use :scope option:

:scope - One or more columns by which to limit the scope of the
  uniqueness constraint.

class Client < ActiveRecord::Base
  validates_uniqueness_of :name, :scope => :user_id
end

Comment: if you want to scope it to more than one, use an array `:scope => [ :some_field, :some_other_field ]`

About validates_uniqueness_of in Rails


Passing parameters to view blocks in Twig

Question: Running Drupal 8.9.18
I have a string that I want to pass to a Drupal block for use in a contextual filter. In a twig template I have a view that creates a simple list of the terms to use. I extract the string from the result array, map the required string to a variable that I pass as a parameter to another view block:
{% set view-output = drupal_block('views_block:view1-block_1') %}

{% for item in view-output.content['#view'].result %}

  {% set qParam = item.taxonomy_term_field_data_name | render | striptags %}
  {% if drupal_block('views_block:view2-block_1', qParam )is not empty %}
    {{ drupal_block('views_block:view-name-block_1', qParam) }}
  {% endif %}

{% endfor %}

The expression item.taxonomy_term_field_data_name | render | striptags gives me the values I expect from the view output.
I get the following error:

The website encountered an unexpected error. Please try again later.
TypeError: Argument 2 passed to
Drupal\twig_tweak\TwigExtension::drupalBlock() must be of the type
array, string given,

Question:  how can I pass qParam as an array (it's a single value). I've tried using
{% set qParam = qParam|merge(..) %} inside the for loop but the (..) bit is a mystery to me.
Or is there a better way of nesting queries that I don't know?
Note that I am not conversant with coding in PHP and want to stick with using Twig alone.
Thanks in anticipation for any help
Answer: following the error-message you probably just use an array with a single value as second argument, e.g
{{ drupal_block('xx', {qParam: qParam} ) }}

Answer: thanks for your help. I'll try that. I've actually found a workaround using a contextual filter to identify a specific path component rather than using a query parameter. This does what I want but I'd be interested to solve the original problem


How to pass the varible value from one layer to other layer in flash actionscript?

Question:
Hello below is the image of my project , you can see dice layer with 25th frame and at 25th frame its having a variable value and I need to pass it to JS layers 1st frame which is another layer down the roll layer please do the needful.
Comment: Layers don't matter at all with variables,  frames do however.  If you create a variable in the first frame, you can read/write to in all subsequent frames (regardless of the layer).
Answer: You can do :
dice / frame 25 :
<code>// here the String type is just for example of course, set the type of your var
// the shared_var var is global, so you can use it in any frame of any layer
var shared_var:String = 'data'
</code>
JS / frame 1 :
<code>// we have to verify if shared_var is defined and not null
// because in the first iteration of your animation, shared_var does not exist yet because it's defined in the frame 25
if(shared_var){

    // here trace is just for example, you do what you want with your var
    trace(shared_var)  // gives : data

}
</code>
Comment: here I am trying to move pawn according to dice roll frames 25,the randomly generated number is in one layer called dice layer and the  pawn movement is in another layer i.e,. named layer JS frame 1, but after every dice roll the pawn is going back to zero means that its resetting...
Comment: @Kogile You want reset it in JS/frame 1?