Distribution for first time when the value is less than the previous one

Question: Let $X_i, i \geq 1,$ be independent uniform (0, 1) random variables, and define $N$ by $$N=\min\{n:X_n < X_{n-1}\}$$. I need to prove that $$P\{N \geq k | X_0=x\} = \frac{(1-x)^{k-1}}{(k-1)!}$$. I am stuck when finding the quantities like $P(X_i \geq X_{i-1} | X_{j} \geq X_{j-1}, \forall j\lt i)$. I have also posted this in math exchange, but not convinced with the answer posted there.
Another question is how to calculate $E[N]$ using conditioning on $X_1$.
Comment: @Prasenjit That's not the way to proceed. You should first leave comment on the site where you posted your question (ask for further clarification, or point toward possible misinterpretation or error in current replies), and if you think stats.SE would be a better fit ask a moderator to coordinate migration for you. I've informed math.SE moderators of the situation; let's wait for their feedback.
Comment: [Cross-posting](http://meta.stackexchange.com/q/64068/150510) on multiple Stack Exchange sites is not recommended. (It appears that you also cross-posted several questions on MathOverflow and math.SE.) I will close this question as a [duplicate](http://math.stackexchange.com/q/321615/26851) then. For future reference, you can ask math.SE moderators to migrate your questions for you.
Comment: From your expression, $N\mid X_0=x$ does not have a geometric distribution. Compare: http://en.wikipedia.org/wiki/Geometric_distribution
Comment: I got some "wrong" answers in math exchange. Thats why I posted here.
Answer: You know that $X_0=x_0$ with probability 1, for $0<x_0<1$, and you have a sequence $\{X_i\}_{i\geq 1}$ of independent $\mathrm{U}[0,1]$ random variables. Let $N$ be the first time the sequence decreases, which means
$$
N=\min\,\{n\geq 1:X_{n-1}>X_n\} \, .
$$
The key point is that $N\geq k$ if and only if $X_{k-1}\geq X_{k-2}\geq \dots \geq X_1\geq X_0$. Convince yourself checking both implications.
The joint density of $X_1,\dots,X_{k-1}$ is just
$$
  f_{X_1,\dots,X_{k-1}}(x_1,\dots,x_{k-1}) = \prod_{i=1}^{k-1} f_{X_i}(x_i) = \prod_{i=1}^{k-1} I_{[0,1]}(x_i) \, .
$$
Hence,
$$
  P(N\geq k\mid X_0=x_0)=P(X_{k-1}\geq X_{k-2}\geq \dots \geq X_1\geq x_0)
$$
$$
= \int_{x_0}^1 \int_{x_1}^1 \dots \int_{x_{k-2}}^1 f_{X_1,\dots,X_{k-1}}(x_1,\dots,x_{k-1}) \, dx_{k-1} \dots dx_2\,dx_1
$$
$$
  = \int_{x_0}^1 \int_{x_1}^1 \dots \int_{x_{k-2}}^1 dx_{k-1} \dots dx_2\,dx_1 = \frac{(1-x_0)^{k-1}}{(k-1)!} \, .
$$
(Note that, contradicting the original title of the question, $N\mid X_0=x_0$ is not a geometric random variable.)
Since $N$ is a nonnegative random variable, using this result, we have
$$
  \mathrm{E}[N\mid X_0=x_0] = \sum_{k=1}^\infty P(N\geq k\mid X_0=x_0)
$$
$$
= \sum_{k=1}^\infty \frac{(1-x_0)^{k-1}}{(k-1)!} = \sum_{i=0}^\infty \frac{(1-x_0)^i}{i!} =e^{1-x_0} \, .
$$
It follows that $\mathrm{E}[N\mid X_0] = e^{1-X_0}$ almost surely. If $X_0$ has density $f_{X_0}$, we can use the tower property to compute
$$
  \mathrm{E}[N] = \mathrm{E}[\mathrm{E}[N\mid X_0]] = \int_0^1 e^{1-x_0} f_{X_0}(x_0)\,dx_0 \, .
$$
For example, if $X_0\sim\mathrm{U}[0,1]$, then $\mathrm{E}[N] = e-1$.
Comment: Thanks for the answer. How to calculate $E[N]$ without using probability distribution for $N$ and using conditioning on $x_1$
Comment: Why are you conditioning on $X_0$ ? $X_0 = x$ with probability 1. I was asking for $X_1$
Comment: I can see from the answer that $f'(x)=-f(x)$ if we assume that $f(x)=E[N|X_0=x]$. So, I want to express $f(x)$ i.e.  $E[N | X_0=x]$ using conditional expectation with respect to $X_1$ and then differentiate both sides to get $f'(x)=-f(x)$
Comment: Sorry for my poor english. I did not mean like that.
Comment: OK, no problem.


Are normal subgroups of finite index in an absolute Galois groups open?

Question: Let $G$ be a profinite group. It is known that open normal subgroups of $G$ have finite index, but in general not every normal subgroup of finite index is open (see https://ncatlab.org/nlab/show/profinite+group#examples for a counterexample). This last fact is true if the profinite group is (topologically) finitely generated (this is a theorem of Nikolov–Segal).
Let now $K$ be a field. A theorem about the "inverse Galois problem" states that for every profinite group $G$ there are fields $K\subseteq L\subseteq F$ such that $Gal(F/L)\cong G$. This means that also for general Galois groups, it is not true that every normal subgroup of finite index is open.
My question is: could this be always true for absolute Galois groups, i.e. for Galois groups of extensions $\bar{K}/K$ with $K$ field and $\bar{K}$ the separable closure of $K$?
My question is justified by a sentence I found in Silverman's book "The Arithmetic of Elliptic Curves" where, at the beginning of the appendix B.2, it is written
"Let $G_{\bar{K}/K}$ be the Galois group of $\bar{K}/K$. (...) Thus $G_{\bar{K}/K}$ is a profinite group, i.e. an inverse limit of finite groups. As such, it comes equipped with a topology in which a basis of open sets around the identity consists of the collection of normal subgroups having finite index in $G_{\bar{K}/K}$".
Comment: I think $\mathbb{Q}$ is a counterexample: https://mathoverflow.net/a/82178/159786
Comment: Thankyou for the hint to look at Milne notes. Indeed, I was very confused by Silvermann's sentence: I know that any group can be endowed with a topology such that a base of open neighborhoods of the identity  is made by open normal subgroups, but it doesn't seem the more natural topology in this setting. Another confusing issue is that Silvermann really uses his definition, when after a few lines he says that the action of the Galois group on a module is continous if and only if the stabilizers have *finite index*, whereas we usually have to require that they are open.
Comment: But it's true for finite fields: https://math.stackexchange.com/q/1013555/688699
Comment: I'm confused with Silverman since *any* group can be equipped with the profinite topology defined the same way. Maybe the issue is that he's just working with this topology on the absolute Galois group instead of the Krull topology. See the last paragraph on page 7 of these notes: https://math.mit.edu/classes/18.785/2015fa/LectureNotes23.pdf
Comment: Actually after looking at those MIT notes (Thm 23.22), I think Silverman means the Krull topology but has just characterized it wrongly.
Comment: Edit: I mean, I know that any group can be endowed with a topology such that a base of open neighborhoods of the identity is made by normal subgroups of finite index.
Answer: The paragraph you cited from Silverman is referring to the following fact: In a profinite group, the collection of open normal subgroups form a base of neighborhoods of the identity. (Lemma 1-17, p.29 in Fourier Analysis on Number Fields).
Here on a Galois group, Silverman considers the Krull topology. Concerning the stabilizer, I think he should require the stabilizer to be open rather than just of finite index.


PDO database connection whitespace throws error!

Question: Ok so I am one for spacing out my code, I find it easier to read, edit and understand. The current way to connect to mysql with PDO is as follows on php.net;
<code>$dbc=new PDO('mysql:host=localhost;dbname='table', 'root', 'password');
</code>
I like my eligibilty so I edited like this adding whitespace;
<code>$dbc = new PDO('mysql:host = localhost; dbname = 'table', 'root', 'password');
</code>
Doing so throws an error, it is not so much as a problem as it doesn't concern me that much at all, but I thought php does not consider whitespace? So why the error?
Answer: PDO DSN syntax doesn't allow to add spaces in any place you want.
This syntax has nothing to do with regular php syntax rules, just because it is a string with DSN and not php.


DirectWrite - Unable to use several system fonts like "Script"

Question: Using the RAD Studio XE7 compiler, I'm trying to draw a text using DirectWrite and the provided VCL TDirect2DCanvas.
The text drawing works well as long as I use the fonts belonging to the Segoe family. However, DirectWrite seems unable to use several fonts like the Script font, and fallback to another font instead when I try to use them.
When I try to use the GDI to draw the exact same text, the Script font is well used. I cannot figure out what I'm doing wrong. Can someone explain to me how to use fonts such the Script font with DirectWrite?
Here is the code I currently use to draw a text with DirectWrite:
<code>void __fastcall TMainForm::btDirectWriteClick(TObject *Sender)
{
    const std::wstring text = L"Test        ";

    HDC hDC = ::GetDC(Handle);

    std::auto_ptr<TCanvas> pGDICanvas(new TCanvas());
    pGDICanvas->Handle = hDC;

    pGDICanvas->Brush->Color = clWhite;
    pGDICanvas->Brush->Style = bsSolid;
    pGDICanvas->FillRect(TRect(0, 0, ClientWidth, ClientHeight));

    ::D2D1_RECT_F textRect;
    textRect.left   = 10;
    textRect.top    = 10;
    textRect.right  = ClientWidth  - 10;
    textRect.bottom = ClientHeight - 10;

    std::unique_ptr<TDirect2DCanvas> pCanvas(new TDirect2DCanvas(hDC, TRect(0, 0, ClientWidth, ClientHeight)));

    // configure Direct2D font
    pCanvas->Font->Size        = 40;
    //pCanvas->Font->Name        = L"Segoe Script"; // this works...
    pCanvas->Font->Name        = L"Script";         // ... but this not!
    pCanvas->Font->Orientation = 0;
    pCanvas->Font->Pitch       = System::Uitypes::TFontPitch::fpVariable;
    pCanvas->Font->Style       = TFontStyles();

    // get DirectWrite text format object
    _di_IDWriteTextFormat pFormat = pCanvas->Font->Handle;

    // found it?
    if (!pFormat)
        return;

    pCanvas->RenderTarget->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE);

    ::D2D1_COLOR_F color;
    color.r = 0.0f;
    color.g = 0.0f;
    color.b = 0.0f;
    color.a = 1.0f;

    ::ID2D1SolidColorBrush* pBrush = NULL;

    // create solid color brush, use pen color if rect is completely filled with outline
    pCanvas->RenderTarget->CreateSolidColorBrush(color, &pBrush);

    // found it?
    if (!pBrush)
        return;

    // set horiz alignment
    pFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);

    // set vert alignment
    pFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);

    // set reading direction
    pFormat->SetReadingDirection(DWRITE_READING_DIRECTION_LEFT_TO_RIGHT);

    // set word wrapping mode
    pFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);

    IDWriteInlineObject* pInlineObject = NULL;

    ::DWRITE_TRIMMING trimming;
    trimming.delimiter      = 0;
    trimming.delimiterCount = 0;
    trimming.granularity    = DWRITE_TRIMMING_GRANULARITY_NONE;

    // set text trimming
    pFormat->SetTrimming(&trimming, pInlineObject);

    pCanvas->BeginDraw();

    pCanvas->RenderTarget->DrawText(text.c_str(), text.length(), pFormat, textRect, pBrush);

    pCanvas->EndDraw();
}
</code>
As an extra question, I'm also highly interested to use custom fonts like Font-Awesome 5 (https://fontawesome.com/) in my apps. How can I use them to draw a text with DirectWrite?
Comment: Doesn't work how?
Answer: If you mean font called "Script Standard" in Windows 10, as far as I can tell its file is script.fon. Bitmap fonts of that kind are not support in DirectWrite, you can tell by enumerating system font collection, this font won't be there.
Regarding custom fonts, there is a how-to on msdn https://learn.microsoft.com/en-us/windows/desktop/directwrite/custom-font-collections.


My python program doesn't quit, keeps running loop

Question: I'm writing a short program where users pick otions, I wrote a function (Yes/No) for the user to pick wether to return to home or quit program, when the user picks "No", the program is supposed to display a goodbye! message and quit but the loop seems to display the goodbye message but still prompting the user if they want to quit or not.
This is my function
def exit_home():
    while True:
            user = input("home or exit? (Yes/No)").lower()
            if user == "yes":
                main()
            elif choice == "no":
                print(quit)
                quit()
                print("Bye! ")
                continue
            else:
                break
                print("enter a valid input (Yes or No)")

And I get the result below
home or exit? (Yes/No)no
<IPython.core.autocall.ZMQExitAutocall object at 0x7fa9c096df10>
Bye!

home or exit? (Yes/No)

Also if there's a neater way of let user exit the program without printing the <IPython.core blah blah blah> I would appreciate the sugesstion.
Thanks
Comment: Because that is how you coded it.  You have `continue` and `break` the wrong way around.  Moreover this has a code-smell about it.  Where is `exit_home()` called from?  Recursion is not iteration, and it looks likely that you are recursively calling `main()` which is a really bad idea.
Comment: you're using `user` as the parameter but you've got `elif choice == 'no'`...
Comment: You must have overridden *quit()* otherwise your program would have terminated and hence 'Bye!' would never have been emitted. What do you think a call to *print()* is going to do after *break*?
Answer: There are several issues in your code:

Remove print(quit) to get rid of
<IPython.core.autocall.ZMQExitAutocall object at 0x7fa9c096df10>
Use return to break the loop instead of continue
print after break doesn't make sense because print will never be executed
break doesn't make sense because it breaks the loop, but you want to get into another interation

Corrected code:
while True:
    action = input("home or exit? (Yes/No) ").lower()
    if action == "yes":
        print("call main function...")
    elif action == "no":
        print("Bye! ")
        break
    else:
        print("enter a valid input (Yes or No)")

Sample output:
home or exit? (Yes/No) yes
call main function...
home or exit? (Yes/No) maybe
enter a valid input (Yes or No)
home or exit? (Yes/No) no
Bye!

Answer: <IPython.core.autocall.ZMQExitAutocall object at 0x7fa9c096df10> was shown because you printed out the function.
Just this should work.
import sys

elif choice == "no":
     print("Bye! ")
     sys.exit()


Error passing values from function to a controller as an object

Question: I have the following code:
<code>        $storedToken = getStoredToken();

        /**
         * Verify if the stored token has expired.
         */
        if ($storedToken->hasExpired()) {

            /**
             * If the stored token has expired, then you request a new one.
             */
            $newToken = $provider->getAccessToken('refresh_token', [
                'refresh_token' => $storedToken->getRefreshToken()
</code>
In my db I have the following fields:

token
refreshtoken
expires

I tried:
<code>public function StoredToken(){
    $user = Auth::user(); //data is on users table.
    return $refreshtoken = $user->melirefreshtoken; //eg.

}
</code>
But with no success. I cannot find the way to create a function to create an object passing all the information.
Right now I received error:

Call to undefined function App\Http\Controllers\getStoredToken()

any help appreciated.
Comment: Could you provide any error code or ar better explanation about where your problem is? You say that "I cannot find the way to create a function to create an object passing all the information"... where? If you need help describing the problem, check this guide: [ask]
Answer: The root of the problem seems to be this line:
<code>$storedToken = getStoredToken();
//             ^^^^^^^^^^^^^^^^^
</code>
If you are trying to call a function from another function (from the same class).. add this:
<code>$storedToken = $this->getStoredToken();
//             ^^^^^^^
</code>


How do I attach a file to a file field when saving (update/insert) a node?

Question: After creating programmatically a PDF file with TCPDF, I am trying to attach it to my field "file_fichier", here is what my code looks like
/**
 * Implements hook_node_presave().
 */
function hook_node_presave($node) {

  if($node->type=='profil'){

    $uri = 'public://profiles/fichier';
    $filename = $node->title.' - PDF - '.$node->language.'.pdf';
    $file_path = $uri . '/' . $filename;

    // Output PDF with TCPDF
    $pdf->Output($file_path, 'F');

    $file = new stdClass;
    $file->uid = $node->uid;
    $file->filename = pathinfo($file_path, PATHINFO_BASENAME);
    $file->uri = $file_path;
    $file->filemime = file_get_mimetype($file_path);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    dpm($file);

    // Now attach file to the file field.
    $node->field_fichier[$node->language][] = (array) $file;

  }

}

The PDF file is well saved to public://profiles/fichier/file_name.pdf as expected, and it's also recorded to the 'file_managed' table.
But the problem is that it's not attached to the field field_fichier, and nothing seems to happen to the field_data_field_fichier table
Comment: do you solve your problem?
Comment: @AdrianCidAlmaguer, I finally avoided to link the pdf with my node field. I simply saved it during node add/edit process into a specific directory. Then I loaded it directly into theme file. I checked your solution but didn't find the time to test it. I think my $file object had already an fid after file_save() was triggered.
Comment: If you post your solution is better for other users that can have in the future the same problem, and you can check your answer as accepted.
Answer: I think that you don't have the fid.
/**
 * Implements hook_node_presave().
 */
function hook_node_presave($node) {

  if($node->type=='profil'){

    $uri = 'public://profiles/fichier';
    $filename = $node->title.' - PDF - '.$node->language.'.pdf';
    $file_path = $uri . '/' . $filename;

    // Output PDF with TCPDF
    $pdf->Output($file_path, 'F');

    $file_temp = file_get_contents($file_path);

    // Saves a file to the specified destination and creates a database entry.
    $file_temp = file_save_data($file_temp, $file_path, FILE_EXISTS_RENAME);

   $node->field_fichier = array(
     'und' => array(
       0 => array(
        'fid' => $file_temp->fid,
        'filename' => $file_temp->filename,
        'filemime' => $file_temp->filemime,
        'uid' => $node->uid;,
        'uri' => $file_temp->uri,
        'status' => 1,
        'display' => 1
    )
  )
);


Html elements hides on script execution

Question: I'm working on solution to find prime numbers and everything is ok except one issue. It stops on i == 373 && j == 15 in web worker file. My Html page disapears and execution can be resumed after reloading page. But input params are the same(they are stored in localStorage) and it makes me crazy. After some time execution again stops and html elements disapears. Also js in console not working too. No errors are handeled.I'm at loss. Thank you.
MAIN.JS
<code>    var db = openDatabase("primeNumbers", "0.1", "Prime numbers db", 200000);
    db.transaction(function (tx) {
      tx.executeSql("CREATE TABLE  IF NOT EXISTS primeNumbers (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, value INTEGER NOT NULL UNIQUE)", [], null, null);
    });
    var settings = {};
    prepareData();

    $(document).ready( function() {
      $('#start_button').click( function() {
        toggleButton();
      });
      $('#show_table_button').click(function() {
        showTableButton();
      });
      $('#show_canvas_image_button').click(function() {
        showCanvas();
      });
    });

    //check if db can be used
    if(!db){alert("Failed to connect to database.");}

    var currNumber = 2;
    var work;

    var worker = new Worker('js/worker.js');//(blobURL);

    //worker event listener
    worker.onmessage = function(event) {
      (event.data != undefined) && (settings.bFlag = true);
      finder(true);
    };

function finder(again) {
  if(settings.j == 14 && settings.i == 373) {
    console.log('70');
  };
  if(again) {
    if ( settings.bFlag ){
      settings.j = 0;
      if ( settings.iShag == 3 ){
        settings.i+=4;
        settings.iShag = 0;
      } else {
        settings.i+=2;
        settings.iShag++;
      };
      iSquare = Math.floor(Math.sqrt(settings.i));
      settings.bFlag = false;
    };
    settings.j++;
  };
  storeTempData();
  work && worker.postMessage('{\"i\":\"'+settings.i+'\",\"j\":\"'+settings.j+'\"}');
};

function toggleButton() {
  btn = $('#start_button');
  if(btn.text() != 'pause_calculations') {
    btn.text('pause_calculations');
    work = true;
    finder(false);
  } else {
    btn.text('resume_calculations');
    work = false;
  };
};

// table with data
function showTableButton() {
  //TODO: check if we can use this as parameter to function
  btn = $('#show_table_button');
  if(btn.text() == 'show_calculated_data') {
    btn.text('reload_table');
    renderTable();
  } else {
    //TODO: implement it renderTable();
  };
};

var table_data;

function renderTable() {
  getBlockOfDataFromDb( function() {
    $('#table_with_results').jqGrid({
      datatype: 'local',
      data: table_data,
      height: 230,
      width: 350,
      colNames: ['id', 'value'],
      colModel: [
        { name: 'id', index: 'id', width: 20, sorttype: 'int', align: 'right' },
        { name: 'value', index: 'value', width: 20, sorttype: 'int', align: 'right'}
      ],
      multiselect: false,
      caption: 'Prime numbers from db',
      rowNum: 10,
      pager: 'table_pager',
      pagination: true,
      gridview: true,
      edit:false,
      add:false,
      del:false
    });
  });
};

function getBlockOfDataFromDb(callback) {
  var res = [];
 db.transaction(function(tx) {
   tx.executeSql('SELECT * FROM primeNumbers', [], function(tx, result) {
     result_length = result.rows.length;
     for(var i = 0; i < result_length; i++) {
       var json_obj = { id: result.rows.item(i).id, value: result.rows.item(i).value };
       res.push(json_obj);
     };
     table_data = res;
    callback();
   });
 });
};

Array.prototype.contains = function(k) {
    for(var p in this)
        if(this[p] === k)
            return true;
    return false;
};

function showCanvas() {
  var primeArray = [];
  var edge;
  db.transaction(function(tx) {
    tx.executeSql('SELECT * FROM primeNumbers', [], function(tx, result) {
      result_length = result.rows.length;
      for(var i = 0; i < result_length; i++) {
        primeArray.push(parseInt(result.rows.item(i).value));
      };
      edge = parseInt(Math.sqrt(Math.max.apply(Math, primeArray))) + 1;

      canv_div = $('#canvas_div');
      $('<canvas width="'+edge+'" height="'+edge+'" id="canvas_elem"></canvas>').appendTo(canv_div);
      canv = $('#canvas_elem')[0];
      var context = canv.getContext('2d');
      var imgd = context.createImageData(edge,edge);
      var pix = imgd.data;
      var iter = 0;
      for (var i = 0; n = pix.length, i < n; i += 4) {
        pix[i] = 0;
        if(primeArray.contains(iter)) {
          pix[i+3] = 255;
        } else {
          pix[i+3] = 50;
        };
        iter++;
      }
      context.putImageData(imgd, 0,0);
    });
  });
};

function prepareData() {

  var ls = localStorage;

  if(ls.getItem('bFlag') && ls.getItem('i') && ls.getItem('j') && ls.getItem('iShag')) {
    settings.bFlag = (ls.getItem('bFlag') === 'true');
    settings.i     = parseInt(ls.getItem('i'));
    settings.j     = parseInt(ls.getItem('j'));
    settings.iShag = parseInt(ls.getItem('iShag'));
  } else {
    settings.i     = 7;
    settings.j     = 1;
    settings.iShag = 0;
    settings.bFlag = false;
    db.transaction(function(tx) {
      tx.executeSql('INSERT INTO primeNumbers (value) SELECT 2 AS value UNION SELECT 3 UNION SELECT 5');
    });
  };
};
function storeTempData() {
  localStorage.setItem('i'     , settings.i);
  localStorage.setItem('j'     , settings.j);
  localStorage.setItem('bFlag' , settings.bFlag);
  localStorage.setItem('iShag' , settings.iShag);
};
</code>
and also my WORKER.JS
<code>onmessage = function(event) {
  data = JSON.parse(event.data);
  i = parseInt(data['i']);
  j = parseInt(data['j']);
  iSquare = Math.floor(Math.sqrt(i));
  run();
};
function run() {
  var db = openDatabase("primeNumbers", "0.1", "Prime numbers db", 200000);
  db.transaction(function(tx) {
    if(i == 373 && j == 15) {
      1+1;
    };
    tx.executeSql('SELECT value FROM primeNumbers WHERE id='+(j+1), [], function(tx, result) {
      val = parseInt(result.rows.item(0)['value']);
      if ( i % val == 0 ){
        self.postMessage('bFlag');
      } else if (j >= iSquare) {
        db.transaction(function(tx) {
          tx.executeSql('INSERT INTO primeNumbers (value) VALUES ('+i+')', [], function() {
            self.postMessage('bFlag');
          });
        });
      } else {
        self.postMessage();
      };
    },
    function(tx, error) {
      self.postMessage('Error processing SQL: ' + error);
    });
  }, function(error) {
    self.postMessage('Error processing Transaction: ' + error)
  });
};
</code>
I will be happy in any ideas.
Perhaps smb know how to catch errors or what i need to find in chrome profiler.
I wrote a video with the proces. youtube
Answer: The issue resolved. I've moved SELECT statment from worker to main file. I think that problem was in error handling in worker, because it was a lot of errors from db when i tried to select nonexistent value(it needs by algorithm).

Html elements hides on script execution


How to change cron PATH permanently?

Question: We need /usr/local/bin in cron's path! this way: http://discuss.joyent.com/viewtopic.php?pid=213759 didnt work for us.
Comment: There are many variants of cron, and sometimes more than one within a given distribution.  Can you provide more details (distribution, where you're adding the cron that's failing, etc.)?
Answer: If you are using Red Hat Enterprise Linux or derivative distributions of it, you can do it by following the "Configuring Cron Tasks" section of Red Hat's manual for RHEL.  You will be editing /etc/crontab and modifying the PATH variable to add /usr/local/bin.
<code>PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
</code>
Comment: does not work on ubuntu, even after restarting cron (only works when used directly in the crontab of the user)
Comment: What user is running the cron job?  Can you just updated the PATH variable in the crontab of the user running it?  According to https://help.ubuntu.com/community/CronHowto, "Depending on the commands being run, you may need to expand the root users PATH variable" by updating PATH variable at the top of the root user's crontab file.  Additionally, http://gaarai.com/2009/03/18/changing-when-daily-cron-jobs-run-in-ubuntu/ indicates that /etc/crontab is a system-wide crontab.  I'm not much of an Ubuntu user though, so if that does not help, I apologize.

How to change cron PATH permanently?


Neyman-Pearson lemma

Question: I have read the Neyman–Pearson lemma  from the book  Introduction to the Theory of Statistics by Mood, Graybill and Boes.  But I have not understood the lemma.
Can anyone please explain the lemma to me in plain words? What does it state?

Neyman-Pearson Lemma : Let $X_1,\ldots,X_n$ be a random sample from $f(x;\theta)$, where $\theta$ is one of two known values $\theta_0$ and $\theta_1$, and let $0<\alpha<1$ be fixed.
Let  $k^*$ be a positive constant and $C^*$ be a subset of $\mathscr X$ which satisfy :$$ \tag 1 P_{\theta_0}[(X_1,\ldots,X_n)\in C^*] = \alpha$$ $$\tag 2 \lambda=\frac{L(\theta_0;x_1,\ldots,x_n)}{L(\theta_1;x_1,\ldots,x_n)} = \frac{L_0}{L_1} \le k^*\quad \text{if } (x_1,\ldots,x_n)\in C^* $$ $$\text{and}\quad  \lambda\ge\quad  k^* \text{ if } (x_1,\ldots,x_n)\in \bar C^* $$
Then the test $\gamma^*$ corresponding to the critical region $C^*$ is a most powerful test of size $\alpha$ of $\mathscr H_0:\theta=\theta_0$ versus $\mathscr H_1:\theta=\theta_1$

Expressed in words, I have understood that the two criteria specify
(1) P[rejecting null hypothesis | null hypothesis is true] =significance level
(2) reject null hypothesis when the likelihood ratio, $\lambda\le$ some positive constant $ k^*$ if $(x_1,\ldots,x_n)$ fall in the critical region
Then the test is the most powerful test of a simple hypothesis.

Why is it only for simple hypotheses? Can't it be for composite hypothesis? Is my explanation in words correct?
Answer: I recently wrote an entry in a linkedin blog stating Neyman Pearson lemma in plain words and providing an example. I found the example eye opening in the sense of providing a clear intuition on the lemma. As often in probability, it is based on a discrete probability mass function so it is easy to undertand than when working with pdf's. Also, take into account I define the likelihood ratio as the likelihood of the alternative hypothesis vs. the null hypothesis, contrary to your lemma statement. The explanation is the same, but rather than less than is now greater than. I hope it helps...
Those of you who work in data analysis and have been through some statistics courses may have come to know Neyman-Pearson lemma (NP-lemma). The message is simple, the demonstration not so much but what I always found difficult was to get a common-sense feeling of what it was about. Reading a book named "Common Errors in Statistics" by P.I.Good and J.W.Hardin I got to an explanation and example that helped me get this gut feeling about the NP-lemma I had always missed.
In not 100% mathematically perfect language, what Neyman-Pearson tells us is that the most powerful test one can come up to validate a given hypothesis within a certain significance level is given by a rejection region made by all possible observations coming from this test with a likelihood ratio above a certain threshold... woahhh! Who said it was easy!
Keep calm and deconstruct the lemma:

Hypothesis. In statistics one always works with two hypothesis that a statistical test should reject or not reject. There is the null hypothesis, that will not be rejected until sample evidence against it is strong enough. There is also the alternative hypothesis, the one we will take if the null seems to be false.
Power of a test (a.k.a. sensitivity) tells us which proportion of times we will correctly reject the null hypothesis when it is wrong. We want powerful tests, so most of the time we reject the null hypothesis we are right!
Significance level of a test (a.k.a. false positive rate) tells us which proportion of times we will wrongly reject the null hypothesis when it is true. We want a small significance level so most of the times we reject the null hypothesis we are not wrong!
Rejection region, given all possible outcomes of the test, the rejection region includes those outcomes that will make us reject the null hypothesis in benefit of its alternative one.
Likelihood is the probability of having seen the observed outcome of the test given that the null hypothesis (Likelihood of the null hypothesis) or the alternative one (Likelihood of the alternative hypothesis) were true.
Likelihood ratio, is the ratio of the alternative hypothesis likelihood divided by the null hypothesis likelihood. If the test outcome was very much expected if the null hypothesis were true versus the alternative one, the likelihood ratio should be small.

Enough definitions! (although if you look at them carefully, you will realize they are very insightful!). Let's go to what Neyman and Pearson tell us: if you want to have the best possible statistical test from the point of view of its power just define the rejection region by including those test results that have the highest likelihood ratio, and keep adding more test results until you reach a certain value for the number of times your test will reject the null hypothesis when it is true (significance level).
Let's see an example where hopefully everything will come together. The example is based on the book mentioned above.  It is completely made up by myself so it should not be viewed as reflecting any reality or personal opinion.
Imagine one wants to determine whether somebody is in favor of setting immigration quotas (null hypothesis) or not (alternative hypothesis) by asking his/her feelings versus the European Union.
Imagine we knew the actual probability distribution for both types of people regarding the answer to our question:

Let's imagine we are willing to accept a false positive error of 30%, that is, 30% of the time we will reject the null hypothesis and assume the interviewed person is against quotas when he/she is really for them. How would we construct the test?
According to Neyman and Pearson we would first take the result with the highest likelihood ratio. This is the answer of "really like the EU" with a ratio of 3. With this result, if we assume somebody is against quotas when he/she said he "really likes the EU", 10% of the time we would be assigning for quotas people as against (significance). However we would only be correctly classifying against quota people 30% of the time (power) as not everybody in this group have the same opinion about the EU.
This seems to be a poor result as far as power is concerned. However, the test does not make many mistakes at misclassifying for quota people (significance) . As we are more flexible regarding significance, let's look for the next test result that we should add to the bag of answers that reject the null hypothesis (rejection region).
The next answer with the highest likelihood ratio is "like the EU". If we use the answers "really like" and "like" the EU as test results that allow us to reject the null hypothesis of somebody being for quotas, we would be misclassifying for quotas people as not 30% of the time (10% from the "really like" and 20% from the "like") and we would be correctly classifying against quotas people 65% of the time (30% from "really like" and 35% from "like"). In statistical jargon: our significance increased from 10% to 30% (bad!) while the power of our test increased from 30% to 65% (good!).
This is a situation all statistical tests have. There is not something such as a free lunch even in statistics! If you want to increase the power of your test you do it at the expense of increasing the level of significance. Or in simpler terms: you want to better classify the good guys, you will do at the expense of having more bad guys looking good!
Basically, now we are done! We created the most powerful test we could with the given data and a significance level of 30% by using "really like" and "like" labels to determine if somebody is against quotas... are we sure?
What would have happened if we had included in the second step after the "really like" answer was chosen, the answer "indifferent" instead of "like"? The significance of the test would have been the same than before at 30%: 10% for quota people answer "really" like and 20% for quota people answer "dislike". Both tests would be as bad at misclassifying for quota individuals. However, the power would get worse! With the new test we would have a power of 50% instead of the 65% we had before: 30% from "really likes" and 20% from "indifferent". With the new test we would be less precise at identifying against quota individuals!
Who helped out here? Neyman-Person likelihood ratio remarkable idea! Taking at each time the answer with the highest likelihood ratio ensured us that we include in the new test as much power as possible (large numerator) while keeping the significance under control (small denominator)!
Comment: Wow, just seeing everything in that table helped a ton, and referring to parts of it helped a ton. Thank you!
Answer: The Context
(In this section I'm just going to explain hypothesis testing, type one and two errors, etc, in my own style. If you're comfortable with this material, skip to the next section)
The Neyman-Pearson lemma comes up in the problem of simple hypothesis testing. We have two different probability distributions on a common space $\Omega$: $P_0$ and $P_1$, called the null and the alternative hypotheses. Based on a single observation $\omega\in\Omega$, we have to come up with a guess for which of the two probability distributions is in effect. A test is therefore a function which to each $\omega$ assigns a guess of either "null hypothesis" or "alternative hypothesis". A test can obviously be identified with the region on which it returns "alternative", so we're just looking for subsets (events) of the probability space.
Typically in applications, the null hypothesis corresponds to some kind of status quo, whereas the alternative hypothesis is some new phenomenon which you're trying to prove or disprove is real. For example, you may be testing someone for psychic powers. You run the standard test with the cards with squiggly lines or what not, and get them to guess a certain number of times. The null hypothesis is that they'll get no more than one in five right (since there's five cards), the alternative hypothesis is that they're psychic and may get more right.
What we'd like to do is minimize the probability of making a mistake. Unfortunately, that's a meaningless notion. There are two ways you could make a mistake. Either the null hypothesis is true, and you sample an $\omega$ in your test's "alternative" region, or the alternative hypothesis is true, and you sample the "null" region. Now, if you fix a region $A$ of the probability space (a test), then the numbers $P_0(A)$ and $P_1(A^{c})$, the probabilities of making those two kinds of errors, are completely well-defined, but since you have no prior notion of "probability that the null/alternative hypothesis is true", you can't get a meaningful "probability of either kind of mistake". So this is a fairly typical situation in mathematics where we want the "best" of some class of objects, but when you look closely, there is no "best". In fact, what we're trying to do is minimize $P_0(A)$ while maximizing $P_1(A)$, which are clearly opposing goals.
Keeping in mind the example of the psychic abilities test, I like to refer to the type of mistake in which the null is true but you conclude the alternative as true as "delusion" (you believe the guy's psychic but he's not), and the other kind of mistake as "obliviousness".
The Lemma
The approach of the Neyman-Pearson lemma is the following: let's just pick some maximal probability of delusion $\alpha$ that we're willing to tolerate, and then find the test that has minimal probability of obliviousness while satisfying that upper bound. The result is that such tests always have the form of a likelihood-ratio test:

Proposition (Neyman-Pearson lemma)
If $L_0, L_1$ are the likelihood functions (PDFs) of the null and alternative hypotheses, and $\alpha > 0$, then the region $A\subseteq \Omega$ which maximizes $P_1(A)$ while maintaining $P_0(A)\leq \alpha$ is of the form
$$A=\{\omega\in \Omega \mid \frac{L_1(\omega)}{L_0(\omega)} \geq K \}$$
for some constant $K>0$. Conversely, for any $K$, the above test has $P_1(A)\geq P_1(B)$ for any $B$ such that $P_0(B)\leq P_0(A)$.

Thus, all we have to do is find the constant $K$ such that $P_0(A)=\alpha$.
The proof on Wikipedia at time of writing is a pretty typically oracular mathematical proof that just consists in conjecturing that form and then verifying that it is indeed optimal. Of course the real mystery is where did this idea of taking a ratio of the likelihoods even came from, and the answer is: the likelihood ratio is simply the density of $P_1$ with respect to $P_0$.
If you've learned probability via the modern approach with Lebesgue integrals and what not, then you know that under fairly unrestrictive conditions, it's always possible to express one probability measure as being given by a density function with respect to another. In the conditions of the Neyman-Pearson lemma, we have two probability measures $P_0$, $P_1$ which both have densities with respect to some underlying measure, usually the counting measure on a discrete space, or the Lebesgue measure on $\mathbb R^n$. It turns out that since the quantity that we're interested in controlling is $P_0(A)$, we should be taking $P_0$ as our underlying measure, and viewing $P_1$ in terms of how it relates to $P_0$, thus, we consider $P_1$ to be given by a density function with respect to $P_0$.
Buying land
The heart of the lemma is therefore the following:

Let $\mu$ be a measure on some space $\Omega$, and let $f$ be a positive, integrable function on $\Omega$. Let $\alpha > 0$. Then the set $A$ with $\mu(A)\leq\alpha$ which maximizes $\int_A fd\mu$ is of the form
$$\{\omega\in\Omega\mid f(\omega)\geq K\}$$
for some constant $K>0$, and conversely, any such set maximizes $\int f$ over all sets $B$ smaller than itself in measure.

Suppose you're buying land. You can only afford $\alpha$ acres, but there's a utility function $f$ over the land, quantifying, say, potential for growing crops, and so you want a region maximizing $\int f$. Then the above proposition says that your best bet is to basically order the land from most useful to least useful, and buy it up in order of best to worst until you reach the maximum area $\alpha$. In hypothesis testing, $\mu$ is $P_0$, and $f$ is the density of $P_1$ with respect to $P_0$ (which, as already stated, is $L_1/L_0$).
Here's a quick heuristic proof: out of a given region of land $A$, consider some small one meter by one meter square tile, $B$. If you can find another tile $B'$ of the same area somewhere outside of $A$, but such that the utility  of $B'$ is greater than that of $B$, then clearly $A$ is not optimal, since it could be improved by swapping $B$ for $B'$. Thus an optimal region must be "closed upwards", meaning if $x\in A$ and $f(y)>f(x)$, then $y$ must be in $A$, otherwise we could do better by swapping $x$ and $y$. This is equivalent to saying that $A$ is simply $f^{-1}([K, +\infty))$ for some $K$.
Answer: I think you understood the lemma well.
Why it does not work for a composite alternative?
As you can see in the likelihood ratio, we need to plug in the parameter(s) for the alternative hypothesis. If the alternative is composite, which parameter are you going to plug in?
Comment: You can get it to work for composite alternatives if the likelihood ratio is monotone.

Neyman-Pearson lemma


Geometric interpretation of multiple correlation coefficient $R$ and coefficient of determination $R^2$

Question: I am interested in the geometric meaning of the multiple correlation $R$ and coefficient of determination $R^2$ in the regression $y_i = \beta_1 + \beta_2 x_{2,i} + \dots + \beta_k x_{k,i} + \epsilon_i $, or in vector notation,
$$\mathbf{y} = \mathbf{X \beta} + \mathbf{\epsilon}$$
Here the design matrix $\mathbf{X}$ has $n$ rows and $k$ columns, of which the first is $\mathbf{x}_1 = \mathbf{1}_n$, a vector of 1s that corresponds to the intercept $\beta_1$.
The geometry is more interesting in the $n$-dimensional subject space rather than in the $k$-dimensional variable space. Define the hat matrix:
$$\mathbf{H} = \mathbf{X \left(X^\top X \right)}^{-1} \mathbf{X}^\top$$
This is an orthogonal projection onto the column space of $\mathbf{X}$, i.e. the flat  through the origin spanned by the $k$ vectors representing each variable $\mathbf{x}_i$, the first of which is $\mathbf{1}_n$. Then $\mathbf{H}$ projects the vector of observed responses $\mathbf{y}$ onto its "shadow" on the flat, the vector of fitted values $\mathbf{\hat{y}} = \mathbf{Hy}$, and if we look along the path of the projection we see the vector of residuals $\mathbf{e} = \mathbf{y} - \mathbf{\hat{y}}$ forms the third side of a triangle. This should furnish us with two routes to a geometric interpretation of $R^2$:

The square of the multiple correlation coefficient, $R$, which is defined as the correlation between $\mathbf{y}$ and $\mathbf{\hat{y}}$. This will appear geometrically as the cosine of an angle.
In terms of lengths of vectors: for instance $SS_\text{residual} = \sum_{i=1}^{n}e_i^2 = \|\mathbf{e}\|^2$.

I would be delighted to see a brief account which explains:

The finer details for (1) and (2),
Why (1) and (2) are equivalent,
Briefly, how the geometric insight lets us visualise basic properties of $R^2$, for instance why it goes to 1 when the noise variance goes to 0. (After all, if we can't intuit from our visualisation then it's no more than a pretty picture.)

I appreciate this is more straightforward if the variables are centred first, which removes the intercept from the question. However, in most textbook accounts which introduce multiple regression, the design matrix $\mathbf{X}$ is as I laid out. Of course it's fine if an exposition delves into the space spanned by the centred variables, but for insight into the textbook linear algebra, it would be very helpful to relate this back to what's happening geometrically in the uncentred situation. A really insightful answer might explain what exactly is breaking down geometrically when the intercept term is dropped - i.e. when the vector $\mathbf{1}_n$ is removed from the spanning set. I don't think this last point can be addressed by considering the centred variables alone.
Answer: If there is a constant term in the model then $\mathbf{1_n}$ lies in the column space of $\mathbf{X}$ (as does $\bar{Y}\mathbf{1_n}$, which will come in useful later). The fitted $\mathbf{\hat{Y}}$ is the orthogonal projection of the observed $\mathbf{Y}$ onto the flat formed by that column space. This means the vector of residuals $\mathbf{e} = \mathbf{y} - \mathbf{\hat{y}}$ is perpendicular to the flat, and hence to $\mathbf{1_n}$. Considering the dot product we can see $\sum_{i=1}^n e_i = 0$, so the components of $\mathbf{e}$ must sum to zero. Since $Y_i = \hat{Y_i} + e_i$ we conclude that $\sum_{i=1}^n Y_i = \sum_{i=1}^n \hat{Y_i}$ so that both fitted and observed responses have mean $\bar{Y}$.

The dashed lines in the diagram represent $\mathbf{Y} - \bar{Y}\mathbf{1_n}$ and $\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}$, which are the centered vectors for the observed and fitted responses. The cosine of the angle $\theta$ between these vectors will therefore be the correlation of $Y$ and $\hat{Y}$, which by definition is the multiple correlation coefficient $R$. The triangle these vectors form with the vector of residuals is right-angled since $\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}$ lies in the flat but  $\mathbf{e}$ is orthogonal to it. Hence:
$$R = \cos(\theta) = \frac{\text{adj}}{\text{hyp}} = \frac{\|\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}\|}{\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|} $$
We could also apply Pythagoras to the triangle:
$$\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|^2 =
\|\mathbf{Y} - \mathbf{\hat{Y}}\|^2 + \|\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}\|^2 $$
Which may be more familiar as:
$$\sum_{i=1}^{n} (Y_i - \bar{Y})^2 =
\sum_{i=1}^{n} (Y_i - \hat{Y}_i)^2 + \sum_{i=1}^{n} (\hat{Y}_i - \bar{Y})^2 $$
This is the decomposition of the sums of squares, $SS_{\text{total}} = SS_{\text{residual}} + SS_{\text{regression}}$.
The standard definition for the coefficient of determination is:
$$R^2 = 1 - \frac{SS_{\text{residual}}}{SS_{\text{total}}} =  1 - \frac{\sum_{i=1}^n (y_i - \hat{y}_i)^2}{\sum_{i=1}^n (y_i - \bar{y})^2} =
1 - \frac{\|\mathbf{Y} - \mathbf{\hat{Y}}\|^2}{\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|^2}$$
When the sums of squares can be partitioned, it takes some straightforward algebra to show this is equivalent to the "proportion of variance explained" formulation,
$$R^2 = \frac{SS_{\text{regression}}}{SS_{\text{total}}} =
\frac{\sum_{i=1}^n (\hat{y}_i - \bar{y})^2}{\sum_{i=1}^n (y_i - \bar{y})^2} =
\frac{\|\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}\|^2}{\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|^2}$$
There is a geometric way of seeing this from the triangle, with minimal algebra. The definitional formula gives $R^2 = 1 - \sin^2(\theta)$ and with basic trigonometry we can simplify this to $\cos^2(\theta)$. This is the link between $R^2$ and $R$.
Note how vital it was for this analysis to have fitted an intercept term, so that  $\mathbf{1_n}$ was in the column space. Without this, the residuals would not have summed to zero, and the mean of the fitted values would not have coincided with the mean of $Y$. In that case we couldn't have drawn the triangle; the sums of squares would not have decomposed in a Pythagorean manner; $R^2$ would not have had the frequently-quoted form $SS_{\text{reg}}/SS_{\text{total}}$ nor be the square of $R$. In this situation, some software (including R) uses a different formula for $R^2$ altogether.
Comment: This is a great answer +1. Just to in form a reader that similar pictures can be found in https://stats.stackexchange.com/a/124892/3277
Comment: +1 Very nice write-up and figure. I am surprised that it only has my single lonely upvote.
Comment: +1. Note that the figure of your answer, with "column space X", Y, Ypred as vectors etc. is what is known in multivariate statistics as "(reduced) subject space representation" ([see](http://stats.stackexchange.com/a/192637/3277), with further links where I've used it).
Comment: So, I have a question. Here, you stated explicitly that $\boldsymbol{1}_n$ is due to the intercept term. But what if, say, we remove the intercept, and by some coincidence, we have such that all samples's p-th feature is 1. In that case, you would have the $\boldsymbol{1}_n$ in the column space. It seems this analysis would still hold even thought here is no intercept term?
Comment: @anonuser01 You'd get the same effect if you include an independent variable whose value for each observation is 2, or $\pi$. Either way, the vector $\mathbf{1}_n$ lies in the column space of the design matrix. Note that if you *did* then include an intercept term as well, you [get perfect multicollinearity](https://stats.stackexchange.com/a/222128/22228) since there's a linear dependence between the intercept column and variable-that-just-so-happens-to-be-constant column of the design matrix.


Make :focus styling remain there after the user clicks the link

Question: I have created a mobile hamburger menu with several links. You can examine the source code here:

?מהי רגולציה

אודות

?למי זה מתאים

פתרונות

צור קשר

  |  052-6582643

Once the user clicks one of the links in the menu, the menu closes and he is navigated to wherever he clicked. I want the border effect I created with CSS to remain there, so he'll have a mark where he is in the navigation:
#menu-solutions:hover .menu-item-text,
#menu-solutions:focus .menu-item-text,
#menu-solutions:active .menu-item-text{
border-bottom: 2.11px solid #61f6ff;
        padding: 4px;
            box-sizing:border-box;
margin-bottom: 4px;

}

#about-menu-mobile:hover .menu-item-text,
#about-menu-mobile:focus .menu-item-text,
#about-menu-mobile:active .menu-item-text{
border-bottom: 2.11px solid #61f6ff;
border-top: 2.11px solid #61f6ff;
        padding: 4px;
            box-sizing:border-box;
margin-bottom: 4px;

}
#contact-menu-mobile:hover .menu-item-text,
#contact-menu-mobile:focus .menu-item-text,
#contact-menu-mobile:active .menu-item-text{
border-bottom: 2.11px solid #61f6ff;
border-top: 2.11px solid #61f6ff;
        padding: 4px;
            box-sizing:border-box;
margin-bottom: 4px;

}
#regulation-menu-mobile:hover .menu-item-text,
#regulation-menu-mobile:focus .menu-item-text,
#regulation-menu-mobile:active .menu-item-text{
border-bottom: 2.11px solid #61f6ff;
border-top: 2.11px solid #61f6ff;
        padding: 4px;
            box-sizing:border-box;
            margin-bottom: 4px;

}

#menu-solutions .menu-item-text {
  border-bottom: 2.11px solid transparent;
  border-top: 2.11px solid transparent;
  padding: 4px;
            box-sizing:border-box;
margin-bottom: 4px;
}

You can also examine the link: www.mayabarber.co.il
Is it possible?
Thanks
Comment: have you tried to use `:visited`?
Comment: `:visited` will apply to every `` with visited URL, which is not what OP wants to achieve. What OP is asking for can't be done without additional CSS class applied to current's route ``.
Answer: I guess defining style for active class should work for you.

.active {
  border-bottom: 2.11px solid #61f6ff;
  padding: 4px;
  box-sizing: border-box;
  margin-bottom: 4px;
}
Comment: I have applied active attributes to every ID
Comment: But at any given time, the active class would apply to only one menu item which would be active at that instant.
Answer: Sure you can. Just replace your above CSS code with this one:
.elementor-widget-wrap .elementor-heading-title > a:hover .menu-item-text,
.elementor-widget-wrap .elementor-heading-title > a:focus .menu-item-text,
.elementor-widget-wrap .elementor-heading-title > a:active .menu-item-text,
.elementor-widget-wrap .elementor-heading-title > a .menu-item-text.active{
border-bottom: 2.11px solid #61f6ff;
border-top: 2.11px solid #61f6ff;
padding: 4px;
margin-bottom: 4px;
}

Working jsfiddle
Comment: If you could explain what was wrong with OP's code and why this works, that would be of great help to the future readers.


What is restrictions in java.io for decorating streams?

Question: I am imagine decorator pattern like this:

I know that java io uses this pattern.
I feel that exist some restrictions for wrapping object but I cannot understand entire rule.
research code:
snippet 1 - working code:
    OutputStream outputStream = new FileOutputStream("2.txt");

    ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
    ObjectOutputStream objectOutputStreamWrapper = new ObjectOutputStream(objectOutputStream);     //double wrapping

    objectOutputStreamWrapper.writeObject("this is my string");
    objectOutputStreamWrapper.close();

    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("2.txt"));
    ObjectInputStream   objectInputStreamWrapper = new ObjectInputStream(objectInputStream);

    System.out.println(objectInputStreamWrapper.readObject());
    objectInputStream.close();

snippet 2 - not working :
    OutputStream outputStream = new FileOutputStream("2.txt");

    ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
    ObjectOutputStream objectOutputStreamWrapper = new ObjectOutputStream(objectOutputStream);     //double wrapping

    objectOutputStreamWrapper.writeObject("this is my string");
    objectOutputStreamWrapper.close();

    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("2.txt"));
    //ObjectInputStream   objectInputStreamWrapper = new ObjectInputStream(objectInputStream);

    System.out.println(objectInputStream.readObject());
    objectInputStream.close();

output:
Exception in thread "main" java.io.OptionalDataException
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1361)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
    at io.WrappingUnwrappingOrderingTest.main(WrappingUnwrappingOrderingTest.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

snippet 3 - not working
    OutputStream outputStream = new FileOutputStream("2.txt");

    ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
  //  ObjectOutputStream objectOutputStreamWrapper = new ObjectOutputStream(objectOutputStream);     //double wrapping

    objectOutputStream.writeObject("this is my string");
    objectOutputStream.close();

    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("2.txt"));
    ObjectInputStream   objectInputStreamWrapper = new ObjectInputStream(objectInputStream);

    System.out.println(objectInputStreamWrapper.readObject());
    objectInputStream.close();

output:
Exception in thread "main" java.io.EOFException
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2325)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2794)
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
    at io.WrappingUnwrappingOrderingTest.main(WrappingUnwrappingOrderingTest.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Looks like in file on filesystem stores information about order of stream decoration. It is strange for me.Please clarify this misunderstanding.
Does always should I use stricly same order of decorators for input and output?
Comment: It is absolutely another question!!!
Answer: The problem here is that constructing an ObjectOutputStream writes some bytes to the underlying stream:

Creates an ObjectOutputStream that writes to the specified OutputStream. This constructor writes the serialization stream header to the underlying stream

And similarly, creating an ObjectInputStream reads the serialization header.
So, if you open two ObjectOutputStreams and read using just one, or vice-versa, you won't read as many serialization headers as wrote, causing it not to work, as shown in the stack trace:

at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)

This is something which is quite unique to ObjectOutputStream. Wrapping buffered streams into buffered streams, for example, won't have this problem.
Comment: Can you clarify cause of writing headers to underlying stream?
Comment: See http://docs.oracle.com/javase/7/docs/platform/serialization/spec/protocol.html. The header contains the stream magic and the stream version.


How do you conduct multiple t-tests per stratum in stratified sampling?

Question: Suppose that I am concerned with the effect of treatment in each stratum, let's say A, B, and C. What is the most appropriate statistical method given that I want to understand the treatment effect and its statistical significance within each group?
I've considered the following methods:

Stratified T-Test
Stratified Sampling with T-Test per stratum
Randomized Complete Block Design

I've read up on articles on how approaches 1 and 3 are utilized, and it seems that they evaluate the effect across the groups as a whole. So, this leaves me to consider evaluating the stratum using a T-Test, separately.
But, if I do so, should I also be concerned with FPR inflation and corrections on either the P-value or significance level to mitigate this?
Thank you in advance!
Comment: I'm not familiar with stratified t-tests. Is there a reason you wouldn't just use a linear model/regression/ANOVA/ANCOVA here, and analyse all your data in one model?
Answer: I would go for a linear regression (or GLM's, in case of distribution families other than Gaussian). Then, you can use packages like emmeans that will allow you to look at the effect per stratum.
Take a look at this vignette for the basics of this package. It has a cool examples on linear regressions and analysis on stratuns:
https://cran.r-project.org/web/packages/emmeans/vignettes/basics.html


Conversão de bases

Question: Em um trabalho da faculdade nos foi exigido simular o funcionamento de uma memória RAM. O usuário pode ler ou escrever nas células dessa memória ou zera todas, sendo que cada uma armazena 8 bits. Essa parte já está feita, mas há algo que não consigo resolver. O usuário pode pedir o endereço de uma célula ou ler o conteúdo dela em binário ou em hexadecimal, de acordo com a escolha dele, mas estou com dificuldades em converter os elementos de cada célula (que já estão em binário) para hexadecimal.
O código está assim:
import numpy as np

celulas = np.array([(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0)])
while True:
    operação = str(input('Ler[A], Escrever[B] ou Limpar[c]? Para terminar a aplicação[D]')).upper()
    if operação == 'A':
        endereço = int(input('Qual célula ler?'))
        base = int((input('Você quer ler em binário(1) ou em hexadecimal(2)?')))
        if base == 1:
            cels = [str(i) for i in celulas[endereço - 1]]
            print(''.join(cels))
    if operação == 'B':
        endereço = int(input('Qual célula escrever?'))
        cont = 0
        while cont <= 7:
            celulas[endereço-1][cont] = int(input('Digite 1 ou 0'))
            cont += 1
    if operação == 'C':
        cont = 0
        while cont <= 31:
            celulas[cont] = (0,0,0,0,0,0,0,0)
            cont += 1
    if operação == 'D':
        break

Desde já, obrigado.
Answer: O jeito mais fácil de obter uma representação hexadecimal é transformar o valor em questão em bytes e chamar a sua função .hex().
Como você não está lidando na sua "memória" com números realmente binários, mas sim inteiros que assumem o valor 1 ou 0, temos que

Transformar os inteiros em uma string binária
Transformar a string binária em um inteiro
Transformar o inteiro em bytes
Aplicar a função hex

Podemos fazer isso assim:
base = int((input('Você quer ler em binário(1) ou em hexadecimal(2)?')))
if base == 1:
    cels = [str(i) for i in celulas[endereço - 1]]
    print(''.join(cels))
if base == 2:

    # Pegar a representação binária da célula (10111001)
    cels = [str(i) for i in celulas[endereço - 1]]
    representacao_binaria = ''.join(cels)

    # Converter representação binária em inteiro (indicando que nossa
    # string está em base 2, binária)
    inteiro = int(representacao_binaria, base=2)

    # Transformamos o inteiro em um byte, e pegamos sua representação
    # hexadecimal (ex. b9)
    representacao_hexadecimal = inteiro.to_bytes(1, sys.byteorder).hex()

    # Mudamos um pouco a apresentação (b9 -> 0xB9)
    print('0x' + representacao_hexadecimal.upper())

Comment: Perfeito, meu amigo, deu certo. Muito obrigado

Conversão de bases


How to make plots appear in Rmarkdown file instead of viewer pane when working with keras in Rstudio?

Question: I am new in R and trying keras in Rstudio. All the accuracy, loss interactive plots by running fit() are appearing in Viewer pane instead of Rmarkdown file.
All other plots usually plot inside Rmarkdown files but not with keras.
I have also checked Global settings in Rstudio Tools>Global Options>R Markdown>Show output preview in "Window".
How do I make them plot in Rmarkdown instead of Viewer Pane.
How do I make this mandatory for all plots to create inside Rmarkdown files only and now in viewer pane?
Comment: In RStudio, when you open a new RMarkdown file, in the editor pane, there is a cogwheel button / menu where you can choose "Chunk Output Inline". That should put the plots into the document.
Comment: @meriops `Chunk Output Inline` is already check marked in my `rmarkdown` file but still I get only `keras` function's generated charts in `Viewer` pane.
Answer: have you tried to plot in only one cell ?
for example you have a code block only like this
plot(x = dataframe$x, y = dataframe$y,
   xlab = "X",
   ylab = "Y",
   xlim = c(0,1.5),
   ylim = c(0,1.5),
   main = "X and Y between 0 and 1",
   col = dataframe$color,
   pch = 16,
   cex = 1.5
)

if you convert the rmarkdown file into html, the output of the plot will be shown

like this, in the browser. the only criteria you need to respect is put the plot function call alone in one cell


Analysis questions about "Jade's Desert" from Mortal Kombat Trilogy OST

Question: I transcribed this song recently, and I wanted some insight for analyzing it. It seems to me that it is a diminished riff, using tritones, chromatic stuff, and major seconds. However, beyond this I am not certain exactly what sort of chord progressions or compositional techniques are being used. For example, even if the song is atonal what sort of atonal methods are being used?
recording of transcription:
Seems to autoplay to some annoying songs afterwords, not sure how to stop this.
original song
Comment: What will you be doing with the results of the analysis? Do you want to make new arrangements of it, possibly altering the harmony, but keeping some aspects of the original intact? Or do you want to compose your own songs by using a similar perspective into harmony and song structure that might have been used to compose this one? What comes to the annoying autoplay thing, it seems to be a SoundCloud thing. Stop using SoundCloud and take your stuff elsewhere. https://community.soundcloud.com/desktop-230066/how-do-i-disable-the-idiotic-infuriating-autoplay-7351891
Comment: I was going to be using it to compose. What I was trying to ask is, if I opened up a music theory textbook what sections would I go to to learn more about this sort of thing? What would you recommend using instead of soundcloud?
Comment: this will be a good ear training to listen and notate music. This is always more effective if you're doing  by yourself and looking for feedback. But you will not find help by a theory book as this music is outside of theory of traditional harmony. Dieter de la Motte has in his Harmonielehre some chapters about individual styles of contemporary composers. (you can download the book as pdf for free and translate those chapters in English.) This could be helpful to find out concepts of modern composers. My advice: make this training with music where you can control your trials with the original.
Comment: If I understand your comment correctly. This is what I am trying to do, learn theory through transcribing songs and then trying to analyze what is happening rather than from a textbook. However, I was trying to figure out what sort of topics/concepts might be happening in this piece to explore further. Atonal/ Music outside of traditional theory is a pretty broad concept, so i'm not sure exactly where in that field to find concepts related to this piece.
Answer: I hear the tune this way:
<code>X: 1
K: C
T: Transcription differences
M: 3/2
L: 1/8
%%score V1 | V2 | V3
V:V1 clef=treble
V:V2 clef=treble
V:V3 clef=bass middle=D''
[V:V1] z12 :||: z12 :| B8-B3B/2c/2 | B8-B3 B/2c/2 | B2 _A2 =A2 c2-c2 d_e | B12 |]
[V:V2] zAdc f_ab=a c'_e'a'^f':||:zAc_A _eB^fd e=ac'_a:| z12 | z12 | z12 | z12 |]
[V:V3] D12 :||: D12:| z12 | z12 | z12 | z12 |]
</code>
So the overall pitch content can be viewed as the octatonic collection (0235689e), or, in other terms, the D diminished scale: D Eb F F# G Ab A B C.
In the opening two measures, and also the measures with the melody, all pitches are present in the measure. The "alternating" measures (mm. 3-4, and whenever there's no melody) leave out the F.
The melodic shape of the three parts is interesting: the unmoving (pedal) bass D, the wide-ranging arpeggios, and the narrow-ranging melody.
I hear D as the pitch center.
I haven't found a pattern for the arpeggios, so best guess is they were just designed to sound cool, but without a specific motif or pitch-class subset in mind.


how to get the first bytes of a file from a given url node.js

Question: I want to a file from a given url, in a aws lambda function.
I wrote this code:
exports.handler = (event, context, callback) => {
   var http = require('http');
   var url= "https://mail.google.com/mail/u/0/?ui=2&ik=806f533220&attid=0.1&permmsgid=msg-a:r-8750932957918989452&th=168b03149469bc1f&view=att&disp=safe&realattid=f_jro0gbqh0"

   //var client = http.createClient(80, url);
   var request = http.request({
     port: 80,
     host: url
   });

   request.on('response', function( res ) {
      res.on('data', function( data ) {
         console.log(data);
      });
   });
   request.end();

   const result = {
      statusCode: 200,
      body: JSON.stringify('Hello from Lambda!'),
   };

   callback(null, result);
};

but I get an error saying:
"Response: {
   "errorMessage": "RequestId: 52baec5e-60bc-47ea-911e-8e6cb1d2f1da Process exited before completing request"
}"

since I only need the first 2 bytes' I thought maybe I should read them, and not the whole file.
any ideas?
thanks a lot!
Answer: Did you increase your lambda execution Timeout limit? When you first created, lambda comes setted with only 3 seconds by default. You can change that under Basic settings. Change Timeout to 2 or 3 minutes to allow your lambda to finish execution. Also check if your memory is enough. You may need to increase it a little bit. I have mine with 256 MB.
When you test your lambda, pay attention at the Duration and Memory Size values. Lambda will print that in the last line of the log output. So if you set your lambda execution Timeout to 5 minutes and it only takes 2 minutes or if your lambda Memory Size is to close to your Memory you might want to increase it so your lambda do not fail execution due to a memory problem.
Comment: I tried that. I changed the timeout to 8 minutes, and the memorey to the maximum. It failed even thought it took only 75 ms. There must be somthing else wrong with my code.
Answer: I usually do this with fetch or request. You can make it with request like this:
exports.handler = (event, context, callback) => {

var request = require('request');
var url= "https://mail.google.com/mail/u/0/?ui=2&ik=806f533220&attid=0.1&permmsgid=msg-a:r-8750932957918989452&th=168b03149469bc1f&view=att&disp=safe&realattid=f_jro0gbqh0"

request(url, { json: true, timeout: 1000 }, (err, response, body) => {
    if (err) {
        console.log(err);
        callback(err, null);
    } else {
        console.log(body);
        callback(null, "Hello from Lambda");
    }
});

};

Just run npm install request to get module request and you are good to go.
It is always a good idea to start with your local development environment and when everything is ready, you just zip your files and then upload them to lambda. This way you know everything is just fine with your code and you can focus on the lambda configuration details. This way it much easier to test and you do not consume any lambda resource.
This is how to upload your file to lambda:
Comment: how can I install somthing on the aws lambda?  In addition, the callback must be the call back of the handler function of lambda... ( exports.handler = (event, context, callback) =>  ).  thanks a lot for answering!!
Comment: You do not install it in lambda. Thats why you dev local and then make a zip an upload your lambda with your packages. Got it? Do you know how to upload? This is the callback from the handler. I will post the entire code so you can get it, ok?
Comment: No problem. Glad to help! If you have any doubts creating your packages, just let me know!
Comment: To dev local just comment the handler part of your code, ok? Just added image showing how to upload a package to lambda.


Looking for documentation on ElasticSearch java node settings in V2

Question: I am unable to locate the documentation as to the settings that i can put in the following Settings instance and what each setting implies to the node client.
<code>Settings settings = Settings.settingsBuilder()
     .put("cluster.name",ESProperties.getInstance().getCacheClusterName())
        .put("http.enabled", "true")
        .put("discovery.zen.ping.multicast.enabled", "true")
        .put("discovery.zen.fd.ping_timeout","60s")
        .build();

Client client = NodeBuilder.nodeBuilder().settings(settings)
        .client(true).node().client();
</code>
Can somebody help me locate those settings documentation?  I am developing common client for our enterprise usage and am badly in need of this listing to make it as a common component.
Answer: Elasticsearch settings are split per module, here's the list of modules :
https://www.elastic.co/guide/en/elasticsearch/reference/current/modules.html
Comment: It did not help me much.  My legacy code has a setting like this:
    .put("plugins.es-plugin.properties", true)
Dont know where to look for the explanation of this.


Somar valor dos nodes childrens ao valor dos parents em array recursivamente

Question: Boa tarde.
Tenho a seguinte estrutura de array abaixo, como somar os valores dos node_value dos nós filhos aos valores node_value dos parents, recursivamente?
Array
    (
    [0] => Array
    (
        [node_id] => 1
        [0] => 1
        [text] => Node A
        [1] => Node A
        [node_value] => 43.5
        [2] => 43.5
        [node_master] =>
        [3] =>
        [children] => Array
        (
            [0] => Array
            (
                [node_id] => 2
                [0] => 2
                [text] => Node B
                [1] => Node B
                [node_value] => 12.4
                [2] => 12.4
                [node_master] => 1
                [3] => 1
                [children] => Array
                (
                    [0] => Array
                    (
                        [node_id] => 5
                        [0] => 5
                        [text] => Node E
                        [1] => Node E
                        [node_value] => 88.9
                        [2] => 88.9
                        [node_master] => 2
                        [3] => 2
                    )
                )
            )
            [1] => Array
            (
                [node_id] => 3
                [0] => 3
                [text] => Node C
                [1] => Node C
                [node_value] => 52.6
                [2] => 52.6
                [node_master] => 1
                [3] => 1
                [children] => Array
                (
                    [0] => Array
                    (
                        [node_id] => 4
                        [0] => 4
                        [text] => Node D
                        [1] => Node D
                        [node_value] => 7.4
                        [2] => 7.4
                        [node_master] => 3
                        [3] => 3
                    )
                    [1] => Array
                    (
                        [node_id] => 8
                        [0] => 8
                        [text] => Node H
                        [1] => Node H
                        [node_value] => 12.8
                        [2] => 12.8
                        [node_master] => 3
                        [3] => 3
                        [children] => Array
                        (
                            [0] => Array
                            (
                                [node_id] => 10
                                [0] => 10
                                [text] => Node J
                                [1] => Node J
                                [node_value] => 90.0
                                [2] => 90.0
                                [node_master] => 8
                                [3] => 8
                                [children] => Array
                                (
                                    [0] => Array
                                    (
                                        [node_id] => 13
                                        [0] => 13
                                        [text] => Node M
                                        [1] => Node M
                                        [node_value] => 18.8
                                        [2] => 18.8
                                        [node_master] => 10
                                        [3] => 10
                                    )
                                )
                            )
                            [1] => Array
                            (
                                [node_id] => 11
                                [0] => 11
                                [text] => Node K
                                [1] => Node K
                                [node_value] => 25.7
                                [2] => 25.7
                                [node_master] => 8
                                [3] => 8
                            )
                            [2] => Array
                            (
                                [node_id] => 15
                                [0] => 15
                                [text] => Node O
                                [1] => Node O
                                [node_value] => 77.0
                                [2] => 77.0
                                [node_master] => 8
                                [3] => 8
                            )
                        )
                    )
                )
            )
            [2] => Array
            (
                [node_id] => 6
                [0] => 6
                [text] => Node F
                [1] => Node F
                [node_value] => 32.1
                [2] => 32.1
                [node_master] => 1
                [3] => 1
                [children] => Array
                (
                    [0] => Array
                    (
                        [node_id] => 7
                        [0] => 7
                        [text] => Node G
                        [1] => Node G
                        [node_value] => 49.7
                        [2] => 49.7
                        [node_master] => 6
                        [3] => 6
                        [children] => Array
                        (
                            [0] => Array
                            (
                                [node_id] => 9
                                [0] => 9
                                [text] => Node I
                                [1] => Node I
                                [node_value] => 19.4
                                [2] => 19.4
                                [node_master] => 7
                                [3] => 7
                                [children] => Array
                                (
                                    [0] => Array
                                    (
                                        [node_id] => 14
                                        [0] => 14
                                        [text] => Node N
                                        [1] => Node N
                                        [node_value] => 2.4
                                        [2] => 2.4
                                        [node_master] => 9
                                        [3] => 9
                                    )
                                )
                            )
                        )
                    )
                    [1] => Array
                    (
                        [node_id] => 12
                        [0] => 12
                        [text] => Node L
                        [1] => Node L
                        [node_value] => 49.7
                        [2] => 49.7
                        [node_master] => 6
                        [3] => 6
                    )
                )
            )
        )
    )
)

Estou tentando chegar a uma função PHP para varrer o array e somar os valores...
Answer: Para que a soma funcione num array tão vasto e aninhado terá que ser recursiva, assim como já indicou na pergunta. O pormenor é que tem de ser feito do fim para o inicio, logo a parte que soma tem que vir obrigatoriamente após a recursão.
Exemplo de implementação desta lógica:
function somaRecursiva(&$arr){

    if (isset($arr["children"])){
        //se este nó tem children, a soma tem de ser calculada e por isso começamos com 0
        $arr["node_value"] = 0;

        foreach ($arr["children"] as $key => $value){ //para cada filho no array children
            //somar o resultado desse filho ao value corrente
            $arr["node_value"] += somaRecursiva($arr["children"][$key]);
        }
    }

    return $arr["node_value"] ?? 0; //retornar a soma para cima
}

Exemplo no ideone


Fatal error: illegal expression while running AFNI bash shell

Question: I want to run the following script in shell
for i in {1..10};
    do
    3dcalc -a COLUMNS.nii -expr 'equals(a, "${i}")' -prefix col_"${i}".nii;
    done

but I am getting errors, COLUMN.nii file is the nifty file with a collection of masks with value ranging from 1 to 10 and I want to separate these masks into individual nifty file using this AFNI command in a for loop.
Comment: The actual *question* is about `bash`, not mask, neuroscience, or neuro-image. http://idownvotedbecau.se/itsnotworking/ - Please c.f. [this page](https://stackoverflow.com/help/asking) for guidelines on asking good questions. (And try `vi`, or even notepad.) ;)
Answer: It seems that you may have edited your code using a word processing program, such as Microsoft Word, which doesn't put "normal" single- and double-quote characters into the file.
In your program the line
3dcalc -a COLUMNS.nii -expr 'equals(a, "${i}")' -prefix col_"${i}".nii;

has those "curly" single- and double-quote characters. Change this to
3dcalc -a COLUMNS.nii -expr 'equals(a, "${i}")' -prefix col_"${i}".nii;

When editing code I recommend that you use a programming-specific editor - there are many out there - rather than a word processing program.
Comment: Mind, I suspect that the OP probably wants _both_ `${i}`s to be expanded, which this answer doesn't accomplish


How do I write a copied value (ctrl + c) to an excel spreadsheet using Python?

Question: Say I use the pyautogui module and use the hot keys to copy a value from a screen (in a database) and I now want to write that value to cell N2 in a spreadsheet how do I go about doing this?
I have used
pyautogui.hotkey('ctrl', 'c')
which has copied a numeric value.
Alternative suggestions also welcomed.
Answer: You can get the copied value from clipboard(windows) using Tkinter
from Tkinter import Tk
clip = Tk()
variable_name = clip.selection_get(selection = "CLIPBOARD")

Reference: How do I copy a string to the clipboard on Windows using Python?
Now open the excel file
pyautogui.hotkey('win','r')
pyautogui.typewrite(<excel_file_location>)
pyautogui.hotkey('enter')

Now we can go to A1 cell first and then we can traverse to any cell we want
pyautogui.hotkey('ctrl','home') # traversing to A1
pyautogui.typewrite(['down'],interval=0.25) # going to A2
pyautogui.typewrite(['tab','tab',..13 times],interval=0.25) # going to N2
pyautogui.typewrite(variable_name,interval=0.25) # entering the copied value


Git: do not pull deletes into branch?

Question: Lead wanted simpler code reviews (PR's). So branched code into 3 branches. A->B->C.
Then deleting code from A. Deleting the additional code so A will be a simpler code review. Then will make a code review for B, and later C.
Since B is branched from A, then I assume I can never do a pull on it. Is this correct?
Similar but not the same question:
How to turn a git branch into fork?
I guess what I should have done is using original code base ABC done this:
<code>ABC->A  (delete B and C stuff. Code review A.)
ABC->BC->B  (delete C stuff and code review B)
BC->C (code review the total. Or ABC->C even.)
</code>
This way changes to ABC could be pulled into A, or B, or C. Correct?
So, given I didn't do that, is there any way to save my code on a Pull or Merge. That is, if I don't Pull into B but do merge B into the EPIC, then will the deletes done in A be applied (not what I want). Or perhaps if I touch every file deleted in A while working on B and C will that save my files and prevent them being deleted on Merge. Afraid I might get burned here. What's the way out? (besides starting all over.)
Comment: Not sure this even makes sense, at least in part because you seem to have some confusion between the concept of a "commit" and a "branch"...
Answer: Don't understand the method behind the madness... Why not create a remote branch and get the team to push and pull from the remote branch. When your lead is happy with code then merge to master.
Comment: We do. But he wanted each task (JIRA issue) to be only a few files of changes/adds. So, break down into smaller tasks/branches. If that makes sense.

Git: do not pull deletes into branch?


Let S be a dense set in the reals. Prove that every real number is the limit of a sequence in S.

Question: Let S be a dense set in the reals. Prove that every real number is the limit of a sequence in S. I know I am supposed to consider S intersected with $(x-$ $1 \over n$, $x)$ for $n\in \mathbb N$, for a given $x \in \mathbb R$.
Comment: What does it mean to you for a set to be dense?
Comment: If a set S is dense in R, then it means that for all real a<b, there exists an x in S s.t. a<x<b
Comment: So for $x \in \mathbb{R}$ and each $n$ there's a point $x_n$ in $S$ satisfying $x - \frac{1}{n} < x_n < x$.  Then $\lim_{n \to \infty} x_n$ = ?
Answer: Take any sequence $s_n \in S$ with $s_n \in (x-\frac{1}{n},x)$ for each n. What does $s_n$ tend to?
S being dense means that there is always some element of $S$ in any interval, so certainly there's an element of $S$ in $(x-\frac{1}{n},x)$ so we know that we can make such a sequence.
Comment: Would s_n tend to x?
Comment: Yes, can you think why?
Comment: Because any sequence in that interval would be bounded above and below by the values either side of the interval?
Comment: Yes, that's true, so what bound can we put on $|s_n - x|$?
Comment: Can we choose an epsilon greater than 0, and say that that is less than epsilon?
Comment: @Mathlete We can if we choose $n$ large enough. We say that $s_n \rightarrow x$ if $|s_n - x| \rightarrow 0$ as $n \rightarrow \infty$. Since $s_n \in (x - \frac{1}{n}, x)$, $|s_n - x| <\frac{1}{n}$. Hence for any $\epsilon > 0$ picking $N$ such that $N > \frac{1}{\epsilon}$ we have that for all $n \geq N$, $|s_n - x| < \frac{1}{n} < \frac{1}{N} < \epsilon$. Hence $|s_n - x| \rightarrow 0$ so $s_n \rightarrow x$. Does that help?
Comment: I completely understand that now, thanks.
Comment: Great, glad to help!


Do I have to cite 'lme4' when using 'lmerTest'?

Question: I am using lmerTest to run linear mixed models (LMM) to get the p-values. However, in the articles I have written, they will show both lme4 and lmerTest. Then I am not sure if I also have cite lme4 when I use only lmerTest to run LMM models.
Do you have any idea about this?
Answer: lmerTest basically offers a bunch of convenience functions on top of lme4. The actual important software is lme4, which implements the model framework. You should definitely give the reference for lme4 as specified in citation("lme4"):

Douglas Bates, Martin Maechler, Ben Bolker and Steven Walker (2014).
  lme4: Linear mixed-effects models using Eigen and S4. R package
  version 1.0-6. http://CRAN.R-project.org/package=lme4

This is not only important for giving well deserved attribution, but also to state the lme4 version number.
Comment: @AdamO I believe that point is valid for most software tools. There were well known bugs in Excel for years and I don't think Microsoft reimbursed anyone.
Comment: +1, wholeheartedly agree with giving version number. In my field this is often neglected.
Comment: +1 and a 3rd possibly important reason to cite the package is that R comes with ABSOLUTELY NO WARRANTY. So, even though we are fairly confident the algorithm is correct, we need to make the methods transparent so that, should any well understood peculiarity arise in the future, we can retrospectively ascertain the validity of your results now.
Comment: Okay. So I will cite both lme4 and lmerTest. Thanks very much Roland.
Comment: @NickStauner Thank you for your suggestion. Sorry for haven't done this for many questions I have posted as I am very new to this website, but now I know that I can do it. (I always wonder who people give me vote and how I can vote for other people)


What if a non-random sample is identical to a random sample?

Question: Sometimes, in political polls, pollsters take non-random samples from a given population, but then they apply the results of the theory of random sampling to their non-random sample. I've heard someone (not a statistician) argue that this is still valid procedure because the non-random sample obtained is one of the possible random samples.
In fact, suppose the following happens: Researcher 1, through some non-random sampling method, selects individuals A, B, C. Researcher 2 makes use of random sampling, and obtains the same sample A, B, C. Both apply random sampling theory to analyse their sample. What's the difference? What makes researcher 1 wrong?
Thoughts
My only thoughts abouts this, at least so far, is that what makes the random sample theoretically valid is the procedure that random sampling dictates, and not the particular sample obtained.
If that wasn't the case, you could fix basically any sample you want (say, a sample of 3000 white, 24-year-old, college-educated women), then claim that this sample is okay to use because it is one of the possible random samples of 3000 people of your population.
Comment: Its not the fact of the specific  sample that impacts the properties we're worried about but the behaviour of the process that produced it.
Comment: Dilbert: https://dilbert.com/strip/2001-10-25
Comment: That claim in the second sentence of the first paragraph is 100% wrong.    I suspect the non-educated reasoning behind that claim is similar to those who  insist that it makes zero difference whether you switch or not in the Monte Hall Problem
Comment: Let's say that there are 100 voters. Researcher 1 cherry picks three voters. Researcher 2 does a random sampling and happens to pick the same three voters. It could happen, but the odds are very very small. 3/100 x 2/99 x 1/98 = 6 x 10^(-6), so roughly 6 times in a million tries. That is just the way that statistics works. A sample is just that a sample.
Comment: and xkcd: https://xkcd.com/221/
Answer: Play poker with your friend, bet a lot of money, and cheat to give yourself a royal flush (it beats every other hand).
"That's cheating!"
"Nah, it's one of the possible hands. Pay up."
Yes, it's about the procedure.
(Don't actually do the poker trick, but I think it makes the point.)
Answer: A particularly biased / non-representative sample is unlikely if you sample randomly.
In an ideal world you'd have a non-random sample which perfectly accurately represents the population such that the proportion of every demographic is the same in the sample as it is in the population as a whole.
This is pretty hard problem to solve in the real world though (to say the least), as you'd need to understand every demographic and how it affects your results. You might say "white, 24-year-old, college-educated women" is specific enough and you just need to make sure your sample has the right proportion of such people (and similarly for every other similar demographic), but they may be more or less likely to act in a certain way based on where they live, where they studied, where they grew up, their religion and many other factors. So you need to take all of that into account too. That'll be a whole lot of work, and in the process you'll probably answer your original query anyway without ever using the sample you generated. Basically doing that just doesn't make a whole lot of sense.
In the real world a random sample is a "good enough" attempt to obtain an accurate representation of the population.
Now it is indeed possible to get a random sample that doesn't reflect what the population as a whole looks like particularly well (i.e. a "biased" sample).
But the probability of getting any given sample when sampling randomly decreases significantly as the sample becomes more biased and a less accurate representation of the population as a whole. This applies especially when you have larger samples.
This is acceptable since statistics is generally about having high confidence of being correct rather than having absolute certainty.
Think of it this way: if 70% of your population is women and you randomly pick one person, you have a 70% chance of picking a woman. So you would expect roughly 70% of your random sample to be women. The maths might not work out to exactly 70% in all cases, but that's the general idea. So the sample proportions should roughly correspond to the proportions of the population as a whole. You should be rather surprised if your sample somehow ends up with 0% women.

There could also be issues depending on how you obtain a random sample. If you want to sample from everyone living in a country, you could, for example, get a random subset of registered voters or people with driver's licences. But then your sample would be heavily biased towards people who are registered to vote or have driver's licences.
This may also lead to a partially random sample where you combine differently-sized random samples from different sources such that the end result is more representative of the population as a whole. Although I'm not sure whether and how often this is done in practice. Finding a single data source for the entire population would be preferable.
But that's a whole other question.
Comment: I believe in opinion polling, it's common to use a partially random sample as you describe. Part of the reason is to attempt to counter selection bias - running a phone poll, you only reach people who answer their phone, which will be skewed towards some demographics more than others, so some samples are weighted higher than others to try to compensate.
Answer: The central issue that has not been explicitly addressed, is that when sampling is correctly performed (randomness being one criterion), the resulting sample is a faithful representation of the underlying distribution of the population being sampled.  This is what allows us to make a meaningful inference about the population from the sample.
When a sample is not chosen at random, depending on how it is chosen, any resulting inference is distorted because the sample is no longer necessarily representative of the likelihoods of the outcomes that were observed.
It is important to phrase it this way because non-random sampling does not imply that rare or unlikely outcomes are overly represented.  You could, for instance, always select the mode of a binomial random variable--this is clearly not random.  And it still violates the notion that the sample represents the population.
Answer: This illustrates the unidirectionality of conditional probabilities. Given a particular a sample and a hypothesis with well-defined probabilities, we can say with confidence what the probability, given the hypothesis, of seeing the sample. But in frequentist statistics, we cannot say what the probability, given the sample, of the hypothesis is.
That the sample is taken randomly is usually not explicitly stated as part of the null hypothesis, but it is always implicitly part of it. When we reject the null, we reject all of the null. And remember that the negation of a statement with "and" turns into a statement with "or". So if the null is "the sample is drawn from a distribution that is normal and the mean is $\mu$ and the standard deviation is $\sigma$ and the samples are independent of each other, and ..." then rejecting the null means that we believe that ""the sample is not drawn from a distribution that is normal or the mean is not $\mu$ or the standard deviation is not $\sigma$ or the samples are not independent of each other, or ..." It's only by eliminating the possibility that the sample was cherry picked that we can definitively conclude that one of the other possibilities holds.
For a Bayesian perspective, this shows the importance of updating not only on your knowledge but also on your meta-knowledge. That is, not only what you know, but how you know it. Much of the controversy surrounding the Monty Hall problem comes from the ambiguous nature of the metaknowledge. If the host always randomly picks from the two unchosen doors and shows what's behind it, then switching doesn't help your odds. But if the host always picks a door with a goat and opens it, then switching does help your odds.
Another puzzle is "Suppose you know a particular woman has two children, and you know that one of her children is a boy. What's the probability that she has two boys?" The answer depends on how you know that one of her children is a boy. If you asked whether her older child is a boy, and she said yes, then the probability is 1/2. But if you asked her whether any of her children are boys, and she said yes, then the probability is 1/3.
Answer:
Sometimes, in political polls, pollsters take non-random samples from a given population,

This is a bit ambiguous. Very often samples are not completely randomised and there are some selection biases. But still, the results from this non-random selection might be in some way random.
The question is by how much the selection effect and the related bias is negligible.
A poll among your close friends is not a good representation. Neither is a poll on some website. However a polling organisation that selects a representative mixture of the population is probably gonna get close to the true answer.
The selection by the polling agency might be random or not, that doesn't really matter.
Urn example
Say there are 100 urns labeled $i,j$ with $1\leq i\leq25$ and $1\leq j \leq 4$.
The urns contain blue and red balls with fractions that are determined by a random process. The random process is likely depending on $j$ but not so much on $i$.
We want to know the fraction of red and blue balls in the total of all urns.
Say that we can only sample twelve of those urns due to limitations of resources. We can randomize our samples in different ways:

We could make a random selection out of the 100 urns, but we could also decide to fix our pick (non randomly) to 3 urns out of each of the 4 $j$ categories.
We could randomly select 3 $i$ out of each $j$ but we could also select some specific $i$ (because it might be more convenient).

All these non-random choices introduce potential bias. But that bias might be negligible if we consider that the intentional choices have only a small effect on bias.
Also note that in the end the sampling process is still giving a random variable (but only biased random). We might have selected some urn labels $i$ non randomly, but how the balls got inside the urns is still a random process, a random value.
The issue with non randomised sampling methods is not that the outcome variable is not random, but that the outcome variable might be biased.
E.g. that poll among your friends is still a random variable.