Batch Script for service restart and alerting over email

Question: Please let me know what i am doing wrong in my code. I am trying to check a set of Services starting with specific set of name. And triggering an email if service is in stop state. I have made a loop where in it will traverse. But i am not able to end that loop.
setlocal

:loop
@for /f "tokens=1*" %%a in ('sc queryex state^=inactive ^| findstr /r /c:"DISPLAY_NAME:.*ASP"') do net start "%%b" && goto :mail

:mail
set Port=25
set SSL=False
set From="firstname.lastname@example.com"
set To="firstname.lastname@example.com"
set Subject="Subject line"
set Body="Email Body in one line"
set SMTPServer="smtp.gmail.com"
set User="email@example.com"
set Pass="1234567"

if "%~7" NEQ "" (
set From="%~1"
set To="%~2"
set Subject="%~3"
set Body="%~4"
set SMTPServer="%~5"
set User="%~6"
set Pass="%~7"
set fileattach="%~8"
)

set "vbsfile=%temp%\email-bat.vbs"
del "%vbsfile%" 2>nul
set cdoSchema=http://schemas.microsoft.com/cdo/configuration
echo >>"%vbsfile%" Set objArgs       = WScript.Arguments
echo >>"%vbsfile%" Set objEmail      = CreateObject("CDO.Message")
echo >>"%vbsfile%" objEmail.From     = %From%
echo >>"%vbsfile%" objEmail.To       = %To%
echo >>"%vbsfile%" objEmail.Subject  = %Subject%
echo >>"%vbsfile%" objEmail.Textbody = %body%
if exist %fileattach% echo >>"%vbsfile%" objEmail.AddAttachment %fileattach%
echo >>"%vbsfile%" with objEmail.Configuration.Fields
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendusing")        = 2 ' not local, smtp
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpserver")       = %SMTPServer%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpserverport")   = %port%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpauthenticate") = 1 ' cdobasic
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendusername")     = %user%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendpassword")     = %pass%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpusessl")       = %SSL%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpconnectiontimeout") = 30
echo >>"%vbsfile%"  .Update
echo >>"%vbsfile%" end with
echo >>"%vbsfile%" objEmail.Send

cscript.exe /nologo "%vbsfile%"

echo email sent (if variables were correct)
del "%vbsfile%" 2>nul
goto :loop

Comment: If my answer was helpful, please consider marking it as accepted. [See this page](http://meta.stackexchange.com/questions/5234/) for an explanation of why this is important.
Answer: You may be interested in sending an email even if the net start command fails. Then, your script could be improved as follows (given merely a template):
This approach applies CALL command (call  a subroutine). To exit the subroutine specify GOTO:eof:
@ECHO OFF
SETLOCAL EnableExtensions

set Port=25
set SSL=False
set From="firstname.lastname@example.com"
set To="firstname.lastname@example.com"
set "Subject=Subject line"
set "Body=Email Body in one line"
set SMTPServer="smtp.gmail.com"
set User="email@example.com"
set Pass="1234567"

if "%~7" NEQ "" (
  set From="%~1"
  set To="%~2"
  set "Subject=%~3"
  set "Body=%~4"
  set SMTPServer="%~5"
  set User="%~6"
  set Pass="%~7"
  set fileattach="%~8"
)

@for /f "tokens=1*" %%a in ('
      sc queryex state^=inactive ^| findstr /r /c:"DISPLAY_NAME:.*ASP"
  ') do (
       set "aServiceFound=%%b"
       REM Success or failure are based on the Exit Code of the `net start` command
       net start "%%b" && set "aServiceLuck=started" || set "aServiceLuck=failed"
       CALL :mail
        )
goto :endloop

:mail
REM Handle `net start` success/failure here
REM add %aServiceFound% and %aServiceLuck% to the email subject and/or body
set Subject="%aServiceLuck%: %aServiceFound%  %Subject%"
set Body="%aServiceLuck%: %aServiceFound%  %Body%"

set "vbsfile=%temp%\email-bat.vbs"
del "%vbsfile%" 2>nul

REM script continues here (creating and running the %vbsfile% script) …

echo email sent (if variables were correct)
del "%vbsfile%" 2>nul
REM goto :loop
goto :eof

:endloop

Read the Redirection article for explanation how && and || work.
Edit after comments all before 2019-02-13 16:14:11Z: The following batch generates a .vbs script which is free of any Microsoft VBScript compilation error:
@ECHO OFF
SETLOCAL EnableExtensions
REM set "Port=25" => error "530 5.7.0 Must issue a STARTTLS command first"
set "Port=465"
set "SSL=False"
set "email@example.com"
set "firstname.lastname@example.com"
set "Subject=Subject line"
set "Body=Email Body in one line"
set "SMTPServer=smtp.gmail.com"
set "email@example.com"
set "Pass=1234567"

@for /f "tokens=1*" %%a in ('
      sc queryex state^=inactive ^| findstr /r /c:"DISPLAY_NAME:.*ASP"
  ') do (
       set "aServiceFound=%%b"
       REM Success or failure are based on the Exit Code of the `net start` command
       2>NUL net start "%%b" && set "aServiceLuck=started" || set "aServiceLuck=failed"
       CALL :mail
        )
goto :endloop

:mail
REM Handle `net start` success/failure here
REM add %aServiceFound% and %aServiceLuck% to the email subject and/or body
set "Subject=%aServiceLuck%: %aServiceFound%  %Subject%"
set "Body=%aServiceLuck%: %aServiceFound%  %Body%"

set "vbsfile=%temp%\email-bat.vbs"
del "%vbsfile%" 2>nul
set "cdoSchema=http://schemas.microsoft.com/cdo/configuration"
echo >>"%vbsfile%" Set objArgs       = WScript.Arguments
echo >>"%vbsfile%" Set objEmail      = CreateObject("CDO.Message")
echo >>"%vbsfile%" objEmail.From     = "%From%"
echo >>"%vbsfile%" objEmail.To       = "%To%"
echo >>"%vbsfile%" objEmail.Subject  = "%Subject%"
echo >>"%vbsfile%" objEmail.Textbody = "%body%"
if exist "%fileattach%" echo >>"%vbsfile%" objEmail.AddAttachment "%fileattach%"
echo >>"%vbsfile%" with objEmail.Configuration.Fields
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendusing")        = 2 ' not local, smtp
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpserver")       = "%SMTPServer%"
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpserverport")   = %port%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpauthenticate") = 1 ' cdobasic
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendusername")     = "%user%"
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendpassword")     = "%pass%"
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpusessl")       = %SSL%
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpconnectiontimeout") = 30
echo >>"%vbsfile%"  .Update
echo >>"%vbsfile%" end with
echo >>"%vbsfile%" objEmail.Send
                              rem `Wscript.Echo` merely for debugging purposes
echo >>"%vbsfile%" Wscript.Echo "Email Sent"

cscript.exe //nologo "%vbsfile%"
goto :eof

:endloop

Comment: Hi JosefZ, Thanks for the revert but i am getting the below error.
Comment: C:\Users\genesys\AppData\Local\Temp\email-bat.vbs(5, 56) Microsoft VBScript compilation error: Expected end of statement
Comment: @Anonymous take a look into the `%temp%\email-bat.vbs`. Note that it's a better practice to _define_ a variable using double quotes  as follow: `set "Subject=Subject line"` and then _use_ it's value (which isn't double-quoted in that case) double-quoted _if necessary_ e.g. as follows: `>>"%vbsfile%" echo objEmail.Subject  = "%Subject%"`.
Comment: i didnt get you...@Josefz..
Comment: @Anonymous Simply check the 5th line in the `.vbs` script for unbalanced double quotes using e.g. `notepad "%temp%\email-bat.vbs"` (use your preferred plain text / code editor instead `notepad.exe`). Answer updated.
Comment: Thanks All...I have utilized the answer,there is an upgrade in above question. For now what if there are multiple services in inactive state, but usually mail is triggered only for the service.


Show that $g$ can be extended to a holomorphic function on $\mathbb{D}$.

Question: Let $g$ be a holomorphic function on $\mathbb{D}\setminus\{0\}$, and denote $g_m(z)=g(z/m)$ for each positive integer $m$. Suppose that $\{g_m\}_{m=1}^{\infty}$ has a subsequence $\{g_{m_k}\}_{k=1}^{\infty}$ which is uniformly bounded by 1 on the circle $\{z;|z|=1/2\}$, i.e., $$\max_{|z|=1/2}|g_{m_k}(z)|\leq 1\quad \text{for all $k\geq 1$}.$$ Show that $g$ can be extended to a holmorphic function on $\mathbb{D}$.
It follows by Montel's Theorem that $\mathcal{F}:=\{g_{m_k}\}_{k=1}^{\infty}$ is a normal family of holomorphic functions. So there exists a subsequence $\mathcal{F}_j:=\{g_{m_{k_j}}\}_{j=1}^{\infty}$ that converges uniformly to a holomorphic $h$ on all compact subsets of the disc $\{z;|z|\leq 1/2\}$.
I'm not sure if this is the right direction.
Answer: Apply MMP to the annulus between the circles of radii $\frac 1 {2m_k}$ and $\frac 1 {2m_{k+1}}$. Do you see now that $g$ is bounded near $0$?.
Comment: @Sham Since $m_k \to \infty$ the union of these annuli is the set $\{z: 0<|z|<\frac 1 {2m_1}\}$. So $g$ is bounded on this set which implies that it has a removable singularity at $0$.
Comment: So here you are supposing that $g$ is unbounded in a neighborhood of 0. Why is it sufficient to suppose there is a subsequence $\zeta_k\to 0$ such that $|g(\zeta_k)|\to \infty$?
Comment: I have edited my answer. @sham
Comment: By the MMP we have $$|g(z)|\leq 1$$ for all $\frac{1}{2m_{k+1}}<|z|<\frac{1}{2m_k}$. This must be true for all positive integers $m_k$


How do we reach the answer to the following recursive problem?

Question: $\large{a_{n+1} = \frac{a_n}{n} + \frac{n}{a_n}, a_1 = 1}$
Let the sequence $\large{\left< a_n \right>}$ be defined as above for all positive integers n. Evaluate $\large{\left \lfloor a_{2015} \right \rfloor}$.
I wrote a C++ program to solve the problem but I've no idea how to mathematically approach it.
Thanks in advance!
Comment: Can you share with us your program's result or any other thoughts?
Comment: Sorry, I forgot to add that the correct answer is **44** according to the output of the program.
Answer: If we let $x_n=a_n/\sqrt n$ then we have the recursive rule for $x_n$:
$$
x_{n+1}={x_n\over\sqrt{n(n+1)}}+{1\over x_n}\sqrt{n\over n+1}.
$$
It is easy to prove that $\lim_{n\to\infty}x_n=1$, so that $a_n/\sqrt{2015}$ should be very close to $1$. In other words we may conclude that
$$
\lfloor a_{2015} \rfloor = \lfloor \sqrt{2015} \rfloor=44.
$$
Comment: How exactly do you prove that $\displaystyle \lim_{n \to \infty} = 1$ ?
Comment: The proof is standard but quite cumbersome, so I've thought of another simpler approach, see my second answer.
Answer: This is close to the Babylonian method or Newton's method for computing $\sqrt n$  You use $a_{n-1}$ (which will be close to $\sqrt{n-1}$) as a starting guess and do one iteration.  If you want, you can show that the error is positive, decreasing, and (after a while) bounded by a small enough fraction that you know $44 \lt a_{2015} \lt 45$
Added:  a little experimentation shows that $a_n$ is a little greater than $\sqrt n$.  For example, $a_{16} \approx 4.06653$.  Define $b_n=a_n-\sqrt n$.  If $\frac 1n \lt b_n \lt \frac 1{\sqrt n}$ (as is true for $n=16$), we can approximate $$b_{n+1}=\frac n{a_n}+\frac {a_n}n-\sqrt n\\
b_{n+1}=\frac n{b_n+\sqrt n}+\frac{b_n+\sqrt n}n-\sqrt n\\
\approx \sqrt n(1-\frac {b_n}{\sqrt n})+\frac 1{\sqrt n}+\frac {b_n}n-\sqrt n\\
=-b_n+\frac 1{\sqrt n}+\frac {b_n}n\\
\approx\frac 1{\sqrt{n+1}}+\frac 2{n^{3/2}}-b_n+\frac {b_n}n$$  We need to argue that $\frac 1{n+1} \le b_{n+1} \lt \frac 1{\sqrt {n+1}}$, but I can't quite get there.  It seems clear, and this gives us an induction that says $b_n$ is small and $a_n \approx \sqrt n$
Comment: how do i prove that $a_{n-1}$ is close to $\sqrt{(n-1)}$ ?
Comment: You can just compute, say, $a_{16} \approx 4.06653$.  Define $b_n=a_n-\sqrt n$, so $b_{16} \approx 0.6653$  I believe you can prove that $b_n$ is decreasing by following through the calculation.  You will probably have to use the Taylor series for $\sqrt {1+1/n}$
Answer: It is probably easier to prove directly by induction that $\sqrt{n-1}\le a_n\le\sqrt{n+2}$ from some $n$ onwards.
We must prove at first that $a_{n+1}\le\sqrt{n+3}$, which is equivalent to $a_n/n+n/a_n\le\sqrt{n+3}$. But by the inductive hypothesis $a_n/n+n/a_n\le\sqrt{n+2}/n+n/\sqrt{n}$, so that we are left to prove that $\sqrt{n+2}/n+\sqrt{n}\le\sqrt{n+3}$. This last inequality boils down to $\sqrt{1+2/n}(\sqrt{1+3/n}+1)\le3$, which is true for $n\ge4$.
In a similar way, to prove that $a_{n+1}\ge\sqrt{n}$ one must prove $\sqrt{n-1}/n+n/\sqrt{n+2}\le\sqrt{n}$. After some tinkering this is equivalent to $\sqrt{1+(3n-2)/n^2}(1+\sqrt{1+2/n})\ge2$, which is true for $n\ge1$.
In the end we get then $\sqrt{2014}\le a_{2015}\le\sqrt{2017}$, that is $44.878\le a_{2015}\le44.911$.


document.getElementsByTagName:Cannot read property 'style' of undefined

Question: I wanna make a varible shortcut $$() so that i can use shortcut like $() [jquery] to save code in my project(ALL MY CODE IS PURE JAVASCRIPT).
when i put the string of id or class, it works all right, but when i put the tagName, it shows  Cannot read property 'style' of undefined, it seems that the code is right,help,thanks
One more, is that way to defined a shortcut variable $$() to use in pure javascript environment right way? or is there any best practice to define a global variable like this?

    window.onload = function(){
 function $$(ele){
   var pattern1 = /#/g;
   var pattern2 = /\./g;
   var pattern3 = /!/g;
        var matches = ele.match(/[^#\.!]/g);//array
        var elementS = matches.join("");

        //alert(matches+elementS);
         // console.log(document.getElementsByTagName(elementS));

        var spaceExist = /\s/.test(elementS)
   if(pattern1.test(ele)){
    return document.getElementById(elementS);

   }else if(pattern2.test(ele)){
    //console.log(elementS);
    return document.getElementsByClassName(elementS);

   }else if(pattern3.test(ele)){
    alert('hi');
    console.log(elementS);
    return document.getElementsByTagName(elementS);
   }else if(spaceExist){
    return document.querySelectorAll(elementS);
   }
  }
  $$('#hme').style.backgroundColor = 'red';
  $$('.myp')[0].style.backgroundColor = 'green';
  $$('!h2')[0].style.display = 'none';//this not work,shows Cannot read property 'setAttribute' of undefined
}

hi,friend

mmdfdfd

hhhhhh

Comment: Note that dot has a special meaning in regex, it matches any character. If you wan to match `.` literally, you have to escape it with a backslash: `\.`.
Comment: @Gothdo, just fix it and still cannot fix my problem,thanks
Answer: Have you stepped through your code? Look at pattern #2:

var pattern2 = /./g;

That pattern will match any character at all given that's what the period represents in regular expressions - ref: http://www.regular-expressions.info/dot.html.
Therefore, this conditional is satisfied and returns its result:
else if(pattern2.test(ele)){
    return document.getElementsByClassName(elementS);
}

Given there appears to be no element with a class name of h2 (which is the value of elementS), the return value is undefined.
Given that undefined has no properties, interrogating for the style property will produce the error you are seeing.
Comment: thanks for your answer. i just fixed it from pattern2 = /./g to pattern2 = /\./g, but still cannot work.
Comment: It wouldn't, given you have `alert(hi);` in the conditional block that will execute... `hi` isn't a variable name, so it will bomb out. Delete that line.
Comment: @franklee Spend some time getting to know how Chrome's dev tools work, they will save you a bunch of time in future: https://developer.chrome.com/devtools/docs/javascript-debugging
Comment: Thanks for your advice^_^
Answer: My advise is use one shortcut since you already using querySelectorAll:
window.$ = document.querySelectorAll.bind(document)

or if you rather need first element
window.$ = document.querySelector.bind(document)

this way you'll be able to do everything you are doing with normal css selectors and not obfuscated !tag for just tag
If speed actually matters, you will save some ticks by just having two aliases:
window.$ = document.querySelector.bind(document)
window.$el = document.getElementById.bind(document)

and calling $el when you need it specifically, instead of trying to make method polymorph.
Comment: It's just about the speed. getElementById is faster,i think . so i coded all the possibilities.querySelectorAll is for circustances when i input a string with a whitespace in it. By the way , i have get first node and then get style of it if you look at my code,thanks
Comment: @franklee Have you tried to profile it?  The way to deal with it is to cache references to nodes and not touching DOM when not nessessary, instead of writing obfuscated language which you anyway fallback to css selectors.
Comment: @franklee just fyi: https://jsperf.com/getelementbyid-vs-queryselector/233 try to run it. also see they are using `charAt` which is blazing fast compared to regex.
Comment: ,interesting. So by this example of the url, what you mean is we donot need to write a shortcut like $$() to map getElementById() but directly code  getElementById(), right?
Comment: yes,  your code to execute 3 regexes to call one method or another is bigger performance hit than using one method or another.
Comment: So in your edited answer above, we can use $el('theid') to represent docuemnt.getElementById('theid'), which is faster than give it a function to represent it?
Answer: Mister Epic's answer spots the main issue.  Your h2 call is getting caught in that if statement, and that's why your error is happening.  You need to make sure it doesn't get caught there, either by creating another pattern, or specifying in your second if statement that your 'ele' doesn't contain an '!'.
After that, in your third if statement:
else if(pattern3.test(ele)){
        alert(hi); <---
        console.log(elementS);
        return document.getElementsByTagName(elementS);

The problem with this is you're going to alert(hi), but hi isn't defined.  Make sure you wrap it in quotes.
Should be looking good after that.


ios uiimageview tap gesture not working during animation

Question: I have a UIImageView that is animated and receiving a UITapGestureRecognizer. The problem is while animated, the tap gesture area doesn't move with the view. I can tap the view's original location and the tap gesture is recognized. Anyone know how to have the tap recognized while the view is moving and not at its original position?
Edit 1:
This is how I've set up my tap gesture recognizer:
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapRecognizer.cancelsTouchesInView = YES;
    tapRecognizer.numberOfTapsRequired = 1;
    tapRecognizer.delegate = (id)self;
    [imageView addGestureRecognizer:tapRecognizer];
    imageView.userInteractionEnabled = YES;

Is there a way to have the gesture recognizer follow my view on its path since my animation lasts a couple seconds? Have I missed a setting?
Edit 2:
This is my code to set up my animation:
    double width = backgroundImageView.frame.size.width;
    double height = backgroundImageView.frame.size.height;

    CGMutablePathRef path = CGPathCreateMutable();
    double startX = -imageView.frame.size.width;
    double startY = height/4;
    double endX = 3*width;
    double endY = 0;
    double duration = 40;
    CGPathMoveToPoint(path, NULL, startX, startY);
    CGPathAddLineToPoint(path, NULL, endX, endY);
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.duration = duration;
    animation.path = path;
    animation.repeatCount = HUGE_VALF;
    [imageView.layer addAnimation:animation forKey:@"theAnimation"];

Comment: can you show the code of animation ?
Comment: I added the code I have for setting up my animation.
Comment: I tried a test by animating a UIButton on a path and it does the same thing. If I make the animation last 30 seconds, the whole time its moving, I can tap on its original spot and it will be "as if" the button is not animated.
Answer: For anyone interested, I solved my problem. Simply use an NSTimer, check and update the UIImageView's frame from the presentation layer by:
CGRect viewLocation = [[[imageView layer] presentationLayer] frame];
imageView.frame = CGRectMake(viewLocation.origin.x, viewLocation.origin.y, viewLocation.size.width, viewLocation.size.height);

After that, touches work wherever my image view is :-)


Obter número de seguidores no instagram com PHP

Question: Tenho o seguinte código:
<code>$username = 'makeup.pro.br';
        $response = @file_get_contents( "https://www.instagram.com/$username/?__a=1" );

        if ( $response !== false ) {
            $data = json_decode( $response, true );
            if ( $data !== null ) {
                $full_name = $data['graphql']['user']['full_name'];
                $follower  = $data['graphql']['user']['edge_followed_by']['count'];
                echo "{$full_name} have {$follower} followers.";
            }
        } else {
            echo 'Username not found.';
        }

        die();
</code>
Ele funciona perfeitamente em localhost. Porém quando coloco no ar, ele não trás nada, não funciona.
Não estou conseguindo achar o motivo de não funcionar no ar.
Comment: Há alguma mensagem de erro nos logs do servidor? Qual é o valor de `$response` e `$data`?
Comment: Tira o `@` do `@file_get_contents`. Não faz sentido você omitir qualquer mensagem de erro quando você não sabe o que está errado.
Comment: Já fiz isso. Não funcionou também.
Comment: Quando dou um echo $response; em localhost, ele me trás um json com as informações da página, mas no ar, ele apenas me trás uma página em branco com o símbolo do Instagram e nada mais. Será que pode ser alguma configuração do meu servidor na nuvem?
Comment: Ao invés do `echo` use `var_dump($response); exit;`
Comment: Com o var_dump, me retornou isso: string(38297) " "
Comment: Ok, agora olhe o código fonte da página. Está retornando um HTML ou XML que o navegador está tentando processar.
Comment: Ta tentando processar um HTML: string(38304) "

Login • Instagram

 ...
Answer: Consegui resolver.
Entrei em contato com o suporte da minha hospedagem e me disseram para fazer o comando dessa forma:
<code>$response = file_get_contents($value->instagram_link . "?__a=1", false, stream_context_create(['socket' => ['bindto' => '0: 0']]));
</code>


Integral formulas for sinus and cosinus: $\int_0^{π}\cos(nx)\cos(mx)dx,\,\int_0^{π}\sin(nx)\sin(mx)dx$

Question: Consider the formulas
$$\int_0^{2π} \cos(nx) \cos(mx)\, dx = 0$$ and $$\int_0^{2π} \sin(nx) \sin(mx) \, dx = 0$$
for $m, n \in \mathbb{N_0}, m ≠ n$.
These formulas can be proven when given the integral $\int_0^{2π} e^{ikx} \, dx = 0$ for $k \in \mathbb{Z}$.
However, why do the two formulas on top still hold if we replace $2\pi$ via $\pi$? Because as far as I've tried, $\int_0^{π} e^{ikx} dx$ isn't always equal to zero anymore. It would be nice if someone could elaborate why this is the case :)
Comment: *Hint:* Rederive those integrals using instead $\cos(a \pm b) = \cos a \cos b \mp \sin a \sin b$.
Answer: Assume that $m$, $n$ are integers such that $m\neq-n$ and $m\neq n$.
You may observe that
$$
\begin{align}
\int_0^{\pi}\cos (n x) \cos (mx) dx&=\frac12 \int_0^{\pi}\left(\cos((m+n)x) +\cos((m-n)x) \right)dx\\\\
&=\frac12 \left[\left(\frac{\sin((m+n)x)}{m+n} +\frac{\sin((m-n)x)}{m-n}\right)\right]_{x=0}^{x=\pi}\\\\
&=\frac12 \left(\frac{\sin((m+n)\pi)}{m+n} +\frac{\sin((m-n)\pi)}{m-n}\right)-0\\\\
&=0.
\end{align}
$$ Similarly,
$$
\begin{align}
\int_0^{\pi}\sin (n x) \sin (mx) dx&=\frac12 \int_0^{\pi}\left(\cos((m-n)x) -\cos((m+n)x) \right)dx\\\\
&=\frac12 \left[\left(\frac{\sin((m-n)x)}{m-n} -\frac{\sin((m+n)x)}{m+n}\right)\right]_{x=0}^{x=\pi}\\\\
&=\frac12 \left(\frac{\sin((m-n)\pi)}{m-n}-\frac{\sin((m+n)\pi)}{m+n}\right)-0\\\\
&=0.
\end{align}
$$
Comment: @MarcoCantarini Thanks to you! I think many of us had this answer :)


Find Minimum value of $\sqrt{58-42x}+\sqrt{149-140\sqrt{1-x^2}}$

Question: Find Minimum value of $$f(x)=\sqrt{58-42x}+\sqrt{149-140\sqrt{1-x^2}}$$
My try: the domain of the function is $x \in [-1 \,\,\,1]$
Differentiating and equating it to zero we get
$$f'(x)=\frac{-21}{\sqrt{58-42x}}+\frac{70}{\sqrt{1-x^2}\sqrt{149-140\sqrt{1-x^2}}}=0$$
but its very tedious to find critical points here.
any other approach?
Comment: You haven't differentiated it correctly.
Comment: According to wolframalpha, the minimizing $x$ is very ugly: $x=\frac{300-3\sqrt{4441}}{763}$.  The minimum value ain't so bad: $\sqrt{109}$.   So, even if you did the differentiation correctly you would get some inconvenient quadratic to deal with.
Answer: Let $(x,y)$ be a point on the unit circle $x^2+y^2=1$. We have to minimize the function:
$$
\begin{aligned}
f(x,y)
&=
\sqrt{(7x-3)^2+(7y-0)^2} \ +\ \sqrt{(7x-0)^2+(7y-10)^2}
\\
&=
\operatorname{Distance}(\ (7x,7y)\ ,\ (3,0)\ )\
+\
\operatorname{Distance}(\ (7x,7y)\ ,\ (0,10)\ )
\\
&\ge
\operatorname{Distance}(\ (3,0)\ ,\ (0,10)\ )
=\sqrt{3^2+10^2}\ ,
\end{aligned}
$$
with equality in the $\ge$ above only for the point of intersection of the segment with the above distance with the circle of radius $7$ centered in the origin.
Comment: excellent analysis
Answer: hint
As $x\in[-1,1]$, you can put
$$x=\cos(t)$$ with $$0\le t\le \pi.$$
the function becomes
$$F(t)=$$
$$\sqrt{58-42\cos(t)}+\sqrt{149-140\sin(t)}$$
$$\frac 17F'(t)=$$
$$\frac{3\sin(t)}{\sqrt{58-42\cos(t)}}-\frac{10\cos(t)}{\sqrt{149-140\sin(t)}}$$
$F'(t)=0$ gives
$$9\sin^2(t)(149-140\sin(t))=$$
$$100\cos^2(t)(58-42\cos(t))$$
Comment: @greendoid well, we only need the points, not the point of the idea.
Comment: Say: Yes, quick hint. Should be maybe a comment, not an answer.
Comment: And what about then?
Comment: @greedoid Diffetentiate with respect to $t$. it is easier.
Comment: @hamam_Abdallah then it is also simple to type this differential and solve w.r.t. $t$. Just fill in the details please. There is a difference between a possible beginning and and answer.
Comment: And you can fill in the details, if you can. It is not about downvoting (points again...) fun and/or happiness here, just respect people and do that what this site is interested in, mathematics.
Comment: Make sure you can do it in a more convincing way, at least for the people.
Comment: @dan_fulea Let it be and take it easy. you and i are nothing in this universe.
Answer: If you are not interested in the analytical zero of $f'(x)$ you could try to find the solution using e.g. the Bisection method, or a Fixed-point iteration, e.g. Newton's method. However, if you are going to be solving it by hand, I admit that this doesn't really help with the tedious part – in fact, it is probably worse.
Edit: Also, as noted in a comment, your differentiation is not correct. Check your second term.
Answer: In the following, $x$ runs in the interval $J=[-1,1]$.
We introduce the functions of $x\in J$
$$
\begin{aligned}
A(x) &= \sqrt{58-42 x}\ ,\\
B(x) &= \sqrt{149-140\sqrt{ 1-x^2}}\ .\\
&\qquad\text{Then we have }\\
10^2(58-A^2)^2 + 3^2(149-B^2)^2 &= 420^2\ .
\end{aligned}
$$
So we can formulate an equivalent problem:

Minimize $a+b$ constrained to $a$ between $\sqrt{58\pm 42}$ (i.e. $3$ and $10$), and $b$ between $\sqrt{149\pm 140}$ (i.e. $3$ and $17$) and $$10^2(58-a^2)^2+3^2(149-b^2)^2= 420^2\ .$$

So we search Lagrange multiplicators for the function
$$F(a,b;t)=(a+b)-t(10^2(58-a^2)^2+3^2(149-b^2)^2-420^2)$$
to get the local extremal points. (Then we still have to compare with the marginal values.)
We obtain the following system:
$$
\left\{
\begin{aligned}
0 &= F'_a(a,b;t) = 1+10^2\;4at\;(58-a^2)\ ,\\
0 &= F'_b(a,b;t) = 1+3^2\;4bt\;(149-b^2)\ ,\\
0 &= F'_t(a,b;t) = 10^2(58-a^2)^2+3^2(149-b^2)^2- 420^2\ .
\end{aligned}
\right.
$$
Algebraically, we have only a slight improvement, compared with the equation $f'(x)=0$, which was the intention in the OP, where we have some radicals. Above we have a purely algebraic system, the slight improvement, and still have to start the solution.
The idea is elimination.
We first eliminate $4t$, which appears linearly, getting:
$$
\left\{
\begin{aligned}
10^2\;a\;(58-a^2) &= 3^2\;b\;(149-b^2) \ ,\\
10^2(58-a^2)^2 &+3^2(149-b^2)^2= 420^2\ .
\end{aligned}
\right.
$$
One possible elimination idea (of $b$) from this point is as follows.
We are squaring the first equation, so we have an expression of $b^2(149-b^2)^2$ in terms of $a$, so $(149-b^2)^2$ is a polynomial in $a$ divided by $b^2$. We insert this expression of $(149-b^2)^2$ in the second equation, thus obtaining a formula for $b^2$ as a polynomial in $a$. We insert this $b^2$ in the second equation, thus obtaining an equation only in $a$. Of course, i cannot stop here and say "from here it simple, details left to the reader"... This bloody job is explicitly as follows, using a computer,
sage in my case:
var('a,b,bb');
EXPR = ( 10^2*a*(58-a^2) / 3^2 )^2 / bb     # (149-b^2)^2
# bb is above a new variable for b^2
eq = solve( 10^2*(58-a^2)^2 + 3^2*EXPR == 420^2, bb )[0]
print "b^2 is the solution bb of:\n%s" % eq
bb = eq.rhs()
a_poly = 10^2*(58-a^2)^2 + 3^2*(149-bb)^2 - 420^2
print "a is a zero point for the expression:"
print a_poly.factor()

Results:
b^2 is the solution bb of:
bb == -100/9*(a^6 - 116*a^4 + 3364*a^2)/(a^4 - 116*a^2 + 1600)
a is a zero point for the expression:
  1/9
  *(100*a^8 - 13400*a^6 + 398509*a^4 + 2317356*a^2 + 47534400)
  *(109*a^4 - 9044*a^2 + 174400)
  /((a + 10)^2*(a + 4)^2*(a - 4)^2*(a - 10)^2)

(The last expression was manually broken to fit in page.)
So $a$ is a root of the one or the other polynomial in the numerator. So $a^2$ is either the root of $100 U^4 - 13400U^3 + 398509 U^2 + 2317356 U + 47534400$, or the root or $109 U^2 - 9044 U + 174400$.

I did the above "in a human manner", and against my taste and conviction.
Let us put it an other way.
Of course, we cannot expect to have "simple solutions" and a "simple elimination by quick hint", so let us the computers do the work for us, then we can still decide...
Using sage, we eliminate blindly:
sage: R. = PolynomialRing(QQ)
sage: R
Multivariate Polynomial Ring in a, b, t over Rational Field

sage: F = a+b - t*( (10*(58-a^2))^2 + (3*(149-b^2))^2 - 420^2 )
sage: J = R.ideal( diff(F,a), diff(F,b), diff(F,t) )
sage: K = J.elimination_ideal([b,t])
sage: K
Ideal (10900*a^12 - 2365000*a^10 + 182067081*a^8 - 5688483592*a^6 + 53723051536*a^4 - 25754227200*a^2 + 8289999360000)
of Multivariate Polynomial Ring in a, b, t over Rational Field

sage: K.gens()[0].factor()
    (109*a^4 - 9044*a^2 + 174400)
  * (100*a^8 - 13400*a^6 + 398509*a^4 + 2317356*a^2 + 47534400)

and this rather reflects my way to work.
We have thus all possible points  / all candidates $a=\sqrt{58-42x}$, so that calculating the corresponing $x$ (or the corresponding $b$) and inserting in $f$ (or $F$) can lead to a local minimum.

Let us finally ask for the numerical values, to finish, and get an answer. For each root $a$ of the above polynomial we compute numerically (to a good precision) the value of $f$. (Since the OP may not be interested in $F$.)
f(x) = sqrt(58-42*x) + sqrt(149-140*sqrt(1-x^2))
R. = PolynomialRing(QQ)
P = (109*a^4 - 9044*a^2 + 174400) \
  * (100*a^8 - 13400*a^6 + 398509*a^4 + 2317356*a^2 + 47534400)

for aroot in P.roots(ring=AA, multiplicities=False):
    if aroot < 3 or aroot > 10:
        print "a = %s :: REJECTED" % aroot
        continue
    x = (58-aroot^2)/42
    print "a = %s x = %s f(x) = %s" % (aroot, x, QQbar(f(x)))

We get:
a = -8.857786578527434? :: REJECTED
a = -7.936142667572221? :: REJECTED
a = -7.245077360672018? :: REJECTED
a = -5.520990047273946? :: REJECTED
a = 5.520990047273946? x = 0.6552064023310009? f(x) = 12.09647575142790?
a = 7.245077360672018? x = 0.1311631913780425? f(x) = 10.44030650891055?
a = 7.936142667572221? x = -0.11862762952524599? f(x) = 11.096611974467387?
a = 8.857786578527434? x = -0.4871519778747795? f(x) = 14.02843358892943?

The minimal value of $f(x)$ among the above is obtained in the line:
a = 7.245077360672018? x = 0.1311631913780425? f(x) = 10.44030650891055?

(The value $f(x)$ is smaller than $f(\pm1)$ and $f(0)$, corresponding to possible global minimal values at the boundary.)
The corresponding $a$ is a root of $109a^4 - 9044a^2 + 174400=0$, explicitly:
$$
a_* = \sqrt{\frac1{109}(4522+18\sqrt{4441})}\ .
$$
And the corresponding $x_*=(58-{a_*}^2)/42$ is
$$x_* = \frac 3{763}(100-\sqrt{4441})\approx 0.13116319137804\dots\ .$$

Note: The numerical computations in between were done with a good enough precision to insure we pick the right candidate. So we have a proof. The following (truly) numerical computation is a check.
sage: var('x');
sage: minimize( sqrt(58-42*x) + sqrt( 149-140*sqrt(1-x^2) ), [0.5] )
(0.13116313434376808)

Answer: In the calculation of the derivative there is a typography error (typos), the value is:
$f'(x)=\frac{-21}{\sqrt{58-42x}}+\frac{70x}{\sqrt{1-x^2}\sqrt{149-140\sqrt{1-x^2}}}=0$
Hence,
$\frac{21\sqrt{2}}{2\sqrt{29-21x}}=\frac{70x}{\sqrt{1-x^2}\sqrt{149-140\sqrt{1-x^2}}}$
Squaring
$\frac{441}{2(29-21x)}=\frac{4900x^{2}}{(1-x^{2})(149-140\sqrt{1-x^{2}})}$
Inverting and squaring
$\frac{(4200x^{3}-7141x^{2}+1341)^{2}}{1944810000x^{4}}=\frac{(1-x^{2})^{3}}{1225x^{4}}$
$19227600x^{6}-59984400x^{5}+46231081x^{4}+11264400x^{3}-14389362x^{2}+210681=0$
$(5341x^{2}-4200x+459)(3600x^{4}-8400x^{3}+1741x^{2}+4200x+459)=0$,
$5341x^{2}-4200x+459=0$,
The acceptable root is
$$x=\frac{300}{763}-\frac{3\sqrt{4441}}{763}$$.


Add attribute to html and body

Question: I need to add class="no-trans" to body, also edit the html tag.
How I can edit the {{ html_attributes }} and {{ body_attributes }} ?
my html.html.twig
<!DOCTYPE html>

    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">

Answer: Here is a preprocess alternative (maybe you will need access to some info to make custom html classes).
use Drupal\Core\Template\Attribute;

/**
 * Implements template_preprocess_html().
 */
function MODULE_OR_THEME_preprocess_html(&$vars) {

  if (is_array($vars['attributes'])) {
    $vars['attributes'] = new Attribute($vars['attributes']);
  }

  $vars['html_attributes']->addClass('goes-to-HTML-tag');
  $vars['attributes']->addClass('no-trans');
}

Answer: The attributes variable is an object, that has some methods available.  One of them is addClass(), which allows you to add additional classes from a string or array.

To add arbitrary attributes to the html tag, you can use the setAttribute() method.  Multiple attributes can be set by chaining additional calls to setAttribute():

Take a look at the community documentation on using attributes in templates.
You can also look at the node.html.twig template in the classy theme for an example of adding an array of classes with addClass():
{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
  ]
%}

Comment: Classes and attributes may already be added in preprocess, so if you add `class="..."` or `attr1="..."` directly in the template, the attribute may then appear twice in the output.  `setAttribute()` should also ensure that the value is correctly encoded for use as an attribute value, which may be important if it is a dynamic value.
Comment: what is the benefit of using this setAttribute(... over just attr1="value" or addClass class="myClass" ?

Add attribute to html and body


Continuity of function and ...?

Question: I'm aware of what continuity is:

A function is continuous in its domain.
A function is continuous in $x=a$ if $\lim_{x \to a} f(x)=f(a)$

Being said that, I don't understand what I have to do in this exercise:
"The function $f(x)=(2x+5)^2+x \sin(\pi x)$ is continuous in $\mathbb{R}$. Find a finite interval where the equation $f(x)=10$ has a solution. Justify your answer. Why it has a solution in that interval?"
I understand that $f(x)=(2x+5)^2+x \sin(\pi x)$ is continuous in $\mathbb{R}$ because the funtion has the combination of polynomial and trigonometric funtion and its domain is $\mathbb{R}$. $f(x)=10$ is a constant function and the domain is also $\mathbb{R}$.
I don't understand what it does refer to when says to find an interval where $f(x)=10$ has a solution.
If someone can clarify me to see how to start here I will appreciate it.
Thanks in advance.
Comment: It means that you need to find an interval $I$ such that there exists $x_0 \in I$ so that $(2x_0+5)^2 + x_0 \sin(\pi x_0) = 10$.
Comment: Suppose you found point, $a$ where $f(a) < 10$  And suppose you found a point, $b$ where $f(b) > 10$.  As $f$ is continuous what can we say about whether $f(x) =10$ anywhere?
Comment: One possible is answer $[-5,0]$. Then you can show, that $(2x+5)^2 + x \sin(\pi x) - 10$ is is positive outside this interval and negative inside.
Comment: "f(x)=10 is a constant function and the domain is also R."  They aren't defining a second function.  the function is still $f(x) = (2x+5)^2 + x\sin (\pi x)$.  What the are claiming is there is a point $x_0$ (although the call the point a *value* $x$... not a *variable* $x$) where $f(x_0) = (2x_0 + 5)^2 + x_0 \sin(\pi x_0) =10$.  You aren't asked to solve for $x_0$ but to find an interval $(a,b)$ so that $x_0 \in (a,b)$.
Comment: ohhh ok get it now. So I must show it with the Intermediate Value Theorem that is has a solution or root?
Answer: When the say $f(x) =10$ they don't mean that $f$ is the constant function.  $f$ is still the function $(2x+5)^2 + x\sin (\pi x)$ but $x$ is a value where $f(x) = (2x+5)^2 + x\sin (\pi x)=10$.
They want you to approximate the value of that $x$ where $f(x) =10$.  But they don't expect you to solve it.  They expect you to find an interval $[a,b]$ for $a < x < b$.
Now using the definition of continuous can you do that.
Hint:  $f(0) = 5^2 + 0*\sin 0 = 25> 10$.  And $f(-1) = 3^2 - 3*\sin (-\pi) = 9-3*0=9 < 10$.
Now use Intermediate Value theorem.
Comment: I must use the Intermediate Value Theorem right?
Comment: Yep.... I wasn't sure if you knew the IVT.
Comment: yes... I just got lost suddenly. Thanks. <3
Answer: In the first part, $f(x)=(2x+5)^2+x \sin(\pi x)$ is defining a function, but $f(x)=10$ is not. It's posing an equation, asking for a value of $x$ such that $f(x)$ (the $f$ defined previously) take the value of $10$.

Continuity of function and ...?


Making a smooth curve that runs around the origin exactly once?

Question: I have just started to read do Carmo's book and this is the first exercise in the book:
Find a parametrised curve $\alpha (t)$ whose trace is the circle $x^2 + y^2 = 1$ such that $\alpha (t)$ runs clockwise around the circle with $\alpha (0) = (0,1)$.
My answer to it is this:
Let $\alpha (t) = (\sin t, \cos t)$ and $t \in (-1, 4 \pi)$. Then $\alpha (0) = (0,1)$ and $\alpha ({\pi \over 2} )= (1, 0)$ so it's clear that $\alpha$ runs around $(0,0)$ clockwise.
After going over this again I realised that this is not a proof that it goes around the origin clockwise. The book does not give a definition of "going around the origin clockwise". I did some digging and came across the winding number . Unfortunately, this is defined for closed curves. But the starting point and end point of my curve do not even exist as it is defined on an open interval.
Hence my first follow up question on this exercise is:

(1) How to mathematically rigorously prove that  $\alpha (t) = (\sin
 t, \cos t)$ where $t \in (-1, 4 \pi)$ goes around the origin
   clockwise?

Now assuming that my answer is okay as it is I was wondering if it's possible to make a smooth curve that goes around the origin exactly once, that is, $\alpha : (a,b) \to \mathbb R^2$ such that $\alpha (a) = (1,0) = \alpha (b)$ and $\alpha (x) \neq \alpha (y)$ if $x \neq y$.
What troubles me is that the domain is an open interval:  The book defines smooth curves as maps defined on $(a,b) \subseteq \mathbb R$.

(2) Is it possible to define a smooth curve (image the unit circle) defined on an open interval that
  goes around the origin exactly once?

After going over this exercise several times I noticed something else that is bothering me, too:

(3) The exercise statement does not require the curve to be
  differentiable. Is this on purpose or a typo? Does it make sense to
  ask for a possibly discontinuous curve?

And lastly:

(4) I was wondering whether if it is impossible to define a smooth
   curve $\alpha : (a,b) \to S^1$ that is bijective if it is possible to
   define a smooth bijection  $\alpha : [a,b] \to S^1$ or $\alpha : [a,b)
 \to S^1$?
Comment: Your first example makes no sense if you only take the domain to be the open interval $(0,4\pi)$, for then $\alpha(0)$ is not even defined.
Comment: (You should also be aware that there is nothing in the definition of a smooth curve that requires the map to be injective. Of course, that does not mean you can't ask whether such an injective map exists.)
Comment: It seems intuitively clear to me that the answer is "no", but i don't have a proof.
Comment: @symplectomorphic Right thank you for spotting the mistake, I fixed it. As you can tell from my example I am aware that the definition does not require the curve to be injective.
Comment: FWIW: Based on the level of writing in this section, it is very likely that do Carmo did not mean anything in particular by "runs clockwise around the circle".
Answer: In the interest of answering your questions, as posed:

A reasonable definition for "going around the circle clockwise" which matches intuition is that if you identify $\Bbb R^2$ with $\{(x,y,0):x,y\in\Bbb R\}\subset \Bbb R^3$, then $\mathbf x(t)\times \mathbf x'(t)=(0,0,z(t))$ for some non-positive function $z$, i.e. $z(t)\leq 0$ for all $t$. From here, I suspect you can answer the question yourself.
This isn't quite right, in that rather than "going around the circle clockwise", it's more like "going around the circle clockwise everywhere". You could probably coarsen this restriction by demanding that instead of holding for all $t$, it holds for a "sufficiently large" subset of $t$, but there's no notion of "sufficiently large" that matches my intuition.
Honestly, the definition you give here kind of depends on which answer you believe. If you want the answer to be 'no', you can say that it means $f$ must be a bijection. If you want the answer to be 'yes', you can say that $f:(a,b)\to \Bbb R^2$ extends to a smooth map $\tilde f:(\tilde a,\tilde b)\to\Bbb R^2$ with $\tilde a<a<b<\tilde b$ such that $\tilde f\big|_{[a,b]}$ is a closed curve with winding number 1. (You may also want $f$ itself to be surjective, if you're really sweating the last point.)
The latter construction may seem more contrived, but it is actually a standard construction in differential topology.
Actually it does: do Carmo defines a parametrized curve to be differentiable.
The half-open interval is of course possible, your curve can be modified for an example. The closed interval is not possible, since any continuous bijection from a compact space to a Hausdorff space is a homeomorphism (it is easy to show, for instance, that it is closed). The fact that $S^1$ and $[a,b]$ are not homeomorphic follows by your favorite method.
The open interval is again impossible, but (as the attempt so far shows) it is more subtle. One approach is to take a continuous extension of $f$ to $[a,b]$: take $\tilde f(a)=\lim_{x\to a}f(x)$ and similarly for $f(b)$; these limits exist since $S^1$ is compact. But now look at some point which is not $\tilde f(b)$ but is $\varepsilon$-close to $\tilde f(a)$. This has exactly one $\tilde f$-preimage because $f$ is a bijection. Since this preimage must be $\delta$-close to $f^{-1}(\tilde f(a))\neq a$, it cannot be $\delta$-close to $a$.
To do this rigorously you will probably have to invoke uniform continuity of $\tilde f$, but that's okay since the domain is compact. You would also have to show that you can force $\delta$ to be small enough: this should follow by sending $\varepsilon\to 0$ and noting that this would force $f$ to send an entire interval to $f(a)$.
Comment: Thank you, your answer is very helpful. Curious that there does not exist a less cumbersome definition of "going around clockwise".
Comment: @self-learner: I *really* want there to be a definition involving curl; after all, $z(t)$ in this notation is "morally" the curl. But the problem is that $\mathbf x(t)$ isn't technically a vector field, and I didn't see any way around that issue.
Answer: Do I understand it correctly that you want an injective ($\alpha(x) \neq \alpha(y)$ if $x \neq y$), smooth curve with image the unit circle defined on an open interval?
There does not exist such a map. There is a simple topological argument for this: if you remove a point from the interval $(a,b)$, the interval becomes disconnected, while removing a point from the circle keeps it connected. Since the function you are considering is bijective, continuous and is a function from a subset of $\mathbb{R}$ to a subset of $\mathbb{R}$, you cannot send a space that is made up of two connected components to a connected space, because there must be a bijection between connected components.
In other language, once you go around the circle once, except for hitting the point $(1,0)$, you have two options. Either you hit the point for a certain $t \in (a,b)$, meaning that where $(t,b)$ is sent, would overlap with a previous part of the curve, or you would never hit the point $(1,0)$.
Edit: The fact that we are considering a map from a subset $U$ in $\mathbb{R}$ to a subset V of $\mathbb{R}$ in the topological argument, is essential. In fact, being injective and continuous is already enough in this case, because of Invariance of Domain (https://en.wikipedia.org/wiki/Invariance_of_domain). This states that such a function is an open map and because connected components are both open and closed, such a function defines a bijection on your connected components.
Comment: Yes, I think you understand correctly. I think I am actually asking for a bijective map since I want it to go around exactly once. Thank you for your answer!
Comment: Your answer helped me realise that one could also say that $(a,b)$ is not compact and $S^1$ is but a continuous map maps compact sets to compact sets :-) Not sure why I didn't think of that before.
Comment: I'm thinking about the topological argument. I believe there might be a flaw, please forgive me, I'm looking for a slight modification. You need that the map is open, not a bijection, for it to map connected components on connected components. The proof in the third paragraph seems to work, although it still implicitly assumes the map is open.

As a remark to your comment, it is not reversed. A non-compact space can still be sent to a compact space. Think of $(a,b]$ mapping on the circle, for example. This is a bijection.
Comment: Fixed it, please read the edit.
Comment: Invariance of domain does not apply here: the map is between Euclidean spaces of different dimension.
Comment: Maybe it was not clear and please correct me if it is wrong, but my idea was to take away a point of $S^1$, making it homeomorphic to a subset of $\mathbb{R}$. Then you have a map from a subset of $\mathbb{R}$ consisting of two connected components to a subset of $\mathbb{R}$ which is injective and continuous map, thus showing that this restricted map must be open.
Comment: I just saw your reply. I cannot reply right now but I will as soon as I can.
Comment: @symplectomorphic You are right, I didn't even notice that Troy thinks we are talking about maps on $\mathbb R$! But as wrong as it might be, after briefly glimpsing at this answer I found a correct topological argument. What should I do now? Accept a wrong answer because it helped me? What is the policy of MSE?
Comment: @symplectomorphic Maybe you could post an answer that I can accept? Or should I post my own answer? Or perhaps delete the question?
Comment: There is no MSE policy, but it is probably good practice (for future readers) that you do not accept an answer which didn't actually help you.


Swiper slider: slide change to other div

Question: I have created a parallax slider but I have one big problem with changing the slider. I can change the slider when my mouse is inside the blue zone

As you could understand the blue zone (or the blue block) is the swiper-wrapper class, I can set the height to 100%, but in this case my layout is destroyed.
I want to know if swiper-slider provides me with such a property so that I can change the slider outside the blue zone (or outside the swiper-wrapper)?
Answer: If you want to create some space inside each slide add extra div inside swiper slide. **it is better to use % and not px for the space.
Snippet example:

const swiper = new Swiper('.swiper', {
  // Optional parameters
  loop: false,
  centeredSlidesBounds: true,
  slidesPerView: 2.1,
  spaceBetween: 20,
  // If we need pagination
  pagination: {
    el: '.swiper-pagination',
  },

  // Navigation arrows
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  }
});
.swiper {
  width: 100%;
  height: 100%;
}

.card_inside_swiper{
  background: red;
  max-width: 90%;
  margin:  0px auto;
}
<link
      rel="stylesheet"
      href="https://unpkg.com/swiper@8/swiper-bundle.min.css"
      />

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

hello

hello

    ...


Aggregate for non-zero increasing values

Question: TL;DR
Is there a mongo array operator that can detect if an array contains at least one entry that's larger than the previous?  eg
 [1,1,1,2,2,2] -> true
 [1,1,1,0,0,0] -> false

We're using mongo to track network activity, where the relative field packets is the running sum of activity over time.  This is best illustrated by example:
[0,0,0,0] -> no packets
[5,5,5,5] -> 5 packets continuous
[0,0,5,5] -> No packets and then a single event of 5
[0,0,5,10] -> two events, each increasing total packets by 5

Our goal is to identify records where there has been activity (ie. the number of packets changes).  At first, this seems straightforward using the $addToSet operator and then taking sets where count > 1.  EG:
[0,0,0,0] -> [0] -> false
[5,5,5,5] -> [5] -> false
[0,0,5,5] -> [0,5] -> true
[0,0,5,10] -> [0,5,10] -> true

However, we then learned of an additional constraint.  When activity goes to 0, that is considered a reset and should not count as activity eg,
[5,5,0,0] -> false (a reset event)
[0,0,5,5] -> true (a network event)
[5,0,5,0] -> true (a reset event followed be a network event followed by a reset - but because there was a network event this is true)

Activity will ALWAYS increase except for when going to zero (ie [5,5,0,0] is possible but [5,5,4,4] is not).
Thus, we need to find out if the data contains a single entry whose value is larger than the prior.  Is there a mongo operator that can sweep through an array and return true if any element is larger than its prior?
Thanks
Comment: Just to be clear, what's `[5,0,5,0]` in your expectation? True or False?
Comment: True - let me update question to reflect
Comment: Oh okay, was a bit worried about that, since that was the only test I was failing. Hate to pick but you just upvoted an answer which actually fails your test cases.
Answer: You can take advantage of $reduce operator to scan the array and keep previous value to compare it with current one.
For sample data like:
db.col.save({ data: [1,1,1,2,2,2] })
db.col.save({ data: [1,1,1,0,0,0] })

you can run:
db.col.aggregate([
    {
        $project: {
            result: {
                $reduce: {
                    input: "$data",
                    initialValue: {
                        previous: { $arrayElemAt: [ "$data", 0 ] },
                        decision: false
                    },
                    in: {
                        previous: "$$this",
                        decision: {
                            $or: [
                                "$$value.decision",
                                { $gt: [ "$$this", "$$value.previous" ] }
                            ]
                        }
                    }
                }
            }
        }
    },
    {
        $project: {
            _id: 0,
            result: "$result.decision"
        }
    }
])

outputs:
{ "result" : true }
{ "result" : false }

Comment: Thanks, let me try this out a bit later and mark as accepted if it works which it seems to nicely
Comment: @AdamHughes sure, you can also test it here: https://mongoplayground.net/p/7A1qWH1Qcur
Answer: Basically you are traversing with $reduce using current and previous values and comparing
db.collection.aggregate([
  { "$addFields": {
    "result": {
      "$reduce": {
        "input": {
          "$range": [ 1, { "$size": "$source_array" } ]
        },
        "initialValue": false,
        "in": {
          "$or": [
            "$$value",
            { "$gt": [
              { "$arrayElemAt": [ "$source_array", "$$this" ]},
              { "$arrayElemAt": [
                "$source_array",
                { "$subtract": [ "$$this", 1 ] }
              ]}
            ]}
          ]
        }
      }
    }
  }}
]);

Given data like:
{ "source_array" : [ 0, 0, 0, 0 ], "expect" : false }
{ "source_array" : [ 5, 5, 5, 5 ], "expect" : false }
{ "source_array" : [ 0, 0, 5, 5 ], "expect" : true }
{ "source_array" : [ 5, 5, 0, 0 ], "expect" : false }
{ "source_array" : [ 5, 0, 5, 0 ], "expect" : true }
{ "source_array" : [ 5, 0, 5, 5 ], "expect" : true }
{ "source_array" : [ 5, 5, 4, 4 ], "expect" : false }

Returns:
[
  {
    "source_array": [
      0,
      0,
      0,
      0
    ],
    "expect": false,
    "result": false
  },
  {
    "source_array": [
      5,
      5,
      5,
      5
    ],
    "expect": false,
    "result": false
  },
  {
    "source_array": [
      0,
      0,
      5,
      5
    ],
    "expect": true,
    "result": true
  },
  {
    "source_array": [
      5,
      5,
      0,
      0
    ],
    "expect": false,
    "result": false
  },
  {
    "source_array": [
      5,
      0,
      5,
      0
    ],
    "expect": true,
    "result": true
  },
  {
    "source_array": [
      5,
      0,
      5,
      5
    ],
    "expect": true,
    "result": true
  },
  {
    "source_array": [
      5,
      5,
      4,
      4
    ],
    "expect": false,
    "result": false
  }
]

All this is done by using $arrayElemAt with the index values from the array. Using $range to generate the indexes from 1..length and comparing n with n-1 for current and previous respectively.
The logic says that no further comparison is needed when a true result is obtained.


Como usar código do github live, para desenvolvimento, testes e demos?

Question: Como posso usar código do GitHub em tempo real numa demo ou em desenvolvimento?
Quando tento usar código no jsFiddle ou jsBin recebo o erro:

Refused to execute script from https://raw.github.com/utilizador/repositorio/ficheiro.js because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.

Exemplo: jsFiddle (ver erro na consola)
Answer: A solução é usar um serviço do Github que disponibiliza os ficheiros com o cabeçalho content type correcto.
Asim o url disponibilizado é quase o mesmo, só precisa de remover o . (ponto)
Antes
https://raw.github.com/utilizador/repositorio/ficheiro.js
           ^

Depois
https://rawgithub.com/utilizador/repositorio/ficheiro.js
// ou mais recente:
https://rawgit.com/utilizador/repositorio/ficheiro.js

Mais info (em Inglês)

Demo


Laravel 5.2 disable csrf_token

Question: How can I disable CsrfToken just for this route ? When I use web Middleware doesn't work, when I use this way doesn't work. help please
This is my Router :
 Route::post('payment_check/{order_id}', ['as' => 'payment', 'uses' => 'users\ChargeController@payment_check']);

and here is my verifycsrftoken.php
protected $except = [
    'payment'
];

and Kernel.php
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
    'api' => [
        'throttle:60,1',
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
    'userAccess' => \App\Http\Middleware\userAccessMiddleWare::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

Comment: csrf is a protection against cross site request forgery it is a bad thing to disable it!
Answer: It should be
protected $except = [
    'payment_check/*'
];

in your verifycsrftoken.php
Comment: define route under except, as @Mahfuzul mentioned it will skip csrf for all under payment_check routes.

Laravel 5.2 disable csrf_token


Any risks associated with habitually updating/reverting ALL features in drush?

Question: I want to start using drush commands to simply update all or revert all features (depending on which environment I'm in) instead of doing them one by one. What are the risks involved or questions I should ask myself before habitually just updating all or reverting all features?
drush fra (to revert all on production and test servers)
drush fua (to update all on dev environment)
Thanks!
Answer: In my opinion, first and foremost thing which should be taken into consideration is that your feature should not have any changes different from your development environment.
secondly, make sure that all of the fields of a content type have same type and widget as that are in your production environment.
You can also take backup of the db before reverting the features in case you are making any major changes.
Answer: Personally, I do "revert-all" all the time (to test / roll out changes on Test and Production).
Because no feature update should be overlooked before / during release.
Personally, I would find "update-all" way too risky. Because Dev potentially contains many small tests, changes, trials, and failed attempts. Those should never slip into a (bloated) commit. Let alone reach a "revert-all" on Production.
An "update-all" would also conflict with my understanding of "atomic commits". Where commits are always (many) small changes, exclusively.
Those are easily read. Easily understood. Easily undone. (And all features contain only small components (are not bloated).)
Changing a content-type? Do "drush fu this-content-type-feature". Commit.
Updating a view? If happy, then do "drush fu that-view-feature". Commit. Next.
Makes for very readable "git diff"s, without including any accidental or experimental changes from a Dev.
Comment: I've come to this conclusion also, perfect, thanks!


What's the difference between "real" and "imaginary" parts of a complex numer?

Question: I was reading Go's documentation for the complex128 and complex64 data types when I came across something odd:

"complex128 is the set of all complex numbers with float64 real and imaginary parts."

And:

"complex64 is the set of all complex numbers with float32 real and imaginary parts."

More specifically:

"real and imaginary parts."

What's meant by this? How can a number be "real" or "imaginary"?
Comment: You could easily have found the answer by looking up the definition of "complex numbers"
Comment: For a complex number $z=a+ib$, the number $a$ is said to be the real part, and $b$ is said to be the imaginary part.
Answer: I suggest that you read the Complex number wikipedia article. There is a lot to learn before you will probably truly understand it. However, to put it in few words, for the creation of complex numbers we introduce an "imaginary" (that's simply terminology) number $i$, that satisfies
$$i^2  =-1. $$
A complex number, then, is any number $z$ that can be written on the form
$$z = a + ib $$
where $a$ and $b$ are real numbers. Here $a$ is the "real part" (i.e. not coefficient of $i$) and $b$ is the "imaginary part" (i.e. coefficient of $i$). It should be noted that the real numbers are then a subset of the complex numbers, because all real numbers can be written on the form $z = a +ib$ with $b = 0$ and $a\in \mathbb R$.
Answer: This is the most basic of basics as one learns about complex numbers.
Complex numbers are polynomials in one variable. Almost exactly the way you already know them. We usually use the variable name $i$, although some physicists and programming languages use $j$ instead.
So $1$ is a complex number. As are $i, 3-5i$ and $1+\sqrt2i-\pi i^2$. We can add, subtract and multiply polynomials exactly the way you learned in school.
However, $i$ comes with a special property. Namely that $i^2$ is $-1$. That means that the last example above, $1+\sqrt2i-\pi i^2$, we may rewrite into
$$
1+\sqrt2i - \pi\cdot(-1) = 1+\pi + \sqrt2i
$$
This way, any polynomial may be reduced to (at most) first degree, in a unique way. This also has the side effect that you can divide two complex numbers by one another, and get a complex number back (usually, you can't divide two polynomials by one another and expect to get a polynomial back, but with the complex numbers, because of $i^2 = -1$, this is possible).
So, in general, one writes a complex number as a first-degree polunomial: $a + bi$, where  $a$ and $b$ are real numbers. As with regular first-degree polynomials, $a$ and $b$ have special names. In the context of complex numbers, however, they aren't called constant term and slope, but rather real part and imaginary part. $a$ is the real part, and $b$ is the imaginary part.
We also often visulaize complex numbers in a plane. Not as lines, but as points. The complex number $a + bi$ is represented by the point $(a, b)$. This way, addition of complex numbers correspond to regular vector addition (ditto subtraction), and multiplication has a nice geometric interpretation as well.
In this interpretation, the $x$-axis is the real number line, exactly the way you learned in school. The $y$-axis is called the imaginary axis. The complex number $a+bi$, which in the plane is the point at $(a, b)$, has $x$-coordinate (real part, the component along the real axis) $a$ and $y$-coordinate (imaginary part, the component along the imaginary axis) $b$.
As for why one uses the word "imaginary", you'd have to ask 16th century mathematicians.
Comment: And why can I divide by these complex numbers? Oh, that's basic. Since the ring of polynomials is a principal ideal domain and $i^2-1$ is irreducible, its generated ideal is maximal. And quotients of commutative rings with unity, such as the ring of polynomials, by maximal ideals are fields. Don't ask me why 16th century mathematicians felt this stuff was more imaginary than names for points on an directed line.
Comment: @Bananach You can divide them because you can expand any fraction by the conjugate of the denominator, which results in the denominator becoming real, and dividing a polynomial by a (non-zero) real number is unproblematic.
Answer: Practically, on your computer in Go or on paper in theory, a complex number is just a tuple of two real numbers, that is, floats as you know them. The first is called the 'real part' (not number), the second is called the 'imaginary part'.
Just as with the floats that you already know, you can add, multiply and divide complex numbers. These operations useful and meaningful in quite a few  situations, but if you haven't heard of them just wait until you do.

If you are interested, here is how the term 'imaginary' came around and how the multiplication of complex numbers was defined they way it is:
Everyone knows that there is no real number such that $x^2=-1$. In other words, $x^2=-1$ is a polynomial equation that you cannot solve. You run into the same kind of problems when you try to solve other quadratic equations, for example $x^2+x=-1$. You can now wonder in how many ways can you fail to solve quadratic equations. To start this analysis, you can just pretend $x^2=-1$ does have a solution, and call it $i$, because this solution is just a product of your imagination.
You may then notice that you can do calculations with $i$ in an obvious way. You can multiply $i$ by real numbers, $b$, and just write the result as $bi$. You can  add a real number, $a$, to this and get $a+bi$. You can add two such expressions, $a_1+b_1i$ and $a_2+b_2i$, and get
$$
a_1+b_1i+a_2+b_2i=(a_1+a_2)+(b_1+b_2)i,
$$ simply using the rules of distributivity, associativity, and commutativity that you already know. You can multiply two such expressions and get
$$
(a_1+b_1i)(a_2+b_2i)=a_1a_2+a_1b_2i+b_1a_2i + b_1b_2i^2=(a_1a_2-b_1b_2)+(a_1b_2+b_1a_2)i,
$$ again just using the rules that you already know and the fact that $i^2=-1$.
Finally, you can also take inverses. Indeed,
$$
(a+bi)(a-bi)=a^2-b^2i^2=a^2+b^2
$$
and therefore
$$
(a+bi)^{-1}=\frac{a-bi}{a^2+b^2}.
$$
As you can see, no matter what calculations you do with your imaginary numbers, you always end up with expressions of the form $a+bi$. To save ink, you may then decide to write $(a,b)$ for $a+bi$. The addition, multiplication and divison rules you discovered above can then be written as
$$
(a_1,b_1)+(a_2,b_2)=(a_1+a_2,b_1+b_2)\\
(a_1,b_1)\times(a_2,b_2)=(a_1a_2-b_1b_2,a_1b_2+b_1a_2)\\
(a,b)^{-1}=(\frac{a}{a^2+b^2},\frac{-b}{a^2+b^2}).
$$
Thus, the complex numbers were born.
It should now be obvious what the terms real part and imaginary part mean. The real part of $(a,b)=a+bi$ is the $a$. The imaginary part is the part with the $i$, namely $bi$.
To get back to your study of quadratic equations, you may notice that you can solve all such equations with your newly found expressions. Moreover, you can use the quadratic formula that you already know,
$$
x_{1,2}=\frac{-b}{2a}\pm \frac{\sqrt{b^2-4ac}}{2a},
$$
even if $b^2-4ac<0$. Indeed, since $(\pm \sqrt{-y}i)^2=-yi^2=y$ for any negative number $y$, you can justify saying that $\sqrt{b^2-4ac}=\pm \sqrt{-(b^2-4ac)}i$, which makes everything in the quadratic formula well defined.
If you are really interested, you can go on and study higher degree polynomial equations. You can show that any such equation can be solved using your complex numbers (a lot of smart men tried hard to prove this, the first satisfactory proof was established a few hundred years after complex numbers were first to solve  quadratic and cubic polynomials).
After all this work, you might wonder what the point of it all is. For that you have to think a bit like a mathematician. For example, you may notice that quadratic equations got much easier, even if you are just interested in real solutions. They always have a solution and you have a formula that is always valid. You just have to check whether the complex solution is in fact a real solution.

What's the difference between “real” and “imaginary” parts of a complex numer?


Google Chrome. Removing items form context menu

Question: Is that possible: remove some context's elements?
I dont want remove core items, but if i will able to remove or disable some things which added by extensions, it will be nice.
Comment: Why do you feel your website should be allowed to override the behaviour of extensions?
Answer: If you want to remove some elements added by other extension from your extension, what you can do is to disable them (you will need management permission for that). There is no way to be more specific than that and disable only some parts of other extensions, sorry.


Add content type machine name as body class

Question: Is there a way to insert a class to the body of the node page? It should be named like the current node type's machine name.
Maybe someone could extend this code below with a content type class:
function marienschule_preprocess_html(&$variables) {

  // Add node ID to the body class.
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) {
    $variables['attributes']['class'][] = 'node-' . $node->id();
  }
}

Answer: You can do this without a preprocess hook, because the node type variable is already available in the html template:
{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
  ]
%}

...

Source: html.html.twig of Classy
Answer: The code sample from your question could be extended to look like that:
function marienschule_preprocess_html(&$variables) {

  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {

    // Add node ID body class.
    $variables['attributes']['class'][] = 'node-' . $node->id();

    // Add content type machine name body class.
    $variables['attributes']['class'][] = 'node-type-' . str_replace('_', '-', $node->bundle());
  }
}


Global variables cannot be read by server.R in shiny

Question: The two files in ./app
ui.R
library(shiny)

a <- 1
ui <- fluidPage(
  textOutput("test")
)

server.R
server <- function(input, output) {
  output$test <- renderText({
    a
  })
}

Run shiny app
shiny::runApp("app")

Error
Warning: Error in cat: argument 1 (type 'closure') cannot be handled by 'cat'
  102: cat
   98: transform
   97: func
   95: f
   94: Reduce
   85: do
   84: hybrid_chain
   83: renderFunc
   82: output$test
    1: shiny::runApp

If I put the code in on file, it work. What is the reason for this?
library(shiny)

a <- 1
ui <- fluidPage(
  textOutput("test")
)

server <- function(input, output) {
  output$test <- renderText({
    a
  })
}

shinyApp(ui = ui, server = server)

Comment: In a shiny application, you can use a `global.R` source file whose objects defined there will be visible to both `server.R` and `ui.R`.
Comment: You can put the variable in an extra .R file and call the file at the beginning (above ui).
Comment: In addition to @nicola's comment please check the section *Global objects* [here](https://shiny.posit.co/r/articles/improve/scoping/)
Answer: Problem is that you dont have global file to call server and ui together, you need to merge ui and server in global, why your first app doesnt run is that shiny::runApp() is to run built beforehand app, but what I see your files you dont have any shinyapp, whereas if you want to create app you need to use complete all steps and add shinyApp() function as well. Therefore second code is working.
Check below solution
ui.R file
a <- 1
ui <- fluidPage(
  textOutput("test")
)

server.R
server <- function(input, output) {
  output$test <- renderText({
    a
  })
}

global.R
library(shiny)

shinyApp(ui = source("app/ui.R")$value, server = source("app/server.R")$value)

if you want to use your app in different solution shiny::runApp()
then you can create one more file for example run.R
and paste:
shiny::runApp("path/global.R", host= "your IP address", port=1336)

and run this command in terminal, and your shiny app will be available online within your IP address unless closing your active terminal
"C:\Program Files\R\bin\x64\Rscript.exe" "path\run.R"

Comment: There is no need to `source()` `ui.R` and `server.R` in `global.R`. `runApp()` only needs the `appDir` where the according files reside.
Comment: For multiple apps in a single project I'd suggest using subdirectories for each app or to create shiny app objects (wrapped in functions) with global variables initialized in `shinyApp()`s `onStart` callback (see `?onStop` for an example). However, this is pretty niche and not what OP asked for.
Comment: I had multiple apps in my project and default wd, so if there is one, then Appdir can be changed


Cast do tipo byte em inteiro

Question: Tenho o seguinte código:
public class Principal {
     public static void main(String[] args){

      int i = 10;
      byte b = 5;
      b = (byte)i;
      b += i;
      i = b;

      System.out.println( i );
      }
}

Sei que o valor retornado em b = 20.
Mas por que? Gostaria de entender o que acontece quando coloco o cast(byte) no int.
Questão 127 página 4 concurso
Comment: `Questão 127 do concurso`, coincidentemente, o valor máximo possível de armazenar no byte :D
Comment: @Bia, atualizei minha resposta baseado na edição que você fez na pergunta.
Comment: @Bia o que significa esse "julgue"? É para dizer o que acha de cada afirmação? É para dizer se ela está errada?
Comment: @bigown julgar se a afirmação é correta ou não.
Answer: Antes de responder a pergunta em si, é importante mencionar que essa instrução byte b = 5 não está alterando em nada o resultado. Poderia ter sido feito direto byte b = (byte)i.
Sobre o resultado, é preciso compreender os tipos envolvidos na pergunta, principalmente o tipo byte.
Em Java, o tipo byte possui sinal e tem tamanho de 1 byte, portanto, 8 bits. Utilizando 8 bits é possível mapear 256 caracteres, nesse caso, números inteiros. Como a variável tem sinal, então o intervalo vai de [-128,127].
Dito isso, se o inteiro que você está fazendo cast para byte estiver nesse intervalo, então ele será impresso corretamente, caso não esteja, acontecerá um overflow na variável do tipo byte e o que será impresso será um número nesse intervalo, mas não o int para o qual você está fazendo cast.
Veja isso: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Atualização
A pergunta foi alterada de maneira significativa o que me fez editar a resposta.
O resultado não era 10 como mencionado anteriormente, mas 20, já que é feita uma soma de b+=i após o cast. Entretanto, isso não altera a explicação, já que 20 é um número que está no intervalo de um byte em Java.
Answer: Note que a pergunta original dá uma pista equivocada do que realmente foi perguntado no concurso. Agora também não está muito preciso. Em qualquer coisa, mas especialmente em concursos é fundamental ter precisão na interpretação ou comunicação do que é o problema. Caso contrário os erros ocorrerão por causa da deficiência da comunicação mais do que a falta do conhecimento.
No caso a afirmação da questão 127 é verdadeira. Será impresso 20.
int i = 10; // i está valendo 10
byte b = 5; // b está valendo 5
b = (byte)i; // agora b passa valer 10, o cast não o afeta, dentro dentro da capacidade do tipo
b += i; //agora b vale o seu próprio valor mais o de i, então 10 de b e 10 de i = 20
i = b; // agora i passa ter o mesmo valor de b, ou seja, 20.

Coloquei no GitHub para referência futura.
O cast não afetou nada o valor. Ele poderia ter afetado se o valor i estivesse fora da faixa aceita pelo tipo byte (-128 até 127). O mesmo vale para a adição do valor de i em b. O valor de i que tem 4 bytes de armazenamento "cabia" dentro de b que tem apenas 1 byte. O tipo byte permite representar 256 números distintos (2 elevado a 8), enquanto que o tipo int permite (de -2.147.483.648 à 2.147.483.647 4.294.967.295 - 2 elevado a 32).
Comment: Importante ressaltar também que a soma do inteiro no byte também não afetou visto que os bits do inteiro não passaram do limite do byte, nem usou do último bit que é usado para negativo do byte.
Comment: @DarkHyudrA verdade, melhorei, obrigado.
Answer: Sempre que é feito um cast de um tipo numeral pra byte, entenda os bits que estão envolvidos, no caso do seu exemplo acontece isso:
00000000 00000000 00000000 00001110

00001110
Ele vai simplesmente descartar tudo a esquerda que seja além do primeiro byte. Vale notar também que o byte do Java tem sinal, então o primeiro bit ajuda a identificar o sinal.
E sobre seu exemplo de código, rode em qual versão de java for, que o resultado sempre vai ser 10 também. Isso gera um comportamento bem estranho, porque, por exemplo, 127 em int é 127 em byte, mas 128 em int é -128 em byte.
Recomendo experimentar comandos como bit shift para entender melhor como a estrutura de dados funciona a nível de bit.
Answer: Se executarmos o código abaixo:
public class HelloWorld{
    public static void main(String []args){
        int i = 10;
        byte b = 5;
        b = (byte) i;
        System.out.println(b); // esta linha irá imprimir 10
     }
 }

Será impresso o valor "10". Pois é um valor que cabe numa variável do tipo byte. Mas se eu mudar o código para:
public class HelloWorld{
    public static void main(String []args){
        int i = 300;
        byte b = 5;
        b = (byte) i;
        System.out.println(b); // esta linha não irá imprimir 10
     }
 }

Não será impresso 300. Pois é um valor que não cabe numa variável deste tipo.
Se olhares para a documentação de Java :  https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
verás que o byte é um tipo de dado inteiro mas bastante limitado. Aceita valores de -128 a 127. Ou seja, valores fora desta margem serão perdidos.
Comment: E o que vai imprimir o último `System.out.println(b);`? Fiquei curioso :P
Comment: no exemplo que usei imprime 44. Vê a resposta do @DarkHyudrA que ele explica porque é que isso acontece

Cast do tipo byte em inteiro


What is the lowest possible winning score in snooker?

Question: What is the lowest possible winning score in snooker assuming that...

The loser does not concede the frame
No fouls are made
No more than one ball is pocketed on any given shot
Answer: Given these requirements, the minimum winning score is 22 points.
Firstly, under these conditions, the lowest total score is 42 points (all reds sunk with no colour, plus all colours in sequence to end the frame).
Secondly, if a player scored exactly half of these points, the opponent scores the other half, and would tie the frame by definition. If they score less than half these points, the opponent must score more, and would win by definition. Therefore, the minimum winning score is one point more than half of 42, i.e. 22 points.
Finally, is it possible to score this number of points? Yes, clearly, for example

Player 1 sinks a red ball, and then misses the colour, while Player 2 misses only, until all reds are sunk (scores 15-0). Thereafter, Player 1 sinks the yellow and green in sequence and misses the brown (scores 20-0). Player 2 sinks the remaining balls in sequence and ends the frame (final scores 20-22)
Player 1 sinks a red ball and misses the colour, while Player 2 misses only, until all red balls are sunk (scores 15-0). Player 2 sinks the yellow, green, brown, pink and blue in sequence, and misses the black (scores 15-20). Player 1 sinks the black and ends the frame (final scores 22-20).

Other combinations that lead to a total of 22 for the winner, or equivalently a total of 20 for the loser, may be found by trial-and-error or via a constructive process (either depth-first or breadth-first tree searching would be recommended).


How to set up an iTunes podcast?

Question: This question about podcasting in Drupal 7 recommends the Views RSS iTunes elements module, which hasn't had any commits on the Drupal 8 dev branch since 2014. (tutorial for D7)
The iTunes RSS tag documentation shows that the tags are not very complex, and indeed the iTunes elements module (D7) documentation shows that there are only about a dozen tags that need to be set up for an iTunes-compatible podcast.
So my question is, do any of the additional features of D8 compared to D7 provide a way to configure this with just the modules in core, or am I going to have to code something to generate an RSS feed that meets the iTunes podcasting requirements?
I was hoping to be able to use something like a Views theming template to just rewrite all the tags in the template and publish the feed that way.
Comment: I had to write my own theme function and route and created feed like that. I do not know about any readily available solution for Drupal as of now. Normally I wouldn't do this but maybe have a look at Wordpress? It has few good modules for this.
Comment: Have you looked into using Views for your RSS? Perhaps you can override or create custom tags with views.
Comment: @NoSssweat Yes, I'm interested in using Views to create custom tags, but how?
Answer: Just because there hasn't been a commit for ages doesn't mean it's totally not worth investigating further - as you say the tags are not complicated so probably that hasn't changed.
I had a quick look and the first issue on the issue queue is for the 8 version and it's to do with how libraries are loaded, which I believe did change as 8 moved along. Someone's posted a patch in Dec 16 so not that long ago and it's marked as 'needs review', so best would be to try it out and report back there as to whether that works or not, if so and something else doesn't work then create another issue if you can't fix it yourself, or post another patch if you can.
If you use composer to install Drupal 8, for example using:
https://github.com/drupal-composer/drupal-project
then you can also apply the patch in the patches section of your composer.json by adding the link to the patch so it can find it:
https://www.drupal.org/files/issues/views_rss_itunes-fatal_error_call_to_undefined_function_libraries_load-2839012-3.patch
This is kinda how it works - if you wait it may never arrive, and if you can't do the above it's all googleable skills.

How to set up an iTunes podcast?


Solving for the values of (x+y) upto 3 decimal places.

Question:
Given a equation:
  $72^x48^y=6^{xy}$ where $x,y\in \Bbb Q \ne 0$
  Find the value of $(x+y)$

I tried using $\log$ but always end up with 2 variables $x,y$.
Thanks for your help
Answer: Apply logarithms, so
$$ x\ln 72+y\ln 48=xy\ln 6$$
or by expanding the integers $72=2^33^2$, $49=2^43^1$, $6=2^13^1$
$$ 3x\ln 2+2x\ln3+4y\ln 2+y\ln 3=xy\ln 2+xy\ln3$$
As $\ln2$ and $\ln3$ are rationally independent and $x,y$ are rational, this gives us in fact two equations
$$\begin{align}3x+4y&=xy\\2x+\hphantom{0}y&=xy\end{align} $$
By equating the expressions for $xy$, $3x+4y=2x+y$, i.e.,
$$ x=-3y.$$
Substituting this gives us
$-5y=-3y^2$, hence either $y=0$ (and then $x=0$, but that solution was excluded) or $$y=\frac 53\qquad\text{and}\qquad x=-5.$$
Comment: @HagenvonEitzen- Thanks for giving your time and solution.
Comment: The question seems to suggest that it is be possible to find $x+y$ without finding $x$ and $y$. I only got as far as $x+y=\frac{2}{5}xy$.
Comment: @ihf- I also got stuck there but later on solved it.


If A and B are compact sets, then A ∩ B is compact.

Question: If A and B are compact sets, then A ∩ B is compact.
my approach is since A and B are compact, for every open covers of A and B, there exists finite sub-covers to cover A and B. Since A ∩ B is a subset of A, for each finite sub-cover of A, there is a sub-cover of that sub-cover to cover A ∩ B. Therefore, A ∩ B is compact. Is my proof rigorous enough?
Comment: Doesn't look convincing to me. When you want to prove that $A\cap B$ is compact, you need to start with some _arbitrary_ open cover of $A\cap B$. This needs not be a cover of $A$ nor of $B$. What do you do then?
Comment: No, your proof is not correct. Note that what you are saying is that any subset of a compact set is compact, what is not true.
Comment: Do you know that your $A$ and $B$ are subsets of $\mathbb R^n$? If you know the compact subsets of $\mathbb R^n$ are exactly the closed and bounded ones, then a proof from this characterization will be is almost immediate. On, the other hand, if $A$ and $B$ live in an arbitrary topological space (perhaps not even Hausdorff so you're not guaranteed that $A$ and $B$ are _closed_), then your claim is not necessarily true. What exactly are your assumptions here?
Answer: You have to assume that the space is Hausdorff so that compact sets ar closed. $A\subset \cup_i V_i$ ($V_i$'s open ) implies $A \subset B^{c} \cap \cup_i V_i$ and this gives an open cover for $A$. Let $A \subset B^{c} \cap \cup_{k=1}^{N} V_{i_k}$. Then $A \cap B$ is covered by $V_{i_k}$,$1\leq k\leq N$.


Need a price quote engine

Question: Folks, I need a module that will give me the ability to collect service requests from anonymous users and will return to them an estimated price, so a quoting engine basically.  I need the information they submit to also be summarized and sent in an email to a sales rep.
I know about Ubercart, but it seems to be overkill for what we need.  Does anyone have experience with it and can vouch for it as far as this problem goes?
EDIT: Further elaboration on collecting service requests.  The requestee selects a few services that they require, and in what quantity, and this request is forwarded to a sales rep who then prices out the request and contacts the requestee via email with a price quote.  Really I see this as a one way mechanism where requests are just submitted, and then the rest of the conversation is carried out either over the phone or via email.
Comment: Sounds like this could be accomplished through a combination of rules and form_api or webform, but it's difficult to know without more detail.  Could you elaborate on what you mean by "collect service requests"?
Answer: Receiving requests
With webform, you can create forms that allow you, or your site-admins, to create and maintain the form that site-visitors will fill out. When the form gets submitted, you can use Rules to send this information on as an e-mail. The module Webform Rules, provides the bridge between the two modules, allowing Rules to react to webform events.
Answering requests
Just turn the whole process around. Again, use webform to create a form for the request reciever to fill out. When this form gets submitted, send a mail to the requestee with the reply.
Custom work
You will most likely need to do some amount of custom coding to make this whole thing work. For example, in the mail to the sales rep, a link must be autogenerated to a form that gets prefilled with the requestee's e-mail. Auto-filling the form is likely best done as a hook_form_alter. There is a lenghty Rules video series that you can view to learn more about how to work with Rules and how to extend it to do what you need.
Comment: Seems promising.  I'll look into this tomorrow.  Cheers mate.
Answer: I've used ubercart in this way before and it does give you some nice free functionality, for example you can mix non quotable items in your database and have Conditional Actions (Rules) that look to see if you need to make this a quote only type request. Once it's in there, the order can have it's status changed so that the customer can see how it's progressing and you can define new/different order states to correspond further to your workflow.
Having said all that, a D7 install I would probably start on commerce rather than Ubercart :)
Comment: Yes that is the project I am referring to. If I have the choice I'll use Commerce as it is some of the core developers from Ubercart who are creating a solution from the ground up to take full advantage of the new features (field, everything is a view) of Drupal 7. Ubercart, while being maintained is a port and will have many of the limitations of the D6 version of Ubercart.
Comment: http://drupal.org/project/commerce is that what you're referring to with 'commerce'?  If so, why do you recommend this over Ubercart?
Comment: Nice, definitely going to mess around with this.  Seems like it's the future, and if it's the from the same devs as Ubercart, seems like a win to me.
Comment: Yeah, it's much more framework like than Ubercart, so if you get into it, grab the Kickstart package. Another nice thing is the differentiation between product and product displays, which sounds like some work at first, but makes amazing sense once you get into it.

Need a price quote engine


do Carmo Riemannian Geometry Exercise 2.3: definition of $\nabla$ for an immersion - Part II

Question: The following is Exercise 3 of Chapter 2 of my Brazilian edition of do Carmo's Riemannian Geometry:

Let $f: M^n \to \overline M^{n + k}$ be an immersion from a differentiable manifold $M$ to a Riemannian manifold $\overline M$. Assume in $M$ the Riemannian metric induced by $f$:
$$
\langle u, v \rangle_p = \langle df_p(u), df_p(v) \rangle_{f(p)}.
$$
Let $p \in M$ and $U \subset M$ be a neighborhood of $p$ such that $f(U) \subset \overline M$ be a submanifold of $\overline M$. Let $X, Y$ be vector fields on $f(U)$ and extend then to vector fields $\overline X, \overline Y$ on an open subset of $\overline M$. Define
$$
(\nabla_X Y)(p) = \text{tangential component of } \overline \nabla_{\overline X} \overline Y(p),
$$
where $\overline \nabla$ is the Riemannian connection of $\overline M$. Prove that $\nabla$ is the Riemannain connection of $M$.

As already discussed in this question, the notation is very confusing and in fact wrong. Proceed as in the answer to the linked question:
if $X, Y$ are vector fields on $U$, we consider the vector fields $df(X), df(Y)$ on $f(U)$ and extend these vector fields to $\overline X, \overline Y$ on an open set of $\overline M$. Recall also that we have the following decomposition of the tangent space at $f(p)$:
$$
T_{f(p)}\overline M = df_p(T_pM) \oplus (df_p(T_pM))^\perp,
$$
and we call the tangential component of $\overline \nabla_{\overline X} \overline Y$ the terms in $df_p(T_pM)$. So the correct definition for $\nabla$ is
$$
\nabla_X Y(p) = (df_p)^{-1}( \text{tangential component of }\overline \nabla_{\overline X} \overline Y(f(p))).
$$
First we show that $\nabla$ well-defined, i.e., does not depend on the extensions $\overline X, \overline Y$. Indeed, if $\overline X_1, \overline X_2, \overline Y_1, \overline Y_2$ are two distinct extensions of $df(X), df(Y)$ respectively, then they coincide at $f(p)$. Then their tangential components coincide and $\nabla$ is indeed well-defined.
Now, in order to show that $\nabla$ is a connection, we have to show the three defining properties. Don't we need that $f$ be in fact an embedding, in order to be able to define $g \circ f^{-1}$ to prove, for example, $\nabla_{g X + h Y}Z = g \nabla_X Z + h \nabla_Y Z$?
Also, how to show that this connection is compatible with the Riemannian metric?
Finally, is the following argument for symmetry correct?
Ordering the basis in $T_{f(p)}\overline M$ so that $X_1, \ldots, X_n \in df_p(T_pM)$:
\begin{align*}
\nabla_{X_i} X_j - \nabla_{X_j} X_i & = (df_p)^{-1}\left(\sum_k\Gamma_{ij}^k X_k\right) - (df_p)^{-1}\left(\sum_k\Gamma_{ji}^k X_k\right) \\
& = (df_p)^{-1} \left(\sum_k(\Gamma_{ij}^k-\Gamma_{ji}^k) X_k \right) \\
& = 0
\end{align*}
by the symmetry of $\overline \nabla$. Thus $\nabla$ is symmetric.
Comment: Although the identification $U \to f(U)$ is confusing when you first see it, this abuse of notation is used by almost everyone. You will have to translate from one to another in your head.
Answer: First, your checking that $\nabla_XY$ is well defined independent of $\overline X, \overline Y$ is unclear: to take an analogy, even if two functions $f_1, f_2$ agree at a point $p$, it does not imply that $f'_1 = f_2'$ at $p$.
To check that $\nabla$ is well-defined, we split into two steps:

If $\overline X, \widetilde X$ are both extension of $df(X)$, then for any local vector fields $Z$ on $V\subset \overline M$ and for all $p\in U$,
$$ \overline \nabla_{\overline X} Z = \overline \nabla_{\widetilde X} Z\ \ \ \ \ \ \text{ at } f(p).$$
Proof: This follows from the fact that $\overline \nabla$ is $C^\infty$-linear in that component, thus the value $\overline \nabla_{\overline X} Z(f(p))$ depends only on $\overline X(f(p))$.

Let $\overline Y, \widetilde Y$ are both extension of $df(Y)$ and $\overline X$ is tangential to $f(U)$, then
$$\tag{2} \overline \nabla _{\overline X} \overline Y =  \overline \nabla _{\overline X} \widetilde Y\ \ \ \ \ \text{ at }f(p).$$
Proof: this follows from the fact that covariant differentiation can be computed using parallel transport (here): In particular, since $\overline X$ is tangential to $f(U)$, one can find an integral curve of $\overline X$ which lies inside $f(U)$ (For example, let $\gamma : (-\epsilon, \epsilon)\to M$ be an integral curve of $X$. Then $f\circ \gamma$ is an integral curve of $\overline X$ lying inside $f(U)$). Since $\overline Y, \widetilde Y$ agrees on $f(U)$, (2) is shown.

Second, we show that $\nabla$ is indeed a connection. To begin with, we show
(1) For any local vector fields $X, Y$ on $U$ and local smooth functions $\varphi:U \to \mathbb R$, we have
$$\nabla_{\varphi X} Y (p) = \varphi(p) \nabla_X Y(p), \ \ \ \forall p\in U.$$
Proof: let $\overline \varphi$ be a smooth function on $V\subset \overline M$ which extends $\varphi\circ f^{-1} : f(U) \to \mathbb R$. That is, for all $f(p) \in f(U)$ we have
$$ \varphi (p) = \overline \varphi (f(p)).$$
Then $\overline \varphi \overline X$ is an extension of $df (\varphi X)$. So
\begin{align*}
\nabla _{\varphi X} Y(p) &= df^{-1} \bigg(\text{tangential component of } \overline \nabla_{\overline\varphi \overline X} \overline Y(f(p))\bigg) \\
&= df^{-1} \bigg(\text{tangential component of }\ \overline\varphi (f(p)) \overline \nabla_{\overline X} \overline Y(f(p))\bigg) \\
&= \varphi (p) df^{-1} \bigg(\text{tangential component of }\overline \nabla_{\overline X} \overline Y(f(p))\bigg) \\
&= \varphi (p) \nabla_X Y (p).
\end{align*}
(2) We show also that $\nabla$ is compatible with the pullback metric $g = f^*\bar g$, let $X, Y, Z$ be vector fields. Then by definition,
$$ X g(Y, Z)(p) = \frac{d}{dt}\bigg|_{t=0} g_{\gamma(t)}( Y(\gamma(t)), Z(\gamma(t))),$$
where $\gamma : (-\epsilon, \epsilon) \to M$ is any curve with $\gamma(0) = p$, $\gamma'(0) = X(p)$. Using the definition of pullback metric,
$$ g_{\gamma(t)}( Y(\gamma(t)), Z(\gamma(t))) = \bar g_{f(\gamma(t))} (df_{\gamma(t)} Y(\gamma(t)), df_{\gamma(t)} Z(\gamma(t))).$$
Since $f\circ \gamma$ is a curve in $\overline M$ with $f\circ \gamma (0) = f(p)$, $(f\circ \gamma)'(t) = df_{\gamma(t)} X(\gamma(t))$, we have
\begin{align*}
\frac{d}{dt}\bigg|_{t=0} g_{\gamma(t)}( Y(\gamma(t)), Z(\gamma(t)))&= \overline X \bar g (\overline Y, \overline Z) f(p)\\
&= \bar g(\overline \nabla _{\overline X} \overline Y , \overline Z ) + \bar g(\overline Y , \overline \nabla _{\overline Y} \overline Z) \ \ \ \ \ \text{ at } f(p)\\
&= \bar g(df (\nabla _{X} Y) , df ( Z) ) + \bar g(df(Y) , df(\nabla _{Y} Z) \\
&= g(\nabla_X Y, Z) + g(Y, \nabla_XZ)
\end{align*}
at $p$. Note we used that $\overline Y, \overline Z$ are tangential to $f(U)$, so that we have
$$ \bar g (\overline \nabla_{\overline X} \overline Y, \overline Z) = \bar g ((\overline \nabla_{\overline X} \overline Y)^\top, \overline Z),$$
where $(\cdot)^\top$ denotes the tangential part of a vector.
Finally, in your checking of the symmetry of $\nabla$ you used $\Gamma_{ij}^k = \Gamma_{ji}^k$, which a priori you do not know yet. Indeed the symmetry of $\nabla$ is equivalent to the symmetry of $\Gamma$.
To give a correct proof we, just like all the others properties we proved, pushforward everything to $\overline M$, prove the property there and then pullback: by definition,
\begin{align*}
\nabla_X Y- \nabla_Y X &= df^{-1} \left( \overline\nabla_{\overline X} \overline Y - \overline\nabla _{\overline Y} \overline X\right)^\top \\
&=  df^{-1} ([\overline X, \overline Y]^\top).
\end{align*}
Since $f(U)$ is a submanifold and $\overline X, \overline Y$ are tangential to $f(U)$,
$$ [\overline X, \overline Y]^\top = [\overline X, \overline Y] = [df (X), df(Y)]$$
(this can be check directly, assuming that $f(U)$ is a plane $\mathbb R^n \subset \mathbb R^{n+k}$. The Riemannian structure is not used here). Then by this, we have
$$\nabla_X Y- \nabla_Y X = [X, Y].$$
Comment: Concerning your question, (1) yes it is just a pointwise argument that you can pull out $\varphi (p)$. (2) I've added something about finding the integral curve (3) $df(X)$ is not a vector field on $N$. it is defined only on $f(U)$ and we need to extend it to a (local) vector field on $N$. @DaniloGregorin
Comment: Thank you very much for the most complete and clear answer (and also for all the help you've given me in the past days). However, I have some doubts. To begin with, don't we need some argument to say that $\overline \varphi \overline X$ extends $df( \varphi X)$? Also, why does $\overline \varphi$ "comes out" of $(df)^{-1}$ as $\varphi$?
Comment: Regarding the first question, is it a pointwise argument? Something along these lines: for each $p \in U$ we have $\varphi(p) \in \mathbb R$, so $df(\varphi(p) X_p) = \varphi(p) df(X_p)$, implying that the value of the vector field $df(\varphi X)$ at $q \in f(U)$ is $\varphi(f^{-1}(q)) df(X)_q = \overline \varphi(f(p)) df(X)_q$?
Comment: How do we know that there is an integral curve of $\overline X$ in $f(U)$, when showing that $\nabla$ is well-defined?
Comment: A more fundamental question: In Lee's Intro to Smooth Manifolds, page 182, he says that for a given smooth map $F: M \to N$ and $X \in \mathfrak X(M)$, there may not be any vector field on $N$ that is $F$-related to $X$. But of course, if $df(X)$ is a vector field on $N$, it is trivially $f$-related to $X$. So how can we know that this is the case?
Comment: To use $\varphi \circ f^{-1}$ don't we need $f$ to be at least an homeomorphism? We do know that immersions are local diffeomorphisms, but glueing these diffeomorphisms (or, better, their domains) together doesn't seem to work.