Pandoc: [WARNING] Could not convert TeX math

Question: I tried to convert html to docx by using Pandoc:
here is my html code:

 Example: ${v_1} = {\rm{ }}{v_2}$

with MathJax config in head:

    MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
        inlineMath: [['$', '$'], ["\(", "\)"]],
        displayMath: [['$$', '$$'], ["\[", "\]"]],
    },
    "HTML-CSS": {availableFonts: ["TeX"]}
});

Pandoc command that i used (Pandoc version 18.104.22.168):

    pandoc -s  test.html --mathjax  -f html+tex_math_dollars   --pdf-engine=xelatex  -o  xxx.docx

then i got a warning:

    [WARNING] Could not convert TeX math '{v_1} = {\rm{ }}{v_2}', rendering as TeX:
      {v_1} = {\rm{ }}{v_2}
                  ^
      unexpected "{"
      expecting "%", "\\label", "\\nonumber" or whitespace

Someone please tell me how to fix this. Thanks!
Answer: Use the LaTeX \textrm instead of the plain tex \rm, and pandoc will be able to handle it.
Answer: Since 7k users have viewed this question since it was asked... perhaps others have made the same mistake I made as a novice RStudio user.
The first comment in both the README.md and the README.Rmd file is

The intended meaning is (at least arguably) apparent if you pay sufficient attention to the this/that relative pronouns!

To repair the damage... I'm currently trying the suggestion to use an explicit devtools::build_readme() which I found  in RStudio README.Rmd and README.md should be both staged use 'git commit --no-verify' to override this check
No luck yet ... but I feel like I'm (finally!) making forward progress on getting $\sqrt{x}$ to display properly in my github README!


Cardinal Arithmetic versus Ordinal Arithmetic

Question: I am reading Philosophy, not Set Theory, so please excuse the naivety of my question.
My question concerns the wildly different character of ordinal arithmetic versus cardinal arithmetic.
The "initial" set of ordinals (upto omega-1), defined using succession and limit supremum, contains only countable ordinals.  Thus, omega, omega squared, ... epsilon-nought (the omega'th tetrate of omega), ... these are all countable sets.  I understand why these sets are countable.
Yet, when we consider cardinal numbers, 2 to the power aleph-nought is not countable.  I understand why it is not a countable cardinal.
What is it about the character of cardinal arithmetic that leads to such wildly different result from that of ordinal arithmetic.  After all, cardinal numbers are defined to be certain types of ordinal number.  Omega and aleph-nought are the same set.  Yet (as cardinals) 2 to the aleph-0 is uncountable, while (as ordinals) 2 to the omega, to the omega, to the omega,... is countable.
Comment: One approach is to ask why we can't define ordinal exponentiation in the same way as cardinal exponentiation. Given well-ordered sets $a$ and $b$, why don't we have a "natural" well-ordering on the set of all functions from $b$ to $a$? It's easy to show that the lexicographic order doesn't work. I'm not sure how to formulate or prove the general result, although I gather that it's possible. Maybe someone can address that?
Comment: The definition of the ordinal arithmetic actually gives you a set and a well-ordering of that set. In the definition of the cardinal exponential, you only get a set. Then the value of the cardinal exponential is the smallest ordinal that well-orders that set. Without the axiom of choice, even one such well-ordering may not exist.
Comment: Please be more precise about the "wild difference" that concerns you? Your question reads as if you think that ordinals are all countable.
Comment: @William and ChrisCulter : Thanks to you both for your interesting and helpful comments.  The definition of cardinal exponentiation in terms of the smallest well-ordering is especially helpful.  I honestly believed that there was no widely accepted definition.  The role of AC is also very revealing.
Answer: The reason is that the definitions of ordinal arithmetics and cardinal arithmetics are very different.
Whereas the ordinal arithmetics operations are concerned with order types, the cardinal arithmetics are concerned with certain sets.
For example, $\alpha+\beta$ as ordinals is the order type of $\alpha$ concatenated with $\beta$. Whereas cardinality strips naked any possible structure, and considering the cardinality of the set $\{0\}\times\alpha\cup\{1\}\times\beta$, which is equal to the maximum of $|\alpha|$ and $|\beta|$ (granted one is infinite).
Exponentiation, which is the strangest one, is defined very differently, again, from ordinals and cardinals.

In cardinals $\alpha^\beta$ is the cardinality of the set of all functions from $\beta$ to $\alpha$.
In the ordinals, we care about the order, so $\alpha^\beta$ is the order type of the reverse lexicographic order of functions from $\beta$ into $\alpha$ which are non-zero only in finitely many coordinates.
Equivalently, and perhaps more clearly, we can define this by induction, $\alpha^0=1$, $\alpha^{\beta+1}=\alpha^\beta\cdot\alpha$, and for a limit ordinal $\delta$, $\alpha^\delta=\sup\{\alpha^\beta\mid\beta<\delta\}$.
Now we easily see that $2^\omega=\omega$ when we are talking about ordinal exponentiation. $2^\omega$ is the limit of $2^n$ for finite $n$, but $2^n$ has a finite order type, and it's a strictly increasing sequence. The limit of a strictly increasing sequence of finite ordinals is $\omega$ itself.

Well, it sounds weird, isn't it? But it's not really weird. We have this sort of phenomenon in other - more familiar - systems of arithmetics.
In the natural numbers $n\cdot m$ can be defined as repeated addition of $n$, $m$ times. Addition itself can be defined as repeated successor operation. On the other hand, when we consider the real numbers $\sqrt2\cdot\sqrt2$ cannot be thought as repeated addition. What does it even mean to add something $\sqrt2$ times? It is true that in this case, if we restrict back to the natural numbers then the operations become repeated application of the "previous operation", but this is because of the nature of the natural numbers as a corner stone of modern mathematics (in many many ways). For infinite, and less-corner stoney this is not the case, as exhibited in ordinals and cardinals.
Comment: Wow!  That is as clear and helpful an answer as I could have ever hoped for.  You have also answered so many questions I have considered but did not here pose. Also,  I love the analog you give with systems of arithmetic.  Many thanks.
Answer: Well, to be frank, the distinction between $2^\omega$ and $2^{\aleph_0}$ is weirder, since we do have a quite natural link between $\omega$ and $\aleph_0$, whereas we do not have that between any natural number and $\sqrt2$.
The former case is using two homomorphic structures, with cardinalities being easily isomorphically embedded into ordinals, and the exact same syntactical operator, yielding non-isomorphic results. That is truly weird.
NOTE: this was intended as a comment to the very nice answer above, not the original question. Sorry.
Comment: Your answer doesn't appear to address the confusion the OP is having that since $\aleph_0 = \omega$, that must mean that also $2^{\aleph_0} = 2^{\omega}$, yet we can also prove by the two different definitions of exponentation that that's not the case. Also, I'm not sure this answer adds anything to Asaf Karagila's answer even if it is fixed up.
Comment: That is weird.  In fact, it's so weird I can't quite make sense of it.  Are you saying : The (order preserving) isomorphism we use to embed the cardinals into the ordinals becomes a non-isomorphism when viewed as a syntactical operator.  I'm still a bit green with this stuff, so sorry if that's a dumb question.
Comment: @Nick: If it's any consolation, I have no idea what's going on here either.
Comment: The difference being that the example @AsafKaragila brought up was that of a **pure extension**, i.e., multiplication of reals is just an **extension** of multiplication of integers, i.e., $N * N$ is still the same, for any integers, in that **extended field**. I.e., the semantics of multiplication doesn't **change** just **extend**...

This is **not** the case for exponentials of ordinals vs cardinals. I.e., an $2^x$ [in the class of cardinals] =/= $2^{iso(x)}$ [in the class of ordinals], where 'iso' is mapping cardinals into ordinals, such as $iso(\aleph_0) = \omega$.
Comment: Again, it is **very** rare that the same syntactical operator stands for entirely distinct operations, in domains being mutually homomorphic. So, I am a bit saddened by getting two down votes on pointing this out. Would be happier to see what exact terms I used were not accurate, so I can learn to get to the level of acuity as @AsafKaragila.


How to restrict field permissions to referenced user?

Question: I have a submit-review process where submitters choose their reviewer. The reviewers are linked By User Reference module. Submissions are public but have an Accept/Deny review button implemented with Button Field which only should be accessible by referenced user.
Workflow fields submodule seems to accomplish that behavior but unfortunately I can't get it to work with Workflow. There is an incompatibility of versions and maintenance seems not to be very active.
So I try to build my own solution using hook_field_access() like that:
<code>function MYMODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  if ($op == 'view' && !empty($entity) && ($field['field_name'] == 'field_accept_review' || $field['field_name'] == 'field_decline_review')) {
        // is current user == node reviewer?
        return ($entity->field_reviewer == $user->uid);
    }
}
</code>
Do I have to use user_load() before getting to the uid of the linked user?
Answer: I assume field_reviewer is an user reference field with only a single value allowed. If so use the following to get the referenced user's uid which is directly stored in field_reviewer array in submission:
<code>// is current user == node reviewer?
if (!empty($entity->field_reviewer)) {
  $reviewerId = $entity->field_reviewer['uid'];
  return ($reviewerId == $user->uid);
}
return FALSE;
</code>


Calculate the order in cycle notation

Question: Please help calculate the order of x and y. Let x and y denote permutations of $N(7)$ - Natural numbers mod 7  . Cycle notation:
$$x= (15)(27436) $$
$$y= (1372)(46)(5)$$
Thanks
Comment: You may want to try to prove that the order of a product of *disjoint* cycles is the lowest common multiple of the cycles' lengths.
Answer: Since you have the products of disjoint cycles, what do you know about the order of a cycle?
For a single cycle, its order is equal to its length.
The order of a product of disjoint cycles, as yours are, is equal to the least common multiple $(\operatorname{lcm})$ of the the orders of the cycles that form it, i.e., the least common multiple of the lengths of the disjoint cycles.
E.g. the order of $(1 2 3 4 5 6 7)$ is $7$. The order of $(123)(4567) = \operatorname{lcm}\,(3, 4) = 12$.
The order of $(123)(456)(7) = \operatorname{lcm}\,(3, 3, 1) = 3$.
Now, can you apply that to your permutations to find their orders?
Comment: Yes, the order of X is indeed 10. applying x 10 times will get you to the identity. But (1,2,3,4,5,6,7) is not the identity. (1)(2)(3)(4)(5)(6)(7) is the identity. (1, 2, 3, 4, 5, 6, 7) is a 7-cycle which maps 1 to 2, 2 to 3, ... 6 to 7, and 7 to 1. The identity maps 1 to 1, 2 to 2...7 to 7.  Note that for y, lcm(2, 4, 1) = 4. So if you take y^4, you will get the identity.
Comment: Okay, this makes more sense. So in X we have lcm(2,5) = 10. So I guess the order would be 10. My question is, is this saying it takes 10 cycles to get back to the identity (1,2,3,4,5,6,7)? I tried 10 cycles from 5 7 6 3 1 2 4, but didn't get the identify back.
Comment: Thank you! That makes a lot of sense. Just one last question-- how do you combine cycles ex- (123) (123) . why does (123)(123)=(132). I understand it's the composite function. So you would end up with 1-> 3, 2->1, 3->2. Not sure how you get to (132). Thanks!
Comment: I'm a bit confused with your notation. Can you write out the steps to arrive at 132. Thanks so much. You have been very helpful!
Comment: Just accepted it. (sorry, i'm new to the site). If you could spell it out that would be great!
Comment: You're right that 1 maps to 3. So we have (1 3 ...). So we need to see what happens to 3 starting back at the right-hand side. 3 maps to 2, so we have (1 3 2). Now we just need to ensure that starting back with the righthand side, 2 maps to 1. And it does. We start with 1, then depending on what 1 maps to, we work with that number, see where it maps, and then check that the number to be sure it maps back to 1.
Answer: we start from left cycle. in the left cycle we have $1\to2$ and in the right cycle we have $2\to3$, so we deduce that $1\to3$.
now in the left cycle we have $3\to1$ and in the right cycle we have $1 \to 2$, so we deduce that 3$\to2$.
Finally in the left cycle we have$ 2\to3$ and in the right cycle we have $3 \to 1$, so we deduce that $2\to1$.
So we have in product of this two cycles $1\to3$ and $3\to2$ and $2\to1 $that is the cycle $(132)$.
Answer: Hint: Find the least common multiple of the orders of each disjoint cycle.

Calculate the order in cycle notation


How to solve this trigonometric equation $\cos(\theta +20) = -0.74$

Question: Hi my question is what approach i should use in order to solve this $\cos(\theta +20) = -0.74$?
and why do we get rid of the negative sign when solving basis angle?
Here is my working
$\cos(\theta +20) = -0.74$
Then, $\alpha+20 = \arccos (0.74)$, to find the basis angle. After I plugged into the calculator and got $42.3$,  I subtract $20$ from $42.3$ to solve for $\theta$ which is $22.3$. $\theta = 42.3 -20 = 22.3$
Since $\cos$ is negative, the angle is at 2nd and 4th quadrant. So I solve for the angle $180-22.3=157.7$ and $180+22.3=202.3$
But all of this is wrong can someone explain? I think it is my approach that got me wrong, but I am unsure.
Comment: $20$ is probably not degrees.
Comment: Also remember that the equation actually has an infinite number of solutions.
Answer: In general we have that in degrees for $x\in[0,360°]$
$$\cos x = y \implies x=\arccos y \quad \lor \quad x=360°-\arccos y$$
therefore
$$\cos(\theta +20°) = -0.74 \implies \theta +20°=\arccos (-0.74) \quad \lor \quad \theta +20°=2\pi-\arccos (-0.74)$$
Check that the calculator is set to give the result in degree.
Comment: Thanks and what do i do when i got a negative angle?
Comment: Working in degrees we obtain [$\arccos(-0.74)= 137.7$](http://m.wolframalpha.com/input/?i=arccos%28-0.74%29) then $\theta=157.7$ and $\theta=360-157.7=202.3$ are both solutions (when we set $\theta\in[0,360]$) and more in general any $\theta=\pm 157.7+360k$ with $k\in \mathbb{Z}$ is a possible solution.
Answer: Assuming all angles are in degrees, you should avoid strange switches in the sign.
With a calculator, $\arccos(-0.74)=137.7$, so the solutions are
$$
\theta+20=137.7+360k
$$
or
$$
\theta+20=-137.7+360k
$$
The solutions in the range $[0,360]$ are therefore $137.7-20=117.7$ or $-137-20+360=202.3$.
On the other hand, if angles are measured in radians,
$$
\theta+20=\arccos(-0.74)+2k\pi=2.404+2k\pi
$$
or
$$
\theta+20=-\arccos(-0.74)+2k\pi=-2.404+2k\pi
$$
Thus
$$
\theta=-20+\arccos(-0.74)+2k\pi
$$
or
$$
\theta=-20-\arccos(-0.74)+2k\pi
$$
For the solutions in the range $[0,2\pi]$ you have to choose $k=6$ in the first case and $k=8$ in the second case, obtaining
$$
1.253\qquad\text{or}\qquad 2.729
$$
Answer: $$\cos(\theta+20) = -0.74$$
$$\theta+20 = \arccos (-0.74)$$
Recall the range of $\arccos x$ is $0 \leq x \leq 180$.
$$\begin{cases}
Quadrant \space II \implies \theta+20 = \arccos(-0.74) \implies \theta = \arccos(-0.74)-20\\
\
\\
Quadrant \space III \implies \theta+20 = 360-\arccos(-0.74) \implies \theta = 360-\arccos(-0.74)-20
\end{cases}$$
Finally, solve for $\theta$.
For the angle in the second quadrant:
$$\theta = \arccos(-0.74)-20 \approx 137.73-20 \approx 117.73$$
For the angle in the third quadrant:
$$\theta = 360-\arccos(-0.74)-20 \approx 360-137.73-20 \approx 202.27$$
Remember that angles repeat infinitely, so each angle repeats after $360°$. If the question asks for angles in the domain $0 \leq \theta \leq 360$, your answer is complete.
If, however, you're asked for a complete set of solutions, you have to add in $\color{blue} {360n}$ for all $\color{blue}{n \in \mathbb{Z}}$.
$$\theta \approx 117.73+360n$$
$$\theta \approx 202.27+360n$$
By changing the order and signs, you reached an incorrect answer. Try to avoid doing that and you'll be fine with these types of questions.
Comment: Thank you. I am actually preferred not to change the signs ie the negative sign and alpha symbol, but my teacher wanted me to use alpha to represent the basis angle which required to take away the negative sign
Comment: Good, I get your point. The reason you got the wrong answer using that method was that you calculated for $\theta$ first. You're supposed to calculate the total angle, and then find $\theta$. Using your way, we can do the following: $$\arccos(0.74) \approx 42.27$$ Our total angle ($\theta+20$) is about $42.27°$. The total angle is in quadrants $2$ and $3$. Thus, for the second quadrant: $$\theta+20 \approx 180-42.27 \implies \theta+20 \approx 137.73 \implies \theta \approx 117.73$$ For the third: $$\theta+20 \approx 180+42.27 \implies \theta+20 \approx 222.27 \implies \theta \approx 202.27$$
Comment: So basically, you find the values for $\theta+20$, or rather, the entire angle, first. Then, you find $\theta$ for both situations. You used the reverse process, which got the signs mixed up.
Comment: awesome thanks for helping out! But I have 1 more question, using the current way you have showed me, i tried in one of the questions and i have obtained a negative answer. What does this mean and how do i proceed? $tan(\theta-50)=-1.7$, solve for $\theta$ and i have got $-9.5$. Can you please help? Thank you and sorry
Comment: @Tfue $$\tan(\theta-50) = -1.7$$ $$\theta-50 = \arctan(-1.7)$$ Recall the range of $\arctan x$ is $-\frac{\pi}{2} < x < \frac{\pi}{2}$. So, the angle given will will be in the the fourth quadrant. But, tangent is also negative in the second quadrant. For the first case, $$\theta-50 = \arctan(-1.7) \implies \theta = \arctan(-1.7)+50 \implies \theta \approx -9.53446 \approx 350.46554$$ For the second case, $$\theta-50 = 180+\arctan(-1.7) \implies \theta = 180+\arctan(-1.7)+50 \implies \theta \approx 170.46554$$
Comment: So yes, you got one of the solutions correctly. Don't freak out if you get a negative angle. For any $-\theta$, the angle can be rewritten as $360-\theta$. Also, as I mentioned, the domain of $\arctan x$ function is $-\frac{\pi}{2} < x < \frac{\pi}{2}$, so the angle returned by the calculator will be in the fourth quadrant. A negative angle is often returned. (For example, $-10°$ rather than $350°$.) If you subtract its absolute value from $360°$ and get a value satisfying $-270° < \theta \leq 360°$, it's all fine.
Comment: Also, as a final note, $\tan x$ is periodic and repeats every $180°$. If the question asks for a general solution, you must add in $\color{blue}{360n}$ for all $\color{blue}{n \in \mathbb{Z}}$. So, you get the following solutions:
$$\theta \approx 350.46554+360n$$
$$\theta \approx 170.46554+360n$$
But if you notice, $350.46554°$ and $350.46554°$ themselves are $$180°$$ apart, so all midpoints will also be covered. Hence, the two solutions can be compressed into one:
$$\theta \approx 170.46554+180n$$
Hence the original point that $\tan x$ is periodic and repeats every $180°$.
Comment: Wow whoever you are thank you everything you have taught me! However, there is stuff I am still unsure about(sorry), such as the $arctan$ domain (or is it range? idk). So you said the $arctan$ domain is $-90<x<90$, does that mean that $x$ is between anticlockwise quadrant 1 and clockwise quadrant 4? With that said so everytime I obtained a negative answer, all I am required to do is just +360?
Comment: @Tfue No problem! I meant range, accidentally wrote domain. Since the range of $\tan x$ is all real numbers, the domain of $\arctan x$ is also all real numbers.
Comment: Also, yes, if your angle is negative, it is always better to add $360$ because positive angles are preferred. You may want to accept the answer if it was helpful too. :-)
Comment: Thank you again! So overall, if i use your method ie (not finding the reference angle), it will not always give you the reference angle but the angle in the range? Which in this case i have obtained $-9.5$, so this is NOT a reference angle right? Or this IS a reference angle but only omitting the negative sign? And my last question (im so sorry), from what you said $-180$ is exact same as $180$, as well as -88.6 is also same as 271.4 Sorry and thank you from my mum and me
Comment: Calculators will only give the angle in the range. I think it would help you out if you knew the domain and range of all six trig functions and their inverses. $$\sin x \implies -\frac{\pi}{2} \leq x \leq \frac{\pi}{2} \implies \vert y\vert \leq 1$$ $$\cos x \implies 0 \leq x \leq \pi \implies \vert y\vert \leq 1$$ $$\tan x \implies -\frac{\pi}{2} < x < \frac{\pi}{2} \implies y \in \mathbb{R}$$ These are for the normal trig functions.
Comment: For reciprocal functions: $$\csc x \implies -\frac{\pi}{2} \leq x \leq \frac{\pi}{2}; x\neq 0 \implies \vert y\vert \geq 1$$ $$\sec x \implies 0 \leq x \leq \pi; x\neq \frac{\pi}{2} \implies \vert y\vert \geq 1$$ $$\cot x \implies -\frac{\pi}{2} < x < \frac{\pi}{2}; x\neq 0 \implies y \in \mathbb{R}$$ For inverses, switch domain and range. This might seem like a bit too much to grasp, but if you write it out and think about it, it all becomes clear. (Yes, $180 = -180$ and $271.4 = -88.6$.)
Comment: Thank you for the info, so ie let say we have $arcsin (-0.5)$ it would give me $-30$ since this is in the range. and since this is a negative angle, I just have to plus $360$ to it which means that the first solution is $330$. But since sin is negative then the second solution is located at quadrant 3 right? But how do i find the second solution? I assume the second solution would be $360-150$ then is this correct? (my last question i promise!)
Comment: Yes, the calculator gives $-30°$ as the angle. To get the angle in the third quadrant, add the absolute value to $180°$, thus getting $210°$. As a hint, you can always use the angle in the first quadrant to get the angles in other quadrants. The first quadrant angle here is $30°$, which corresponds to $150°$, $210°$, and $330°$ in the other three quadrants. (At least that's how I always think about it.) But always remember this applies to the whole angle, not to a part of it. That could get the signs mixed up (like what happened for your first question).
Comment: Wow Thanks so much, but unfortunately i have 1 more question :( sorry. I am currently doing this problem $sin\theta=0$ in the range of 0 or equal to 360 or equal.So, i solved for $\theta$ which i obtained 2 solutions which are $0$ and $180$ BUT this is not completely right! I apprently there is 1 more solutions which is 360! But how?
Comment: Haha no problem, I'm fine answering questions. Technically, $0°$ and $360°$ are the same. (The simplest and most complete solution would be $180n$ for all $n \in \mathbb{Z}$. This would mean all integer multiples of $180°$ are part of the solution. (Also, do you always work with degrees? Usually radians are preferred, at least from what I've seen.)
Comment: Yes sir i worked with degrees. So, does that mean i have 3 solutions? and when i have $0$ as my solution, i must include $360$ as well? What are  $180n$ for all $n$ E thingy and Z thingy?
Comment: I think it's better to include $360°$ in the solution since the domain given is usually $0 \leq x \leq 360$. $180n$ for all $n \in \mathbb{Z}$ is another way of saying "all multiples of $180°$ are in the answer". (There are infinite solutions in reality.) $$...-720°, -540°, -360°, -180°, 0°, 180°, 360°, 540°, 720°, ...$$ Now whether or not you include that statement depends on what domain the question gives. If it asks for all solutions in the domain $0 \leq x \leq 360$, you don't include it. If it asks for a complete set of solutions, however, you have to include it.


JOIN always the default value, else join the match value

Question: I have the following SQL Server Query
select r.isactive,r.workingyear,r.startperiod,r.endperiod,r.anniversary
from setup_holiday_policy t cross apply
 (select data
  from dbo.Split(t.scheduleapplication, ',')
 ) di cross apply
 (select max(case when did.id = 1 then did.data end) as isactive,
         max(case when did.id = 2 then did.data end) as workingyear,
         max(case when did.id = 3 then did.data end) as anniversary,
         max(case when did.id = 4 then did.data end) as startperiod,
         max(case when did.id = 5 then did.data end) as endperiod
  from dbo.Split(di.data,':') did
 ) r
 WHERE r.workingyear =  @employeeworkingyears

The policy table can have a 0 value in the workingyear field. Meaning that when this field has 0 then is the default record I should return.
setup_holiday_policy

So, if @employeeworkingyears = 2 and there is no workingyears = 2 in setup_holiday_policy I should return the default row that has the 0 value in workingyears field.
This is a sample of the rows returned.

Any clue how to achieve this?
Comment: Can you show an example data table and result table?
Comment: If my table matches the where r.workingyear = something then return the record found, else if there is no match I should always return the row that has 0 in the workingyear field.
Comment: Can you please reduce your query to the absolute minimum required to demonstrate your problem - specifically don't copy paste your entire actual query, because 90% of it is noise and irrelevant to the problem.
Answer: If only one row is going to be returned (as suggested by the sample data), you can do this using top:
select top 1 r.isactive,r.workingyear,r.startperiod,r.endperiod,r.anniversary
from setup_holiday_policy t cross apply
     (select data
      from dbo.Split(t.scheduleapplication, ',')
     ) di cross apply
     (select max(case when did.id = 1 then did.data end) as isactive,
             max(case when did.id = 2 then did.data end) as workingyear,
             max(case when did.id = 3 then did.data end) as anniversary,
             max(case when did.id = 4 then did.data end) as startperiod,
             max(case when did.id = 5 then did.data end) as endperiod
      from dbo.Split(di.data,':') did
     ) r left outer join
     (select @employeeworkingyears as employeeworkingyears
     ) e
     on
WHERE r.workingyear in (@employeeworkingyears, 0)
order by r.workingyear desc;


Sleeping within nested for loops in bash

Question: I have a pair of nested for loops in a bash shell script.
I want to pause the script every 60 seconds when a counter hits a multiple of 50 "ticks" or iterations, so I put in a modulo test:
counter=1
for ((i=0; i<${#libraries[@]}; i++)); do
    for ((j=(i+1); j<${#libraries[@]}; j++)); do
        # do stuff...
        if [ $counter%50 == 0 ]; then
            sleep 60s
        fi
        counter=$[$counter+1]
    done
done

This loop behaves erratically — specifically, this script does not pause every 50 iterations, but occasionally staggers and mostly skips or otherwise does not appear to be triggering the expected sleep call correctly.
Whatever I put into # do stuff... this script does not pause as expected, but behaves in roughly the same erratic way. I can comment it out — same behavior.
The ${#libraries[@]} stuff is just an array of file paths.
Does sleep not work inside loops, or am I not using it correctly? Is there an alternative way to pause the script without breaking out the nested loops into separate wrapper scripts?
Comment: `$[...]` was deprecated *decades* ago; use `$((...))` instead.
Comment: Also the trailing `s` after `60` in your `sleep` command is suspicious, check your `man sleep`.  The program probably ignores it, but I doubt it should be there.
Comment: No, that's fine.
Answer: I think your test is wrong.  Try this instead :
if (( counter % 50 == 0 ))

The $counter%50 part will never expand to 0, so this test will always fail, and the sleep will never be executed.  The % modulo operator requires an arithmetic context, which the standard test command does not provide, but the double parentheses will.
Comment: Rest assured I am an idiot too, we all take turns :).


É mais vantajoso usar "return" de tupla ou um parâmetro "out"?

Question: Agora que existe as duas formas de retornar um valor de uma função, é sempre vantajoso usar o retorno de tupla, o "novo" recurso, ou ainda tem motivos para usar um out ou até mesmo um ref?
Answer: O advento da tupla retirou muito da funcionalidade do out, fazendo com que ele se torne mais legado. Porém ele ainda pode ser útil em alguns casos.
Apesar de ser mais intuitivo e elegante usar múltiplo retorno com uma tupla, o out é interessante pelo menos quando você quer obrigar o chamador a pegar o valor retornado. O return permite o código só descartar o valor, já o parâmetro terá que criar uma variável e receber o valor. Obviamente que se depois o código não fizer nada com a variável não tem o que fazer.
Lembre-se que um método não pode ser marcado como assíncrono se tiver um parâmetro out ou ref.
A performance da tupla pode ser ligeiramente inferior nos cenários mais típicos, mas há casos que isso pode se inverter. Não deveria ser uma preocupação até que precise do extremo.
Para o geral é melhor:
(int x, bool ok) = Resultado();

Do que:
bool ok;
int x = Resultado(out ok);

Como última informação, o comportamento é ligeiramente diferente, já que usando o out ou mesmo ref se mudar o valor na função chamada, no mesmo momento está mudando na variável da chamadora, porque a variável da chamada é a variável da chamadora por causa da referência usada. Com a tupla isso só aconteça no fim da execução da função. Em alguns cenários isso pode fazer diferença, especialmente com concorrência.
Ver mais.
Coloquei no GitHub para referência futura.
Comment: Nem sempre tuplas dão certo onde `out` estão. Por exemplo, `T TryParse(string, out T)` é um pattern que dispensa o uso de tuplas.
Comment: Não é que dispensa, é que a tupla não existia na época que este método foi criado, hoje não seria assim.


Leave a loop after 2 seonds

Question: I would like to repeat a text for 2 seconds in a while loop. How do I break the loop after 2 seconds?
This is what I have tried so far but it doesn't work:
var repeat = true;
setTimeout(function() { var repeat = false }, 2000)
while(repeat) {
    console.log("Let's repeat for 2 seconds...");
}

Comment: Not possible with the timeout, the while loop locks it up. You would need to check the time inside the loop. Still not great because it will still lock up the browser and the browser can stop it
Comment: Possible duplicate of [Using javascript how to break the while loop after a set time?](https://stackoverflow.com/questions/34069086/using-javascript-how-to-break-the-while-loop-after-a-set-time)
Comment: @ivar please undelete your answer, its a good one
Comment: Um, that dupe is a very bad one ?!
Comment: @JonasW. Well, at least this one got some good answers.  Maybe we should consider closing the other as a dupe of this :p
Comment: @merv yup, i did
Answer: Additionaly to the other answer you could just check the time instead:
 const start = +new Date;

  while(+new Date < start + 2000) {
     console.log("Let's repeat for 2 seconds...");
 }

Answer: JavaScript is single threaded. This means that as long as your loop runs, your timeout will never be fired.
Depending on what you want and whether or not you want to lock down your browser (by using an actual infinite loop), you can use the setInterval as a loop, and use the setTimeout to stop the interval after 2 seconds.

console.log("Starting loop");

var interval = setInterval(function () {
    console.log("Let's repeat for 2 seconds...");
}, 0);

setTimeout(function() {
    clearInterval(interval);
    console.log("Finished loop");
}, 2000);
Answer: If you're concerned at all with performance of this loop, the proposed solution would be a problem.
Note that in most cases, you shouldn't be synchronously iterating a huge number of times in Javascript since that would completely block the browser or server during this time, but there are some cases where this might be needed. Just be aware that this is generally not a good thing to do.
What follows is my own experimentation with several options to reduce the overhead of checking a timeout, since I was using it to benchmark other code.
I added console.time logs to both solutions, and added a couple of optimizations that might be worth considering.
The accepted solution has the worst performance:

const label = 'interval';
console.time(label);
let i = 0;
const interval = setInterval(
  () => {
    i += 1;
  },
  0);

setTimeout(
  () => {
    clearInterval(interval);
    console.timeEnd(label)
    console.log(`${i.toExponential()} iterations`);
  },
  2000);
// interval: 2001.100ms
// 4.93e+2 iterations

The next answer has much better performance, but it's still performing unnecessary work, type conversions and addition on every loop run:

let i = 0;
let start = +new Date;
let label = '+new Date + 2000';
console.time(label);
while ((+new Date) < start + 2000) {
  i += 1;
}

console.timeEnd(label)
console.log(`${i.toExponential()} iterations`);
// +new Date + 2000: 1999.800ms
// 1.0921121e+7 iterations

By using Date.now() instead of (+new Date) you get a performance increment of around 2.5x:

let label = 'Date.now()';
console.time(label);
let end = Date.now() + 2000;
let i = 0;
while (Date.now() < end) {
  i += 1;
}
console.timeEnd(label)
console.log(`${i.toExponential()} iterations`);
// Date.now(): 1999.000ms
// 2.6477108e+7 iterations

If performance is much more important that the exact nanosecond when you stop, and the operations are super fast, you can reduce the number of checks for even more operations:

let label = 'fuzzy + 2000';
console.time(label);
let end = Date.now() + 2000;
let i = 0;
// Only check the timeout every 1000 operations thanks to lazy evaluation.
while (i % 1000 !== 0 || Date.now() < end) {
  i += 1;
}
console.timeEnd(label)
console.log(`${i.toExponential()} iterations`);
// fuzzy + 2000: 1999.800ms
// 6.5632e+8 iterations

30x better! You will need to tweak the frequency of the checks based on both the average loop time and how exact you want your timeout to be.

Leave a loop after 2 seonds


Issue installing version 10 on a new DNN 9.2.2

Question: I'm trying to install the blog app and keep getting an error message.
<code>05/26/2019 20:49:27
Admin Alert
host

2sxc-Api Auto-Log Exception 2sInst[3e Path http://enjoythisworld.com/deskt
2sxc-Api:Auto-Log Exception

2sInst[3e]:Path: http://enjoythisworld.com/desktopmodules/2sxc/api/app-sys/installer/installpackage?packageUrl=https://2sxc.org/Portals/0/adam/AppCatalog/5EMutByRNEWtODu1sMkpDg/Download/2sxcApp_Blog_03.00.02.zip

2sInst[3e]DNN.Enviro[1b]Dnn.Publsh[70]:()

2sInst[3e]:install package:https://2sxc.org/Portals/0/adam/AppCatalog/5EMutByRNEWtODu1sMkpDg/Download/2sxcApp_Blog_03.00.02.zip

2sInst[3e]Dnn.MapA2I[53]:get appid from instance for Z:2 Mod:451 not found = null

2sInst[3e]Zip.Imp[6f]:import zip from url:https://2sxc.org/Portals/0/adam/AppCatalog/5EMutByRNEWtODu1sMkpDg/Download/2sxcApp_Blog_03.00.02.zip, isApp:True

2sInst[3e]Zip.Imp[6f]:try to download:https://2sxc.org/Portals/0/adam/AppCatalog/5EMutByRNEWtODu1sMkpDg/Download/2sxcApp_Blog_03.00.02.zip to:C:\Inetpub\vhosts\enjoythisworld.com\httpdocs\desktopmodules\tosic_sexycontent_\4po5clpp.vke.zip

Server Name: GenericAU04

Check
05/26/2019 20:49:27
General Exception
host
Enjoy This World
AbsoluteURL /desktopmodules/2sxc/api/app-sys/installer/installpackage Defa
AbsoluteURL:/desktopmodules/2sxc/api/app-sys/installer/installpackage

DefaultDataProvider:DotNetNuke.Data.SqlDataProvider, DotNetNuke

ExceptionGUID:f9b14e08-800d-4577-b7f3-4751cf4e96ec

AssemblyVersion:

PortalId:-1

UserId:-1

TabId:-1

RawUrl:

Referrer:

UserAgent:

ExceptionHash:EUTd+51qrnU8qi8gRlrnBDlmOGY=

Message:An error occurred while installing the app: Could not download app package from 'https://2sxc.org/Portals/0/adam/AppCatalog/5EMutByRNEWtODu1sMkpDg/Download/2sxcApp_Blog_03.00.02.zip'.

StackTrace:

at ToSic.SexyContent.WebApi.InstallerController.InstallPackage(String packageUrl) in C:\Projects\2sxc-dnn742\Website\DesktopModules\ToSIC_SexyContent\Sxc WebApi\InstallerController.cs:line 51 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Tracing.ITraceWriterExtensions.d__18`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Tracing.ITraceWriterExtensions.d__18`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ExceptionFilterResult.d__0.MoveNext()
InnerMessage:Could not download app package from 'https://2sxc.org/Portals/0/adam/AppCatalog/5EMutByRNEWtODu1sMkpDg/Download/2sxcApp_Blog_03.00.02.zip'.

InnerStackTrace:

at ToSic.Eav.Apps.ImportExport.ZipImport.ImportZipFromUrl(String packageUrl, Boolean isAppImport) at ToSic.SexyContent.WebApi.InstallerController.InstallPackage(String packageUrl) in C:\Projects\2sxc-dnn742\Website\DesktopModules\ToSIC_SexyContent\Sxc WebApi\InstallerController.cs:line 32
Source:ToSic.SexyContent.WebApi

FileName:

FileLineNumber:0

FileColumnNumber:0

Method:

Server Name: GenericAU04
</code>
Answer: I'm guessing that your server doesn't have an internet connection - maybe communication between the server and the internet is prohibited. To work around this, download the app directly from the app catalog and upload/install it from the zip.
Best, iJungleboy
Comment: The server does have internet.  Could you elaborate on the option to upload and install manually.
Comment: you can always download apps from 2sxc.org/apps and then use the down-arrow-button to install the zips.
Comment: It installed fine from the down arrow thanks.  I've reported the other issue to you with error messages after I removed the demo items.


Approximate the sine function with shallow neural network

Question: I want to approximate a region of the sin function using a simple 1-3 layer neural network. However, I find that my model often converges on a state that has more local extremums than the data. Here is my most recent model architecture:
layers:     x, h1, y

dimensions: 1, 128, 1

activations: tanh, tanh

error function: sum((y_predict - y)^2)

and the result, trained with 4000 data points for 3000 iterations with learning rate = 4e-7:

another deeper model trained under the same conditions:
layers:     x, h1, h2, h3, y

dimensions: 1, 32, 128, 32, 1

activations: tanh, tanh, tanh, tanh

error function: sum((y_predict - y)^2)

I often see an excess of complexity in the output within the first 2 X units, and it stabilizes after that. What is the reason for this noise, and how can modify my architecture to fit the full range of the data without overfitting this early range of the data?
The training is also highly variable (Y=loss, X=iterations):

I used pytorch to implement the model:
import torch
from torch.autograd import Variable
import numpy
from matplotlib import pyplot

dtype = torch.FloatTensor
# dtype = torch.cuda.FloatTensor # Uncomment this to run on GPU

layer_size = 1, 128, 1
layer_functions = ["tanh","tanh"]

m_x = 4000
n_x = layer_size[0]
n_y = layer_size[-1]

x_raw = numpy.random.rand(m_x,n_x)*10 - 1
y_raw = (numpy.sin(x_raw))/2.5 + (numpy.random.randn(m_x,n_x)/20)

# Create Tensors to hold input and outputs, and wrap them in Variables.
x = Variable(torch.from_numpy(x_raw).type(dtype), requires_grad=False)
y = Variable(torch.from_numpy(y_raw).type(dtype), requires_grad=False)

# Create random Tensors for weights, and wrap them in Variables.
layer_weights = list()
for i in range(0,len(layer_size)-1):
    print(layer_size[i],layer_size[i+1])
    layer_weights.append(Variable(torch.randn(layer_size[i],layer_size[i+1]).type(dtype), requires_grad=True))

def forward_step(x,weights,activation):
    if activation == "sigmoid":
        fn = torch.nn.Sigmoid()
    elif activation == "tanh":
        fn = torch.nn.Tanh()
    elif activation == "relu":
        fn = torch.nn.ReLU()
    else:
        exit("ERROR: invalid activation function specified")

    output = fn(x.mm(weights))

    return output

y_pred = None
losses = list()
learning_rate = 4e-7
for t in range(3000):
    # Forward pass: compute predicted y using operations on Variables
    y_pred = forward_step(x,weights=layer_weights[0],activation=layer_functions[0])
    for i in range(1,len(layer_weights)):
        y_pred = forward_step(y_pred, weights=layer_weights[i], activation=layer_functions[i])

    # Compute and print loss using operations on Variables.
    loss = (y_pred-y).pow(2).sum()
    print(t, loss.data[0])
    losses.append(loss.data[0])

    # Use autograd to compute the backward pass. This call will compute the
    # gradient of loss with respect to all Variables with requires_grad=True.
    # After this call weights.grad will be Variables holding the gradient
    # of the loss with respect to w1 and w2 respectively.
    loss.backward()

    # Update weights using gradient descent; w1.data and w2.data are Tensors,
    # w1.grad and w2.grad are Variables and w1.grad.data and w2.grad.data are
    # Tensors.
    for i in range(0,len(layer_weights)):
        layer_weights[i].data -= learning_rate*layer_weights[i].grad.data

        # Manually zero the gradients after running the backward pass
        layer_weights[i].grad.data.zero_()

y_pred = y_pred.data.numpy()

print(y_pred.shape, y_raw.shape)

fig1 = pyplot.figure()
x_loss = list(range(len(losses)))
pyplot.plot(x_loss,losses)
pyplot.show()

fig2 = pyplot.figure()
pyplot.scatter(x_raw,y_raw,marker='o',s=0.2)
pyplot.scatter(x_raw,y_pred,marker='o',s=0.3)
pyplot.show()

Comment: "activations: tanh, tanh"  Try using single layer with sin for activation function.
Comment: I was able to solve it with a more advanced gradient update algorithm. See my own answer below. The tanh function is theoretically capable of transforming x -> y in this example, and the results demonstrate this.
Comment: This has nothing to do with logistic regression. LR is a model for binary data (sin function is not binary). Moreover NN $\ne$ LR.
Comment: edited title and tags.
Comment: Your output layer should be linear (you cannot control the shape of tanh  and range of output independently so the tanh nonlinearity doesn't help
Answer: So I solved my own problem, and the solution was to use a more advanced optimizer instead of vanilla gradient descent. By using the "nn" module from pytorch, you can select from a range of optimizers which incorporate concepts like "momentum", regularization, and learning rate decay to update the weights of the network in a way that is more likely to find a local minimum.
UPDATE:
I have created an interactive tutorial on this problem for those interested. It is a Jupyter notebook containing the minimum code to get this problem running, and leaves room for the user to improve the fit of the model through experimentation with layers, optimizers, etc.: link
This page has some explanation. More in their cs231n (free) online lectures.
Another explanation with nice animations.
Training with Adam optimizer, 1000 iterations, loss=L1Loss (Y=loss, X=iter):

Resulting model (orange=prediction, blue=training data):

zoomed:


O que é shadow DOM?

Question: Quando eu estava lendo sobre alguns frameworks Javascript, como por exemplo o React, li algumas vezes a expressão shadow DOM em alguns artigos.
Parece inclusive que é possível, nas configurações de console do Chrome, ativar esse tal de Shadow Dom.

Mas o que é Shadow DOM e pra que serve?
Tem alguma coisa a ver apenas com o Framework citado acima, ou não?
Comment: Relacionado: [Google Polymer](https://www.polymer-project.org/) também faz uso de Shadow DOM para definir seus componentes.
Comment: https://glazkov.com/2011/01/14/what-the-heck-is-shadow-dom/  está em inglês
Comment: Pode ser que https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM aqui tenha algo interessante, mas a página é só um rascunho
Comment: Parece estar diretamente relacionado com [Web Components](http://pt.stackoverflow.com/questions/160175/o-que-s%C3%A3o-web-components)
Answer: Shadow DOM
O shadow DOM, ou shadow tree, é uma árvore de nós HTML assim como qualquer outra árvore que já conhecemos (a light tree), mas que é anexada a um elemento específico da light tree, não ao documento em si. Ou seja, é criado um novo contexto de nós em que todos os nós pertencentes à shadow tree não interagem diretamente com os nós do documento. Esta regra é válida também para o CSS (aparentemente o JavaScript não é encapsulado), ou seja, você pode definir regras no CSS utilizando ids e classes normalmente, que tais regras se aplicarão apenas ao contexto da shadow tree e não se aplicarão ao documento em si.
Veja o exemplo abaixo. É criado uma shadow tree a partir do elemento template e anexado ao elemento #nameTag. Perceba que as definições de estilo da shadow tree não se aplicam aos elementos externos, presentes na light tree.

A classe .outer é definida tanto para um elemento na light tree quanto um elemento na shadow tree, porém, devido o encapsulamento das definições de estilo, apenas o elemento da shadow tree é estilizado.

var shadow = document.querySelector('#nameTag').createShadowRoot();
var template = document.querySelector('#nameTagTemplate');
var clone = document.importNode(template.content, true);
shadow.appendChild(clone);

Stack Overflow em Português

Bob

<template id="nameTagTemplate">

      Olá! Meu nome é

      Bob

</template>

O conceito de shadow DOM faz parte dos quatro padrões de Web Component, junto com modelos HTML, elementos personalizados e importações de HTML.

Os outros três podem outras perguntas semelhantes a esta aqui no SOpt, acredito eu.

Terminologia
A composição do Shadow DOM introduz vários conceitos básicos novos no desenvolvimento da Web. Antes de entrarmos em detalhes, vamos padronizar a terminologia para falarmos o mesmo idioma.
Light DOM
A marcação escrita por um usuário do seu componente. Esse DOM reside fora do shadow DOM do componente. Ele consiste nos filhos reais do elemento.
<button is="better-button">

  Settings
</button>

Shadow DOM
O DOM escrito pelo autor do componente. O Shadow DOM é local em relação ao componente e define sua estrutura interna e o CSS com escopo, bem como encapsula os detalhes da sua implementação. Além disso, ele define como renderizar marcação criada pelo consumidor do seu componente.
#shadow-root

  <slot name="icon"></slot>

    <slot>Button</slot>

Árvore plana do DOM (plane tree)
O resultado da distribuição do light DOM do usuário pelo navegador no shadow DOM, renderizando o produto final. A árvore plana é o que você finalmente verá no DevTools e o que será renderizado na página.
<button is="better-button">
  #shadow-root

    <slot name="icon">

    </slot>
    <slot>
      Settings
    </slot>
</button>

Posso Usar (Can I Use?)
Shadow DOM v0

Shadow DOM v1

Tenha mais informações sobre a compatibilidade de navegadores e polyfills aqui.

Fonte:

Especificação W3C
Shadow DOM v1: Componentes da Web Independentes
Comment: @Matheus, o documento é o documento raiz da página. A interação dos elementos contidos na *shadow tree* se limita ao elemento *host*, isto é, o elemento da *light tree* ao qual foram associados. Prova disso é que se você ler sobre a propagação de eventos, qualquer evento gerado na *shadow tree* será mapeado para o elemento *host* da *light tree*. Por exemplo, se houver um `button` na *shadow tree* do elemento `my-component` e eu clicá-lo, o evento que será propagado é o `click` do elemento `my-component`, não do `button` em si.
Comment: Excelente resposta +1
Comment: Achei a resposta mais fácil de entender, mas nesse trecho  *"Ou seja, é criado um novo contexto de nós em que todos os nós pertencentes à shadow tree não interagem diretamente com os nós do documento."*, não sei se está tentando dizer que "documento" é o documento raíz da página ou o documento parente da sombra. (Se for esse o caso, então a sombra interior não se interage com a exterior?).
Comment: Pode ler sobre isso nos tópicos [O modelo de eventos do Shadow DOM](https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom?hl=pt-br#events) e [Processamento de foco](https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom?hl=pt-br#focus).

O que é shadow DOM?


Prove $f_{n_k}$ converges uniformly on compact sets.

Question: Assume $(f_n)$ is a monotically increasing sequence of functions on $\mathbb{R}$ with $0\leq f_n(x)\leq 1$ for all $n$ and all $x$. There are two parts to this. In the first, I show that $\exists f$ and a sequence $(n_k)$  such that $f(x)=\lim\limits_{k\to\infty}f_{n_k}(x)$ for all $x$. In my work so far, I think I have sufficiently shown this.
However, if I also assume that $f$ is continuous, I want to show that $f_{n_k}\to f$ uniformly on compact sets.
My thoughts: Take any compact set $K\subseteq\mathbb{R}$ and since $K$ is closed and bounded, there exists a closed and bounded interval $[a,b]$ such that $K\subseteq [a,b]$. If we can show uniform convergence on $[a,b]$, then it follows for $K$ and we are done. I then want to say something like:
"Let $\varepsilon >0$ and choose $\delta$ such that $\{x_1,\dots x_l\}$ is a $\delta$-dense set in $[a,b]$ where, by continuity and monotonicity, $x_m\leq x\leq x_{m+1}$ implies $f(x_m)-\varepsilon\leq f_{n_k}(x_m)\leq f_{n_k}(x)\leq f_{n_k}(x_{m+1})\leq f(x_{m+1})+\varepsilon$."
in order to begin showing this convergence within $\varepsilon.$ I am painfully aware of how incorrect the above is, but can't find a the right way to phrase my goal. Any help is greatly appreciated.
Comment: Is $f_{n}$ continuous also (for the uniform convergence case)?
Answer: For the uniformly convergence case, I assume further that those $f_{n}$ are continuous.
As what you have said, we need only to deal with $[a,b]$. For any $\epsilon>0$ and any $x\in[a,b]$, choose $n_{x}>0$ and $\delta_{x}>0$ such that $n\geq n_{x}$ implies $|f_{n}(x)-f(x)|<\epsilon$ and that $y\in B_{\delta_{x}}(x)$ implies $|f(y)-f(x)|<\epsilon$ and $|f_{n_{x}}(y)-f_{n_{x}}(x)|<\epsilon$. Compactness of $[a,b]$ implies some $\delta_{x_{1}},...,\delta_{x_{N}}$ such that $[a,b]\subseteq B_{\delta_{x_{1}}}(x_{1})\cup\cdots\cup B_{\delta_{x_{N}}}(x_{N})$. Now take $n_{0}=\max\{n_{x_{1}},...,n_{x_{N}}\}$ so for any $n\geq n_{0}$ and any $y\in[a,b]$ we have some $y\in B_{\delta_{x_{k}}}(x_{k})$ and hence
\begin{align*}
|f_{n}(y)-f(y)|&=f(y)-f_{n}(y)\\
&=f(y)-f(x_{k})+f(x_{k})-f_{n_{x_{k}}}(x_{k})+f_{n_{x_{k}}}(x_{k})-f_{n_{x_{k}}}(x)+f_{n_{x_{k}}}(x)-f_{n}(y)\\
&\leq f(y)-f(x_{k})+f(x_{k})-f_{n_{x_{k}}}(x_{k})+f_{n_{x_{k}}}(x_{k})-f_{n_{x_{k}}}(y)\\
&<3\epsilon.
\end{align*}


Bootstrap4 grid system align cols to be close to each other

Question:

...

So in this width it looks well aligned

When i go slightly wide i see that the div's in the second row are not close to each other. Is there a way to align the cols in the last column to be close to each other (and aligned with column 2,3,4 of row 1)?

Here is a jsfiddle for the same.
Comment: Just added a jsfiddle.
Answer: Use col-auto instead of *col, because you use fixed width for the boxes so that they takes as much space as necessary. And use justify-content-center for the row to  align the columns in the center. Most importantly, use p-2 instead of m-2.

.box {
  width: 200px;
  height: 100px;
  background: lightblue;
}
<link href="http://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>

         hello

         hello

         hello

         hello

         hello

http://jsfiddle.net/6bx12u5w

You use an older version of Bootstrap. Better to use the latest one since there are a few new classes has been added.

Update
col takes all the available space while col-auto takes as much as space as it needs: it takes as much space as the natural width of it content.
Comment: What exactly is col-auto doing, as opposed to just col?
Answer: Here are a few different options for last row alignment.
Align last row to center
I see that you want the last row cols aligned under 2,3,4, so in this case you can simply use justify-content-center along with the col-auto columns. The col-auto uses flexbox shrink to make the column width fit the content.

                hello

                hello

        ..

                hello

                hello

https://www.codeply.com/go/iwL7PW77En

Align last row to left
Aligning the last row to the left is a flexbox issue that has been addressed before. If you don't mind having the entire layout not centered, just use col-auto to shrink the width of the columns to fit the boxes and justify-content-start.

                hello

                hello

        ....

https://codeply.com/go/LZkOF9zexh (align start)
If you need the entire layout centered, as you can see from the other answers there are various workarounds to align the last row left. IMO, the simplest, most reliable way in Bootstrap 4 is using a empty spacer elements at the end. You'll need 4 empty spacers since the max in any row is 5 cols.

            hello

            hello

            hello

    ...

            hello

https://codeply.com/go/F7pGyqIIT6 (spacers at end)


Nativescript Vue v-show with transition

Question: I am struggling with using of v-show with Nativescript. I was trying to make an animation described in https://www.nuvious.com/posts/nativescript-vue-transitions .
When using v-show the element does not really disappear from the screen.
Here is my code
<template>
    <Page actionBarHidden="true">
        <GridLayout>
            <transition name="bounce">
                <MainMenu v-show="menuOpen" class="mainMenu" @menu-closed="toogleMenu" />
            </transition>
            <StackLayout >
                <button text="Menu" @tap="toogleMenu" />

            </StackLayout>
        </GridLayout>
    </Page>
</template>

MainMenu.vue
<template>
    <AbsoluteLayout class="mainMenu">
        <StackLayout class="mainMenuItems">

            <button text="Close" @tap="closeMenu" />
        </StackLayout>
    </AbsoluteLayout >
</template>

As I understand, transition 'bounce' should be executed when v-if or v-show state of the inner element is changed. The problem is that area of the created menu is getting non-responsible, as another element is taking place here. This is obviously caused by z-index, but with v-show is should theoretically disappear from the view and have no effect from z-index.
It is especially interesting that with v-show I can click on the main screen and button from the hidden menu is triggered. The Menu button is getting blocked. In case of v-if, I can see only blocked Menu button.
Alternatively, if remove this z-index, I can see all the element of the StackLayout on the front layer. If I specify z-index of StackLayout, e.g. 2 (lower than the MainMenu), I am still getting an issue that this element is not fully removed from the screen.
The following libraries are used:

"@nativescript/core": "~8.5.0",
"@nativescript/theme": "~3.0.2",
"@nativescript/types": "^8.5.0",
"nativescript-vue": "~2.9.3"

Android API 26 (also tested with 29 and 30)
Could you please help with an idea how to deal with it and keep correct order of the layers? Obviously, z-index is not the most elegant solution.
Answer: Finally, it was found that use of Animate.css does not cause any problems that were met with a custom animation. Probably, so far it is the only solution.

Nativescript Vue v-show with transition


Why $\mathbb{Z}[\mu_6]$ is a PID?

Question: Let $\mu_6$ be the 6th unit root of $1$. Why $\mathbb{Z}[\mu_6]$ is PID?
I tried to prove it by the method proving $\mathbb{Z}[i]$ is a PID but failed.
Anyone can help?
Comment: Note that $\mathbb{Z}[\mu_6] = \mathbb{Z}[\mu_3]$. To prove that it's a PID, prove that it's a Euclidean domain by exhibiting a Euclidean norm function.
Comment: Hmm. IIRC the same method should work. Which step did you have problems with?
Comment: @JyrkiLahtonen. Yeah I see, I did not realize that $\mu_6^2=-\mu_6-1$..Now I'm clear.
Comment: @AlexB....I worked out. Thank you very much!
Answer: For every complex number $z$ there is at least one element $x\in\Bbb Z[\mu_6]$ such that $|z-x|<1$ (in fact the maximal necessary distance is $1/\sqrt3$, which is less than the maximal distance $1/\sqrt2$ for the Gaussian integers). This means that one can define a Euclidean division on $\Bbb Z[\mu_6]$ by rounding the exact quotient $z$ towards such an element $x$. It is an easy exercise to show the remainder is now less in (complex) absolute value than then the divisor in the Euclidean division, as it should. So $\Bbb Z[\mu_6]$ is norm-Euclidean, and therefore a PID. See Eisenstein integer for more details.

Why $\mathbb{Z}[\mu_6]$ is a PID?


Mean Absolute Error Cost Function in Logistic Regression

Question: Is there any reasons not to use MAE as cost function in logistic regression?
Yes, I know about problems with optimization, I know that this estimation won't be max-likelihood estimation.
But is there something else? Another pitfalls?
Answer: Here is how this could give unexpected results if you are using logistic regression for prediction. Suppose there is actually nothing to model, just a straightforward binomial distribution with $p=0.3$. We can predict anything between $0\leq\hat{p}\leq 1$. What will the expected MAE and MSE for various $\hat{p}$ look like? Let's simulate 1000 draws.
<code>set.seed(1)
gold.standard <- runif(1e3)<0.3
summary(gold.standard)

   Mode   FALSE    TRUE
logical     707     293

Prediction <- seq(0,1,by=0.01)
MAE <- sapply(Prediction, function(xx)mean(abs(xx-gold.standard)))
MSE <- sapply(Prediction, function(xx)mean((xx-gold.standard)^2))

plot(Prediction,MAE,ylim=range(c(MAE,MSE)),type="l",col="red",ylab="Error",lwd=2)
lines(Prediction,MSE,lwd=2)
legend("topleft",inset=.02,lwd=2,col=c("red","black"),legend=c("MAE","MSE"))
</code>

The expected MSE is minimized, as expected, by $\hat{p}=p$. (More precisely, by $\hat{p}=0.293$ because of our simulation.) But the expected MAE is minimized by $\hat{p}=0$, i.e., by always predicting the most common outcome, FALSE. This may be what you want, but it typically isn't. (And one would usually argue that if you want a classification prediction, then you should really aim at getting an unbiased $\hat{p}$, then base your classification on whether $\hat{p}$ exceeds a threshold that balances the cost of Type I and II errors - not bias $\hat{p}$ itself.)
The key thing you should keep in mind is that minimizing the MAE will bias your predictions towards the median of their distribution (whereas minimizing the MSE will asymptotically yield unbiased predictions: you'll get their expectation). See, e.g.,  Hanley et al., 2001, The American Statistician.
An analogous problem plagues forecasts of low volume count data - if you assess your forecast quality using the MAE, you'll get "optimal" forecasts that may be a flat zero. I have written a little paper on this (Kolassa, 2016, IJF) which may have some helpful pointers to further literature and in fact contains an analogue to the graph above.


Why does the point crash when free it?

Question: In the following code, the result is ok, but the code will be crash when executing finish, and increase one error: Heap corruption detected, the free list is damaged at 0x600000008f50
int *mergeSort(int *a,int count) {

    int leftCount  = count / 2;
    int rightCount = count - leftCount;
    int *leftData  = getData(a, 0, leftCount);
    int *rightData = getData(a, leftCount, count);

    int *sortedLeftData  = mergeSort(leftData, leftCount);
    int *sortedRightData = mergeSort(rightData, rightCount);

    int *resultData = mergeData(sortedLeftData, sortedRightData, leftCount,
                                rightCount);

    return resultData;
}

int *getData(int *a,int from, int to) {

    if (from > to) { return nil; }
    int *res = malloc(to - from + 1);
    for (int index = from; index < to; index ++) {

        int value = a[index];
        res[index-from] = value;
    }
    return res;
}

int *mergeData(int *a, int *b, int acount, int bcount) {

    int *result = malloc(acount + bcount);

    int aindex,bindex,rindex;
    aindex = bindex = rindex = 0;

    while (aindex < acount | bindex < bcount) {

        int value,avalue = INT_MAX,bvalue = INT_MAX;
        if (aindex < acount) { avalue = a[aindex]; }
        if (bindex < bcount) { bvalue = b[bindex]; }
        // get value from a point.
        if (avalue <= bvalue) {

            value = avalue;
            aindex ++;
        }else {
            // get value from b point.
            value = bvalue;
            bindex ++;
        }

        result[rindex] = value;
        rindex ++;
    }

    return result;
}

I don't understand why does crash when free the point, any answer will helpfull, thanks.
Answer: All of your allocations are too small, and thus you are overflowing your buffers.
The malloc function allocates the requested number of bytes.  You need to multiply the number of elements you require by sizeof(int) if your elements are int type.  e.g.
int *result = malloc((acount + bcount) * sizeof(int));

Other potential problems I spotted while reading your code are:

Using the bitwise-or operator instead of logical-or:
while (aindex < acount | bindex < bcount)
                    // ^ should be ||

You never free your temporary buffers, thus your program will blow out memory by leaking like crazy.  You must free leftData, rightData, sortedLeftData and sortedRightData in the mergeSort function after you are finished with them.
Note that merge sort actually does not require so much allocation.  Doing so will have a huge impact on performance.  An efficient implementation only requires a single additional buffer for scratch operations, which can be allocated at the beginning.
Comment: Thank you respond to this question as so detail, and it resolved my problem.

And I will think about how to use one single buffer to implementation merge sort,

thank you very much.
Comment: I'd implementation the merge sort use one buffer as following code.
Answer: I did implementation merge sort use single buffer, as the following code:
void mergeSort(int *a, int count) {

    int *tempBuffer = malloc(count * sizeof(int));
    mergeSortWithBuffer(a, 0, 0, count - 1,tempBuffer);
    free(tempBuffer);
}
void mergeSortWithBuffer(int *a, int leftStart, int rightStart, int end, int *tempBuffer) {

    int leftCount  = rightStart - leftStart;
    int rightCount = end - rightStart + 1;
    if (leftCount + rightCount <= 1) { return; }

    if (leftCount != 0) {

        // left dichotomy
        int lls = leftStart;
        int lrs = leftStart + leftCount/2;
        int lnd = rightStart - 1;
        mergeSortWithBuffer(a, lls, lrs, lnd,tempBuffer);
    }

    if (rightCount != 0) {

        // right dichotomy
        int rls = rightStart;
        int rrs = rightStart + rightCount/2;
        int rnd = end;
        mergeSortWithBuffer(a, rls, rrs, rnd,tempBuffer);
    }

    mergeData(a, leftStart, rightStart, end, tempBuffer);
}

void mergeData(int *a, int leftStart, int rightStart, int end,int *tempBuffer) {

    int leftCount  = rightStart - leftStart;
    int rightCount = end - rightStart + 1;

    int lindex,rindex;
    lindex = rindex = 0;

    while (lindex < leftCount || rindex < rightCount) {

        int lv = INT_MAX,rv = INT_MAX;
        if (lindex < leftCount) { lv = a[leftStart + lindex]; }
        if (rindex < rightCount) { rv = a[rightStart + rindex]; }

        if (lv <= rv) {

            tempBuffer[leftStart + lindex + rindex] = lv;
            lindex ++;
        }else {

            tempBuffer[leftStart + lindex + rindex] = rv;
            rindex ++;
        }
    }

    for (int index = 0; index < end - leftStart + 1; index ++) {

        a[leftStart + index] = tempBuffer[leftStart + index];
    }
}

I thought the mergeData function can replace data in the point a each other without the temp buffer, but the logic is too complex and the efficient is not fast, so i add the temp buffer in this function.
Would you have better suggestions if you have willing?

Why does the point crash when free it?


Fourier Transform of $\sin(\ln(t))u(t) $

Question: Can someone help me with the example of Fourier transform
$$\mathcal{F}[\sin(ln(t))u(t)](\omega)\ = \ \ ?$$
I know that there is a formula in the Table of Fourier Transform Pairs but it is only for $\sin(\omega_0 t)u(t)$, but how I deal with the natural logarithm inside the $\sin$ ?
yes sorry for my bad english is not my first language, thanks for the corrections
Answer: It is complicated. For any $a \in \mathbb{C}, Re(a) > -1$ we have the Laplace transform :  $$\mathcal{L}[e^{a \ln t} 1_{t > 0}](s) =\mathcal{L}[t^a 1_{t > 0}](s)=\int_0^\infty t^a e^{-st}dt = s^{-a-1}\int_0^\infty u^a e^{-u}du=s^{-a-1} \Gamma(a+1)$$ where for $s > 0$ I applied the change of variable $u = st$  and I extended to $s \in \mathbb{C}, Re(s) > 0$ by analytic continuation, and $\Gamma$ is the Gamma function.
Hence
$$\mathcal{L}[\sin(\ln t) 1_{t > 0}](s) =\mathcal{L}[\frac{e^{i \ln t}-e^{-i \ln t}}{2i} 1_{t > 0}](s)=\frac{s^{-i-1}\Gamma(1+i)-s^{i-1}\Gamma(1-i)}{2i} $$
and in the sense of distributions $$\mathcal{F}[\sin(\ln t) 1_{t > 0}](\omega)=\lim_{\sigma\to 0^+}\mathcal{L}[\sin(\ln t) 1_{t > 0}](\sigma+i\omega)$$ $$=p.v.\frac{(i\omega)^{-i-1}\Gamma(1+i)-(i\omega)^{i-1}\Gamma(1-i)}{2i}$$
where $p.v.$ is the principal value


I'm tonedeaf. If I sing to my baby, will I damage his/her musical ear?

Question: I'm amusical - I cannot discriminate between higher and lower pitch even when there is a large difference between them.  I want my child to develop musical abilities. I know that an out-of-tune piano can affect the development of absolute pitch recognition, would a parent who sings out-of-tune have the same effect? I find it difficult to get the tune right even for simple nursery rhymes such as twinkle twinkle little star.
Comment: I have no idea. However you can of course play music in the background while spending time with your child - or do you have spouse/family who would enjoy singing?
Comment: OMG horrors!  You must hire a quartet from the Metropolitan Opera RIGHT NOW!  <-- and of course I'm kidding.  Your poor tonal quality will have absolutely no effect.  Once the child reaches speech age (I'm guessing right now you're talking about a very small kid), he/she can learn to play some simple instrument, or follow along with singers on radio/TV and you'll be off the hook.
Comment: Likely poor singing will have a slight negative or neutral effect on their musical ability, but there are other more important considerations.  Giving a child attention and speaking/singing to them is instrumental in early development.  I'm not sure that we're the best site for these concerns.
Comment: Ask _your_ parents.
Comment: I guess we are talking about the first months as a baby, not early childhood, right?
Comment: I'd think consistently intoning the wrong pitch would be worse than singing all kinds of different pitches. When your child reaches a rebellious age, they'll learn perfect pitch to make you feel bad. Then when they love you again, assuming they do, they'll learn xenharmonics to 'prove' your singing a bridge to a better world. Sing your heart out :) Besides, to really teach them good pitch, you'd play only just intonation for them.
Comment: First of all, the "absolute pitch recognition" is not a real parameter of a true musical ability. Second: no matter how do you sing, the most important thing for your baby is to involve him/her in any kind of musical activity (melodic and rhythmic) as a part of a funny game. So, please, don't stop to sing, either with wrong notes!
Comment: If carrying a tune is not your strength, then why not just Shatner it? Speaking words like they actually mean something may actually be more useful for development than trying to match some arbitrary notes.
Comment: You can have a hearing impairment, but being tone deaf is a myth promulgated by subpar teachers who don't want to put the effort in by teaching pupils who struggle. It is like the Suzuki teacher trainer once told my mother. A teacher is just as much defined by the pupils that struggle than those which excel.
Answer: Unlikely, because unless your child has a genetic reason for being unable to distinguish pitches (which you apparently may, if what you say is true), he or she will soon learn to identify the inaccuracies in your singing.
For example, there has been some noise about bilingual families and a fear that the non-native parent will "infect" the child with bad grammar, but it turns out the children tend to learn quickly and can soon tell that one parent speaks incorrectly sometimes. Eventually non-family sources of language will dominate anyways.
To that note, if you play any recorded music or movies/television, every note in that music will be rigorously tuned to its exact pitch. So there will be plenty of chances to hear properly tuned music if you live in a typical household. I wouldn't really worry about damaging your child's hearing skills at all. But why not do some activities with a pitched instrument such as a piano, or take your child to musical activities? If you're concerned, just make sure you spend time listening to recorded music at home.
Comment: I'm seeing a fairly worrying pattern lately, where people assume that learning language and learning music happens through the same processes. We are born with an *instinct* to learn language, unlike music, which is something humans invented relatively recently, and is learned through entirely different means and processes. While your analogy may sound logical, it is not necessarily correct.
Comment: @LeeWhite I disagree with your though about music being "invented recently".  Written music extends almost as far back as written language, and anthropologists have pretty good ideas about how music was used for communication.  Music conveys concepts and meanings - is that not the function of language?
Comment: @LeeWhite  I disagree with your claim about instinctual learning. For one thing,  the distinction between 'music' and 'language' is largely cultural.  Look at how "sing-songy" us Westerners consider some Far Eastern languages.  And I'd like to see a citation that we 'inherited' language from any other species.
Comment: There is no guarantee that recorded music will play back at exactly the right pitch. Even if it was rigorously controlled at every point in production, playback is entirely dependent on the playback device. (Granted, the amount of variance which is likely or possible to introduce is probably small, but a blanket "It's exact" cannot be guaranteed at all.)
Comment: @CarlWitthoft: Tone has importance in most languages, but it never involves exact pitching. Think of the way we ask questions in English: we raise the tone towards the end of the question to give it intonation. Although this involves a certain degree of relative pitching, it is not related to the ability to recognize and produce correct pitching. You will notice that even people who are completely tone-deaf can make a question sound like a question without even thinking about it. In other languages (such as Mandarin and Swedish) this is more prominent, but based on the same principle.
Comment: @LeeWhite actually it might be a bit of both (instinctual and/or deliberate) so the answer is not necessarily entirely wrong
http://tip.duke.edu/node/658
Comment: @jjmusicnotes: "relatively" is a key word there. The bottom line is that music is an invention by humans, while language is a skill we inherited from the species before us, and have continued developing throughout millions of years. Unlike communication, music is not something we require in order to survive, which is why we never developed an instinct for it.
Comment: I am going to stop posting here though, because this is not what comments are for. Instead, I will post a new question where an expect can give their black-on-white input, instead of my own "I had to study this long ago, but I don't remember what the sources were" kind of input.
Comment: Disagree with the 'bad grammar' assumption. I were learned by my parents who could talk proper. Seriously, most kids will speak as their parents do, good or bad! But this discussion is going off at too much of a tangent.
Comment: @LeeWhite [A recent related discussion](http://linguistics.stackexchange.com/questions/10004/is-music-a-language)
Comment: @LeeWhite I think perhaps you need to revisit your understanding of cultural, musical, evolutionary, and biological history. I am supposing your expertise are derived from classes you're currently taking, and haven't had the luxury of accumulating enough life experience to eventually forget them?  Save discussion for the chat.
Comment: @LeeWhite actually, music predates _Homo sapiens sapiens_. We have found instruments used by older hominids. See, for example, [here](http://en.wikipedia.org/wiki/Evolutionary_musicology#The_origin_of_music). Music is about as old as we are.
Comment: FYI, an NTSC encoded DVD (or VHS tape if you are still able to play such a thing) will usually have the music played back slightly slower and therefore slightly flat because of the slight slowing of the original film and 3:2 pulldown process used to telecine the film to video.
Answer: You should pay attention to your singing.
Tone-deafness is a result of a disconnection between what are you hear and what you produce. It is generally fixable through conscious attention.
I work developing musical training computer games for children.
My mother sang to me as a child, and she is tone-deaf. I also learned to sing in a tone deaf manner. We learn by copying.
I subsequently spent thousands of hours playing the piano, but my early training (basically to NOT pay attention to the sounds I am making) retarded my musical development. That caused me much suffering.
It was only in my 30s that I trained myself consciously to sing correctly, it has been hard work. I taught myself to sing accurately using a solfege system.
I fixed such things as gradual pitch drift, incorrect intervals such as getting a fourth, fifth, octave muddled up, squashed thirds.
It is a blessing for your child that you are conscious enough to enquire.
You should find your child a teacher, who can teach them to sing. This should be the first instrument everyone learns upon, it is our natural inbuilt instrument. To try and bypass it is stupid. Chopin said "If you wish to play, you must first learn to sing."
If your child has a good teacher, you don't need to worry about damaging their musicality. (Note: It is difficult to find a good music teacher. And a bad one will do more harm than good. So choose carefully!)
If the child doesn't, you do. Even by abstaining from singing, your child will learn to perceive the world as you do by a million subtle cues. The way you use words, the way your eyes will move, the way your physical form follows conscious intent. And the set of conditions that led to your own disconnection may well be transferred to the child. Maybe you are primarily a visual person, this is your primary perception and the root of your attention. It's quite easy to see if someone is primarily a visual person. The renowned 19th century music teacher Evelyn Fletcher Copp (the first teacher to systematically impart Absolute Pitch to her child students) said that when a parent brought a prospective new student to see her, she would look closely and ascertain how the child primarily perceives the world (visual, auditory, kinaesthetic, logical, emotional, etc).
It's worth remembering that these balances can be adjusted. Imbalance can show proclivity which is to be encouraged. But at the same time weaknesses should be addressed.
If someone is strongly primarily visual, maybe practising music in a pitch dark room would encourage them to rebalance.
PS Someone commented earlier that music is unlike language, it is something artificial. This is an ignorant statement. It has been demonstrated to be an intrinsic component of spoken language. Diana Deutsch (a world-famous researcher of Absolute Pitch) demonstrated (in a public lecture) the presence of the diatonic scale in spoken language, by time-stretching and looping short phrases of spoken word. We use this scale to communicate (subliminally for most of us) at an emotional level.
Comment: And there is, I believe, a whistling language in the Canaries, probably instigated as it carries better than the voice.
Answer: It may be, genetically, that your child has inherited your amusicality. You won't know for a while. In fact, if only you listen to it, then you'll never know! Children tend to believe that their parents are inscrutable, so your out of tune singing may be acceptable as the right way to your child. This will then oppose renditions by others, giving a bit of a dilemma. I say far better to not try to sing to your child - there are multiple other better ways to communicate.  If, for instance, you weren't good at spelling, when your child has to learn words for a test, would you spell badly whilst trying to help?
Comment: I'm highly skeptical of these claims as well.  There are too many sources of "good tone" available for a child to be biased by a parent's off-key humming.
Answer: It occurs to me in reading all the answers posted so far (by well meaning members of the community offering what they perceive to be useful advice) that the ONLY answer that seems correct is: We don't actually know how singing dissonant off pitch musical phrases to an infant during the very early stages of language development might affect their future ability to recognize or reproduce what we consider the proper notes within a particular key.
I don't know if there have been any scientific studies on this.  But I do know, that science has proved that language development and word recognition comes at a very early age and begins before the development of the ability to reproduce the words that are recognized.
And we know that learning multiple languages is much easier for younger children and the ability to learn new languages diminishes as we get older.  I actually have a relative who speaks both Russian and English with equal aplomb at the age of two, because her mother speaks Russian and English to her.  If I tried to learn to speak Russian, it would take years of intense study before I could even develop the vocabulary of this two year old.
So unless someone can cite some scientific evidence to support either a yes or a no, I feel it may be misleading to answer either way.
The safest thing to do in my opinion would be to both sing to your child (a mother's voice is "music to a child's ears"), but also play recorded music for your child - just to be on the safe side.
Answer: I think a very safe answer is that interacting with your child is much more  important than worrying about unknown risks linked to parental tone deafness.
Give and take, have a conversation, sing, smile, dance to the beat of music, and don't hold back - add rich emotional dynamics with your face while you interact with your child.  Make sure the musical experience positive even if you are only playing a drum.  Try a peek-a-boo style game to get your child to guess the key you hit on a xylophone and take turns.
If (certainly an if) a musical developmental window exists, then the only sure fire way to miss it would be through absence.
Comment: Agreed.  As I said - a mothers voice is music to her child's ears.
Answer: I have multiple music degrees that involve child development and education. Yes, your tonedeaf singing will cause the baby to be tone deaf. There are tons of research studies from the Suzuki "Mother tongue" method. The baby becomes what the parents are or what the baby is exposed to.
High quality music that is in tune will benefit the baby more than family that sings out of tune.
Comment: Welcome to Stack Exchange! Do you have any sources or evidence for that claim, or could you offer an explanation of why this is the case?
Comment: I have also heard this. Please point to a study or two.
Answer: Don't worry, if the child has the skill, he/she will soon be able to tell the difference between your singing and a perfect tune singing.
In addition to that, establishing an emotional communication with your child is more important than anything else. Rather than blocking yourself from singing, provide access to good quality music besides that. So that you don't prevent your child establishing emotional communication skills which may be very beneficial if he/she develops interest in any creative process in the future.
Just keep an easy and natural access to hearing and playing music around and don't force anything, that would be sufficient. Proper education is something you should think of later according to his/her capabilities. (I assume we are talking about the first few months).
Again no worries, in time it will learn many things that you are not capable of.
Comment: This answer is to me off-key.  It makes questionable assumptions (tone-deafness/AP are genetic), seems to be entirely opinion based, and skirts the issue instead offering general parenting advice.
Comment: @Pi sorry, I wrote that section right after this answer (http://music.stackexchange.com/a/29042/17019) so the context is lost after here become more crowded. Actually it was a reply to a generalization in that answer. So it should have been a comment there actually. Editign accordingly.
Answer: what about tone and pitch?
I am fully bilingual in Mandarin and English. I sing pentatonic traditional chinese music as well as Italian arias. I can't say that I can detect middle eastern or indian music to be out of tune. I think they have smaller intervals than us and very very small range.
Linguists will say that language acquisition works best prior to age 11. After that, you probably have a very hard time speaking Chinese the way I do. (I spent 11 yrs in Taiwan and 30 yrs in US). I am a little different. My English is without accent and my Spanish is overwhelmingly convincing for an asian person. When I hear a 'foreigner' speak Chinese, their intonation is horrible.  We can understand it when they speak a full sentence, but when speaking short phrases it can be embarrassingly incomprehensible for both speaker and listener.
It is quite obvious that tone is culture/immersion thing and is trained at early pre-pubescent age....
(Sorry I am probably mixing 3 discussions thread into one)
Like the story of Jane (movie with Jodie Foster), who grew up in isolation with her mother who suffered from brain damage that impaired her speaking ability, one probably should be wary of what they want to expose their very impressionable child to....
Comment: I'm not sure how your background and the information about language acquisition (as interesting as it may be) help to answer this question. Please do not "mix thread discussion" in answers here. It is preferred that you write a separate answer for each question. If you would like to add some related information that is not an answer to a question, please leave a comment instead.
Comment: The inflections are very subtle in Mandarin. In order to speak that perfectly, you need to be in full immersion at young age. One slight inflections off, you are speaking a completely different word. I am simply using that as a parallel in this scenario.  My older child sings in pitch, but when their teacher starts singing happy birthday all over the place, I feel that the entire student body follows her lead and do not hit the right notes.  I think the original poster poses a great question and is very conscientious of her kids learning.


Rails submit_tag form validation

Question: In my view I have:
event.html.erb

            <%= form_tag(register_learner_path, {remote: true}) do -%>

              <%= label_tag :email %>
              <%= text_field_tag :email %>

              <%= label_tag "First Name" %>
              <%= text_field_tag :first_name %>

              <%= label_tag "Last Name" %>
              <%= text_field_tag :last_name %>

              <%= hidden_field_tag 'event_id', @event.id %>

              <%= submit_tag "Register for this event", id: 'register_button', :onclick => "return validateform();" %>
                  Enter your name and email above and the link will be magically revealed

            <%- end -%>

...and my coffeescript is:
events.js.coffee
jQuery ->
    if $('div').hasClass 'form-group registration_form'
        $(".location").hide()
        $(".location-section-link").hide()
        $(".submit_register").click ->
            validateForm()
            if validateEmail($("#email").val()) == false
                alert('Please enter a valid email address')
                return false
            else
                $(".location").show()
                $(".location-section-link").show()
                $(".registration_form").hide()

    #validate email
    validateEmail = (email) ->
      re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
      re.test email

    #validate email, first name and last name
    validateForm = ->
        if $("#email").val() == '' || $("#first_name").val() == '' || $("#last_name").val() == ''
                alert('Please enter first name, last name, and email')
                return false

Essentially I am trying to accomplish two validations here. One I want to ensure no empty strings in email, first name and last name. Second, I want to verify a 'valid' email based on the regex in the js.
The behavior I am seeing with this code is that both the validations are running, however I only want the email validation to run IF the other validation (test of empty strings) passes.
Comment: `$('div').hasClass 'form-group registration_form'` is just plain weird. You select every `div` on the page and then filter them, thats horrible for performance. Use `$group = $('.form-group.registration_form')` `if $group.length`
Comment: @papirtiger Just to sanidty check https://gist.github.com/marklocklear/5f2b61f2d3b66441824a
Comment: Better. Also [`submit_tag`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-submit_tag) creates a ``  element which does not have content, it only has a value attribute which specifies the text, what you want is [`button_tag`](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-button_tag). And get rid of the onclick attribute while you are at it.
Comment: Ah sorry ignore that last comment, I was just thrown off by the code indentation.
Comment: `if !validateForm() return false`?
Answer: So this feels a little busy, but it works. Feel free to make suggestions...
jQuery ->
    $group = $('.form-group.registration_form')
    if $group.length
        $(".location").hide()
        $(".location-section-link").hide()
        $(".submit_register").click ->
            if validateForm() == false
                return false
            else if validateEmail($("#email").val()) == false
                alert('Please enter a valid email address')
                return false
            else
                $(".location").show()
                $(".location-section-link").show()
                $(".registration_form").hide()

    #validate email
    validateEmail = (email) ->
      re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
      re.test email

    #validate email, first name and last name
    validateForm = ->
        if $("#email").val() == '' || $("#first_name").val() == '' || $("#last_name").val() == ''
                alert('Please enter first name, last name, and email')
                return false

Comment: What if you moved the email alert to the email function, and did this `if !validateForm || !validateEmail($('#email').val()) return false` it validates in order, so if `validateForm` returns `false`, it becomes true and `validateEmail` is not run, and we return `false`, causing the form to not submit. if `vForm` is `true`, it becomes `false` and `vEmail` is checked, if both return `true` and are flipped, the `return false` is not executed and the form continues normally.

Rails submit_tag form validation


Javascript check search term against array and return value

Question: Firstly I'm grabbing the search term the user has entered and storing in in the variable 'searchWord' Then defining an array of retailers and setting the length of this array in the variable 'subStringLength'. Now i run w while loop that checks for any of the words in my 'searchWord' and if it finds a match it returns true. The problem is indexOf() only returns a number or boolean. How would I adapt this code so if it matches any of the words with 'searchWord', if returns the value of the word it has matched. I can then take that word and match if with an object key which is used to store voucher codes for that retailer? Any help appreciated, heres how I am doing it so far:
const searchWord = $('.form-control').val();
const searchRetailers =['Debenhams','debenhams', 'Argos', 'argos', 'Currys', 'currys', 'PC World', 'Pc World', 'pc World', 'pc world', 'John Lewis', 'john Lewis', 'john lewis','eBay', 'Ebay', 'ebay', 'Amazon', 'amazon'];
let subStringLength = searchRetailers.length;

while(subStringLength--) {
    if (searchWord.indexOf(searchRetailers[subStringLength])!=-1) {
         // show popup 1
    }else {
        // show popup 2
    }
}

Comment: Can you post an example of what `searchWord` could be!
Comment: so search word could be "Argos television" or "cheap debenhams scarf"
Answer:
How would I adapt this code so if it matches any of the words with
  'searchWord', if returns the value of the word it has matched.

It would be reasonable to stop traversal when matched value found:
...
var matched = '';
while (subStringLength--) {
    if (searchWord.indexOf(searchRetailers[subStringLength]) !== -1) {
         matched = searchRetailers[subStringLength]; // <-- capturing matched word
         break;
    }
}

Another approach is using Array.prototype.some() function:
...
var matched,
    hasMatches = searchRetailers.some(function(w){
         var m = searchWord.indexOf(w) !== -1;
         if (m) matched = w; // <-- capturing matched word
         return m;
    }, matched);

 if (hasMatches) {
    // show popup 1
 } else {
    // show popup 2
 }

Answer: I don't recommend this type of searching because it can usually be handled better by a database which is designed to index/search values like this, however, I'm giving you some rough code, but essentially you can do something like this:
const searchWord = $('.form-control').val();
const searchRetailers =['Debenhams','debenhams', 'Argos', 'argos', 'Currys', 'currys', 'PC World', 'Pc World', 'pc World', 'pc world', 'John Lewis', 'john Lewis', 'john lewis','eBay', 'Ebay', 'ebay', 'Amazon', 'amazon'];

function search(searchWord) {
    searchWord = searchWord.toLowerCase();
    let results = [];
    searchRetailers.forEach(function(el){
        if(el.toLowerCase().indexOf(searchWord) != -1)
            results.push(el);
    });
    return results;
}

let matches = search(searchWord);
//Do stuff with matches

Answer: Thanks for everyone's answers. I ended up going with the following way as then i didn't need an array and an object storing the code for the retailers, i've used regex to match with the object key value. This way seems to be more efficient than using indexOf() which seemed fairly slow.
const searchRetailersCode = {
    'debenhams': {
        'code': 'YH99'
    },
    'argos': {
        'code': 'HOME25'
    },
    'currys': {
        'code': '123456'
    },
    'pc world': {
        'code': '123456'
    },
    'john lewis': {
        'code': '123456'
    },
    'ebay': {
        'code': '123456'
    },
    'amazon': {
        'code': '123456'
    },
};

const searchWord = $('.form-control').val();

let regexp = new RegExp('(' + Object.keys(searchRetailersCode).join('|') + ')', 'i');
let matches = regexp.exec(searchWord);

if (matches != null && matches.length > 1) {
    let retailer = matches[1].toLowerCase();
    let discountCode = searchRetailersCode[retailer].code;
}