How can i sort an array ascending rather than random

Question: I found this awesome snippet online.
It shows a new testimonial at random on refresh of the page and am wondering how to show the array in an ascending order rather than random?
$target = sort(0, $num-1);

^ This was my attempt
<?php
    /*
    --------------------------------------------
    Random Testimonial Generator Created by:
    Ryan McCormick
    Ntech Communications
    Website: http://www.ntechcomm.com/
    Blog: http://www.ntechcomm.com/blog/
    Twitter: @ntechcomm
    --------------------------------------------
    */

    //Start Array
    $testimonials = array();
    $testimonials[0] = "Testimonial 1";
    $testimonials[1] = "Testimonial 2";
    $testimonials[2] = "Testimonial 3";
    $testimonials[3] = "Testimonial 4";
    //Automate script by counting all testimonials
    $num = count($testimonials);
    //randomize target testimonial
    $target = rand(0, $num-1);
    /*
    To display testimonials on site
    --------------------------------------------
    place the following code in the
    display area:
    <?php echo $testimonials[$target]; ?>
    --------------------------------------------
    Use a PHP include to use this code on your
    target page.
    */
    ?>

Output the testimonial in page with:
<?php echo $testimonials[$target]; ?>

To clarify:
The code i posted displays one testimonial randomly on refresh of the page. I would like it to keep this function and display only one at a time but I want them to display in the order they are added.
Comment: don't use `rand()`, in that case?
Answer: Sort using ascending order
$testimonials = array();
$testimonials[0] = "Testimonial 1";
$testimonials[1] = "Testimonial 2";
$testimonials[2] = "Testimonial 3";
$testimonials[3] = "Testimonial 4";

$random  = rand(0, count($testimonials) - 1);
$asc_arr = sort($testimonials);
print_r($result);

Comment: where would i place this or what would this replace?
Comment: tried this like `$target = sort($testimonials, $num-1);` but its not showing a new testimonial on refresh?
Comment: no. directly do it like this `sort($testimonials);` No need to assign it in other variables.
Comment: Thanks, this outputs all the testimonials. The code i posted displays one testimonial randomly on refresh of the page. I would like it to keep this function (only one at a time) but show the testimonials ascending in order.
Comment: Would love to but it hasn't answered my question.
Comment: is it needed in your output?
Comment: indeed, the current output (which is also part of the above snip) is ``
Answer: You can use sort() to sort an array's values in ascending order. Here's the documentation for it.
http://php.net/manual/en/function.sort.php
Basically, you can use it like this:
$myarray = array('aa', 'bb', 'abc', 'cde', 'az');
sort($myarray);
var_dump($myarray);

In addition (because of the "The code i posted displays one testimonial randomly on refresh of the page. I would like it to keep this function and display only one at a time but show the testimonials ascending in order" clarification added by OP):
If you want to display just one testimonial per page load, then you'll need to retain the last array index on each page load. If it's just whenever the page is refreshed, then you can use a session variable. Something like this:
session_start();
if (!isset($_SESSION['cur_index'])) { $_SESSION['cur_index'] = 0; }
$target = $_SESSION['cur_index'];
// Prepare for the next index when the page is refreshed.
$_SESSION['cur_index']++;
// If the index goes pass the array's limit, then go back to index 0.
if ($_SESSION['cur_index'] >= count($testimonials)) {
    $_SESSION['cur_index'] = 0;
}

That will update the $target variable to the next index based off of the previous index.
Comment: Thanks for your answer, I'm not quite sure how to use this ^ PHP is still a bit of a mystery to me.


Proof that $1-\frac{1}{e}\sum_{k=0}^{n} \frac{1}{k!} \leq \frac{1}{n!}$ for $n \in \mathbb{N}^*$

Question: For $n \in \mathbb{N}^*$, consider the function $f_n(x)=e^{-x}\sum_{k=0}^{n} \frac{x^k}{k!}$ over $[0;1]$.
I have to prove the following inequality : $\forall n \in \mathbb{N}^*:0 \leq f_n(0)-f_n(1) \leq \frac{1}{n!}$. By taking the derivative and showing the function is decreasing over $[0;1]$, I am able to prove the LHS, however I struggle to prove the RHS... How would you do?
Edit: The point of this question is to then prove the convergence of the infinite serie $\sum_{k=0}^{\infty} \frac{1}{k!}$ to $e$, which means such a result is not supposed to be used.
Comment: Try to show it by induction.
Answer: Proof without induction :
One has $$e- \sum_{k=0}^n \dfrac{1}{k!} = \sum_{k=n+1}^{+\infty} \dfrac{1}{k!} = \sum_{k=0}^{+\infty} \dfrac{1}{(k+n+1)!} \quad \quad (*)$$
But for every $k \geq 0$, one has $$\dfrac{(k+n+1)!}{(n+1)!k!} = {k+n+1 \choose n+1} \geq 1, \quad \text{so} \quad \dfrac{1}{(k+n+1)!} \leq \dfrac{1}{(n+1)!k!}$$
Then $(*)$ becomes $$e- \sum_{k=0}^n \dfrac{1}{k!} \leq \sum_{k=0}^{+\infty} \dfrac{1}{(n+1)!k!} = \dfrac{e}{(n+1)!}, \quad \text{i.e.} \quad \boxed{1- \dfrac{1}{e}\sum_{k=0}^n \dfrac{1}{k!} \leq \dfrac{1}{(n+1)!}}$$
(which is a little bit more precise than the inequality you want to prove).
Comment: See my edit, I cannot use the fact that $e=\sum_{k=0}^{\infty} \frac{1}{k!}$ (my fault, I should have mentioned it before)
Comment: If you cannot, what is your definition of $e$ ??
Comment: I just finished high-school, and here in France, $e$ is taught as equal to $exp(1)$, with $exp$ being the exponential function, defined as the unique solution of the differential equation $y'=y$ satisfying the initial condition $y(0)=1$. Other definitions such as this infinite series are not seen until higher education.
Answer: The most straightforward proof uses Lagrange error bound for the Maclaurin series for $x \mapsto e^x$.
This bound shows us that $|e - \sum\limits_{k = 0}^n \frac{1}{k!}| \leq \frac{e}{(n+ 1)!}$. We can drop the absolute value sign to conclude $e - \sum\limits_{k = 0}^n \frac{1}{k!} \leq \frac{e}{(n+ 1)!}$.
Then dividing both sides by $e$, we have $1 - \frac{1}{e} \sum\limits_{k = 0}^n \frac{1}{k!} \leq \frac{1}{(n + 1)!} \leq \frac{1}{n!}$.
Comment: I'm afraid those concepts are unfamiliar to me... My question is supposed to be solved using "basic" calculus.
Comment: @LucasMartiniano I would call the Lagrange error basic since it is typically covered in AP calculus, but perhaps I overstate the simplicity of it. At any rate, it is quite easy to prove the Lagrange error bound is correct, and many of the other proofs I'm seeing simply take that proof and apply it to the particular case you've presented.
Answer: I think I got the most elementary proof of the result. We want to prove that
$e-\sum_{k=0}^{n}\dfrac{1}{k!}\leq e\dfrac{1}{n!}$
which is,  $\,\,\,\sum_{k=n+1}^{+\infty}\dfrac{n!}{k!}\leq\,e\,\,$ i.e.
$\dfrac{1}{n+1}+\dfrac{1}{(n+1)(n+2)}+\dfrac{1}{(n+1)(n+2)(n+3)}+...\leq\,e$.
We observe that $\dfrac{1}{(n+1)(n+2)}\leq\,\dfrac{1}{(n+1)^{2}} , \dfrac{1}{(n+1)(n+2)(n+3)}\,\leq\,\dfrac{1}{(n+1)^{3}},$ e.t.c.
so we obtain a geometric series $\dfrac{1}{n+1}(\dfrac{1}{1-\dfrac{1}{n+1}})$=$\dfrac{1}{n}\,\leq\,e$  and the result is proved!!
Comment: My question is taken from a high-school exercise book, hence Taylor's theorem cannot be used, which is why I accepted Frederico's answer.
Comment: See my edit, I cannot use the fact that $e=\sum_{k=0}^{\infty} \frac{1}{k!}$ (my fault, I should have mentioned it before)
Comment: It is very easy to prove this, Define $f_{n}(x)=1+x+\dfrac{x^{2}}{2!}+....+\dfrac{x^{n}}{n!}$ and use Taylor's theorem with a remainder. Then $e^{x}=f_{n}(x)+\dfrac{e^{\xi}}{(n+1)!}x^{n+1}$. So on any closed bounded set $sup|e^{x}-f_{n}(x)|$=sup$|\dfrac{e^{\xi}}{(n+1)!}|$$|x^{n+1}|$ and the latter $\to 0$ on closed bounded sets! So$ f_{n}(x)\to e^{x}$ uniformly and hence $\sum_{0}^{+\infty}\dfrac{1}{k!}=e$ setting $x=1$
Answer: Taking the derivative, we have
$$
f_n'(x) = - e^{-x} \sum_{k = 0}^n \frac{x^k}{k!} + e^{-x} \sum_{k=1}^n \frac{x^{k-1}}{(k-1)!} = - e^{-x} \sum_{k = 0}^n \frac{x^k}{k!} + e^{-x} \sum_{k = 1}^{n-1} \frac{x^k}{k!} = -e^{-x} \frac{x^n}{n!} \leq 0
$$
for any $x \in [0,1]$.
Thus, as you noticed, the function is decreasing in $[0,1]$, and you get $f_n(0) \geq f_n(1)$.
Now, from the mean-value theorem there exists $c \in [0,1]$ such that
$$
f_n(0) - f_n(1) = -f_n(c)' = e^{-c} \frac{c^n}{n!} \leq e^{-1} \frac{1}{n!} \leq \frac{1}{n!}
$$
Edit: For completeness, the inequality $e^{-c} \frac{c^n}{n!} \leq e^{-1} \frac{1}{n!}$ follows from the fact that $g(x) = e^{-x} \frac{x^n}{n!}$ is an increasing function for $x \in [0,1]$, as
$$
g'(x) = -e^{-x} \frac{x^n}{n!} +  e^{-x} \frac{x^{n-1}}{(n-1)!} = e^{-x}x^{n-1}\frac{n - x}{n!} \geq 0
$$
Comment: Clever use of the MVT, thank you!


Dealing with async function doing sync work

Question: So I have an interface that defines some function including this
Task DoWork();

The problem is that some of the class implementing this interface does not need to do work asynchronously so my current solution is returning Task.CompletedTask after doing some synchronous work.
The question is: Am I doing it in a wrong way, I feel that having an async function doing sync work is kind of wrong
Comment: Strictly technical, this is fine. It won't cause any issues. It just becomes an issue with readability and preferred convention for your implementations.
Comment: There is a slight difference in error handling, which might make it desirable to use `async` even if you're not doing asynchronous work (https://stackoverflow.com/a/56490137/120955). Then again, returning Task.CompletedTask is going to have slightly better performance. So there's not a single right answer here.
Answer: It may feel wrong - it may even BE wrong, but the wrongness is not on your side.
If a method is defined as returning a Task, then this is either you implementing a special case of the method that in this particular case does not have to be async... or it is simply that the definition of the method is wrong and it should not return a Task.
THIS is the semantical challenge. But you implementing it as Task.CompletedTask is just you following in this case the semantics as lined out, as per the C# specifications, actually.
With a concrete example we could discuss whether the method SHOULD return a Task or not... but generally: This happens. Why you think Task.CompletedTask exists?
Comment: The `Task.CompletedTask` exists for the case where no work has to be done.
Comment: No, Task.CompletedTask exists also for cases when there is work, but it can be done synchronous, so there is no need for the task to be awaited for. This may be that the method in this particular implementation (of an interface) can do it sync, or for code paths that are not io bound. There is no requirement for not work to be done for using it. I have plenty of code where you call a method, and under some circumstances you get back a completed task immediately (while under other parameters you may have to await the results).
Comment: *"Why you think Task.CompletedTask exists?"* I assume that no one here has internal knowledge about the design goals behind the introduction of this API. Also just because an API exists, is not by itself a justification for using it. Otherwise we would all use `ArrayList`s and `SecureString`s every day.
Comment: " I assume that no one here has internal knowledge about the design goals behind the introduction of this API." - except the team actually talked about it on their blog.
Comment: Could you post the link?
Comment: Nope. This is ancient and MS reorganized all the development blogs. The next time things came up was with the introduction of ValueTask... https://devblogs.microsoft.com/dotnet/understanding-the-whys-whats-and-whens-of-valuetask/ or https://devblogs.microsoft.com/dotnet/async-valuetask-pooling-in-net-5/ but the older blogs are simply gone these days.
Answer: If your usage of the interface requires the operation be async-friendly, then no it's not wrong. Task.CompletedTask was made available as part of the C# language for a reason. It's important to reflect on usages of it and whether you're really doing something wrong or just conforming to the contract defined by your interface, which you seem to be doing by asking this question.
If you find yourself repeating this pattern often in your interface implementations then perhaps that's an opportunity to rethink your architecture: why you have interfaces that sometimes run synchronously and sometimes run asynchronously and how you can better design a system that handles a concrete implementation that needs to do work asynchronously versus a concrete implementation that doesn't need to run asynchronously.


Programmatically set URL Alias when creating node in form plugin

Question: I'm currently importing data from a database to create nodes based on them. My node save code looks like this
<code>$node = \Drupal\node\Entity\Node::create([
        'type'                 => 'issue',
        'title'                => $title,
        'body'                 => $body,
        'field_issue_category' => $term,
        'field_issue_type'     => 'publication',
        'field_pub_id'         => [
            'target_id'           => $publication_id,
        ],
        'field_issue_group' => $group_id,
        'field_date'        => $date,
    ]);
$node->save();
</code>
I also want to create a url alias based on the title of this node, which I create like this,
<code>$nid       = $node->id();
$title     = preg_replace("/[\s_]/", "-", $title);
$path      = \Drupal::service('path.alias_storage')->save('/node/'.$nid, '/mypath/'.$title);
</code>
This successfully create a url alias that shows up in the URL aliases list in the URL alias config. However it doesn't show up in the URL alias field on the node edit page.

This creates a problem. One, the user can't see what the actual alias is.
Also I have a block plugin that puts every node of that type in a list on a page. It also displays the url to that node. I'd like the url displayed to be the alias like '/mypath/title' but Drupal only seems to know about the '/node/nid' path.
Is there a proper way to programmatically set a nodes url alias so that it still appears in the url alias field?
Answer: The node widget currently only shows aliases that have the same langcode as the node. https://www.drupal.org/node/2511968 will change that and also display aliases without a specific language.
But if the alias also doesn't work on the site then that sounds like something else also isn't correct yet. Does it work in that block if you create an alias manually in the UI? If so, compare the two records in the url_alias table, do you see a difference?
You can create an alias as part of saving the node, there is a path pseudo/computed field. Try adding this to your array:
<code>'path' => [
  'alias' => '/mypath/' . $title,
  'pathauto' => PathautoState::SKIP,
]
</code>
That should create the alias correctly as well.
And last, if your alias is so predictable, you should look at Pathauto. That allows you to set up rules for creating aliases. Among other things, it has a ton of logic to deal with special characters and duplicates, your code will have a problem if you have two nodes with the same title, for example.
Comment: Yeah, having valid PHP helps. Fixed in my answer.
Comment: Use  `'path' =>  ['alias' => '/mypath/' . $title,  'pathauto' => Drupal\pathauto\PathautoState::SKIP]` to skip pathauto generation.
Comment: looks like the issue was that it needed to be 'alias' => '/mypath/' instead of 'alias' > '/mypath/
Comment: Does pathauto work when a node is being created programmatically?
Comment: Yes, should work fine, it works with entity hooks
Comment: I'm receiving an error 'Alias path 1 has to start with a slash' even though I'm using 'path' => ['alias' > '/publications/convention-proceedings/'.$title_cut]


What is the reason for the name *left* coset?

Question: Let $G$ be a group and let $H \leq G$ be a subgroup. It seems that it is now standard to call the cosets
$$gH=\{gh \ | h \in H \}$$ the left cosets of $H$ in $G$. I have to admit to being slightly annoyed with this convention: these are the orbits for the right action of $H$ on $G$. Therefore I am perpetually tempted to refer to them as right cosets. Is there a second good reason (I happily admit convention is a very good reason) for calling these left cosets? (The fact that the "g" is written on the left does not count, as far as I am concerned).
Comment: It may not count, but it's obviously the reason for the terminology.
Comment: The element $g$ is multiplying on the **left**. Isn't that enough for you?
Comment: During the Algebra course in my freshman year, I was told that what we called *left coset* was also called *right coset* by some people.
Answer: Don't think of them as the orbits of the right action of $H$ on $G$. The set of left cosets itself admits a natural left $G$-action, and every transitive left $G$-action arises in this way.


How to center the ".input-group-btn" in bootstrap?

Question: How to center the bootstrap input-grop?
Here is the jsfiddle: http://jsfiddle.net/Qs4T9/
I would like to make the input-grpup in the center of the row, but without manually calculating all that offsets. Would be better if it would be something like .text-center, display: table, display: table-cell or similar.
Here is an "answer" [ Centering Bootstrap input fields ], but it's not a really centering, looks more like just a workaround for the concrete elements and the sizes, not a general solution (at least for the whole non-mobile scheme).
Answer: It looks like the class .col-xs-6 is set to float:left;
If you remove that and add:
margin-left:auto;
margin-right:auto;

instead, it should solve your problem!
Comment: nope, doesn't work (if I remove the `.col-xs-6` it becomes full-width (i.e. block)). could you edit the jsfiddle I posted?
Comment: I didn't say remove col-xs-6! Just remove the float value for it, but since col-xs-6 is built-in bootstrap css, you have to override it like so: [jsfiddle](http://jsfiddle.net/Qs4T9/2/)


Divs não aparecem com display: block e efeito rollover não funciona

Question:

 $(document).ready(function(){

  $("img.menuAdmin").click(function(){
   $(this).css("display","none");
   $("div.menuAdmin div.dropdown").css("display","block");
   $("div.menuAdmin div.dropdown span").css("display","block");
   $("div.menuAdmin div.dropdown div.dropdown-content").css("display","block");
   $("div.menuAdmin div.dropdown div.dropdown-content span").css("display","block");
  });

 });
 @import url('http://fonts.googleapis.com/css?family=Open+Sans');
 * {
  margin: 0;
  padding: 0;
  border: 0;
  outline: none;
 }
 html {
  font-family: 'Open Sans';
 }
 img.menuAdmin {
  display: block;
 }

 div.menuAdmin {
  display: none;
  width: 1000px;
  margin: 0 auto;
 }

 div.menuAdmin div.dropdown {
  position: relative;
  display: inline-block;
  background-color: #CCC;
  vertical-align: middle;
 }

 div.menuAdmin div.dropdown:hover {
  background-color: #A9A9A9;
 }

 div.menuAdmin div.dropdown span {
  display: block;
  width: 190px;
  height: 60px;
  line-height: 60px;
  cursor: pointer;
  text-align: center;
  vertical-align: middle;
 }

 div.menuAdmin div.dropdown span.last-child {
  line-height: 30px;
 }

 div.menuAdmin div.dropdown-content {
  display: none;
  position: absolute;
  width: 200px;
  z-index: 1;
  background-color: #F9F9F9;
 }

 div.menuAdmin div.dropdown:hover div.dropdown-content {
  display: block;
        transition: transform .4s ease;
 }

 div.menuAdmin div.dropdown:hover div.dropdown-content p {
  width: 195px;
  height: 40px;
  line-height: 40px;
  padding-left: 5px;
  border: 1px rgba(0,0,0,.1) solid;
 }

 div.menuAdmin div.dropdown:hover div.dropdown-content p:hover {
  background-color: #CCC;
  cursor: pointer;
 }

 @media screen and (min-width: 0px) and (max-width:620px) {
  img.menuAdmin {
   display: block;
  }
  div.menuAdmin,
  div.menuAdmin div.dropdown,
  div.menuAdmin div.dropdown span,
  div.menuAdmin div.dropdown div.dropdown-content,
  div.menuAdmin div.dropdown div.dropdown-content p {
   display: none;
   width: 100% !important;
  }
 }

  Home

  Célula

  Cadastros

Membro

Administrador

Gcéu

Membro no Gcéu

Mensagem

Estudo

  Edições

Membro

Administrador

Gcéu

Membro em Gcéu

Mensagem

Estudo

  Lançamentos e Relatórios

Reunião no Gcéu

Relatórios

E-mails

Tenho 2 dificuldades com esse código:
A) Quando clico no imagem img.menuAdmin, ela se esconde como era de se esperar, mas o div.menuAdmin não aparece.
B) Quando clico em algum ítem do menu, suas opções abrem como era de se esperar, mas o efeito de abrir rolando não ocorre.
Comment: Esse B) esse efeito de abrir rolando, eu não entendi  bem.
Comment: então, é assim: Quando passo o mose sobre um ítem de menu ele abre uma lista com as opções. Certo? Mas isso abre instantãneo. Gostaria que abrisse lentamente. Tipo um efeito de rollover.
Answer: Creio que com CSS você não consiga esse efeito rollover porque teria que definir um height fixo no elemento, ou seja, se o elemento tivesse um height fixo, seria possível apenas com CSS usando transition. Mas você pode usar os métodos .slideDown() e .slideUp() do jQuery, que faz a mesma coisa com o elemento independentemente do seu height.
É só usar dois eventos, mouseenter e mouseleave, do método .hover() na div:
$("div.menuAdmin div.dropdown").hover(
   function(){ // mouseenter
      $("div.dropdown-content", this).slideDown();
   }
   ,function(){ // mouseleave
      $("div.dropdown-content", this).slideUp();
});

Sobre o menu não estar aparecendo, é porque você não mostrou ele no seu código (apenas alguns elementos filhos que não estão ocultos). Neste caso, basta este código e não aquele enorme que você colocou:
$("img.menuAdmin").click(function(){
   $(this).hide();
   $("div.menuAdmin").show(); // mostra o menu
});

Veja funcionando (note a parte comentada no CSS que não é necessária):
EXECUTE EM TELA CHEIA

$(document).ready(function(){

   $("img.menuAdmin").click(function(){
      $(this).hide();
      $("div.menuAdmin").show();
   });

   $("div.menuAdmin div.dropdown").hover(
      function(){
         $("div.dropdown-content", this).slideDown();
      }
      ,function(){
         $("div.dropdown-content", this).slideUp();
   });

});
@import url('http://fonts.googleapis.com/css?family=Open+Sans');
 * {
  margin: 0;
  padding: 0;
  border: 0;
  outline: none;
 }
 html {
  font-family: 'Open Sans';
 }
 img.menuAdmin {
  display: block;
 }

 div.menuAdmin {
  display: none;
  width: 1000px;
  margin: 0 auto;
 }

 div.menuAdmin div.dropdown {
  position: relative;
  display: inline-block;
  background-color: #CCC;
  vertical-align: middle;
 }

 div.menuAdmin div.dropdown:hover {
  background-color: #A9A9A9;
 }

 div.menuAdmin div.dropdown span {
  display: block;
  width: 190px;
  height: 60px;
  line-height: 60px;
  cursor: pointer;
  text-align: center;
  vertical-align: middle;
 }

 div.menuAdmin div.dropdown span.last-child {
  line-height: 30px;
 }

 div.menuAdmin div.dropdown-content {
  display: none;
  position: absolute;
  width: 200px;
  z-index: 1;
  background-color: #F9F9F9;
 }

 /*div.menuAdmin div.dropdown:hover div.dropdown-content {
  display: block;
     transition: all 1s ease;
 }*/

 div.dropdown-content p {
  width: 195px;
  height: 40px;
  line-height: 40px;
  padding-left: 5px;
  border: 1px rgba(0,0,0,.1) solid;
 }

 div.menuAdmin div.dropdown:hover div.dropdown-content p:hover {
  background-color: #CCC;
  cursor: pointer;
 }

 @media screen and (min-width: 0px) and (max-width:620px) {
  img.menuAdmin {
   display: block;
  }
  div.menuAdmin,
  div.menuAdmin div.dropdown,
  div.menuAdmin div.dropdown span,
  div.menuAdmin div.dropdown div.dropdown-content,
  div.menuAdmin div.dropdown div.dropdown-content p {
   display: none;
   width: 100% !important;
  }
 }

  Home

  Célula

  Cadastros

Membro

Administrador

Gcéu

Membro no Gcéu

Mensagem

Estudo

  Edições

Membro

Administrador

Gcéu

Membro em Gcéu

Mensagem

Estudo

  Lançamentos e Relatórios

Reunião no Gcéu

Relatórios

E-mails

Comment: Oi, obrigado pela aula. Mas ainda tem um problema. Quando passo o mouse, as opçoes se abrem para aqule item de menu beleza. Mas quando você deixa (mouseleave  e escolhe outro ítem de menu, às vezes, o item que voce deixou continua abertas as suas opços porem perde o style. Verifica aí, e às vezes fixam os 3 menus abertos]
Comment: Fiz uma alteração no jQuery, agora usando `.hover()`... testando aqui não detectei os menus ficarem abertos ao mesmo tempo. Veja se agora isso ainda acontece. Quando aos estilos do menu, era só tirar o `:hover` no CSS que afetava os ``.
Comment: muito obrigado!


Pass Webform Submission Back to Form Template

Question: I'm trying to use a webform to accept data, do some processing and calculation, and pass it back to the user. For user-friendly purposes I don't want to redirect to a confirmation page, but back to the form page so they can enter the information again. So essentially, I want the form template to submit back to itself, and if it has received a submission, print out the results (for now). I'm having trouble finding a way to do this.
I have an override template (webform-form-9.tpl.php) in my theme folder and it is successfully overriding the default, however I can't find any any way to actually get the values the user just submitted - even printing all available variables doesn't display the submission. I can't even seem to check if the user submitted a form or not. Does the form template not even receive the submission data? That seems extremely peculiar if so, so I can only imagine I'm not just not getting it right.
Any advice here?
Comment: So I've managed to get the data displaying on the form template by redirecting the form to a custom URL consisting of the current URL (the form template) and the sid of the submission, then getting the submission data through nid and sid. But I still want to keep the form populated with the info they entered, whereas when the page reloads, the form fields are empty. How can this be accomplished?
Answer: Just configure your webform, so the "redirect URL" is the following:
node/[node:id]/submission/[submission:id]

Now after submission you will see the result overview page of that submitted form


code-prettify não funciona com código linear (uma única linha)

Question: Estou utilizando a biblioteca do Google para formatar código:
Google code-prettify
Ele funciona muito bem em quase todos os casos, porém como meu texto vem em uma única string, não funciona tão bem.
Ele funciona bem para:

E não funciona para:

Meu exemplo no JSFiddler: https://jsfiddle.net/dorathoto/3qpwtcoy/8/
Tentei utilizar vários plugins JavaScript para formatar, que no meu caso é padrão XML e não consegui sucesso em nenhum.
Comment: Só uma dúvida: parece que o problema é de indentação. Por que vc não pode indentar o código manualmente?
Comment: pq esse código que vem linear, vem de um database, claramente se eu pudesse já teria resolvido, mas não tenho acesso a esse código inline, então eu preciso achar algum plugin q faça essa identação
Comment: Olhando o código no JSFiddle, é sempre essa tag `` ou pode vir qualquer código?
Comment: @Sam, acredito que sim, mas não posso ter certeza(acredito q 99% das vezes sim), o melhor seria formatar sem saber se vem ou não.
Comment: Blz. Eu só que ria saber pq estou tentando fazer um indentador e pra não perder tempo essa informação era necessária, porque se fosse só uma tag seria bem mais fácil. :)
Answer: Fiz um indentador do zero que funcionou no seu exemplo do JSFiddle e em alguns outros testes que fiz.
Funciona da seguinte forma:
Deixe a tag <xmp> inicialmente vazia e crie logo após ela uma div oculta e coloque o código linear que vem do banco dentro dessa div:

código aqui

O código irá percorrer todos os nós dentro da div e montar um array de objetos tags = [], para pegar a tag do elemento ou o nó de texto, que são duas coisas diferentes. É preciso distinguir uma coisa da outra para poder montar a indentação corretamente.
Em seguida ele percorre a array de objetos criando um novo HTML na ordem dos nós com quebras de linhas (\n) para cada nó, e joga esse novo HTML dentro da div, substituindo o que estava lá. As tags do novo HTML vão todas sem fechamento, porém o navegador fecha todas automaticamente.
Depois ele pega o novo HTML da div e joga pra dentro do <xmp>, porém a última linha irá ficar linear com todos fechamentos automáticos gerados pelo navegador. Aí é preciso tratar isso. Irá pegar essa linha e quebrar em array (last_str.match(/<.+?>/g)).
Depois basta percorrer essa array adicionando novas linhas ao <xmp> dinamicamente com document.createElement(), ao mesmo tempo atribuindo as classes nas
 de forma sequencial (se não o componente não reconhece) que vai de L0 a L9.
Mas para isso funcionar, é preciso usar o callback do componente adicionado ao final da URL a string &callback=iniciar (onde iniciar é o método da função do callback. Você pode dar o nome que quiser em vez de iniciar). Esse callback é chamado pela sintaxe:
window.exports = {
   iniciar: function(){

    // código aqui

   }
}

A função é executada após o componente ter renderizado o código.
Agora vamos ver funcionando:

document.addEventListener("DOMContentLoaded", function(){
   var xmp = document.getElementById("XMlHtml"),
   code = document.getElementById("fonte"),
   tags = [],
   tab = "   ", // espaços de tabulação
   tabr = 0;

   nos(code);
   function nos(node){
       for (var i = 0; i < node.childNodes.length; i++){
         var child = node.childNodes[i];
         no(child); nos(child);
       }
   }

   function no(e){
      var html = e.nodeType != 3 ? e.outerHTML.match(/^<.+?>/)[0] : null;
      tags.push({ no: html, txt: e.nodeValue });
   }

   var nhtml = '';
   for(var x=0; x<tags.length; x++){
      var no = tags[x].no;
      if(x != 0 && tags[x-1].no) tabr++;
      if(!no) no = tags[x].txt;
      nhtml += tab.repeat(tabr)+no+"\n";
   }

   code.innerHTML = nhtml;
   xmp.innerHTML = code.innerHTML;

   window.exports = {
      iniciar: function(){
         var linhas = xmp.querySelectorAll("li"),
         last = linhas[linhas.length-1],
         classe = Number(last.className.replace("L", "")),
         last_str = last.textContent,
         ltags = last_str.match(/<.+?>/g);

         for(var x=0; x<ltags.length; x++){

            tabr--;

            if(x == 0){
               if(tabr == 0) tabr++;
               last.querySelector("span").textContent = tab.repeat(tabr)+ltags[0];
            }else{
               classe = classe < 9 ? classe+1 : 0;
               if(tabr < 0) tabr = 0;
               var nli = document.createElement("li");
               nli.setAttribute("class", "L"+classe);
               var span = document.createElement("span");
               span.setAttribute("class", "tag");
               var tabula = document.createTextNode(tab.repeat(tabr));
               span.appendChild(tabula);
               span.appendChild(document.createTextNode(ltags[x]));
               nli.appendChild(span);
               xmp.querySelector("ol").appendChild(nli);
            }
         }
      }
   }
});

<?prettify lang=xml?>
<xmp class="prettyprint linenums:4" id="XMlHtml"></xmp>

<properties><property key="expression">from CodigoOcorrencia couch in {[left] => DefaultIfEmpty()}</property><property key="EventId"><structure type=""><property key="Id">20500</property><property key="Name">Microsoft.EntityFrameworkCore.Query.QueryClientEvaluationWarning</property></structure></property><property key="SourceContext">Microsoft.EntityFrameworkCore.Query</property><property key="Scope"><sequence><item>Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor</item></sequence></property><property key="SetorErro">MVC</property></properties>

Coloquei todo o código dentro do evento DOMContentLoaded para
  restringir o escopo das variáveis e evitar possíveis conflitos com
  outras variáveis que você possa estar usando em outro código ou
  script.

Note também que você pode definir a largura da tabulação pela variável var tab = "   ", que no caso acima, coloquei com 3 espaços.
Comment: quem sabe, sabe! quem não sabe vai no CTRL+C...obrigado, vou testar e já qualifico
Comment: Dá uma testada. Se der algum bug a gente verifica.


Notification Handler don't receiving notification after mediator.publish in .NET-Core

Question: I created a notification class called SendMail as follows:
 public class SendMail : INotification
    {
        public string From { get; set; }
        public string To { get; set; }
        public string Subject { get; set; }
        public string Message { get; set; }
    }

After that, I implemented the SendMailNotificationHandler:
public class SendMailNotificationHandler: INotificationHandler<SendMail>
    {
        public Task Handle(SendMail notification, CancellationToken cancellationToken)
        {
            Console.WriteLine("Testing");

            return Task.CompletedTask;
        }

And at last I did the procedure to publish a notification in the system in my RequestHandler:
public Task<OperationResult> Handle(CreateMailRequest request, CancellationToken cancellationToken)
        {
            // Just for example
            _repo.Insert(anything);

            _mediator.Publish(new SendMail
            {
                From = "firstname.lastname@example.com",
                To = "email@example.com",
                Subject = "New message",
                Message = "New test message"
            }, cancellationToken);

            return OperationResult.Success().AsTask;
        }

The problem is, when debugging I see the publish method is run, but NotificationHandler never catches this notification of a new mail created.
I don't what is happening. Could someone help with this?
Answer: The problem was in my SimpleInjectorBootstrap.cs. I had to add the following code in my GetAssemblies method:
private static IEnumerable<Assembly> GetAssemblies()
        {
            yield return typeof(ExceptionPipelineBehavior<,>).GetTypeInfo().Assembly;

            //added line
            yield return typeof(ReportCreatedNotificationHandler).GetTypeInfo().Assembly;
        }

Answer: Add an assembly of the given project or class library entry point:
builder.Services.AddMediatR(typeof(MediatrEntryPoint).Assembly , typeof(Program).Assembly);

If there is no entry point in the class library, then add an empty class and name it <Library>entryPoint, then add it to the assembly.


Prove that the perpendiculars from $D,E,F$ to $BC,CA,AB$ are concurrent

Question: If two triangles $ABC$ and $DEF$ are such that the perpendicular from $A,B,C$ to $EF,FD,DE$ are congruent, prove that the perpendiculars from $D,E,F$ to $BC,CA,AB$ are concurrent.
Source: Challenge and Thrills of pre-college mathematics.
Thanks in advance!
Answer: Hint: the perpendicular to $AB$ through $C\not\in AB$ is the locus of points $P$ for which:
$$ PA^2-PB^2 = CA^2-CB^2.$$
Comment: D' Aurizio can you help me with a diagram and explain on the technique or idea used whence I can understand and solve similar questions.


"Term reference" for two language versions

Question: I'm currently working on a Drupal's website for my client. We have a small issue related to new fields in "content types".
I've created a new field with field type "Term reference". We're using terms for isotpe grid, and it should work in both language versions - NL and EN.
That field only displays a single language version (default one), even when we change thhe language.
Here is an example - "field_thema[nl][8]", it supposed to be:
<code>"field_thema[nl][8]"
</code>
and
<code>"field_thema[en][8]"
</code>
Is there any way we could fix this?
Comment: Is your issue at the form level where you are adding the reference or on the output level?
Comment: Well, it's related to both, form and output. In the input form there is an issue with saving it in EN version as I mentioned in the question. On the other hand, output don't display any classes that are auto generated from the terms.
Answer: is this a Drupal 7 or Drupal 8 question ?
in Drupal 7 you can use i18n_taxonomy submodule of i18n module.
Comment: We are using Drupal 7 with i18n_taxonomy module enabled :(


Set the title for a node view panel

Question: I am trying to use panel in Drupal 8 node view template. I have enable Node view panel and added a new variant for Basic page view. But I couldn't mention in panel page to take the title as current node title. Where I can mention it in panel configuration?
Drupal 8

Even I have created the panel variant in Drupal 7. Here title is taking by default node title.
Drupal 7
Answer: FYI: Page Manager is in beta, but that doesn't affect the solution; see below.
You should first check if the node context is available in your Variant. Here is an example screenshot for that:

If that is the case, then you can simply use the following token in the page title field:

[node:title]

should look like this:

Good luck!

Set the title for a node view panel


Reading/writing binary file returns 0xCCCCCCCC

Question: I have a script that dumps class info into a binary file, then another script that retrieves it.
Since binary files only accept chars, I wrote three functions for reading and writing Short Ints, Ints, and Floats. I've been experimenting with them so they're not overloaded properly, but they all look like this:
void writeInt(ofstream& file, int val) {
    file.write(reinterpret_cast<char *>(&val), sizeof(val));
}
int readInt(ifstream& file) {
    int val;
    file.read(reinterpret_cast<char *>(&val), sizeof(val));
    return val;
}

I'll put the class load/save script at the end of the post, but I don't think it'll make too much sense without the rest of the class info.
Anyway, it seems that the file gets saved properly. It has the correct size, and all of the data matches when I load it. However, at some point in the load process, the file.read() function starts returning 0xCCCCCCCC every time. This looks to me like a read error, but I'm not sure why, or how to correct it. Since the file is the correct size, and I don't touch the seekg() function, it doesn't seem likely that it's reaching the end of file prematurely. I can only assume it's an issue with my read/write method, since I did kind of hack it together with limited knowledge. However, if this is the case, why does it read all the data up to a certain point without issue?
The error starts occurring at a random point each run. This may or may not be related to the fact that all the class data is randomly generated.
Does anyone have experience with this? I'm not even sure how to continue debugging it at this point.
Anyway, here are the load/save functions:
void saveToFile(string fileName) {
    ofstream dataFile(fileName.c_str());
    writeInt(dataFile, inputSize);
    writeInt(dataFile, fullSize);
    writeInt(dataFile, outputSize);
    // Skips input nodes - no data needs to be saved for them.
    for (int i = inputSize; i < fullSize; i++) {    // Saves each node after inputSize
        writeShortInt(dataFile, nodes[i].size);
        writeShortInt(dataFile, nodes[i].skip);
        writeFloat(dataFile, nodes[i].value);
        //vector<int> connects;
        //vector<float> weights;
        for (int j = 0; j < nodes[i].size; j++) {
            writeInt(dataFile, nodes[i].connects[j]);
            writeFloat(dataFile, nodes[i].weights[j]);
        }
    }
    read(500);
}
void loadFromFile(string fileName) {
    ifstream dataFile(fileName.c_str());
    inputSize = readInt(dataFile);
    fullSize = readInt(dataFile);
    outputSize = readInt(dataFile);
    nodes.resize(fullSize);

    for (int i = 0; i < inputSize; i++) {
        nodes[i].setSize(0);    // Sets input nodes
    }

    for (int i = inputSize; i < fullSize; i++) {    // Loads each node after inputSize
        int s = readShortInt(dataFile);
        nodes[i].setSize(s);
        nodes[i].skip = readShortInt(dataFile);
        nodes[i].value = readFloat(dataFile);
        //vector<int> connects;
        //vector<float> weights;
        for (int j = 0; j < nodes[i].size; j++) {
            nodes[i].connects[j] = readInt(dataFile); //Error occurs in a random instance of this call of readInt().
            nodes[i].weights[j] = readFloat(dataFile);
        }
        read(i); //Outputs class data to console
    }
    read(500);
}

Thanks in advance!
Comment: You never check the stream state when reading.  That's bad.
Comment: ... or writing. or that file was opened... You also want to open them (for reading and writing) as binary
Comment: Try writing and reading an `int`, before you attempt a complex class. Small steps.
Comment: What's a `node`? And what does `read` do? Please provide a [mcve]
Comment: You should take advantage of *function overloading* and use one function name for writing int, short, etc.  You could use a template too.  IMHO, all this extra work for a single statement?
Comment: I don't think `node` is relevant - the issue is within the read and write functions.
Comment: Thomas, I already spoke on overloading and templates. I'm still experimenting with the functions.
Comment: Passer, there's a comment in the code that explains what `read` does. Seriously, does nobody read before commenting?
Comment: BTW, there is an overhead for executing a function (which consumes processing time), such as pushing variables onto a stack or making copies of registers.  A branch or call instruction may cause the processor's instruction pipeline to be reloaded (again a waste of time).  Then there is the set up for returning a value.  All this overhead can be removed by not using functions for single line statements.  (Some compilers *may* optimize away the overhead, depending on the optimization settings).
Comment: Artemy thank you, I had that in there before, but took it out when playing with it. It looks like that was my error!
Comment: Thanks Thomas, but I'd rather correct critical bugs before working on optimizing my program, especially when I'm experimenting with methods.
Comment: Have you actually tried debugging this?  I'd expect you to have run your [mcve] within Valgrind or a similar checker, and to have investigated with a debugger such as GDB.  Please [edit] your question to summarize what the debugging tools told you and why they didn't solve your problem.  And read Eric Lippert's [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/).
Comment: @TobySpeight, I knew the source of the issue via debugging. This was mentioned in the original post. This question was solved by Artemy Vysotsky, but was not posted as an answer.
Comment: @ArtemyVysotsky, if you post your response as an answer, I will mark the question as solved.
Comment: It's helpful for readers to know *what kind of debugging* you've done, as waiting for a crash with GDB is very different from finding uses of uninitialised variables or wild pointers with Valgrind.  And it turns out that the error seems to be in code you didn't even show us; that's why we ask for a [mcve].
Comment: @TobySpeight, not sure what you're talking about. `ofstream dataFile(fileName.c_str());` is the second line of code in my second posted chunk, and Artemy noticed that it wasn't declared properly.
Answer: You have to check the result of open, read, write operations.
And you need to open files (for reading and writing) as binary.


Serve ports through URL using lighttpd

Question: Settings and goal
On a raspberry pi, I'm running a Lighttpd server (version: lighttpd/1.4.53 (ssl)). This server was initially installed by pi-hole, a DNS I'm starting to use to manage my network. I already managed to associate http://raspi.home to my raspberry pi IP.
This device already runs several services, for instance an R-shiny server on port 3838 and a homeassistant installation on port 8123, that I can thus access through http://raspi.home:3838/ and http://raspi.home:8123 respectively.
My goal is now to be able to access my services through user-friendly addresses, such as  http://raspi.home/shiny (port 3838) and http://raspi.home/homeassistant (port 8123).
Since the lighttpd server was configured for pi-hole, /var/www/html/ contains only two folders: "pihole" and "admin". I can access pi-hole admin panel through http://raspi.home/admin and http://raspi.home/pihole is accessible but not of much use.
My goal is to make that browsing http://raspi.home/shiny/... serves http://raspi.home:3838/... (and same for homeassistant).
Advance so far
I'm modifying /etc/lighttpd/external.conf, which adds on /etc/lighttpd/lighttpd.conf (code here). I tried various things but lighttpd conf files are quite confusing to me, and I'm never sure what should I put at the root level or in a $HTTP["url"].
What worked the most so far was adding an URL mapping with the server definition:
$HTTP["url"] =~ "^/shiny" {
    proxy.header = (
        "map-urlpath" => ( "/shiny" => "/" ),
        "upgrade" => "enable"
    )
    proxy.server = ( "" => ( ( "host" =>  "localhost", "port" => 3838) ) )
}

Unfortunately, this changed all the relative URLs as well so that any image in http://raspi.home/shiny/index.html is searched in http://raspi.home/images/image.png instead of http://raspi.home/shiny/images/image.png. Therefore, no resource could be found.
If I remove the condition, the mapping is global so the app is usable, but since everything is mapped all other sites are now unusable. This is described in this bug but I couldn't make the solution provided work.
I tried with "map-urlpath" => ( "/shiny(.*)$" => "/$1" ) but inexpectedly this throws a 404 error (with or without the condition).
resources
Here are more resources that might be related/useful:

Proxy URL to different port via Lighttpd
Lighttpd proxy redirect by port
https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModProxy
https://redmine.lighttpd.net/boards/2/topics/1946 (redirection worked though)
Rewrite URL before passing to proxy Lighttpd
https://redmine.lighttpd.net/boards/2/topics/8322

They didn't work for me, either because I didn't put the code on the right place or not adapted to my case, who knows...
Comment: I've put a lot of effort to make a good question with details, why would someone downvote it without even telling how to improve?
Comment: Please share concrete setup that you have tried, and what were the concrete issues with the setup.
Comment: @TeroKilkanen Here is my best shot so far, in the edit. 2 days ago, there was unfortunately no setup that worked enough to be presentable here.
Answer: $HTTP["url"] =~ "^/shiny" {
    proxy.server = ( "" => ( ( "host" =>  "192.168.1.138", "port" => 3838 ) ) )
}

Delete proxy.header until you better understand what it does and does not do.
https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModProxy
proxy.header "map-urlpath" will modify the request-line of the HTTP headers, but lighttpd does not rewrite the response body, so your R-shiny server will have to understand it is rooted under /shiny/.  I have not looked at R-shiny to see if that is possible.
A different alternative is to create DNS names shiny.raspi.home and homeassistant.raspi.home, which you can then configure lighttpd to reverse proxy
$HTTP["host"] =~ "shiny.raspi.home" {
    proxy.server = ( "" => ( ( "host" =>  "192.168.1.138", "port" => 3838 ) ) )
}

Please note that I changed the target "port" in my examples above, as I am guessing that is the reverse-proxy target host and port to which you would like lighttpd to reverse-proxy the request to http://shiny.raspi.home/
Comment: Thank you for your answer. I'd like to have a configuration that is totally independent of the target if possible, so that the Shiny server remains accessible from its own address as well. Also, I messed up when writing my comment, the shiny-server is at localhost on a different port (but I intend to do it with 192.168.1.138::80 as well).
Comment: However, the DNS names `shiny.raspi.home` works very well, thanks! This is not what I intend to do but it is definitely a workaround solution.
Comment: You said that "lighttpd does not rewrite the response body", couldn't I use `map-host-response` for this? I tried but didn't manage to make it work.
Comment: lighttpd `proxy.header` mappings apply to HTTP request-line and HTTP response headers such as `Location`, but do not apply to the response **body**.  (Note the word "header" in `proxy.header` directive is distinct from the word "body".)
Comment: I'm sorry not to understand fast enough but it felt like the *body* was a bit modified, since all URLs were rewritten.
Comment: Check the HTML source code of the response in your client browser to see URL links.  Using relative-path urls in the response body is quite portable.

Serve ports through URL using lighttpd


Translate glmer (lme4) model specification into MCMCglmm

Question: I am having some computational trouble estimating the following model with the glmer function in lme4:
glmer(Y ~ x1*x2 + x2*x3 + (1+x1+x2|class) + (1|obs), family=poisson)

where class refers to my groupings,
obs refers to observation (because I would like to an observation-level random effect).

I'd like to try the MCMCglmm package (without deep knowledge of MCMC unfortunately), but cannot figure out how to specify the random effects. So far, my draft command is:
MCMCglmm(fixed = Y ~ x1*x2 + x2*x3,
  random = ~ class + x1:class + x2:class + obs, family="poisson")

Could you please help me specify the model?
Comment: Here is a detailed tutorial describing how to use MCMCglmm and how to implement lme4-style LMMs: https://github.com/tmalsburg/MCMCglmm-intro
Answer: According to MCMCglmm documentation: "Multiple random terms can be passed using the + operator" (as you already do). Having said that you appear to be defining multiple random intercepts and no random slopes.
In general you need to use a syntax similar to ~us(1+x1):x2, where x2 is your discrete variables (for the intercepts), x1 is your continuous variable (for the slopes) and us denotes an unstructured random covariance. You may want to check other covariance structures (eg. idh for an identity one). Please check the chapters 3 and 4 in dealing with Categorical Random Interactions and Continuous Random Interactions respectively in the related MCMCglmm Course Notes. The general overview document is also very helpful (and more concise). I cannot emphasise enough how helpful these notes are, using MCMCglmm without reading them would be nearly impossible for me.
I suspect you want a structure similar to:  ~us(1+x1+x2):class + obs but please check this twice before using it. Note that a global intercept is not fitted by default for variance structure models so you need the +1 that was otherwise redundant for lmer.
Good luck specifying your priors! :D
Answer: To my understanding, MCMCglmm poisson models include an observation-level random effect by default, as the author seems to believe that over-dispersion is the regular case, not the exception. In the manual it is called additive over-dispersion. In MCMCglmm summaries it is called the unit effect


Solving the system $b+c+d=4$, $ad+bc=-8$, $a+b=5$, $cd=-8$

Question: There is a given system of equations
\begin{align} ab+c+d&=\phantom{-}4 \\ ad+bc&=-8 \\ a+b&=\phantom{-}5 \\ cd&=-8 \end{align}
I have tried to simplify it by multiplying one equation by another or adding one to another or similar. Nothing came up.
Any hints would be great! Thank you.
Comment: @JMoravitz sorry, my bad! I've just updated the second equation, there should've been d, not z
Comment: You can at least eliminate a variable... or two... or three...
Comment: I mean... if you insist you could use the relationships $a+b=5$ and $cd=-8$ instead in the forms $b = 5-a$ and $d = \frac{-8}{c}$ to replace $b$'s and $d$'s as they appear elsewhere, for instance $a(5-a)+c+\frac{-8}{c} = 4$ so that it is written in two variables instead of four.  Whether or not this is "simpler" to you is open to interpretation.  There certainly isn't enough information to uniquely determine the values of $a,b,c,d,z$ from these.
Comment: Using JMoravitz's approach to reduce this system of equations, [Wolfram Alpha](https://www.wolframalpha.com/input/?i=a%285-a%29+%2B+c+-+8%2Fc+%3D+4%2C+-8a%2Fc+%2B+%285-a%29c+%3D+-8) gives 6 solutions which are relatively neat ($a, c$ are all in the form $p + q\sqrt{5}$).
Answer:
\begin{align} ab+c+d&=-4 \tag{1}\label{1} ,\\ ad+bc&=-8 \tag{2}\label{2},\\ a+b&=-5 \tag{3}\label{3},\\ cd&=-8 \tag{4}\label{4}.\end{align}

Substitution of
\begin{align}
a&=5-b
\tag{5}\label{5}
,\\
d&=-\frac8c
\tag{6}\label{6}
\end{align}
into \eqref{2} results in
\begin{align}
b&=\frac{40-8c}{c^2+8}
\tag{7}\label{7}
,\\
a &= \frac{c(5c+8)}{c^2+8}
\tag{8}\label{8}
.
\end{align}
Next, substitution of \eqref{6}-\eqref{8}
into \eqref{1} gives an equation in $c$
\begin{align}
\frac{136c^3-32c^4+256c^2+c^6-512}{c(c^2+8)^2}
&= 4
\tag{9}\label{9}
,
\end{align}
which is equivalent to
\begin{align}
(c-2)(c+4)(c^2-4c-16)(c^2-2c-4)&=0
\tag{10}\label{10}
\end{align}
with six real roots
\begin{align}
\{
2,-4,
1+\sqrt5, 1-\sqrt5, 2+2\sqrt5, 2-2\sqrt5
\}
\tag{11}\label{11}
.
\end{align}
Expressions \eqref{6}-\eqref{8} provide corresponding values of $d,b$ and $a$.
Answer: From the 3rd and 4th equations we find that
$$b=5-a\quad \text{ and }\quad d=-8/c. \tag{1}$$
Substituting these in the 1st and 2nd equations they become
$$ x:=(c^2+5ac-a^2c-4c-8)/c \tag{2} = 0$$ and
$$ y:=(5c^2-ac^2-8a+8c)/c = 0. \tag{3}$$
The polynomial resultant of $\,x\cdot c\,$ and $\,y\cdot c\,$
eliminating $\,c\,$ is
$$ 8(a-2)(a-3)(a^2-4a-1)(a^2-6a+4). \tag{4}$$
This has six roots for $\,a$. For each value of $\,a\,$
the GCD of $\,x\,$ and $\,y\,$ uniquely determines $\,c\,$ and the values for $\,b\,$ and
$\,d\,$ are uniquely determined from equations in $(1)$.
Of course, there is nothing unique about picking the 3rd and 4th
equations and solving for $b$ and $d$. Also, I decided to use resultants
to solve for $a$, but there are alternative ways to do so.


eigenvector of 2x2 matrix

Question: A = $ \begin{pmatrix} -1 & 1  \\  -1 & -1\end{pmatrix} $
eigenvalues are $-1 + i$ and $-1-i$
I am a bit confused working out the eigenvectors for each eigenvalue, for example
for the second eigenvalue $ \lambda_{2}= -1-i$
I get
$ \begin{pmatrix} i & 1  \\  -1 & i \end{pmatrix} $ $   \begin{pmatrix} x_1   \\  -x_2 \end{pmatrix} $ = $  \begin{pmatrix} 0 \\  0 \end{pmatrix} $
so first equation I get,
$ ix_1 + x_2 = 0 $
$ -x_1+ix_2 = 0 $
from the first equation
$ ix_1 = -x_2 $
$ x_1 = -x_2/i $
so setting $x_2 = -i,  x_1 = 1$
so  $  x_{2} =   \begin{pmatrix} 1 \\ -i \end{pmatrix} $
but from the second equation I get a differenct eigenvector
$ -x_1 = ix_2 $
if I let $x_2 = 1$ then $x_1=-i$
so I get
$ x_2$ =  $  \begin{pmatrix} -i \\ 1  \end{pmatrix} $
Which eigenvector is correct ?
Answer: $x_2$ is a complex number, not a vector. Subsitituting $x_2 = -ix_1$ in the second equation gives $-x_1 -i^2x_1 = 0$, which is always true. So the only constraint is $x_2 = -x_1i$, so any eigenvector is of the form $(x_1, -x_1 i)^T$ for any $x_1\in \mathbb{C}$.
Both vectors you gave (and mislabeled) $x_2$ are eigenvectors. Eigenvectors are not unique.
Comment: Oh okay, so either one would be correct? Also I labelled it x2 because it's the eigenvector Associated  with the second eigenvalue.
Comment: @italy yes, either is correct. If you need to give all eigenvectors (aka the eigenspace), you need to give it by $\{(\lambda, -\lambda i)^T \ | \ \lambda \in  \mathbb{C}\}$.

eigenvector of 2x2 matrix


Questions on the definition of a function to be continuous.

Question: A function f: D $\to$ R is said to be continuous at the point $x_0$ in D provided that whenever {$x_n$} is a sequence in D that converges to $x_0$. The image sequence ${f(x_n)}$ converges to $f(x_0)$. The function f: D $\to$ R is said to be continuous provided that it is continuous at every point in D.
I have 3 questions:
1) What is an image sequence? Is it like a function?
2) Using this definition, how do you show $x^2$ is a continuous function? (Show me step by step if possible. Thank you.)
3) The book mentions the Dirichlet function. I don't understand why it's not continuous. Like I plug in the definition, but the book is telling me that the density of the rationals makes it irrational. I'm not sure why it's still a non continuous function.
Answer: 1) The image sequence is not a function. It is another sequence. I'll use an example to illustrate: Let $f(x) = x^2$ be the function in question. One sequence we might consider is $x_n = 1/n$, i.e. the sequence $\{1, 1/2, 1/3, 1/4, \ldots\}$. Its limit is $0$, which is therefore our $x_0$. The image sequence is what you get if you take each term above and feed it through $f(x)$. What we get is $$\{f(1), f(1/2), f(1/3), \ldots\}$$ i.e. $$\{1, 1/4, 1/9, \ldots\}.$$ This sequence still converges to $0$, and $f(x_0) = f(0) = 0$, so indeed, we have that the image sequence $\{f(x_n)\}$ converges to $f(x_0)$. If we can show that this works for every convergent sequence $\{x_n\}$ then $f(x)$ is continuous.
${}$
2) What I showed above does not prove that $x^2$ is continuous. It doesn't even prove that $x^2$ is continuous at $0$. It simply fails to give a counterexample to the continuity of $x^2$. To prove that $x^2$ is continuous we will need to do more work.
Let $\{x_n\}$ be some sequence converging to some limit point $x_0$. Its image sequence is $\{x_n^2\}$. We need to show that this converges to $x_0^2$. Let $\varepsilon > 0$ be given. By the definition of convergence, there exists a sufficiently large $N$ such that whenever $n > N$, $$|x_n - x_0| < \min\{\frac{\varepsilon}{2|x_0| + \varepsilon},\varepsilon\}.$$ (I'm using this minimum so that I can assume that $|x_n - x_0|$ is less than both $\varepsilon$ and the given fraction; both inequalities will be useful.) Therefore, if $n>N$, then $$|x_n^2 - x_0^2| = |(x_n-x_0)(x_n+x_0)| = |x_n - x_0||x_n +x_0| < \frac{\varepsilon}{2|x_0| + \varepsilon} \cdot |x_n + x_0|.$$ Notice that since $|x_n - x_0| < \varepsilon$, it follows that $|x_n| < |x_0| + \varepsilon$, and therefore $$|x_n + x_0| \leq |x_n| + |x_0| < 2|x_0| + \varepsilon.$$ Thus we have that $$|x_n^2 - x_0^2| < \frac{\varepsilon}{2|x_0|+\varepsilon} \cdot |x_n + x_0| < \varepsilon.$$ This proves that $\{x_n^2\}$ converges to $x_0^2$.
My thought process here was to look at $|x_n^2 - x_0^2|$ and ask myself how I can make this number small. I first thought to factor it as $|x_n^2 - x_0^2| = |x_n - x_0|\cdot |x_n+x_0|$. I realized that since $\{x_n\}$ converges to $x_0$, I can make $|x_n - x_0|$ as small as desired. On the other hand, when $x_n$ is close to $x_0$, then $|x_n + x_0|$ should be about $2|x_0|$. This is something bounded; indeed it doesn't depend on $n$! Thus, if $|x_n-x_0|$ is small, then $|x_n-x_0|\cdot|x_n + x_0|$ should be too. I figured out the correct bound of $\min \{\frac{\varepsilon}{2|x_0| + \varepsilon},\varepsilon\}$ from there.
${}$
3) I'm assuming the Dirichlet function is the following: $$f(x) = \left\{ \begin{array}{rcl} 1 & : & x \in \Bbb Q\\0 & : & x \notin \Bbb Q\end{array}\right.$$ To prove it's not continuous, we need to find a sequence $\{x_n\}$ converging to some number $x_0$ such that $\{f(x_n)\}$ doesn't converge to $f(x_0)$.
The thing to try is a sequence of rational numbers converging to some irrational number. For instance, take $x_0 = \pi$ and let $\{x_n\}$ be given by the decimal expansion: $$x_1 = 3,\, x_2 = 3.1,\, x_3 = 3.14,\, \ldots$$ By construction $\{x_n\}$ converges to $\pi$, and every number in the sequence $\{x_n\}$ is rational. Therefore the image sequence is $$1, 1, 1, \ldots$$ This sequence obviously converges to $1$. Yet $f(x_0) = f(\pi) = 0$ because $\pi$ is irrational. Since $f(\pi)$ is not the limit of the sequence $\{f(x_n)\}$, we conclude that $f(x)$ is not continuous at $\pi$. Indeed, you can show that $f(x)$ is not continuous at any real number!
Answer: $x_n$ converge to $x$ and $x\in D$. The image sequence here is $y_n=f(x_n)$. For to show that $f(x)=x^2$ is continuous use that if $x_n,y_n$ converge to $x$ and $y$ then $x_ny_n$ converge to $xy$.
Answer: The image sequence is the sequence $y_n=f(x_n)$, which is the image of the original sequence by $f$.
To show $f(x)=x^2$ is continuous, fix a convergent sequence $x_n$ so that $\lim_{n\rightarrow\infty}= x_0$. The image sequence is $y_n=f(x_n)=x_n^2$. Because $\lim_{n\rightarrow\infty}=x_0$, it can be shown that $\lim_{n\rightarrow\infty}x_n^2= x_0^2$.
From what I gather, the Dirichlet function is $g$ where $g(x)=1$ for $x$ rational, and $g(x)=0$ for $x$ irrational. This is continuous nowhere. Fix $x_0\in\mathbb{R}$. For $x_0$ rational, we can choose a sequence $x_n$ of irrational numbers so $\lim_{n\rightarrow\infty}x_n=x_0$. In this case, $g(x_0)=1$, but $\lim_{n\rightarrow\infty}g(x_n)=\lim_{n\rightarrow\infty}0=0$. For $x_0$ irrational, we can choose a sequence $x_n$ of rational numbers so $\lim_{n\rightarrow\infty}x_n=x_0$. In this case, $g(x_0)=0$, but $\lim_{n\rightarrow\infty}g(x_n)=\lim_{n\rightarrow\infty}1=1$.


R: Calculating Quantiles with (group_by .add = TRUE)

Question: I am working with the R programming language.
I have the following dataset:
set.seed(123)
library(dplyr)

Patient_ID = 1:5000
gender <- c("Male","Female")
gender <- sample(gender, 5000, replace=TRUE, prob=c(0.45, 0.55))
Gender <- as.factor(gender)

status <- c("Immigrant","Citizen")
status <- sample(status, 5000, replace=TRUE, prob=c(0.3, 0.7))
Status  <- as.factor(status )

Height = rnorm(5000, 150, 10)
Weight = rnorm(5000, 90, 10)
Hospital_Visits = sample.int(20,  5000, replace = TRUE)

################

disease <- c("Yes","No")
disease <- sample(disease, 5000, replace=TRUE, prob=c(0.4, 0.6))
Disease <- as.factor(disease)

###################
my_data = data.frame(Patient_ID, Gender, Status, Height, Weight, Hospital_Visits, Disease)

  Patient_ID Gender    Status   Height    Weight Hospital_Visits Disease
1          1 Female   Citizen 145.0583 113.70725               1      No
2          2   Male Immigrant 161.2759  88.33188              18      No
3          3 Female Immigrant 138.5305  99.26961               6     Yes
4          4   Male   Citizen 164.8102  84.31848              12      No
5          5   Male   Citizen 159.1619  92.25090              12     Yes
6          6 Female   Citizen 153.3513 101.31986              11     Yes

In a previous question (R: Calculating Proportions Based on Nested Groups), I learned how to calculate "nested proportions" based on ntiles (e.g. calculate 3 ntiles for one variable, group by these 3 ntiles and then claculate 3 ntiles for the second variable based on these previous ntiles,etc.):
# e.g. using 3 ntiles

my_data %>%
  group_by(Gender, Status) %>%
  mutate(Height_ntile = ntile(Height, 3),
         Height_range = paste(min(Height), max(Height), sep = "-")) %>%
  group_by(Height_ntile, Height_range, .add = TRUE) %>%
  mutate(Weight_ntile = ntile(Weight, 3),
         Weight_range = paste(min(Weight), max(Weight), sep = "-")) %>%
  group_by(Weight_ntile, Weight_range, .add = TRUE) %>%
  mutate(Hospital_Visits_ntile = ntile(Hospital_Visits, 3),
         Hospital_range = paste(min(Hospital_Visits), max(Hospital_Visits), sep = "-")) %>%
  group_by(Hospital_Visits_ntile, Hospital_range, .add = TRUE) %>%
  summarize(percent_disease = mean(Disease == "Yes"),
            count = n(),
            .groups = "drop")

Now, I am trying to repeat this exact same function but using "quantiles" instead:
I tried to modify the above code - here is my attempt:
my_data %>%
  group_by(Gender, Status) %>%
  mutate(Height_group = cut(Height, breaks = c(-Inf,
                                               quantile(Height, c(0.33, 0.67)),
                                               Inf)),
         Height_range = paste(min(Height), max(Height), sep = "-")) %>%
  group_by(Height_group, Height_range, .add = TRUE) %>%
  mutate(Weight_group = cut(Weight, breaks = c(-Inf,
                                               quantile(Weight, c(0.33, 0.67)),
                                               Inf)),
         Weight_range = paste(min(Weight), max(Weight), sep = "-")) %>%
  group_by(Weight_group, Weight_range, .add = TRUE) %>%
  mutate(Hospital_Visits_group = cut(Hospital_Visits, breaks = c(-Inf,
                                                                quantile(Hospital_Visits, c(0.33, 0.67)),
                                                                Inf)),
         Hospital_range = paste(min(Hospital_Visits), max(Hospital_Visits), sep = "-")) %>%
  group_by(Hospital_Visits_group, Hospital_range, .add = TRUE) %>%
  summarize(percent_disease = mean(Disease == "Yes"),
            count = n(),
            .groups = "drop")

This code runs, but I am not sure if I have done this correctly (e.g. the "infinite" values appearing):
 A tibble: 108 x 10
   Gender Status  Height_~1 Heigh~2 Weigh~3 Weigh~4 Hospi~5 Hospi~6 perce~7
   <fct>  <fct>   <fct>     <chr>   <fct>   <chr>   <fct>   <chr>     <dbl>
 1 Female Citizen (-Inf,14~ 115.86~ (-Inf,~ 58.991~ (-Inf,~ 1-20      0.314
 2 Female Citizen (-Inf,14~ 115.86~ (-Inf,~ 58.991~ (7,14]  1-20      0.458

Can someone please show me if I have done this correctly?
Thanks!
Comment: It is correct.  If you want integer values in place of that range, wrap with `as.integer(cut(..`
Comment: @ akrun: I posted an answer based on your insights - is this correct?
Comment: It is the same error I mentioned in your other post i.e. `quantile` gives length of length of probs output.  You need to `cut` with `breaks = quantile(..`
Comment: @akrun: thank you for your reply! Does this also apply when using group_by(add = true)?
Comment: It is the lines like this `Height_quantile = quantile(Height, probs = seq(0, 1, length.out = 3)` which should be `Height_grp = cut(Height, breaks = quantile(Height, probs = seq(0, 1, length.out = 3))` or if you want to create a summarised output it will be fine as quantile i.e. `%>% summarise(Height_quantile = quantile(Height, probs = seq(0, 1, length.out = 3))` because summarise  doesn't have the restriction to return the length same as original column
Comment: Now your code doesn't give any error for me
Comment: @ akrun: I  just made the changes based on my interpretation of your "cut function" advice - can you please let me know if I have done this correctly? Thank you so much!
Comment: Should the "infinite" values be appearing within the ranges?
Comment: It will be `1, 2, 3....`
Comment: @ akrun: thank you so much! if you have time, can you please write an answer with your logic - just so I can clarify again? I can then accept it as the answer. thank you so much!
Comment: Your answer just needs `as.integer(` wrapping around the `cut`.  Otherwise it is fine
Answer: Answer based on insights provided by @akrun:
my_data %>%
  group_by(Gender, Status) %>%
  mutate(Height_group = as.integer(cut(Height, breaks = c(-Inf,
                                               quantile(Height, c(0.33, 0.67)),
                                               Inf))),
         Height_range = paste(min(Height), max(Height), sep = "-")) %>%
  group_by(Height_group, Height_range, .add = TRUE) %>%
  mutate(Weight_group = as.integer(cut(Weight, breaks = c(-Inf,
                                               quantile(Weight, c(0.33, 0.67)),
                                               Inf))),
         Weight_range = paste(min(Weight), max(Weight), sep = "-")) %>%
  group_by(Weight_group, Weight_range, .add = TRUE) %>%
  mutate(Hospital_Visits_group = as.integer(cut(Hospital_Visits, breaks = c(-Inf,
                                                                quantile(Hospital_Visits, c(0.33, 0.67)),
                                                                Inf))),
         Hospital_range = paste(min(Hospital_Visits), max(Hospital_Visits), sep = "-")) %>%
  group_by(Hospital_Visits_group, Hospital_range, .add = TRUE) %>%
  summarize(percent_disease = mean(Disease == "Yes"),
            count = n(),
            .groups = "drop")

Have I understood this correctly?


Shut down a notebook instance

Question: I am using a couple of notebook instances on Google Cloud as my everyday compute engines. The usual workflow is to iteratively develop my data product using Jupyterlab, and then SSH into the machine once the code is ready to be run (My typical workflow is to run several simulations and hyper parameter tuning experiments). At this point, I usually quit the Jupyterlab interface (File > Quit). After the compute process is over, I typically issue a shutdown command on the SSH instance sudo shutdown -h now (sometimes this is the last line in a bash script).
However, I observe that this does not necessary shutdown the instance (I am looking at the cloud console to verify this). The only way to shutdown is to use the Cloud Console shutdown. However, this is inefficient since I would like to have a bash script that runs my simulations and then shuts down the instance once I am done.
Is there a best practice to be followed for shutting down notebook instances post the workload is done?
Answer: You can manage your notebook instance from Compute Engine too, so you have actually 3 ways for stopping your instance (From the console, with the gcloud command or calling an API).
I recommend you to add the gcloud stop instance command at the end of your bash script.

gcloud compute instances stop notebook-instance-test --zone=us-west1-b

Remember to add the zone of the instance at the end of the command (if you don't added it the command will ask for the zone)
I tested this myself in a notebook instance and it worked perfectly.

Shut down a notebook instance


Update ListView after fill in the dialog

Question: I am starting with developing of android apps. I've created a dialog box where I can add some text. When I click on OK, so I'd expected that activity will start from onResume() or something like this. I want to update ListView after I click on OK in dialog box.
UPDATE
MainActivity:
public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.server_list);

}

@Override
protected void onResume() {
    super.onResume();

    //database query and call showServerList

}

public void showServerList(ArrayList<HashMap<String, String>> servers){

    ListView list = (ListView) findViewById(R.id.server_list);

    ListAdapter adapter = new SimpleAdapter( MainActivity.this, servers, R.layout.server_list_entry,
            new String[] {"name"}, new int[]{R.id.server_name});

    list.setAdapter(adapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.action_add_server:
            DialogFragment newFragment = new AddServerDialog();
            newFragment.show(getSupportFragmentManager(), "addServer");
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

AddServerDialog:
public class AddServerDialog extends DialogFragment {

View view;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();

    view = inflater.inflate(R.layout.dialog_add_server, null);

    builder.setView(view)

           .setPositiveButton("Add", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {

                   EditText name = (EditText) view.findViewById(R.id.add_server_name);
                   EditText url = (EditText) view.findViewById(R.id.add_server_address);

                   if(name.getText().toString().isEmpty() || url.getText().toString().isEmpty()){
                       getDialog().cancel();
                   }else{

                       HashMap<String,String> map = new HashMap<String,String>();
                       map.put("name", name.getText().toString());
                       map.put("url", url.getText().toString());
                       //Database query with insert

                   }
               }
           })
           .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   getDialog().cancel();
               }
           });
    return builder.create();
}

}
Comment: I'm sorry, It works now. I had needed time for relax.
Comment: sometimes it happens, you need take a break for a rest
Comment: add please your code, or you can try use to call your methods where you set data to listView and call method notifyDataSetChanged() in adapter to listView.
Comment: Ok, it is here. Maybe it's all wrong. This is my third day with Android.
Answer:     dialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                    //listview.getAdapter().items = newItems...
                    listview.getAdapter().notifyDataSetChanged();
            }
    });


How to split a string and summarize the parts into a new numeric variable in SQL?

Question: I have several datasets with a stringvariable that is the result of a concatenation of up to four numeric variables. The variables looks like something like my example below:

I need to create a new numeric variable which contains the sum of "ParSokBel". I have no need for information about the different parts or how many they are in the future use of this data.
In the next step I will loop the solution several times. There might be more than four values in a single row in some of the following datasets.
The variable is in a datastructure which contain between 61-75 attributes (varies up and down with tablegeneration).
I realy don't want to import the data again and I'm not realy shure how I would have done this anyway, since some of the other attributes contain commas and should do so.
Anyone who have an idea of how I can solve this? I can'n show an example code because I dont have any. I'm not even shure where to begin since I've never encountered something like this before.
I'm using MSN SQL Server Express and MSN SQL Server 2014 (they are both used but in different parts of the dataproduction process where Server Express handles the import and Server 2014 is the global environment for our system). I have greater freedom/rights in the Express environment than in the Server 2014 environment.
Comment: Those aren't variables, they're rows. The real problem here is you are storing delimited data representing numbers. This means you have a `varchar` storing the value, so, in your data, the "highest" value you have is `'400000'` (as that is the string that starts with the highest number and has the longest length). Plus the fact that you you can't appy the `SUM` function to a `varchar` as well means need a lot of work before you can aggregate your data. you really need to fix your design.
Comment: I know. If I had access to the source data I would have done it in a different way. But, I don't have access to the system that delivers the data. It comes from an external source that is delivered exclusivly for my employer. I don't know why they have delivered the data in this way. The last delivery it was'nt and I have asked if they could redeliver the earlier data, but they could'nt. So, I'm stuck with this structure and need to find a way around it.
Answer: Well, you can use string_split() in the latest versions of SQL Server:
select sum(try_convert(int, ss.val))
from t cross apply
     string_split(parsokbel, ',') ss(val);

If you have an older version of SQL Server, you can peruse the web for a split() function.
Comment: Thanks. This partly helped me. My db-engine did'nt recognize "string_split", but this helped me to move on. I'll search further on split functions. The ones I've found before I posted my question ended up with putting the values in different rows, but I try to search again and this time from a "string_split" perspective.
Comment: [Here](https://sqlperformance.com/2012/07/t-sql-queries/split-strings) are several excellent splitters.


Routing to Actions using Ajax asp.net MVC

Question: I am attempting to actually get my jqGrid to load data on a button click...  So far I have my button ready to be clickable as you can see. The problem is, I some how or the other not getting the navigation info correct...  I am trying to AJAX call an that is set up using @HTML.BeginForm like so...
@using(Html.BeginForm("returnJSONEncoutnerData", "AddEncounter", new { popId = (int)TempData["POPULATIONID"]}, FormMethod.Post, new { id = "SearchPatID" }))

And here is my button click function.
$('#submit').click(function (event) {
        //alert("What the FONK is going on here!");
        debugger;
        var theURL = $("#SearchPatID").action;
        var type = $("#SearchPatID").methd;
        event.preventDefault();
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            dataType: "json",
            success: function (result) {
                bindCustomers();
            }
        });
        return false;
    });

My function bindCustomer is supposed to fill a jqGrid with JSON data that the above method collects and JSONifies!
I thought I would put it out there to quench your curiosity.
 var bindCustomers = function () {
    alert('');
    $("#list").jqGrid({
        url: $("#DisplayUniqueEncounters").attr("action"), //'/Home/GridData/',
        gridview: false,
        shrinkToFit: false,
        autowidth: true,
        datatype: 'json',
        mtype: 'POST',
        colNames: ['Edit',
                   'MRN',
                   'Hospital Fin',
                   'First Name',
                   'Last Name',
                   'Date of birth',
                   'Completed Pathway',
                   'Completed Pathway Reason',
                   'PCP Appointment',
                   'Specialist Appointment',
                   'Admit Date',
                   'Discharge Date',
                   'Discharge Disposition',
                   'Discharge To',
                   'Discharge Advocate Call',
                   'Home Healthcare',
                   'Safe Landing Accepted',
                   'PCP Name',
                   'PCP Phone',
                   'PCP Appointment Location',
                   'Specialist Name',
                   'Specialist Phone',
                   'Specialist Appointment Location',
                   'Comments',
                   'Patient Room Phone',
                   'Phone',
                   'Payor',
                   'MRN Type'
                   ],
        colModel: [
                   { name: 'Edit', width: 95, align: 'left' },
                   { name: 'MRN', width: 125, align: 'left' },
                   { name: 'Hospital_Fin', width: 145, align: 'left' },
                   { name: 'First_Name', width: 115, align: 'left' },
                   { name: 'Last_Name', width: 115, align: 'left' },
                   { name: 'Date_of_birth', width: 145, align: 'left' },
                   { name: 'Completed_Pathway', width: 125, align: 'left' },
                   { name: 'Completed_Pathway_Reason', width: 165, align: 'left' },
                   { name: 'PCP_Appointment', width: 115, align: 'left' },
                   { name: 'Specialist_Appointment', width: 125, align: 'left' },
                   { name: 'Admit_Date', width: 185, align: 'left' },
                   { name: 'Discharge_Date', width: 185, align: 'left' },
                   { name: 'Discharge_Disposition', width: 155, align: 'left' },
                   { name: 'Discharge_To', width: 85, align: 'left' },
                   { name: 'Discharge_Advocate_Call', width: 155, align: 'left' },
                   { name: 'Home_Health_Care_Accepted', width: 105, align: 'left' },
                   { name: 'Safe_Landing_Accepted', width: 165, align: 'left' },
                   { name: 'PCP_Name', width: 85, align: 'left' },
                   { name: 'PCP_Phone', width: 85, formatter: formatPhoneNumber, align: 'left' },
                   { name: 'PCP_Appointment_Location', width: 185, align: 'left' },
                   { name: 'Specialist_Name', width: 195, align: 'left' },
                   { name: 'Specialist_Phone', width: 135, formatter: formatPhoneNumber, align: 'left' },
                   { name: 'Specialist_Appointment_Location', width: 185, align: 'left' },
                   { name: 'Comments', width: 185, align: 'left' },
                   { name: 'Patient_Room_Phone', width: 135, formatter: formatPhoneNumber, align: 'left' },
                   { name: 'Phone', width: 125, formatter: formatPhoneNumber, align: 'left' },
                   { name: 'Payor', width: 155, align: 'left' },
                   { name: 'MRN_Type', width: 135, align: 'left' }
                   ],
        //pager: jQuery('#pager'),
        rowNum: 10,
        rowList: [5, 10, 20, 50],
        sortname: 'Id',
        sortorder: "desc",
        viewrecords: true,
        imgpath: '/scripts/themes/coffee/images',
        caption: 'My first grid'
    });
}

I need data to be thrown back at me asynchronously at some point.  But beggers can't be chosers at this point.  I need to figure out why I can't get the correct routing information.
Answer: this is the button, not the form.
It doesn't have an action.
You should handle the form's submit event instead, so that this will be the form.
Comment: well put btw.  I wonder if you know about loading Json data ino a jqGrid asynchronously?


Checking the normality of a large sample?

Question: If I want to analyze a large sample size (N = 50.000) of continuous data ($ revenue) from an A/B test, what would then be the best way to check for normality?
Thanks in advance!
Comment: Why do you want to check for normality?
Comment: The t test does not require that the *observations* are normally distributed; it requires that the *means* are. By the Central Limit Theorem, they are so asymptotically even if the original observations have a quite non-normal distribution, under some quite weak assumptions. The Mann-Whitney test is nonparametric and makes no normality assumptions. You can probably use a t test out of the box, or possibly consider a permutation test for means ([but see here](https://stats.stackexchange.com/a/163935/1352)).
Comment: That the numerator in a t-test is close to normal is not of itself sufficient to make a t-statistic have a t-distribution. To get that, you really do need the observations to be normal. Beyond that, in large samples you have a justification for an approximate z-test (CLT + Slutsky), not a t-test. Is there some argument that shows that t will be better than z in general in that situation?
Comment: to understand if I can use for example a T-test or if I need to use something like a mann-whitney u test
Answer: The comments are all worthwhile and you may not need to test for normality at all.
But if you are comparing revenue from two groups (A and B) then I would be amazed if it were normally distributed. In my experience, money variables are almost never normally distributed - they tend to have long tails to the right and to have outliers.
I would also wonder if comparing the mean revenue (which is what a t-test does) is really what you want (or, if it is wanted, if you might also want something else).
Testing normality for large samples has its own problems. Tests (like Shapiro Wilk and so on) are likely to give significant results (i.e. not normal) for trivial deviations from normality. Graphical methods (such as quantile normal plots) are better, but require some experience and judgment to read.
Given all this, why not go to quantile regression? It doesn't make assumptions about the residuals and gives you (at least optionally) more information?


What is melodic inversion and how to do it?

Question: I understood how to invert the chords (moving the bass note an octave above). When it comes to melodies I have seen many examples on the net but cant seem to understand the idea behind it.

This example above is given on wikipedia. On the sources they say you invert the melody upside down. This is not what I get when I invert it upside down. I dont understand it.
Could someone please explain it in a simple way and why we do this?
Comment: I might recommend furthering your understanding of chord inversions, as it sounds like you may have a slightly inaccurate view based on the way you phrased that.  Simply, a inverted chord is one that has any chord tone other than the root of the chord as its lowest note.
Comment: Related question: [What kind of melodic inversion is this?](https://music.stackexchange.com/questions/94895/what-kind-of-melodic-inversion-is-this)
Answer: Melodic Inversion
Where the original melody goes up by an interval, the inverted melody goes down by the same interval.  Sometimes you do it where you keep the same number of semi-tones (sometimes you do a "diatonic" inversion and just keep the scale degree).  It's a technique for taking given melodic content and constructing more, related melodic content.
In your example, the original goes from a to c (up three semitones); the inverted goes from e down to c# (down 3 semitones).  Then it goes from c down to b (1 semitone); the inverted goes up one semitone and so on.
(The diatonic version would go down a third, to c-natural, then up one scale degree to d and so on.  The key feature is that no accidentals would be used).
As far as I can tell melodic inversion doesn't have much to do with chord inversions, other than sharing the same name.
Comment: The point is to generate a new melody whose relationship to the existing one is extremely close.  It's really hard to get any simpler than the Rachmaninov example. Instead of up a third, down a tone, down a tone, and up a fifth, he goes down a third, up a tone, up a tone, and down a fifth.  Do you see how Rachmaninov's melody is a mirror-image of Paganini's?  The melodic contour has been inverted.  What are you still unsure of?
Comment: Thank you for your answer. Is there any easy way to do that for the entire piece or we should do it note by note just like you said? And what is the point of doing these, to spice the melody? By the way I still did not understand could you give me a simpler example which you do inversion on it?
Comment: @dennisdeems What I am unsure of is everything actually. I do not get what am I supposed to do. Lets assume that I have a sequence which is C D E G could you invert it step by step to show me how we do it?
Comment: c d e g goes +2 +2 +2 semitones (c to d, d to e, e to g),  so the inverted melody would go -2 -2 -2, so if you started on c, it would go: c b-flat, a-flat, g-flat (the inverted melody could start on any note).
Comment: Actually e to g is +3 semitones so the inversion would be a-flat to f.
Comment: @dennisdeems yes you are correct; my bad


Climber rankings at Tour de France - must the winner finish the tour?

Question: What if a few (2/3) stages to the end of the Tour de France a cyclist retires when he had a number of points that would make it mathematically unreachable by other cyclists in the climber ranking?

Does he win the climber rankings or is it necessary to arrive to Champ Elysee?
Answer: Quote from 2016 Tour de France rules (emphasis mine):

ARTICLE 24|RANKINGS
  ...
  c) General best climber ranking
  The general best climber ranking is established by adding together the points obtained on all passes and hills, according to the following tables:
  ...
  Riders must finish the Tour de France in order to appear in the best climber ranking.

A similar rule is mentioned for points classification, too.
Answer: When rules didn't specify that the rider had to finish the Tour, the Climber Jersey was awarded to Félicien Vervaecke (1937) even when he didn't finish the tour.

After the last mountain in the fifteenth stage, the [mountain] classification was won by Félicien Vervaecke. Vervaecke did not finish the Tour, but in 1937 that was not needed to win the mountains classification.
Source: Wikipedia


Conexão com Banco de dados

Question: Estou com um problema em fazer a conexão com o Banco de Dados Mysqli,
está dando vários erros, segue os erros abaixo:
PHP Warning:  mysqli_query() expects parameter 1 to be mysqli, null given in D:\web\localuser\riobonitopiscinas\www\acessorios-para-construcao.php on line 63
PHP Warning:  mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in D:\web\localuser\riobonitopiscinas\www\acessorios-para-construcao.php on line 66
PHP Warning:  mysqli_close() expects parameter 1 to be mysqli, null given in D:\web\localuser\riobonitopiscinas\www\acessorios-para-construcao.php on line 84

E o meu código da página é:
<?php
   include ('admin/include/conexao.php');

   $result = mysqli_query($con,"SELECT * FROM produto WHERE id_subcategoria=78");

   while($row = mysqli_fetch_array($result)) {
?>

<?php include ('includes/box.php'); ?>

<?php
   }
   mysqli_close($con);
?>

O meu código da conexão :
<?php

$parseini = parse_ini_file('admin/ini/config.ini', true);

$dsn = sprintf('mysql:dbname=%s;host=%s',$parseini['bancodedados']['dbname'], $parseini['bancodedados']['host']);

try {
    $conexao = new PDO($dsn, $parseini['bancodedados']['usuario'], $parseini['bancodedados']['senha']);
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}
?>

Comment: "*estou com um **problema em fazer a conexão** com o Banco*", se o problema é com a conexão, você precisa nos mostrar o arquivo que faz a conexão. Todos os erros citados são de objeto nulo, o que indica que sua variável `$con` é nula.
Comment: @Vinicius, coloque o código da conexão na pergunta em si e não aqui nos comentários.
Comment: getMessage());
}
?>
Comment: Pronto esta na pergunta
Comment: Você conecta o banco em `$conexao`, mas utiliza `$con`? Por que isso?
Answer: Tem dois erros no teu código.

Já foi apontado por outros usuários nos comentários é que você está inicializando a conexão com o mysql e guardando isso na váriavel $conexao (no arquivo conexao.php), na hora de utilizar a conexao tu usa a váriavel $con que nem existe no seu código.
Tu abre uma conexao utilizando PDO como conexão e depois tu utiliza métodos do mysqli. PDO e Mysqli são duas formas de se conectar no banco em php, escolha uma e utilize ela.

Se tu mudar a conexao para mysqli deve funcionar já que tu utiliza os métodos do mysqli no outro arquivo, segue aqui em baixo utilizando mysqli para se conectar.
conexao.php
$parseini = parse_ini_file('admin/ini/config.ini', true);

$con = mysqli_connect($parseini['bancodedados']['host'], $parseini['bancodedados']['usuario'], $parseini['bancodedados']['senha'], $parseini['bancodedados']['dbname']);

if (mysqli_connect_errno()) {
  echo "Erro ao conectar no mysql: " . mysqli_connect_error();
}

Link uteis:
mysqli
pdo
Answer: seu código esta com erro na variavel $con
note que no seu arquivo de conexão você utiliza $conexao
tente desta maneira :
<?php
   include ('admin/include/conexao.php');

   $result = mysqli_query($conexao,"SELECT * FROM produto WHERE id_subcategoria=78");

   while($row = mysqli_fetch_array($result)) {
?>

<?php include ('includes/box.php'); ?>

<?php
   }
   mysqli_close($conexao);
?>

Conexão com Banco de dados


Disproving the statement "If $f(z)$ is not an entire function, then $g(z) = f^2(z)$ is not entire."

Question:
If $f(z)$ is not an entire function, then $g(z) = (f(z))^2$ cannot be an entire function."

From this statement why would saying "Let $f(z) = \sqrt z$, assuming that it is a branch that takes $−1$ to $i$. Then it is not analytic on the branch cut, but $g(z) = (f(z))^2 = z$ is obviously an entire function."
Not be a proper example to disprove this statement/ be a incorrect counterexample?
I understand that for $\sqrt z$ to be a incorrect counterexample means it is not analytic on the branch -1 to I, therefore not entire.
However I thought $\sqrt z$ would be analytic throughout the whole branch cut from -1 to i. Since on the complex plane,
$\lim_{z \to -1} \sqrt z$ exists as it would approach $i$ in that case, and in the other case $\lim_{z \to i} \sqrt z$
it approaches $\sqrt i$ meaning that at least on that branch cut in the complex plane it is continuous everywhere, therefore the partial derivatives exist everywhere on the branch cut meaning it is analytic, but this assumption seems to be incorrect. What am I missing or not understanding here.
Precisely, I don't understand why $\sqrt z$ would not be a proper counterexample to the statement.
Comment: And maybe I'm misunderstanding your branch cut, but $\lim_{z\to i }$ seems completely irrelevant if the negative numbers are your branch cut.
Comment: (Comment edited/re-posted.) You are wrong that $\lim_{z\to-1}\sqrt{z}$ exists. It is different when approached from the upper half-plane and the lower half-plane.
Answer: Your counterexample is essentially correct, although when one talks about a "branch" of the square root function, one generally means an open set $U \subseteq \mathbb{C}$ together with a holomorphic function $f : U \to \mathbb{C}$ such that $(f(z))^2 = z$ for all $z \in U$. In this case, that is not what we want.
In fact, all you need to know is that for all $z \in \mathbb{C}$, there exists a $p \in \mathbb{C}$ such that $p^2 = z$. Then there must be some "square root function" $f$ which satisfies $(f(z))^2 = z$ for all $z$. But this function cannot be entire because it cannot be differentiable at $0$, even though its square is entire.
Comment: Let me add that if $f$ is continuous and $f^{2}$ is entire then $f$ is entire.
Comment: @KaviRamaMurthy That's good to know and quite interesting, as it means that under Brouwer-style intuitionism, a function's square being entire would make the function itself entire (at least assuming the proof is constructive). Is there a nice proof of this? I'm not familiar with the theorem.
Comment: That is quite easy to prove. Write down the definition of the derivative of $f^{2}$, factor $f(z+h)^{2}-(f(z))^{2}$; you will see that $f$ is differentiable at $z$ if $f(z) \neq 0$. Now use  the fact that zeros of $f$ are isolated to show that $f$ has a removable singularity at $z$ if $f(z)=0$.
Comment: How about why it wouldn't be analytic on the branch cut -1 to i, why would it not be considered analytic on that cut? If the function is continuous on a branch cut wouldn't that mean that it must also be analytic on the cut? I'm just not quite understanding why this particular example wouldn't work as a counterexample to the statement.
Comment: More generally, if $f$ is continuous in an open set $U$, and analytic except possibly on a straight line segment, then $f$ is analytic in $U$.  This is easy to prove using Morera's theorem.
Comment: @user3655510 I ask you to look carefully at the continuity of $\sqrt{z}$ at $-1$ or on any branch cut.
Answer: Your example IS a counterexample to the statement above. Yes, it is possible to have a function that cannot be made entire by analytic extension such that the square is an entire function. The square root is precisely such an example.
We can make this more concrete. We will define "a" square root function to be based on the polar representation of each point in $\mathbb{C}$; i.e., it is well known that given a complex number $z\not=0$ there exist unique $r\in\mathbb{R}^+$ and $\theta\in[-\pi,\pi)$, such that $z=re^{i\theta}$. Hence, we define $f(0)=0$ and for $z=re^{i\theta}\not=0$,
$$f(z)=\sqrt{r}e^{i\theta/2}$$
We see that $f(z)$ is defined and exists for every value in $\mathbb{C}$. Moreover, $f(z)^2=z$ for every value in $\mathbb{C}$. However, $f(z)$ (while defined at every negative real value) is not continuous at any value on the negative real axis. This is because a limit from the 2nd quadrant down towards a point and a limit from the 3rd quadrant up towards a point, will not agree. Explicitly, if $a\in(-\infty,0)$, then
$$\lim_{\epsilon\to 0}f(a+\epsilon i)=\lim_{\epsilon\to 0}\sqrt{-a-\delta_\epsilon}e^{i(\pi-\gamma_\epsilon)/2} = \sqrt{-a}e^{i(\pi/2)} = i\sqrt{-a} $$
but
$$\lim_{\epsilon\to 0}f(a-\epsilon i)=\lim_{\epsilon\to 0}\sqrt{-a-\delta_\epsilon}e^{i(-\pi+\gamma_\epsilon)/2} = \sqrt{-a}e^{i(-\pi/2)} = -i\sqrt{-a}$$
These two values are not the same value and hence no general limit can exist at the value of $a$. This means $f$ fails to be continuous at $a$ and means that $f$ fails to be analytic at $a$. Everywhere, (besides $z=0$ and the explicitly chosen interval endpoints of $[-\pi,\pi)$) the function is analytic. Moreover we could have chosen any interval we wanted, thus creating a new "branch cut"; hence there are many possible square root functions that can be defined.

Disproving the statement "If $f(z)$ is not an entire function, then $g(z) = f^2(z)$ is not entire.”


Apply conditional formatting in Google Docs if current cell exists in a range

Question: Very simply, I am attempting to highlight a cell if that cell matches (exactly) with a different cell from a different column (in a different sheet, specifically).
For example, I have an 'Active' and 'Inactive' sheet in my Google Docs Spreadsheet.  Some of the items listed in 'Inactive' are also listed in 'Active', and I need to highlight those.
What I've gotten so far is this (that doesn't work):

Format -> Conditional Formatting
Format Cells If -> Custom Formula Is
GT(MATCH(A1, 'Active'!A2:A, 0), 0)

The general formula above works if I use it in the spreadsheet normally and correctly pass the 1st parameter to MATCH(), however when I attempt to move the regular formula to a conditional formatting, it seems to break down: I need to pass the current cell's contents as the 1st parameter, not A1 statically.  If using GT() + MATCH() is indeed the correct way to accomplish this, I need a way to express:
GT(MATCH(  'Inactive'! [A + ROW()]  , 'Active'!A2:A, 0), 0)

... Where A+ROW ends up being the non-literal expression, -- i.e. on row 123 this would refer to the cell contents of A123.
There may be also an easier and more intuitive way to do this altogether.  To state my problem in a different way, "If the current cell's data [a string] is present (or 'matches') in the range 'Active'!A2:A then highlight it".
Comment: If you are going to downvote my question, suggestions to improve the question or reasons as to such would be helpful in the future!
Answer: The problem is that when you are using a different sheet in conditional formatting you need to pass it using INDIRECT(). Use this formula in conditional formatting:
=GT(MATCH(A1, INDIRECT("'Active'!A2:A"), 0), 0)

And apply it to range A1:A. You do not need to pass the row number, google does it for you.
Comment: There is a mismatched single quote there, but aside from that it worked here.
Comment: Oh sorry, that happened when I pasted your sheet name in to the formula.
Comment: how do you negate this?  NOT() is not working for me
Comment: Super great expression! Worked like a charm! Thanks for sharing