Proof that a degree 4 polynomial has at least two roots

Question:
Let $$P(x) = x^4+a_3x^3+a_2x^2+a_1x+a_0$$
  $$P(x_0) = 0$$
  $$P'(x_0) \not= 0$$
  with $x_0$ and each $a_i$ real. Prove that $P(x)$ has a at least two real roots.

I can't figure why this is true.
Comment: Hint: Show that there exists a point $x_1$ (near $x_0$) such that $P(x_1)<0$. Combine that with IVT and your observation of the limits at infinity on the same side of $x_0$ where $x_1$ lies.
Comment: You should draw a picture, one for $P'(x)>0$ and one for $P'(x)<0$. It will be easier to see the argument.
Comment: First show that if $(x-x_0)^2$ divides $P(x)$ then $P(x_0)=0$ and $P'(x_0)=0$.
Comment: I'm assuming $x_0$ and the $a_i$ are real?
Comment: @Taylor Yes they are
Comment: Since $\lim_\limits{x\to\pm \infty}P(x)=\infty$ there has to be at least one minimum and since you have at least one point $x_0$, where $P(x_0)=0$, either left or right of it, the minimum will lie. Therefore there has to be another point in the direction from $x_0$ to the minimum that crosses the $y$ axis. $P'(x_0)\neq 0$ excludes that the minimum touches the $y$-axis at a single point...
Comment: by 'has a least two roots', I'm do you mean 'has at least two distinct roots'? or 'has at least two real roots'?
Comment: @Ethan I thought of "two real roots"...
Answer: Hint: have you tried sketching possible shapes for the polynomial, noting that the $x^4$ term dominates when $|x|$ is large.

 Hint: can you show that there is a value of $x$ for which the polynomial takes a negative value? Then use the intermediate value theorem.
Answer: You know that $P(x_0)=0$. Thus you can write $P(x)=(x-x_0)\cdot g(x)$ where $g$  is a polynom of odd degree. Thus, by mean value theorem, there is $r$ such that $g(r)=0$. If $x_0=r$ you can write $P(x)=(x-x_0)^2 \cdot h(x)$. But in this case you get $P'(x_0)=0$, so it is a contradiction and you get $r\neq x_0 $ and you get at least two real roots.
Answer: By the hyphotesis $x_0$ is a simple root of $P(x)$; $i.e.$ $(x-x_0)^2$ do not divided $P(x)$ because $P'(x)\neq0$. Then you can decompose $P(x)$ as follow
$$ P(x)=(x-x_0)(x^3+b_1x^2+b_2x+b_3)=(x-x_0)q(x).$$
Now $q(x)$ is a polynomial of degree $3$ with real coefficients; then there exists another real number $x_1$ such that $P(x_1)=0$; otherwise $P(x)$ needs to have $3$ complex roots; and this is not possible. Then $P(x)$ has al least two real different roots;
$$(x-x_0)(x-x_1)q'(x),$$ where $q'(x)$ is a polynomial of degree $2$. Now: if the discrimant $\Delta$ of $q'(x)$ is greater than $0$ you have four real roots (one of them could be equal to $x_1$), if $\Delta=0$ you have another two real roots $x_2=x_3$; if $\Delta<0$, $q'(x)$ has two conjugate complex roots; then $P(x)$ has only two real roots.
Notice that in general a polynomial with real coefficient of degree $4$ could not have real roots; for instance
$$P(x)=(x^2+1)(x^2+4);$$
so the roots $x_0,...x_3$ are complex and $x_0=\overline{x_1}$; $x_2=\overline{x_3}$; but if $P(x)$ has a real root; then it needs to has another one.
Answer: The idea is simple. Since coefficient of $x^{4}$ is $1$ it is clear that $P(x) \to \infty$ when $x \to \infty$ or $x \to -\infty$. Now we are given that $x_{0}$ is a root of $P(x)$ and we need to show that there is at least one more root of $P(x)$. Since $P'(x_{0}) \neq 0$, it follows that there is a point $c$ near $x_{0}$ for which $P(c) < 0$ (if $P'(x_{0}) > 0$ then $c < x_{0}$ and if $P'(x_{0}) < 0$ then $c > x_{0}$, moreover there is an interval full of such points $c$ but we just need one such $c$).
If $c < x_{0}$ then we can see that $P(c) < 0$ and $P(x) \to \infty$ as $x \to -\infty$ and hence by intermediate value theorem there is a root of $P(x)$ in $(-\infty, c)$. If $c > x_{0}$ then we can show in similar manner that there is a root of $P(x)$ in $(c, \infty)$.
Answer: First of all, assume by root, you mean real root here, and also assume all coefficients $a_i$ are real here.
No matter what, $P$ has 4 roots in $\mathbb{C}$, and since all $a_i$ are real, when $y$ is a root, $\bar{y}$ has to be a root too, where $\bar{y}$ is the conjugate of $y$. So $P$ can have 0,2,4 real roots, multiplicity counted. So only chance $P$ has a single real root is that this root's multiplicity larger than 1, in other words, $P(x)=(x-x_0)^2(x^2+bx+c)$. If this were true, $P'(x_0)=0$, which contradicts of what was given. So $P$ must have at least 2 real roots.
Answer: Since, the given polynomial has the real coefficients. So we know that if it has a complex root then its conjugate must be the root of the polynomial. Now in the given polynomial since $ P(x_0)=0, x_0\in \mathbb{R} $ also $ P'(x_0)\neq 0 $ which implies the multiplicity of $x_0$ is 1; $i.e.$ if $P(x)=(x-x_0)g(x) \implies g(x_0)\neq 0.$ the degree of $g(x)$ is 3 which is odd. So, $ g(x)$ must have a real root as the coefficients of $g(x)$ is also real. Hence, $P(x)$ has at least 2 real roots.


match and merge in XSLT with optional nodes

Question: I have a sample XML message which contains multiple parent node. The requirement is if the two parent node are same, merge the child node. This works fine when all the nodes are present but doesn't work when the optional node is absent
Sample Message:1 With Optional Nodes present
<document>

    <party>
        <gtin>1000909090</gtin>
        <pos>
            <attrGroupMany name="temperatureInformation">
                <row>
                    <gtin>1000909090</gtin>
                    <attr name="temperatureCode">STORAGE</attr>
                    <attrQualMany name="temperature">
                        <value qual="FAH">10</value>
                        <value qual="CC">20</value>
                    </attrQualMany>
                    <attrGroupMany name="temperatureStats">
                        <row>
                            <attr name="StatsCode">CODE1</attr>
                        </row>
                        <row>
                            <attr name="StatsCode">CODE2</attr>
                        </row>
                    </attrGroupMany>
                </row>
                <row>
                    <attr name="temperatureCode">STORAGE</attr>
                    <attrQualMany name="temperature">
                        <value qual="FAH">10</value>
                        <value qual="CC">20</value>
                    </attrQualMany>
                    <attrGroupMany name="temperatureStats">
                        <row>
                            <attr name="StatsCode">CODE3</attr>
                        </row>
                        <row>
                            <attr name="StatsCode">CODE4</attr>
                        </row>
                    </attrGroupMany>
                </row>
                <row>
                    <attr name="temperatureCode">HANDLING</attr>
                    <attrQualMany name="temperature">
                        <value qual="FAH">10</value>
                    </attrQualMany>
                    <attrGroupMany name="temperatureStats">
                        <row>
                            <attr name="StatsCode">CODE5</attr>
                        </row>
                        <row>
                            <attr name="StatsCode">CODE6</attr>
                        </row>
                    </attrGroupMany>
                </row>
                <row>
                    <attr name="temperatureCode">HANDLING</attr>
                    <attrGroupMany name="temperatureStats">
                        <row>
                            <attr name="StatsCode">CODE7</attr>
                        </row>
                        <row>
                            <attr name="StatsCode">CODE8</attr>
                        </row>
                    </attrGroupMany>
                </row>
            </attrGroupMany>
        </pos>
    </party>

</document>

The below sample XSLT works fine to remove the duplicate from 'attrGroupMany name="temperatureInformation" '
XSLT used
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

<xsl:key name="group" match="party/pos/attrGroupMany[@name = 'temperatureInformation']/row"
    use="concat(generate-id(ancestor::pos), '|', attr[@name = 'temperatureCode'], '|', attrQualMany[@name = 'temperature'])"/>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="attrGroupMany[@name = 'temperatureInformation']">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="row[generate-id() = generate-id(key('group', concat(generate-id(ancestor::pos), '|', attr[@name = 'temperatureCode'], '|', attrQualMany[@name = 'temperature']))[1])]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="attrGroupMany[@name = 'temperatureStats']">
    <xsl:copy>
        <xsl:apply-templates select="@* | key('group', concat(generate-id(ancestor::pos), '|',../attr[@name = 'temperatureCode'], '|', ../attrQualMany[@name = 'temperature']))/attrGroupMany[@name = 'temperatureStats']/row"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Sample Message 2 which doesnt work with above XSLT is
<document>

    <party>
        <gtin>1000909090</gtin>
        <pos>
            <attrGroupMany name="temperatureInformation">
                <row>
                    <gtin>1000909090</gtin>
                    <attr name="temperatureCode">STORAGE</attr>
                    <attrQualMany name="temperature">
                        <value qual="FAH">10</value>
                        <value qual="CC">20</value>
                    </attrQualMany>
                </row>
                <row>
                    <attr name="temperatureCode">STORAGE</attr>
                    <attrQualMany name="temperature">
                        <value qual="FAH">10</value>
                        <value qual="CC">20</value>
                    </attrQualMany>
                    <attrGroupMany name="temperatureStats">
                        <row>
                            <attr name="StatsCode">CODE3</attr>
                        </row>
                        <row>
                            <attr name="StatsCode">CODE4</attr>
                        </row>
                    </attrGroupMany>
                </row>
                <row>
                    <attr name="temperatureCode">HANDLING</attr>
                    <attrQualMany name="temperature">
                        <value qual="FAH">10</value>
                    </attrQualMany>
                    <attrGroupMany name="temperatureStats">
                        <row>
                            <attr name="StatsCode">CODE5</attr>
                        </row>
                        <row>
                            <attr name="StatsCode">CODE6</attr>
                        </row>
                    </attrGroupMany>
                </row>
                <row>
                    <attr name="temperatureCode">HANDLING</attr>
                    <attrGroupMany name="temperatureStats">
                        <row>
                            <attr name="StatsCode">CODE7</attr>
                        </row>
                        <row>
                            <attr name="StatsCode">CODE8</attr>
                        </row>
                    </attrGroupMany>
                </row>
            </attrGroupMany>
        </pos>
    </party>

</document>

Can someone please let me know how to handle optional node in match n merge
The expected output for sample message 2 is
<?xml version="1.0" encoding="UTF-8"?>
<document>

  <party>
     <gtin>1000909090</gtin>
     <pos>
        <attrGroupMany name="temperatureInformation">
           <row>
              <gtin>1000909090</gtin>
              <attr name="temperatureCode">STORAGE</attr>
              <attrQualMany name="temperature">
                 <value qual="FAH">10</value>
                 <value qual="CC">20</value>
              </attrQualMany>
              <attrGroupMany name="temperatureStats">
                 <row>
                    <attr name="StatsCode">CODE3</attr>
                 </row>
                 <row>
                    <attr name="StatsCode">CODE4</attr>
                 </row>
              </attrGroupMany>
           </row>
           <row>
              <attr name="temperatureCode">HANDLING</attr>
              <attrQualMany name="temperature">
                 <value qual="FAH">10</value>
              </attrQualMany>
              <attrGroupMany name="temperatureStats">
                 <row>
                    <attr name="StatsCode">CODE5</attr>
                 </row>
                 <row>
                    <attr name="StatsCode">CODE6</attr>
                 </row>
              </attrGroupMany>
           </row>
           <row>
              <attr name="temperatureCode">HANDLING</attr>
              <attrGroupMany name="temperatureStats">
                 <row>
                    <attr name="StatsCode">CODE7</attr>
                 </row>
                 <row>
                    <attr name="StatsCode">CODE8</attr>
                 </row>
              </attrGroupMany>
           </row>
        </attrGroupMany>
     </pos>
  </party>

</document>

Can someone please let me know how to handle optional node in match n merge. Thanks
Comment: Some of us avoid answering questions if they are described as urgent. Saying this often suggests that you haven't put enough time and thought into formulating the question carefully.
Comment: I have been trying this for 2 days now but no luck. Please let me know if you can throw some light on it
Answer: You haven't explained the logic behind what you are trying to do, but from looking at the XSLT from this question, and previous questions too, you are grouping the attrGroupMany[@name = 'temperatureInformation']/row elements but a concatenation of the ancestor pos together with "temperatureCode" and "temperature".
Then for each such distinct row it looks like you want to add in all the <attrGroupMany name="temperatureStats"> elements. Having a template matching this element is not going to work if you say it is optional. Instead, have a template matching the parent row and use that to select all the child elements from all elements in the keys.
<xsl:template match="attrGroupMany[@name = 'temperatureInformation']/row">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()[not(self::attrGroupMany[@name = 'temperatureStats'])]"/>
        <attrGroupMany name="temperatureStats">
            <xsl:apply-templates select="key('group', concat(generate-id(ancestor::pos), '|', attr[@name = 'temperatureCode'], '|', attrQualMany[@name = 'temperature']))/attrGroupMany[@name = 'temperatureStats']/row"/>
        </attrGroupMany>
    </xsl:copy>
</xsl:template>

I am assuming all the StatsCode are distinct here. If there could be duplicated, and you want to remove such duplicates, you need to say so in your question.
Try this XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output method="xml" indent="yes" />

<xsl:key name="group" match="party/pos/attrGroupMany[@name = 'temperatureInformation']/row"
    use="concat(generate-id(ancestor::pos), '|', attr[@name = 'temperatureCode'], '|', attrQualMany[@name = 'temperature'])"/>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="attrGroupMany[@name = 'temperatureInformation']">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="row[generate-id() = generate-id(key('group', concat(generate-id(ancestor::pos), '|', attr[@name = 'temperatureCode'], '|', attrQualMany[@name = 'temperature']))[1])]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="attrGroupMany[@name = 'temperatureInformation']/row">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()[not(self::attrGroupMany[@name = 'temperatureStats'])]"/>
        <attrGroupMany name="temperatureStats">
            <xsl:apply-templates select="key('group', concat(generate-id(ancestor::pos), '|', attr[@name = 'temperatureCode'], '|', attrQualMany[@name = 'temperature']))/attrGroupMany[@name = 'temperatureStats']/row"/>
        </attrGroupMany>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Comment: Yes Duplicate Stats code are to be removed but the code shared by you doesnt support it. Sorry I missed to explicitly call out that
Comment: I have used your answer and added the piece of code for removing duplicate in this scenario
Answer: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"    version="1.0">

<xsl:output method="xml" indent="yes" />

<xsl:key name="grouptemperatureInformation" match="party/pos/attrGroupMany[@name = 'temperatureInformation']/row"
use="concat(generate-id(ancestor::pos), '|', attr[@name = 'temperatureCode'], '|', attrQualMany[@name = 'temperature'])"/>

<xsl:key name="grouptemperatureStats"
         match="party/pos/attrGroupMany[@name = 'temperatureInformation']/row/attrGroupMany[@name = 'temperatureStats']/row"
         use="concat(generate-id(ancestor::pos), '|', ../../../attr[@name = 'temperatureCode'], '|', ../../../attrQualMany[@name = 'temperature'], '|', attr[@name = 'StatsCode'])"/>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="attrGroupMany[@name = 'temperatureInformation']">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="row[generate-id() = generate-id(key('grouptemperatureInformation', concat(generate-id(ancestor::pos), '|', attr[@name = 'temperatureCode'], '|', attrQualMany[@name = 'temperature']))[1])]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="attrGroupMany[@name = 'temperatureInformation']/row">
    <xsl:variable name="group" select="key('grouptemperatureInformation', concat(generate-id(ancestor::pos), '|', attr[@name = 'temperatureCode'], '|', attrQualMany[@name = 'temperature']))/attrGroupMany[@name='temperatureStats']/row" />
    <xsl:copy>
        <xsl:apply-templates select="@*|node()[not(self::attrGroupMany[@name = 'temperatureStats'])]"/>
        <attrGroupMany name="temperatureStats">
            <xsl:apply-templates select="@* | $group[generate-id() = generate-id(key('grouptemperatureStats', concat(generate-id(ancestor::pos), '|', ../../../attr[@name = 'temperatureCode'], '|', ../../../attrQualMany[@name = 'temperature'], '|', attr[@name = 'StatsCode']))[1])]"/>
        </attrGroupMany>
    </xsl:copy>
 </xsl:template>
 </xsl:stylesheet>


Chartkick: Undefined method `line_chart'

Question: I am working on a Rails 6 application and I am trying setup Chartkick for charts in my application.
I installed Chartkick this way:

For Rails 6 / Webpacker, run:
yarn add chartkick chart.js

And in app/javascript/packs/application.js, add:
require("chartkick")
require("chart.js")

3 Install Groupdate to use the group_by_day method
gem 'groupdate'

And then run bundle install.
However, when I added this line to my Dashboard views:
<%= line_chart @products.group_by_day(:created_at).count %>

To show a graph for products using the @products variable:
class Admins::DashboardController < ApplicationController
  before_action :authenticate_admin!

  # GET /dashboards
  # GET /dashboards.json
  def index
    @products = Product.all
  end
end

I get the following error:
undefined method `line_chart'

I'm wondering what I am doing wrong.
Answer: I finally figured it out.
Here's how I fixed it:
The issue was that I was missing the first requirement which is :
Adding this line to your application's Gemfile:
gem "chartkick"

And then running bundle install
My initial misconception was that I did not need this requirement since I am working with a Rails 6 application.
I thought that this step only applies to Rails 5 applications and below and not on Rails 6 applications since I am running yarn add chartkick chart.js. But it turned out to be untrue. It is required for both Rails 6 applications and Rails 5 applications and below.
That's all.
I hope this helps


Limit of multivariable function $\frac{x^2 y^2}{x^2 + y^2}$

Question: I need to find the limit:
$ \lim \limits_{P \to P_.0} \frac{x^2 y^2}{x^2 + y^2}$ where $P_0 = {0,0}$
I know that I can find the limit using polar coordinates, BUT how can I find it with $\epsilon - \delta$ definition?
Please explain step step so I can understand it.
Comment: You have omitted some important information about taking the limit. Saying limit as $P \to P_0$ is not enough to make a determination.
Comment: Yes i forgot to include $P_0$. Edited.
Answer: With the AM-GM inequality: for $x,y)\neq (0,0)$
$$
0 \leq \frac{x^2 y^2}{x^2+y^2} \leq \frac{x^2 y^2}{2\sqrt{x^2 y^2 }} = \frac{\lvert x y\rvert }{2} \xrightarrow[(x,y)\to(0,0)]{}0
$$
the last part being "easy" to quantify with $\epsilon$ and $\delta$, as $\sqrt{x^2+y^2}=\left\lVert \begin{pmatrix} x\\y\end{pmatrix}\right\rVert_2\leq \delta$, the very same AM-GM inequality implies $\sqrt{2\lvert xy \rvert }\leq \delta$.
Answer: Remember that $y^2$ and $x^2\leqslant x^2+y^2$, so $x^2y^2\leqslant (x^2+y^2)^2$, i.e. your function is less than $x^2+y^2$.
Using fancier terminology, if $\lVert (x,y)\rVert=\sqrt{x^2+y^2}$ is the Euclidean norm, $|x|,|y|\leqslant \lVert (x,y)\rVert$ by taking squareroots above. Your function is $$\frac{x^2y^2}{\lVert(x,y)\rVert}\leqslant\frac{\lVert (x,y)\rVert^4}{\lVert(x,y)\rVert^2}\leqslant \lVert (x,y)\rVert^2\to 0$$ when $\lVert (x,y)\rVert \to 0$, i.e. $(x,y)\to 0$.
Answer: Note we have,
$$|\frac{x^2y^2}{x^2+y^2}| \leq |\frac{x^2y^2}{x^2}|=|y^2| \to 0$$
Now conclude with squeeze theorem. And show $\lim_{y \to 0} |y^2|=0$.


How to sort incoming log messages by their hostname & timestamp with Rsyslog?

Question: I was curious if anyone has sorted incoming logs captured by Rsyslog by hostname and time stamp in the log.
Right now I have Rsyslog sort messages by the hostname moving them to appropriate folders and then Logrotate set to daily. My concern is if logs come in after logrotation that have a timestamp for the previous day. Since not all the servers times are in sync I figured this could cause some confusion if I ever need to search the logs and the file name is not 100% the correct date for the logs inside.
Any help?
Cheers
Answer: make sure you are using ntp to sync the time.If not try to use Message Property Variables
These are items derived from the message or the connection information, such as the timestamp within the message, the timestamp when the message was received on the local system, the hostname in the message, the hostname/IP of the system that delivered the message to the local box, PRI info, etc.For rsyslog version 5 and earlier, these were the only variables
available.
So try using receiving time variable rather then timestamp to make sure this problem never happens.
<code>> $template TEMPLATE_NAME,"%timegenerated:::date-rfc3339% %fromhost% %syslogtag%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n"
</code>
Comment: I have a separate conf file under the rsyslog.d/ directory. In the file I have the below format.

"
if $hostname == 'test-server' then /mnt/logs/test-server.log
& stop
"

Is it possible to use your format in there?
Comment: @cabotek the above mentioned format need to be defined to rsysconf which will be implemented globally for all the file formats within the server.


Calling get_theme_setting from php-as-css file

Question: I'm developing a Drupal 7 theme, and I'm using a php file as my theme's css file, in order to be able to use variables to simplify colour changes across the entire css.
I've also defined some theme settings in the theme-settings.php
What I want is to be able to call get_theme_setting() from within my style.php file, and use the theme settings to determine CSS attributes.
Answer: I recommend you to take a look to less css:
http://lesscss.org/
In fact there is a drupal module for this:
http://drupal.org/project/less
I used it a project and works great.
Comment: As fantastic as that is, I am still left with the problem of transferring variables from Drupal's settings to the CSS/Less file.
Answer: The solution I ended up implementing is embedding the PHP/CSS within the html.tpl.php file, as in inline style.
Comment: Just realised, I could have just pulled in the relevant settings in the html.tpl.php file, and sent them to the PHP-as-CSS file as GET arguments.


Retirando virgula da coluna pl sql

Question: Boa tarde, tenho uma tabela que tem nomes.
Em algumas linhas o nome está separado por virgula. Ex: Alberto, Luiz
Quero alterar essas linhas para ficar Luiz Alberto
DECLARE
  final VARCHAR(50);
  inicio VARCHAR(50);
  string_pronta VARCHAR(110);
BEGIN
  SELECT substr(NOME, instr(NOME, ',') + 1) into final FROM participantes;
  SELECT substr(NOME, 1, instr(NOME, ',') - 1) into inicio FROM participantes;
  string_pronta := inicio || ' ' || final;
  UPDATE participantes
   SET NOME := string_pronta;
END;

Comment: Axelmar, você quer apenas remover a vírgula?
Answer: Dessa forma abaixo você conseguirá ter o resultado esperado.
Possivelmente existe uma outra forma até mais elegante de ser feita, mas esta funciona.. :)

Tabela participantes:
  Constante, Filipe | de Tal, Fulano

UPDATE participantes SET nome = LTRIM(REPLACE(REGEXP_SUBSTR(nome, ',[^,]+'), ',') || ' ' || REGEXP_SUBSTR(nome, '[^,]+'));

Tabela participantes (RESULTADO):
  Filipe Constante | Fulano de Tal

Caso seja outra necessidade, explique melhor na pergunta que eu ajusto a resposta.
Espero ter ajudado.

A referência para esta resposta, obtive em:
  https://www.techonthenet.com/oracle/functions/replace.php
Comment: Desculpa, digitei errado. Alem de remover a virgula preciso inverter o nome de Constante, Felipe o resultado seria: Felipe Constante
Comment: Ajustei o update que irá resolver o seu problema.
Comment: Dê o feedback se deu certo para você.
Comment: Funcionou, obrigado

Retirando virgula da coluna pl sql


MongoDB service cannot be found in service list

Question: I have following the instruction from this link
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/
And when I'm going to
sudo service mongod start

it's shown as unrecognized service
I have known that I may need to use mongodb instead of mongod, but it's the same.
Then I have checked all services list by
service --status-all

There's no mongodb-related service in the list
I have reinstall it again and it's the same. I have also searched through the internet and I cannot find the solution. I install on Windows's ubuntu bash. I have reinstall bash once before this issue (14.04 to 16.04). Last time I installed it before I reinstalled bash it work just fine.
Thank you in advance for your answers.
Answer: I faced the same issue. I don't know the reason and solution but you can check the status of mongo itself by this command:
sudo service mongod status

You may see something like this output:
root@lab# service mongod status
● mongod.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
   Active: active (running) since Fri 2018-04-06 09:47:57 BST; 1min 31s ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 5973 (mongod)
   CGroup: /system.slice/mongod.service
           └─5973 /usr/bin/mongod --quiet --config /etc/mongod.conf


Angular 2 with Google Drive Realtime API

Question: I'm looking to create a new application based on the Drive Realtime API and want to do it with the shiny new Angular 2 framework.  However, I'm kind of stuck trying to figure out how to best integrate the APIs and philosophies.  I can't find any examples that use both.
What is the best way to get these two frameworks working together. In particular, how do I reconcile the differences between Angular's two way binding with ngModel and the Realtime APIs data binding with gapi.drive.realtime.databinding.Binding?
Answer: You can download the declaration file (*.d.ts) for the Google Drive Realtime API here. This provides a TypeScript wrapper for the API. Specifically, it defines a module named gapi.drive.realtime whose classes can be accessed in Angular2.
To tell the compiler about the declaration file, you need to add the following line to your TypeScript source file:
///<reference path="google-drive-realtime-api.d.ts" />

Then you need to import the module's features. One way to do this is with the following import command:
import * as Drive from "gapi.drive.realtime";

Then you can access the module's classes under the Drive namespace: Drive.Collaborator, Drive.CollaborativeObject, and so on.
Comment: Thanks for the response.  I'm familiar with using type definitions and importing with System.js.  Mine is not a simple _'how to use an ES5 library in Typescript?'_ question. My question is more about reconciling the differences between the approaches, such as with data binding.  I'm sure I could hack it to get it working, but am looking for thoughts, experience and patterns on how best use a library with collaboration usage constraints in an environment like Angular 2.
Comment: @MattScarpino do we need to npm install google drive api?
Comment: @MattScarpino: Where should the reference be added ? I did `npm install' but was not able to understand as to where the reference needs to be added.


Redirect User to their Profile Page After Saving

Question: Each user has a "Edit" tab/button on their profile. They click it, edit their profile, and when it is saved, they are kept on that page. I want the user to be taken back to his/her "View" or profile page.
Comment: using rules module consider an option for you?
Comment: Related with answers for D8: https://drupal.stackexchange.com/questions/131324/redirect-to-a-specific-page-when-user-update-their-profile/131338
Answer: As @Aboodred, if you already have the Rules module installed, adding a simple rule can do the job.

Create a rule with the React on event type After updating an existing user account.
Add a Page redirect action. Set the 'Data selector' field to account:url (either manually or using the dropdown).
Comment: This worked @obliquely! Many thanks (and to @Aboodred1 too).
Answer: If you want to do it with code instead of rules you can take a look at how the user_edit_cancel_submit function does it in user.pages.inc.
First you define an submit function:
$form['#submit'][] = 'custom_redirect_after_save';
Then you add the function:
function custom_redirect_after_save($form, &$form_state) {
  if (isset($_GET['destination'])) {
    unset($_GET['destination']);
  }
  $form_state['redirect'] = array("user", array());
}

Answer: In Drupal 8/9:
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_user_form_alter(&$form, &$form_state) {
  // Redirect users to their profile pages.
  $form['actions']['submit']['#submit'][] = 'MYMODULE_user_edit_form_submit';
}

/**
 * Redirect users to their profile pages when submitting the edit form.
 */
function MYMODULE_user_edit_form_submit($form, &$form_state) {
  $form_state->setRedirect('entity.user.canonical', ['user' => \Drupal::currentUser()->id()]);
}

Answer: You can add additional submit function to user_profile_form by using hook_form_alter to return back to profile page after editing user profile.
Your code should look like the following:
function MODULE_NAME_form_user_profile_form_alter(&$form, $form_state, $form_id) {
  $form['#submit'][] = 'MODULE_NAME_user_profile_form_submit';
}

function MODULE_NAME_user_profile_form_submit($form, &$form_state) {
  global $user;
  drupal_goto('user/' . $user->uid);
}

Comment: You don't need to do a drupal_goto because you can use a $form_state['redirect'] instead. See the answer from @andeersg.
Comment: @JenLampton all roads lead to Rome :D
Comment: @Aboodred1If you use `drupal_goto` you cut off every other submit function or alter hooks. If you set the redirect key in the form_state all the submit functions will execute before redirecting.
Answer: On my system (Drupal 6) it was
1) Install Rules Module:
https://www.drupal.org/project/rules
2) Activate Rules Module in Administration Console
[site url]/admin/build/modules (Look for a new Module category called Rules)
3) Enable the following Module(s):
Rules Administration UI 6.x-1.5 Provides the administration UI for rules.
Depends on: Rules (enabled)
Rules Forms support 6.x-1.5 Provides events, conditions and actions for rule-based form customization.
Depends on: Rules (enabled)
Rules Scheduler 6.x-1.5 Schedule the execution of rule sets.
Depends on: Rules (enabled)
4) Navigate to Rules area and configure the rule:
Rules | Triggered Rules | Add a new rule
....fill in as per Obliquely's instructions...
BUT - There was no DATA SELECTOR or dropdown.
Instead I had to fill it in by hand, which was easy:
To:  [account:account-url]
Answer: It worked in Drupal 8
use Symfony\Component\HttpFoundation\RedirectResponse;

function YOUR_MODULE_user_update($account) {
  $uid = \Drupal::currentUser()->id();
  $url = '/u/' . $uid;
  $response = new RedirectResponse($url);
  $request = \Drupal::request();
  $request->getSession()->save();
  $response->prepare($request);
  \Drupal::service('kernel')->terminate($request, $response);
  $response->send();
}

Comment: This is a bad answer because terminating the kernel early while in a hook means that no other hook will get a chance to operation.


How to convert dataframe with datetimes to daily time series in + mean aggregation R

Question: I have a dataframe that looks like this:
Arrival_DateTime = c("2009-01-01 08:35:00", "2009-01-01 10:00:00", "2009-01-01 10:25:00",
                     "2009-01-02 07:45:00", "2009-01-02 15:32:00", "2009-01-02 11:15:00",
                     "2009-01-02 12:35:00")
Cust_ID = c("1214", "2643", "31231", "41244", "1214", "15317", "51591")
Wait_Time_Mins = c("54","43","88","94","12","130", "170")
df_have = data.frame(Arrival_DateTime, Cust_ID, Wait_Time_Mins)

and want to convert it so I get the number of customer visits per day, and also their average wait time per day, so it looks something like this:
dates = c("2009-01-01", "2009-01-02")
num_visits = c("3", "4")
avg_wait_time = c("61.7","101.5")
df_want = data.frame(dates, num_visits, avg_wait_time)

How would I go about doing this?
Similarly, is there a way to do monthly aggregations as well?
Answer: You can use -
library(dplyr)

df_have %>%
  mutate(Arrival_DateTime = lubridate::ymd_hms(Arrival_DateTime),
         Date = as.Date(Arrival_DateTime),
         #For monthly aggregation -
         #Date = format(Arrival_DateTime, '%Y-%m'),
         Wait_Time_Mins = as.numeric(Wait_Time_Mins)) %>%
  group_by(Date) %>%
  summarise(num_visits = n_distinct(Cust_ID),
            avg_wait_time = mean(Wait_Time_Mins))

#        Date num_visits avg_wait_time
#1 2009-01-01          3      61.66667
#2 2009-01-02          4     101.50000

Comment: perfect, thank you so much.
Comment: Quick question though, when I try to use ggplot to plot the monthly time series I am getting a blank canvas. I noticed that the Date format is "chr" instead of date for the monthly case. Do you know what is wrong here? The code I used was exactly what you've got, but the with `#Date = format(Arrival_DateTime, '%Y-%m')` portion commented out. Thanks!
Answer: Using aggregate().
aggregate(as.double(Wait_Time_Mins) ~ as.Date(Arrival_DateTime), df_have,
          \(x) c(length(x), mean(x))) |>
  do.call(what=data.frame) |>
  setNames(c('date', 'num_visits', 'avg_wait_time'))
#         date num_visits avg_wait_time
# 1 2009-01-01          3      61.66667
# 2 2009-01-02          4     101.50000

Note: R >= 4.1 used.

Data:
df_have <- structure(list(Arrival_DateTime = c("2009-01-01 08:35:00", "2009-01-01 10:00:00",
"2009-01-01 10:25:00", "2009-01-02 07:45:00", "2009-01-02 15:32:00",
"2009-01-02 11:15:00", "2009-01-02 12:35:00"), Cust_ID = c("1214",
"2643", "31231", "41244", "1214", "15317", "51591"), Wait_Time_Mins = c("54",
"43", "88", "94", "12", "130", "170")), class = "data.frame", row.names = c(NA,
-7L))


How to write a MySQL query that returns a temporary column containing flags for whether or not an item related to that row exists in another table

Question: How might I write a MySQL query to achieve the desired result shown below?
I have two tables:
TABLE_USERS:

 ID | Name  |  ...
--------------------
 1  | Ash   |
 2  | Tim   |
 3  | Jim   |
 4  | Jay   |
 5  | Tom   |

TABLE_FLAGS:

 ID | Reason |  ...
----------------------
 2  |  ??    |
 4  |  ...   |

I want to know how to write a query that yields a result with the following columns:
DESIRED RESULT:

 ID | Name  | Flagged
----------------------
 1  | Ash   |  false
 2  | Tim   |  true
 3  | Jim   |  false
 4  | Jay   |  true
 5  | Tom   |  false

I could do:
SELECT TABLE_USERS.ID, TABLE_USERS.NAME
FROM TABLE_USER

To get the first two columns, but I'm not sure how to get the last one...
The final column does not directly correspond to a column in one of the two tables; instead for each row it returns true or false base on whether an entry for that rows id value exists in TABLE_FLAGS
Thanks
Answer:    SELECT   tu.ID,
            tu.NAME,
            CASE WHEN tf.ID IS NOT NULL THEN 'true' ELSE 'false' END AS Flagged
      FROM  TABLE_USER tu
            LEFT OUTER JOIN TABLE_FLAGS tf ON tu.ID = tf.ID

Comment: was going to suggest the same except using if(tf.id IS NOT NULL, 'true', 'false') as flagged. Nice answer!
Comment: I'll get an `Error Code: 1054` for a `Flagged = ...` construct.
Answer: This will show your desired output:
SELECT tu.ID, tu.NAME,
       CASE WHEN tf.ID IS NOT NULL THEN 'true' ELSE 'false' END AS Flagged
  FROM TABLE_USER tu
       LEFT OUTER JOIN TABLE_FLAGS tf ON tu.ID = tf.ID ;


infinite loop with changing timeouts

Question: I have an array that contains time windows. For a simple case I'm making these 10 second windows as follows, (In the beginning the current time will be inside window 1)
var now = new Date();
windowList = [
    { id: 1,
        start: new Date().setSeconds(now.getSeconds() - 5),
        end: new Date().setSeconds(now.getSeconds() + 5),
        waitTime: 2000},
    { id: 2,
        start: new Date().setSeconds(now.getSeconds() + 10),
        end: new Date().setSeconds(now.getSeconds() + 20),
        waitTime: 500}]

Then I've setup two functions to check if current time is in a window and in some window.
function isInWindow(window){
    var now = new Date();
    return (window.start < now && now < window.end);
}

and
function isInSomeWindow(windows){
    for (var i = 0; i < windows.length; i++) {
        if(isInWindow(windows[i])){
            return windows[i];
            break;
        } else {
            return false;
        }
    }
}

Now I want to go through the windowList as I loop with a period of waitTime. Whenever I'm not in a window I loop with period of 500 ms.
function daynmicRepeat() {
    var localPeriod = 1000;
    setTimeout(function () {
        window = isInSomeWindow(windowList);
        if (window){
            console.log('in window ' + window.id + ' @ ' + new Date())
            localPeriod = window.waitTime;
        } else {
            console.log('not in a window @ ' + new Date());
            localPeriod = 500;
        }
        daynmicRepeat();
    },localPeriod);
}

when I run it
daynmicRepeat()

I start off inside the first window and then eventually come out of it but never seem to go in to the 2nd window. What am I doing wrong?
Comment: I dont understand what you want to do. But I think that you can do it better with setInterval() .
Answer: isInSomeWindow breaks the loop. Try this:
function isInSomeWindow(windows){
    for (var i = 0; i < windows.length; i++) {
        if(isInWindow(windows[i])){
            return windows[i];
    }
}

Answer: Take another look at the loop in your isInSomeWindow function -- it will never get past the first run:
if(isInWindow(windows[i])){
    return windows[i];
    break;
} else {
    return false;
}

If isInWindow(windows[0]) returns false, you hit the else statement, and return out of the function.
Assuming you want the function to return false if no matching window is found, you want to return if the loop finished without returning:
function isInSomeWindow(windows){
    for (var i = 0; i < windows.length; i++) {
        if(isInWindow(windows[i])){
            return windows[i];
            break;
        }
    }
    return false;
}

infinite loop with changing timeouts


Smooth transition between two Forms in VCL

Question: I have been playing around for few hours with this but I cannot make it work. I have an application made of two Forms, and I want to switch from one form to another. I want this switch to be "smooth" (ie blending effect).
I came up with this solution which works partially : using the AnimateWindow function in the ShowForm() method. This works fine when I switch from Form1 to Form2. But switching back to Form1 does not work. Form1 is painted "behind" Form2 and when Form2 hides, the transition is already done.
Below is the very simple code for Form1:
#include <vcl.h>
#pragma hdrstop

#include "main_form.h"
#include "child_form.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    Form2 -> Show();
    Form1 -> Hide();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormShow(TObject *Sender)
{
    const int speed = 1000;
    AnimateWindow(Handle, speed, AW_BLEND);
}

and here the code for Form2:
#include <vcl.h>
#pragma hdrstop

#include "child_form.h"
#include "main_form.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm2 *Form2;
//---------------------------------------------------------------------------
__fastcall TForm2::TForm2(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm2::Button1Click(TObject *Sender)
{
    Form1 -> Show();
    Form2 -> Hide();

}
//---------------------------------------------------------------------------
void __fastcall TForm2::FormShow(TObject *Sender)
{
    const int speed = 1000;
    AnimateWindow(Handle, speed, AW_BLEND);
}

I tried to invert the Form1->Show()and Form2->Hide()statements in the code for Form2, to force hiding Form2 before painting Form1, but it does not work either: Form2 is hidden, then nothing is shown during animation time, and then Form1 is displayed all of a sudden.
Any idea?
Thanks.
Comment: In help of my version (XE7) it is said, not to use `TAnimateWindowProc()` directly. But in any case, the forms have a property `AlphaBlend` which enables/disables alphablending of forms, and an accompanying `AlphaBlendValue`. Increasing one forms value (0..255) in a loop, while decreasing another forms value (255..0) gives you the effect you are looking for. Both forms must have `Visible = True`.
Comment: @TomBrunberg Thanks for the reply. I actually tried this solution before posting this and it does not work either. Actually it works once. The first time each form is created this works, and then the form is displayed directly, without any blending. I'll try editing the initial question with a sample code of this solution tomorrow. But still, it's really frustrating not to be able to control which form is in front of the other.
Comment: In my test I changed both forms `AlphaBlendValue` in a loop, and the problem you describe is not so apparent. But it has the effect that since both forms are partly transparent during the transition, whatever is behind shows through briefly. I understand that you want to avoid that. The problem that you raise in your question is due to the fact that **one of the forms is the main form**. If you can rearrange so that the forms you want to swap smoothly are "not-main-forms", then you can bring to front, before the loop, whichever form is to become visible.
Comment: Indeed the main problem is the fact that one of the form is the main form. I tried creating a blank 3rd form as the main one, with a black background, that partially solves this. I will post this as an answer for lack of a better solution for the moment. Can you post your code with the use of AlphaBlendValue as an answer to the question too? So I can check the difference with mine?
Answer: As you requested, here's my take on the subject, but, as I'm shaky with C++Builder, in Delphi's pascal.
The problem you are describing (difference in behaviour depending on whether Form1 or Form2 is being brought to front) is due to Form1 being the main form. The problem does not exist if neither form is a main form.
If one form is the main form, the problem is less visible if you use AlphaBlendValue to change both forms visibility simultaneously, that is, raise the value for the form to bring into view and decrease the value for the other one. As both forms are partly visible, their z order is not so apparent as if you change only one of the forms.
Begin with a project with two forms (TForm25 and TForm26 in my code).
TForm25
  property AlphaBlend = True
  property AlphaBlendValue = 255
  property Visible = True

TForm26
  property AlphaBlend = True
  property AlphaBlendValue = 0
  property Visible = True

Add following code somewhere where both forms has access to it.
procedure FadeOutIn(FOut, FIn: TForm);
var
  i: integer;
begin
  FIn.BringToFront;
  for i := 1 to 255 do
  begin
    FOut.AlphaBlendValue := 255-i;
    FIn.AlphaBlendValue := i;
    sleep(1); // use 20 for a really slow transition, just to demonstrate
              // or remove if not needed
  end;
end;

In my test both forms are autocreated, and Visible = True for both, but Form26 is not visible since its AlphaBlendValue = 0. Each form has a button to call FadeOutIn() to fade out (hide) it self and fade in (show) the other form.
procedure TForm25.Button1Click(Sender: TObject);
begin
  FadeOutIn(Form25, Form26);
end;

procedure TForm26.Button1Click(Sender: TObject);
begin
  FadeOutIn(Form26, Form25);
end;

A caveat:
- As both forms are semi transparent simultaneously, whatever lies behind will also show through during the transition.
Comment: This works fine, but only if one of the forms is not the main form. If one of the form is the main one, there I still a strange effect I don't get. I can switch back and forth one time between forms, and then clicking again on Form1 shows briefly Form2 (without blending) and reverts back directly to Form1... By adding an extra blank Form as the main one, then it works perfectly, even with more than 2 windows.
Answer: Following @TomBrunberg 's advice, here is a possible solution. The main problem here is that one of the Form is a MainForm which stays always behind the other. To circumvent this, a 3rd blank Form can be created and declared as the main one. This Form Visibleproperty is set to False. The code for this 3rd Form is the following:

#include <vcl.h>
#pragma hdrstop

#include "background.h"
#include "main_form.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm3 *Form3;
//---------------------------------------------------------------------------
__fastcall TForm3::TForm3(TComponent* Owner)
    : TForm(Owner)
{

}
//---------------------------------------------------------------------------

void __fastcall TForm3::FormShow(TObject *Sender)
{
     Form1->Show();
}
//---------------------------------------------------------------------------

and the code in the two other Form is modified so that the Hide() method is called before the Show() one as shown below.
Form1:
#include <vcl.h>
#pragma hdrstop

#include "main_form.h"
#include "child_form.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    Form1 -> Visible = false;
    Form2 -> Visible = true;
}

void __fastcall TForm1::FormShow(TObject *Sender)
{
    int const sleep = 500;
    AnimateWindow(Handle, sleep, AW_BLEND);
}

and Form 2
#include <vcl.h>
#pragma hdrstop

#include "child_form.h"
#include "main_form.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm2 *Form2;
//---------------------------------------------------------------------------
__fastcall TForm2::TForm2(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm2::Button1Click(TObject *Sender)
{
    Form2 -> Visible = false;
    Form1 -> Visible = true;
}
//---------------------------------------------------------------------------

void __fastcall TForm2::FormShow(TObject *Sender)
{
    int const sleep = 500;
    AnimateWindow(Handle, sleep, AW_BLEND);
}

This only partially works : at first launch, Form1 is displayed, without transition effect but it is not very important. But when Form2 is called for the first time, the transition effect does not work either and the blank Form3 is visible during the length of the transition effect. After this, it works and both Forms can be displayed with transition effects.
Comment: I don't understand why `Form3` would become visible suddenly. Do you call up `Form2` from `Form1` (as I would expect you to)  or ….?
Comment: Yes I do. I edited the answer to add the code for Forms 1 and 2.


How to make the float field accept decimal values?

Question: I am using Drupal 7 and have a float field. It is used to enter prices.
Most of prices I enter have decimals (e.g. 101.82, 99.88). Some of the prices are negative values (e.g. -55.52, -1009.88).
Sometimes when I enter a decimal value, Drupal will remove the decimal value. (E.g. 101.82 will become 101.00). Other times, it will keep the decimal value.
There doesn't seem to be any rhyme or reason as to why it keeps the decimal values for some fields and omits it for other fields.
How can I ensure that it always keeps the decimal value?
Comment: Sounds like this: https://www.drupal.org/forum/support/post-installation/2011-05-19/float-field-gets-rounded-to-one-decimal-point-on-save
Comment: @RyanHartman Thanks! The solution given there appears to be for Durpal 8. Do you know how I can translate it for Durpal 7? Thanks in advance!
Answer: Your float values are working correctly. It is important to understand when to use a float and when to use a decimal type field. In your situation, using a decimal field seems to be the best solution. Check out these two wiki pages which break down how you would use these in Drupal.
Float

Floating point is something that confuses a lot of people. Floating point numbers are essentially numbers stored in scientific notation, almost the same thing that we learned in math class in school...Floats and Doubles are used to store estimated values. The numbers they store can only be accurate to a certain precision.

Decimal (Numeric)

It allows you to specify the precision and scale of a number...use DECIMAL data type to store exact numeric values, where we do not want any rounding off,  but exact and accurate values.

How to convert the field
In order to accomplish this you will need to create a simple module and activate it in Drupal. Start off by following steps 1-4 of this Drupal wiki page. After that is done, follow these steps:

Copy the new ****.module file you created in steps 3-4 and change the extension to ****.install so you now have two files, both with just <?php at the beginning.
Inside of the ****.install file, you need to add an update function that Drupal can run.
Once you have that function, you would place the code from this answer inside.
You will want to adjust the variables in the script to match your configuration ie; $field, precision, scale, not null.
Backup your database, and be ready to revert back to the backup if things go wrong.
Activate the new module, which I suggest you do from the command line via drush en your_module_name.

If your website is not too large, you can get away with this, but if it is big, you will have to explore your options because eventually PHP will timeout.
Comment: In Drupal 7, is there anyway to convert a float field into a decimal field? I have hundreds of values in the float field already (I know some of these won't be correct, but I'll just have to live with that). Thanks!
Comment: @big_smile use https://drupal.stackexchange.com/a/151367/20866 and edit the script to set the correct `precision` and `scale`.
Comment: @big_smile Sorry! I had the edit my answer a few times when I realized my first solution wouldn't handle everything you needed.
Comment: Thanks for your help! I assume I go to PHPmyadmin > Database name > SQL. Then put the code in the query window & hit "Go". Is that correct? I get this error: `3 errors were found during analysis.
Unexpected character. (near "$" at position 0)
Unexpected beginning of statement. (near "$" at position 0)
Unrecognized statement type. (near "field" at position 1)
SQL query:
$field = 'field_transaction_amount'
#1064 - You have an error; check the manual that corresponds to your MySQL server version for the right syntax to use near '$field = 'field_transaction_amount'' at line 1`
Comment: @big_smile I updated the answer with more details on the script.
Comment: Thank you so much! `You will want to adjust the variables in the script to match your configuration ie; $field, precision, scale, not null.` Based on the artilces you linked to, for prices (e.g. 28.53 or -15.99), the `precision` and `scale` would be `2` and I'd leave `not null` as `not null`. Is that correct?
Comment: @big_smile Precision is the total digits, scale is how many after the decimal. Your scale should be set to 2, and you can leave precision at 10. With precision at 10, you can have 8 digits before the decimal so the max/min values would be +/-99,999,999.99 respectively. Concerning the `not null`, I believe you would set that to TRUE if your field was required, I think.
Comment: I followed the steps exactly, but it doesn't seem to work. The machine name of my field is  field_transaction_amount, so for the script I entered `$field = 'field_transaction_amount';`. However, it still remains as a float field both with in the Drupal UI and phpmyadmin. I also ran Drush CC All and went to mysite.com/update, but neither did anything  (the update page didn't even have any updates). Any ideas? Thanks for all your continued help!
Comment: Did you enable the module before you added the `hook_update_7000()` function? You could make a new `hook_update_7001` function in your install file and drupal will detect that is has something new to run. You are most likely going to find the details you need to get the update to fire under the link in #2 in the answer.
Answer: Ryan Hartman's answer is the best to use. However, here is an alternative just in case that answer doesn't work.

Make a back up of your database.
Export your database from phpmyadmin. Before exporting, you might want to sort tables by size and then empty all the cache tables if they are too big. You can also empty search_index.
Open the software in an application that can read large database files such as BBedit. Sublime doesn't seem to cope with the size.
Search for "number_float" (ensure grep is off)
You will find results like this:
(23, 'field_name', 'number_float', 'number', 1, 'field_sql_storage', 'field_sql_storage', ….)
Replace the  'number_float' bit with 'number_decimal',
Repeat steps 3-5 for all instances of "number_float".
Now search for "float"
You will find multi line entries that begin with:
CREATE TABLE field_data_field_name(

In the multiple lines, they will have a line like this:
 field_name float DEFAULT NULL
Replace the word float with 'decimal(10,2)'.
Repeat steps 8 to 10 for all instances of "float". However, when searching you will come across entries that don't make references to fields, such as search_index and search total. Do not changes these.
Save the file and import into Phpmyadmin. Check in Drupal to see if all is okay.

Tip: Before exporting in step 2, go to Drupal and create a dummy field that uses decimal. (Give it a name that it is easy to search for such as aaaaa). Fill it with some dummy entries within Drupal. Then when you export your database, you can study how Drupal handles decimal fields, so you will know how best to change your float fields in the database.


Cannot run without administrator privileges

Question: I have a user who is running Lync, but unless it is run as an administrator, she cannot log in. Her Lync account is fine and other standard users do not have this issue.
I have been able to log in by logging on the machine as a domain admin and also by logging into her user account and running Lync as an administrator.
This issue occurs with both Lync 2010 and Lync 2013. The OS is Windows 7 Professional.
Edit:
We have just found out that if she logs onto other machines, she can log on fine. It seems the issue is local to that laptop.
Comment: It sounds like the kind of miscellaneous random corruption or just the wrong combination of things that would be way more effort to root out than it's worth... probably a few files (who knows which) have the wrong ownership or something.
Comment: Can you log in with a standard domain user account on her machine and then log into Lync?  You mention your domain admin works, but what about a normal account on her computer besides her?
Comment: Any particular reason against reimaging?
Comment: @FalconMomot No, but it would be great to know why first. Reimaging is fast becoming an option.
Answer: I have run into the same problem.  Support has said it is just a software issue.  They mentioned it might be a conflict between Office and Lync.  I have completely uninstalled Office and Lync; reinstalled Lync; no good.  I have completely uninstalled Office and Lync; reinstalled Office 2013 with Lync; no good.
What I have found is an order to run the Office programs.
1) Run Outlook.
2) Run Lync as administrator.
If you do them in the opposite order, Outlook will require you to run it as administrator.  When it is run as administrator, the search functionality is no longer available.
I believe Lync is accessing Outlook's files and does not have the correct permissions.  This leads to the conflicts and having to run Lync as administrator.


why some ioctl cases always fails?

Question: Recently, I am practicing a simple ioctl driver with three commands: print,get,set
In the ioctl switch statement, it looks like this pseudo-code:
switch (cmd) {
case "print":
    break;
case "get":
    break;
case "set":
    break;
default:
    break;
}

But, the print case can be correctly executed whereas get and set case are not.
therefore, I get the output
[ 2682.940000] mymem_ioctl: <---Switch Command =27395--->
[ 2682.940000] getdata=80046b01 80046b01setdata=40046b02 40046b02print=6b03 6b03
[ 2682.950000] <---ORG IOCPRINT :test_var=-1095999702--->
[ 2682.960000] <---IOCPRINT complete:test_var=111--->
cmd:6b03, arg=10 success
SETDATA cmd:40046b02
ioctl_setdata error
GETDATA cmd:80046b01
ioctl_getdata error

I tried to decode the ioctl command, but everything looks good.
getdata=0x80046b01 => 1000 0000 0000 0100 ....
setdata=0x40046b02 => 0100 0000 0000 0100 ....
print=0x6b03

0100 is size of int
6b is my magic number 'k'
01,02,03 is the number of function(get,set,print)

I don't know why... anyone can help on that?
the kernel version is 2.6.38, and below is my code

mymemdev.c
mymemdev.h
mymemdev_ioctl.h
user-space test program
Comment: Please update your question to show valid code. `case "print":` will not compile; you can't use string literals as case labels.
Comment: sorry for making an ambiguous  wrong....  it's just a sample code illustrating the workflow.
Comment: Are you going to update the question?
Comment: Talshorer has given the correct answer, in my driver file mymemdev.c line14 _IOC_NR(cmd)!=MYMEMDEV_IOC_MAXNR is WRONG which makes only  the PRINT command whose NR is equal to MAXNR can pass this if statment.
Answer: @line 14
_IOC_NR(cmd)!=MYMEMDEV_IOC_MAXNR

should probably be check
_IOC_NR(cmd) <= MYMEMDEV_IOC_MAXNR

Also, I beg you, follow the kernel coding style. It would make it so much easier for us to help that way.
http://lxr.free-electrons.com/source/Documentation/CodingStyle
Comment: i just solved this by myself few hours ago. it's exactly what you said. a stupid mistake. thanks for the info about coding style. :)

why some ioctl cases always fails?


Passing down the result of a promise

Question: so in my react code I have this:
  componentDidMount = () => {
    firebase.auth().getRedirectResult().then(function(result) {
        if (result.credential) {
          var token = result.credential.accessToken;
        }
        var ruser = result.user;
        console.log(ruser.displayName, 'lol'); //THIS LOGS CORRECTLY
      }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        var email = error.email;
        var credential = error.credential;
      }).then(function(result){
        this.setState({user: ruser});
        console.log(result, 'rslt'); //THIS LOGS UNDEFINED
      });

  }

I basically want to set the state of the user who is logged in. however, I get undefined when I pass this down, what have I done wrong with promises? i want to just pass down the result and make it available outside the scope of the function...
Comment: Also, `this` will not be defined in your last `then` callback. You need to either use an arrow function or bind `this` to the callback.
Comment: You probably need to `return result/ruser` in your first `then`.
Answer: Declarations from within a promise are meaningless unless you return what you declared - you have to return result if you want to pass it down:
componentDidMount = () => {
  firebase.auth().getRedirectResult().then(function(result) {
      if (result.credential) {
        var token = result.credential.accessToken;
      }

      console.log(result.user.displayName, 'displayName');

      return result; // this will be passed down
    }).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
      var email = error.email;
      var credential = error.credential;
    }).then(result => {
      this.setState({user: result.user});

      console.log(result.user, 'user');
    });
}

Also - as nils mentioned you have to use arrow function in the last .then to use parent's context and it's setState.
Comment: Don't forget to also `return` something meaningful from the `catch` callback - or move that to the end

Passing down the result of a promise


Auto login in raspi-config not available (Xenial 16.04)

Question: I am currently programming a robot that is controlled by a raspberry-pi3 b with Xenial 16.04.
When i turn it on, the raspberry needs to automatically start up and launch some python programs. The problem is that it gets stuck on the login screen, waiting for me to press 'ok' (i removed the password).
Auto login isn't available in raspi-config, and going into System > Users and groups doesn't offer the option either.
I've tried using systemd service and other solutions but none have worked for now. Do you have any ideas how i could login automatically into my session?
Answer: Auto login IS available in raspi-config.

Run sudo raspi-config;
Scroll down to Boot Options and press Enter;
Select Desktop/CLI;
You should see the options for Desktop Autologin or Console Autologin.

This is based on Raspbian Stretch.
You should not mess with systemd service.


Lost on "Simple Computations"

Question: I have come across the follow assertion: $$\text{for } x,y,z >0, xyz = x+y+z+2$$ may be rewritten as $$\frac{1}{1+x}+\frac{1}{1+y}+\frac{1}{1+z}=1$$
and that proving this is a matter of 'simple computations'. However, I can't seem to see the way about this.
I would say what I've tried so far, but every approach I've tried so far as petered out after a step or two.
Comment: Start with the second expression and multiply both sides by $(1+x)(1+y)(1+z)$
Comment: Wow, I started that but gave up for some reason. Thank you for a lesson in perseverance.
Comment: $\dfrac{x y+x z+2 x+y z+2 y+2 z+3}{x y z+x y+x z+x+y z+y+z+1}$ plug in what is given for $xyz$, you do get $1$.
Answer: I would go reverse engineering for that one $$\frac{1}{x+1} + \frac{1}{1+y} + \frac{1}{1+z} = 1$$
First you add $\frac{1}{x+1} + \frac{1}{1+y}$ to get $$\frac{1+y+1+x}{(x+1)(y+1)}= \frac{2+x+y}{(x+1)(y+1)}$$ now we add this result to $\frac{1}{z+1}$ to get  $$\frac{2+x+y}{(x+1)(y+1)} +  \frac{1}{z+1} = \frac{(2+x+y)(1+z) + (x+1)(y+1)}{(x+1)(y+1)(z+1)} =1$$
now you have $(2+x+y)(1+z) + (x+1)(y+1) = (x+1)(y+1)(z+1) $ Now Subtract $(x+1)(y+1)$ from each side , you will end up with $$(2+x+y)(1+z) = (x+1)(y+1)(z+1)-(x+1)(y+1)$$ now we have $$(2+x+y)(1+z) = (x+1)(y+1)(z+1-1)$$ and so we have
$$(2+x+y)(1+z) = (x+1)(y+1)z$$ Now expand the LHS and the RHS to get $$2 + 2z + x + xz + y + yz = xyz + zx + zy + z$$. Now $xz$ cancels with $xz$ and $yz$ cancels with $yz$ and you end up with $$ 2 + 2z + x + y = xyz + z$$ Now final step , you subtract $z$ from each side to end up with $$2 + z + x + y = xyz$$ and you are done !!!!
If you don't like reverse engineering , you can reverse what I did, and you would be able to go from that to the fraction form. reverse reverse = direct :)

Lost on "Simple Computations"


How to add newly created values in grid in extjs4

Question: I am working in extjs4. I have gridview as-
{
xtype : 'grid',
            id : 'g2',
            store : 'qb.qbquestionoptionStore',
            columns : [ {
                text : 'Options',
                dataIndex : 'option',
                flex : 1
            }, {
                text : 'Answer',
                dataIndex : 'isAnswer',
                flex : 2.5
            },{
                header : 'edit',
                renderer : function(val) {
                    return 'Edit';
                }
            },

Above grid is showing option and isAnswer field. I am also having addoption button. When i am clicking on this button,its showing new option creation window as-
on click of its save button i want to add thses new option and isAnswer fields value in above grid.I have retrived thses newly inserted field values by code-
var win = button.up('window');
        form = win.down('form');
        record = form.getRecord(), values = form.getValues();
    console.log(values.option);
    console.log(values.isAnswer);

So how to insert these values in above grid?
Answer: There is separation between data and view in ExtJs. All data related stuff is handled via stores and models. So if you want to insert new row into the grid you should insert it into the corresponding store:
var store = Ext.getStore('qb.qbquestionoptionStore');
store.add(form.getValues());

Comment: thanx sir for reply.. i have inserted lines as per you told. It is inserting these newly created entry in store. but does not showing this newly inserted entry on grid. So how to bring this entry on gridview also
Comment: @user1722857, Make sure that you insert into correct store (the one that connected to the grid). I use `Ext.getStore('qb.qbquestionoptionStore')` because I don't know your other code. You may use something like `grid.store`. Provided you inserted record into correct store the row should appear in the grid.


Correlation between two quadratic forms of Gaussian random vectors

Question: I want to calculate the correlation between two quadratic forms of two Gaussian random vectors (of course these are in fact non-Gaussian densities). Does anyone know the derivation of this case?
More precisely:
$$
\vec{x} \sim \mathcal{N}(\mu_{x}, \Sigma_{x}), \\
\vec{y} \sim \mathcal{N}(\mu_{y}, \Sigma_{y}),
$$
Furthermore, assume the following variance-covariance (correct term?):
$$\mathbb{E}((\vec{x} - \mathbb{E}(\vec{x})(\vec{y} - \mathbb{E}(y))^{T}) = \Sigma_{xy}$$
Asumme $\vec{A}$ is symmetric (for simplicity) and hence one can define quadratic forms
$$ z_{1} = \vec{x}^{T}\vec{A}\vec{x}, \ z_{2} = \vec{y}^{T}\vec{A}\vec{y} $$
What I know (http://en.wikipedia.org/wiki/Quadratic_form_%28statistics%29) is
$$\mathbb{E}(z_{1}) =  \mathbb{E}(tr(\vec{x}^{T}\vec{A}\vec{x})) \\
= \mathbb{E}(tr(\vec{A}\vec{x}\vec{x}^{T})) \\
= tr(\vec{A}(\Sigma_x + \mu_{x}\mu_{x}^{T})) \\
= tr(\vec{A}\Sigma_x) + \mu_{x}^{T}\vec{A}\mu_{x}  $$
With similar "tricks" one can derive $$var(\vec{x}^{T}\vec{A}\vec{x})$$ (see also Wikipedia or the Matrix cookbook).
However, I am totally stuck at finding $$cov(\vec{x}^{T}\vec{A}\vec{x}, \vec{y}^{T}\vec{A}\vec{y})$$
That is
$$\mathbb{E}((\vec{x}^{T}\vec{A}\vec{x} - \mathbb{E}(z_{1})(\vec{y}^{T}\vec{A}\vec{y} - \mathbb{E}(z_{2})) \\
= \mathbb{E}[\vec{x}^{T}\vec{A}\vec{x} \vec{y}^{T}\vec{A}\vec{y}] - \mathbb{E}(z_{1})\mathbb{E}(z_{2})$$
For the second term, see above. However, the first part seems to be tricky. The problem is, when I derive the variance, e.g. of $z_1$ then a similar term appears with all $\vec{x}$ instead of both variables. One can then apply a result on the expected value of a quartic (!) form (see: http://www.ee.ic.ac.uk/hp/staff/dmb/matrix/intro.html).
Unfortunately I find neither a derivation of the above nor a result on what I am looking for.
Wikipedia only lists the case where both quadratic forms are in the same random variable ($x$) but with different matrix ($A$ and $B$).
Has anyone seen this derivation or knows what I have to do?
EDIT: Not a complete solution but a hint for everyone who has the same problem. It turned out that even with the given moment generating functions in the Provost book, this is a tough issue. Frustrated by finding the derivatives, it turned out that is in fact easier to reformulate my specific problem to the one listed at wikipedia, i.e. two quadratic forms in the same random vector but with different Matrices. In fact, the solution I obtained is quite simple and totally agrees with the previous result where I had the variance only (not the correlation). But this might be a peculiarity of my specific problem and not a general result.
Comment: You could have a look at the references given in the answer to:  http://math.stackexchange.com/questions/442472/sum-of-squares-of-dependent-gaussian-random-variables/442916#442916
Comment: Note that you do not need to assume the matrix $A$ is symmetric, a quadratic form is determined by only the symmetric part of $A$, the antisymmetric part is zeroed.
Comment: Thanks but I did not find any references that deal with this question :(
Comment: Have a look  at  Mathai & Provost: "Quadratic forms in random variables".
Comment: Thanks for the Provost hint!

However, I've just flipped through it and apparently, my problem is contained under "Generalised Quadratic Forms". Which makes perfectly sense, as I am in fact looking for the covariance matrix of a vector $X$ of quadratic forms $X_i = x_i^T A x_i$ where the $x_i$ are correlated Gaussians.

Unfortunately, I do find lengthy expressions for the moment generating function but no word on the moments themselves. Only special cases where the correlation $cov(x_i, x_j)$ has a special form.Is that really that hard?
Comment: Well, you have the moment generating function, so you ca find the moments by differentiation ... Or you can try to mimick the techniques used by the book.
Comment: I guess the answer could be found here: https://math.stackexchange.com/questions/668641/covariance-of-two-chi-square-random-variables
Answer: The Mathai & Provost book "Quadratic forms in random variables" was mentioned in the comments. There, in page 76 you have the following formula for a covariance between two quadratic forms of a non-centered gaussian:
For $Q_1 = X^T A_1 X$ and $Q_2 = X^T A_2 X$ with $X \sim N(\mu, \Sigma)$:
$Cov(Q_1, Q_2) = 2 tr (A_1 \Sigma A_2 \Sigma) + 4 \mu^T A_1 \Sigma A_2 \mu$.
You can adjust this formula (for a single random variable) to your problem (where you have two different random variables $x$ and $y$). For this, you just need to set the random variable $X$ above to be the  concatenation of $x$ and $y$ from your problem. The mean of $X$ will be the concatenation of $\mu_x$ and $\mu_y$. The covariance $\Sigma$ would be a matrix composed of $\Sigma_x$, $\Sigma_y$ and $\Sigma_{xy}$ you mention in the different quadrants.
Finally, you can define $A_1$ and $A_2$ in the formulas above to just contain the matrix $A$ of your question, located in the upper left quadrant of the matrix for $Q_1$ and the lower right quadrant for $Q_2$, which would give you your desired quadratic forms. Now we have all the elements of your problem reparametrized in a way that is suitable to use the formula from the Matahn & Provost book above.


Sequence File in Spark - Read And Write Custom

Question: We had a data pipeline which was earlier built on Hadoop. But now we are trying to port some of our application to Spark.
In our data pipeline we had used sequence file as OP for each stage and which is passed to next stage.
So there are custom classes already written for Hadoop which implements Writable Interface for storing these data.
If I am trying to use it in Spark by creating the object of that class and save it as Sequence File I am getting errors like
Text/IntWritable or any other Writable class as not Serializable.
Is there any way to save the Sequence File in Spark using these custom classes.
The class is already present in Java and I don't want to modify those
Sample Example
public class Abc implements Writable,Serializable{
    private Text requestId;
    private Text requestType;

    //Constructor and other methods
    @Override
    public void write(DataOutput out) throws IOException {
        requestId.write(out);
        requestType.write(out);
    }

    @Override
    public void readFields(DataInput in) throws IOException {
        requestId.readFields(in);
        requestType.readFields(in);
    }
}

Its giving an error as Text object is not Serializable.
Answer: You will need to make you custom class both Writable and Serializable.  E.g.
class MyText(var string: String) extends Writable with Serializable {

  def this() = this("Empty")

  override def write(out: DataOutput): Unit = {
    Text.writeString(out, string)
  }

  override def readFields(in: DataInput) : Unit = {
    string = Text.readString(in)
  }
}

If possible, I would move away from Sequence Files, and switch to Parquet, for example.  You can see issues with Sequence Files, especially with Scala, where on reads Sequence Files are not immutable and you can get the same value for all objects in a collect.  See this JIRA ticket.
If you have a Java class which already implements Writable you could try creating a new class which inherits from that custom class and implements Serializable.  E.g.
class MyWritableAndSerializable extends MyCustomJavaWritable with Serializable {

    def this() = super.this()

}

Comment: "If possible, I would move away from Sequence Files, and switch to Parquet, for example. You can see issues with Sequence Files, especially with Scala, where on reads Sequence Files are not immutable and you can get the same value for all objects in a collect." Thank you Sir, I have been debugging this for a day now, and was just about to lose hope.
Comment: I am able to write to sequence file using Scala Class but my Class is already present in Java and I don't want to modify it as there are some important custom codes in it.(Part of important flows). I have updated the question can you please help me onto this
Comment: I have updated my answer with a suggestion, note I haven't tested it.


Question regarding identificaiton of Onto and Into Functions

Question: Was reading up my textbook about the identification of onto and into functions and one of the method given is as follows
Solve $f(x) = y$ for $x$, say $x = g(y)$ Now if $g(y)$ is defined for each $y \in \text{ codomain }$ and $g(y) \in \text{ domain of } f \text{ for all } y \in { codomain}, then f(x) \text{ is onto}$.
Quite did not understand how this works and what even the function $g(y)$ is?, is it the inverse of the function $f(x)$ could someone explain to me how this method works.
Comment: It is just an extremely imprecise and confusing way of saying that a function $f:X\to Y$ is onto if there exists a function $g:Y\to X$ such that $f(g(y))=y$ for all $y\in Y$.
Comment: Note: the method given in the original question subtly adds an unnecessary requirement, which will lead to confusion.  I do *not* recommend the method given in the book.  Consider a very simple function, with domain$=\{1,2\}$ and codomain, $= \{ 3 \}. f(1) = 3, f(2)=3$
This is clearly onto because the codomain has a single element which gets used by f.
However, the reverse is not a function.
Comment: @MichalAdamaszek Yes i did notice it thank you! please post this as a answer so that i can accept it
Comment: A simpler definition or method for determining "onto" also called being "surjective" follows.
For any and every choice of $y$ in the codomain, some $x$ exists, making $f(x) =y$ true.

Note: I'm using some *informal* terminology and methods.
Answer: That is indeed quite a confusing way to put it. The idea is that for any $y \in Y$, you can find an $x$, written as $g(y) = x$, such that $f(x) = y$. Below I have written a few things out, also for injective maps (because the idea is similar) and I hope this makes it more clear.
Suppose $f : X \to Y$ is a function. Then

$f$ is surjective iff for each $y \in Y$, there exists an $x \in X$ such that $f(x) = y$.

"$f$ is able to reach every point $y$ in the codomain $Y$"

$f$ is injective iff for all $x_1, x_2 \in X$ we have $f(x_1) = f(x_2)$ implies that $x_1 = x_2$.

"$f$ maps distinct elements in the domain to distinct elements in the codomain"

Now suppose there exists $g : Y \to X$ such that $f(g(y)) = y$ for all $y \in Y$. This implies that $f$ is surjective. This easily follows from the definition. The reverse is also true (actually, only if you assume the axiom of choice, but if you have never heard of this, you should not mind it. see also: Why the fact that surjective map has an inverse at right is equivalent to axiom of choice?).
You want to define $g : Y \to X$ such that $f(g(y)) = y$ for each $y \in Y$, and you do this as follows: for any $y \in Y$, we know by surjectivity that there exists $x \in X$ such that $f(x) = y$, now use this $x$ to define $g(y) = x$. This defines the required map $g : Y \to X$.
For injective maps something similar works. Suppose there exists $g : Y \to X$ such that $g(f(x)) = x$ for all $x \in X$. In a similar way, this implies that $f$ is injective. (Why?) The reverse direction is also true: if $f$ is injective, you can show yourself that there exists $g : Y \to X$ such that $g(f(x)) = x$ for all $x \in X$.


Can this be done because of the relationship between the Standard Deviation and the Median?

Question: <code>If a set of values create a Median of 85 and a Standard Deviation of 5, can you say:

    1-That all the values are between 75 and 95.

    2-That there are not any values greater than 90 and less than 70.

    3-None of the above.
</code>
I'm learning by myself, practicing and starting to read about this topic, but I'm having a little trouble with the "Standard Deviation" so I make this question, hope you can help, please.
Comment: You might want to add the `self-study` tag to the question.
Comment: To gain intuition you should see how these things behave for yourself. Try making up some data and see how far you can push the largest and smallest values around . For example, look at these data sets I made: **Set1**: $(70, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
85, 85, 85, 100)$,  **Set2**::$(85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
105)$...  **Set3**::$(65, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
85)$. They all have median 85 and sd 5. What do they tell us about your question? How did I manage to make them up just now?...ctd
Comment: ctd... (Hint try playing with data sets that only take values 0, 1 or -1 and then try making the sample size larger and smaller. Getting from there to any particular sd and median is simply scaling and shifting.(multiplying and adding appropriate amounts)
Answer: You can't say anything just knowing the median and standard deviation about a bound on the values. For instance, you could have a very large concentration of points close to the median (85), with a single outlier less than 70 or above 90 that raises the standard deviation to 5.
In general, all summary statistics (including median/standard deviation) do just that: Summarize. They will tell you things about the group of points as a whole, but will not tell you anything about individual data points.


How many kilograms of each type of fertilizer should the farmer use?

Question:
A farmer has a supply of chemical fertilizer of type A which contains 10% nitrogen and 5% phosphoric acid, and type B which contains 6% nitrogen and 10% phosphoric acid. After testing the soil conditions of the field, it was found that atleast 14 kg of nitrogen and 14 kg of phosphoric acid is required for producing a good crop. The fertilizer of type A costs Rs.5 per kg and the type B costs Rs.3 per kg. How many kg of each type of the fertilizer should be used to meet the requirement at the minimum possible cost? Using L.P.P. solve the above problem graphically.
Comment: Aside from typing the raw text of your homework, what effort have you made ? Unless you say where you are blocked, this question will be closed...
Comment: @JeanMarie hey there I have tried this and actually wanted to attach it with the question but as I am new here and lack experience with this platform I am not able to, it says I need 10 notices or something to be able to post them my equations are 10x+6y greater than or = 1400 and 5x+10y greater than or = 1400
Comment: @JeanMarie I am almost at the answer if there's any way I could post the picture so you guys could review it do let me know
Comment: Very well. Each one of these inequalities (to which you should add $x \geq 0$ and $y \geq 0$) defines a half-plane : hatch each of them ; the quadrilateral region which is hatched four times is the "feasible region". Now take a moving line $ax+by=m$... that should be just touching the feasible region, as you have been taught, I assume in your lectures.
Comment: @JeanMarie I got Zmin min at two points (80,100) and (0, 700/3) the value of Zmin in both cases is 700 now how do we chose between them ? When both the points have same value
Comment: @user74981 See [here](https://math.stackexchange.com/questions/2865834/linear-programming-optimization-with-multiple-optimal-solutions/2866071#2866071) how a linear program can be solved graphically.
Answer: Your inequalities are right. Now see here how to solve the a linear program graphically. Below the picture shows the graph of your problem.

I got $Z_{min}$ min at two points (80,100) and (0, 700/3) the value of Zmin
  in both cases is 700 now how do we chose between them ?

As you see at the graph that after the shift the objective function lies direcly on the first constraint $y\geq \frac{700}3-\frac53\cdot x$.  If we solve the objective function for y we get $y=\frac{z}3-\frac53\cdot x$
The reason why the objective function lies directly on the first constraint is that both have the same slope of $-\frac53$.
Thus the optimal solution is on every point on the constraint.
$(x^*,y^*)=\left(x, \frac{700}3-\frac53\cdot x\right)$, where $0\leq x\leq 80$
So both solutions you mentioned are valid. But all solutions in between them as well.
Comment: Thank you very much! Really appreciated, I learnt something new today
Comment: @user74981 You are welcome. I´m glad that it helps.


How can I enable pid and ppid fields in psacct dump-acct?

Question: I am currently using the psacct package on Centos to perform accounting on processes run by users.
The info file1 suggests that it is possible to output pid and ppid depending on what information your operating system provides in it's struct acct.
pid and ppid are listed in /usr/include/linux/acct.h on my system:
struct acct_v3
{
        char            ac_flag;                /* Flags */
        char            ac_version;             /* Always set to ACCT_VERSION */
        __u16           ac_tty;                 /* Control Terminal */
        __u32           ac_exitcode;            /* Exitcode */
        __u32           ac_uid;                 /* Real User ID */
        __u32           ac_gid;                 /* Real Group ID */
        __u32           ac_pid;                 /* Process ID */
        __u32           ac_ppid;                /* Parent Process ID */
...

But pid and ppid are not output when I run dump-acct:
# dump-acct /var/account/pacct.1 | tail
awk              |   0.0|   0.0|  81.0|    0|    0|8792.0|Thu Nov 24 04:03:04 2011
tmpwatch         |   0.0|   0.0|   1.0|    0|    0|3816.0|Thu Nov 24 04:03:04 2011
cups             |   0.0|   0.0|   4.0|    0|    0|8728.0|Thu Nov 24 04:03:04 2011
awk              |   0.0|   0.0|   4.0|    0|    0|8792.0|Thu Nov 24 04:03:04 2011
runlevel         |   0.0|   0.0|   0.0|    0|    0|3804.0|Thu Nov 24 04:03:04 2011
chkconfig        |   0.0|   0.0|   0.0|    0|    0|3840.0|Thu Nov 24 04:03:04 2011
inn-cron-expire  |   0.0|   0.0|   0.0|    0|    0|8728.0|Thu Nov 24 04:03:04 2011
awk              |   0.0|   0.0|   0.0|    0|    0|8792.0|Thu Nov 24 04:03:04 2011
gzip             |   5.0|   0.0|   9.0|    0|    0|4044.0|Thu Nov 24 04:03:04 2011
accton           |   0.0|   0.0|   1.0|    0|    0|   0.0|Thu Nov 24 04:03:04 2011

Is it likely that there is no support in my kernel for this feature or that my psacct version does not support this?
How can I add pid and ppid to my accounting logs?
CentOS release 5.6
Kernel 2.6.18-238.19.1.el5
psacct 6.3.2
Answer: I just found this in the changelog for the psacct RPM:
* Fri Nov 13 2009 Ivana Varekova <varekova(at)redhat.com> - 6.3.2-56
  - fix the psacct to deal with all acct types and
    if it is possible and wanted then add the possibility
    to display the pid and ppid number

So it looks like it depends in exactly which release you are using.
Answer: CentOS release 5.6
psacct 6.3.2

The psacct package shipped with CentOS 5.6 has release number 44:
Name       : psacct
Arch       : x86_64
Version    : 6.3.2
Release    : 44.el5
Size       : 107 k
Repo       : installed
Summary    : Utilities for monitoring process activities.
License    : GPL
Description: The psacct package contains several utilities for monitoring process
           : activities, including ac, lastcomm, accton and sa. The ac command
           : displays statistics about how long users have been logged on. The
           : lastcomm command displays information about previous executed
           : commands. The accton command turns process accounting on or off. The
           : sa command summarizes information about previously executed
           : commands.

and as @Ladadadada mentioned, according to the change log, PID and PPID are only available from 6.3.2-56 version. On my CentOS 6 (psacct-6.3.2-63):
accton           |   0.0|   0.0|   1.0|    0|    0|3832.0|   16114    16111|Thu Nov 24 13:37:50 2011
touch            |   0.0|   0.0|   3.0|    0|    0|105088.0|   16115    16111|Thu Nov 24 13:37:50 2011
psacct           |   0.0|   0.0|   9.0|    0|    0|106304.0|   16111    16059|Thu Nov 24 13:37:50 2011
w                |   0.0|   0.0|   3.0|    0|    0|105280.0|   16116    16059|Thu Nov 24 13:37:52 2011


How to stop Android Studio from copying files when adding module?

Question: I have 2 android projects: Tower and dronekit-android. I try to import both projects into Android Studio at the same time. So I first import Tower, then import dronekit-android in the project setting window. (Using File -> Project Structure -> +)
However, The Android Studio did something very unusual, namely, it always copy all source codes from the other project into the root directory of the current project. As illustrated in the following screenshot, in which all folders shown in the diff window are copied from dronekit-andorid to Tower.

How do I change this behaviour and import them without copying? Like in this:

UPDATE: I tried to modify my settings.gradle to include the other project with submodules:
//Android projects
include ':Android'
project(':dronekit-android').projectDir = new File('/home/peng/git-drone/dronekit-android')

but I can't import it due to this error:
Error:Project with path ':dronekit-android' could not be found.

is there anything wrong with the setting?
UPDATE2: I eventually edit setting.gradle manually and add the other project & all its submodules into it, take quite some time I was expecting Google Android Studio is smart to do it automatically:
//Android projects
include ':ServiceApp', ':StarterApp'
include ':ClientLib'

//Library projects
include ':Mavlink'
include ':UsbSerialLibrary'

project(':UsbSerialLibrary').projectDir = new File('dependencyLibs/usb-serial-for-android/UsbSerialLibrary')
project(':Mavlink').projectDir = new File('dependencyLibs/Mavlink')
project(':StarterApp').projectDir = new File('samples/StarterApp')

But then I got into another problem:
When I synchronise the project, I got this error:
Error:Plugin with id 'com.jfrog.bintray' not found.

Please see the screenshot for detail:
Answer: You forgot to include :dronekit-android:
include ':Android',':dronekit-android'
project(':dronekit-android').projectDir = new File('<fullpath>/<projectname>/<module folder>')

And in your build.gradle
dependencies {
    compile project(':dronekit-android')
}

Comment: You are right! Now I can see the files in the project window. But I got into a problem that never happens when importing either of the project independently. Is it a version conflict?
Comment: Not really, this is really how you import from local directory since your library module might have a similar name to other other modules (though that's a rare case).
Answer: If you're just trying to include another project into the one (without copying things over) you can add an entry in the "settings.gradle" file to specify the project name and where on the file system the project is (relative path is ok):
project(':project-name').projectDir = new File('path-to/project-name')

After doing this you just need to import the "main" project (the one with the modified settings.gradle).
Comment: Apparently doesn't work: Error:Project with path ':dronekit-android' could not be found. see my update for detail.
Comment: What's the directory structure under dronekit-android? The path should be to the module and not the root project (i.e. the path should point to the build.gradle with the "android" configuration)


Vector equation to line equation

Question: I've not read vectors in math yet but I'm done with those in physics. I want to find out a line equation from a vector equation. Say I've 2 points in 3D space: Point A with coordinate $(a, b, c)$ and point B with coordinate $(d,e,f)$. I can write it as $a\hat{i} + b\hat{j} + c\hat{k}$.
Now for another point $(d, e, f)$, I write it: $d\hat{i} + e\hat{j} + f\hat{k}$.
Now subtracting these 2 vectors would give me a resultant vector from one point to another. How to I get the line equation of that vector? i.e. in this case: $(a-d)\hat{i} + (b-e)\hat{j} + (c-f)\hat{k}$?
Answer: You don't have a 3D line definition with single equation like in the 2D case: $ax + by + c = 0$, or $y = mx + n$
In 3D, with a single equation of some linear combination of variable $x,y,z$, you can only define planes.
So in this case; ${\vec u} = (a,b,c)-(d,e,f)$ is our direction vector. And any point $(x,y,z)$ on the line can be written as
$(x,y,z) = (a,b,c) + t*{\vec u}$
$x = a + t*(a-d)$
$y = b + t*(b-e)$
$z = c + t*(c-f)$
If you want you can pull $x$ and re-write y-equation and z-equation in terms of x.
Answer: Hint: You can simply subtract the two vectors like $(a,b,c)-(d,e,f)$ to get what you have written.
Comment: Then? How do I get a line equation? like we have ax + by + c = 0 in 2D?
Comment: See Corbah ans above.
Answer: We have two vectors
$$
v_1 = (a, b, c) \\
v_2 = (d, e, f)
$$
then one can describe the line through the endpoints of the $v_i$ as
$$
(1-t) \, v_1 + t \, v_2 = v_1 + t (v_2 - v_1) \quad (t \in \mathbb{R})
$$

Vector equation to line equation


Spring integration with Struts 1 - injecting dependencies to the ActionForm

Question: We are expanding an old Struts 1 project to be Spring managed - yet we wish to change the code and the flow as little as possible. We have therefore decided to leave Struts to manage the requests and have delegated the actions via the org.springframework.web.struts.DelegatingActionProxy class.
Example:
The struts-config.xml contains:
<action name="InvalidSession"
        path="/pages/InvalidSession"
     type="org.springframework.web.struts.DelegatingActionProxy"
        scope="request">
    <forward name="success" path="/pages/Startup.do" />
</action>

The action-servlet.xml contains:
<bean name="/pages/InvalidSession"
      class="com.xxx.actions.InvalidSessionAction" />

Now the plot thickens:
Normal Spring beans have been defined in the applicationContext.xml. An example:
<bean id="parserUtils" class="com.xxx.el.parser.ParserUtils" >
    <property name="parserFactory" ref="parserFactory"/>
</bean>

I now wish to wire (not automatically - but that is not an issue) the parserUtils bean to an ActionForm.
Had I wanted to wire it to an Action I would simply define the follwing in the action-servlet.xml:
<bean name="/pages/CaseUpdate"
      class="com.xxx.actions.CaseUpdateAction" >
   <property name="parserUtils" ref="parserUtils" />
</bean>

where the following is in the struts-config.xml:
<action path="/pages/CaseUpdate"
        name="CaseUpdateForm"
     type="org.springframework.web.struts.DelegatingActionProxy"
        scope="request">
   <forward name="success" path="/pages/SwitchView.do" />
</action>

But the stuts-config also contains the following ActionForm definition:
<form-bean name="CaseUpdateForm"
           type="com.xxx.forms.CaseUpdateForm" />

and I wish to wire the parserUtils bean to the CaseUpdateForm class.
What must I do?
Thanks all!
Comment: the following did not help me, or perhaps I misunderstood it:  http://stackoverflow.com/questions/354171/struts-and-spring-together
Answer: It seems as if I have found a solution:
In the struts-config.xml file I have changed:
<form-bean name="CaseUpdateForm"
           type="com.xxx.forms.CaseUpdateForm" />

to:
<form-bean name="CaseUpdateForm"
           type="org.springframework.web.struts.SpringBindingActionForm" />

I have added the following to the action-servlet.xml file:
<bean name="CaseUpdateForm"
      class="com.xxx.forms.CaseUpdateForm" >
   <property name="parserUtils" ref="parserUtils" />
</bean>

And:
<bean name="/pages/CaseUpdate"
      class="com.xxx.actions.CaseUpdateAction" >
   <property name="caseUpdateForm" ref="CaseUpdateForm" />
</bean>

I have added the following to the CaseUpdateForm.java class file:
private ParserUtils parserUtils;

public void setParserUtils(ParserUtils parserUtils) {
    this.parserUtils = parserUtils;
}

And the following to the CaseUpdateAction.java class file:
private CaseUpdateForm caseUpdateForm;

public void setCaseUpdateForm(CaseUpdateForm caseUpdateForm) {
    this.caseUpdateForm = caseUpdateForm;
}

Finally the method:
public ActionForward execute(ActionMapping mapping,
                     ActionForm form,
                 HttpServletRequest request,
                 HttpServletResponse response)
                throws Exception

got the following lines of code inserted to it:
SpringBindingActionForm springBindingActionForm = (SpringBindingActionForm) form;
ServletRequestDataBinder binder =
    new ServletRequestDataBinder(caseUpdateForm, "CaseUpdateForm");

binder.bind(request);
springBindingActionForm.expose(binder.getBindingResult(), request);

I also had to include the following jar in the classpath:

spring-webmvc.jar

That is due to the usage of the class: ServletRequestDataBinder
Answer: You always have the option of programmatically fetching the parserFactory bean from the Spring context.
Spring's DispatcherServlet "publishes" the servlet's application context as a session attribute. You can retrieve the application context from there, and manually obtain your parserFactory from that context.
Something to get you started:
public Object getBean(ServletContext servletContext, String servletName, String beanName) {
    String attrName = FrameworkServlet.SERVLET_CONTEXT_PREFIX + servletName;
    BeanFactory beanFactory = (BeanFactory) servletContext.getAttribute(attrName);
    return beanFactory.getBean(beanName);
}

As you can see, you need access to the ServletContext object (which your ActionForm should be able to get using getServlet().getServletContext()), plus the name of the Spring servlet (as defined in web.xml), plus the name of the bean in the Spring application context that you need to retrieve.
It's pretty ugly, but it should work, if you have access to the above information.
Comment: I am trying to avoid all that and to somehow configure all this "magically" :)
Comment: Nothing magical about Struts. Since your Struts objects are not Spring-managed (just delegated), Spring has no say in their construction or configuration.