Solving $\sqrt{x^2 +2x + 1}-\sqrt{x^2-4x+4}=3$

Question: My question is: Solve  $\sqrt{x^2 +2x + 1}-\sqrt{x^2-4x+4}=3$
I deduced that:$LHS= x+1-(x-2)$
I am unable to solve this equation.  I would like to get some hints to solve it.
Comment: By "whole root" do you mean square root, as in $\sqrt{x^2+2x+1}-\sqrt{x^2-4x+4}=3$?
Comment: Yes i meant the square root
Comment: like the one posted by André Nicolas
Comment: Abstract duplicate of [this recent question](http://math.stackexchange.com/questions/98157) and [this one.](http://math.stackexchange.com/questions/153818)
Comment: Please refer to : http://math.stackexchange.com/questions/167087/what-is-the-algorithm-for-solving-an-equation-like-this-one
Answer: $$\sqrt {x^2 +2x + 1}-\sqrt { x^2-4x+4}= \sqrt{(x+1)^2} - \sqrt{(x-2)^2}=|x+1|-|x-2|$$
You have to consider three cases:

$x \geq 2$
$-1<x<2$
$x \leq -1$
Comment: I didn't write the full solution as you asked for hints to solve it on your own.
Comment: Hey but there is a whole root sign
Comment: Oops, sorry. I'm not used to English-mathematics-nolatex notation!
Answer: $\sqrt {x^2 +2x + 1}-\sqrt { x^2-4x+4}= \sqrt{(x+1)^2} - \sqrt{(x-2)^2}=|x+1|-|x-2|=3$
$|x+1|-|x-2|=3$
1) $x\in(-\infty, -1)$$\Rightarrow$$|x+1|=-(x+1)=-x-1$, $|x-2|=-(x-2)=2-x$.
$|x+1|-|x-2|=3$$\Rightarrow$ $-x-1-2+x=3$$\Rightarrow$$-3=3$, this is a contradiction.
In this interval equation has no solution.
2) $x\in[-1, 2)$$\Rightarrow$ $|x+1|=x+1$, $|x-2|=-(x-2)=2-x$.
$|x+1|-|x-2|=3$$\Rightarrow$ $ x+1-2+x=3$ $\Rightarrow$$2x=4$$\Rightarrow$$x=2$.
$2\notin [-1, 2)$. Also in this interval equation has no solution.
3)  $x\in(2, \infty)$$\Rightarrow$ $|x+1|=x+1$, $|x-2|=x-2$.
$|x+1|-|x-2|=3$$\Rightarrow$ $ x+1-x+2=3$ $\Rightarrow$$3=3$.
On this interval equation has infinity solutions.
Comment: More precisely, the last interval **is** the solution set. It would still have "infinity solutions" if the solution set were, say, $(2,3)$, or the set of integers greater than $2$.
Comment: Nitpick: The number $2$ is not contained in any of your intervals now.


why $\mathbb{Q}[x]= \mathbb{Q}(x)?$

Question: Theorem :  If  $x$  is  algebraic over $\mathbb{Q} $, then  $\mathbb{Q}[x]= \mathbb{Q}(x)$
My doubt : Here $\mathbb{Q}(x)$ is field  and $\mathbb{Q}[x]$ is not field  since $\frac{1}{x} \notin \mathbb{Q} $ but $\mathbb{Q}[x]$ is ring
we know  that  field  $\neq$  ring
Then why  $\mathbb{Q}[x]= \mathbb{Q}(x)?$
Comment: I think you're confused about ambiguous notation: in the context of the theorem $\Bbb Q[x]$ is not the polynomial ring, but the subring generated by $\Bbb Q$ and $x$ (in some field extension)
Comment: $\frac 1x\notin\mathbb Q$ does not show $\mathbb Q[x]$ is not a field. You have to show it's not in $\mathbb Q[x]$. And the thing is, the inverse is actually in it when $x$ is algebraic, and eventually it is a field.
Comment: Try here! https://math.stackexchange.com/q/1098032/914078
Comment: You can first show that $\mathbb{Q}[x]$ is a field. See here: https://math.stackexchange.com/questions/397733/ring-inside-an-algebraic-field-extension . Then note that $\mathbb{Q}(x)$ is the field of fraction of $\mathbb{Q}[x]$.
Comment: Consider, say, $\Bbb Q(\sqrt[3]2)$. What does a typical element in that field look like? Then consider $\Bbb Q[\sqrt[3]2]$. What does a typical element in that ring look like? See any similarities that might hint at an isomorphism? (And "field $\neq$ ring" is ambiguous. It's true that the requirements of a field and the requirements of a ring aren't the same, and the collection of all fields and the collection of all rings are different collections. But any field is a ring, with additional requirements.)
Comment: This is standard theorem that if $\alpha$ is algebraic over any field $F$ then $F[\alpha] =F(\alpha) $ ie rational functions in $\alpha$ with coefficients in $F$ can also be expressed as polynomials in $\alpha$ with coefficients in $F$. This is very straightforward for simple examples when $\alpha=\sqrt{2}$, but the proof for general algebraic $\alpha$ needs the idea of GCD of polynomials.
Comment: I hope your textbook includes a proof of the theorem and you should try to study it carefully.
Comment: @Arthur can you  check   my answer in answer box whether my solution is correct or not ?
Answer: Take $f(x)=x^2 +1 \in \mathbb{Q}[x]$.
$x^2+1=0 \implies x= i$
Here
$$\frac{\mathbb{Q}[x]}{f(x)} \cong \mathbb{Q}[i]$$
since $\langle f(x)\rangle$  is  maximal  $\implies \mathbb{Q}[i] \subseteq \mathbb{Q}(i) \tag1$
Also $x^{-1} \in \mathbb{Q}[x]$ this $\implies \mathbb{Q}(i) \subseteq \mathbb{Q}[i]\tag2$
From $(1)$ and $(2)$ we have $\mathbb{Q}[i] = \mathbb{Q}(i)$
Comment: This is not enough. What immediately jumps out to me is that you shouldn't just claim that $i^{-1}\in \Bbb Q[i]$. You should prove it. For instance, you could point out that we have $i^{-1} = -i\in \Bbb Q[i]$. More fundamentally, though, you haven't proven that, say, $(i+1)^{-1}\in \Bbb Q[i]$. Or any other non-zero complex number. They all need to be there. And once you've done that, you've proven that $\Bbb Q[i] = \Bbb Q(i)$. But that's just one algebraic number. It should be proven for all of them.

why $\mathbb{Q}[x]= \mathbb{Q}(x)?$


Windows Embedded Compact 7 Applicationwide Errorhandler

Question: I want to implement an applicationwide Errorhandler under Windows Embedded Compact 7. It shall catch all exceptions that haven't been caught on their way up the call stack.
It is a Winforms Compact Framework 3.5,  C# application. The application is multithreaded.
Any hint, or also a link to usefull informations.
Answer: You can use the AppDomain.UnhandledException event. Main aspect of the code from the link.
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler(MyHandler);

//event handler
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
   Exception e = (Exception) args.ExceptionObject;
   Console.WriteLine("MyHandler caught : " + e.Message);
}

It seems the CF does not have an equivalent of the ThreadException. However, according to this post, it doesn't need it:

With NETCF 2.0, we still don't have Application.ThreadException but,
  unlike the desktop scenario, we don't need it since the NETCF 2.0
  AppDomain.UnhandledException catches all unhandled exceptions.

I assume nothing has changed on that front from 2.0 to 3.5.


UWP MapControl: distinction between user- and app-manipulation

Question: Within an UWP-App containing a MapControl, is there a way to distinct between a manipulation to the map made by the user (e.g. by pinch to zoom) and one, that is made by the app itself? (e.g. by calling mapControl.TrySetViewAsync(...))
It doesn't seem like that there's an eventhandler for that, right?
I already tried several ones (like LoadingStatusChanged or CenterChanged), but none of them are making any difference between user- and app-manipulation..
Comment: Just found this suggestion brought to the bing-devs: https://binglistens.uservoice.com/forums/283355-ideas/suggestions/9494889-add-a-centermanuallychanged-event-to-mapcontrol - but is there a way to do it yourself atm?
Answer: You should be able to register to receive a TargetCameraChanged event that will fire whenever the map view changes. The MapTargetCameraChangedEventArgs returned contain a ChangeReason property.
The ChangeReason property will be System, UserInteraction or Programmatic.
Map movements caused by calling APIs such as TrySetViewAsync(...) cause events that have ChangeReason == Programmatic, and movements caused by user actions such as pinch to zoom should have ChangeReason == UserInteraction.
Comment: I've made a small edit to your answer to make it more readable (at least as I see it), if you find it bad, don't hesitate to rollback. Also +1 for the answer.
Comment: Thank you for your help!


How to run custom code on rollback?

Question: I have write a migration class to enter the value in custom table. But I want to know that how to rollback custom table entry.
I used :
public function complete($entity, stdClass $row) {
  // db_insert in my custom table
}

I want to rollback the above changes. For this I tried the completeRollback method below but it is not working.
public function completeRollback($entity_id) {
  dsm($entity_id);
}

Answer: You want to use prepareRollback() because at that point the thing that you are rolling back has not been removed yet.
public function prepareRollback($entity_id) {
  parent::prepareRollback();
  // Code to execute before an entity has been rolled back
}

Take a look at this guide for more info.
Comment: No luck..... :(
Comment: this is in MigrateDestinationEntity, not Migrate class, fyi
Answer: What I just did for the solutions is, I set the variable in complete function as like :
public function complete($entity, stdClass $row) {
  $migrated_variable = variable_get('migrated_variable', array());
  $migrated_variable[] = $entity->nid;
  variable_set('migrated_variable', $migrated_variable);
}

And used in postRollback function :
  public function postRollback() {
    parent::postRollback();
    $migrated_variable = variable_get('migrated_variable', array());
    foreach ($migrated_variable as $nid) {
      db_delete('custom_table')
        ->condition('nid', $nid)
        ->execute();
    }
    variable_del('migrated_variable');
  }

How to run custom code on rollback?


How To print composit element in twig file

Question: I have my twig file for theming pdf submission. In my webform there is a "custom composite" element with three fields, is multivalue and I set to display it as table.
Now, I must to print it in my twig file but I don't know how.
Comment: What Twig file? Have you tried Twig debugging already?
Comment: I'm using entity_print module with webform for theming webform_submission: entity-print--webform-submission--test.html.twig. I can print any simple data with this: {{ data. first name }} or {{ data.field1 }} but I don't know how to print a compost element.
Answer: This is a solution for my scenario and post it if can help anyone.
So, my "custom composite" element is multivalue and for print it in my custom entity-print--webform-submission--test.html.twig file I have insert this code:
{% for item in data.my_custom_composite %}

                {{ item.day|date('d.m.Y') }}
                {{ item.from }}
                {{ item.to }}

            {% endfor %}


Solution for DDOS

Question: My server is under DDoS attacks. I see my access log and get something:
<code> 968966 93-97-53-41.zone5.bethere.co.uk - - [27/Jul/2011:12:13:58 +0700] "GET /forum/forum.php HTTP/1.1" 200 91231 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.        1)"
 968967 126.96.36.199 - - [27/Jul/2011:12:13:39 +0700] "GET /forum/forum.php HTTP/1.0" 200 91539 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
 968968 188.8.131.52 - - [27/Jul/2011:12:13:38 +0700] "GET /forum/forum.php HTTP/1.1" 200 91228 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
 968969 cable-27-4.botevgrad.com - - [27/Jul/2011:12:13:39 +0700] "GET /forum/forum.php HTTP/1.1" 200 91228 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
 968970 18.104.22.168 - - [27/Jul/2011:12:13:39 +0700] "GET /forum/forum.php HTTP/1.0" 200 91539 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
 968971 22.214.171.124 - - [27/Jul/2011:12:13:39 +0700] "GET /forum/forum.php HTTP/1.0" 200 91539 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
 968972 18.104.22.168 - - [27/Jul/2011:12:13:35 +0700] "GET /forum/forum.php HTTP/1.0" 200 91539 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
 968973 18.104.22.168 - - [27/Jul/2011:12:13:58 +0700] "GET /forum/forum.php HTTP/1.1" 200 91542 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
 968974 ::1 - - [27/Jul/2011:12:14:03 +0700] "OPTIONS * HTTP/1.0" 200 - "-" "Apache (internal dummy connection)"
 968975 18.104.22.168 - - [27/Jul/2011:12:13:58 +0700] "GET /forum/forum.php HTTP/1.1" 200 91231 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
 968976 ::1 - - [27/Jul/2011:12:14:03 +0700] "OPTIONS * HTTP/1.0" 200 - "-" "Apache (internal dummy connection)"
</code>
I don't have any experiences about DDoS, please help me find and resolve issue? :(
My server is CentOs 5.4 Apache 2.2 and PHP 5.2.6.
Thanks,
Comment: do you have the resources to place a hardware firewall in front of the server?
Comment: No, I didn't used hardware firewall.
Answer: A DDOS is a tough thing. By the time it's reached your server, or your network, it's already too late. Call your ISP. They're the proper ones to deal with a DDOS attack. Give them as much information as possible so they can find a pattern and block it.
Answer: As Jason already pointed out, your best current option is to call your ISP/Hoster for help.
After that, sign up for a CDN, if possible - they thwart most DDoS'es by design, or at least, make them only a localized nuisance. There are many CDN's which provide some free plan, which might be sufficient for you. I heard good stuff about CloudFlare, and used it a bit at some point. YMMV.
Answer: Theoretically, u can use Client Puzzle to solve DDos attack. Depend on the situation, you may use different kind of puzzle to solve your problems.
[May I know, how do you know if you are under DDos attack from above log?]
Comment: CPP won't help you if the traffic is saturating your upstream links. The only thing you can do is work with your provider to blackhole the traffic.
Comment: I use this command: watch "netstat -an | grep ':80' | awk '{print \$5}' | sed s/'::ffff:'// | cut -d\":\" -f1 | sort | uniq -c" and found a lot of requests from each IP in my access-log. So I think my server attacked by DDoS.
Comment: Without the additional double-quotes, the command by Tuan is as: netstat -an | grep ':80' | awk '{print $5}' | sed s/'::ffff:'// | cut -d":" -f1 | sort | uniq -c
Answer: For a quick fix if you are aware of active DDOS
The page/site/portal where you are being DDOSed in the index.php pnly (or however you are handling the code flow in case of mvc) you can restrict the hacker's IP and return him true or false. and prevent him from hampering your Database.
 As avoiding abusive traffic and returning a sorry page would always be a better way than letting them impact the database.
Comment: You unfortunately seem to have a fundamental misunderstanding of a DDoS: good Luck trying to block those thousands of IPs. Also, there is the same issue present with a CPP: upstream bandwidth.
Comment: 100% agree in case if there are thousands of the IPs which are targeting. But as the log posted shows me few I suggested the quick fix of blocking those which are actively attacking (which was happening in my own case). Also in case if they are many and are targeting one portal and and which ultimately is hitting the database i am using for multiple clients, I'd prefer to block/take down one portal for a while. Any wise suggestion to clear my fundamental misunderstanding will be a great help.

Solution for DDOS


Display photo bigger when click on it flutter

Question: How i can make a photo in my app to be displayed bigger when you click it . For example when you searching for a photo on google and then when you click it , it's popping out bigger .
children: <Widget>[
                                  Container(
                                    margin: EdgeInsets.only(
                                        top: 8, bottom: 8, right: 12),
                                    width: 80,
                                    decoration: BoxDecoration(
                                        image: DecorationImage(
                                            image: NetworkImage(
                                                "https://i.pinimg.com/originals/d4/05/f9/d405f9671b3dd8e365dd97e50e801f86.jpg"),
                                            fit: BoxFit.cover),
                                        color: Colors.red,
                                        boxShadow: [
                                          BoxShadow(
                                              color:
                                                  Colors.black.withOpacity(0.1),
                                              blurRadius: 2,
                                              spreadRadius: 1)
                                        ],
                                        borderRadius: BorderRadius.circular(4)),
                                  ),

Comment: You can take a look at this answer it have all the detailed code - https://stackoverflow.com/questions/62623892/flutter-long-press-on-picture-to-get-zoomed-preview-like-instagram/62625820#62625820
Answer: You may want to take a look at the widget called Hero (https://flutter.dev/docs/development/ui/animations/hero-animations)
Otherwise, you could simply use a variable "_imgWidth" set to 80 by default and as you click on the image wrapped in a InkWell or a GestureDetector, call
setState({
  _imgWidth = _imgWidth == 80 ? 160 : 80;
})


If $\,1 + \frac {1}{2}+\frac {1}{3} +..... +\frac {1}{p-1} = \frac {a}{b}$ then $p\mid a$

Question: Let $p$ be an odd prime and let $1 + \frac{1}{2} + \cdots + \frac 1{p-1} = \frac ab$, where $a,b$ are integers. Show that $p\mid a$. (Hint: As $a$ runs through $U_p$, so does $a^{-1}$.)
P.S. $U_p$ means the group of of invertible elements in $\mathbb{Z}_p$, and I believe for prime $p$, $U_p = \mathbb{Z}_p$.
Comment: For prime $p$, $U_p = \mathbb{Z}_p \setminus \{0\}$.
Answer: Hint: If you take $\pmod p$ on both side,  do you see that $\sum_\limits {n=1}^{p-1} 1/n \equiv \sum  \limits_ {n=1} ^{p-1} n \pmod p   $ ?
Comment: Oh, this is what "run through" mean. Thank you so much!


Is it possible that bounded function on a compact interval of $\mathbb{R}$ has infinite Riemann integral?

Question: Is it possible that a bounded function on a compact interval of $\mathbb{R}$ has infinite Riemann integral?
Answer: No. If $f$ is bounded (and integrable) on $[a,b]$, then
$$
\left|\int_a^b f \, dx\right| \leq \int_a^b |f| \, dx \leq (b-a)\max_{[a,b]}|f|.
$$
Answer: If the absolute value of the function is less than $M$ and the length of the interval is less than $l$, then none of the Riemann sums will exceed $Ml$ in absolute value.  So, in short, no.  This isn't possible.
On the other hand, there are plenty of bounded functions on compact intervals for which the limit which defines a Riemann integral won't exist.  So a bounded function might fail to be integrable, but you won't get any infinities showing up.


Can a fielder pretend to field a ball to deceive the batter/runners?

Question: In baseball, if a ball is hit, can a fielder such as the shortstop or third baseman pretend to have caught or fielded the ball to trick a runner into not running, or a batter into not advancing?
What are the limitations, if any? Could the player tag the runner, or could the whole team jog to the dugout in hopes of making the runners think the inning is over?
Answer: A fielder can act like however they want as long as they are not impeding any runners.   There are no rules that cover this because it is not against the rules.
Tagging a runner would just be interference.   You are not allowed to touch a runner if you do not have the ball.
Jogging to the dugout... I am not sure how this works.   Who is going to tag a runner out if everyone is in the dugout?  The runner unless we are talking about 8 year old baseball would be looking at an umpire to make an out call.  Also any good umpire would signal a strong "safe" call or shout out the number of outs if they felt there was confusion.
The only limitation of a hidden ball play where players act like they are going to the dugout is the pitcher must not be a stride from the rubber.   If he is, that is a balk.


Phase portraits

Question: I have problem and need your help. I must draw phase portraits of dynamical system which looks like this:
$$\dot{x}_{1}(t) = -x_{1}(t) + x_{2}(t)$$
$$\dot{x}_{2}(t) = -x_{2}(t)$$
I know that the first I sould get eigenvector and eigenvalue of matrix but I'm not soure. Is this matrix will looks like this:
$$\begin{matrix}
  -1 & 1  \\
  -1 & 0  \\
 \end{matrix}$$
Am I right? What sould I do next?
Comment: A very helpful website and tool for drawing phase portraits can be found at http://math.rice.edu/~dfield/dfpp.html
Comment: In your particular case the situation is a bit difficult because the eigenvalues are complex. They both have negative real part, which means the origin is ultimately stable, but you need to know how to interpret the complex eigenvalues/eigenvectors to properly sketch how the solutions spiral in towards the origin. An easier example to sketch would be $\begin{bmatrix} -1 & -1 \\ -1 & 0 \end{bmatrix}$, which has a saddle point instead of a stable spiral at the origin.
Comment: Apparently I get down-voted for attempting to educate rather than hand over the answer on a plate, but the linearised system is wrong as stated in the question
Comment: I didn't down-voted you but it was a bit hard to check is something is Hamiltonian when you hear this word first time in life ;). To find some information about dynamical systems in homeland language is really hard and my science english isn't so good, i read this like forth time and still don;t know how do to it ;/
Comment: Oh, there IS a typo: you actually have $\begin{bmatrix} -1 & 1 \\ 0 & -1 \end{bmatrix}$. This is quite different from what you wrote, because this system is "defective", meaning that there is a single real eigenvalue of algebraic multiplicity $2$ and geometric multiplicity $1$. This comes with a certain characteristic behavior.
Answer: Not sure I understand what you are asking exactly but, if you want to draw a phase portrait, draw a phase portrait:

The general approach is to delineate the regions of the $(x_1,x_2)$-plane where $x'_1$ and $x'_2$ have a constant sign, and to deduce the variations of the solutions from this decomposition. These regions are limited by the so-called nullclines, which are the lines where $x'_1=0$ or $x'_2=0$.
In the present case, $x'_1=0$ corresponds to the first diagonal $x_2=x_1$ and $x'_2=0$ corresponds to the horizontal axis $x_2=0$. For example, at every point in the region $0<x_2<x_1$ (North-East to East angular sector), the dynamics points to the South-East ($x'_1<0$, $x'_2<0$). Likewise for the three other angular sectors and the four halflines which delimit them (whose union is the union of the nullclines), hence the diagram above.
Finally, in case the system you are interested in is actually $$x'_1=-x_1+x_2\qquad x'_2=-x_1$$ the same procedure applies, and yields the phase portrait below.
Comment: Did is describing the method of nullclines, which can be easily googled for more details.
Answer: First thing should be to check if it's Hamiltonian which makes the whole process much easier as you just sketch level sets.
Find the stationary points, then classify them using the trace and determinant of the linearized system at those points. You can find the eigenvectors to find the orientation of sources/sinks/saddles/centres if it's not obvious from plugging in some values.
This should get you quite some way to a complete portrait.
Comment: That useful but could you say step by step or show on example how should i do that? This is my first time in this kind of math thats will be very grateful

Phase portraits


Foto tirada pela minha app não aparece na Galeria

Question: Ao gerar a foto através do meu app ele cria corretamente a pasta e salva as fotos tiradas lá, mas quando vou na galeria do Celular é como se as fotos não existissem, a galeria padrão do Android não reconhece os arquivos.
Alguém saberia me dizer se tem alguma permissão que preciso dar para que as fotos possam ser visualizadas na galeria? Ou até mesmo se isso seria uma configuração do Android.
Estou Utilizando a 4.0 do Android
private void addImage() {
     Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
     intent.setData(uri);
     this.sendBroadcast(intent);
}

Answer: Isso acontece porque a Galeria só é atualizada, pelo SO do Android, de tempos a tempos.
Para que a Galeria seja actualizada imediatamente você necessita de chamar o método scanFile da classe MediaScannerConnection.
Defina os seguintes métodos no seu programa:
void doScanFile(String fileName) {
        String[] filesToScan = {fileName};

        MediaScannerConnection.scanFile(this, filesToScan, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String filePath, Uri uri) {
                        mediaFileScanComplete(filePath, uri);
                    }
                });
}

void mediaFileScanComplete(String mediaFilePath, Uri mediaFileUri) {

   //Guarde esta informação se você necessitar dela.
    _lastMediaFilePath = mediaFilePath;
    _lastMediaFileUri = mediaFileUri;
}

Chame o método doScanFile(fileName) após ter salvo a foto.
Em alternativa pode lançar um Broadcast para indicar que houve uma alteração no arquivo de mídia:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(fileName))));

Comment: Funcionou direitinho, muito obrigado


Applying Brush Effect to Whole Word While Animating Each Letter Individually in Jetpack Compose

Question: I am trying to create a text effect in Jetpack Compose where the text uses a brush that looks like a set of colors smoothly changing diagonally. The individual letters in the text should move up and down, as well as make half turns.
I have encountered two problems:

If I try to apply the brush to the whole word, I don't know how to
animate the letters that are moving and rotating. Here is the code I
have tried:

<code>        Text(
        text = word,
        fontSize = fontSize,
        style = LocalTextStyle.current.copy(brush = gradientBrush),
        modifier = modifier
    )
</code>

If I apply the animation to each letter individually, I can achieve
the desired result with the animation, but the brush is applied to
each letter individually as well, creating an unattractive effect. I
need the brush to be applied to the whole word. Here is the code I
have tried:

<code>    Row {
        word.forEachIndexed { index, char ->
            val angle by rotationAngles[index]
            val offset by letterOffsets[index]
            Text(
                text = char.toString(),
                fontSize = fontSize,
                style = LocalTextStyle.current.copy(brush = gradientBrush),
                modifier = Modifier
                    .rotate(angle)
                    .offset(y = offset.dp)
            )
        }
    }
</code>
Here are two demonstrations:

The desired result of applying the brush to the whole word, but I don't know how to animate the letters.
The desired result of applying the animation, but I can't apply the brush to the whole word (the brush is applied to each letter individually).

How can I create an animation of moving up, down, and half-turning for each letter individually, while applying the brush to the whole word in Jetpack Compose?
Here is the full code:
<code>@Preview(showBackground = true)
@Composable
fun RotatingLettersPreview() {
    RotatingLetters("Medium")
}

@OptIn(ExperimentalTextApi::class)
@Composable
fun RotatingLetters(word: String,
                    fontSize: TextUnit = TextUnit.Unspecified,
                    modifier: Modifier = Modifier) {

    val colorGradient = listOf(
        Color(0xFFC0EFFF), // Light blue
        Color(0xFF9BDBFB), // Medium blue
        Color(0xFF75C2F9), // Dark blue
        Color(0xFFF7D7C4), // Light pink
        Color(0xFFF5B2C7), // Medium pink
        Color(0xFFF28BAE), // Dark pink
        Color(0xFFF7F2D4), // Light beige
        Color(0xFFF5E0C3), // Medium beige
    )

    val fontSizeInPx = with(LocalDensity.current) { 30.sp.toPx() }
    val doubleFontSizeInPx = fontSizeInPx * 2

    val infiniteTransitionForOffset = rememberInfiniteTransition(label = "")
    val offsetAnimation by infiniteTransitionForOffset.animateFloat(
        initialValue = 0f,
        targetValue = doubleFontSizeInPx,
        animationSpec = infiniteRepeatable(tween(200000, easing = LinearEasing)), label = ""
    )

    val gradientBrush = remember(offsetAnimation) {
        object : ShaderBrush() {
            override fun createShader(size: Size): Shader {
                val widthOffset = size.width * offsetAnimation
                val heightOffset = size.height * offsetAnimation
                return LinearGradientShader(
                    colors = colorGradient,
                    from = Offset(widthOffset, heightOffset),
                    to = Offset(widthOffset + size.width, heightOffset + size.height),
                    tileMode = TileMode.Mirror
                )
            }
        }
    }

    val infiniteTransitionForRotation = rememberInfiniteTransition(label = "")
    val rotationDirection = remember { mutableStateOf(1) }

    val rotationAngles = List(word.length) { index ->
        infiniteTransitionForRotation.animateFloat(
            initialValue = 0f,
            targetValue =
            if (index % 2 == 0) 5f * rotationDirection.value else -5f * rotationDirection.value,
            animationSpec = infiniteRepeatable(
                animation = tween(250, easing = LinearEasing),
                repeatMode = RepeatMode.Restart
            ), label = ""
        )
    }

    LaunchedEffect(key1 = Unit) {
        while (true) {
            delay(250)
            rotationDirection.value *= -1
        }
    }

    val letterOffsets = List(word.length) { index ->
        infiniteTransitionForRotation.animateFloat(
            initialValue = 0f,
            targetValue = if (index % 2 == 0) 2f else -2f,
            animationSpec = infiniteRepeatable(
                animation = tween(250, easing = LinearEasing),
                repeatMode = RepeatMode.Reverse
            ), label = ""
        )
    }

    Text(
        text = word,
        fontSize = fontSize,
        style = LocalTextStyle.current.copy(brush = gradientBrush),
        modifier = modifier
    )

/*
    Row {
        word.forEachIndexed { index, char ->
            val angle by rotationAngles[index]
            val offset by letterOffsets[index]
            Text(
                text = char.toString(),
                fontSize = fontSize,
                style = LocalTextStyle.current.copy(brush = gradientBrush),
                modifier = Modifier
                    .rotate(angle)
                    .offset(y = offset.dp)
            )
        }
    }
*/
}
</code>
Answer: you can achieve a similar effect by using a combination of drawWithContent and clipping each letter to create a single continuous gradient across all letters. Here is a conceptual solution:
Create a custom composable that uses Canvas to draw the text manually, allowing you to apply a single gradient brush across the entire word.
Use drawWithContent to clip the drawing area to the bounds of each character when drawing them, so they can each animate independently while still sharing the same brush.
Here's an example of how you might implement it:
<code>@Composable
fun AnimatedGradientText(word: String, gradientBrush: Brush, fontSize: TextUnit, modifier: Modifier = Modifier) {
    // Calculate text size, character positions, etc.
    val textPaint = remember {
        Paint().asFrameworkPaint().apply {
        isAntiAlias = true
        style = android.graphics.Paint.Style.FILL
    }
}

// For each letter, create a rotation and offset animation.
val rotationAngles = remember { /* ... Your rotation animations ... */ }
val letterOffsets = remember { /* ... Your offset animations ... */ }

Canvas(modifier = modifier) {
    // Calculate text size and positions
    val textLayoutResult = remember(word, fontSize) { /* ... Measure text ... */ }

    word.forEachIndexed { index, char ->
        // Get animation values
        val angle: Float by rotationAngles[index]
        val offset: Float by letterOffsets[index]

        // Save the current canvas state
        save()

        // Position the canvas for this character
        translate(left + characterPositions[index], top)

        // Apply the rotation transformation
        rotate(angle)

        // Set the shader to the paint
        textPaint.shader = gradientBrush.asAndroidShader()

        // Draw this character
        drawContext.canvas.nativeCanvas.drawText(
            char.toString(),
            0f,
            0f + offset,
            textPaint
        )

        // Restore the canvas to avoid affecting subsequent characters
        restore()
    }
}
}
</code>


residuals in the simple regression model

Question: The residuals in the simple regression model have to sum up to 0?
Comment: In practice, yes.  In the abstract, it depends upon the loss function used to determine the parameter estimates; you could construct a loss function with a huge penalty for any negative error at all and a small penalty for a positive error, which might lead to all errors being $\geq 0$.
Comment: Please don't attempt to recruit answerers to your other questions in comments.
Comment: It's true if you use least squares.
Comment: isn't it always true?
Comment: thank you so much! Could you try to help me and in my other question i have posted? i am struggling with that
Answer:
The residuals in the simple regression model can not have the same sign, because the sum of the residuals must be equal to 0, right?

With ordinary least squares, this is indeed the case $-$ that the residuals sum to zero $-$ so they clearly cannot all have the same sign. It's certainly possible to have $n-2$ residuals of one sign and $2$ of the other. One interesting question is whether you can have fewer than two residuals with one of the signs but I suspect you can't avoid having at least two. [With regression through the origin, you could get it down to one, though.]
As jbowman suggests if you move away from least squares and (say) consider simple quantile regression, then it is possible to get a case where no residuals have one of the signs (e.g. no negative residuals).


Como enviar várias variáveis para outra página e retornar numa div (JQuery)?

Question: Estou tentando enviar dados de um formulário para uma outra página, e trazer da mesma um gráfico numa div com id="retorno",  que está abaixo do formulário.
O formulário possuí o código, data1, data2 e loja, porém parece que as variáveis não estão sendo enviadas de forma correta.
Já fiz algo parecido porém só com uma variável, mas com várias assim não.
Minha função jQuery está abaixo, acredito que tenha algo nela errado.
Achei vários exemplos na internet, porém nenhum me ajudou e resolveu o meu problema.
  $(document).ready(function() {

    //alert("teste 1 ");

    /// Quando usuário clicar no botão será feito todos os passo abaixo
        $('#formulario').submit(function() {

        //alert("teste 2");

            var codigo = $('#codigo').val();
            var data1 = $('#data1').val();
            var data2 = $('#data2').val();
            var loja = $('#loja').val();

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'retorna_produto.php',
                async: true,
                data: {codigo, data1, data2, loja},
                //data: {'codigo='+ $('#codigo').val(),
                //  'data1='+ $('#data1').val(),
                //  'data2='+ $('#data2').val(),
                //  'loja='+ $('#loja').val()
                //},
                success: function(data) {
                     $('#retorno').html(data);
                }
            });

            return false;
        });
    });

Answer:
O formulário possuí o código, data1, data2 e loja, porém parece que as
  variáveis não estão sendo enviadas de forma correta.

Verifique se os seletores de identificação estão de acordo.
Você pode simplificar a coleta das informações do formulário utilizando o serialize. um exemplo disto seria:

$('#formulario').submit(function(e) {
  e.preventDefault();
  var dados = $(this).serialize();
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: 'retorna_produto.php',
    data: dados,
    success: function(data) {
      $('#retorno').html(data);
    }
  });
});

<form id="formulario">
  <input type="text" name="codigo" value="1">
  <input type="text" name="data1" value="valor data 1">
  <input type="text" name="data2" value="valor data 2">
  <input type="text" name="loja" value="Loja 1">
  <button>
    Enviar Formulario
  </button>
</form>

Desta forma você pode passar uma queryString para o parâmetro data do ajax e enviar.
Outra coisa, no metodo submit é recomendado utilizar o preventDefault() ao inves do return false para previnir que a pagina seja recarregada.
Comment: Vou testar, obrigado.
Comment: Deu certo, obrigado, a única coisa que mudei foi o dataType: 'json', que tive que colocar dataType: 'html', senão não funcionava.


iOS : is there a leak?

Question: .h:
#import <UIKit/UIKit.h>
#import "Todo.h"
@interface TodoCostApplyViewController : UIViewController

{
    NSThread* headViewThread;
    NSThread* tableViewThread;
}
@property (nonatomic, retain) NSThread* headViewThread;
@property (nonatomic, retain) NSThread* tableViewThread;
@end

.m:
@interface TodoCostApplyViewController ()
@end
- (void)viewDidLoad
{
    [super viewDidLoad];
    headViewThread = [[NSThread alloc] initWithTarget:self
                                             selector:@selector(drawHeadView)
                                               object:nil];
    [headViewThread start];
    tableViewThread = [[NSThread alloc] initWithTarget:self
                                         selector:@selector(drawTableView)
                                           object:nil];
    [tableViewThread start];
}

- (void)dealloc
{
    [tableViewThread release];
    [headViewThread release];
}

Is there a leak of memory about tableViewThread and headViewThread ?
And if there is a leak, what should I do with this problem?
Thank you in advance!
Comment: looks fine and i think you missed to post the synthezise calls..
Comment: You have declared properties in the header but not used `@synthesize` or `@dynamic` for them.
Answer: Yes, there is a potential leak. viewDidLoad can potentially be called multiple times, in which case you would see memory leaks. Everything you retain in viewDidLoad should be released (and set to nil) at the latest in viewDidUnload (and also in dealloc).
Had you used the synthesized setters in viewDidLoad (as you should almost always do), the problem would be mitigated because every time viewDidLoad was executed, the old thread objects would get released when you assigned the new ones.

iOS : is there a leak?


Multiple hypothesis tests, "comparing the expected values"

Question: If I have two sets of random samples and I'd like to test whether there is some difference or not between them (or if one is better than the other) I'd test the null hypothesis
$H_0: \mu_1 = \mu_2$ with a one-tailed test. So if it turns out that the null hypothesis is rejected on some significance level I could say the one has a significantly higher mean than the other (It was some time ago I studied this so please correct me if I'm wrong).
But what if I have more than two sets of random samples, is it possible to do a similar (I would assume: set of) test(s) so that I could draw the conclusion that one or some of has a significantly higher mean than the others.
If possible you someone please direct me to some keywords, papers and/or briefly explain how it's done.
Thanks in advance!
Comment: You could look into analysis of variance (ANOVA) and the linear model, for a start. This is covered in a huge number of books.
Comment: Mike, "whether there is some difference" is a *two tailed* alternative. If you're using a one tailed test with what (before seeing the sample) is a two tailed alternative, that's basically halving your p-values by cheating (choosing the direction of the alternative after the fact). If on the other hand your (*a priori*) alternatives are truly directional, then the F-tests that ANOVA gives you are always non-directional. If your $k$-sample alternative is actually directional then a non-directional test becomes increasingly weak against your directional alternative compared to a suitable test.
Comment: Appropriate directional (ordered-alternatives) tests - there are both normal-parametric and nonparametric versions - have much better power; some parametric tests are to be found, for example in the book by Barlow, Bartholemew, Bremner and Brunk (1972) (or in papers by, for example, Bartholemew), and an example of an ordered non-parametric equivalent to one way ANOVA is the Jonckheere-Terpstra test.
Answer: Apart from ANOVA, also take a look at:

Dunnett's test
Hotteling's T-test: Use this when you have multivariate data (for ex: height, income, weight) and you want to compare the means "all at once"


What are the best practices for dealing with the Back Button in IE (and Firefox)

Question: I know this in old issue but I can't figure out the best practices for dealing with the back button.
I'm writing a web application with lots of data movement between the browser and the backend server. I currently use post and of course when the user bypasses the application navigation and uses the back button both IE and Firefox popup messages asking the user if they want to resend the data.
I tried "get" and aside from all the data being displayed within the URL, IE8 still generates a message.
Additionally I can't really identify when the post causes a message and when it doesn't, since I have test cases posting data where the back button does not cause a message.
My environment is JavaScript, PHP and MySQL.
Any help or pointer to a research location is greatly appreciated.
Edited:
I wrote 3 little pages to test posting a->b->c->a and they don't cause any postdata messages. I don't know why:
A
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test post A</title>

testPostA.php

Came from <?php print (isset($_POST['data'])?$_POST['data']:"NoWhere"); ?>

<form action="testPostB.php" method="post">
    <input name="data" type="text" value="from testPostA.php" />
    <input type="Submit" value="Submit To: testPostB.php" />
</form>

B
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test post B</title>

testPostB.php

Came from <?php print (isset($_POST['data'])?$_POST['data']:"No where"); ?>

<form action="testPostC.php" method="post">
    <input name="data" type="text" value="from testPostB.php" />
    <input type="Submit" value="Submit To: testPostC.php" />
</form>

C
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test post C</title>

testPostC.php

Came from <?php print (isset($_POST['data'])?$_POST['data']:"No where"); ?>

<form action="testPostA.php" method="post">
    <input name="data" type="text" value="from testPostC.php" />
    <input type="Submit" value="Submit To: testPostA.php" />
</form>

Answer: The Post/Redirect/Get pattern will prevent the re-POST warning.  However, you still have to take care that your application can handle/reject duplicate form submissions and the like.
Edit 1
For an application that's heavy on Javascript, I've also seen some design patterns that leverage the browser history and fragment identifiers to provide a more seamless integration with the back button, bookmarking, etc.
Edit 2
Regarding the addendum to your question, it's hard to say.  It could be that the in some cases the browser has the page cached and doesn't need to resubmit the POST to render the page again.  You could play around with various ways of disabling browser caching on these requests to see if you can make the behavior more predictable (i.e. always cause the resubmit warning). At any rate, I think web applications that follow the Post/Redirect/Get pattern are slightly more user-friendly, but your mileage may vary.
Another thing to keep in mind is that you can use method="get" on forms that are performing queries, generating reports, etc.  Sometimes GET is a better option in those read-only scenarios because it makes your URL scheme richer and avoids these sort of POST warnings.
Answer: You could use ajax to post your data, then when the response comes back, redirect them to whatever page you'd like.
Answer: The user prompt to re-submit data is displayed when the page that they are trying to navigate to was first navigated to from a POST form submission.  If you do any sort of AJAX POST'ing, the re-submit prompt will not be displayed if the user navigates back or forward to it.
To avoid ever getting this prompt, you could just use AJAX, or POST and then redirect.  However, this is the behavior of a great many web applications (Amazon's cart, for example).  I'm not fully aware of the context or behavior of your application, but I'm not fully convinced that this is a problem that you need to worry about, especially if you're not allowing duplicate data.
Comment: You might want to add that to your question, or perhaps start a new question
Comment: I wrote 3 pages that post to each other with no back issues - why?

this is the first:

testPostA.php
Came from
Comment:

test post B

testPostB.php
Came from
Comment: I edited the original question and added the html, but, for some reason, it's showing the result of the page and not the code
Comment: @sdfor For question and answer text, you can use Markdown syntax. Code must be indented with 4 spaces to get the stylizer to kick in.  There's a toolbar button in the editor (look for 1s and 0s) that lets you highlight a piece of code and indent appropriately. I fixed it for you on this one.


Ansible regex_search module

Question: Can anyone please help me to explain this code in ansible regex_search module:
- set_fact:
    regex: "{{ '/opt/conf/path.txt' | regex_search('/?(.*)', '\\1') }}'

What "\\1" means in this code.
What is the function of each special letter in '/?(.*)'
Answer: This is actually more of a regex-question, not ansible. Apart from that, all information you are looking for is in the python documentation and ansible documentation.

\\1 will return the first matching group
/?(.*) has several parts

/? will match a / if it is there, or nothing if it isn't. The ? means "optional".
Everything in brackets () is a matching-group. You can have multiple to get different parts of your match, but here it is only one.
.* matches any string composed of any character except new-lines of any length, as . matches any character (except newline) and * means, 0 or more characters.

Check the documentation linked above, they explain all this in detail.
Comment: thanks so much for your answer, now I got it.

Ansible regex_search module


Confusion about HSRP Groups

Question: If I have a router that has several LANs on it, and each of these LAN is attached to a second router, do I need to use different HSRP groups for each LAN?
With this set up, each virtual gateway will be on a Layer 2 segment.  And within a router, no interface will have multiple gateways.
So, For example:
Router 1:
F0/0:
ip address 192.168.1.2 255.255.255.0
standby ip 192.168.1.1
F2/0:
ip address 192.168.2.2 255.255.255.0
standby ip 192.168.2.1

Router 2:
F0/0:
ip address 192.168.1.3 255.255.255.0
standby ip 192.168.1.1
F2/0:
ip address 192.168.2.3 255.255.255.0
standby ip 192.168.2.1

Will this work, or do I need standby 1 ip 192.168.2.1 on the F2/0 interfaces? (When no group is specified, the default group is 0.)  Since according to the RFC, the group number of the packet is in the HSRP multicast packets, my guess is that I don't need different groups, and that multiple groups are only needed when they are all on the same Layer 2 segment.  However, I haven't been able to find this setup....
Answer: If these LANs are all on separate L2 segments, you can safely use the same HSRP group number on all of them. I have seen this used in production with no issues; 100+ VLANs on a 6500 router pair all using HSRP group 1. Like you, I can't find any documentation blessing this right now.
One example I have seen where multiple HSRP groups used were used on the same interface was for combining subnets. For example, given the following two subnets:
interface Vlan1
 ip address 192.168.1.2 255.255.255.128
 standby 1 ip 192.168.1.1
!
interface Vlan2
 ip address 192.168.1.130 255.255.255.128
 standby 1 ip 192.168.1.129
!

If you wanted to combine them into one subnet (192.168.1.0/24), but maintain both existing HSRP addresses while hosts were reconfigured, the following configuration:
interface Vlan1
 ip address 192.168.1.2 255.255.255.0
 standby 1 ip 192.168.1.1
 standby 2 ip 192.168.1.129
!

Would allow you to do so.

Confusion about HSRP Groups


Como adicionar um ActionBar/ToolBar em projeto Android 2.2?

Question: Tenho um projeto/app desenvolvido no Android 2.2. O mesmo roda sem problema algum, mas como os dispositivos atuais estão abolindo o botão "menu" ou em alguns caso usam botões virtuais, o mesmo  passou a ficar "deficiente" se for instalado em alguns dispositivos que não possuam o referido botão. Gostaria de saber como posso implementar uma ActionBar/ToolBar para esse projeto/app da forma mais simples possível, ou seja, não gostaria de ter que fazer grandes alterações no código.
Grato a todos e aguardo qualquer ajuda.
Ps.: A minha aplicação já existe, então não sei como incluir tal "recurso" na mesma.
Comment: Veja na [documentação](https://developer.android.com/tools/support-library/features.html) e esta [pergunta](http://pt.stackoverflow.com/q/5555/2541)
Answer: o código da Toobar no seu xml:
<code>    <android.support.v7.widget.Toolbar
        android:id="@+id/toobar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:popupTheme="@style/Theme.AppCompat.Light"
        android:background="@color/colorPrimary"
        android:elevation="3dp"
        />
</code>
Na classe da activity:
<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seuLayout);
        toobar = (Toolbar)findViewById(R.id.toobar);
        setSupportActionBar(toobar);
}
</code>
Na styles.xml:
<code> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorPrimary</item>
 </style>
</code>


Find $f$ and $g$ by trial and error and a rigorous proof for showing that $\mathbb{Q}[\sqrt{2} + \sqrt{3}] = \mathbb{Q}[\sqrt{2},\sqrt{3}]$

Question: Here is the question I am trying to solve:
Find polynomials $f(x), g(x) \in \mathbb{Q}[x]$ such that $\sqrt{2} = f(\sqrt{2} + \sqrt{3})$ and $\sqrt{3} = g(\sqrt{2} + \sqrt{3}).$ Deduce the equality of fields: $\mathbb{Q}[\sqrt{2} + \sqrt{3}] = \mathbb{Q}[\sqrt{2},\sqrt{3}].$
And I found the following solution online:

 a formula for $f$ and $g$

 $\mathbb{Q}[\sqrt{2} + \sqrt{3}] = \mathbb{Q}[\sqrt{2},\sqrt{3}]$

My questions are:
1- How did we know that $f$ and $g$ look like that? what are the trials that lead to this?
2- Is there a more rigorous way of proving that  $\mathbb{Q}[\sqrt{2} + \sqrt{3}] \subseteq \mathbb{Q}[\sqrt{2},\sqrt{3}]$? or what is written is enough?
3- the stated reason for showing that  $ \mathbb{Q}[\sqrt{2},\sqrt{3}] \subseteq \mathbb{Q}[\sqrt{2} + \sqrt{3}]$ is not that much clear for me ......could anyone explain it in details for me please?
Note: $F[\alpha]$ is a symbol for subring while $F(\alpha)$ is a symbol for a subfield for any $\alpha$
Comment: Trying squaring $\sqrt 2 + \sqrt 3$ to get started.  Once you have $\sqrt{2\cdot 3}$ as a polynomial function (over $\mathbb Q$, to be pedantic about this), see what happens when you multiply that times $\sqrt 2 + \sqrt 3$.  Now it's a bit of linear algebra to get either $\sqrt 2$ or $\sqrt 3$ as a polynomial function of $\sqrt 2 + \sqrt 3$.
Comment: They are reasonable questions, though I suspect you just need a bit of confidence in your ability to reason through the first part to answer them yourself.  I'm not trying to answer your Question, just trying to give you some momentum to pursue the ideas.
Comment: See https://math.stackexchange.com/a/3832301/589
Comment: @hardmath what about my other questions?
Answer: $(\sqrt 2 + \sqrt 3)^k$ will be a linear combination of $\sqrt 2$, $\sqrt 3$, and $\sqrt 6$ so any polynomial $f(\sqrt 2 + \sqrt 3)$ will yield result of $a\sqrt 6 + b \sqrt 2 +c \sqrt 3 + d$ so we need a polynomial where the yielded values are $a=c=d=0$ and $b = 1$ (and for $g$, $a=b=d=0; c=1$).  And, for simplicity, we want the least power.
Now if we have a power of $k$ and $k+1$ coefficients, $e_k$ we will end up with the $4$ variables, $a,b,c,d$ in $a\sqrt 6 + b \sqrt 2 + c\sqrt 3 + d$ being linear combinations of $e_j$.  That is we will have $4$ equations of combinations of $e_j$ equaling each of $a,b,c,d$.  If we have fewer than $4$ coefficients, $e_j$, we must have linear dependence which are likely to result in inconsistancies.  If we have more than $4$ coefficients we will have superflous solutions.
Best guess is to try a polyinomial of $k+1 = 4$ or of power $k = 3$.
A power of $3$ with $mx^3 + nx^2 + px + q$ will yield $m(2\sqrt 2 + 6\sqrt 3 + 9\sqrt 2+3\sqrt 3) + n(5 + 2\sqrt 6) + p(\sqrt 2 + \sqrt 3) + q$ so we'd need:
$2m +9m+p =11m + p = 1; 6m + 3m+p =9m + p= 0; 2n = 0; 5n+q = 0$ which is a far more promising set of equations.
$n=q=0$ and $11m + p = 1$ and $9m + p =0$. So $m= \frac 12$ and $p=-\frac 92$.
So $f(x) = \frac 12x^3 -\frac 92x$ will yeild $f(\sqrt 2+ \sqrt 3) = \sqrt 2$.
TO find $g$ is much the same but we must solve $11m + p = 0$ and $9m+p = 1$ so $m=-\frac 12$ and $p=\frac {11}2$.
ANd $g(x) = -\frac 12x^3 + \frac {11}2 x$ will yeild $f(\sqrt 2 + \sqrt 3) = \sqrt 3$.
====
Note we could have tried powers of $k < 3$ but the $4$ equations and fewer than $4$ unknown all lead to inconsistencies.
$k = 0$ and $f(x) = e_0$ requires $e_0 = \sqrt 2 \in \mathbb Q$.  Impossible. $k = 1$ and $f(x) = e_1x + e_0$ requires $e_1 = 1; e_1=0;e_0=0$.  Impossible.
$k = 2$ and $f(x)=e_2x^2 + e_1x + e_0$ when evaluated for $x=\sqrt 2 + \sqrt 3$ would yield
$e_2(5+2 \sqrt 6) + e_1(\sqrt 2 +\sqrt 3) +e_0$ which to equal $\sqrt 2$ would require $2e_2 = 0; e_1=1; e_1=0; 5e_1+e_0 = 0$ which is of course impossible  ($4$ equations and $3$ unknowns requires linear dependence, and in this case inconsistently so).
Comment: Do we have to prove that each of $\mathbb{Q}[\sqrt{2} + \sqrt{3}]$  and $ \mathbb{Q}[\sqrt{2},\sqrt{3}]$ are really fields?
Comment: So the given $g$ in the statement of the question above is wrong..... correct?
Answer: 2 - Any arbitrary element in $\mathbb{Q}[\sqrt2 + \sqrt3]$ looks like $x=a+b(\sqrt2+\sqrt3)$, where $a,b\in\mathbb{Q}$. That should give you why $x\in\mathbb{Q}[\sqrt2,\sqrt3]$.
3 - Consider the reciprocal of $\sqrt2 + \sqrt3$, $\frac{1}{\sqrt2 + \sqrt 3} = \sqrt3-\sqrt2$. This element is also in $\mathbb{Q}[\sqrt2 + \sqrt3]$ since it needs to be closed. Now you should be able to show that both $\sqrt2$ and $\sqrt3$ are in $\mathbb{Q}[\sqrt2 + \sqrt3]$.
Note that any element in $\mathbb{Q}[\sqrt2,\sqrt3]$ looks like $x=a+b\sqrt2 + c\sqrt3$, where $a,b,c \in \mathbb{Q}$, so $x \in \mathbb{Q}[\sqrt2 + \sqrt3]$.
Comment: Note that $\mathbb Q[\sqrt 2 + \sqrt 3]$ need not be *closed* under taking reciprocals. If it were, then your last argument would make things much easier.   The problem is to construct polynomials (rather than rational expressions) of $\sqrt 2 + \sqrt 3$ to get the individual surds.
Comment: @hardmath Since $\mathbb{Q}[\sqrt{2}+\sqrt{3}]$ is a finite dimensional vector space over $\mathbb{Q}$, and since multiplication by any nonzero element of $\mathbb{Q}[\sqrt{2}+\sqrt{3}]$ is a linear map with trivial kernel, it follows that $1$ is in the image of multiplication by any nonzero element of $\mathbb{Q}[\sqrt{2}+\sqrt{3}]$. So $\mathbb{Q}[\sqrt{2}+\sqrt{3}]\setminus\{0\}$ is colsed under inverses.
Comment: @MathIgnorance Because to be otherwise would mean that two nonzero elements multiply together to make $0$. And all this is still taking place within $\mathbb{R}$, after all.
Comment: @JasonF Your proof of 2. is not correct : an element of $\mathbb{Q}[\sqrt{2}+\sqrt{3}]$ is **not** necessarily of the form described (actually $\sqrt{2}$ is not of the form described while being in this field). Similarily in 3., an element of $\mathbb{Q}[\sqrt{2},\sqrt{3}]$ is not necessarily of the form $a+b\sqrt{2}+c\sqrt{3}$ as claimed.
Comment: What about question 1?
Comment: I think what @hardmath gave is a pretty solid idea.
Comment: Ok, thank you Jason!
Comment: @hardmath so do we need to prove that both are subfields?
Comment: @alex.jordan why the kernel is trivial?
Comment: @Roland so can you give us a correct proof for 2 in a separate answer please?
Comment: @MathIgnorance I wrote an answer for 2. and 3.
Answer: As requested, I give another answer for 2. and 3. which is more accurate than the currently accepted.
First I start with two general claims which are worth knowing :

$\mathbb{Q}[x_1,x_2,...,x_n]$ is the smallest $\mathbb{Q}$-algebra containing $x_1,...,x_n$. It follows that if $A$ is a $\mathbb{Q}$-algebra such that $x_1,...,x_n\in A$, then $\mathbb{Q}[x_1,x_2,...,x_n]\subset A$.
If $A$ is a $\mathbb{Q}$-algebra and $f\in\mathbb{Q}[X]$ a polynomial, then for any $a\in A, f(a)\in A$ (this is simply because a $\mathbb{Q}$-algebra is stable by taking power, sums, and multiplication by a rational number).

Now the proof of the questions :

$\mathbb{Q}[\sqrt{2},\sqrt{3}]$ is a $\mathbb{Q}$-algebra containing $\sqrt{2}+\sqrt{3}$. From the first claim : $\mathbb{Q}[\sqrt{2}+\sqrt{3}]\subset\mathbb{Q}[\sqrt{2},\sqrt{3}]$.

From question 1., we have polynomials $f,g\in\mathbb{Q}[X]$ such that $f(\sqrt{2}+\sqrt{3})=\sqrt{2}$ and $g(\sqrt{2}+\sqrt{3})=\sqrt{3}$. Hence, from the second claim, we have $\sqrt{2},\sqrt{3}\in\mathbb{Q}[\sqrt{2}+\sqrt{3}]$. Therefore, using the first claim $\mathbb{Q}[\sqrt{2},\sqrt{3}]\subset \mathbb{Q}[\sqrt{2}+\sqrt{3}]$.


Using command in ssh authorized_keys breaks scp

Question: I would like to use command per key in authorized_keys to set some environment variables.
command="MYVAR=test $SHELL" ssh-rsa mykey

Shell works fine but scp is not working.
What would be the correct way to set environment variables per key and not break ssh file transfers?
Comment: Have you considered setting your variables in `~/.ssh/rc`?  Or how about `environment="NAME=value"`.
Comment: http://serverfault.com/questions/142997/what-options-can-be-put-into-a-ssh-authorized-keys-file
Comment: Thanks, Zoredache. environment param solves my problem. You can add your solution as an answer to this question, I would accept it for you to get reputation points.
Answer: Your configuration forces ssh to run whatever command is in $SHELL whenever you connect with the matching private key.  This is fine if what you want is an interactive shell, but will break any attempt at running a command directly.  This breaks `scp as you've seen, but will also break things like:
ssh myhost uptime

The solution is to either (a) set your environment variables somewhere else (.ssh/rc, or just use your standard shell initialization files), or (b) use a dedicated key when you want to force a command via your authorized_keys file.
Comment: Thanks for the answer, but my problem was that I want to set environment variables per ssh key. It was solved by Zoredache suggestion.
Answer: So I realize this question is ancient at this point but I discovered an answer to this today. This is an alternative to setting environment variables and may be a better solution depending on your situation. My situation is this:
I have a Splunk instance that initiates an SCP and SSH session to a remote host. A list of emails is sent via SCP and then SSH is used to run a script on the remote system to take action on that list of emails. Here's the top of my authorized_keys file:
command="/home/username/wrapper.sh",no-port-forwarding,no-X11-forwarding,no-pty ssh-rsa AAAAB3 etc...

This is my wrapper.sh script:
#!/bin/bash

vars=( $SSH_ORIGINAL_COMMAND )
case "${vars[0]}" in
        "/home/username/scripts/myscript.py")
                /home/username/scripts/myscript.py ${vars[1]}
                exit 0
                ;;
        "scp")
                scp -t ${vars[2]}
                chmod 644 ${vars[2]}
                exit 0
                ;;
        *)
                exit 1
                ;;
esac

The first case allows /home/username/scripts/myscript.py with any command line parameters that were passed to it.
The second, scp case entry, allows the incoming file to be written to disk at its intended location.
This method allows me to limit the use of the public key to 1 command and still allow scp. If anyone has a better option please share. :)


Loading red-arrow into serverless lambda

Question: I have a serverless ruby lambda.
I want to use red-arrow to process some data but when I add require 'arrow' to my lambda it throws an exception:
require: cannot load such file -- arrow (LoadError)

Any idea how I can make this work?
Note: I haven't even tried to deploy this, this error occurs when I run it locally.
Answer: For some reason my serverless configuration was not picking up the gems specified in the Gemfile - I had to do a gem install red-arrow and that fixed it.


Level set of a convex function itself convex

Question: I am trying to see how is a level set of a convex function itself convex.
The level set is defined as $$L_c(f)=\{x|f(x)=c\}$$ (see here and here for the definitions)
So, to show that a set is convex, we need to show that if $x,y\in L_c(f)$ then it implies that $\alpha x +(1-\alpha)y\in L_c(f)$.
However I am confused at to how this is possible, since if we take the well-known convex function $x_2$, and we take the level set $L_c(x^2)=\{-2,2\}$, then how is it possible that for all $\alpha\in (0,1), \alpha(-2)+(1-\alpha)(2)\in\{-2,2\}$, since if $\alpha=\frac{1}{2}$ we have that $\frac{1}{2}(-2)+\frac{1}{2}(2)=-1+1=0$
Answer: You're right, a level set defined like this need not be convex. But the set
$$\{ x : f(x) \leqslant c \}$$
will always be convex provided that $f$ is convex.


PyQt: Getting the amount of lines from QTextEdit

Question: I am trying to make a chat application, so i added the QTextEdit widget where user types the content, maximum height of widget is 30 pixels, so basically one line.
    self.msgtext = QtGui.QTextEdit(self)
    self.msgtext.setObjectName('msgtext')
    self.msgtext.setStyleSheet("#msgtext {background-color: black; color: yellow; font-size: 18pt; }")
    self.msgtext.setMaximumSize(500, 30)
    self.msgtextplain = self.msgtext.toPlainText()

I want to increase the maximum height of the widget whenever user get's one new line, But i don't know if there is any signal that can tell that i have reached new line.
Is there any signal, that can count the amount of lines from QTextEdit?
Answer: You can use blockCount() but don't forget to also resize whatever parent you are using for your QTextEdit. Here is an example:
import sys
from PyQt5 import QtGui, QtWidgets, QtCore

class Window(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)

        self.msgtext = QtWidgets.QTextEdit(self)
        self.msgtext.setObjectName('msgtext')
        self.msgtext.setStyleSheet("#msgtext {background-color: black; color: yellow; font-size: 18pt; }")
        self.msgtext.resize(500, 30)
        self.msgtextplain = self.msgtext.toPlainText()

        self.msgtext.textChanged.connect(self.changed)

    def changed(self):
        lines = self.msgtext.document().blockCount()
        self.msgtext.resize(500, 30*lines)
        self.resize(500, 30*lines)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())

It's PyQt5. To do this in PyQt4 change everything that is QtWidgets to QtGui (and check the import lines evidently; this should be enough but do tell if you have any difficulties). Here is the result:
Comment: Thanks a lot for the awesome and detailed answer!, worked without any problems!


.tsx component Button onclick event shows undefined

Question: I create a .tsx component and a function that is returning dynamic HTML.
   getCellValues(_data) {
    var ret=`<div onClick="`+this.selectDate("1")+`">1</div>`;
     console.log(ret)
     return ret; }

and this select data function looks like
 selectDate(_data: string) {
     console.log("*****selectDate**************************");
     console.log(_data); }

and in component constructor added this line of code.
this.selectDate = this.selectDate.bind(this);

but after loading component this div onclick event shows undefined... ANd the rendered html looks like..

1

Any ideas?
Answer: You could simply return the JSX:
getCellValues(_data) {
  return
 this.selectDate(1)}>1

};

Comment: i cant return like this because i am having a complete dynamic html block and this div is the part of that html block
Comment: I see. I don't know the fix for this, but ideally, you'd refactor the code so it's not using dynamic HTML this way. The point of using React kind of evaporates.
Comment: actually i am creating a dynamic calender so i have to use dynamic html
Comment: How so? I'd gladly look into a snippet, but I doubt it's not refactorable into generic JSX components.
Comment: Its not possible for me to upload complete snippet here... i have a calender with all dates should be clickable event.. and for that i want this button click event which is currently undefined