Usar dados database mysql e php

Question: Esse código funciona corretamente com as datas fixas. Como fazer para usar as datas que estão cadastradas no banco de dados mysql?
<code>if (!empty($_REQUEST['year']) && !empty($_REQUEST['month'])) {
$dates = array(
    array(
        'date' => '2016-09-17',
        'badge' => false,
        'title' => 'Evento para o dia 22-09-17',
        'body' => 'Descrição do evento',
    ),
    array(
        'date' => '2016-09-23',
        'badge' => false,
        'title' => 'Evento para o dia 22-09-23',
        'body' => 'Descrição do evento',
    ),
    array(
        'date' => '2016-09-30',
        'badge' => false,
        'title' => 'Evento para o dia 22-09-30',
        'body' => 'Descrição do evento',
    ),
    array(
        'date' => '2016-10-02',
        'badge' => false,
        'title' => 'Evento para o dia 22-10-02',
        'body' => 'Descrição do evento',
    ),
);
echo json_encode($dates); } else { echo json_encode(array()); }
</code>
Comment: @DiegoRibeirodaSilva coloque a resposta como resposta.
Comment: o que vc já tentou? Um select * from tabela e algum loop por exemplo?
Comment: Consegui resolver.
Comment: @DiegoRibeirodaSilva Poste vc mesmo a reposta.
Comment: Ja editei e coloquei a resposta.
Answer: Consegui resolver assim.
<code>$mysqli = new mysqli('localhost','usuario','senha_database','tabela_database');
if ($result = $mysqli->query("SELECT * FROM eventos")) {

    while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $dates[] = array(
                            'date' => $row['data'],
                            'badge' => false,
                            'title' => 'Evento para o dia' . $row['data'],
                            'body' => 'Descrição do evento',
                        );
    }
    echo json_encode($dates);
}
</code>

Usar dados database mysql e php


A little confusion on galois groups

Question: We know $Gal(Q(\zeta_n)/Q) \cong (Z/nZ)^*$  for $n\geq 2$.
Then $Gal(Q(\zeta_2)/Q) \cong (Z/2Z)^*$ this means $Gal(Q(\zeta_2)/Q)$ has one element, the identity automorphism.
The map $\delta:Gal(Q(\zeta_2)/Q)\rightarrow Gal(Q(\zeta_2)/Q)$
where $\delta(a_0 + a_1\zeta^1)=a_0 - a_1\zeta^1$ is an automorphism that fixes Q by applying the property of ring homomorphisms.
QUESTION:
Whys is it that $\delta$ is not an element of $Gal(Q(\zeta_2)/Q)$?
Comment: Title: you have a little confusion already before Galois groups, namely about $\mathbb{Q}(\zeta_2)/\mathbb{Q}$, which is the trivial $1$-degree field extension.
Answer: Hint: What is $\Bbb Q(\zeta_2)$? What is your $\zeta$? Write it out explicitly, and you will probably see your error.
Comment: Can you answer my question, then? Which number is $\zeta$?
Comment: alright thanks i solved it. $Q(\zeta_2) = Q$
Comment: because the square roots of unity are 1 and -1
Comment: @unknownMe Which makes the Galois group trivial, as your theory told you it should be.
Comment: im trying to check for errors but i cant really point out. can you please show your solution sir?

A little confusion on galois groups


$5$-th power of a complex matrix is identity. What are the eigenvalues?

Question: Suppose $A$ is a complex matrix satisfying: $A^5=I$ What are the possible (complex) eigenvalues of $A$?
Don't really have any ideas. Can we say that $\det(A)=1$ ? if so does it help at all?
Any help is appreciated.
Comment: How about using this: if $p$ is a polynomial and $\lambda$ is an eigenvalue of $A$, then $p(\lambda)$ is an eigenvalue of $p(A)$,
Comment: @GEdgar: While that is true, the statement somewhat obscures what is going on. I find it easier to remember and understand that $P[A]$ acts on an eigenspace of$~A$ for eigenvalue$~\lambda$ by the scalar $P[\lambda]$.
Answer: The polynomial $X^5-1$ is annihilator of $A$, therefore the eigenvalues of $A$ are fifth roots of the unity. Please note, that not all fifth roots of the unity are necessarily eigenvalues of $A$, this is only an inclusion.
Answer: Hint. If $Au=\lambda u$ (with $u\not=0$) then $0=(A^5-I)u=(\lambda^5-1) u$.
What may we conclude about the eigenvalue $\lambda$?
Comment: That would mean \lambda are the fifth roots of unity? But how did you get $(A^5-I)u=(\lambda^5-1)u$
Comment: @Kevin Yeh Because $A^2u=A(Au)=A(\lambda u)=\lambda A u=\lambda(\lambda u)=\lambda^2 u$ and so on.
Comment: @Kevin Yeh Any further doubt?
Comment: No, all is clear. Thank you very much for the help.
Answer: From the definition of the Eigendecomposition,
$$A=P^{-1}DP$$ so that
$$A^5=P^{-1}DPP^{-1}DPP^{-1}DPP^{-1}DPP^{-1}DP=P^{-1}D^5P=I$$ and $D^5=I$.
This shows that the Eigenvalues are fifth roots of the unit.
Comment: You're assuming that $A$ is diagonalizable without justification
Comment: @Omnomnomnom: that's right.


Drupal users getting blocked automatically

Question: I am experiencing a strange problem with my drupal website. On it, there are a good number of registered users. Sometime the users login, but not very frequently. Suddenly I figured out that some of the users (who are relatively old) are getting blocked. I check with blocked users, they said they did nothing. I do not have any idea how they got blocked.
Ok, then I unblock them manually and now they are active. Next day, I find them blocked again. So, now I need to unblock a bunch of users manually which is not the optimal way to deal with the users.
Anyidea? Anybody?
Thanks,
Answer: Do you happen to have the Inactive User module installed? This module can be used to block users who are inactive for some time. Otherwise, are you sure that the users are not trying to log in with the wrong password (5 times), which would also block them. It could be possible that someone else is trying to log in with these user accounts and is getting them blocked (I suppose it would be up to you to decide how likely this is based on whether or not your website is fairly high or low profile).


Ingres stored procedure to delete multiple records from table

Question: I am creating a SP in Ingres to delete multiple records from single table by comma separated id's, but it is not working. Though when I execute it in a separate query (without storedprocedure) then it is deleting records.
create procedure sptest
(
    In Ids varchar(300)
)
AS
BEGIN
   Delete from "ingres".mytable where request_id IN (:Ids);

END

Requested rows should be deleted from table
Answer: The input is a varchar so in effect what you have in the delete statement is something like:
delete from mytable where request_id in ('1,2,3,4');
Inside a database procedure you can't run "execute immediate", so you can't build a delete string without the quotes and execute it dynamically (though this might be an option to you if your calling program has "execute immediate" available).
To process the IN list within a database procedure I think you'll need to loop through the input string and delete for each value...
eg:
set session authorization ingres;

drop table if exists mytable;
create table mytable(request_id integer);
insert into mytable values(1),(2),(5),(10);

drop procedure if exists sptest;
create procedure sptest
(
    In Ids varchar(300)
)
AS
declare msg = varchar(300) not null;
        eno = integer not null;
        rc  = integer not null;
        pos = integer not null;
        n   = varchar(300);
BEGIN
   while (length(:Ids) > 0)
   do
     pos = locate(:Ids, ',');
     n = left(:Ids, :pos-1);
     Ids = shift(:Ids, -1 * pos);
     msg = 'Removing ' + :n;
     message :msg;
     Delete from "ingres".mytable where request_id = integer(:n);
     select iierrornumber, iirowcount into :eno, :rc;
     msg = 'Error number '+varchar(:eno) + ' rowcount ' + varchar(:rc);
     message :msg;
   endwhile;
END;

execute procedure sptest('1,5,10');
select * from mytable;


Time-series linear combination that fits a given time-series

Question: Given N different time-series and a new time-series for the same time period, what would be the correct approach to finding a linear combination of the N time-series which best describes the new time-series?
*I'm new to the field so this might be a simple question with a simple answer, I just want to be sure I'm in the right direction for further reading.
Comment: It all depends on what you mean by "best describes".  As it stands, if we were to drop the term "time series" and just view your data as vectors, it would sound like a routine least squares fit.  How does your problem differ from that?
Comment: Yes, that's what it sounds like.
Comment: @whuber assuming "best describes" means "least squares", then would you say that this is a multivariate linear regression with N variables (vectors)?
Comment: thanks @whuber, your suggestion to view the time-series as plain vectors helps.
How would you define "best describes" if we want to consider a time-series that changes twice as fast as one of the base N time-series as "described" by that time-series. lease-squares would not work here. In this case, should we transform the N time-series to their respective rate-of-change vectors and run a regression on them?
Comment: You have to decide whether variable transformations are allowed. If not, then you are left with least squares on the original regressors. If yes, then you would have to figure out the relevant transformations first and then do least squares.
Answer: I ended up using Multiple Linear Regression, on the log-returns of the time series.
In the content of time-series of asset returns, a key note on using the intercept:
 - if the goal is to fit an assets return using a set of other assets for purposes of portfolio construction, than an intercept should be avoided as it provides an external sources of "free" baseline return (a bias in the linear regression) which is not achievable using any of the given assets.
 - if the goal is to create the best possible fit, then the intercept should be used and it will provide a better fit (or at least no worse) then without the intercept.
These are probably very basic concepts, but it took me a while to get a clear grip of the solution so I'm adding my answer.


Self-studying differential forms and tensors

Question: I am interested in understanding the generalized Stokes' Theorem. From my understanding, this theorem involves differential forms and exterior algebra, and tensors (to some extent).
I'm not particularly interested in geometry; I do like analysis, though, and generalizations of the fundamental theorem of calculus have fascinated me since I first heard of Green's Theorem.
I've taken vector calculus; I'm in real analysis now, where we are going to cover the change of variables theorem of multiple integrals before we finish. I haven't, however, taken any classes in geometry. The point-set topology of metric spaces is as far as my topology knowledge goes.
With this background, is there a path towards self-studying (and hopefully understanding) Stokes' Theorem?
Answer: There is definitely a path towards getting there.  In fact, I recommend jumping right into "An Introduction to Manifolds" by Loring W Tu.
The advantage to this book is that, coming from your background, you should find the reference to be self-contained.  That is, you should be able to just read through this book without outside references.
There are definitely books that build up to the "Stokes' theorem" punchline faster, but this seems about right for where you are.  If you use this book, I recommend skipping chapters 3 and 4 at first, at least to get through to Stokes' theorem.
Comment: Thank you for the recommendation. I must say that I didn't expect such a book to exist, i.e. one that is spot on for my level.
Comment: Just flipped a bit through this book. Looks very nice. Thanks!
Comment: You're welcome, both of you :D
Answer: I am quite happy with this already:


Migration run will execute rb files under 'config/initializers/' firstly?

Question: Is it so that if I run 'rake db:migrate' to run the latest migration, the files under 'config/initializers/' will be triggered to run firstly?
At least, when I create migration with 'rails generate migration XXXX' command, the ruby files under 'config/initializers/' will run firstly... So, I would like to know is it so that all the initializer files will be run before migration run?
Comment: Yes... Environment files are needed because in running migration files so many things are required like database connection, model etc.
Answer: During a migration the full Rails environment is setup, so YES, the initializers in config/initializers will be run before the migrations.


Android: prevent display from turning off

Question: I've written a small game, that is only controlled via some sensors. There is no touchscreninput or something similar.
The problem is, that after a few seconds of gaming, the screen turns off (because of no touch-input)
Is there something like a manifest-entry that prevents the screen from this behaviour?
regards
Answer: use this code in the your game's Activity as first line in the onCreate() after the super call:
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

This will result in the System handling the screen for you.
Best wishes,
Tim
Answer: The simplest would be adding android:keepScreenOn="true" to the layout in your xml.
Comment: for my small app, this was exactly what i've searched:) thanks it works
Answer: use WakeLock
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
WakeLock mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "My Tag");
mWakeLock.acquire();

and put the permission in your manifest file
<uses-permission android:name="android.permission.WAKE_LOCK" />

dont forget to release that lock in your onStop()
Answer: You can request a WakeLock as specified here: http://developer.android.com/reference/android/os/PowerManager.html


Polar to Rectangular Coordinates

Question: Problem:
Transform the following equation from polar to rectangular coordinates.
\begin{eqnarray*}
\rho &=& \frac{2}{1 - \cos \theta} \\
\end{eqnarray*}
Answer:
Recall that:
\begin{eqnarray*}
\rho &=& {(x^2+y^2)} ^ {\frac{1}{2}} \\
\cos \theta &=&  \frac{x}{\rho} =\frac{x}{(x^2+y^2)^{\frac{1}{2}}} \\
\end{eqnarray*}
This gives us:
\begin{eqnarray*}
{(x^2+y^2)}^{\frac{1}{2}} &=& \frac{2}{1 - \frac{x}{(x^2+y^2)^{\frac{1}{2}}}} \\
2 &=& {(x^2+y^2)^\frac{1}{2}} - x \\
x + 2 &=& (x^2+y^2)^\frac{1}{2} \\
(x + 2)^2 &=& x^2+y^2 \\
x^2 + 4x + 4 &=& x^2+y^2 \\
4x + 4 &=& y^2 \\
y^2 &=& 4x + 4
\end{eqnarray*}
However, the book gets:
\begin{eqnarray*}
y^2 &=& 4(x + 2)
\end{eqnarray*}
What am I missing?
Comment: A typo in the book?
Answer: Let's check with $\theta=60^\circ$ so that $\rho=4$. Then: $x=2$, $y=2\sqrt3$, $y^2=12$. But $4(x+2)=16$ and $4x+4=12$. So you are right and the book is wrong.
Comment: Perhaps even easier, check at $\theta = \frac\pi2$ ($90$ degrees). Then $\cos\theta = 0$, $x=0$, and $\rho = 2$, hence $y = 2$ and $y^2 = 4$. The book says $y^2$ would be $8$ when $x = 0$.

Polar to Rectangular Coordinates


Adding text to moving Ellipse in C# WPF

Question: i have a program in C#, wpf.
i have a canvas and on the canvas exists many ellipses that are moving randomly.
Can i add text to each ellipse for example the position of the ellipse ???
Comment: This might help you: http://social.msdn.microsoft.com/Forums/en-AU/wpf/thread/27c9eb93-8a32-40d8-b0dd-b441a2496907
Answer: Of course, create a user control. The xaml of that user control is a grid that contains your ellipse and your textbox that you set up like you want. Then define the PropertyChanged notifying properties you need, like X,Y, and maybe other text property. Then bind your user control's xaml (Canvas.Top/.Left) to your user control's properties, and you're done.
Comment: i am using canvas not grid and i need to do it not in xaml but in c#
Comment: there's no reason not to do it in xaml... anyway if you insist on doing it in C# then show your code for ellipse and i (or someone else) can help you add your text. If you don't make a user control, you'll have to make custom control.

Adding text to moving Ellipse in C# WPF


Converting JSON into readable format

Question: enter image description here
I am trying to put the data in this array, into a readable format for my data tables. I have no clue how i'd solve this one. Any help is appreciated.
The only part of the array I want is the 'message' row.
Answer: Looks like you skipped a few or more tutorials, but it's done like this:
<code>$data = json_decode($yourJsonString, true);
var_dump($data['message']);
</code>

Converting JSON into readable format


Issue with calling PHP global variable in phalcon

Question: I have the following code in my controller:
<code><?php
class skillsController extends \Phalcon\Mvc\Controller
{
    public function indexAction()
    {
        $skills = Skills::find();
        $this->view->setVar("skills", $skills);
    }

    public function deleteSkillAction()
    {
        $GLOBALS['gID'] = $_GET["id"];
    }

    public function yesAction()
    {
        $id = $GLOBALS['gID'];
        echo $id;
        $manager = $this->modelsManager;
        $phql    = "DELETE FROM skills WHERE id =:id:";
        $manager->executeQuery($phql, array('id' => $id));
    }

    public function noAction()
    {

    }
}
</code>
I am retriving a varible called id via GET and setting it to $GLOBALS['gID'] in my deleteSkillAction function, now why when i call it in the yesAction function does phalcon not know what this varible is?
Comment: You should use the session for that: http://ch2.php.net/manual/en/intro.session.php - $GLOBALS are only persistent to one request.
Answer: You should read more basic information about PHP and HTTP. There is nothing wrong with Phalcon here. You assigned variable to GLOBALS array during request to the deleteSkill action, and then you try to access this variable during another request to the yesAction. Use some persistent container for this case: session or memcache for example.


Display form within a custom field?

Question: I've created a module that has a 'form builder' on the admin side.  Once the form has been created, I store the form array in the database.  Then on the front end I've created a custom field that pulls the form array from the database and displays it as part of a node.  Here is the pseudo-code to show my thinking:
- Create form via admin side and store form array in database
- Create node with custom field, choose which form you wish to display
- Set url alias on the node
- When user views url, display the form as part of the node

The problem I have is that when I complete the form on the front end and press submit, nothing happens.  Looking at the html, it doesn't have a <form> tag, presumably because it's part of a node and not a hook_form.
So, I'm wondering if it's possible to display a submittable form as a custom field?  Or do I need to find another way around this?
Edit:  I'm using the following code to display the form:
function mantis_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

    $element = array();

    switch($display['type']) {
        case 'mantisform_default': {

            // Retrieve the form from the database
            $form_data = mantis_retrieve_form_data($items[0]['mantis_form_id'], 'display');

            $element[]['#markup'] = drupal_render($form_data);

        }
    }
    return $element;
}

Edit:  $form_data structure can be seen here http://pastebin.com/JfeNGBGA  and $element is here http://pastebin.com/HU5NSHd5
Answer: You have to check your field handler, node tpl.php or field tpl.php and use drupal_render($yourform), it's the cleanest solution I see.
Comment: What give your dpm($form_data) and dpm($element) ?
Comment: I've edited the question to show the code I am using to display the form.  I am using drupal_render already, so wondering if there is a difference between using drupal render in a template file as oppose to using it in hook_field_formatter_view?
Comment: Sorry for the delay, I've added the structure of form data to pastebin http://pastebin.com/JfeNGBGA
Comment: Output for $element http://pastebin.com/HU5NSHd5
Answer: Figured this one out.  The reason the form wasn't submitting was because I wasn't calling drupal_get_form.  It seems that drupal_get_form carries out a lot of essential processing that allows the form to function.  Simply creating a form array and calling drupal_render is not enough to create a functional form.
The solution was to create an implementation of hook_form and retrieve my form data from the database:
function mantis_form($form, &$form_state) {

    $data = db_select('mantis_forms', 'f')
    ->fields('f', array('form_data'))
    ->condition('id', $form_state['build_info']['args'][0], '=')
    ->execute()
    ->fetchField();

    if($data) {
        $data = unserialize($data);

        // If we're on the admin side then disable the submit button
        if($form_state['build_info']['args'][1] == 'admin') {
            $data['form_wrapper']['submit_form']['#disabled'] = true;
        } else {
            // If we're on the front end then enable the submit button and remove the optional fields
            $data['form_wrapper']['submit_form']['#disabled'] = false;
            array_slice($data, 1, 1);
        }

        return $data;
    }
}

And then amend the hook_formatter_view to use drupal_get_form:
function mantis_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

    $element = array();

    switch($display['type']) {
        case 'mantisform_default': {

            $form_data = drupal_get_form('mantis_form', $items[0]['mantis_form_id'], 'display');

            $element[]['#markup'] = drupal_render($form_data);

        }
    }
return $element;
}

Comment: drupal_get_form before drupal_render. Good one, bye !

Display form within a custom field?


Pausar a execução em um Service em Android

Question: Estou desenvolvendo uma aplicação Android onde há um IntentService para ler um arquivo.
Cada linha do arquivo representa um registro que deve possui um formato específico de acordo com os requisitos da aplicação. Um registro é inválido, por exemplo, se o numero de caracteres for maior que um determinado tamanho.
Preciso que, se durante a leitura do arquvio for encontrado algum registro inválido, a execução seja pausada e seja exibida uma notificação para perguntar se ele deseja pular aquela linha e continuar a leitura a partir da próxima linha ou se deseja cancelar toda a leitura.

Minha única dúvida é: Como posso pausar a execução do código dentro de um while no método protected void onHandleIntent(Intent intent) em um IntentService  para exibir a notificação, se isso for possível?

Código de exemplo:
public class ImportImovelService extends IntentService {

    {...}

    // Será chamado assincronamente pelo Android
    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent == null)
            return;

            fis = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(fis, FileUtil.ENCODE));

            String strLine;
            boolean eof = false;

            do {

                if ((strLine = br.readLine()) == null) {
                        // End of file (eof)
                        eof = true;
                        break;
                    }

                    if (strLine.length() > 136) {

                        // foi encontrado um registro inválido, deve pausar a
                        // leitura do arquivo e perguntar ao usuário se deve
                        // continuar a leitura do arquivo.
                        // O usuário seleciona se continua ou se encerra a
                        // leitura

                        if (usuarioEscolheContinuar) {
                            // pula o registro, cancela a iteração atual e
                            // prossegue para a próxima iteração
                            continue;
                        } else {
                            // a execução inteira é cancelada
                            stopForeground(true);
                            stopSelf();
                            return;
                        }

                    }

                // leitura normal do arquivo
                {...}

            } while (!eof);

            stopForeground(true);
            stopSelf();
    }
}

Answer: Opa, tudo bem!?
Talvez o CountDownTimer possa lhe ajudar.
 new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

Crie uma contagem regressiva, e no caso do usuário der ok, vc poderá cancelar a contagem regressiva e dar continuidade na sua instrução.


Paypal IPN listener INVALID most of the time

Question: I have this strange problem where some IPN verification return INVALID.
The type of IPN is subscr_payment.
The other types like subscr_eot or subscr_cancel are verified just fine.
I use ipnlistener.php
Nothing fancy with it. What can be wrong?
Answer: There must be something about the way you're sending the data back to PayPal for those types of transactions that it doesn't like.  Are you re-formatting amounts or anything like that?
You need to send it back to PayPal exactly as they send it to you in order for it to validate.
Comment: yes, I found the issue, there was a SSL certificate required in the curl config. Strange only subscr_payment required it.


Find the general solution of a linear system of ODEs, with non-constant coefficients

Question: It is given, that the following system of ODEs has a non-trivial solution with a constant y axis
\begin{alignat*}{4}
   \frac{dx}{dt} = x-e^{-t}y \\
   \frac{dy}{dt} = 2e^tx-y \\
\end{alignat*}
Find the general solution of this system.
Any ideas?
Thank you
Comment: Where do you get stuck?
Comment: Are you learning to solve it as a first-order system or possibly decouple into a single second-order equation instead?
Answer: Multiply the top equation by $e^t$ and subtract this first equation from the second.  The result is
$$y'-e^tx' = xe^t.$$
$$y' = e^tx' + xe^t = \frac{d}{dt}(e^tx).$$
Thus,
$$y = e^tx + C_1.$$
Substitute into original first equation.
$$x' = x - e^{-t}(e^tx + C_1).$$
$$x' = x-x-C_1e^{-t} = -C_1e^{-t}.$$
You should be able to continue from here.  Solve for $x(t)$.  Then,
simply substitute to find $y(t)$.
You will find that $y$ constant is a special case.


Find AB where A= matrix and B=matrix

Question: $A=\left[\begin{array}{ccc} 2&1&0\\0&3&-1
\end{array}\right]$
$B=\left[\begin{array}{cc}a&1\\1&b\\b&a\end{array}\right]$
Matrices
Find $AB$
Comment: Welcome to math.SE! Please consider taking the time to read the [faq] to familiarise yourself with some of our common practices. In addition, [this page](http://meta.math.stackexchange.com/q/5020/8348) should give you a start at learning how to typeset mathematics here so that your posts say what you want them to, and also look good. As this question appears to be homework, please consider reading [this page](http://meta.math.stackexchange.com/q/1803/8348) for information about asking _effective_ homework-related questions. Cheers!
Comment: Please, use latex to write math. I don't have a clue of what are the matrices and what do you want, you just need the product AB?, is this homework?.
Answer: It seems that the matrix $A$ is $2\times 3$ and $B_{3\times 2}$ so we have $$AB=C_{2\times 2}$$ Now to do the latter matrix, you need to multiply the only row of $A$ by all columns of $B$ as follows:
<code> C[11]=[2 1 0][a  = 2*a+1*1+0*b=1+2a
               1
               b]

 C[12]=[2 1 0][1  = 2*1+1*b+0*a=2+b
               b
               a]

 C[21]=[0 3 -1][a  = 0*a+1*3+(-1)*b=3-b
                1
                b]

 C[22]=[0 3 -1][1  = 0*1+3*b+(-1)*a=3b-a
                b
                a]
</code>
Comment: Needs a TU to go with the green tick! (+)
Comment: @amWhy: In that time, I was at my Prof. room and honestly not to manage the good shape of matrices inside. :)
Answer: $$AB=\left[\begin{array}{ccc} 2&1&0\\0&3&-1
\end{array}\right]\left[\begin{array}{cc}a&1\\1&b\\b&a\end{array}\right]$$
If you know basic matrix multiplication, you should know
$$\begin{align}
AB =& \left[\begin{array}{cc}
A\left[\begin{array}{c}a\\1\\b\end{array}\right]&
A\left[\begin{array}{c}1\\b\\a\end{array}\right]
\end{array}\right]\\=& \left[\begin{array}{cc}
\left[\begin{array}{ccc}2&1&0\\0&3&-1\end{array}\right]\left[\begin{array}{c}a\\1\\b\end{array}\right]&
\left[\begin{array}{ccc}2&1&0\\0&3&-1\end{array}\right]\left[\begin{array}{c}1\\b\\a\end{array}\right]
\end{array}\right]\\
=&\left[\begin{array}{cc}
\left[\begin{array}{ccc}2&1&0\end{array}\right]\left[\begin{array}{c}a\\1\\b\end{array}\right]&
\left[\begin{array}{ccc}2&1&0\end{array}\right]\left[\begin{array}{c}1\\b\\a\end{array}\right]\\
\left[\begin{array}{ccc}0&3&-1\end{array}\right]\left[\begin{array}{c}a\\1\\b\end{array}\right]&
\left[\begin{array}{ccc}0&3&-1\end{array}\right]\left[\begin{array}{c}1\\b\\a\end{array}\right]
\end{array}\right]\\
=&\left[\begin{array}{cc}
2a+1&
\left[\begin{array}{ccc}2&1&0\end{array}\right]\left[\begin{array}{c}1\\b\\a\end{array}\right]\\
\left[\begin{array}{ccc}0&3&-1\end{array}\right]\left[\begin{array}{c}a\\1\\b\end{array}\right]&
\left[\begin{array}{ccc}0&3&-1\end{array}\right]\left[\begin{array}{c}1\\b\\a\end{array}\right]
\end{array}\right]
\end{align}$$
For each value in the resultant array, the row vector and column vector multiplication is simply the sum of product of corresponding values. For example
$$\begin{align}
\left[\begin{array}{ccc}2&1&0\end{array}\right]\left[\begin{array}{c}a\\1\\b\end{array}\right] =& 2\times a + 1\times 1 + 0\times b\\
=& 2a +1
\end{align}$$
You should be able to find all values in terms of $a$ and $b$ now.

Find AB where A= matrix and B=matrix


How do I use ssh forwarding?

Question: I have a Linux server which only opens two ports for public:
remote-server-ip : 1111
remote-server-ip : 2222

We have a web application in the server which use 3333 port and can't be changed.
So, to be briefly what I need is:

In a public network, use browser visit http://remote-server:1111 or http://remote-server:2222.
The remote server access my request and forward my request to port 3333.
Response my request.

I thought ssh forwarding should do this. But what exactly should I do to make it ?
I have tried this in the remote-server :
ssh -N -L 1111:127.0.0.1:3333 127.0.0.1

But it doesn't work at all, nothing happened.
Comment: This question appears to be off-topic because it is about defeating local security settings.
Comment: Can you make it clear ***WHY*** you want to do this (as opposed to just opening another port)? This does tread dangerously close to "circumvention of security or policy", which is an explicitly out-of-bounds topic area on Server Fault (we're not going to help you break out of another sysadmin's security, we wouldn't appreciate it if they helped you break out of ours!)
Comment: You should check out what exactly ssl -L does.  It's probably only listening on loopback.
Answer: What did you expect to happen?
That said, you have ssh'ed from the remote server to the remote server while forwarding ports on the remote server, which although it will work, may not produce the results you expect.  Try:
desktop% ssh -N -L 26622:localhost:3333 remote.server.address

and then access localhost:26622 from desktop; that should connect you to remote.server:3333.
Edit: that's not how ssh forwarding works, and it's not what it's for. You need to talk to the sysadmin who maintains the firewall on remote.server, if you want to open up a port for the inbound internet. Also, I'm afraid questions about defeating security provisions are generally considered off-topic for Server Fault.
Comment: I need to access the remote server's 3333 port via `http://remote.server:3333`, from a public network. I can't access `remote.server:3333` directly since it only opens `1111` and `2222` for public.
Answer: This sound more like the need for a local proxy.
The solution I use is based on Apache httpd. Externally only port 80 can be accessed but the internal web application listens on port 8080. If you can set up an apache with the following config it shold work:
Listen 1111

ProxyRequests Off

<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

<VirtualHost *>
    Servername localhost
    ProxyPass   /   http://localhost:3333/
    ProxyPassReverse   /   http://localhost:3333/
</VirtualHost>

How do I use ssh forwarding?


moving thread-synchronisation-responisbility into shared resource

Question: Given an object(=instance) that is used by multiple threads the following approach is the most common (as far as I know):
the shared resource:
class Resource():
    def return_some_value(self):
      return self.somevalue

global (or parent context):
lock = Lock()
res = Resource()

within an accessing thread:
lock.acquire()
res.return_some_value()
lock.release()

Obviously the accessing thread is responsible to lock and unlock the shared resource.
Lets presume the shared resource is more complex and some methods/properties are read-only while others are not. The Threads using the resource now have to know which is which and lock accordingly. That is obviously error-prone and I sometimes have trouble choosing where to put the Lock object.
Now my question: Is it possible to shift the responsibility to correctly lock to the shared resource itself? Does it even make sense?
Something like:
class Resource():
    def __init__(self):
        self.lock = Lock()
    def return_some_value(self):
        self.lock.acquire()
        return self.somevalue
        self.lock.release() # obviously this won't work

Answer: Yes, doing that makes perfect sense. You can also use a Lock as a context manager to ensure it's always released:
class Resource():
    def __init__(self):
        self.lock = Lock()

    def return_some_value(self):
        with self.lock:  # Lock gets acquired
            return self.somevalue  # Lock gets released

The owner of a Lock is based on the thread that acquired it. So many different callers can call into your Resource object from different threads, and the lock will behave appropriately.
This wouldn't work well if you need to call multiple methods on Resource which require you to hang onto the lock the entire time. In that case, you may want to consider making the resource itself lockable:
class Resource():
    def __init__(self):
        self.lock = Lock()

    def __enter__(self):
        self.lock.acquire()

    def __exit__(self, *args, **kwargs):
        self.lock.release()

    def return_some_value(self):
        return self.somevalue

    def some_method(self):
        # stuff

    def some_other_method(self):
        # stuff

r = Resource()
with r:
    r.some_method()
    r.some_other_method()
    val = r.return_some_value()

Comment: Thank you. I was not sure if the lock would be released after the return statement. But apparently that is always the case with a with-statement (and also with try-finally). I did not know that.
Comment: @Peter Yep, as [stated in the docs](https://docs.python.org/2/reference/compound_stmts.html#the-try-statement): "*When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed 'on the way out.'*"
Comment: In regard to the second part of your answer: If the methods are independent from one an other, both variants would work equally well, wouldn't they?
Comment: @Peter I would say that if each method is independent, the first option is better, since the client doesn't need to worry about locking things at all. If a property/method is read-only for all threads, there's no need to lock them. The only exception to that is if the read-only method is using some resource that can't be shared (like a method that reads from a file object, or uses an iterator, that's stored in the instance, for example). Though I suppose you could argue that's not really "read-only".


How do I compare the performance of random forests for regression?

Question: I've trained two random forests for a regression, based on the same data and variables, only with a different number of tree in each one.
If I'm not wrong, having more trees is always better in terms of how the model performs. Can you confirm that?
However, due to practical considerations, we can't afford to load a random forest of 10Gb, so we need to lower the number of trees in the forest.
How can I compare the respective performance of the forests?
Comment: Better is a very loaded word.  More trees takes longer to compute so it is not better for compute.  What is your items per leaf, and max depth?  How many trees are we talking about?  What can you tell about the data?
Comment: I mean better in terms of predictive accuracy. Items per leaf is `mtry`, right ? It's chosen by the package (`caret` and `ranger` in `R` ) using RMSE (and it's 7, there are 11 features in total). `Max depth` : I don't know (I thought that in random forest, trees went all they way to the point were one node = one data point ?). How many trees : I want to compare how well a 50 trees and a 200 trees RF do against a 500 trees RF.
Comment: I like the diagnostics and access to internal data provided by the 'h2o' and 'Flow' tools.  They both come in the R library 'h2o'.  You should repeat each fit some number of times and look at the distribution of errors at the end of the fit.  This way you can see overlap in distribution or non-overlap in distribution.  I would plot the end-error using a vioplot.
Answer: I like the @hxd1011 answer, and this is only to expand on it slightly.
Here is my code:
#with  random forest
library(randomForest)

#how many trees
ntree_list <- c(15,30,60,125,250,500)

#how many tests per tree
ntests <- 100

#prepare for loop
err <- as.data.frame(matrix(nrow = ntests, ncol=length(ntree_list)))

#main loop
#for each tree-size
for (i in 1:length(ntree_list)){

     names(err)[i] <- paste(as.character(ntree_list[i]),"tree",sep="_")

     #run a stack of tests
     for (j in 1:ntests){

          #fit the forest
          fit=randomForest(mpg~.,data=mtcars,ntrees = ntree_list[i])

          #pop the final error off the ensemble
          err[j,i] <- fit$mse[ntree_list[i]]

     }
}

You could, if you wanted, put other tree parameters in there instead of tree-count.
And now to plot the results:
#make plot
boxplot(err,notch=T,names=names(err), ylab = "MSE of Random forest",
        ylim = c(0, (range(mtcars$mpg)[2]-range(mtcars$mpg)[1])/2 ) )

grid()

This gives the following plot:

About the better, and agreeing with @hxd1011, eventually more trees doesn't do much good.  It doesn't improve error.  It does take more memory and cpu.  You can observe that the 125 tree forest is, most of the time, pretty close to the MSE of the 500 tree forest.
When you start pruning, both by requiring at least so many samples to make a leaf, and by only allowing the tree to get so many levels deep, it substantially improves memory.  A "not bad" start is 5 elements per leaf, and max depth of 8.  This really is emprical and depends on the problem being solved.
If we change the code as follows:
n_list <- seq(from=1,to=29,by=1)
err <- as.data.frame(matrix(nrow = ntests, ncol=length(n_list)))
for (i in 1:length(n_list)){
names(err)[i] <- paste(as.character(n_list[i]),"count",sep="_")

          #fit the forest
          fit=randomForest(mpg~.,       #formula
                           data=mtcars, #data frame
                           ntrees = 125,
                           nodesize = n_list[i])

          #pop the final error off the ensemble
          err[j,i] <- fit$mse[125]

Then the plot changes as follows:

You can see that when we use around 7 leaves per node, the MSE is still reasonably consistent with the "1" or "4" elements. If we had used 19 leaves, that requirement substantially impacts the MSE, and the MSE could be nearly double that of a "7" elements per leaf on tree rule.
The red lines are the mutant child of an eyeball norm and a scree plot.  After 21 leaves per tree are required the RF becomes essentially no more useful than the midrange.
You can also do things like round the input data, or truncate digits.  This allows less discrimination on inputs and can drive generalization.  Take baby steps when doing this because while throwing away a little data can be a good thing, throwing away a lot of data is usually a bad thing.
Fun observation:

Breiman's randomForest beat h2o here.  It takes much longer to do this exercise with h2o from today than with Breiman's work from a decade ago.
Comment: great answer! Interestingly, I have tried many "revised random forest" model. Most models claim the original CART has biased feature selection problem and their tree are better in terms of unbiased feature selection. But in many real world data I worked with, it seems Brieman's original random forest is outperforming many modern models.
Answer:
You should always have loss calculated to compare how good the model is. In regression the loss can be least square or least absolute value. You can compare how good the model is in a "testing data / validation data".
mtry should be the only parameter you are tuning on.
More trees is not "better", with sufficient number of trees, the "estimated testing error / out of bag error" will "converge". I personally never use more than 1000 trees. And you can observe when does it converge by plotting random forest.
library(randomForest)
fit=randomForest(mpg~.,data=mtcars)
plot(fit)
Comment: Thanks. Is there a way to plot the same thing with `ranger` ?
Comment: Number of trees should be driven by data.  If you have many columns and many rows, and the relationship are complex, then you can "over-fit" later than 1000 trees.  If you use a training and validation split then the oob error is not your only estimator for overfit.
Comment: @EngrStudent I think there are many discussions about random forest "over fitting". My experience is that it seems does not over fit at all. Although there are signs like very low loss in training data, but in testing it seems fine.
Comment: @hxd1011 I think you've been lucky. Random forest does overfit, particularly if you have large number of features.
Comment: Thanks for your information @horaceT. Could you please give me some examples of over fitting? I found one [here](http://stats.stackexchange.com/questions/113177/random-forest-cant-overfit)
Comment: @hxd1011 Sorry most examples are from my own modeling. But you could simulate "fat" datasets and I'm sure you'll see it very quickly.
Answer: Random forest overfits too. It happened everytime I tried RF model. All the models I tried had more than 15 features to somewhere more than a couple of hundred. I have read in many places that it does not overfit but it does and sometimes by a big margin. Sometimes, it does really well on the development sample but really poorly on the validation. It depends on the data (noise level) and many other parameters.
Comment: 1) Your answer makes unsupported assertions, not arguments. It would be improved if you could substantiate them. 2) The number of features being high does not imply overfitting; the RF uses all features that you give it.
Comment: @Mahesh - I've used RF on data with ~20k columns, and had good results.  Width alone  isn't necessarily the problem.


What is no ' information rate ' algorithm?

Question: I plan to implement ' no information rate ' as part of summary statistics. This statistic is implemented in r (Optimise SVM to avoid false-negative in binary classification) but not in Python (at least I cannot find a reference) .
Is there a canonical reference that I can refer to so as to implement this algorithm ?
I've searched Wikipedia and various Google searches but have not found a reference.
Update :
Reading caret doc https://cran.r-project.org/web/packages/caret/caret.pdf
"
The overall accuracy rate is computed along with a 95 percent confidence interval for this rate
(using binom.test) and a one-sided test to see if the accuracy is better than the "no information
rate," which is taken to be the largest class percentage in the data.
"
Comment: In R's `caret` package `confusionMatrix` function (which is what was used in the example you linked to), the No Information Rate is just the largest class percentage in the data (this is explained in the help for the function, which you can access by typein `?confusionMatrix` in the R console). The idea is that a useful model should do better than you could do by always predicting the most common class.
Comment: @eipi10 thanks , does this mean ' no information rate ' term originated with r  ?
Answer: Suppose that you have response $y_i$ and covariates $x_i$ for $i = 1 ...n$, and some loss function $\mathcal{L}$. The no information error rate of a model $f$ is the average loss of $f$ over all combinations of $y_i$ and $x_i$:
$${1 \over n^2} \sum_{i=1}^n \sum_{j=1}^n \mathcal{L}\left(y_i, f(x_j)\right)$$
If you have a vector of predictions predicted and a vector of responses response, you can calculate the no info error rate by generating all the combinations of predicted and response and then evaluating some function loss on these resulting vectors.
In R, supposing RMSE loss, (using the tidyr library) this looks like:
predicted <- 1:3
response <- 4:6
loss <- function(x, y) sqrt(mean((x - y)^2))

combos <- tidyr::crossing(predicted, response)
loss(combos$predicted, combos$response)

In Python this looks like
import numpy as np

predicted = np.arange(1, 4)
response = np.arange(4, 7)

combos = np.array(np.meshgrid(predicted, response)).reshape(2, -1)

def loss(x, y):
    return np.sqrt(np.mean((x - y) ** 2))

loss(combos[0], combos[1])

Comment: Although implementation is often mixed with substantive content in questions,
we are supposed to be a site for providing information about statistics, machine
learning, etc., not code. It can be good to provide code as well, but please
elaborate your substantive answer in text for people who don't read this language
well enough to recognize & extract the answer from the code.
Comment: Further discussion of this equation (and topic) can be found in "Elements of Statistical Learning, 2nd edition", see equation 7.58. https://web.stanford.edu/~hastie/ElemStatLearn/
Comment: Finally had some time to update the answer. Let me know if this still needs changes?
Comment: expand.grid can be used in place of tidyr::crossing for a base solution
Answer: The no information error rate is the error rate when the input and output are independent. You can compute it by evaluating the prediction rule on all possible combinations of the target and the features, i.e as
$$\hat \gamma = \frac{1}{N}\sum_{i=1}^N\sum_{j=1}^NL\left(y_i, \hat f(x_j)\right).$$
Answer: No information rate is Naive classifier which needs to be exceeded in order to prove that model we created is significant. We calculate accuracy and then compare it with Naive classifier. accuracy should be higher than No information rate (naive classifier) in order to be model significant.


Decimal expansion of a Cauchy sequence

Question: In one of the construction of $\mathbb{R}$ we make each real number an equivalence class of Cauchy sequences in $\mathbb{Q}$. More precisely, two Cauchy sequences $a_n$ and $b_n$ are equivalent iff $|a_n-b_n|\to 0$.
Is there a general method of computing the decimal expansion of the limit of a Cauchy sequence? In other words, given a Cauchy sequence $a_n$ is there a way of determining an equivalent Cauchy sequence $b_n$ such for all $n\in\mathbb{N}$ it is true that $b_{n+1}$ and $b_n$ are identical for the first $n$ digits (making $b_n$ a sequence of decimal truncation of $\lim_{n\to\infty} a_n$). If there is no such algorithm, can we determine these decimal places up to $n$ digits? My problem is that different Cauchy sequences converge at various rates, and determining the nature of their convergence seems to be a case-by-case problem.
If there is no algorithm, how can one go about proving that every real number (as equivalence classes of Cauchy sequences) has a decimal expansion?
Answer: For the second part of your question, if you have $a\in\mathbb R$ you can build the sequence $a_n=\lfloor a\cdot10^n\rfloor\cdot10^{-n}$ and then prove that this is a Cauchy sequence.
Now, you are right about different rates of convergence.  Given $a_n$ a Cauchy sequence, then $b_n=\lfloor a_n\cdot10^n\rfloor\cdot10^{-n}$ should also be a Cauchy sequence converging to the same point a $a_n$, but if $a_n$ converges slowly, then $b_n$ and $b_{n+1}$ will have few ($\ll n$) digits in common.
Another possibility is having the subseries $\varepsilon_m=10^{-m}$, now, by definition of Cauchy sequence, there should be $N_m$ such as $|a_n-a_{N_m}|<\varepsilon_m$ (for each $n>N_m$), so let's take $b_m=\lfloor a_{N_m}\cdot10^m\rfloor\cdot10^{-m}$ and it should be possible to prove that $b_m$ is a Cauchy sequence and it converges as $a_n$.
Comment: This is pretty close, but I would specifically like to have $b_n$ represent decimal truncations of $a=\lim_{n\to\infty} a_n$. Also sorry for the really late response.
Comment: @ChristianBueno The second $b_n$ sequence is pretty close to the decimal expansion of $a$, although in some cases the $n$th digit might be off by 1.
Answer: If you have constructive info about the Cauchy-ness of the sequence, i.e. you are able for any given $\epsilon>0$ to actually  exhibit $N$ such that $|a_m-a_n|<\epsilon$ for all $n,m>N$, you may have a chance to algorithmically find the decimal (or binary or whatever) expansion of the limit. To find the first $n$ digits, you can start with some $\epsilon<10^{-n}$, determine the corresponding $N$, check how close $a_{N+1}$ is to adjacent $n$-digit numbers and retry with smaller $\epsilon$ if necessary. This is guaranteed to give you the desired $n$ digits after finite time - unless the limit actually happens to be precisely of the form $\frac m{10^n}$.

Decimal expansion of a Cauchy sequence


Running multiple domains on same server

Question: I have a Ubuntu server running Apache and have 3 sites under /var/www/website/abc, /var/www/website/xyz and /var/www/website/lmn. I have 3 domains (www.abc.com, www.xyz.com, www.lmn.com) mapped to same machine (mapped same ip to 3 different domains on godaddy).
So I googled around and found this link - virtual host setup and made abc.com.conf in /etc/apache2/sites-available/ and correspondingly for other sites. Enabled the sites and then restarted apache but same site(/var/www/website/abc) appears on all 3 domains. I rechecked the paths but they seem to be correct. I can't figure out what is wrong. How can I route them to their corresponding sites?
Answer: It would be helpful in the future if you share your code (in this case the apache config files) to figure out what's wrong. In any case, this is roughly how the files can look (they don't have to look like this, there are other ways it can be configured).

First check /etc/apache2/apache2.conf and make sure you see the following code:
IncludeOptional sites-enabled/*.conf

The apache2.conf file is the primary configuration file. That line above includes all of the configuration files in the site-enabled folder. If you use a Red Hat derived OS you'll notice that the configuration file structure is different (Debian derivatives like Ubuntu like to split everything up into tons of configuration files, Red Hat derivatives keep it together)

Make sure that each of the files in the sites-enabled folder includes lines that look like this.

For abc.com.conf:
<VirtualHost *:80>
    ServerName www.abc.com
    DocumentRoot /var/www/website/abc
</VirtualHost>

If you also want "abc.com" to point to this virtual host enter "ServerAlias abc.com" underneath the ServerName line. What you're doing here is creating a VirtualHost block for any ip address (*) on port 80 (:80).  You could replace the * in the opening VirtualHost line with your external ip address if you want to make sure that the VirtualHost is only matched to a particular ip (this is only potentially needed if there are multiple external ips pointing to your webserver). The ServerName line tells apache to match this VirtualHost whenever the Host HTTP header is www.abc.com. ServerAlias can be used to specify additional Hosts to match. Remember that www.abc.com and abc.com are treated as different Hosts. The DocumentRoot line sets the directory from which files are served.
Similarly for xyz.com.conf:
<VirtualHost *:80>
    ServerName www.xyz.com
    DocumentRoot /var/www/website/xyz
</VirtualHost>

If you also want "xyz.com" to point to this virtual host enter "ServerAlias xyz.com" underneath the ServerName line.
And finally for lmn.com.conf:
<VirtualHost *:80>
    ServerName www.lmn.com
    DocumentRoot /var/www/website/lmn
</VirtualHost>

If you also want "lmn.com" to point to this virtual host enter "ServerAlias lmn.com" underneath the ServerName line.
Comment: I had the servername as www.lmn.com thats why it didnt work :P I removed it and restarted and it worked.

Running multiple domains on same server


Will the roots of $p(p(x))=0$ be purely real or purely imaginary or neither?

Question: Question
The quadratic equation $p(x)=0$ with real coefficients has purely imaginary roots. Then the equation $p(p(x))=0$ will have -
a) only purely imaginary roots
b) all real roots
c) two real and two imaginary roots
d) neither real nor purely imaginary roots
My Thoughts
I assumed a quadratic equation $${p(x)=ax^2+bx+c=0}$$ Now, as the coefficients are real the two roots must be conjugates. Let these roots be $ki$ and $-ki$.
Satisfying it in the equation gives $b=0 \Rightarrow p(x)=ax^2+c=0$ or $x^2+λ=0$ where $λ=c/a$ (to reduce the variables).
Now, putting it in $p(p(x))=0$ we get $x^4+2λx^2+λ^2+λ=0$. Now I am stuck here. I don't know how to proceed further.
Comment: Hint: If $p(p(x))=0$, then $p(x)$ is a root of $p$.
Comment: You have expanded $\frac{1}{a} p\left( \frac{1}{a} p(x) \right)$, but this is not equal to $p(p(x))$ or a multiple of it, and will have different roots.
Comment: What happens if you make $x$ purely imaginary in $ax^2+c$? Can the result be a root of $p(x)$?
Comment: Have you thought about using the formulas for roots of quadratic polynomials?
Comment: @aschepler Sorry, yes you are right. I should have kept a and c separate and after opening p(p(x)) should have reduced variable.
Comment: @aschepler Then I would get p(p(x))= a^3x^4+2ca^2x^2+ac^2+c=0.
Comment: By applying quadratic formula I am getting $${x^2= -c/a ± root(c/a)i}$$
Comment: What do I interpret from this?
Answer: WLOG the polynomial has the form $p(x)=x^2+a^2$. Then
$$(x^2+a^2)^2+a^2=0$$ has two distinct pairs of complex conjugate roots.
Comment: So, the answer should be (d) right? Can you also confirm whether $${x^2=-c/a±root(c/a)i)}$$ should be the general solution?
Comment: For $${a(ax^2+c)^2+c=0}$$
Comment: @InfiniteCool23: no, redo the resolution.
Comment: Sorry, is it $${x^2=-c/a±(1/a)root(c/a) i}$$


Printing an Entity Reference Field Value in a field collection in views-view-fields.tpl.php

Question: I am overriding my view with the template views-view-fields.tpl.php, and have called it views-view-fields--front-featured-blocks.tpl.php
I wont bother putting all of my code for this block up, but the two defining lines of my code are as follows...

  <?php print $fields['field_link_to_content']->content; ?>

  <?php print $fields['field_block_title']->content; ?>

The field_block_title span prints a value, but the field_link_to_content does not.
The field_link_to_content is an Entity Reference field, which is printing the Entity ID, which I need to build a link.
Can anyone tell me why this doesnt work, but I can print every other field in the same method? The entity reference field is only allowed one value, but is there a delta value involved? How would I print a list of allowed values? I have devel installed.
Comment: what does devel show? can u take a screen shot & upload it
Comment: @NoSssweat How do I print from Devel in a views theme template file? Where would I see the output?
Answer: I found my main answer from this question here.. Calling a field in views-view-fields--view-name.tpl.php ---- Error
My problem was excluding the display of the field. I assumed that I would want the field hidden as I wanted to show it elsewhere, but as I am overriding the views.view.fields.tpl.php anyway, I could choose to declare it or not.
As soon as I set the field to display again, I could use...
print $fields['field_link_to_content']->content;

If I had wanted to keep the field hidden, I could have used something like...
$row->field_field_my_custom_field[0]['rendered']['#markup']

Comment: oh yeah, I had that happen to me, forgot about that.


Static members vs instance members

Question: If I need to declare just some constants to use in my class, and there is no real need for declaring them as static, i.e. there will no be several instances sharing that member, is there any sense to declare them as static? Is there a "cost difference" between using static and instance members? Please give information about both java and C#.
And also, is there a difference between java's static members and C#'s static members?
Comment: As far as I'm aware of in __Java__ static variables are stored in the PermGen space while instance variables are stored on the heap (the PermGen space is a special kind of heap which contains all the loaded blueprints of classes and their methods as well as static variable definitions). Often larger application servers are confronted with this issue, but for small applications this is forgettable. For C# see [this link](http://stackoverflow.com/questions/337019/hows-memory-allocated-for-a-static-variable)
Comment: I don't know about Java, but in C#, constants are inherently static ([reference](http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/why-can-t-i-use-code-static-code-and-code-const-code-together.aspx)). This seems intuitive to me; what would be the point of having an instance-level constant?
Comment: @RomanVottner is that about java or c#?
Answer:
I need to declare just some constants to use in my class

No Idea about Java but in C# constant member's are implicitly static in nature.
See MSDN Document: Constants (C# Programming Guide) for more information. Quoting from the referred document:

Constants are accessed as if they were static fields because the value
  of the constant is the same for all instances of the type. You do not
  use the static keyword to declare them.
Comment: Constants are not implicitly static in Java
Comment: Good to know but have no idea about `Java`.
Comment: Yeah I know, I was just clarifying for the "*Not sure about Java*" - The only implicitly static members in Java are fields declared in interfaces (implicitly static final). Edit it into your answer and I'll delete my comments. I wasn't saying whether or not you knew; I was telling you so you could include it into your answer.
Comment: @VinceEmigh, No worries; feel free to edit my answer anytime(in future) if it value adds.
Answer: I generally declare every constant in my applications as a private static final variable, for a number of reasons.

Consistency. It's clear to myself and others what are the default core constant definitions are in my application. I can keep them all grouped together, and it's very easy to navigate over to them if they need to be modified. Because they're static, these changes ripple down through every call. This safegaurds you from making accidentally multiple definitions of the same constant.
Performance. If I have a constant that's never changed, there's no point in constantly allocating memory for it during a method call. It's allocated once when a reference to the class is made, and then you're done with it. There that memory remains references until all references to the class are done with.
Good practice. There's a convention in programming where dependencies of should be as highly decoupled as possible. When you declare a function or variable as static, you enforce that it must be interacted with in a static way, i.e. independently of a runtime instance. Without this dependency of a class encapsulating member variables at runtime, you can more precisely control interaction with that class, because it ensures you define precise rules on how a class can be interacted with. You find that the more constants and methods you can declare as static, the more flexible your software becomes because there's little confusion over how certain values and behaviours are supposed to be manipulated.
Exposure. Some functions or constants you define may be useful to other parts of your application. This means you can take advantage of functionality without the requirement for using a runtime instance. For example, the quadratic formula is the same everywhere, so why should it belong to a single instance at all? The same goes for constants, like the speed of light.

Personally, I always declare all functionality of my application as private static. If it makes sense for a class to use that functionality as part of it's operation, then the programmer can wrap the method call in another method and provide the appropriate member variable data. If another part of your application needs to use that static function, all you need to do is increase the visibility of the function.
Comment: In C# you may want to use `private static readonly` or `private const`
Comment: Ah, true. Alas, that's where I fail. I'd say that `const` is probably the same as `final`, but I don't know enough about the semantics to provide a precise explanation!
Answer: In Java, constants are not implicity static; constants are not an actual language specification, so constants in Java are simply variables that we refer to as constants.
In C#, constants are implicitly static. Constants are part of the language specification, and states in the documentation:

Constants are accessed as if they were static fields because the value of the constant is the same for all instances of the type. You do not use the static keyword to declare them.
Answer: if you will declare constant as static than your program will use only one memory location to store this constant value, and if you will not use static than every object will store this constant separately. As you said there are no several instances, in this case either you specify constant as static or declare it simply both will be of same cost.

Static members vs instance members


Access token ou Sessions em APIs

Question: Estou desenvolvendo um api e estou com uma dúvida sobre como manipular o usuário logado. A api e administração do usuário logado (adicionar coisas, editar perfil, fotos, etc.) está desenvolvida em Rails em um único projeto.
Como tenho uma parte muito interativa nesse projeto, e estou utilizando o React para consumir a api. Essa parte é um projeto a parte que roda em um subdomínio. Hoje estou utilizando sessões para identificar o estado do usuário. Algum problema em continuar assim? Segurança? Performance? Cache?
Ex: O usuário loga em www.dominio.com (Rails+API+Adm) e quando vai para projeto.dominio.com (Projeto separado) ele permanece logado, fazendo requisições para GET www.dominio.com/api/v1/amigos.json com resultados específicos para esse usuário. Na api eu identifico esse usuário via sessão e não por query sting e nenhum tipo de parâmetro.
Outra dúvida: Quando o usuário logar, eu poderia criar um access_token e armazenar em sessão, para que ele navegue e faça consultas com esse access_token na api? Eliminado assim que minha api tenha que consultar a sessão e consulta pelo access_token.
Em um outro projeto que estou desenvolvendo em paralelo, a api está com access_tokens, entretando só tem a api, não tenha nada além dos serviços em rest.
Comment: Gostaria de estar em casa para responder sua pergunta. Lá pelas 21h, eu respondo. Por enquanto, me diga quantos usuários simultâneos sua aplicação pretende suportar. Até mais.
Comment: Não tenho um número definido, mas seriam vários.. Eu vi que com o access token tenho mais flexibilidade para escalar, certo?
Answer: JSON Web Tokens VS Sessions
Se estivermos falando sobre escalabilidade, não é possível usar somente Sessions porque o uso de memória ou I/O que você vai precisar é gigantesco. Usando somente JWT, tanto faz ter 10, 100 ou 100 milhões de usuários, mas nem tudo é somente doce.
O modelo híbrido é, normalmente, o melhor. Você pode persistir sessions para que o estado do seu usuário seja persistido entre vários dispositivos diferentes. Enquanto isso, o uso do JWT pode te auxiliar na redução do tráfego de rede e operações de I/O. Os JWT podem ser usados também para te dar uma aplicação de Login Único, onde as credenciais do usuário só serão utilizadas no primeiro login e, depois, você utilizará tokens de autorização para renovar seus tokens normais.
Para sua aplicação ter o estado mantido, basta assinar seu JWT com alguma informação relevante ao estado do usuário. Lembre-se que o JWT pode guardar qualquer informação que você quiser no lado do cliente, com o cliente sem conseguir ler aquilo. Você pode adicionar a rota atual, o caminho que ele percorreu e persistir no database depois, pode guardar o nomeDeUsuario ou algum token aleatório usado para identificar a sessão.
Sobre tráfego de rede, conforme você vai adicionando informações ao JWT, ele vai crescendo e, com isso, cresce também o tráfego de dados. É necessário perceber que cada estratégia possui um ponto negativo, sendo o uso do processador para decodificar os tokens o negativo dos JWT. Enquanto isso, o lado negativo das sessions é o uso de I/O e RAM.
Algo importante a se notar é que o design de sua aplicação deverá perceber quando é necessário fazer uso de I/O, sessions in-memory ou JWT.

Dois exemplos de aplicações minhas que posso te dar:

1) Uma aplicação empresarial para 50~100 pessoas com pouco acesso.

Nessa aplicação, não me importei com muita coisa. As 50~100 seções estavam sempre na RAM para garantir o estado dos usuários. Uma queda de energia e 'xablau'. Enquanto isso, o login dos usuários era feito somente uma vez e, após isso, o servidor mandava um JWT somente com o username do usuário, que era utilizado para identificá-lo e salvo nos cookies. O servidor confiava no JWT criptografado e tomava o username como verdadeiro. Enquanto isso, a cada login o JWT era renovado por mais uma semana e, caso estivesse vencido, o servidor solicitava as credenciais.

2) Uma aplicação de aprendizado, um jogo escalável.

Nessa aplicação, não haviam sessões. O usuário simplesmente cria a conta, recebe seu JWT, que é armazenado no Local Storage e fica logado para sempre. Sempre que ele vai para a aplicação, sua conta é identificada e um I/O é feito para lhe criar um personagem para jogar com base nas partidas anteriores. Sempre que o jogador morre, é feito outro I/O para salvar algumas informações sobre a partida e o personagem morto.

Resumo rápido

Tokens

Padronizado pela RFC 7519.
Bastante compatível com dispositivos móveis.
Consome mais CPU, mas menos RAM
Inseguro.
Nasceu para ser pequeno e manter logado com único login.
Armazenado no cliente, processado no servidor.

Sessions

Apesar de não ser padronizado, é largamente utilizado.
Workarounds para lidar com mobile.
Consome mais RAM e I/O, mas menos CPU.
Inseguro.
Nasceu para 'manter usuário logado'.
Armazenado no servidor.

Tudo é inseguro, só deixei como um lembrete. ;)

Access token ou Sessions em APIs


Domain name points to different IPs from different locations

Question: I'm having this problem that seems odd to me. I have a domain name (www.arioo.com) which must point to the IP, 22.214.171.124. It's ok when I try to reach it from my local PC or every other network that I have physical access to.
The problem occurs when I try to ping the domain from it's own server using ssh! The domain name points to a completely different IP address.
I wonder if this is caused by DNS caching since we had a server change almost a month ago, in which case that should be odd too for taking this long to update.
Answer: Why would you have the server ping itself? Anyway, the A record looks fine to me, so try doing a dig of the domain from the server again. If it's still pointing elsewhere and you haven't set a ridiculously long TTL or updated name servers in the last couple of days, then the problem lies with what DNS servers your server is querying.
Comment: I was essentially trying to use `wget` in crontab for some php script to run periodically when I found out about this problem. So is there any way to know what DNS servers are being used?
Answer: Two options I can think of:

your resolver might give you a special "view" on the DNS database
(more details in the BIND manual: http://www.zytrax.com/books/dns/ch7/view.html)
your /etc/hosts file might have a manual entry
Answer: I'd also look at what settings you have in your /etc/nsswitch file.  This controls the order of hostname/IP lookups.  Make sure it is in the order you want them.
One other thing, try restarting (or disabling) the nscd service.  I have found that in several instances it causes the wrong result to be returned.
Take a look at the DNSen you are pointing to on your host (/etc/resolv.conf).  If you are using a broken DNS then you might be having problems.


Unix/Linux cat x y > y : is my understanding of the processing correct?

Question: I'm currently working through Kernighan and Pike's excellent book The UNIX Programming Environment. One interesting example they give (Exercise 3-7) is the command
cat x y > y

I tried running this command with the initial contents of the files being x contains xxx and y contains yyy:
The command does not complete. x remains unchanged (as you would expect) and y ends up with an large number of lines of xxx.
This is how I've rationalised the behaviour:

First thing the > redirection operator does is truncate y ready to receive the redirect data. Hence no yyy bytes end up in y.
As y is empty when the redirect process starts writing data., the output of cat x y (initially) is just xxx.
cat will not stop writing until it reaches EOF on y. But it never reaches EOF, because as each write operation completes, it pushes EOF further past the current read/write pointers? So cat keeps appending y to itself indefinitely.

If anyone could provide a more articulate (and less handwavy) explanation of this behaviour, or correct me if this is total rubbish, that would be much appreciated.
Also I'm sure at one point I found a set of worked solutions online for the problems in this textbook, but I can't find them now. If anyone could point me to such a thing, that would be great.
Many thanks,
MB
Comment: which version of `cat` are you using? gnu cat 8.21 dumps x's contents into `y`, then aborts with `cat: y: input file is output file`
Comment: you overwrote the contents of file y.
Comment: using cat 8.23. when you stated in 2nd point, y is empty, it is overwritten with contents of x, which in turn yields the message `$ cat x y > y
cat: y: input file is output file'
Comment: @Marc B - I'm using OSX cat. @Charles Duffy - I will try learning about `strace` - sounds useful :-) ... *looks into it* ... uh oh, `strace` isn't available for OSX ... I'll have to research an equivalent. Thanks for the suggestion.
Comment: See if you have `truss` or `dtruss`.
Answer: Yes, your existing understanding is correct.
To look at the actual syscalls (from strace busybox cat x y >y, to avoid the GNU version's attempts at detecting and terminating such loops):
open("x", O_RDONLY)                     = 3
read(3, "xxx\n", 4096)                  = 4
write(1, "xxx\n", 4)                    = 4
read(3, "", 4096)                       = 0
close(3)                                = 0
open("y", O_RDONLY)                     = 3
read(3, "xxx\n", 4096)                  = 4
write(1, "xxx\n", 4)                    = 4
read(3, "xxx\n", 4096)                  = 4
write(1, "xxx\n", 4)                    = 4

...and the final two lines repeat ad infinitum.
Not shown is the outer shell's open("y", O_WRONLY|O_CREAT|O_TRUNC, 0666), done after the fork() to spawn the subprocess which then exec's cat but before cat's actual execution -- and thus, before all of the above.
Thus, we see exactly what you posited: Only a single line of xxxs is available for read until cat performs a write, at which point additional content is immediately available for read, so the loop proceeds.


I get other website's tls certificate when visiting my website

Question: i have a weird issue while visiting my website using https...
I can't track how often this happens, but sometimes T get a TLS certificate of another website.... and the browser warns me that the certificate is fake. however I set the certificate using "let's encrypt" and there shouldn't be any problem with that...
I remember that it happened once before i set the TLS cert to my domain so lets encrypt its probably not the cause of the problem, but i would like to know what can cause that?
I would like your help guys! thanks ahead.
EDIT:
Here's my nginx config:
<code># Redirect www to non-www and http to https
#
server {
    server_name doctorice.co.il www.doctorice.co.il;
    return 301 https://doctorice.co.il$request_uri;
}

server {
    listen 443;
    server_name www.doctorice.co.il;
    ssl_certificate      /etc/letsencrypt/live/doctorice.co.il/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/doctorice.co.il/privkey.pem;
    return 301 https://doctorice.co.il$request_uri;
}

# The actual server configuration goes here:
#
server {
    listen       443 ssl;
    server_name  doctorice.co.il;

    ssl_certificate      /etc/letsencrypt/live/doctorice.co.il/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/doctorice.co.il/privkey.pem;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    charset utf-8;

    root   /var/www/doctorice/public;
    index index.php index.html index.htm;

    # Redirecting all requests to index.php and enabling rewrites.
    #
    location / {
        try_files $uri $uri/ @rewrites;
    }

    location @rewrites {
        rewrite ^(.*) /index.php?p=$1 last;
    }

    # Making sure enyone can access .well-known directory
    # for auto-renewal of the ssl sertificates. Do not remove!
    #
    location ~ /.well-known {
        allow all;
    }

    # Redirectiong 404's to craft cms.
    #
    error_page  404              /index.php;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # Pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
</code>
To get the cert, i cloned the "lets encrypt" repo and ran:
<code>./letsencrypt-auto certonly --standalone
</code>
And then, i just followed the instructions.
The link to the website is http://doctorice.co.il/
Comment: Post your nginx configuration, the command you used to issue the certificate, and a link to your actual website. You can edit your post to remove the link later if you're paranoid about that.
Comment: I think that i can make it happen if i shut down the server or nginx. thats how it happened the last time. the link to the website that the cert i accidentally receive is https://www.ramtours.com/.
Answer: Your certificate is for the root domain only, it doesn't include the www domain. You have a server listening for https connections on the www domain that is using a certificate that's not valid for the www domain, which causes a certificate warning. You will get a certificate warning when you go to https://www.doctorice.co.il/
The solution is to get a certificate which includes both the root domain name and the www domain name, or issue a second certificate for the www domain. I suggest one certificate with two domain names, which is easy to do with Let's Encrypt.
Note that while this is a problem, it may or may not be the root cause of the occasional problem you're seeing. Try it and report back if it happens again.
Comment: That's strange. Those domains are on different servers, different continents even. I think you need to isolate when this happens a bit more to work out a pattern. It's possibly browser related.
Comment: I know that, that is the first thing i checked when it happened. the warning said that the certificate belonged to "ramtours.com". and if i decide to proceed, it shows that website but with my domain...


In a deck of $ 18 $ when $ 6 $ cards are dealt, what is the chance for at least one of the cards to be an $ A $ card ($ 3 $ $ A $ cards in the deck)?

Question: A bit of background (can skip this), I play this card game called Coup and in this game there are $ 6 $ types of characters with the Duke being the best card at the start of the game, there are $ 3 $ Dukes in the deck of $ 18 $. I usually play with $ 2 $ others and each person gets dealt $ 2 $ cards each, so $ 6 $ cards get dealt.
In the deck of $ 18 $ cards there are $ 6 $ types of cards (for simplicity just $ A,B,C,D,E,F $), for each type of card there are $ 3 $ identical cards. I want to know the probability of when dealt $ 6 $ cards at least one has an $ A $ on it. I tried to work this out with the binomial formula however this gave a very low chance of drawing $ 4 $ $ A $ cards which is impossible because there are only $ 3 $ $ A $ cards in the deck. Did I do something wrong? And how can prevent to make this mistake in the future?
Thanks a lot!
Answer: There are ${18 \choose 6}$ ways to choose 6 cards from a deck of 18,
and ${15 \choose 6}$ ways to choose 6 cards from the 15 non-A cards.
So the chance of drawing at least one A-card is
$$1-\displaystyle\frac{{15 \choose 6}}{{18\choose 6}}.$$
Comment: @insipidintegrator $~$No, the cards are individual objects. $~$ $\rm A_1,A_2,B_1$ and $\rm A_2,A_3,B_3$ are two distinct outcomes in the event "two A and one B".
Comment: I don't agree. Some cards are identical. So picking A1,A2,B1 is same as A2, A3,B3.


How do I upgrade from oVirt 4.2 to oVirt 4.3?

Question: I have a oVirt 4.2 datacenter. I like to upgrade to 4.3. What steps are necessary and where do I get documentation. The oVirt documentation is sparse on this matter to say the least.
Answer: To answer my own question:
There is good documentation available from Redhat for RHEV 4.3.

upgrade guide
maintenance guide

Don't use any Redhat repos. Stay with the release notes of oVirt and use their repos only, which are CentOS based.
If anything in this answer is unclear to you: RTFM until clearing up happens.
I recommend waiting for 4.3.4 to arrive, since 4.3.3 is still a little bit rough on the edges.
This guide is for oVirt Node NG based installations. If you rolled out your own nodes this guide may be working as well, but I don't know. Have backups of your engine. REALLY!
I did:
1.
Check of all nodes are using firewalld. You have to switch all nodes to use firewalld,
because Iptables is deprecated and removed in 4.3 as it was said in documentation. You
have to re-install every node for that. So every node has to go through maintenance.
2.
Upgrade the engine. First to the 4.2.8 then to 4.3.x
My upgrade flow for this is:
<code>Engine Update START

Minor Upgrades first

enable global maintenance mode

login to engine
engine-upgrade-check
yum update "ovirt-*-setup*"
engine-setup [The questions come with sane defaults from your current installation]
yum update
when success: disable global maintenance mode

Major Upgrade

enable global maintenance mode

login to engine
yum install http://resources.ovirt.org/pub/yum-repo/ovirt-release[releasenumber].rpm
engine-upgrade-check
yum update "ovirt-*-setup*"
engine-setup [Same questions like above, but also for new features]
remove the old ovirt release from /etc/yum.repos.d
yum update
when success: disable global maintenance mode

Engine Upgrade END
</code>
3.
Upgrade the nodes.
First to 4.2.8 then as specified in ovirt release info:
<code>  # yum install https://resources.ovirt.org/pub/ovirt-4.3/rpm/el7/noarch/ovirt-node-ng-image-update-4.3.3-1.el7.noarch.rpm
  # reboot
</code>
4.
Upgrade the Datacenter Compatibility to 4.3
This includes rebooting all VMs at one point. You can read about it in the documentation.
Then you're done.


nginx restart fails: [emerg] directive "pagespeed" is not terminated by ";" in /etc/nginx/vhosts.d/name.d/pagespeed.conf:14 nginx

Question: attempted to restart nginx to get this:
<code>[emerg] directive "pagespeed" is not terminated by ";" in /etc/nginx/vhosts.d/appname.d/pagespeed.conf:14
nginx.
</code>
pagespeed.conf:
<code>pagespeed Domain domain.com
pagespeed Domain www.domain.com
pagespeed Domain d3r58zp8b5siia.cloudfront.net
pagespeed MapRewriteDomain d3r58zp8b5siia.cloudfront.net domain.com
# pagespeed Domain http://example.com;
# pagespeed Domain http://cdn.example.com;

#pagespeed MapRewriteDomain d1v88ngz0mzdwa.cloudfront.net cdn.example.com;

pagespeed EnableFilters add_head, combine_css, combine_javascript, convert_meta_tags, extend_cache, fallback_rewrite_css_urls, flatten_css_imports, inline_css, inline_import_to_link, inline_javascript, rewrite_css, rewrite_images, rewrite_javascript, rewrite_style_attributes_with_url

# Ensure requests for pagespeed optimized resources go to the pagespeed
# handler and no extraneous headers get set.
location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" { add_header "" ""; }
location ~ "^/ngx_pagespeed_static/" { }
location ~ "^/ngx_pagespeed_beacon$" { }
location /ngx_pagespeed_statistics { deny all; }
location /ngx_pagespeed_global_statistics { deny all; }
location /ngx_pagespeed_message { deny all; }
location /pagespeed_console { deny all; }
</code>
Comment: This question was caused by an **obvious typographical error**. While similar questions may be on-topic here, this one was resolved in a manner which is unlikely to be useful to future readers. This can often be avoided by carefully inspecting error messages, configuration samples and relevant documentation.
Answer: All of your pagespeed config entries need ';' at the end.
Comment: thansk. one fixed, now another issue: [emerg] open() "/opt/sp/nginx/logs/static.log" failed (2: No such file or directory)
Comment: Are you sure the file is there? Is it accessible by the user you're running nginx with?


Calculating the information contained in a message

Question: Lets say i want to calculate the information content of a particular message.What apart from the message itself has to be taken into account in doing so, and what data would i need to collect to perform my action?
Answer: Using notions like entropy (like in Ashok's answer) only work if you believe the message is coming from a specific distribution. If all you have a single message, then the only measure of complexity that's meaningful is the Kolmogorov complexity of the message, which is sadly uncomputable.
Comment: Suresh is right -- in classical information theory, the information content of a single message isn't defined. You can only measure information content for some ensemble (distribution) of signals.
Answer: May be, one needs to estimate the frequency $p(m)$ of occurrence of the message $m$. Then $\log \frac{1}{p(m)}$ is the information content of the message $m$.
Comment: This is a nice answer.  The quantity $h(m) = \log 1/p(m)$ can be conceived as the "surprise" of seeing message $m$ (it's a decreasing function of the probability of encountering message $m$ -- if we always observe this message then $p(m)=1$ and surprise $h=0$.).  This quantity averaged over the distribution of all messages $p(m)$ is the Shannon entropy.  So the surprise of seeing $m$ is the contribution of that message to the total entropy, but it's not really an "information" in the classical sense.


What might be wrong in this php code?

Question: This code when opened in the browser, displays "Reply button not pressed!" at first when the page loads, and After text is entered and Post button is pressed, The text isn't inserted into the database:
Here's the code:

<title>Some Title</title>

<form action="#reply" method='post'>
    <input type="submit" class="button" value="Post">
</form>

Reply to this Topic

What would you think about this?

    <form name="pform" method="post" action="">

        <textarea name="text" placeholder="Enter your thoughtful response here!" cols="50" rows="20"></textarea>

        <input type="submit" name="reply" class="tbutton" value="Reply"/>

    </form>

    x

<?php
$id=$_GET['id']; //id fetched from the URL
if(isset($_POST['reply']) && !empty($_POST['reply']))
{
    $conn=new mysqli('localhost','root','','forum') or die(mysql_error());
    if(!strlen(trim($_POST['text']))>0)
    {
        echo "Reply!";
    }
    else
    {
        $stmt= $conn->prepare("INSERT into messages(id,text) VALUES(?,?)");
        $stmt->bind_param('is',$id1,$text);
        if(isset($_POST['text'])){ $tag = $_POST['text']; }
        $id1=$id;
        $stmt->execute();
        $stmt->close();
        $conn->close();
    }
    header("Location: forum.php");
    }
    else{
        echo"Reply button Not pressed!";
}
?>

What might be wrong in this php code?
Database details:

Database Name: forum
Table name: messages

columns-

id (foreign key referring to topicID in a different table)
time (Default being set to CURRENT_TIMESTAMP)
text

PS: I'm new to php. So help is really appreciated
Comment: `mysql_error()` will not work with the MySQLi API.
Comment: Try this if(isset($_POST['reply']) && $_POST['reply'] != "")
Comment: First in your code $id will not get from form as you are not passing it in GET request.
Comment: You've a lot of syntax errors here and not bothering to check for errors anywhere.
Comment: I think it's that not all browsers send the values associated with "submit" inputs
Answer: I believe the error is in this line:
if(isset($_POST['text'])){ $tag = $_POST['text']; }

it should be
if(isset($_POST['text'])){ $text = $_POST['text']; }

instead, since you require the parameter $text and not $tag.
I would also set this line
$stmt->bind_param('is',$id1,$text);

after this line:
$id1=$id;

Answer: I think your ID will be a text string and not an integer so the bind_param() function will fail. Try casting the id as an integer.
$id=$_GET['id']; //id fetched from the URL
$id = (int) $id;

Comment: You are correct but I was just being modest. I've edited my answer.
Answer: My guess is your redirect command (header("Location: forum.php");), It's in the wrong place there
Comment: That's just the tip of the iceberg.
Comment: Please do not guess.

What might be wrong in this php code?


How to confirm that LDAP SSL patches are working

Question: We have applied the LDAP SSL Security Elevation patches on our domain controller, and have set the LdapEnforceChannelBinding entry to 2 (to force a hard fail for insecure connections), but all of my attempts have been successful, leading me to believe that either the patch isn't properly applied, or the registry setting hasn't been made to the right place.
Can someone provide a script or program that we can point to our LDAP server that can definitively say whether or not this mitigation is in place and working?
Note: I posted this to Stack Overflow after seeing a similar post there about LDAP, but then I thought about it for a bit and determined that Server Fault would be a better place for this question.
Comment: `but all of my attempts have been successful, leading me to believe that either the patch isn't properly applied, or the registry setting hasn't been made to the right place.` Why is that? Are you able to perform a simple bind using basic authentication on tcp/389?
Comment: We have two places where it needs to work for our customers, one within a Delphi application that uses a Jedi code library that looks like it's connecting on tcp/389, and a second on a web page that uses a library from IP*Works that I *think* is also connecting on tcp/389.  Both of these work, with the mitigations in place.  However, we have tools we've used in the past to validate our LDAP connections (LDAP Search from SecurityXploded.com and LDAP Browser from Softerra) but I can't get either of them to connect.
Answer: If you cannot connect using LDAP Browser that is a good sign.
https://techcommunity.microsoft.com/t5/core-infrastructure-and-security/ldap-channel-binding-and-ldap-signing-requirements-march-update/ba-p/921536
If a basic auth on tcp/389 is attempted and is rejected, an event Id 2888 event will be recorded in the Directory Services event log every 24 hours to summarize. So your LDAP Browser failed attempts should be logged there.
Probably a good idea to get more information about the apps though.  I would not assume it is using basic auth.
Comment: So, I searched the Domain Server's Event Viewer for event 2888, but found nothing.
I reduced the `LdapEnforceChannelBinding` to 0 and tried connecting again with the LDAP Browser from Softerra and still can't connect (Error 91).

I don't have a lot of experience with LDAP/AD, but I'll start with the LDAP Browser, getting it to connect, and will continue troubleshooting *after* I have succeeded, because LDAP Browser should give me the information I need to be certain that things are or aren't working correctly.
Comment: I upgraded to LDAP Browser 4.5 (I was using 2.5), and installed it on our web server (not the Domain Server), and was able to connect successfully, but could not from my local workstation.  While I would like to be able to do all testing from the workstation, the fact that I can connect successfully from the web server means I can continue my testing.  Thank you for the help, and I'll reply back with my progress.
Comment: OK, I changed the `LdapEnforceChannelBinding` entry to 2 again, and the LDAP Browser on my web server could still connect, using port 389, and Simple credentials.  That has to mean that the mitigation isn't correctly installed on the LDAP server, yes?
Comment: @Dan: seems that way


Convergence of series $\sum_{n=2}^\infty \frac{\ln (\ln n)}{\ln n}$

Question: How do I test the following series for convergence?
$$\sum_{n=2}^\infty \frac{\ln (\ln n)}{\ln n}$$
I tried to use the integral test, but I don't think this has an elementary antiderivative. What else could I do to solve this question?
Comment: Compare to $\sum\frac{1}{\ln n}$ which diverges
Answer: If you want to use the integral test, $\frac{\ln (\ln n)}{\ln n}$ may not have an elementary antiderivative but
$$ \frac{\ln (\ln n)}{\ln n} > \frac{\ln (\ln n)}{n(\ln n)}$$
does have an antiderivative.
For a comparison test, notice that
$$ \ln (\ln n) > \frac{\ln n}{n}$$
for $n \geq 5$. Then divide and say that the series you have is bigger than $\frac{1}{n}$.
Comment: You have an ln too much in the numerator after the first >
Comment: @Milten could you explain? I don't see what you are referring to.
Comment: I'm sorry, didn't you want to use $\ln(\ln n)>\frac{\ln n}{n}$, giving $\frac{\ln(\ln n)}{\ln n}>\frac{\ln n}{n\ln n} = \frac 1n$? Maybe I misunderstood...
Comment: @Milten Ah no, right now I have exactly what I want because $\int \frac{\ln(\ln x)}{x\ln x}dx = \frac{1}{2}(\ln(\ln x))^2$. I have edited the post to make it clear that I am talking about two different approaches.
Comment: Oh, I didn't realise you were integrating! Sorry. My bad.
Answer: By comparison test, show that $$\sum_{n=2}^\infty \frac{\ln(\ln(e^e))}{\ln(n)}\le \sum_{n=2}^\infty \frac{\ln(\ln(n))}{\ln(n)}$$
for every $n\ge 16$.
Comment: Very nice trick!
Answer: HINT
By Cauchy condensation test we have
$$\sum_{n=2}^\infty 2^na_{2^n}= \sum_{n=2}^\infty \frac{2^n\ln (\ln (2^n)}{\ln (2^n)}=\sum_{n=2}^\infty \frac{2^n\ln (n\ln 2)}{n\ln 2}$$
As an alternative by limit comparison test with $\sum \frac 1n$
$$\frac{\frac{\ln (\ln (n)}{\ln (n)}}{\frac1n}=\frac{n\ln (\ln (n)}{\ln (n)}\to \infty$$
Comment: Should it say $2^na_{2^n}$ in the first sum?
Comment: @Milten Yes of course! Thanks
Answer: Hint For $n\geq  9$ we have
$$\frac{\ln( \ln(n))}{\ln(n)} \geq \frac{\ln(\ln(e^2))}{\ln(n)} \geq \frac{\ln(2)}{\ln(n)} \geq \frac{\ln(2)}{n}$$
Comment: If I use the integral test on ln(2)/n, should I integrate from 9 to infinity?
Comment: @AakashJajoo Yes... Anyhow, you probably already know that the harmonic series diverges....


How to list Category - Subcategory in navigation menu in Laravel

Question: How to list Category - Subcategory in the navigation menu in Laravel?
I have a query like this below.
id  Title    parent_id
1   cat1     1
2   cat2     1
3   cat3     2
4   cat4     3

Answer: add these functions to your model
public function children()
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}

public function parent()
{
    return $this->belongsTo(Category::class, 'parent_id', 'id');
}

Then in your view:
@foreach ($categories as $category)

   @if($category->parent_id == 0)

      @include('categories.view', $category)

    @endif
@endforeach

And the is content of categories.view.blade file

id}}" data-jstree='{"icon":"fa {{$category->icon}}"}'>

  {{ $category->name }}

  @if ($category->children()->count() > 0)

      @foreach($category->children as $category)
         @include('categories.view', $category)
     @endforeach

  @endif


How to run a shapiro test with a subset of data defined by more than 2 variables

Question: I have a data frame with structure:
str(Ehen)
'data.frame':   412 obs. of  5 variables:
 $ DATE      : Date, format: "2012-09-11" "2012-09-19" ...
 $ Population: Factor w/ 9 levels "Brathay","Clun",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ Fish      : Factor w/ 3 levels "C","S","T": 2 2 2 2 2 2 2 2 2 2 ...
 $ Length    : int  NA 70 70 80 70 60 70 60 60 70 ...
 $ Width     : int  NA 60 50 70 60 50 60 50 50 60 ...

I want to test is Length is normally distributed for each population, subgrouping the data by date and fish.
I have tried:
aggregate(Ehen$Length ~ Ehen$Fish + Ehen$DATE, FUN =shapiro.test)

  Ehen$Fish  Ehen$DATE Ehen$Length
1          C 2012-09-19   0.7975819
2          S 2012-09-19   0.8164554
3          S 2012-09-25   0.7935195
4          S 2012-10-04   0.9006435
5          C 2012-10-09   0.8411583
6          S 2012-10-09    0.913051
7          S 2012-10-11   0.8525953
8          C 2012-10-18   0.9084524
9          S 2012-10-18   0.9415459
10         C 2012-10-24   0.9592422
11         S 2012-10-24   0.9774688
12         C 2012-11-02   0.9536037
13         S 2012-11-02   0.9607917
14         C 2012-11-12   0.9570341
15         S 2012-11-12   0.9728865

This is more or less what I am looking for, but, how would I get p-values for the Shapiro test instead of W value?
I could go date by date with:
shapiro.test(Ehen$Length[Ehen$DATE=="2012-10-24"])
data:  Ehen$Length[Ehen$DATE == "2012-10-24"]
W = 0.9761, p-value = 0.2868

But it is not adequate... SO I tried:
lapply(split(Ehen$Length, Ehen$Fish, drop = TRUE),shapiro.test)

$C
        Shapiro-Wilk normality test

data:  X[[1L]]
W = 0.9219, p-value = 1.548e-07

$S
        Shapiro-Wilk normality test

data:  X[[2L]]
W = 0.9201, p-value = 2.056e-10

But, I do not know how to include the Date as a variable to subset the data in the test.
I might be wrong all the wayalong, or I might be close to the answer!! Thank you in advance
Answer: You could try
res <- aggregate(cbind(P.value=Length) ~ Fish + DATE, Ehen,
             FUN = function(x) shapiro.test(x)$p.value)

head(res,3)
#  Fish       DATE    P.value
#1    C 2012-09-19 0.25510132 #####
#2    S 2012-09-19 0.11941675
#3    C 2012-09-20 0.04459457

shapiro.test(Ehen$Length[Ehen$DATE=='2012-09-19' & Ehen$Fish=='C'])

#   Shapiro-Wilk normality test

#data:  Ehen$Length[Ehen$DATE == "2012-09-19" & Ehen$Fish == "C"]
# W = 0.9414, p-value = 0.2551 ######

data
set.seed(25)
Ehen <- data.frame(DATE= sample(seq(as.Date('2012-09-19'), length.out=10,
   by='1 day'), 412, replace=TRUE), Fish= sample(c("C", "S"), 412,
   replace=TRUE), Length=sample(c(NA,60:80), 412,replace=TRUE))


asp.net core appears to freeze when debugging application

Question: Has anyone seen the issue when debugging an Asp.Net 5 (core) application where the application seems to just go to sleep. Selecting another function/page in the browser just says "Waiting for LocalHost" (as I am running it locally on IIS Express).
We have a staged version of the Asp.Net app and it has no such problem. It runs wonderfully, but in Debug mode, it can have serious delay issues in executing code. Nothing is reported in the output window, during the time it appears to be doing nothing. Nothing on the Diagnostic tools windows either
A lot of the time - it will ultimately come back if you let it do its thing. But sometimes it can take up to 15-30 seconds.
The issue seems to become more prevalent when you change the Razor or javascript client files while the app is running?
Soemtimes pressing F5 on the web page makes it get out of its sleep mode (but not always, and it seems the more times you do this it, the slower it gets). Is it perhaps rebuilding the page that changed? but why the delay?
Again this works fine in Staging or Production (as none of the back end client side files would be changing). But it can be very annoying
Any ideas?
Comment: Had a similar problem I resolved by installing VS 2015 Update 2 and the web tool extension update.
Answer: So I found I didn't have the web tool extensions even installed - and after I installed it - the Freeze disappeared, but a colleague of mine still has the problem (as he already had the extension loaded and there is no way to uninstall it once its loaded
Answer: For me it was my Anti Virus. As soon as I disable AVG all requests get immediately run by the debugger.