how tell to a function to wait the end of animation of another function

Question: I have two functions here say animation1 and load1 they work like that:
function animation1() {
    element.animate({width(size)});
}

and
function load1() {
    element.find('img').after(newImg)
}

there's a click event who fires both, but how can I tell to load1 to wait until animation 1 has finished the animation and then add the newImg element? I know I can callback load1 into animate() of animation1, but I've separate one from another because I'm reusing animation1 in a lot of places. What happens now is that both are fired together, and it's not nice to the eyes.
thank you
d.
Comment: In `element.animate({width(size)});`, you're **calling** a `width` function, passing in a `size` argument, and then trying to put its return value inside `{}` as a parameter to `animate`. I'm fairly sure that's a syntax error, did you mean `element.animate({width: size});`?
Comment: sure, it's just a quick example. I'm trying to tell to Load1 to wait until animation1 has finished his animation, do his .after method. This in the case that both are fired togheter.
Answer: Two options:
Use a callback
I know you've said

I know I can callback load1 into animate() of animation1, but I've separate one from another because I'm reusing animation1 in a lot of places.

...but a callback really is the best way to do this. In the places where you don't need a callback, just don't pass one to animation1.
Modify animation1 to accept a callback, which it passes to the animate function, which accepts a "completion" callback it fires when the animation is complete:
function animation1(callback) {
    // See also my comment on the question regarding `{width(size)}`
    element.animate({width: size}, callback);
}

...and then your click would pass in a reference to load1 to animation1 rather than calling it directly, like this:
function clickHandler() {
    animation1(load1);
}

See the animate docs for details of the completion function.
Use a timer
If you tell animation1 exactly how long to take, you could use setTimeout to delay your call to load1:
function animation1(duration) {
    // See also my comment on the question regarding `{width(size)}`
    element.animate({width: size}, duration);
}

...and then your click would pass in a duration to animation1 and use setTimeout to delay calling load by the same amount:
function clickHandler() {
    animation1(400);
    setTimeout(load1, 400);
}

Of the two, I'd definitely go for the callback rather than the setTimeout barring some other design constraint.
Comment: after reading all your suggestions I think that using a callback it's the best way to achieve this. Thanks everybody!

d.
Answer: You are "using animation1 in lots of places" but you want it to behave differently in terms of the funciton flow? Souds like you need a separate function animation2 which can include the callback. Reuse is an excellent idea in general, but you are actually doing something different here, because you are animating AND THEN something.
Comment: maybe this could be the case. Thank you.
Answer: jQuery's animate function has a callback function that you can use for this. You can use it in various different ways. The easiest for the example you've given is probably to use a global variable:
var isAnimating = false;

function animation1(){
  isAnimating = true;
  element.animate({width(size)}, function(){ isAnimating=false; });
}

function load1(){
  if(isAnimating){
    load1(); // call again
  }
  else {
    element.find('img').after(newImg);
  }
}

However this isn't very efficient - load1() will keep running in a perpetual loop until isAnimating is false. A better option is therefore to use the callback to actually call load1...
function animate1(){
  element.animate({width(size)}, function() { load1(); });
}

function load1(){
  element.find('img').after(newImg);
}

This can be expanded incase you need to call different functions for each...
function animate1(callback){
  element.animate({width(size)}, function() {
    var fn = window[callback];
    if(typeof fn === 'function') {
      fn();
    }
  });
}


Eight objects into distinct bins (number per bin and circular order matters)

Question: Problem
I have eight objects {a,b,c,d,e,f,g,h} that I wish to place into some number of bins, such that:

every bin has at least two objects
all the objects are in a bin

Furthermore, within each bin, the order of the objects matters e.g. {a,b,c} and {a,c,b} are two different assignments. However, circular permutations are not distinct, e.g. {a,b,c} and {c,a,b} should be considered one assignment.
How many ways may this be done?
My reasoning so far
First off I want to say I'm approaching this in a naive way with only a little knowledge of combinatorics.
There are 7 possible groups of bins (i.e. 4 bins of two, 1 bin of eight etc.):
[2,2,2,2], [2,2,4], [2,3,3], [2,6], [4,4], [5,3], and [8] in this notation I just made up.
Starting from the largest bin in each group, there are $8 \choose k$ ways to select the objects to go inside the bin, where $k$ is the size of the bin.  There are additionally $(k-1)!$ ways to arrange the objects such that circular permutations are correctly treated.
This process is repeated for the remaining bins using ${{8- \sum_{i=1}^{j-1} k_{i}} \choose k_j} (k_j-1)!$, where $k_j$ is the size of the $j^{th}$ bin. All of the numbers are multiplied together to get the total number of assignments for each group. Symbolically,
$$ \prod_{m=1}^n  {{8- \sum_{i=1}^{j-1} k_{m,i}} \choose k_{m,j}} (k_{m,j} - 1)! $$
where $n$ is the number of bins in a particular group.
After doing the computations and summed across all the groups I came up with 20,888 different ways to solve the task. Have I done this correctly? I've started to second guess myself.
Thank you
Edit: Thinking about it some more I believe I also need to divide by the multiplicities in each group of bins.
Comment: Are the bins distinguishable?  If so, then [2,6] and [6,2] are different and you have undercounted.  If not, then e.g. [2,2,2,2] you would need to divide by $4!$ just to permute the bins themselves.
Comment: The bins are not distinguisable...  in that case, do you realize you are calculating the number of [derangements](https://en.wikipedia.org/wiki/Derangement) of size $8$?  Your answer should be $14833$ according to [OEIS](https://oeis.org/A000166)
Comment: They are not distinguishable. Thanks for the feedback.
Answer: As stated by the commenter my solution is simply the number of derangements of size 8, which is 14833. This corresponds with the result I obtained from applying my formula naively. Thanks, I learned something new from this problem.


Post multiple images using SLComposeViewController on Facebook/ Twitter?

Question: I am an iOS developer and I am currently using SLComposeViewController to share a post on Facebook/Twitter. My issue is that I have to post multiple images in a single post.
I have done this as follows:
<code>SLComposeViewController* mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
[mySLComposerSheet setInitialText:textTobeShared];
mySLComposerSheet addURL:[NSURL URLWithString:@"http://click-labs.com/"]];
for(int count=0;count<imageArray.count;count++)
        if([mySLComposerSheet addImage:[UIImage imageWithData:[imageArray objectAtIndex:count]]])
</code>
In the above code, imageArray is the array of images that I want to post.
When I am doing this on Facebook, all the images are posted as a separate post.
While in case of Twitter, addImage method returns true only for the first images while in case of other images it returns false. So only one image is posted.
So I want to know how to achieve my goal and is it possible to post multiple images in  a single tweet.
Comment: @girish_vr check this Twitter blog post. It should be already possible. https://blog.twitter.com/2014/photos-just-got-more-social
Comment: In twitter you can only post one image per tweet. There is no such thing as an album in twitter.
Comment: are you sure there is no way to achieve this in twitter. Is there any documentation regarding this issue available.
Comment: If you are a twitter user then you will know this. Each tweet(post in other term) will have a single picture associated to it.
Comment: Actually I am new to twitter so I have no idea about it.
Answer: I think you need to create an album first.
Here's a link to the facebook album API documentation.
<code>- (void)shareToFacebook {
if (FBSession.activeSession.isOpen) {
    NSLog(@"SESSION IS OPEN");

    [self createFacebookAlbum];
} else {
    NSLog(@"SESSION IS NOT OPEN");
    NSArray* permissions = [NSArray arrayWithObject:@"email"];
    [FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
        [self sessionStateChanged:session state:state error:error];

        if (error) {
            /* handle failure */
            NSLog(@"error:%@, %@", error, [error localizedDescription]);
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There was a problem with your Facebook permissions." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alert show];
        }
        else if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed ) {
            [FBSession.activeSession closeAndClearTokenInformation];
        }
        else if (state == FBSessionStateOpenTokenExtended || state == FBSessionStateOpen) {
            if(!self.presentedFacebookSheet) {
                [self performSelector:@selector(reauthorizeAndContinuePostToFacebook) withObject:nil afterDelay:0.5];
                self.presentedFacebookSheet = YES;
            }
        }
        }];
    }
}

- (void)reauthorizeAndContinuePostToFacebook {
    NSArray *permissions = [NSArray arrayWithObjects:@"publish_actions", nil];

    [[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
        [self shareToFacebook];
    }];
}

- (void)createFacebookAlbum {
    NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"Test name" forKey:@"name"];
    [parameters setObject:@"Test message" forKey:@"message"];

    FBRequest* request = [FBRequest requestWithGraphPath:@"me/albums" parameters:parameters HTTPMethod:@"POST"];

    NSLog(@"creating facebook album");
    FBRequestConnection *connection = [[FBRequestConnection alloc] init];
    [connection addRequest:request
         completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
             if (!error) {
                 NSString* albumId = [result objectForKey:@"id"];
                 NSLog(@"OK %@", albumId);
             }
             else {
                 NSLog(@"Error: %@",error.userInfo);
             }
         }];
    [connection start];
}

- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error {
    switch (state) {
        case FBSessionStateOpen:
        {
            [[FBRequest requestForMe] startWithCompletionHandler:
             ^(FBRequestConnection *connection,
               NSDictionary<FBGraphUser> *user,
               NSError *error) {
                 if (error) {
                     //error
                 }
                 else {
                     NSLog(@"User session found");
                 }
             }];
        }
            break;
        case FBSessionStateClosed:
        case FBSessionStateClosedLoginFailed:
            [FBSession.activeSession closeAndClearTokenInformation];
            break;
        default:
            break;
    }
}
</code>
Comment: Is it not possible using SLComposeViewController to do the same thing
Comment: Funny, in this post the problem/requirement is totally opposite.  http://stackoverflow.com/questions/14514179/facebook-ios6-integration-adds-image-to-album-and-not-separate-posts
Comment: Yes, I have just now seen the question. But it is in the case of single image post.


Need SQL query (MS) to indicate status transition time

Question: I'm pretty crafty with T-SQL but I haven't delved into spans and partitions, and I suspect something like is needed.  I have a table with two columns, datetime and status, with status being "ON" or "OFF".  I'm looking for a query that will give me a resultset of when a transition from OFF to ON or ON to OFF happened.
To clarify, I have a process reporting the status of an external object every (interval) so there will be multiples of ON status' followed by multiples of OFF status' - I am interested in just the transitions.
Optionally, the time delta between the last transition and this one (e.g., how long has it been "OFF" before it transitioned to "ON").
I do not see any way of doing this without a cursor.
Thank you in advance!
Comment: What version of SQL? 2012 has support for LEAD and LAG operators, which should work.
Comment: 2012, so I will be looking up the two operators.  Thank you!
Comment: The LAG operator did it for me.  If anyone is interested in the SQL, I'll happily post it.  @ken I cannot mark your comment as an answer - if you post it again as an answer I'll tag it.
Comment: congrats, nice that it worked!
Answer: What version of SQL? 2012 has support for LEAD and LAG operators, which should work.
<code>SELECT LAG(field) over([partition by field[,field]] order by field[,field])
</code>


Converting expression markings to "music character style" in Sibelius

Question: I have a fairly long piece with a fair few dynamic markings, but I've only just realised that you can get the traditional dynamic font ("music character style") by holding down Cmd (I'm on Mac) before typing "mf"/"mp" etc.
Is there a fast way to retrospectively change this rather than deleting and re-entering dozens of dynamic markings? I tried using the Inspector but no luck.
Answer: Figured it out: the font is "Opus Text Std" in the Inspector after using Shift + Alt + D to select all expression markings and hairpins.
Answer: Use the plugin Change Dynamics.    It's very well explained here.
https://www.rpmseattle.com/of_note/enter-and-edit-dynamics-as-music-text-characters-in-sibelius/
You suggested: "Figured it out: the font is "Opus Text Std" in the Inspector after using Shift + Alt + D to select all expression markings and hairpins."
That won't quite do it right.
Comment: What is "that", and why won't it quite work? And how does one fix it once the link goes dead?
Comment: @LaurencePayne Is this best served as a comment to that answer, then?
Comment: 'That' is the solution mentioned in the OP's reply  - "Figured it out: the font is "Opus Text Std" in the Inspector after using Shift + Alt + D to select all expression markings and hairpins."   In the unlikely event of the link to 'Of Note' dying, revert to my basic answer 'Use the plugin Change Dynamics'.   I'll clarify my answer.  Thanks.
Comment: No.  Because it's primarily an answer.  Perhaps I should reverse its two halves.
Comment: Can you explain why my solution won't do it right? Looks fine to me.


Prove transitivity of relation (defined by  if the arithmetic mean of  and  equals the geometric mean of  and ) on positive real numbers

Question: A relation $$ is defined on the set $\mathbb{R}^{+}$ of positive real numbers by $$ if the arithmetic mean of $x$ and $y$ equals the
geometric mean of $$ and $$, that is, if
$$\frac{1}{2} \cdot ( + ) = \sqrt{xy}$$
In order to prove $R$ is an equivalence equation I proved that $R$ is reflexive and symmetric but I am having trouble proving it being transitive.
I supposed $x,y,z \in \mathbb{R}^{+}$ such that $xRy$ and $yRz$ and got two equations
$$
\begin{cases}
\frac{1}{2}(x+y)=\sqrt{xy} \\
\frac{1}{2}(y+z)=\sqrt{yz} \\
\end{cases}
$$
but I am struggling to reach $\frac{1}{2}( + z) = \sqrt{z}$, I tried multiplying $\sqrt{z}$ and $\sqrt{x}$ to both side of each equations and substituting but I can't seem to eliminate $y$.
Comment: $R$ is actually, "$=$", the equality. For starters, show that $x+y-2\sqrt{xy}$ is a complete square.
Answer: Think about what the relation actually means. Can you find a nontrivial example of two numbers whose arithmetic and geometric means match?
It turns out that the relation isn't actually all that interesting: it's just regular equality. To see this, choose any $x, y > 0$ and observe that:
\begin{align*}
\frac{x + y}{2} = \sqrt{xy}
&\iff x + y = 2\sqrt{xy} \\
&\iff (x + y)^2 = (2\sqrt{xy})^2 \\
&\iff x^2 + 2xy + y^2 = 4xy \\
&\iff x^2 - 2xy + y^2 = 0 \\
&\iff (x - y)^2 = 0 \\
&\iff x - y = 0 \\
&\iff x = y
\end{align*}
So the given relation is transitive because equality is transitive.
Comment: Thank you, these things really make me feel like an idiot


Solve the functional equation $f(xf(y)+yf(x))=yf(x)+xf(y)$

Question: Let $f:\mathbb{R}\to \mathbb{R}$ and such for any real numbers $x,y$ we have
 $$f(xf(y)+yf(x))=yf(x)+xf(y)$$
Find $f(x)$.
I have let $x=y=0$ have
$$f(0)=2f(0)\Longrightarrow f(0)=0$$
and I guess the solution is $f(x)=x$ or $f(x)=0$, but I can't prove it.
Comment: If you let $x=y=0$, you should get immediately $f(0)=0$ instead of $f(0)=2f(0)$.
Comment: This might help. Let $g(x)=f(x)/x$ and then put $y=1/x$
Comment: Where does the question come from?
Comment: $f(x)=x$ also satisfies the equation.
Comment: If we had $f:\mathbb{C}\to\mathbb{C}$ instead of $f:\mathbb{R}\to\mathbb{R}$, then $f$ could be any field automorphism of $\mathbb{C}$ of order $2$, and so there would be lots of solutions.
Comment: In the future, I'd kindly request that you put [tag:functional-equations] on these types of questions.
Answer: There are many such functions $f$, probably too many to classify in any useful way.
First, if $A\subseteq \mathbb{R}$ and $f:A\to\mathbb{R}$, say that $f$ is good if it satisfies the following property:

For all $x,y\in A$, $xf(y)+yf(x)\in A$ and $f(xf(y)+yf(x))=xf(y)+yf(x)$.

The following lemma gives one way to construct many such functions.
Lemma: Let $A\subseteq\mathbb{R}$ with $0\in A$, let $f:A\to\mathbb{R}$ be good, let $a\in \mathbb{R}\setminus A$, and let $b\in\mathbb{R}$ be transcendental over the field generated by $A\cup f(A)\cup\{a\}$.  Then there exists $B\subseteq\mathbb{R}$ such that $A\cup\{a\}\subseteq B$ and $|B|\leq |A|+\aleph_0$ and a good function $g:B\to\mathbb{R}$ which extends $f$ such that $g(a)=b$.
Proof:  Let $B_0=\{2ab\}\cup\{af(x)+bx:x\in A\}$.  Let $B_1$ be the closure of the set $B_0$ under the following operations:

multiplication by $x+f(x)$ for any $x\in A$
multiplication by $a+b$
the binary operation $(x,y)\mapsto 2xy$.

Let $K$ be the subfield of $\mathbb{R}$ generated by $A\cup f(A)\cup\{a\}$; then clearly $B_1\subseteq K[b]$ (so in particular $|B_1|\leq |A|+\aleph_0$).  Moreover, $B_1$ contains no nonzero elements of $K$, since $B_0$ contains no nonzero elements of $K$ and $K[b]\setminus K$ is closed under all of these operations except when we multiply by $0$.
Now let $B=B_1\cup A\cup\{a\}$ and define $g:B\to\mathbb{R}$ by $g(x)=f(x)$ for $x\in A$, $g(a)=b$, and $g(x)=x$ if $x\in B_1$.  Note that $g$ is well-defined, since $B_1\cap A=\{0\}$ and we must already have $f(0)=0$ since $f$ is good.
I claim that $g$ is good; to prove this, suppose $x,y\in B$.  If $x,y\in A$, then we are done since $f$ is good.  In all other cases, we will show that $xg(y)+yg(x)\in B_1$ and so $g(xg(y)+yg(x))=xg(y)+yg(x)$.  Here are all the cases (with cases which are equivalent to these by swapping $x$ and $y$ omitted):

If $x\in A$ and $y=a$, then $xg(y)+yg(x)=xb+af(x)\in B_0$.
If $x\in A$ and $y\in B_1$, then $xg(y)+yg(x)=xy+yf(x)=y(x+f(x))\in B_1$ since $B_1$ is closed under multiplication by $x+f(x)$.
If $x=y=a$, then $xg(y)+yg(x)=2ab\in B_0$.
If $x=a$ and $y\in B_1$, then $xg(y)+yg(x)=ay+yb=y(a+b)\in B_1$ since $B_1$ is closed under multiplication by $a+b$.
If $x,y\in B_1$, then $xg(y)+yg(x)=xy+yx=2xy\in B_1$ since $B_1$ is closed under $(x,y)\mapsto 2xy$.

Now here's how you can use the lemma to construct good functions on all of $\mathbb{R}$.  Fix an enumeration $(r_\alpha)_{\alpha<\mathfrak{c}}$ of the real numbers.  We construct our function $f$ by transfinite recursion as a limit of good partial functions $f_\alpha:A_\alpha\to\mathbb{R}$, starting with $A_0=\{0\}$ and $f_0:A_0\to\mathbb{R}$ given by $f_0(0)=0$.  At limit steps, we just take unions.  At successor steps, we use the Lemma to extend $f_\alpha$ to a larger domain.  More precisely, let $a$ be the first number in our enumeration of the reals which is not in $A_\alpha$, and let $b$ be some real number that is transcendental over the field generated by $A_\alpha\cup f(A_\alpha)\cup\{a\}$.  (We can do this since by induction, $|A_\alpha|\leq |\alpha|+\aleph_0<\mathfrak{c}$.)  We then let $A_{\alpha+1}$ and $f_{\alpha+1}$ be $B$ and $g$ as given by the lemma.
In the end, this gives a function $f=\bigcup_{\alpha<\mathfrak{c}} f_\alpha$ which is defined on all of $\mathbb{R}$ and good, so it is a solution to your problem.  Moreover, by varying the choice of $b$ used in each successor step, we can get many different such functions ($2^{\mathfrak{c}}$ of them, though this takes a bit of work to prove).
Answer: Most compactly written, part of the solution set is $$\{x\mapsto x\cdot\mathbb{1}_A(x):A\subseteq\mathbb{R},2\cdot A\cdot A\subseteq A,A\cdot(\mathbb{R}\backslash A)\subseteq A\}$$
where $\mathbb{1}_A$ is the indicator function on the set $A$. (Three such sets $A$ include $\varnothing$, $\{0\}$ (both giving $f(x)=0$), and $\mathbb{R}$ (which gives $f(x)=x$)) Now, consider the function $f(x)=x\cdot\mathbb{1}_A(x)$ where $A$ is such subset of $\mathbb{R}$. Take $x,y \in \mathbb{R}$. Assume that $x,y \in A$. Then, we have
$$\begin{split}
f(xf(y)+yf(x))&=f(xy+yx)\\&=f(\underbrace{2xy}_{\in A})\\&=2xy\\&=yx+xy\\&=yf(x)+xf(y).
\end{split}$$
Now, assume that $x,y \notin A$. Then, we have
$$\begin{split}
f(xf(y)+yf(x))&=f(0+0)\\&=f(0)\\&=0\\&=0+0\\&=y\underbrace{f(x)}_{0}+x
\underbrace{f(y)}_{0}.
\end{split}$$
Finally, assume that $x \in A$ and $y \notin A$ (the fourth case follows by symmetry). Then, we have
$$\begin{split}
f(xf(y)+yf(x))&=f(\underbrace{y}_{\notin A}\underbrace{f(x)}_{\in A})
\\&=f(\underbrace{yf(x)}_{\in A})\\&=yf(x)\\&=yf(x)+x\underbrace{f(y)}_{0}.
\end{split}$$
Now, let's attempt to show the converse. Suppose that a function $f$ satisfies $$f(xf(y)+yf(x))=yf(x)+xf(y)\text{ for all }x,y\in\mathbb{R}$$
and consider the set $$B=\{x\in\mathbb{R}:f(x)=x\}.$$
Now, take $x,y \in B$. Then, we have
$$\begin{split}
f(2xy)&=f(x\underbrace{y}_{\in B}+y\underbrace{x}_{\in B})
\\&=f(xf(y)+yf(x))\\&=xf(y)+yf(x)\\&=xy+yx\\&=2xy
\end{split}$$
so $2xy\in B$ as well. Now, suppose that $x \in B$ but $y \notin B$. I would not have any idea how to prove that $xy \in B$ as well. The only thing I know is that taking $x=y=1/2$ leads to $f(f(1/2))=f(1/2)$ so $f(1/2) \in B$ as well...
Comment: I think there are no non-trivial solutions of this form (see [my answer](https://math.stackexchange.com/a/3233551/659499) to your question).  The general requirement, if $B_\alpha = \{x | f(x) = \alpha x\}$ is $B_\alpha \cdot B_\beta \cdot (\alpha + \beta) \subseteq A$, and your conditions are necessary if $f$ is always $x$ or $0$. I don't know how to handle case when $f(x) / x$ is different from $0$ and $1$.
Comment: @Servaes Strangely enough, $A=\varnothing$ and $A=\{0\}$ give the same function.
Comment: But $\mathbb R$ is a field, so only ideals in it are $\{0\}$ and $\mathbb R$. However, your solution requires only $2 \cdot A \cdot A \subseteq A$ and $A \cdot (\mathbb R \setminus A) \subseteq A$, so maybe there are some non-trivial sets with this property...
Comment: The empty set satisfies the requirements you set for $A\subset\Bbb{R}$, so there is no need to include the zero map in the set of solutions separately.
Comment: I already posted the spin-off, you can find it [here](https://math.stackexchange.com/questions/3233500/can-one-characterize-the-set-of-all-a-subseteq-mathbbr-satisfying-2-cdot-a).
Comment: @mihaild As you can read in the answer, I managed to prove that the first requirement you posed is necessary but I didn't manage to prove the second. Also, _if_ it turns out that the solution set as I described in the answer is the full solution set, we will still have problems characterizing it.
Comment: That sounds profound, I would agree on that. Maybe someone will find a solution to that particular case.


Services Module Unable To Update User Fields

Question: I am using the Services module configured with a REST endpoint. I can update all other fields on the user account but when I attempt to update the mail field (user e-mail field) it doesn't appear to change.
I think this has to do with the "current_pass" field. Am I supposed to validate the password somehow?
I am testing this but any "hey, silly guy, did you try this?" would be helpful.
Answer: Way 1:
Yes, you need to send the current password to update the user email that is default Drupal user account configuration, and the default user update enpoint exposed by services programmtically submit the same user profile form, which triggers all the validation your form has. In order to send the current password your request load may look like
<code>{
    "current_pass": "onso",
    "mail": "email@example.com"
}
</code>
Way 2:
If you don't want to provide current password, you can consider using No Current Password module, but remember that it will remove the current password field from the form UI as well.
Way 3:
Expose custom endpoint to update user email. Make sure you have authentication on your endpoint.
Comment: Thanks! I just needed someone to tell me that I wasn't entirely crazy. For the options above, making sure to pass the tokens is definitely the way to go. Removing the password confirmation is an option but not terribly secure if the e-mail is intercepted. But the third option, I haven't tried. It is good idea to test.


Hard limit to solve involving exponential and square root

Question: How to find this limit:
$$\lim_{x \to 0}\frac{a(1-e^{-x})+b(e^x-1)}{\sqrt{a(e^{-x}+x-1)+b(e^x-x-1)}}.$$
Where $a$ and $b$ are integer constants. I've tried substitution, L'Hôpital's rule, rationalizing the denominator and all the techniques I knew about limits, but I can't find the answer.
Comment: Have you tried using the second-order approximation $e^x = 1 + x +x^2/2~$?
Comment: Yeah... if I substitute the exponential term by its second order approximation I still get zero over zero.
Answer: You can try with
$$
\lim_{x \to 0}\frac{(a(1-e^{-x})+b(e^x-1))^2}{a(e^{-x}+x-1)+b(e^x-x-1)}
$$
If you try l'Hôpital, you get
$$
\lim_{x\to0}\frac{
  2(a(1-e^{-x})+b(e^x-1))(ae^{-x}+be^x)
}{
  -ae^{-x}+a+be^{x}-b
}\tag{*}
$$
If you assume $a+b\ne0$, then you can remove the factor $2(ae^{-x}+be^x)$ from the numerator (you can reinsert $2(a+b)$ at the end) and apply l'Hôpital again
$$
\lim_{x\to0}\frac{ae^{-x}+be^x}{ae^{-x}+be^x}=1
$$
Then the limit (*) is $2(a+b)$ (which should be positive) and your limit is
$$
\sqrt{2(a+b)}
$$
You can check that with $b=-a\ne0$, the limit is $0$.
Comment: To add flavor and another method, I added practically the same thing to my answer. Rats! Nice work +1
Answer: (assuming limit from the right). Use Taylor Series: $$e^x=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\ldots\implies e^{-x}=1-x+\frac{x^2}{2!}-\frac{x^3}{3!}+\ldots$$
so that $$\lim_{x \to 0}\frac{a(1-e^{-x})+b(e^x-1)}{\sqrt{a(e^{-x}+x-1)+b(e^x-x-1)}}$$ $$=\lim_{x \to 0}\frac{a(x-\frac{x^2}{2}+\ldots)+b(x+\frac{x^2}{2}+\ldots)}{\sqrt{a(\frac{x^2}{2}-\frac{x^3}{3!}+\ldots)+b(\frac{x^2}{2}+\frac{x^3}{3!})}}\cdot\dfrac{\frac{1}{x}}{\frac{1}{x}}$$ $$= \lim_{x \to 0}\frac{a(1-\frac{x}{2}+\ldots)+b(1+\frac{x}{2}+\ldots)}{\sqrt{a(\frac{1}{2}-\frac{x}{3!}+\ldots)+b(\frac{1}{2}+\frac{x}{3!})}}=\dfrac{a+b}{\sqrt{\frac{1}{2}(a+b)}}=\boxed{\sqrt{2(a+b)}}$$
If it's the limit from the right, it's just the negative of this. Note that we used that $\frac{1}{x}=\frac{1}{\sqrt{x^2}}$ (principle).
Alternatively, we could have used L'Hopital just fine: $$I=\lim_{x \to 0}\frac{a(1-e^{-x})+b(e^x-1)}{\sqrt{a(e^{-x}+x-1)+b(e^x-x-1)}}$$
$$= \lim_{x \to 0}\frac{ae^{-x}+be^x}{\frac{1}{2}\left(a(e^{-x}+x-1)+b(e^x-x-1)\right)^{-\frac{1}{2}}\cdot \left(a(-e^{-x}+1)+b(e^x-1)\right)}=2(a+b)\lim_{n\to0}\frac{\sqrt{a(e^{-x}+x-1)+b(e^x-x-1)}}{a(1-e^{-x})+b(e^x-1)}=2(a+b)\frac{1}{I}\implies I^2=2(a+b)\implies \boxed{I=\sqrt{2(a+b)}}$$
Answer: Use the second-order approximation $e^x = 1 + x +x^2/2$ to get
$$\lim_{x \to 0}\frac{a(1-e^{-x})+b(e^x-1)}{\sqrt{a(e^{-x}+x-1)+b(e^x-x-1)}} = \\ \lim_{x \to 0}\frac{a(x- x^2/2)+b(x +x^2/2)}{\sqrt{a(x^2/2)+b(x^2/2)}} = \\ \lim_{x \to 0} \frac{a(1- x/2)+b(1 +x/2)}{\sqrt{a(1/2)+b(1/2)}}=\sqrt{2(a+b)}$$


Intervalo de hora entre datas ORACLE SQL

Question: Boa Tarde pessoal, Estou com uma dúvida no oracle SQL em que pra resolver eu queria pegar a seguinte informação:
Antes, tenho essa query:
SELECT  cd_atendimento,ds_atendimento,cd_valor,hr_atendimento
FROM  atendimento WHERE cd_atendimento IN
(
  5587064,
  5584065,
  5587654,
  4568985,
  5587062,
  5584061,
  5587659,
  4568910
)
AND hr_atendimento BETWEEN TO_DATE('01/11/2020 00:00:00', 'DD/MM/YYYY HH24:MI:SS')
AND TO_DATE('11/11/2020 05:59:00', 'DD/MM/YYYY HH24:MI:SS')
AND cd_atendimento IS NOT NULL

Eu queria que ele retornasse, Todos os atendimentos Do dia 01 até o dia 11 dentro das horas: 00:00 até 05:59, Seria um filtro por "DATA e hora Obviamente", ou seja ele teria que me retornar todos os atendimentos realizados entre essa hora de cada dia.
ex de retorno desejado :
Dia 01 de 00:00 as 05:59 : atendimentos: 5587064,
  5584065,
  5587654

Dia 02 de 00:00 as 05:59: atendimentos:5584061,
  5587659,
  4568910

e assim sucessivamente...
Podem me ajudar?, Pois do jeito que está ele vai me retornar desde o dia 01 as 00:00 até o dia 11 até as 05:59, o que não é o que eu preciso :(
Answer: Separe data e hora
SELECT cd_atendimento,
           ds_atendimento,
           cd_valor,
           hr_atendimento
    FROM atendimento
    WHERE cd_atendimento IN ( 5587064, 5584065, 5587654, 4568985, 5587062, 5584061, 5587659, 4568910 )
    AND trunc(hr_atendimento) BETWEEN TO_DATE('01/11/2020', 'DD/MM/YYYY') AND
                                      TO_DATE('11/11/2020', 'DD/MM/YYYY')
    AND to_char(hr_atendimento,'hh24mi') BETWEEN '0000' and '0559'
    AND cd_atendimento IS NOT NULL


Looking for a good book on groups and graph theory

Question: Can anyone help me on which book would be best book to understand
Permutation groups how it represents graphs in graph theory and other with good simple examples and is much self explanatory
And dihedral groups how it represents graphs too
Orbits and stabilizer
In a very self explanatory way with examples relating it to graphs in graph theory with examples from basis
For a beginner
Kindly help by recommending a book that I can study as a beginner to learn algebra in graph theory of the above topic mainly permutation groups, orbits and stabilizer
Comment: Then it seems better to talk to someone like a good teacher. Posting here will just give you references you can google yourself. Alternatively you could try to improve your question by asking something precise about an explicit example, like $D_5$.
Comment: I know abstract algebra like herstien and graph theory now I am looking books which can explain the relationship between permutation groups and all above with simple example so that it can help me understand
Comment: S exactly and also I need it with small examples for dihedral groups and orbits , stabilizer etc how in graph theory with very very simple graphs and small examples so that it will be easy for me understand and also find the number of unique permutation of a graph with simple example in self explanatory way and should be like a good teacher explaining. Even group of symmetries of a graph is also mean not exactly Cayley graphs
Comment: S I need good book written who might have been the best written and great person in that who writes good book who is by himself be a great teacher because then only they can write a such a self explanatory book understanding students requirements. As I need to read a good book than posting each line as a question.  I tried in Google not able to may be good people here as all give us the best understanding the students requirements
Answer: I'm not entirely sure if this is what you are looking for, but there is a field known as "Geometric Group Theory" where we study groups by their actions on graphs (and other things too).

A fantastically approachable first reference (I'm biased, as it was my first reference) is Meier's "Groups, Graphs, and Trees".

As for how this pertains to your question, chapter 1 of this book discusses Cayley's Theorem (that every group is a subgroup of a symmetric group) and what is somewhat cheekily referred to as Cayley's Better Theorem (that every group is a group of symmetries of some graph). Chapter 1 also discusses the orbit-stabilizer theorem, as well as the dihedral groups (and how they act on graphs).
The entire book is wonderful, but already the first 2 chapters will discuss everything you have brought up in this question. It is filled with good exposition and fantastic pictures to help you see what's happening.

I hope this helps ^_^
Comment: You should be able to find it on the Library of Genesis, which you can Google
Comment: Great yes will check if any link for book kindly share too
Comment: Found Graphs and Groups title one book for a starter like me
Comment: I'm not sure what you mean - did you find a book you like?
Comment: S sir I found the book


Cannot import getSignInClient method in Android Studio 4.2.2

Question: In my Class that extends AppCompatActivity
import com.google.android.gms.auth.api.identity.Identity.getSignInClient;

cannot resolve symbol getSignInClient that appears in red.
In Gradle is put
implementation platform('com.google.firebase:firebase-bom:28.1.0')
implementation 'com.google.firebase:firebase-auth'
implementation 'com.google.firebase:firebase-database:20.0.0'
implementation 'com.google.firebase:firebase-storage:20.0.0'
implementation 'com.google.android.gms:play-services-auth:19.0.0'

So, the code has an error on this line
oneTapClient = ContactsContract.CommonDataKinds.Identity.getSignInClient(this);

oneTapClient is declare as follows:
private SignInClient oneTapClient;

where is the mistake ?
Answer: I had same issue before
check your imports and remove
 import android.provider.ContactsContract; this
and use the following
import com.google.android.gms.auth.api.identity.Identity;

oneTapClient = Identity.getSignInClient(this);

or just use it like this
 oneTapClient = com.google.android.gms.auth.api.identity.Identity.getSignInClient(this);


Restricting the domain of the trigonometric functions in identities

Question: I have this formula in my textbook:
$
\sin ^2 \alpha =  \frac{\tan ^2 \alpha}{1+\tan^2 \alpha}
$
where $\alpha \neq \frac{\pi}{2}+ k\pi $
I think that the restriction for the angle is wrong and it should be $\alpha \neq k \times \frac{\pi}{2}$ where $k \in \mathbb{Z}$.
Also i want some advice on how to take care of the angle restriction when moving from one formula to another. For example in some formula we restrict the angle and then do some algebraic transformations and get a new formula with different trigonometric function etc. How to connect the previous angle restrictions to the current ones that arise in the new formula? I guess this is general for all functions and so for the trigonometric but let's hear your opinion.
Comment: The restriction in the textbook is correct. It excludes values of $\alpha$ for which $\tan\alpha$ is not finite, so it avoids having the indeterminate expression $\infty/\infty$ on the right hand side. Remember, the period of the tangent function is $\pi$, and its graph has a vertical asymptote at odd multiples of $\pi/2$.
Comment: My restriction of the angle doesn't allow the angle to be on the y axis because there the tangent is undefined. It also doesn't allow the angle to be on the x axis because there the sine function is zero and here we must restrict the sine to not be equal to zero. This is ommited in the textbook's restriction. Am i missing something?
Comment: Why are you not allowing the sine to be zero? There's nothing wrong with allowing it to be zero. The left side of the equation is $0$, the right side is $\frac{0}{1+0^2} = 0$. You are excluding values that don't need to be excluded.
Comment: But if we rewrite the equation with the $\sin^2\alpha$ in the denominator on the RHS then it must not be zero?
Comment: Isn't it added to $1$ in the denominator, not just by itself? That's okay, right? $1/(1+0)$ is just $1$.
Comment: If we have $1+\tan^2\alpha$ on the LHS and $\frac{\tan^2\alpha}{\sin^2\alpha}$ on the RHS than the sine must not be zero.
Comment: That's true, but you didn't mention that in the question. Also, if you are only using such division in an intermediate step, and it doesn't appear in the final result, you can still manually verify that the formula is correct for those values of $\alpha$ even if they are excluded during the derivation.
Comment: So you want to say that if we excluded some value for $\alpha$ in some step in the derivation of the final formula, then it is possible the final formula to be defined for that value for $\alpha$? How/Why is this possible?
Answer: The RHS is undefined when the tangent is infinite, i.e. when the cosine is $0$. This occurs for $-\frac\pi2$, $\frac\pi2$, $\frac{3\pi}2$, $\frac{5\pi}2$... i.e. $(k+\frac12)\pi$.
Anyway we have
$$\lim_{\alpha\to(k+\frac12)\pi}\frac{\tan^2\alpha}{1+\tan^2\alpha}=1=\lim_{\alpha\to(k+\frac12)\pi}\sin^2\alpha,$$
so that the formula is virtually valid everywhere.
The rules for angle restrictions follow from the rules of equation manipulation:

the domain must exclude the values for which expressions are undefined,
it must also exclude the values for which the equation transformation rules are violated.

Example: you may not divide by zero. So a transform like $\sin^4\alpha=\sin^2\alpha-\sin^2\alpha\cos^2\alpha\implies\sin^2\alpha=1-\cos^2\alpha$ must exclude $\alpha=k\pi$.
Once a value has been excluded, it remains excluded for the rest of the derivation. (But you are allowed to treat special cases separately.)


Sending docker logs to logstash

Question: I have a number of CoreOS servers on Amazon AWS and would like to collect events or logs from them and forward them onto my ELK stack provider logz.io.
Being a little new to the ELK stack, I'm a little lost on how to best get the data out.  It was suggested to me to use filebeat.  But filebeat works with ordinary log files and most of the data is currently being fed into journald.
All my services are running on docker and I see that docker has the idea of logging drivers.  Could I plug into that in some way?
There is a project called journalbeat which looks promising, but incomplete and currently forwards everything.  I just want specific units and actually, specific events.  So I may have to work on that project to make it do what I need.  But, before I go further there, is there perhaps another way?
e.g. another lightweight service that I could run on the machine that might accept logging events and forward them on.  So long as it's not logstash because that will consume too many resources on my already memory and cpu constrained aws instances.
I'm surely not the only person to run into this type of issue.
Comment: You could always filter it, if you don't want everything.
Comment: I know I can filter it at the elasticsearch end, but then I don't want to be charged for uninteresting data.  It costs to store it and on the account I currently have there is an amount of data per day.
Answer: There is a Docker log driver for 'gelf', and a input plugin for Logstash that understands gelf format. That is probably the most straightforward way.
Comment: Yes although it appears that logz.io doesn't accept gelf?  I'll have to ask them.
Comment: Also if gelf is udp I guess there is no end to end encryption, so that would be a no-go for me.
Comment: Also I'm using docker 1.91 which doesn't yet support the -log-driver options.  It looks like rsyslogd can be configured to pull from journald and that can then send to logz so I'm going to see if that might work.

Sending docker logs to logstash


What is the relationship between "do re mi" and note letter names?

Question: When people sing the song, they use do, re, mi, fa, sol, la, ti, (si), etc, but sometimes I hear that the music people say A, B, C, D flat, etc.
Is there a relationship or are they two different things?
Answer: Do-re-mi-etc. is "sol-fa" or "solfege".
Sol-fa represents a major scale, with Do being the first note, Re being the second, and so on. I'm sure you can sing that scale.
The A-G note names are absolute names for a certain note. An 'A' is an 'A' no matter what key you are performing in.
There are two variants of sol-fa. Fixed do and Movable do.
Fixed do is used in China, France, Italy, Portugal, Spain, Romania, Russia, South America and parts of North America, Japan, and Vietnam.
In fixed-do, Do is always equivalent to C; Re is always equivalent to D; and so on.
Movable Do is used in Britain, Germany, Indian classical music, and the United States.
In movable-do, you can pick a different pitch to start on, and sing Do-re-mi-... starting at that note. What you are doing when you do that is singing the major scale in different keys.
If you are singing in C major, d,r,m,f,s,l,t,d is C,D,E,F,G,A,B,C
If you are singing in D major, d,r,m,f,s,l,t,d is D,E,F♯,G,A,B,C♯,D
... and so on.
In both forms, there are other phonetic names for sharp and flat names. The complete list is on Wikipedia.
Comment: Also interesting, the do re mi syllables come from a song in latin. Each phrase starts on a different tone, starting with the tonic for the first phrase, and one step up for every phrase. The first syllables of every phrases give: ut re mi fa so la si ut. I do not know when, where, and why ut got changed to do. A source: http://en.wikipedia.org/wiki/Solf%C3%A8ge
Comment: In Indian classical music, you are correct that the concept of solfege is there, but you should probably note that the syllables are different: sa re ga ma pa dha ni.
Comment: The alternative phonetic names for sharp and flat are not in use in fixed doh countries (see the table "Traditional fixed do" in your link to Wikipedia). In France at least, the altered notes are named in a way very similar to the anglo-saxon way: C sharp is "do dièse", B flat is "si bémol". When singing and naming the notes' name at the same time, the alteration is discarded (you would sing the syllable "si" while singing a B flat).
Comment: It would appear it's not "as easy as do re mi"!!
Comment: @DarrenRinger Doh, Fah etc are acceptable spellings according to Chambers' dictionary - but you're right, for consistency I am changing to the more common spellings.
Comment: The sound of music did the same thing later on :)
Comment: I note that the Sound of Music song is in Bb, to they're using movable Doh :)
Comment: Indonesia uses the movable do system.
Comment: I may be mistaken, but AFAIK movable Do is sometimes used in Italy as well - mainly in ear-training and singing contexts, where it is a shortcut for "the Nth note of the ionian mode", even if the piece is not in C. At least, I have seen a rehearsal in which they did it, but I'm no musician, so take this with a grain of salt.
Comment: Did Homer Simpson come in and edit this post at some point?
Comment: Moveable Do is also used here in Austria, which is not, contrary to popular belief, part of Germany.  Anyone remember the song "Do, a deer, a female deer" from "The Sound of Music"?
Comment: @Gauthier the Latin hymn only has *ut* through *la; si* was a later invention (the hymn lacks the note *B* entirely).  When the original six solmisation syllables were invented, *ut* could correspond to C, G, or F.  These hexachords were the *hexacordum naturale, hexacordum durum,* and *hexacordum molle,* respectively.  See https://en.wikipedia.org/wiki/Guidonian_hand.
Comment: Is there any software library that can be used to convert notes from absolute to all of these other systems ?
Answer: On a Fixed Do scale the A Note is assigned to La, the A was assigned because it has the precision of the frequency (440 Hz) which doesn't have decimals, so  it's easier to remember. So you end up with a correspondence as follows
A = La
B = Si
C = Do
D = Re
E = Mi
F = Fa
G = Sol
Take into account that while on the english notation (A,B,C,D) you start on the 400 Hz note which is A4, on fixed Do you start on the first discernible note (which is C0 at 16.3516 Hz)
By the way the note names on the Fixed Do scale come from a poem of the benedictine monk "Paul the Deacon" which goes like this:
Ut queant laxis
Resonare fibris
Mira gestorum
Famuli tuorum
Solve polluti
Labii reatum
Sancte Ioannes
And the Ut was replaced by Do to make it easier to say on the Romance languages
Comment: Still not convinced that A was chosen as la because of its whole number frequency pitch. 440 Hz is not industry standard everywhere, and probably wasn't when sol-fa/solfege was invented.
Comment: The names come from a poem of Paul the Deacon and set to music by Guido D'Arezzo, the inventor of modern notation (as opposed to neumatic notation).
Comment: Though i can understand it may not be standard always, in the classical period the scale was constantly changed for multiple reasons, so there is no certain way of knowing why this specific scale was the one that survived until our times
Comment: Also, consider that during the classical period each orchestra tried to get a commercial edge over other orchestras by constantly moving the base note towards treble to make it sound more energetic.
Comment: @Tim indeed, solfège was invented centuries before it was possible to measure frequency in cycles per second (because it was [not yet possible to measure seconds](https://en.wikipedia.org/wiki/Pendulum_clock#History)).  The idea that *la* was associated with *A* because *A* has an integer frequency is unfounded.  In fact, *la* was associated with *A* because the phrase *labii reatum* of the hymn [ut queant laxis](https://en.wikipedia.org/wiki/Ut_queant_laxis) starts on A.
Comment: @phoog that sounds really interesting, if you can get me the reference i would love to update the answer with your information
Comment: @jclozano which reference?
Comment: @phoog by reference i mean if you can point me out where did you learn of that i can put that in my edit so i can properly credit you with the info :)
Comment: Is there any software library that can be used to convert notes from absolute to all of these other systems ?
Answer: Solfege (do, re, mi, ...) is a numbering system which starts from the first note of the scale (do=1, re=2, ...). Solfege identifies the position of the note in the scale.
Pitch names are a numbering system which starts from a particular sound (A440 or concert A=1, B=2, ...). Pitch names identify the sound of the note in the scale.
Take an example. Say you are singing a song that's in F major. The pitch names for that scale will be F G A B♭ C D E F, and the solfege for that scale will be do re mi fa so la ti do.
Now, sing that song in G major. The pitch names will change to G A B C D E F♯ G, but the solfege for that scale will still be do re mi fa so la ti do.
Comment: I'm talking rubbish, above. If you're in F, in France, you'd be in fa. So changing to G  you'd be in So. So fa so good.
Comment: In France, doh is always C. To change the key to G major,the root note will be called mi. Confusing ?
Answer: If you have ever looked at pop sheet music in Spanish, you'll see that they don't use "C, D, E, F, G, A, B" at all. They only call notes by their Fixed Do names.
In Spanish sheet music, a C dominant 7 chord is called "Do7". A G# dominant 7 chord is called "So#7".
Comment: It is Sol#7 , no So#7
Answer: They are the relative names of the notes with reference to each other and the tonic note.
In indian music its known as(if tonic note is C#) Sa(C),Re(D),Ga(E),Ma(F),Pa(G),Dha(A),Ni(B),Sa(Upper octve C).
if the tonic changes then, respectively other notes will be change accordingly.
And this name are very sound friendly,when singing user can utter it easily.
Answer: Do = Tonic    ,
Ra = Supertonic    ,
Me = Mediant    ,
Fa = Sub-dominant    ,
So = Dominant    '
La = Sub-mediant    '
Ti = Leading note    ,
Do = Tonic for whichever diatonic key you choose.


Compact subset of the image of a continuous function

Question: Given complete metric spaces $(X,d_{X})$ and $(Y,d_{Y})$, a continuous function $f:X \to Y$,  and a compact subset $K \subset f(X)$, I would like to know if it is possible to claim that there exists a compact $F \subset X$ such that $K \subset f(F)$.
It seens to be right in particular cases when I suppose for instance $f$ to be bijective, and both spaces $X=Y=\mathbb{R}$.
Any help and counterexamples would be great.
Comment: Just a remark: If $K = f(X)$ is already compact, then the question is: does there exist a compact set $F\subset X$ such that $f(F) = f(X)$.
Comment: So, here is a counterexample: Let $X = (-\infty,0]\cup [1,2]$, $Y = [0,1]$, and $f : X\to Y$ defined by $f(x) = e^x$ for $x\le 0$ and $f(x) = 0$ for $x\in [1,2]$. So, you should assume at least that $X$ is connected.
Comment: You're right! We could assume for now $X = \mathbb{R}$, for example.
Comment: To prove the easier question, I started with closed balls $\overline B_n$ around a fixed point $x_0\in X$ with radius $n\in\mathbb N$. Aim: $f(\overline B_n) = Y = f(X)$ for some $n$. For this it is enough to show that each $y\in Y$ is in the interior $V_n$ of some $f(\overline B_n)$, because then, since $Y$ is compact, we have $Y = \bigcup_{k=1}^NV_s = f(\overline B_N)$. But until now I couldn't prove this. It must be somehow connected with the connectedness of each $f(\overline B_n)$. BTW, since $Y = \bigcup_nf(\overline B_n)$, we have $V_n\neq\emptyset$ for some $n$ by Baire's theorem.
Answer: I only refer to the easier question:

If $f : \mathbb R\to\mathbb R^n$ is continuous and $f(\mathbb R)$ is
  compact, does there exist a compact set $K\subset\mathbb R$ such that
  $f(K) = f(\mathbb R)$?

The answer is yes, if $n=1$ and no (i.e., not in general) if $n\ge 2$.
Proof for $n=1$: In this case $f(\mathbb R)$ is a compact and connected set in $\mathbb R$, hence an interval: $f(\mathbb R) = [a,b]$. Now, choose $x,y\in\mathbb R$ such that $f(x) = a$ and $f(y) = b$. Then, by the intermediate value theorem, $f([x,y]) = [a,b] = f(\mathbb R)$.
Counter example for $n=2$. Define $\phi(x) = 4\arctan(x)$ and set
$$
f(x) =
\begin{cases}
(1+\cos(\phi(x)-\pi),\sin(\phi(x)-\pi)) &\text{if }x\ge 0,\\
(-1+\cos\phi(x),\sin\phi(x)) &\text{if }x< 0.
\end{cases}
$$
Then $f$ is obviously continuous and $f(\mathbb R) = C_1\cup C_{-1}$ is compact, where $C_t$ denotes the circle with center $(t,0)$ and radius $1$. But there can never be a compact $K\subset\mathbb R$ such that $f(K) = f(\mathbb R)$ since $f$ is injective.
Comment: Yes, that's it! Thank you very much. And it is interesting that even if the function is injective (and so bijective in its range), your example for $n = 2$ shows that the property can not be true. ;)
Comment: Could you please check and upvote my answer? Thanks.
Comment: I checked and it seems right for me. I tried to vote but the only thing I got is
  "Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score."
Comment: @ArthurCavalcante I see. Thanks. Stupid system. ;-)


Unwanted android permission

Question: My app is using only the following permission:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

But when I install my app it asks for an unknown permission:

modify or delete the contents of your USB storage read the contents of your USB storage

Following is my build.gradle file:
apply plugin: 'com.android.application'

android {
compileSdkVersion 22
buildToolsVersion '22.0.1'

defaultConfig {
    applicationId "com.plusgaurav.weatherballoon"
    minSdkVersion 16
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

repositories {
maven { url "https://jitpack.io" }
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
// support libraries
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:design:22.2.0'
compile 'com.android.support:cardview-v7:22.2.0'
compile 'com.android.support:recyclerview-v7:22.2.0'
// google play services location api
compile 'com.google.android.gms:play-services-location:7.5.0'
// making connection requests
compile 'com.squareup.okhttp:okhttp:2.4.0'
// animation
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.easing:library:1.0.1@aar'
compile 'com.daimajia.androidanimations:library:1.1.3@aar'
}

Thanks in advance.
Comment: What permissions are you seeing? The library most likely bringing in the permission is `com.google.android.gms:play-services-location`.
Comment: modify or delete the contents of your USB storage read the contents of your USB storage when I install the app via the generated apk. I was also getting contacts permission when I was using the whole gms library, so I put a specific one instead.
Comment: @JaredBurrows You were right. I read up with the possible duplicate of this question and it seems that it is a known issue with gms 7.5. I have accepted that it is a duplicate question and the other users having the same doubt will be redirected there. Thanks.
Answer: Google play services 7.5 add other permissions, it's normal. If you try to include for example all the play services (you are now including only the location part) you will see a lot of new permissions as well.

Unwanted android permission


Split Time Frequency To Rows

Question: I am trying to split a time frequency that has a start time, an end time, a frequency and a duration into separate rows. Here is some example data:
+------+------------+----------+-----------------+---------------+
| Name | Start_Time | End_Time | Frequency_Hours | Duration_Mins |
+------+------------+----------+-----------------+---------------+
| A    | 08:00:00   | 18:00:00 |               2 |             2 |
| B    | 00:00:00   | 23:59:59 |               1 |             5 |
| C    | 00:00:00   | 23:59:59 |               4 |            15 |
+------+------------+----------+-----------------+---------------+

Can be created using the following query:
DECLARE @Tmp AS TABLE(Name VARCHAR(128)
                     ,Start_Time VARCHAR(8)
                     ,End_Time VARCHAR(8)
                     ,Frequency_Hours INT
                     ,Duration_Mins INT)

INSERT INTO @Tmp VALUES ('A','08:00:00', '18:00:00', 2,2)
                       ,('B','00:00:00', '23:59:59', 1,5)
                       ,('C','00:00:00', '23:59:59', 4,15)

Here is my desired output (I will then use this to drive a gantt chart visualisation):
+------+------------+----------+
| Name | Start_Time | End_Time |
+------+------------+----------+
| A    | 08:00:00   | 08:02:00 |
| A    | 10:00:00   | 10:02:00 |
| A    | 12:00:00   | 12:02:00 |
| A    | 14:00:00   | 14:02:00 |
| A    | 16:00:00   | 16:02:00 |
| A    | 18:00:00   | 18:02:00 |
| B    | 00:00:00   | 00:05:00 |
| B    | 01:00:00   | 01:05:00 |
| B    | 02:00:00   | 02:05:00 |
| B    | 03:00:00   | 03:05:00 |
| B    | 04:00:00   | 04:05:00 |
| B    | 05:00:00   | 05:05:00 |
| B    | 06:00:00   | 06:05:00 |
| B    | 07:00:00   | 07:05:00 |
| B    | 08:00:00   | 08:05:00 |
| B    | 09:00:00   | 09:05:00 |
| B    | 10:00:00   | 10:05:00 |
| B    | 11:00:00   | 11:05:00 |
| B    | 12:00:00   | 12:05:00 |
| B    | 13:00:00   | 13:05:00 |
| B    | 14:00:00   | 14:05:00 |
| B    | 15:00:00   | 15:05:00 |
| B    | 16:00:00   | 16:05:00 |
| B    | 17:00:00   | 17:05:00 |
| B    | 18:00:00   | 18:05:00 |
| B    | 19:00:00   | 19:05:00 |
| B    | 20:00:00   | 20:05:00 |
| B    | 21:00:00   | 21:05:00 |
| B    | 22:00:00   | 22:05:00 |
| B    | 23:00:00   | 23:05:00 |
| C    | 00:00:00   | 00:15:00 |
| C    | 04:00:00   | 04:15:00 |
| C    | 08:00:00   | 08:15:00 |
| C    | 12:00:00   | 12:15:00 |
| C    | 16:00:00   | 16:15:00 |
| C    | 20:00:00   | 20:15:00 |
+------+------------+----------+

I am hoping to be able to create a view out of this so I am trying to do it without cursors or other cpu intensive methods.
Any ideas?
Thanks,
Dan.
Answer: You could use a recursive cte like this
;WITH temp AS
(
    SELECT t.Name, CAST(t.Start_Time AS time) AS CurrentStart_Time, dateadd(minute,t.Duration_Mins,CAST(t.Start_Time AS time)) AS CurrentEnd_Time, t.Frequency_Hours, CAST(t.End_Time AS time) AS End_Time
    FROM @Tmp t

    UNION ALL

    SELECT t.Name, dateadd(hour,t.Frequency_Hours,t.CurrentStart_Time), dateadd(hour,t.Frequency_Hours,t.CurrentEnd_Time), t.Frequency_Hours, t.End_Time
    FROM temp t
    WHERE t.CurrentStart_Time < t.End_Time AND t.CurrentStart_Time < dateadd(hour,t.Frequency_Hours,t.CurrentStart_Time)
)

SELECT t.Name, t.CurrentStart_Time, t.CurrentEnd_Time
FROM temp t
ORDER BY t.Name
OPTION (MAXRECURSION 0)

Demo link: http://rextester.com/XJK25805
Answer: It can be done without RECURSIIVE CTE also.
If we create number instead of using
select distinct number master..spt_values then performance will be far better.
Like Number table can be populated from 1 to 100.
try this with various sample data,
declare @t table(Name varchar(20), Start_Time time(0),End_Time time(0)
, Frequency_Hours int,Duration_Mins int)
insert into @t VALUES
 ('A','08:00:00','18:00:00', 2 , 2 )
,('B','00:00:00','23:59:59', 1 , 5 )
,('C','00:00:00','23:59:59', 4 ,15 )

SELECT NAME
    ,dateadd(hour, n, Start_Time) Start_Time
    ,dateadd(minute, Duration_Mins, (dateadd(hour, n, Start_Time))) End_Time
FROM @t t
CROSS APPLY (
    SELECT DISTINCT number * Frequency_Hours n
    FROM master..spt_values
    WHERE number >= 0
        AND number <= datediff(HOUR, t.Start_Time, t.End_Time) / Frequency_Hours
    ) ca

Comment: Also works very well, and with it not being a CTE, is very easy to work with in my code. Thanks!

Split Time Frequency To Rows


Como fazer controle de versões com GitLab?

Question: Cenário
Tenho uma pasta local (em minha máquina) com todas as pastas e arquivos de vários projetos.
Por algumas indicações, escolhi o GitLab pois preciso guardar projetos privados.

Dúvidas

Existe uma ferramenta para "sincronizar" toda essa minha estrutura?

Essa ferramenta faria controle de versões?

Caso não, existe outra forma ou não há possibilidade?

Agradeço qualquer outra dica importante sobre o GitLab.
Comment: Quem faz o controle de versão é o git, o GitLab é apenas um gerenciador de repositório de software (ou programas) que é baseado no git.
Comment: @JoãoPedroSchmitz então devo usar uma ferramenta git?
Comment: Assim, você vai usar comandos git para controlar as versões do seu código e de uma maneira bem simples, vai "jogar", ou melhor, subir o seu código para o GitLab, por exemplo, onde ele ficará salvo. Dá um olhada nesse curso, https://www.udemy.com/git-e-github-para-iniciantes/, é gratuito e muito bom. Vai te ensinar bastente.
Comment: @JoãoPedroSchmitz opa cara! Bom demais! Vou ver esse curso. Acredito que no lugar do GitLab, está o Github, então é praticamente o mesmo conceito em relação ao git e o restante, correto!?
Comment: Isso mesmo, no lugar do GitLab é o GitHub, mas a ideia por trás é a mesma. O importante mesmo é aprender os comandos do git, que hoje em dia, é quase que um pré-requisito básico para qualquer vaga de emprego.
Answer: GitLab já oferece o serviço de controlar versões
Talvez você seja novo no Git e por isso esteja confundindo as coisas, então eu indico que você passe pelo guia básico e rápido do Git.
Em resumo resumido, o Git é o software que você instala localmente para controlar as versões dos seus arquivos localmente. GitLab, GitHub, BitBucket e outros serviços, oferecem um repositório Git na nuvem para você espelhar o seu repositório local, além de outras ferramentas bem bacanas para você organizar e compartilhar o seu trabalho.
Para simplificar, se estiver em um trabalho solo, o seu procedimento no dia-a-dia é alterar o seu código-fonte no seu editor favorito e executar comandos git para atualizar o seu repositório local e depois outros comandos git para enviar essas alterações para o serviço na nuvem que você escolheu.
Existem diversas opções de ferramentas gráficas que você pode usar para executar os comandos git caso não queira fazer isso por linha de comando. Algumas IDEs já tem integração com Git também.


multiplication in GF(256) (AES algorithm)

Question: I'm trying to understand the AES algorithm in order to implement this (on my own) in Java code.
In the algorithm all byte values will be presented as the concatenation of its individual bit values (0 or 1) between braces with the most significant bit first.
So bytes are interpreted as finite field elements using a polynomial representation:
$$b_7x^7+b_6x^6+b_5x^5+b_4x^4+b_3x^3+b_2x^2+b_1x+b_0$$
Example: ${01100011} \equiv x^6 + x^5 + x +1$
These finite field elements can easily be added with the XOR operator.
But multiplication is a little bit more complex, and I don't understand it.
In the polynomial representation, multiplication in GF(256) corresponds with the multiplication of polynomials modulo an irreducible polynomial of degree 8
This irreducible polynomial is: $m(x)=x^8 +x^4 +x^3 +x+1$
Here is my example:
$$01010111 * 00010011$$
$$01010111\equiv (x^6+x^4+x^2+x+1)$$
$$00010011\equiv(x^4+x+1)$$
$$(x^6+x^4+x^2+x+1) * (x^4+x+1) = x^{10}+x^8+x^7+x^3$$
$$(x^{10}+x^8+x^7+x^3) \mod m(x)$$
$$(x^{10}+x^8+x^7+x^3) \mod (x^8 +x^4 +x^3 +x+1) = x^2 + 1$$
$$x^{10}         x^3$$
$$x^8+x^7+x^6+x^5+x^2$$
$$x^8$$
$$x^7+x^6+x^5+x^4+x^3+x^2+x+1$$
So here $x^7+x^6+x^5+x^4+x^3+x^2+x+1$ is my solution, that leads to a binary representation: $11111111$
But in the literature the correct solution is: $11111110$
I would be happy if you could tell me where my mistake is.
Comment: I wanted to tidy up the chain of computation, but I couldn't understand what you were doing, so I've just added `$` symbols to invoke $\LaTeX$ markup.
Comment: Oh Thanks, now its easier to read. It should be a polynomial divison.
Answer: $$(x^6+x^4+x^2+x+1) * (x^4+x+1) = x^{10}+x^8+x^7+x^3$$
should make you suspicious. What happened to the cross-term $1*1$?
I make that product to evaluate to $x^{10}+x^8+x^7+x^3+1$, and the difference of $+1$ should carry through the remaining computation to give the difference you sought.
The modulo operation is equivalent to assuming $x^8 = x^4+x^3+x+1$, which gives $x^{10} = x^6+x^5+x^3+x^2$ so $$\begin{eqnarray*}x^{10}+x^8+x^7+x^3+1 & = & (x^6+x^5+x^3+x^2) + (x^4+x^3+x+1) + x^7+x^3+1\\
& = & x^7+x^6+x^5+x^4+x^3+x^2+x\end{eqnarray*}$$
Comment: Thank you, that is a small miscalculation with big effects!


Finding a special power series

Question: Find a power series for F, such that $F'(x)=e^{-x^2}$.
Don't understand how to come up with the solution
Comment: Do you know the power series for $e^x$, and if so, do you know how to get the power series for $e^{-x^2}$ from it?
Answer: We have
$$F'(x)=e^{-x^2}=\sum_{n=0}^\infty (-1)^n\frac{x^{2n}}{n!}$$
with radius of convergence $+\infty$ hence by integrating term by term we find:
$$\int_0^xF'(t)dt=F(x)-F(0)=\sum_{n=0}^\infty (-1)^n\frac{x^{2n+1}}{(2n+1)n!}$$
Answer: Recall that the power series for $e^x$ is
$$
\sum_{n=0} ^\infty { \frac{x^n}{n!} } .
$$
Thus, the power series for $e^{-x^2}$ is
$$
\sum_{n=0} ^\infty { \frac{(-x^2)^n}{n!} } = \sum_{n=0} ^\infty { \frac{(-1)^n x^{2n}}{n!} }  .
$$
Integrating term by term yields
$$
F(x) = \int F'(x) = \int \sum_{n=0} ^\infty { \frac{(-1)^n x^{2n}}{n!} } = \sum_{n=0} ^\infty { \frac{(-1)^n x^{2n + 1}}{(2n+1)n!} } .
$$
Answer: The power series for $F'(X)$ is $$F'(x) = \sum_0^\infty \frac{(-x)^{2n}}{n!} = \sum_0^\infty \frac{(-1)^nx^{2n}}{n!}$$
We now integrate each side and get:
$$
\begin{align}
F(X) &= \sum_0^\infty \frac{(-1)^n (x)^{2n+1}}{(2n+1)(n!)}
\end{align}$$

Finding a special power series


Usando mapas dinâmicos com a API do Google Maps

Question: Vejo os exemplos de como usar a API do Google Maps e geralmente nos exemplos em que vejo, sempre existe uma coordenada padrão(inicial).
Agora, digamos que eu venha a fazer um programa e distribuo esse aplicativo para vários clientes no Brasil, por exemplo.
Há uma forma de eu não fixar uma coordenada, mas que o programa sempre em for abrir o mapa, tenha sempre como start(default) as coordenadas do cliente?
Assim: Se você está em João Pessoa, num determinado bairro, ele começa por essa coordenada. Sei que isso é possível, pois há muitos aplicativos que faz isso. Como eu faria isso? Uso MVC5(VS 2013), C#.
Comment: acredito que você necessite apenas de HTML Geolocation para obter as coordenadas do navegador do cliente, e setar essas para o centro do mapa, esse [link](http://www.w3schools.com/html/html5_geolocation.asp) mostra como usar, não é muito preciso, mas ja ajuda
Answer: Não entendo bem como você vai usar o GoogleMaps API com C#, provavelmente vai ser um webView, não vou entrar em detalhes porque o webView pode ser algo Desktop ou WindowsPhone (ou outro tipo de dispositivo), pela tag asp-net-mvc suponho que seja web, talvez depois eu edite isso.
Se for mesmo web o asp.net-mvc é apenas a parte "back-end", no caso vou por um exemplo então apenas javascript para usar o Google-Maps a partir da posição inicial do usuário, veja um exemplo na própria documentação:

https://developers.google.com/maps/documentation/javascript/examples/map-geolocation

Você vai ter que usar navigator.geolocation.getCurrentPosition para obter a posição do usuário.

Notas:

Troque o YOUR_API_KEY pela sua chave (requer uma conta do google)
O navegador solicita uma permissão do usuário para permitir o rastreamento

<!DOCTYPE html>

    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

Comment: Não consegui abrir no browser e vi que há uma coordenada chumbada. A idéia é a página pegar as coordenadas local do usuário. O projeto é web e terá partes mobile, mas ainda não defini.
Answer: No exemplo que o @Guilherme Nascimento passou eu só trocaria a função initMap()
function initMap() {

  // Try HTML5 geolocation.
  if (navigator.geolocation) {

     navigator.geolocation.getCurrentPosition(function(position) {

        var myLatlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);

        var mapOptions = {
             center: myLatlng,
             zoom: 16,
        };

        var map = new google.maps.Map(document.getElementById("map"),
                        mapOptions);

     }
   }
 }

Desta forma só vai pegar a posição do usuario, porém se o usuário não permitir que use a localização dele você não terá mapa, ai vai ter que dar alguma mensagem para o usuário ou setar uma localização padrão.


Angular 6 - Installing ng-recaptcha gives error TS1005: ';' expected

Question: I want to use ReCaptcha V3 in my Angular 6 project so I have installed ng-recaptcha using the command
npm i ng-recaptcha --save as per the doc https://www.npmjs.com/package/ng-recaptcha#installation.
After the installation, the error "firstname.lastname@example.com requires a peer of @angular/core@^11.0.0 but none is installed" displayed but I don't want to upgrade "@angular/core" to 11.0.0 as my current project uses 6.1.0.
When I try to run the application it is giving the error
ERROR in node_modules/ng-recaptcha/recaptcha/recaptcha.component.d.ts(5,43): error TS1005: ';' expected
I am not sure whether any lesser version of ng-recaptcha will resolve my problem or not.
Please help
Answer: Version 6.1 of ng-recaptch needs Angular version 6 and up
  "peerDependencies": {
    "@angular/core": "^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0"
  },

https://github.com/DethAriel/ng-recaptcha/tree/v6.1.0
try to install it instead
Comment: Used version 6.1 of ng-Recaptcha and it solved the problem. Thanks for your detailed info.
Comment: firstname.lastname@example.com requires a peer of @angular/core@^11.0.0, meaning ng-recaptcha expects you to supply it with that dependency, but you supplied @angular/core@6.
When you downgraded to email@example.com you supplied @angular/core@6 which is a valid peer dependency of email@example.com
Comment: exactly, the latest version that is compatible with angular 6 of ng-recaptcha is version 6.1


How to Extract Transit Stop locations from Google Maps?

Question: I'm building an application that requires the name, long, and lat for the transit stops in my area.
Google Maps API displays this information, but in this scenario I can't use the API and need to extract this information to an XML format.
I'm not sure if this is possible and can't find any reference to this on the web.
Any Ideas how I can extract the transit stop long, lat, and name from Google Maps, preferably to an XML format?
Answer: Now it's possible to get this done, check this post:
Detect the nearest transit stop from the given location
And if you want to see it in action try this jsfiddle:
http://jsfiddle.net/doktormolle/aZrvs/


Aviso de erro no console ao rodar ionic app

Question: criei uma app pelo ionic creator. Tenho um form para cadastro e ao clicar em qualquer campo do formulário o seguinte aviso aparece no console:

'webkitMovementX' is deprecated. Please use 'movementX' instead. ........   ionic.bundle.js:1173

Já me deram a sugestão de atualizar o ionic, já atualizei a lib, também, e foi para a versão  Ionic, v1.2.4-nightly-1917, sendo que tem que ser a v1.2.4-nightly-2019, pelo que me falaram.
Quando tentei reinstalar o ionic, esse mensagem apareceu:

Atualizei o npm e uma cassetada de coisas foi atualizada tb.
E no final, aparece isso: Vcs veem os ERRS!?

Alguém teu alguma ideia ou sugestão?
Comment: Já atualizou o npm?
Comment: Como atualizo o npm @MarcoAurélioDeleu?
Comment: fazendo isso?
npm install -g npm?
Comment: Atualizei vários pacotes e não ajudou, quero dizer, atualizou muitos pacotes, mas o ionic.bundle.js
Answer: Eu já passei por um erro semelhante e pelo menos no meu caso era problema de permissão de usuário. Tente executar o seguinte comando:
sudo chown -R meuusuario /usr/local/lib/

Depois instale o cordova e o ionic:
npm install -g cordova ionic

Answer: Na sua aplicação você está usando a função "webkitMovementX" que está desatualizada, utilize a movementX.
Isso é só um aviso, não é um erro. Essa função pode ter problemas que na versão mais nova já foram corrigidos.
Comment: É bem provável que quem esteja usando a função obsoleta seja o próprio Ionic e não o autor da pergunta. Sua resposta não é relevância ao problema.
Comment: Não Lucas, não estou usando por conta própria essa função. É do próprio ionic.bundle.js
Comment: Obrigado por retornar, achei o link desse bug no ionic: https://github.com/driftyco/ionic/issues/4259
Comment: Esse link, infelizmente, não ajudou.


Unit-speed parametrization of $\langle t^2, t^3 \rangle$

Question: I need to do a change of variables ($t$ to $s$) for $r(t) = \langle t^2, t^3 \rangle$ such that the speed along the curve is always $1$. My trouble is in varifying that $||r'(s)|| = 1$.
$$ s(t) = \int_a^t ||r'(u)|| du = \int_a^t \sqrt{4u^2 + 9u^4} du = \int_a^t u \sqrt{(4 + 9u^2)} du$$
Letting $x = 4 + 9u^2$ then
$$\frac{1}{18}\int_{4 + 9a^2}^{4 + 9t^2} \sqrt{x} dx$$
$$ s(t) = \frac{1}{27}[(4 + 9t^2)^{3/2} - (4 + 9a^2)^{3/2}] $$
We can write $||r'(t)||$ as $\sqrt{t^2 (4 + 9t^2)}$ and from the previous equation we have
$$ 4+9t^2 = [27s + (4+9a^2)^{3/2}]^{2/3} $$
and
$$ t^2 = \frac{[27s + (4+9a^2)^{3/2}]^{2/3} - 4}{9} $$
So plugging these into $\sqrt{t^2 (4 + 9t^2)}$ gives me $||r'(s)||$ but I don't see how it reduces.
Answer: You do not verify that $\|r'(s)\|$ is one. What you verify is that the curve $\gamma(s)=r(t(s))$ has speed one w.r.t. the new time parameter $s$. Just write
$$
s(t)=\int_a^t\|r'(u)\|\,du
$$
so that $\frac{ds}{dt}=\|r'(t)\|$ and therefore $\frac{dt}{ds}=\frac{1}{\|r'(t(s))\|}\,.$ Then we have trivially by the chain rule
$$
\gamma'(s)=\frac{d}{ds}r(t(s))=\frac{d}{dt}r(t(s))\frac{dt}{ds}=\frac{r'(t(s))}{\|r'(t(s))\|}
$$
which has norm one.
Comment: Oh I see. The way I was verifying it missed the chain rule.
Comment: And $a$ can be anything as long $|| r'(t)|| $ isn't zero everywhere?
Comment: $a$ can be anything. The only condition we need is that $\|r'(t)\|$ is *nowhere* zero.
Comment: But my book says "If we assume that $||r′(t)||= 0$ for all $t$, then $s(t)$ is an increasing function of $t$. In this case, $s(t)$ has an inverse, which we denote $t = \phi(s)$..." It doesn't use that fact that it is nowehere $0$.
Comment: You and I defined $s(t)$ in exactly the same way. The book is obviously wrong or has a typo. A total no brainer.
Comment: That was a typo on my part. Should say $|| r'(t) || \neq 0$ for all $t$. Still, it's a weaker assumption than you are making.
Comment: In my first comment I made the assumption that $\|r'(t)\|$ is *nowhere* zero, in other words, *not zero for every* $t\,.$ Why is your assumption weaker ?
Comment: It's weaker because 'nowhere $0$ $\implies$ isn't $0$ everywhere' but 'isn't $0$ everywhere $\not\!\!\!\implies$ nowhere $0$'. I understand that your assumption is sufficient, I'm just pointing out that my book says it's not necessary. We can asume the weaker 'isn't $0$ everywhere' and still get the result.
Comment: Last attempt: Claim:  $f(t)\not=0\,\,\forall t\Leftrightarrow \{f=0\}=\emptyset$ ($f$ is nowhere zero). Proof. Assume $f(t)\not=0\,\,\forall t$ and that $\{f=0\}\not=\emptyset\,.$ Then there exists a $t$ such that $f(t)=0$. A contradiction. Conversely assume $\{f=0\}=\emptyset$ and that there exists a $t$ such that $f(t)=0$. Also a contradiction. Nothing is weaker.$\Box$


Effective method for Date.parse in javascript

Question: In a method, i am using Date.parse to convert the date to millisecond as below.
 Date.parse(Tue Apr 1 00:00:00 PST 1930);

but i am using it for 1000 points , so the execution time for Date.parse is 60ms(shown in profiler), i need to optimize it, is there any other way to do it or Date.parse is the only way?
Thanks in advance
Comment: I can't think of any other way of generating a `Date` from a `string` in JS. Where do you get the date strings from? Perhaps you could manipulate the output to be less verbose which should reduce the parsing time.
Comment: `new Date("Tue Apr 1 00:00:00 PST 1930").getTime()` could be an alternative, but not sure about its performance.
Comment: @Nikhil `new Date(...)` is the equivalent of `Date.parse(...)` so I can't imagine the performance will be any different.
Comment: @James then I also can't think of any other alternative for now.
Answer: Even custom parser of a predefined date's format is slower then direct date parsing: jsperf. May be you know what in a custom parser could be eliminated, or to try to get rid of the .split function by storing your dates direct in JSON format like {year:2013, date:1, month:11, hour: 11}.


In what contexts is the word "iff" actually used?

Question: When I took a proofwriting class, I was told that it was not appropriate for formal mathematical writing to abbreviate "if and only if" as iff. I've heard iff called "mathematical slang". And, indeed, I have never seen it used in a formal proof -- really only ever in online discussions of mathematics, as on StackExchange.
But it's apparently widespread enough to make it into general-purpose dictionaries. It doesn't really work in speech, so if it's not used in mathematical writing, where is it used?
Comment: It is used widely in mathematical proofs.
Comment: As for "*It doesn't really work in speech*"... despite it being spelled "iff" I still pronounce it as "if and only if" personally.
Comment: This sounds like personal preference and nitpickyness of editors.  There is little difference to me between the question of using "iff" versus "if and only if" and the question of using "won't" versus "will not."  I had some high school writing teachers who insisted that no contractions with apostrophes were to be used in work we handed in.  Once leaving that class however, I continue to see contractions used in many contexts including professional ones.
Comment: If your tutor doesn't like it, don't use it in the work you do for them. Otherwise it is well-understood and as precise as the longer expression it abbreviates, so there is no mathematical or logical loss in using it. The objection seems to me to be sociological rather than mathematical.
Comment: Some quick situations that come to mind are during presentations (when someone's writing on a board, e.g.) or informal chat discussions.
Comment: It is often used and is widely accepted and saves time while writing answers
Comment: Imho it shouldn't be used in proofs to be read by another person, because it can easily be misread as *if*. Its not a question of formality, it is a question of service to the reader.
Comment: Well, we had a [related dicussion on Meta](https://math.meta.stackexchange.com/q/30468/537079) before.
Comment: @JMoravitz That is, in fact, the pronunciation given in Merriam Webster's dictionary, which makes it the only word in English that has more syllables than letters.
Comment: I cannot say that I can recall ever having seen "iff" in a research level publication, and the only books in which I've seen it used are elementary texts where the notation "iff" is being defined (note:  this doesn't mean that "iff" doesn't appear in publications or more advanced texts, only that I cannot recall seeing it in this context).  On the other hand, the word(?) is frequently used in informal contexts, such as lecture notes.  It is a useful shorthand in that setting, but my preference is to see it expanded in more formal contexts.
Answer: The word "iff" is a shortcut for "if and only if". As such, it has the same status as "wlog" (without loss of generality), w.r.t. (with respect to) and "s.t." (such that). As these three examples, it is mostly used in one of the following circumstances:

During a lecture on a blackboard, when time is limited.
During a lecture using slides, when time and space are limited.
When you take handwritten notes, again to save time and space.

P.S. When I prepared this answer, I was almost sure to find some arguments in Halmos' paper [1], my favourite reference on mathematical writing. To my surprise, I found no mention of "iff" in [1], but I later realized that the neologism "iff" has been popularized by Halmos, who could then hardly give a strong opinion on his own creation... Quoting Halmos [2, p. 403]:

My most nearly immortal contributions are an abbreviation and a
  typographical symbol. I invented "iff", for "if and only if"- but I
  could never believe that I was really its first inventor. I am quite
  prepared to believe that it existed before me, but I don't know that
  it did, and my invention (re-invention'1) of it is what spread it
  through the mathematical world.

[1] Paul R. Halmos, How to write mathematics. Enseign. Math. (2) 16 (1970), 123--152.
[2] Paul R. Halmos, I want to be a mathematician. An automathography. Springer-Verlag, New York, 1985. xvi + 421 pp. ISBN: 0-387-96078-3


proper use of secondary dominant

Question: I'm writing a song--the photo posted below is the last two measures of the verse and the first measure of the chorus (this is a reduction). I wanted to create some extra tension before playing the A minor chord, so I figured I would play an E minor chord (the fifth of A) and add some 7th scale degrees in there (D note) to make it the dominant seventh chord for A. Did I execute this properly? The E minor chord sounds quite muddy.
I am just wondering if there are any ways to improve this sequence. Please let me know!

After fiddling a bit, this is where I'm at:

This sounds like an improvement to me. Thanks for the help!
Comment: A dominant seventh needs a major third, so you would want an E7 not an Em7 to have a dominant seventh chord.  In a sense, you've stumbled accidentally onto the reason for the harmonic minor scale existing; in order to have a dominant chord for A minor, we raise the G to G#.
Comment: As for your improvement: you can certainly have a C in the middle staff, but that creates more of an augmented V7 chord (the C is really understood as a B♯, a raise chordal fifth). But you could also replace that C with a B and see what you think. This would be the more "normal" V7, but that doesn't necessarily mean it's better!
Answer: As you have it now, it's just a simple fifth relationship. You're in the key of C, and you have iii7 moving to vi.
In order to have a secondary dominant (also called an "applied chord"), you want to temporarily use the leading tone of the chord you're moving to. You're moving to A (vi), so you want to actually use this key's leading tone (G♯) in that E chord.
Therefore, your Em7 chord will become E7 (E G♯ B D), and that chromatic addition of G♯ will add in the color I think you're looking for. You can experiment whether you want the G♯ to begin right on the downbeat of that measure (what I would recommend) or on the second half.
In making this Em7 an E7, we can now better analyze it as V7/vi. In this way, we show precisely how this chord is functioning: as a secondary dominant of vi. This label is much more informative than just calling it something like III7.
(And technically speaking, we tend to resolve chordal sevenths down by step. This means that D, the chordal seventh above E, will want to resolve down to C in the next chord. You do this in the middle staff, but it looks like the D in your top staff resolves up.)
As for the chord sounding "muddy," it may because of how you've voiced it. Notice that you have two Bs, two Ds, and only one G(♯) and one E. Typically you'll want to double the root (E) before you double anything else. Even changing the D in the middle staff to an E might make a big difference.
Comment: @286642 Honestly, there are so many different possible permutations that I can't think of a good source. Furthermore, I worry that the claims would be too opinion-based to be helpful. In general, we tend to double the root before anything else, and we can omit the chordal fifth whenever we like. Otherwise, I think the best I can do is recommend you just experiment with different things to get a sense of the sounds and what you think of them.
Comment: thanks for the awesome response @Richard. Do you know where I can learn more about the effects of different voicings of the same chord?
Answer: Secondary dominants are used to get to another chord other than the tonic. It could be just about any chord - in C, there's a good chance it'll be Am, Dm, Em or G as the main contenders.
That secondary dominant needs to be dominant. Therefore, it needs that leading note to the new chord. In your case, going to the Am, it needs to have a leading note to A, which is G#. G doesn't quite hack it. So, with that G#, (which is found in the Am key if that's an issue) and the D making a tritone, it resolves nicely to the Am.
If the chord you were going to was Em, then the secondary dominant would need to be B7, with a couple of non-diatonic notes necessary. That would be B7. And if you were getting to G, you'd need the leading note of F#, with a C, producing the tritone again which would be crying out to resolve to a G chord.
Answer: The mentioned sequence vi-iii-iii7-vi isn't a secondary dominant as usually used. A secondary dominant would usually be III7-vi (or V7/vi-vi to show the structure) without a preceding vi. A common use would be C-E7-a(perhaps followed by D7-G7-C) where the E7 is a secondary chord used as a dominant to an a-minor chord; the D7-G7-C is the most common secondary dominant replacing the ii-V7-I sequence.
There's nothing wrong with the original sequence (if it sounds good with the rest of the piece); it's not really a secondary dominant. Formally a secondary dominant is a major-minor chord built on the step above major or minor chord. It makes a local tonicization of the major or minor chord; if that chord isn't confirmed as representing a key (by playing a cadence there and "neutralizing" the tone or tones which differ from the home key), it's just a blip reinforcing the original tonality.
Answer: Well, going from a minor chord to its minor seventh is a very uncommon chord change. It's of course doable, but you may like other tension-building sounds better. It's difficult to add in a chord between the dominant and its resolution.
You may like changing the iii7 to III7 (E7), as usually the "dominant seventh" of a minor key refers to the dominant seventh chord, not the minor seventh. Additionally, if your song is in A minor, I'd suggest analyzing in A minor rather than C major. If it's in C, you're good. Alternatively, you could change the iii to a chord with subdominant function, say iv or VI, maybe even the minor ii-V (B half-diminished 7 to E7 in A minor). The main problem I see is the fact that only one note changes through the iii-iii7 movement, usually not ideal when the chords have the same root.
Unusual chord movements are also on the table, such as, depending on how the unreduced version of the song goes,

IV7-III7 (F7-E7)
♭VII-III7 (B♭-E7)
♭VI-III (A♭-E)
III+7 - III7 (Em-E+)

My suggestion is to change one or more of the chords in order to create more movement, as generally that E-D movement sounds pretty weak. Good luck with the song!
Comment: Secondary dominants are more usually written as such - V/ii, V/iii, V/V. Labelling as VI, VII, II respectively doesn't really label them as secondary dominants, but rather as a minor diatonic chord change to major.
Comment: True, but as I don't see OP specifically asking how to create a secondary dominant, and with regard to harmony, I suggested analysis in A minor, so my suggestion was basically just the dominant of A minor and not a secondary in C major. EDIT: I just saw the words "Secondary Dominant" in the title of the question. My apologies to Tim. Anyway, I revise my opinion to that OP is not describing a secondary dominant and is really writing in A minor.
Comment: @user45266 thanks for the suggestions! I tried implementing your first one. Let me know what you think! (see update). Thanks!

proper use of secondary dominant


Need to limit INPUT PSH+ACK packets

Question: I have several HEAD queries a week that look like this (I assume that this is some kind hack attempt):

289 24133.787750 184.108.40.206 -> 220.127.116.11 HTTP 118 HEAD / HTTP/1.1
290 24133.987861 22.214.171.124 -> 188.8.131.52 TCP 118 [TCP Retransmission] 53341 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
291 24134.215884 188.8.131.52 -> 220.127.116.11 TCP 118 [TCP Retransmission] 53341 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
292 24134.442721 22.214.171.124 -> 126.96.36.199 TCP 118 [TCP Retransmission] 36843 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
293 24134.671833 188.8.131.52 -> 126.96.36.199 TCP 118 [TCP Retransmission] 53341 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
294 24135.583822 18.104.22.168 -> 126.96.36.199 TCP 118 [TCP Retransmission] 53341 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
295 24136.110698 126.96.36.199 -> 126.96.36.199 TCP 118 [TCP Retransmission] 36843 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
296 24137.411821 18.104.22.168 -> 184.108.40.206 TCP 118 [TCP Retransmission] 53341 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
297 24139.442873 220.127.116.11 -> 184.108.40.206 TCP 118 [TCP Retransmission] 36843 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
298 24141.063860 220.127.116.11 -> 126.96.36.199 TCP 118 [TCP Retransmission] 53341 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
299 24146.114817 220.127.116.11 -> 184.108.40.206 TCP 118 [TCP Retransmission] 36843 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
300 24148.375866 22.214.171.124 -> 126.96.36.199 TCP 118 [TCP Retransmission] 53341 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
301 24159.458755 18.104.22.168 -> 220.127.116.11 TCP 118 [TCP Retransmission] 36843 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
302 24162.983859 184.108.40.206 -> 184.108.40.206 TCP 118 [TCP Retransmission] 53341 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
303 24186.146998 184.108.40.206 -> 184.108.40.206 TCP 118 [TCP Retransmission] 36843 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
304 24192.231838 22.214.171.124 -> 18.104.22.168 TCP 118 [TCP Retransmission] 53341 → 80 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=5
305 24192.839296 22.214.171.124 -> 22.214.171.124 TCP 66 80 → 36843 [FIN, ACK] Seq=1 Ack=1 Win=14592 Len=0
306 24192.847089 22.214.171.124 -> 184.108.40.206 TCP 66 36843 → 80 [FIN, ACK] Seq=53 Ack=2 Win=29312 Len=0
307 24192.847545 184.108.40.206 -> 18.104.22.168 TCP 54 80 → 36843 [RST] Seq=2 Win=0 Len=0

I have this iptables entry to drop the HEAD request:

iptables -A INPUT -m string --string "HEAD " --algo bm --to 300 -j DROP

  It doesn't seem to be being dropped because of the subsequent burst of [PSH, ACK] packets.  Possibly the #305 [FIN, ACK] is the drop.  What I want to do is stop or limit the [PSH, ACK] packets that are always after the HEAD request.  I tried this, but it gave some sites a problem getting into my web pages:

iptables -A INPUT -p tcp --tcp-flags ALL SYN,ACK -j DROP

  I thought I might try this:

iptables -A INPUT -p tcp -m multiport --dports 80,443 --tcp-flags ALL PSH,ACK -m limit --limit 10/s --limit-burst 2 -j DROP

 but I would like some advise before I manage to block legitimit web page inquiries.  Thanks.
Answer: A HEAD request is a completely valid HTTP request which simply returns the HTTP Headers without the actual content body.
Aside from the fact that HEAD requests are part of the HTTP standard, blocking them to deny potential attackers your HTTP header information is pointless because they could just as easily make a GET request and retrieve the same information. In fact, blocking HEAD requests could actually increase your bandwidth consumption because now the attackers have to make a full GET request rather than a low bandwidth HEAD request.
The reason you are seeing the TCP retransmissions is because you are dropping the HEAD request without sending any response back. The device which sent the HEAD thinks that its request never got through so it tries again...and again and again until the connection eventually times-out.
As you have already found out, dropping packets SYN, ACK packets is a terrible idea because you are breaking the TCP handshake and will prevent clients from connecting to your server. Dropping or rate limiting PSH, ACK packets is also not a good idea.
As long as you follow basic principles of security on your server, you should have no need to block access to HEAD requests and no matter what steps you take you will always see automated access attempts probing your server for weakness.
If you are insistent on dropping HEAD requests, your best bet would be to REJECT the requests with a TCP RST rather than silently dropping them. So rather than -j DROP, use -j REJECT --reject-with tcp-reset. This will forcibly tear down the TCP connection.
Comment: Good advice. Though I think there is one caveat to the use of `-j REJECT --reject-with tcp-reset`. I believe that will only send a RST packet to the client causing the connection to be cleaned up on the client side. That would leave the connection open on the server side with no client to tell it otherwise. That connection would stay around until the http server times out the connection. It could stay around forever if the http server does not time out connections. Still using `REJECT` is pretty much always going to work better than `DROP`.
Comment: Good catch, I never considered that.
Comment: Will remove the HEAD drop.  I was not familiar with what it did and as you suggest, pointless to drop.

Need to limit INPUT PSH+ACK packets


Dúvida para remover atributos JavaScript

Question: Dado o seguinte objeto:
var pessoa = {
    nome: 'Fernando',
    idade: 15,
}

Gostaria de saber qual o jeito mais CORRETO(se é que existe um jeito mais correto) de se remover um desses atributos.
Answer: Você pode usar o operador delete:

var pessoa = {
    nome: 'Fernando',
    idade: 15,
};

// verifica se nome existe
if (pessoa.nome)
 delete pessoa.nome;

console.log(pessoa);
Comment: Nem precisa verificar se existe, o delete só vai lançar exceção se a a propriedade não for deletável (e ainda assim só propriedades customizadas, não-nativas).
Comment: Hmmm, entendi. Mas existe algum jeito correto?? Ou não tem isso?
Comment: Eu não conheço outra forma de remover uma chave de um objeto além do delete. Se não tiver certeza quando se a chave existe, seria interessante usar `pessoa['nome'];`. Essa é a forma padrão.
Comment: Um amigo falou pra eu fazer "pessoa.idade = undefined". Isso tá certo?? Pode trazer algum problema?
Comment: Isso é para verificar se o atributo existe. Se você quiser verificar se ele existe antes de deletar por exemplo, é possível fazer: `if (pessoa.idade) delete pessoa.idade`. O que acontece aqui, é que ele só vai deletar se existir.
Comment: @fernandoocf O seu amigo te falou para mudar o valor da propriedade para undefined. Isso é diferente de remover a propriedade do objeto, só remove o valor.
Comment: Obrigado! @bfavaretto


i am not getting month/year slider using jquery

Question: i want to get month/year picker slider on right side of my website.i got a code from one site.it is working,but after i download its not working.i added jquery.js folder.is it right.please help..my code is

    Date :
    <input name="myDate" class="monthYearPicker" />

please help.whicj jquery i have to include?jquery.js or jquery.min.js?
Comment: Remove `src` from second `
Comment: Don't include compressed as uncompressed jquery. Include onlye one of them. Include jquery ui files also.
Comment: i  removed  src,but it s not working
Comment: press `F12` and check for console errors
Comment: Other then that its working fine!! check it **[here](https://jsfiddle.net/Guruprasad_Rao/Lyw2h0nz/)** and I hope `ui-datepicker-calendar` is a class so you need to refer with `.` preceeding while applying styles in CSS as I have in my demo.
Answer: You have to include correct files:
HTML:

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">

Date :
<input name="myDate" class="monthYearPicker" />

JS:
$(function () {
    $('.monthYearPicker').datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy'
    }).focus(function () {
        var thisCalendar = $(this);
        $('.ui-datepicker-calendar').detach();
        $('.ui-datepicker-close').click(function () {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            thisCalendar.datepicker('setDate', new Date(year, month, 1));
        });
    });
});

Demo: http://jsfiddle.net/lotusgodkk/GCu2D/797/
Comment: if i want to display this month/year picker page on load what i have to do
Comment: Change the label to the div. The datepicker will show on load. OR just trigger focus on the input on load.
Comment: when on load displaying calendar also.i just want a month/year portion only,below calendar i dont want,please guide


How to scrape an interactive charts with scrapy?

Question: I'm using scrapy to scrape and crawl webpages.
I am interested in how to scrape this page. As you can see there are several charts. But when I look at the source code, I do not find the values of the points, even when I search in the


Centering on Twitter Bootstrap doesn't work

Question: I thought text-align works in Twitter Bootstrap but it doesn't? I'm not sure what's going on. Is there an alternative to centering or am I just going to have to use margin? Sorry for the overkill with the style text-align. I just wanted to make sure I wasn't missing anything.

Skills

Music

Things I Read

Answer: I think it might be because bootstrap sets the anchors to be display: block. Text alignment works on inline and inline-block elements. Have you otherwise customized the bootstrap css? The nav pills should have the text centered anyway, unless you've specified a width, because it should just be adding even padding to the block-level anchor element.
Comment: Solved. Thanks for the try though.
Comment: Take that back, I need nav-pills. I haven't made any width changes nor messed with bootstrap css.
Comment: Is it that you want to center the pills in the container, or the text inside the pills?
Comment: to center the nav div on the page itself.
Comment: Then text-align:center definitely won't work, it's for text alignment, not for centering block-level elements. Are your nav pills always going to have the same width or be the same number? They're all set to float: left, so if you change the container width and set an offset, you can "center" it and still be using the bootstrap grid, like:  instead of
Comment: The problem I realized with using offset was that it doesn't center it exactly. It's always off by just a little bit. Should I use offset and then set a margin to adjust it accordingly?
Comment: Fixed it. Just used margin 0 auto, float none, and set a width. Thanks for the help.
Comment: Yeah I've run into the same issue before; and I agree the offset solution isn't really centering it either. :-/ found this, anyway, in my googling: http://jsfiddle.net/rfkrocktk/hcQ48/