Zsh : command not found : ng on new Mac OS Catalina

Question: I have download the new Mac OS Version Beta of Catalina. Now I should start to use Zsh. But when I want to run a Angular project in Atom, I receveid this message : "The default interactive shell is now zsh.
To update your account to use zsh, please run chsh -s /bin/zsh.
For more details, please visit https://support.apple.com/kb/HT208050."
I'am already using zsh Terminal but he doesn't found the ng commands.
Comment: Did you `npm install -g @angular/cli` ?
Comment: Have you tried raising this issue on Angular's Github?
Comment: @wentjun I am having the same issue, raised it an angulars github, they closed it and sent me here.  Apparently, they dont find it to be a bug lol.  Very helpful crowd over there  https://github.com/angular/angular-cli/issues/15692#event-2667473843
Comment: Same here, as before, Angular github is useless place to ask about angular issues
Answer: I also lost access to my commands after moving over to zsh following the Catalina upgrade. This fixed it for me:
source /Users/YOURUSERNAME/.bash_profile
In order to get these changes to persist, I used oh-my-zsh (https://github.com/robbyrussell/oh-my-zsh).
Install with curl:
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
Then modify your .zshrc file:
vi ~/.zshrc
Underneath this line: source $ZSH/oh-my-zsh.sh
I simply added the command I mentioned at the start of the post:
source /Users/YOURUSERNAME/.bash_profile
Save the file as you normally would with vi/vim: :wq
Oh-my-zsh is also capable of a lot of cool things so be sure to read the documentation.
Comment: Much appreciated, that fixed it for me.  Just needed to restart terminal
Comment: You on macOS, forget vi just type "open ~/.zshrc"
Comment: No worries! I'm glad it helped :)
Comment: True - should have mentioned vi is a bit of a pain for those who aren't familiar.
Answer: The angular-cli has to be installed on your machine.
install the cli by running the command : npm install -g @angular/cli
Comment: I tried uninstalling, reinstalling and I did not even have a project so there is no way to complain about angular version in my project being older than global cli version.  I also linked it, no success.  Angular github is useless, they just closed it and refered to ask on so
Comment: Yes, I'ts installed, but before the new version of Mac all was running well. Now I received this error : Your global Angular CLI version (8.0.4) is greater than your local
version (7.3.9). The local Angular CLI version is used.

To disable this warning use "ng set --global warnings.versionMismatch=false".
Comment: @Julianh1805 That's not an error its a warning, This is because of the angular-cli version specified in your projects package.json file is older than your global cli version. If you want to get rid of it, upgrade the project's angular version to match with the global veriosn of the cli (8.0.4 in your case)
Comment: I'm in the same situation, I tried every thing like you but it's not working.
Answer: check with node version you're on. Download here - https://github.com/nvm-sh/nvm
For me I encountered same problem with version 8.
nvm ls

it should list node version - using version 13 of node - worked for me.
 nvm install 13
 npm install -g @angular/cli

should work now.
Answer: If you had previously gone through the steps by sindresorhus to "Install npm packages globally without sudo" for bash, do them again for zsh. https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md


How to create a loading spinner method that include display:Block display: none using Selenium C#?

Question: I can not catch the loader in my test. I need to create a method that will help me to see when the loader is no longer visible. I can not select any of the page elements because of this problem.
Code attempted:
public static void SeeNoLoaderInQD()
{
    Actor.Wait.UntilElementIsNotDisplayed(Elements.QDLoader);
    Assert.IsTrue(Elements.SeeException.Count == 0);
}

Comment: can you add code you have tried?
Comment: public static void SeeNoLoaderInQD()
        {
            Actor.Wait.UntilElementIsNotDisplayed(Elements.QDLoader);
            Assert.IsTrue(Elements.SeeException.Count == 0);
        }
Answer: I would try something like this:
public static void WaitForElementAttributeValue(this IWebDriver driver, By by, string attribute, string value)
{
    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
    wait.Until(d => d.FindElement(by).GetAttribute(attribute).Contains(value));
}

You can call this method for your scenario like this:
driver.WaitForElementAttributeValue(By.Id("line-scale-loader"), "style", "display: none;");

When calling this method, you are telling WebDriver to wait until the WebElement's style attribute value is equal to display: none; meaning the loader is no longer visible.
Comment: Based on the HTML sample that was provided, the load spinner seems to appear at the top of the DOM so there was not risk of parent elements being hidden. `ExpectedConditions` is deprecated in .NET bindings and requires `DotNetSeleniumExtras.WaitHelpers` to use now, so I try to provide an example that does not require adding any other packages if possible.
Comment: This will only work if the specific element located contains this attribute. What if one of the parent elements have "display: none" which causes the desired element to not be displayed? Why not use the built in `ExpectedConditions` and handle both/all cases?
Answer: To check if a page is loaded, I usually check 3 criteria, those are:-

Is page ready?
Are ajax calls completed?
Is the spinner/loader invisible?

Sample code,
    public static void WaitForPageToLoad(IWebDriver driver)
    {
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
        wait.Until(driver =>
        {
            bool isPageReady = (bool)((IJavaScriptExecutor)driver).
                ExecuteScript("return document.readyState == 'complete'");
            bool isAjaxFinished = (bool)((IJavaScriptExecutor)driver).
            ExecuteScript("return jQuery.active == 0");
            bool isLoaderInvisible = (bool)((IJavaScriptExecutor)driver).
                ExecuteScript("return $('#line-scale-loader').is(':visible') == false");
            return isPageReady && isAjaxFinished && isLoaderInvisible;
        });
    }

Hope this helps.
Answer: Selenium has ExpectedConditions built in that you can use with WebDriverWait to handle situations like this. It might be the case that your wait for invisible is firing and passing before the loader becomes visible which could cause later actions to fail because the loader appears later. You might add a wait for visible and then a wait for invisible.
By qdLoaderLocator = By.Id("line-scale-loader");
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(qdLoaderLocator));
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(qdLoaderLocator));

Side note... don't use Asserts like
Assert.IsTrue(Elements.SeeException.Count == 0);

because when they fail, you will get
Expected: true
Actual: false

which doesn't tell you anything. Instead use one of the below options.
Assert.Zero(Elements.SeeException.Count, "Verify no exceptions");
Assert.AreEqual(0, Elements.SeeException.Count, "Verify no exceptions");

Now you will get
Verify no exceptions
Expected: 0
Actual: 2

In this case it might not seem terribly useful but you at least get more information than just true/false. When you start comparing strings, numbers, etc. it will be a LOT more useful.


Ballot problem with tie

Question:
We have two candidates $c_1$ and $c_2$. At the end of a ballot each candidate receives $p$-many votes.
What is the probability that $c_2$ has never been ahead of $c_1$ the whole process of vote counting? (assume that each path of votes has the same probability)

My approach:
We are allowed to use the ballot theorem: $c_1$ wins with $a$-many votes and $c_2$ loses with $b$-many votes ($a>b$). The number of paths where $c_1$ leads is given by ${a+b\choose a}\frac{a-b}{a+b}$.
First we define the sample space by $\Omega:=\left\{\omega\in\{-1,1\}^{2p}\right\}$ where $1$ rerpresents a vote for $c_1$ and $-1$ represents a vote for $c_2$. We define the set $A:=\{\omega\in\Omega\mid \sum\limits_{i=1}^{n}\omega_i\geq 0\text{ for each } 1\leq n\leq 2p\}$ which denotes the set of paths where $c_2$ never leads/$c_1$ always leads or has the same amounts of votes as $c_2$.
Now we consider a second ballot where $c_1$ got $p+1$-many votes and $c_2$ only $p$- many votes. The respective sample space is $\Omega':=\left\{\omega'\in\{-1,1\}^{2p+1}\right\}$. We know by ballot theorem that all paths where $c_1$ leads can be counted by ${2p+1\choose p}\frac{1}{2p+1}$. Let's denote this set of paths by $B$ where $B:=\{\omega'\in\Omega'\mid \sum\limits_{i=1}^{n}\omega_i\geq 1\text{ for each } 1\leq n\leq 2p+1\}$.
We construct a bijection between $A$ and $B$. Let be $\omega'\in B$ if we remove the first vote of $\omega'$ then we get a new path $\omega$ which lies in $A$. On the other hand, if we consider a path $\omega\in A$ and add a vote for $c_1$ at the beginning then we get a new path $\omega'$ which lies in $B$. Moreover, it is obviously that this mapping is injective. Hence, $|A|=|B|={2p+1\choose p}\frac{1}{2p+1}\implies P(A)=\frac{|A|}{|\Omega|}=\frac{1}{p+1}$.

Is this approach correct?
Comment: Doesn't Bertrand's ballot theorem gives the result directly? Separate one envelope. It belongs to $c_2$ with a probability of 0.5. Then calculate $c_1$ is always ahead of $c_2$ or tied to $c_2$ for the given $2p-1$ votes?
Comment: With my approach, I find $\frac{1}{2p+2}$.
Comment: @C.Koca an easy example shows that your approach is wrong.
Comment: You are right, removing an envelope changes nothing. Your result is correct.
Answer: While I can't comment on your approach, your result is correct.
The thing that confused me in the comments is that probability of $c_1$ is always leading or equal to $c_2$ within $2p$ votes distributed evenly is actually equal to $c_1$ is always leading or equal to $c_2$ within $2p-1$ votes with $c_1$ getting $p$ of them. Thus, removing a single envelope does not change the result.
In other words, we know that $c_1$ and $c_2$ will have a draw at the end of counting. So, for $c_1$ never to fall behind, the last envelope has to be for $c_2$ anyway. Thus, removing an envelope does not alter the probability.
Now we can use Bertrand's Ballot theorem directly for (p, p-1) votes, giving us $\frac{1}{p+1}$.
I have the simulation results and the simulation code here.

<code>def hitting_simulation(m,p):
    hit=0
    for j in range(m):
        votes=np.ones(2*p)
        while not sum(votes)==0:
            a=random.randint(0,2*p-1)
            votes[a]=-1
        voting=np.cumsum(votes)
        #print(voting)
        if any(voting<0):
            hit+=1
    return m-hit
</code>
Comment: I started the simulation for $p=2$.

Ballot problem with tie


Displaying elements based on search

Question: I would like the .box elements to show/hide based on the words the user searches for, so for example if a user types in 'Title2 Title1' because those words exists inside box one and two they will remain visible with the renaming .box elements hiding. All the text within the .box elements needs to be searchable not just that in the .title element.
Below is how far I've got. It's almost there but it's not quite working as hoped.
Any help would be great.
Many thanks.
<input placeholder="Search" id="search" type="text" />

Box Title1

      Box title one content

Box Title2

      Box title two content

Box Title3

      Box title three content

Comment: You should explain more on the remaining part you want to achieve
Answer: You need to use a different search method. :contains does not work as you expect. Consider the following example.

$(function() {
  function filter(e) {
    var term = $(e.target).val();
    if (term.length < 3) {
      $(".box").show();
      return;
    }
    $(".box").each(function(i, el) {
      if ($(".content", el).text().indexOf(term) >= 0) {
        $(el).show();
      } else {
        $(el).hide();
      }
    });
  }
  $("#search").keyup(filter);
});

<input placeholder="Search" id="search" type="text" />

Box Title1

Box title one content

Box Title2

Box title two content

Box Title3

Box title three content

So for example if on is entered, no filtering is performed. If one is entered, the script will look inside the content class of each box and if one is found in the text, it will be shown otherwise, it is hidden. If the User clears their search out, all items are shown.
Answer: Loop through all .boxs and using regex pattern matching, check either the title or content matches the search query. Show all matched boxes and hide all others
I have also fiddled it here
$("#search").on("input", function () {

      var searchables=$('.box');
      console.log(searchables)
      var query=$(this).val();
      searchables.each(function(i,item){

      var title=$(item).find('.title').text();
      var content=$(item).find('.content').text();
      var rgx=new RegExp(query,'gi');

      if(rgx.test(title) || rgx.test(content))
      {
                $(item).show();
      }
      else
      {
                $(item).hide();
      }

    })
})

Answer: Hide all box before iterate, then only show when match any words:

$("#search").on("input", function () {

   var search = $(this).val();

   if (search !== "") {

      var searchArray = search.split(" ");

      // Hide all .box
      $(".box").each(function () {
        $(this).hide();
      })

      searchArray.forEach(function(searchWord) {
         $(".box").each(function () {
            if($(this).is(':contains('+ searchWord +')') ) {
               $(this).show();
            }

         });

   });

   } else {
      $(".box").show();
   }

});

<input placeholder="Search" id="search" type="text" />

Box Title1

      Box title one content

Box Title2

      Box title two content

Box Title3

      Box title three content

Displaying elements based on search


How to create AVD with Android & (7.0) with Google APIs?

Question: When I downloaded and select "N" (API = 24) for the AVD, I see the following message on bottom right:

Consider using a System Image with Google APIs to enable testing with Google Play Services.

Is this image not available yet? or am I missing something? I dont see it in  the SDK Manager yet.
Comment: Late August and this is still an issue. Yay Google.
Comment: Yes, the issue continue... anyone have found a solution?? I tried using Android Studion 2.2 Beta but the problem exists too.
Answer: As of SDK Tools 25.1.7 and Intel x86 Atom_64 System Image Rev. 6, it appears that there is no longer a separate emulator image for the Google APIs - instead, the normal emulator image now includes the Google APIs by default.  So, the message shown in the "Recommendation" section when creating an AVD appears to be old/incorrect.
I was able to run this project (using gradlew installObaGoogleDebug), which requires Google Play Services for maps and other items, by selecting Nougat / API Level 24 / x86_64 / Android 7.0.

EDIT Nov. 3rd 2016
It appears this was a temporary issue with the emulator image.  As of SDK Tools 25.2.2 and Intel x86 Atom_64 System Image Rev. 7, when I try to run the same app on the same emulator image (API Level 24) I created above, it now says "OneBusAway relies on Google Play Services, which is not supported on your device".
However, it looks like there is now an API Level 25 (Android 7.1.1) emulator w/ ABI x86_64 available for download that does explictly include the Google APIs - see area circled in red below (note that the update message still seems to erronouesly appear):
Comment: Verified this now works. Update since August 23rd must have fixed something as the same emulator failed on the 23rd, but works now.
Answer: I had the same issue recently, I think it's probably a bug with the tool.
I was able to solve it by downloading the x86_64 version, and then it allowed me to use both the N x86 and N x86_64 emulator images.


Problemas com cifrão $ em JavaScript no VS Code

Question: Toda vez que faço um código que vai cifrão ${} ele não funciona, como se não reconhecesse, não sei como solucionar isso, peço ajuda. Já baixei conversores de string de modelo mas não consegui.
Segue o código, é um exemplo simples está em HTML, mas no JS é exatamente o mesmo problema.
Comment: https://pt.stackoverflow.com/a/78768/112052
Comment: https://pt.stackoverflow.com/q/458004/137387
Answer: o uso do cifrão, conforme você mencionou, no JavaScript, nós chamamos de Template Strings/Template Literals, o conjunto ${} é usado para passar uma expressão, e deve estar contida entre duas crases, veja um exemplo abaixo:
<code>console.log(`Quinze é ${a + b} e não ${2 * a + b}.`);
</code>
Observe se está passando a crase em volta,  outro detalhe é que entre ${} só pode ser passado expressões, como comparações, expressões numéricas, entre outros. Se ainda, assim, não conseguir resolver o problema, uma outra possibilidade é dar uma olhada no MDN Web Docs, segue o link do assunto em questão para você poder dar uma olhada
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Template_literals
Link no CodePen: https://codepen.io/liandro-wesley/pen/MWvOwQZ?editors=1011
Comment: Olá Liandro, muito obrigada por responder, muito mesmo! Estou iniciando no aprendizado sobre o assunto a respeito, e desde que o professor inseriu essas templates com cifrão eu estou tendo dificuldades em executar, estarei mandando um código simples que tentei executar como exemplo, está em HTML somente, mas no JS também estou com o mesmo problema. Desde já agradeço a atenção e a ajuda.
Comment: Liandro Wesley, veja no [nosso modelo de comportamento](https://pt.stackoverflow.com/help/behavior) que cumprimentos e agradecimentos devem ser evitados nas publicações. Outra cousa não oriente os usuários a usarem o site como mecanismo de [depuração ou revisão de código](https://pt.meta.stackoverflow.com/questions/514/o-que-fazer-com-perguntas-que-apenas-procuram-code-review-for-typos/518#518) isso está fora do nosso escopo, o autor do código deve ser [autossuficiente para depurar o próprio código](https://pt.meta.stackoverflow.com/questions/7785/como-debugar-programas-pequenos).
Comment: Quando verificar que o usuário ainda não sabe como usar ferramentas de depuração use o campo de comentários para orientar e instruir e não o campo de respostas.
Comment: Vitória, segue a solução para o seu problema. Estarei editando esta resposta colocando um código de exemplo


Na programação, o que significam "raw mode" e "cooked mode"?

Question: Ao ler uma das respostas à "Capture characters from standard input without waiting for enter to be pressed" me deparei com os termos "raw mode" e "cooked mode":

I found this on another forum while looking to solve the same problem. I've modified it a bit from what I found. It works great. I'm running OS X, so if you're running Microsoft, you'll need to find the correct system() command to switch to raw and cooked modes.

Já pesquisei, mas não acho seus significados, possivelmente porque estão mais para gírias, e se traduzirmos para o nosso idioma ("modo cru" e "modo cozido"), perde-se ainda mais o sentido. O que eles significam?
Comment: Poderia fornecer links? Acho que esses termos precisam de mais contextualização. Jogados assim realmente têm pouco significado. :D
Comment: @GabrielCavalcante esse site, assim como muitos outros, são gerados por tradutores automaticos, copiados de fontes do stackoverflow em inglês. Se olhar abaixo da pergunta tem um link escrito `source`. obs: A pergunta original foi removida do SOen.
Comment: @LuizFelipe - https://qastack.com.br/programming/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed
Comment: @GuilhermeNascimento, eu acho que a pergunta original é esta aqui: https://stackoverflow.com/q/421860/7445826
Comment: @LuizFelipe sim, o tal qstack que esta gerando o link assim `https://stackoverflow.com/programming/`, por isso não "navegou". Obs: link relacionado: [Confusion about raw vs. cooked terminal modes?](https://stackoverflow.com/q/13104460/1518921)
Answer: O par raw mode e cooked mode é usado para descrever a forma que um terminal recebe o input de caracteres. Raw é o contrário de cooked.

Um terminal em cooked mode, ou em modo canônico, processa cada caractere internamente e passa tudo para o terminal quando o Enter é pressionado. Esse é o padrão, e por isso é chamado também de canônico.
Já um terminal em raw mode, ou em modo não-canônico, os caracteres não são processados internamente e são mandados diretamente (de forma crua) pro terminal.

Essa terminologia raw ou cru é também usada em programação. Por exemplo, se você recebe um dado cru, ou raw data, quer dizer que esse dado não passou por nenhum tipo de sanitização, e que ainda precisa de tratamento para poder trabalhar com ele. Esse tratamento pode ser transformar strings em outros tipos de dado, pivotar uma tabela, entre outras coisas.


Change numbers into Arabic words

Question: When I use a macro to change numbers into Arabic words, it displays characters like this:
��� �������.
I adjusted Windows language options and enabled Arabic in system locale with the beta Unicode support enabled.
In Windows everything is set to Arabic by default: Apps & websites, Regional Format, Keyboard (except display language and speech).
In Excel language options I set Arabic as preferred but not as display language.
I noticed when I copy and paste the code into any other module or text file, it pastes Arabic letters incorrectly like this: æÇÍÏ ÇËäÇä ËáÇË ÇÑÈÚ
Screenshot of the function outcome in xlsm file: https://i.stack.imgur.com/B0YR5.png
MS Office 2021
<code>Public Function SpellIt(num_entry)
Dim LE
Dim PT
Dim iVal
Dim fFrac
Dim cDigit
Dim cFrac
Dim result

      LE = " جنيه "
      PT = " قرش  "
      iVal = Int(num_entry)
      cDigit = Digit_Translator(iVal)
      fFrac = Val(Right(Format(num_entry, "000000000000.00"), 2))
      cFrac = Digit_Translator(fFrac)
      If cDigit <> "" And fFrac > 0 Then result = cDigit & LE & " و " & cFrac & PT
      If cDigit <> "" And fFrac = 0 Then result = cDigit & LE
      If cDigit = "" And fFrac <> 0 Then result = cFrac & PT
      SpellIt = result

End Function

Private Function Digit_Translator(X)
Dim n
Dim c
Dim c1
Dim Digit1
Dim c2
Dim Digit2
Dim c3
Dim Digit3
Dim c4
Dim Digit4
Dim c5
Dim Digit5
Dim c6
Dim Digit6

      n = Int(X)
      c = Format(n, "000000000000")
      c1 = Val(Mid(c, 12, 1))
      Select Case c1
            Case Is = 1: Digit1 = "واحد"
            Case Is = 2: Digit1 = "اثنان"
            Case Is = 3: Digit1 = "ثلاث"
            Case Is = 4: Digit1 = "اربع"
            Case Is = 5: Digit1 = "خمس"
            Case Is = 6: Digit1 = "ست"
            Case Is = 7: Digit1 = "سبع"
            Case Is = 8: Digit1 = "ثمان"
            Case Is = 9: Digit1 = "تسع"
      End Select

      c2 = Val(Mid(c, 11, 1))
      Select Case c2
            Case Is = 1: Digit2 = "عشر"
            Case Is = 2: Digit2 = "عشرون"
            Case Is = 3: Digit2 = "ثلاثون"
            Case Is = 4: Digit2 = "اربعون"
            Case Is = 5: Digit2 = "خمسون"
            Case Is = 6: Digit2 = "ستون"
            Case Is = 7: Digit2 = "سبعون"
            Case Is = 8: Digit2 = "ثمانون"
            Case Is = 9: Digit2 = "تسعون"
      End Select

      If Digit1 <> "" And c2 > 1 Then Digit2 = Digit1 + " و" + Digit2
      If Digit2 = "" Then Digit2 = Digit1
      If c1 = 0 And c2 = 1 Then Digit2 = Digit2 + "ة"
      If c1 = 1 And c2 = 1 Then Digit2 = "احدى عشر"
      If c1 = 2 And c2 = 1 Then Digit2 = "اثنتى عشر"
      If c1 > 2 And c2 = 1 Then Digit2 = Digit1 + " " + Digit2
      c3 = Val(Mid(c, 10, 1))
      Select Case c3
            Case Is = 1: Digit3 = "مائة"
            Case Is = 2: Digit3 = "مئتان"
            Case Is > 2: Digit3 = Left(Digit_Translator(c3), Len(Digit_Translator(c3))) + "مائة"
      End Select
      If Digit3 <> "" And Digit2 <> "" Then Digit3 = Digit3 + " و" + Digit2
      If Digit3 = "" Then Digit3 = Digit2

      c4 = Val(Mid(c, 7, 3))
      Select Case c4
            Case Is = 1: Digit4 = "الف"
            Case Is = 2: Digit4 = "الفان"
            Case 3 To 10: Digit4 = Digit_Translator(c4) + " آلاف"
            Case Is > 10: Digit4 = Digit_Translator(c4) + " الف"
      End Select
      If Digit4 <> "" And Digit3 <> "" Then Digit4 = Digit4 + " و" + Digit3
      If Digit4 = "" Then Digit4 = Digit3
      c5 = Val(Mid(c, 4, 3))
      Select Case c5
            Case Is = 1: Digit5 = "مليون"
            Case Is = 2: Digit5 = "مليونان"
            Case 3 To 10: Digit5 = Digit_Translator(c5) + " ملايين"
            Case Is > 10: Digit5 = Digit_Translator(c5) + " مليونا"
      End Select
      If Digit5 <> "" And Digit4 <> "" Then Digit5 = Digit5 + " و" + Digit4
      If Digit5 = "" Then Digit5 = Digit4

      c6 = Val(Mid(c, 1, 3))
      Select Case c6
            Case Is = 1: Digit6 = "مليار"
            Case Is = 2: Digit6 = "ملياران"
            Case Is > 2: Digit6 = Digit_Translator(c6) + " مليارات"
      End Select
      If Digit6 <> "" And Digit5 <> "" Then Digit6 = Digit6 + " و" + Digit5
      If Digit6 = "" Then Digit6 = Digit5
      Digit_Translator = Digit6

End Function
</code>
Comment: Possibly an issue with your VBA code.  I certainly have no problem using VBA to place arabic characters into an Excel cell, even with all US English settings.
Comment: I've posted an Answer that worked in my case.
Comment: I do not have the Arabic SA language pack installed.
Comment: I used your code... thank you... but, if `iVal` and `num_entry` not **Dim**entioned as Double, it sometimes converts the number wrong... try with `2,495,159,565.00` for example...
Answer: The problem has been solved by installing the "Arabic SA" Language Pack from MS Office website.
Language pack downloaded from this link:
https://support.microsoft.com/en-us/office/language-accessory-pack-for-office-82ee1236-0f9a-45ee-9c72-05b026ee809f?ui=en-us&rs=en-us&ad=us
Screenshot: https://i.stack.imgur.com/4w1ka.png
Rebooted the PC and all I needed to do is to re calculate formulas (or just edit the cell and Click Enter without modifying anything).
This is so weird as the "Arabic Egypt" is the one installed in the windows.
Comment: There may be another solution, as I do not have the Arabic-SA language pack installed. (My installed languages are only English and  Hebrew.
Comment: I've done a lot of search. it's been 3 months with this issue. I know another person who has the same problem. in his case an excel file imported from a cloud ERP App.

Change numbers into Arabic words


curl_init php não funciona em url amigável?

Question: Estou fazendo uns testes com curl_init php
Acontece que tenho os links assim:
http://localhost/produto/novo

Internamente ele acessa o arquivo novo.php, mas estou usando htaccess para trabalhar com URLs amigaveis
Preciso fazer um arquivo que ira aceitar consultas via curl_init do php que está em outro servidor
Se eu abrir o navegador e digitar:
http://localhost/produto/novo?codigo=1

Ele aceita beleza, ou seja, a pagina esta operando normalmente e aceitando os parametros.
Mas se eu uso essa mesma URL no curl_init ele não aceita, ele me traz o conteudo da index.
Agora se eu coloco a url com o nome do arquivo ele aceita:
$url = http://localhost/produto/novo.php

o curl_init só acessa arquivos diretamente, não da pra usar url amigaveis nele?
Minha requisição:
    ...
    $dados = array("pedidos" => $pedidos, "status" => $status, "loja" => $loja);

    $url = "http://220.127.116.11/recebe.transito.php";
    AQUI EU GOSTARIA DE COLOCAR A URL AMIGAVEL
    $url = "http://188.8.131.52/recebe.transito"; // SEM O .PHP
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt_array($curl, array(CURLOPT_FOLLOWLOCATION => true));
    curl_setopt($curl, CURLOPT_POSTFIELDS, $dados);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($curl);
    //$res = curl_getinfo($curl, CURLINFO_HTTP_CODE); // Pegar o código de resposta

    $result = json_decode($res);
....

Meu .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

Comment: poste seu .htaccess
Comment: Você precisa postar o código do seu `htaccess` e o código da sua requisição `curl`, se não as respostas vão ficar muito 'especulativas'
Comment: "Preciso fazer um arquivo que ira aceitar consultas via curl_init do php que está em outro servidor". Em outro servidor ou outro arquivo/pasta? Os dois servidores estão na sua máquina rodando em portas diferentes? Elabore melhor o cenário para podermos ajudar melhor.
Comment: Apenas adiantando e respondendo sua pergunta do título: sim, o curl funciona perfeitamente com url amigável. O curl é um cliente http como o navegador. O problema deve estar na implementação.
Comment: Coloquei os códigos talvez facilite a compreensão
Comment: Uma coisa interessante, o uso de URL amigável não é um redirecionamento mas sim um "include" de arquivos, ou seja o index é responsável por exibir  o conteúdo de outros arquivos conforme a requisição, dessa forma o curl_init não deveria mostrar o conteúdo do index e sim  do include, a impressão que dá é: ou o curl_init não envia a url completa ou o php não compreende a url enviada pelo curl quando não ha um fim de arquivo como .php ou .html
Comment: Amigo, quando você diz que está exibindo o conteúdo do index.php, você quer dizer que exibe o código do index.php, e não o resultado gerado pelo mesmo? Se sim, seu problema é na configuração do seu servidor web. Você usa apache?
Comment: Não é o codigo não... é a pagina index (html)... é como se ele não entendesse que existe uma requisição em um arquivo entao ele mostra o conteudo do index.
Answer: Por default o curl não segue as regras de redirect escritas no seu .htaccess. É necessário adicionar a flag CURLOPT_FOLLOWLOCATION antes:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
Comment: De onde você tirou essa informação, meu jovem? Poderia adicionar essa informação? Porque, se o navegador reconhece, porque não o `Curl`?
Comment: Wallace, redirect é diferente de rewrite
Comment: Joel veja que no meu script ja tenho essa opção ativa, mas ainda não funciona


Trouble Transferring data from FTP server to S3 via stream using Python

Question: I am looking to transfer the contents of a folder from an ftp server to a bucket in s3 without writing to disk. Currently, s3 is getting all of the names of the files in the folder, but none of the actual data. Each file in the folder is only a few bytes. I'm not quite sure why it is not uploading the whole file.
from ftplib import FTP
import io
import boto3

s3= boto3.resource('s3')

ftp = FTP('ftp.ncbi.nlm.nih.gov')
ftp.login()
ftp.cwd('pubchem/RDF/descriptor/compound')

address =  'ftp.ncbi.nlm.nih.gov/pubchem/RDF/descriptor/compound/'

filelist = ftp.nlst()

for x in range(0, len(filelist)-1):
    myfile = io.BytesIO()
    filename = 'RETR ' + filelist[x]
    resp = ftp.retrbinary(filename, myfile.write)
    myfile.seek(0)
    path = address + filelist[x]
    #putting file on s3
    s3.Object(s3bucketname, path).put(Body = resp)

ftp.quit()

Is there any way to make sure the whole file is uploaded?
Answer: We can transfer the data from FTP server to S3 via stream using Python. The data won't download in /tmp location in AWS Lambda. It will directly stream the data from FTP to S3 bucket.
from ftplib import FTP
import s3fs

def lambda_handler(event, context):
    file_name = "test.txt" #file name in ftp
    s3 = s3fs.S3FileSystem(anon=False)
    ftp_path = "<ftp_path>"
    s3_path = "s3-dev" #S3 bucket name

with FTP("<ftp_server>") as ftp:
    ftp.login()
    ftp.cwd(ftp_path)
    ftp.retrbinary('RETR ' + file_name, s3.open("{}/{}".format(s3_path, file_name), 'wb').write)

Answer: I had the same issue and got it to work when I changed .put() to read the actual file in from the location that it was saved in. So something like this where you aren't handling the resp directly :
s3.Object(s3Bucketname, filename).put(Body=open(filename, 'rb'))


How do I programatically add address to commerce order

Question: I've a subscribe form on my website which i've got working(ish). So far i've got it asking user to input name, address, email, password and the subscription level + starter kit (from a list of promoted commerce items).
Once a user hits 'subscribe' the module creates a blocked user account (it will be activated by Paypal IPN listener if they pay), adds the commerce order (at checkout stage, thanks to Ryan for the script!) and then redirects to paypal for appropriate payment.
Up to this point i'm happy with everything except that the recorded order doesn't contain the address the user entered on the subscribe form and I can't figure out how do do this.
Has anybody managed it before,  just point me in the direction of the function and i'll go from there.
Thanks
Answer: To record the address on the order, you must create a customer profile of the relevant type (billing information or, if you have Commerce Shipping on the site, shipping information), populate its addressfield value, and reference it from the order you've created. My recommendation would be to use the entity_metadata_wrapper() from the Entity API to manipulate those field values.
The addressfield on the customer profile you need to populate is commerce_customer_address, and the reference field on the order is commerce_customer_billing (or _shipping respectively).
Comment: Thanks a lot.  I've never really used Entity metadata wrappers before.  WOW!  it's opened my eyes to a much easier way of handling data that's even slightly related to each other.


Add video URL, with live preview option

Question: I am creating a form which allows people to enter a video url. Standard input form, to accept a URL like:
http://video.google.com/videoplay?docid=1299927595688205543

I would like to add a button (within the form, which says something like [preview video]). Basically that button/link appends the link they entered into the input field, to this code:
google video

This is to be available prior to form submission.
Answer: <form id="video_upload_form" action="">
    Video URL
    <input type="text" id="video_input_box" value="" />

    <input type="submit" value="Add Video" />
</form>

Preview Video

Also here it is as a JSFiddle: http://jsfiddle.net/Treffynnon/CEMpT/
You will need to do some validation on the URL supplied by the user before putting it into the preview link, but I will leave that part up to you as you have not asked for help with it in your question.
Comment: so what do I put in the input field ? @Treffynnon
Thanks for the quick response by the way
Comment: I am struggling to figure out how to add this within a form.
Comment: Thanks, but the link is not being passed to the preview link: I get Preview Video
I guess thats what you mean by url validation ?
Comment: strike that, lol wicked it works. But can we code it so we dont need to click [add video] button. Just want it to parse via the preview video link
Comment: You can take look at jQuery's `$.keyup` event to get the url as they type in the input. I think this is what you mean anyway.
Comment: Kinda. I was looking to have NO submit button. User enters video url in input field, then when they click OUT of that input field, the URL is appended to your script, so that when they click the link, the lightbox opens up. Any suggestions ( we are 80% there ) lol
Comment: Cheers mate, awesome, we now have live preview :) yayyyy thanks so much.

Add video URL, with live preview option


Setting alpha of background of layout using setAlpha doesn't work

Question: I am a bit confused.
I have this :
this.opacitySeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            // updating opacity of layout
            RelativeLayout ledColor;
            for(int index = 0; index < selectedLedsIndices.size(); index++) {
                ledColor = (RelativeLayout)ledsLayout.getChildAt(index).findViewById(R.id.led_color);
                ledColor.setAlpha(((float)i) / 255);
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

I am trying to change the opacity of a layout using the progress value of a seekbar. The value of the seekbar goes from à to 255. But when running, the opacity of the layout doesn't change. I'm getting no error trace. It just doesn't want to change. How that?
I am running the app on api 24 (and my app should target api from 19 to 27).
Comment: What is  `ledsLayout` and what is `ledColor`? Post your xml and make clear which layout you want to change its alpha and how you access it.
Answer: Use ledColor.getBackground().setAlpha(...)
Comment: it still doesn't work...........I am working inside a fragment, but it shouldn't be a problem...I really don't see where is the problem.


Drush on Windows trouble

Question: I had installed Drush for Windows and trying use it.
I open directory (in CLI, in my example: Z:\home\www\drush-test) where I want install drupal and run drush dl command:
Z:\home\drush-test\www>drush dl
Install location Z:/drush/drupal-7.25 already exists. Do you want to overwrite it? (y/n):

But i need install drupal to Z:\home\drush-test\www not Z:/drush/drupal-7.25 (this directory where Drush installed)
Also I trying using drush status in my old project (drupal installed). Drush don't see my drupal:
Z:\home\comp\www>drush status
X-Powered-By: PHP/5.3.13
Content-type: text/html; charset=utf-8

 PHP executable        :  php.exe
 PHP configuration     :  Z:\usr\local\php5\php.ini
 PHP OS                :  WINNT
 Drush version         :  7.0-dev
 Drush configuration   :
 Drush alias files     :

Z:\home\comp\www>ls
CHANGELOG.txt       LICENSE.txt      cron.php     nbproject   update.php
COPYRIGHT.txt       MAINTAINERS.txt  includes     profiles    web.config
INSTALL.mysql.txt   README.txt       index.php    robots.txt  xmlrpc.php
INSTALL.pgsql.txt   UPGRADE.txt      install.php  scripts
INSTALL.sqlite.txt  __files          misc         sites
INSTALL.txt         authorize.php    modules      themes

Z:\home\comp\www>

(Drupal 7 installed in this directory)
Windows 8.1, PHP 5.3
Comment: It seems you have two separate problems, one being regarding status, and one regarding pm-download (dl). Please ask two separate questions. Also your title suggests the problem is windows related, but from the question I see no reason to believe it would be.
Comment: I think Drush for some reason can't see other directories apart from its directory
Answer: Reinstalling Drush for Windows fix this problem.

Drush on Windows trouble


Extract text between multilevel repetitive xml tags using Php

Question: I am trying to extract text between Multilevel XML tags.

This is the data file
<eSearchResult>
    <Count>7117</Count>
    <RetMax>10</RetMax>
    <RetStart>0</RetStart>
    <QueryKey>1</QueryKey>
    <WebEnv>
    NCID_1_457044331_188.8.131.52_9001_1401819380_1399850995
    </WebEnv>
    <IdList>
    <Id>24887359</Id>
    <Id>24884828</Id>
    <Id>24884718</Id>
    <Id>24884479</Id>
    <Id>24882343</Id>
    <Id>24879340</Id>
    <Id>24871662</Id>
    <Id>24870721</Id>
    <Id>24864115</Id>
    <Id>24863809</Id>
    </IdList>
    <TranslationSet/>
    <TranslationStack>
    <TermSet>
    <Term>BRCA1[tiab]</Term>
    .
    .
    .
    </TranslationStack>
    </eSearchResult>

I just want to extract the ten ids between <ID></ID> tags enclosed inside <IdList></IdList>.
Regex gets me just the first value out of the ten.
    preg_match_all('~<Id>(.+?)<\/Id>~', $temp_str, $pids)
the xml data is stored in the $temp_Str variable and I am trying to get the values stored in $pids
Any other suggestions to go about this ?
Comment: Can you add the php code that has the regex?
Comment: @mrk added in the post above.
Answer: You should use php's xpath capabilities, as explained here:
http://www.w3schools.com/php/func_simplexml_xpath.asp
Example:
<?php
$xml = simplexml_load_file("searchdata.xml");
$result = $xml->xpath("IdList/Id");
print_r($result);
?>

XPath is flexible, can be used conditionally, and is supported in a wide variety of other languages as well.  It is also more readable and easier to write than regex, as you can construct conditional queries without using lookaheads.
Comment: @Vignesh as a disclaimer, I don't have PHP setup on this machine, so I won't be able to fully test these code snippets.  According to the documentation for simplexml_load_file you should be able to pass in a URL to the xml file.  Please look here: https://php.net/manual/en/function.simplexml-load-file.php
Comment: The data I have is in a file pointer. Its retrieved from a online search from Pubmed website. All my xml data is in a variable. Is there a way I can use a variable in the xpath functionality? @stephen
Answer: Using preg_match_all (http://www.php.net/manual/en/function.preg-match-all.php), I've included a regex that matches on digits within an <Id> tag.  The trickiest part (I think), is in the foreach loop, where I iterate $out[1].  This is because, from the URL above,

Orders results so that $matches[0] is an array of full pattern
  matches, $matches[1] is an array of strings matched by the first
  parenthesized subpattern, and so on.

preg_match_all('/<Id>\s*(\d+)\s*<\/Id>/',
   "<eSearchResult>
<Count>7117</Count>
<RetMax>10</RetMax>
<RetStart>0</RetStart>
<QueryKey>1</QueryKey>
<WebEnv>
NCID_1_457044331_22.214.171.124_9001_1401819380_1399850995
</WebEnv>
<IdList>
<Id>24887359</Id>
<Id>24884828</Id>
<Id>24884718</Id>
<Id>24884479</Id>
<Id>24882343</Id>
<Id>24879340</Id>
<Id>24871662</Id>
<Id>24870721</Id>
<Id>24864115</Id>
<Id>24863809</Id>
</IdList>
<TranslationSet/>
<TranslationStack>
<TermSet>
<Term>BRCA1[tiab]</Term>
</TranslationStack>
</eSearchResult>",
$out,PREG_PATTERN_ORDER);
foreach ($out[1] as $o){
      echo $o;
      echo "\n";
}
?>

Comment: Assuming WebEnv looks like this: `
NCID_1_457044331_220.127.116.11_9001_1401819380_1399850995
NCID_2_222222
`, then the regex, `'/\s*([0-9A-Za-z\.\_\n]+)\s*<\/WebEnv>/s'` will do the trick.  The key is the ending '/s' modifier to switch to "single line" mode. Read more about regex modifiers here:  http://php.net/manual/en/reference.pcre.pattern.modifiers.php
Comment: No need for the `U` modifier - its just slowing down the match and confusing things. That, and its never needed. In other words: _Never use the `U` ungreedy flag!_
Comment: If I want to search for someother tag between which there are alpha numeric multi line sentences, How will I tweak this regex?
Answer: Do not use PCRE to parse XML. Here are CSS Selectors and even better Xpath to fetch parts of an XML DOM.
If you want any Id element in the first IdList of the eSearchResult
/eSearchResult/IdList[1]/Id
As you can see Xpath "knows" about the actual structure of an XML document. PCRE does not.
You need to create an Xpath object for a DOM document
$dom = new DOMDocument();
$dom->loadXml($xmlString);
$xpath = new DOMXpath($dom);

$result = [];
foreach ($xpath->evaluate('/eSearchResult/IdList[1]/Id') as $id) [
  $result[] = trim($id->nodeValue);
}
var_dump($id);

Answer: use this pattern (?:\<IdList\>|\G)\s*\<Id\>(\d+)\<\/Id\> with g option
Demo
Comment: `$pattern = "(?:\|\G)\s*\(\d+)\<\/Id\>";
 preg_match_all($pattern, $string, $matches);`
This gives me unexpected ? error


Find $1 \le a < b \le n$ such that $a\cdot b + a + b = n\cdot (n+1)/2$

Question:
Find $1 \le a < b \le  n$ such that $$a\cdot b + a + b = \frac{n\cdot (n+1)}2$$

Is there a more efficient way than picking $a$ or $b$ and trying all values between $1$ and $n$ ?
Comment: Since that is an increasing function of $a$ and $b$ you can certainly limit your search to a much smaller range, and adjust your tests efficiently.
Comment: @EthanBolker thank you for your comment. Can you please say more?
Comment: In light of @CYAries answer and comments there it seems that you want an integer solution for large $n$. That's a factoring problem known to be hard, so my observation won't be much help.
Answer: $(a+1)(b+1)=\dfrac{n^2+n+2}{2}$.
If $a$ and $b$ are restricted to integers, consider the factors of $\dfrac{n^2+n+2}{2}$.
Comment: @גלעדברקן:  He has already restricted the search to about $\frac n{\sqrt 2}$, so that is an improvement.  You also know that you need a factor greater than $\frac n2$ because otherwise the other factor will be greater than $n$.  Both these ignore the addition of $n+2$, but that is small for large $n$.
Comment: Thank you for a great insight. Isn't finding factors of (n^2 + n + 2)/2 on the order of the square root of that, which is basically still O(n)?
Comment: You may find the prime factorization of the number. For example, $1176=2^3\times 3\times7^2$. Its positive factors are those numbers of form $2^a3^b7^c$, where $a\in\{0,1,2,3\}$, $b\in\{0,1\}$ and $c\in\{0,1,2\}$.
Comment: Sure, but to find prime factors of `x`, we still need to explore all numbers below the square root of `x`, which in this case is on the order of magnitude of `n`. No? (My question is whether there is a more efficient way than O(n).)
Comment: Yes. If $n$ is large, it is still very difficult.


How do I interpret or explain loess plot?

Question: I used the following R code:
ggscatter(DF_w, x = "Age", y = "Value",
          add = "loess", conf.int = TRUE
          )

to get this plot:

However, I don't understand how I can report this in a scientific paper or presentation. I understand the graph suggests a non-linear relationship between X Age and Y Value, where there is some variability until late life when Value declines with increased Age. Is that all there is to it? Is there a way to show this is a significant relationship with loess or do I need to carry out a regular regression / correlation to determine significance?
Any information on interpreting such plots is appreciated.
Comment: Loess is for exploration and smoothing.  It's a bit of a stretch to use it to demonstrate "significance," because what would the null hypothesis be?
Comment: @whuber: one could do something ANOVA-like and compare the loess fit to an intercept-only model, or to a simple linear regression. Perhaps some kind of permutation test could be used?
Comment: @Stephan It's unclear how you would compute the DF for an ANOVA-like solution.  Permutation tests and bootstrapping are always available, of course--but they still require formulating a test statistic.  I wonder what statistic someone would select *before* examining the data?  I also wonder whether and to what extent this approach might be superior to standard nonparametric trend tests, if at all.
Comment: As whuber has pointed out, you can use it for exploring apparent trends in the data.  In this case, your response variable appears more variable for smaller values of Age.  Additionally, a cubic or quintic trend is shown
Comment: @whuber do you have any suggestions on how to further explore this data? I am trying to show how value is changing with Age but a normal regression doesn't seem appropriate
Comment: @whuber: yes, of course, we can't use ANOVA because we have no idea about the degrees of freedom. As a test statistic, I would still use proportion of variance explained, just as in ANOVA (as I said, compared to either an intercept-only model or a simple linear regression). What I am struggling with is setting up a permutation test...
Comment: Why are you relating this to age at all? If it's just to check whether there is a relationship and because age is measured for all patients, that is fine by me, but it's half an answer to your question. No ideas about what the relationship should or could be mean that interpretation is necessarily difficult. There isn't a statistical answer without a (medical? biological?) question.
Comment: @Stephan One common way is to fix the fit under the null hypothesis (likely a constant equal to the mean of the responses in this case) and permute the residuals, repeating the Loess calculation for each permutation.   This gives you the permutation distribution of the proportion of variance under the null hypothesis.  Compare it to the value for the actual data.  I will post an answer with the details.
Comment: One could ask whether a linear regression line (or other functional form) could fit within the confidence boundary. You could also interpret the relationship between **value** and **Age** between inflection points *a la* value decreases with age until about Age 27, when it increases untill about age 55, when it again declines.
Comment: @NickCox, it is a value from MRI brain scan. I just wanted to keep the question as simple as possible for anyone to answer / use in future situations.
Answer: Bootstrapping or a permutation test (as suggested by Stephan Kolassa) will help you assess the significance of the apparent (but complex) association in the plot.
You need to adopt a reasonable measure of what the Loess fit has accomplished.  One is the mean squared residual.  (Many others are possible, but a discussion of that is not pertinent here.)  Let's call this the "loss."
You also need to formulate a specific null hypothesis.  The simplest is that the data exhibit no trend: that is, they vary randomly and independently around a common value.  The best way to estimate this common value with mean squared error loss is to compute its arithmetic mean.  With a sufficient amount of data--often ten or more observations suffice--the differences between the response ("Value" in the plot) and this mean will be only slightly (negatively) correlated and can stand in as surrogates for the true random errors.
The permutation distribution in this setting is the distribution of the losses associated with all possible permutations (reorderings) of the residuals after conducting a Loess fit.  Under the null hypothesis, all these permutations are equally likely.
The permutation test compares the actual loss to the permutation distribution of losses.  As a practical matter, the latter is estimated by means of a few random permutations.  (There are far too many permutations to permit generating them all.)

Here, to illustrate, are data generated with no inherent trend along with a permutation distribution estimated from 500 draws.  The vertical red line shows the loss for these data: it is close to the middle.  Its p-value is computed as usual for a two-sided test: the red line splits the histogram left and right into two areas and the p-value is twice the smaller area.  Very small p-values are called "significant" and taken as evidence of some kind of trend.  The shape of the Loess plot (shown at left) helps you interpret just what that trend might be.

The large, anodyne p-value is consistent with the trend-free method of generating these data.
For data closer to those in the question, the result is different:

The actual mean squared error of $0.000735$ is inconsistent with the squared errors typical of the permutation distribution: this is a significant trend.  The data plot at the left suggests the trend is principally a decrease in mean values from $0.31$ at age 60 to $0.25$ at ages 80 and over.
BTW, it is no surprise that the actual statistics in both cases have approximately the same values: they both estimate the error variance, which was equal to $0.025^2 = 0.000625$ in both cases.  The curvilinear trends in the second instance, though, cause the simple fit (under the null hypothesis) to be poorer, thereby shifting the permutation distribution to higher values, as you can see by comparing the two figures.

The R code needed is simple, clear, and efficient. fit performs the Loess fit while stat uses that to compute the mean squared error.
fit <- function(y, x, ...) lowess(x, y, ...)
stat <- function(y, x) mean((y -  fit(y, x)$y)^2) # Mean squared error loss

Given a data frame object X with Value and Age columns to store the response and explanatory variables, respectively, the permutation distribution is estimated by computing predicted values and residuals under the null hypothesis and then iteratively permuting the residuals (with the sample function) and recomputing the loss.
  predicted <- mean(X$Value)
  residuals <- X$Value - predicted
  dsample <- replicate(5e3, stat(predicted + sample(residuals), X$Age))

In this case, after about one second of computation, dsample winds up with 5e3 ($5000$) values randomly drawn from the permutation distribution.  The figures are then created by applying hist to dsample to show these values.
  # Compute the p-value
  actual <- with(X, stat(Value, Age))
  stats <- c(actual, dsample)
  p <- mean(stats <= actual)
  p <- 2 * min(1/2, p, 1-p)
  # Display the results
  hist(dsample, freq=FALSE, xlim=range(stats),
       col=gray(.95),
       sub=paste("p-value is approximately", signif(p, 2)),
       main="Simulated Null Permutation Distribution",
       xlab = "Mean Squared Difference")
  abline(v = actual, lwd=2, col="Red") # The statistic for the data

One caveat: I had to tune this Loess fit by specifying a relatively short width for its search radius.  This frequently is the case.  An honest permutation test must implement this fine-tuning in some automatic way and apply it to each permutation.  Otherwise, the original (hand-tuned) fit will be too good and the resulting p-value will be too small--perhaps far too small.  People often use some sort of cross-validation technique for such automatic tuning.
Comment: @SingleMalt: I sort of agree. Permutation tests for simple situations are easy enough (e.g. for the equivalent of a t test for the means in two groups), and indeed some such are implemented in R and other software. But more complex situations may require a lot of thought, indeed, as to the test statistic and which permutation scheme represents the null hypothesis best. One could argue that having to think about this is a Good Thing, compared to blindly applying a test without understanding these factors. Incidentally, I liked Good's *Permutation, Parametric, and Bootstrap Tests of Hypotheses*.
Comment: @Single Aware that many readers will not know `R` well, I explained the code, including saying explicitly what `sample` does.  Your summary is accurate, although a bit oversimplified (which is fair for any very short summary).
Comment: I read the text then went through the code neglecting to then remember the commentary that function sample was used to do the permutation. A permutation test is probably an underrated tool—after viewing this question I had not considered it as a solution to it. Possibly and speculatively, its under use is because it requires some tailoring to the context, and maybe off the shelf functions to perform it are not so common.
Comment: @Single Those are interesting thoughts (I mean that truly, not as dismissive hyperbole).  But since bootstrapping can sort of be automated, as in the `boot` function in `R`, permutation tests could be automated just as readily, one would think.  As always, though, there is no substitute for thinking about the problem... .
Comment: So under the null of no trend, the sample mean is taken. Then the residuals are found, and these are "permuted" by sampling from them all without replacement, and adding them back to the mean. These are then run through loess and the MSE found, and then this is compared with the actual loess MSE. Is this a correct summary? There is a very slight readability reliance on knowing that the sample function with all values and without replacement is a permutation.
Comment: @Stephan Good points.  I studied the entirety of Good's book when it came out and continue to use it as a reference.
Comment: @StephanKolassa have heard that encouraging thinking at the outset given as a reason for Bayesian techniques also. The book by Good does look a readable reference. "A growing recognition that most real-world data are drawn from mixtures of populations", which is in the third edition preface, not only shows why permutation tests may be more flexible than other techniques but is useful to remember.
Comment: @Whuber, thanks for this. If you have a chance, I have asked a new question trying to apply (to an extent) what you answered here in a more hypothesis driven way. https://stats.stackexchange.com/questions/557675/how-to-interpret-polynomial-regression-bootstrap-output
Answer: First off, it's extremely good practice to also show the original data, which puts the loess plot into context. Here, the context is that there is still a lot of variation in the data. For instance, the initial dip looks rather strange and could easily be due to noise - and we only see this because we see the full point cloud, not only the loess line with the confidence band. So this is good.
You ask two questions: one about interpretation, the other about significance. In terms of interpretation, I would discuss the downward slope at the right end, but per above, not really trust the dip in the middle.
In terms of significance, this is harder. You could try to assess whether your loess model explains significantly more variation in the data than a comparison model, like an intercept-only model (a horizontal flat line), or a simple linear regression (a slanted straight line). This is what ANOVA does. The problem is that the standard F test in ANOVA requires knowing how many parameters (degrees of freedom) your model used - and that is notoriously difficult to know in the case of a loess model. Greg Snow's answer to How do I find a p-value of smooth spline / loess regression? gives a few tentative ideas in his penultimate paragraph (though not in terms of variance explained, but his ideas could be adapted to this test statistic).
However, as Greg also notes in his answer, assessing the significance of a spline fit can be done in an ANOVA framework. Given the suspicious behavior of your loess fit, I would suggest that you try a fit using natural or restricted cubic splines with few knots, then test this spline fit against the more parsimonious linear fit.


How to retain Magento customer session throughout all pages?

Question: I am creating customer login using custom php code. I am using API calls for creating the frontend, so I need to maintain the logged in session values throughtout all the pages once the customer has logged in.
Code in a.php
require_once "../magento/app/Mage.php";
Mage::app('default');
umask(0);
Mage::getSingleton('core/session', array('name' => 'frontend'));
$session = Mage::getSingleton('customer/session', array('name' => 'frontend'));

$session->start();
if (!empty($email) && !empty($password )) {
    try {
        $a = $session->login($email, $password );
        $session->setCustomerAsLoggedIn( $session->getCustomer() );
        if ($session->getCustomer()->getIsJustConfirmed()) {
            $this->_welcomeCustomer($session->getCustomer(), true);
        }
    }
}

I am able to log in using this code but I need to maintain this logged in session throughout all the pages.
I tried to get the logged in user information from other page. But I can't.
Code in b.php
require_once "../magento/app/Mage.php";
umask(0);
Mage::app('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));

$session = Mage::getSingleton('customer/session');
$session->start();
var_dump(Mage::getSingleton('customer/session')->isLoggedIn());

if($session->isLoggedIn()) {
    echo 'User logged In';
} else {
    echo 'User not logged In';
}

After calling the page a.php and when I call b.php in the same browser, I need the customer information of the user logged in using a.php? Is that possible? Can anyone help me in this?
Answer: Try this one

if(Mage::getSingleton('customer/session')->isLoggedIn()) {
     $customerData = Mage::getSingleton('customer/session')->getCustomer();
      echo $customerData->getId();
 }
Comment: getCustomer()
Call this function at the end
Comment: Hi Hassan Ali Shahzad,

Its working ..!! :) Thanks a lot for your help
Comment: In chrome may be cache issue.
If its working then please select the answer and rank up for me :-)
Comment: @user3755732 if hassan's solution is working then you should give them upvote
Answer: <?php

require_once "../magento/app/Mage.php";

Mage::app('default');

umask(0);

Mage::getSingleton('core/session', array('name' => 'frontend'));

var_dump(Mage::getSingleton('customer/session')->isLoggedIn());
// print true

if(Mage::getSingleton('customer/session')->isLoggedIn()) {
     $customerData = Mage::getSingleton('customer/session')->getCustomer();
      echo $customerData->getId();
      // return customer's id
}


How do convert mysql query with sub queries to a db_select version?

Question: Below is a mysql query that returns a proper result set. How can I convert this into a db_select() version?
<code>SELECT p.id, u.name, pa.field_address_2_value, pa2.display, pa3.field_company_value
FROM ms_order_products p
LEFT JOIN ms_orders o ON p.oid = o.oid
LEFT JOIN users u ON o.uid = u.uid
LEFT JOIN
(
    select *
    from field_data_field_address_2

) pa
ON u.uid = pa.entity_id
LEFT JOIN
(
    select *
    from ms_order_adjustments

) pa2
ON o.oid = pa2.oid
LEFT JOIN
(
    select *
    from field_data_field_company

) pa3
ON u.uid = pa3.entity_id
WHERE p.id = 'RM11'
</code>
Comment: Could you add the code you've tried along with what didn't work please?
Comment: Just curios, in your original query what is the point of using those "left join (select * "s , the query can be simplified a lot
Answer: I found the answer, see below. (I added a few more fields as well)
<code>  $sub_query_1 = db_select('field_data_field_address_2', 'addr2');
  $sub_query_1->fields('addr2', array('field_address_2_value', 'entity_id'));

  $sub_query_2 = db_select('ms_order_adjustments', 'a');
  $sub_query_2->fields('a', array('display', 'oid'));

  $sub_query_3 = db_select('field_data_field_company', 'comp');
  $sub_query_3->fields('comp', array('field_company_value', 'entity_id'));

  $query = db_select('ms_order_products', 'p');

  $query->fields('p', array('id', 'oid', 'type', 'amount'));
  $query->fields('o', array('oid', 'uid', 'status', 'order_type', 'created'));
  $query->fields('u', array('uid', 'mail', 'name'));
  $query->fields('fn', array('field_first_name_value'));
  $query->fields('ln', array('field_last_name_value'));
  $query->fields('adr1', array('field_address_1_value'));
  $query->fields('city', array('field_city_value'));
  $query->fields('state', array('field_state_value'));
  $query->fields('zip', array('field_zip_code_value'));
  $query->fields('pa', array('field_address_2_value'));
  $query->fields('pa2', array('display'));
  $query->fields('pa3', array('field_company_value'));

  $query->leftjoin('ms_orders', 'o', 'o.oid = p.oid');
  $query->leftjoin('users', 'u', 'o.uid = u.uid');
  $query->leftjoin('field_data_field_first_name', 'fn', 'u.uid = fn.entity_id');
  $query->leftjoin('field_data_field_last_name', 'ln', 'u.uid = ln.entity_id');
  $query->leftjoin('field_data_field_address_1', 'adr1', 'u.uid = adr1.entity_id');
  $query->leftjoin('field_data_field_city', 'city', 'u.uid = city.entity_id');
  $query->leftjoin('field_data_field_state', 'state', 'u.uid = state.entity_id');
  $query->leftjoin('field_data_field_zip_code', 'zip', 'u.uid = zip.entity_id');

  $query->addJoin('LEFT', $sub_query_1, 'pa', 'u.uid = pa.entity_id');
  $query->addJoin('LEFT', $sub_query_2, 'pa2', 'o.oid = pa2.oid');
  $query->addJoin('LEFT', $sub_query_3, 'pa3', 'u.uid = pa3.entity_id');

  $query->condition('p.id', 'RM11', '=');

  $result = $query->execute();
</code>


Make port appear as subdomain

Question: I have Jira set up to serve on myserver:8080.
There is an DNS A reference that points jira.otherserver to the ip address of myserver.   (otherserver is going to host the Jira setup in the future)
Based on other answers here, I tried enabling mod_proxy, and added the following to my httpd.conf on myserver:
<VirtualHost *:80>
    ServerName jira.otherserver/
    ProxyPreserveHost On

    # setup the proxy
    <Proxy *>
        Order allow,deny
        Allow from all
    </Proxy>
    ProxyPass http://jira.otherserver/ http://localhost:8080/
    ProxyPassReverse http://jira.otherserver/ http://localhost:8080/
</VirtualHost>

However, when I visit http://jira.otherserver it gives me the generic start page (phpinfo).  I can still access jira at http://myserver:8080
What am I doing wrong?
Edit: I can also access Jira at jira.otherserver:8080, so DNS is working correctly
Edit 2: I followed the suggestions in an answer, and modified the section to
NameVirtualHost *:80
<VirtualHost *:80>
    ServerName jira.software-task
    ProxyPreserveHost On

    # setup the proxy
    <Proxy *>
        Order allow,deny
        Allow from all
    </Proxy>
    ProxyPass "/" "http://localhost:8080/"

    ProxyPassReverse "/" "http://localhost:8080/"

</VirtualHost>

Now connecting to jira.otherserver causes an error 500, with the following in the logs:

[Fri Nov 18 13:40:03 2016] [warn] proxy: No protocol handler was valid for the URL /. If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule.

httpd -M outputs the following:

M:\>httpd -M
Loaded Modules:
 core_module (static)
 win32_module (static)
 mpm_winnt_module (static)
 http_module (static)
 so_module (static)
 actions_module (shared)
 alias_module (shared)
 asis_module (shared)
 auth_basic_module (shared)
 authn_alias_module (shared)
 authn_default_module (shared)
 authn_file_module (shared)
 authnz_ldap_module (shared)
 authz_default_module (shared)
 authz_groupfile_module (shared)
 authz_host_module (shared)
 authz_user_module (shared)
 autoindex_module (shared)
 cgi_module (shared)
 dav_module (shared)
 dav_fs_module (shared)
 dir_module (shared)
 env_module (shared)
 include_module (shared)
 isapi_module (shared)
 ldap_module (shared)
 log_config_module (shared)
 mime_module (shared)
 negotiation_module (shared)
 proxy_module (shared)
 rewrite_module (shared)
 setenvif_module (shared)
 dav_svn_module (shared)
 authz_svn_module (shared)
 php5_module (shared)
Syntax OK

Comment: That configuration makes your webserver an open proxy that can be abused by anyone to proxy to any web site anywhere. That is what `` is for, and should never be present in a reverse proxy setup (or, generally, at all).
Comment: @MichaelHampton it's only visible from the internal network, but I will improve it.  Thanks for the reminder.
Answer: You should enable Virtual Hosts on port 80: NameVirtualHost *:80 before <VirtualHost *:80> and remove trailing slash from ServerName jira.otherserver/
Comment: I made those changes, and no change in result.
Comment: And now lets fix `ProxyPass` directive: `ProxyPass "/" "http://localhost:8080/"` and `ProxyPassReverse "/" "http://localhost:8080/"`
Comment: That causes an error 500.  Logs show "[warn] proxy: No protocol handler was valid for the URL /. If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule."
Comment: Add `LoadModule proxy_http_module libexec/apache22/mod_proxy_http.so` or some other path instead of `libexec/apache22` you use for loading proxy_module
Comment: It's currently `LoadModule proxy_module modules/mod_proxy.so`
Comment: I enabled `mod_proxy_http`, and it works now.
Comment: So try adding `LoadModule proxy_http_module modules/mod_proxy_http.so` and restart Apache
Comment: And I can now copy and paste for the other services.  Thank you hugely.

Make port appear as subdomain


How to calculate mean, median, mode, std dev from distribution

Question: How to calculate mean, variance, median, standard deviation and modus  from distribution? If I randomly generate numbers which forms the normal distribution I've specified the mean as m=24.2 standard deviation as sd=2.2:
> dist = rnorm(n=1000, m=24.2, sd=2.2)

Then I can do following:
Mean:
> mean(dist)
[1] 24.17485

Variance:
> var(dist)
[1] 4.863573

Median:
> median(dist)
[1] 24.12578

Standard deviation:
> sqrt(var(dist))
[1] 2.205351

Mode aka Modus (taken from here):
> names(sort(-table(dist)))[1]
[1] "17.5788181686221"

Is this the whole magic, or is there something else that I did not
realized?
Can I somehow visualize my bell shaped normal distribution with vertical lines representing (mean, median...)?
What does those attributes say about distribution?

PS: code is in R
Comment: It's not clear what you mean by your question 1. Question 3 seems too broad as it stands, since one could write a lot about each. Could you review the wikipedia pages on the mean, median, standard deviation and mode, and then ask something more specific?
Comment: Also, your title speaks of a "distribution" but your body text seems to be referring instead to a *sample*. Should your title refer to a sample?
Comment: @Glen_b by 1st I mean that if the methods that I've posted are OK for calculating parameters (mean, variance ...) for distribution or something else or somehow differently should be used? 3rd I did not realize that is too broad, I was expecting answer like: if median is larger than mean then your data .... Regarding retitling maybe it is OK, indeed I was working with normal distribution or am I wrong?
Comment: I'm sorry but I can't follow your comment there at all.
Comment: You don't need to bin a continuous variable before you can estimate its mode. See https://stats.stackexchange.com/questions/176112/how-to-find-the-mode-of-a-probability-density-function for discussion. (You should want to avoid binning as being dependent on arbitrary choices of bin width and origin.)
Answer: First a general comment on the mode:
You should not use that approach to get the mode of (at least notionally) continuously distributed data; you're unlikely to have any repeated values (unless you have truly huge samples it would be a minor miracle, and even then various numeric issues could make it behave in somewhat unexpected ways), and you'll generally just get the minimum value that way. It would be one way to find one of the global modes in discrete or categorical data, but I probably wouldn't do it that way even then. Here are several other approaches to get the mode for discrete or categorical data:
x = rpois(30,12.3)

tail(sort(table(x)),1)   #1: category and count; if multimodal this only gives one

w=table(x); w[max(w)==w] #2: category and count; this can find more than one mode

which.max(table(x))      #3: category and *position in table*; only finds one mode

If you just want the value and not the count or position, names() will get it from those
To identify modes (there can be more than one local mode) for continuous data in a basic fashion, you could bin the data (as with a histogram) or you could smooth it (using density for example) and attempt to find one or more modes that way.
Fewer histogram bins will make your estimate of a mode less subject to noise, but the location won't be pinned down to better than the bin-width (i.e. you only get an interval). More bins may allow more precision within a bin, but noise may make it jump around across many such bins; a small change in bin-origin or bin width may produce relatively large changes in mode. (There's the same bias-variance tradeoff all over statistics.)
Note that summary will give you several basic statistics.
[You should use sd(x) rather than sqrt(var(x)); it's clearer for one thing]
--
In respect of q.2 yes; you could certainly show mean and median of the data on a display such as a histogram or a box plot. See here for some examples and code that you should be able to generalize to whatever cases you need.
Comment: Extremely useful. Very surprising the R Project didn't make this into a base function.
Comment: Thank you, can you please explain the difference between binding and smoothing?
Comment: @Wakan What's binding?
Answer: Some additional and not very well known descriptive statistics.
x<-rnorm(10)

sd(x) #Standard deviation

fivenum(x) #Tukey's five number summary, usefull for boxplots

IQR(x) #Interquartile range

quantile(x) #Compute sample quantiles

range(x) # Get minimum and maximum

I am sure you can find many others in one of those freely available R manuals.
Comment: Can you post some situations when you've used those (fivenum, IQR, quantile ...) and they were useful?
Answer: As @Glen_b described the mode of a continuous distribution is not as straightforward as it is for a vector of integers.
This R code will get the mode for a continuous distribution, using the incredibly useful hist() function from base R. As @Glen_b described this involves putting observations into bins - discrete categories where if the observation falls within the bin interval it is counted as an instance of that bin, which gets around the problem of it being highly unlikely in a continuous distribution to observe the exact same value twice.
set.seed(123)
dist <- rnorm(n=1000, m=24.2, sd=2.2)
h <- hist(dist, # vector
          plot = F, # stops hist() from automatically plotting histogram
          breaks = 40) # number of bins

Now we treat the midpoint of the bin interval that has the maximum count within it as the mode
h$mids[which.max(h$counts)]

# [1] 23.75

Voila! The mode.
p.s. you could also treat the start of the interval as the mode via h$breaks[which.max(h$counts)]. As discussed modes for continuous distributions are not simple and require decisions to be made, hence why there is no simple function for them like there is with mean() and median()
Comment: So this boils down to saying that to find the mode you find the most frequently occurring bin. What do you do when there are ties? How do you choose bins systematically?
Comment: These are very good questions @Nick Cox? Would love to know the answer. I guess you would need a rule for when there are ties.


Using Linked-lists to implement a stack, debug assertion failed

Question: I am currently working on implementing a stack data structure using linked lists in C++. I can compile everything fine up until the point I test my "stack.push" method when I receive a debug assertion failed error that I have no where near enough knowledge as to how to begin to fix it. I just started on here so I cannot post images apparently, but in short it says:
Debug Assertion Failed!
Program...ual studio 2013/....~
File:f:/dd/vctools/crt/crtw32/misc/dbgdel.cpp
Line: 52
Expression:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse

and here are my codes: Stack.h
#ifndef _STACK_H
#define _STACK_H

#include "LList.h"
typedef int ItemType;
class Stack{

public:
    Stack();
    ~Stack();

    int size() { return size_; }
    void push(ItemType x);
    ItemType pop();
    ItemType top() { return top_; }

private:
    ItemType top_;
    void copy(const Stack &source);
    int size_;
    LList items_;

};
#endif _STACK_H

stack.cpp:
#include "Stack.h"

Stack::Stack()
{
    size_ = 0;
    ItemType top_ = NULL;
}

void Stack::push(ItemType x)
{
    items_.append(x);
    size_ += 1;
    ItemType top_ = x;
}
ItemType Stack::pop()
{
    ItemType top_ = size_ - 1;
    size_ -= 1;
    return items_.pop();
}

Stack::~Stack()
{
    items_.~items_();
}

The error occurs after writing test code that assigns a stack and then tries to push a number onto the stack.
Any help would be appreciated and I apologize if there are any formatting issues with my post.
Answer: There are several problems with your code:

Like mentioned in another answer, append will add the item at the end of the list (i.e., at the bottom from stack perspective) instead of at the top.
Your usage of top is inconsistent, you should decide what it means. Classically, top would hold or point to the last inserted element.
You have syntax issues and you're actually redeclaring a new local variable for top instead of using the class member.
You have memory corruption in the destructor when you explicitly call the contained list destructor.
Comment: Okay, from both of your answers I obviously need to put some more thinking into it... I'll try to come up with a better solution
Answer: You are a bit confused as to what append does. Append places a value (in this case an ItemType x) to the end of your stack, not the front. You then assign the top of the stack to the end of the stack, and you lose the pointers to the head of your list.
In fact, there are multiple things wrong now that I look at the rest of your code. I think you lack an understanding of what Linked Lists do, and you should go and read them yourself instead of me just dropping working code in my answer.
Comment: Okay, from both of your answers I obviously need to put some more thinking into it... I'll try to come up with a better solution


adding numbers in sql

Question: I have a mysql database that has the column balance. This table is used for storing data about a user's account balance, so how to add numbers in mysql statement?
here is what I have so far
$sql_data = "UPDATE `database1`.`users` SET (`balance`) = '(what to put here?)'
WHERE ('" . $mysqlid . "') ";

so do I have to a) retrieve the current balance with a mysql select query?
and b) what do I use to add the integer 5 to the column balance, the mysql row is double(16,2)
Comment: I feel like I should remind all of you to watch out for SQL injections, maybe by using prepared statements.
Answer: $sql_data = "UPDATE `database1`.`users` SET `balance` = MIN(`balance` + 5, (maximum_value_they_can_have)) WHERE ('" . $mysqlid . "') ";

Edit:
Arguably you can do a check to verify that balance + 5 doesn't go over the bounds of the balance data-type in PHP using something that is unlikely to run into issues, like bcmath functions. (Does math via given precision with string comparison)
Answer: You can do this:
$sql_data = "UPDATE `database1`.`users` SET `balance` = (`balance` + [value to be added]) WHERE ('" . $mysqlid . "') ";

Answer: Try this :
$bal=100.5;  // balance to be add
$sql_data = "UPDATE `database1`.`users` SET `balance` = (`balance`+'$bal')  WHERE ('" . $mysqlid . "') ";

adding numbers in sql


Binomial Theorem 3Unit Australia Year 12

Question: If X is the sum of the first, third, fifth, ... terms in the expansion of $$ (a+b)^n $$ and Y is the sum of the second, fourth, sixth, ... terms, show that $$ X^2 - Y^2 = (a^2-b^2)^n $$
So if I expand it, it is basically the sum of the odd terms would include:
$$ X=\binom{n}{0} +\binom{n}{2}x^2 + \binom{n}{4}x^4 + \binom{n}{6}x^6+ ... $$
and the sum of the even terms would include
$$ Y= \binom{n}{1}x +\binom{n}{3}x^3 + \binom{n}{5}x^5 + \binom{n}{7}x^7+ ... $$
What would you do like factorise (X-Y)(X+Y) or something but theres like infinite numbers n
Comment: What happens two the "$0^{th}$" term? Does it belong to $X$ or $Y$?
Comment: the first term would could nC0
Answer: The terms of the expansion of $(a-b)^n$ are the same as those of $(a+b)^n$ except that the terms for odd powers of $b$ are multiplied by $-1$.  Thus
$$ X + Y = (a+b)^n$$
while
$$ X - Y = (a-b)^n$$
So $$ X^2 - Y^2 = (X + Y)(X - Y) = (a+b)^n (a-b)^n = (a^2-b^2)^n$$


What is the MLB record for the most errors by a single player on a single play?

Question: What is the MLB record for most errors committed by a single player on a single play?
I wondered about this today, when Giants shortstop Brandon Crawford was charged with two errors on the same play in the second inning.  (With a runner at second, Crawford booted a ground ball, then threw wildly to first, allowing the runner from second to score.)  I imagine this must happen with some regularity, but I had never seen it before.
This article reports that Tommy John committed three errors on one play in a game in 1988.  The story suggests that at the time, this tied the record for pitchers, but does not address other positions or whether this dubious record has since been broken.
Has any player ever been charged with four or more errors on the same play?
Answer: This Yahoo! Sports page contains the quote

Three errors charged on one play, which by all accounts ties a major league record.

The Wikipedia page List of Major League Baseball single-game records claims that there are four instances of three (team) errors on one play, of which I can find three:

Dodgers vs Padres, 2014-09-08
Angels vs Tigers, 2014-04-20
Yankees vs Brewers, 1988-07-27 - this is the Tommy John play you found

Assuming that in the fourth instance the errors were not all committed by one player (which is implied by the various reports on Tommy John's play), this would leave Tommy John as the holder of this dubious record.
Answer: The record is actually 4 errors one one play - by one player! Committed by a Giants 3rd baseman named Mike Grady in 1899. The specifics of fhd unfortunate play are explained right here: http://phillysportshistory.com/2011/05/15/grady-commits-4-errors-in-one-play-then-saves-women-and-children-from-deadly-fire/
Comment: Links can disappear, so could you add a brief description of the errors in your answer please?
Comment: Looks like https://books.google.com/books?id=gcwv4OxWTgIC&pg=PA10&lpg=PA10&dq=mike+grady+1899+4+errors&source=bl&ots=3rOvM4TDik&sig=kueBlSEE1Ug2whjIzbP__b41Rbg&hl=en&sa=X&ved=0ahUKEwjjguqVt_3LAhWLqx4KHUK7AwUQ6AEIPDAF#v=onepage&q=mike%20grady%201899%204%20errors&f=false tends to dispute this happening, at least with the details largely held.
Comment: This is interesting, but it would be great if there were records to support it.  So far I haven't found box scores from 1899.


PowerShell_ISE "an error occurred while creating the pipeline" #Requires -Version 3.0

Question: If using PowerShell_ISE, when attempting to use any of the #Requires commands, for example:
<code>#Requires -Version 3.0
</code>
They error with the text:

An error occurred while creating the pipeline.
+ CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : RuntimeException

I've tested this on ISE and the Console with the same results, my versions are below:

<code>Name                           Value
</code>

<code>----                           -----
PSVersion                      5.1.14409.1012
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14409.1012
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           18.104.22.168
</code>
Comment: The `about_Requires` help topic explains how the `#requires` statement works. It prevents the _entire_ script from running if the version is insufficient. This is by design.
Comment: The reason I posted this (and the answer) was that I found no information about it anywhere (including help). As I've come across the issue previously, I thought others may also benefit if they found this article.
Answer: My final test before posting the question provided the answer:
It seems the '#Requires' commands are designed to break out of the script if it doesn't meet the requirements rather than posting an error, and testing it on a single line will result in an error.
To test, find your PowerShell version (e.g. 5.1) and save the following transposing 5.1 with your (major.minor) version:
<code>#Requires -version 5.1
$PSVersionTable.PSVersion
Read-Host
</code>
This will work on both ISE and the Console, providing an output even if 'Run with PowerShell'.

Using the #Requires -(anything) line on its own will display the error.

In ISE 'Run selection' will work, as long as it's accompanied by another line of code.

Using ISE, If the #Requires parameter doesn't match yours, it'll throw a more descriptive error. If run in the console, it'll break and close.
Comment: I see. I've added the `powershell-ise` tag to your question. However, at least as of   v5.1.22621.963 I don't see your symptom with `#Requires -Version 3.0`. However, I do see an error with a _nonexistent_ historical version of PowerShell, such as `#Requires -Version 3.99` - unlike in regular console windows. Perhaps you've long since moved on from the ISE anyway, but let me provide current advice in the next comment:
Comment: As an aside: The PowerShell ISE is [no longer actively developed](https://docs.microsoft.com/en-us/powershell/scripting/components/ise/introducing-the-windows-powershell-ise#support) and [there are reasons not to use it](https://stackoverflow.com/a/57134096/45375) (bottom section), notably not being able to run PowerShell (Core) 6+. The actively developed, cross-platform editor that offers the best PowerShell development experience is [Visual Studio Code](https://code.visualstudio.com/) with its [PowerShell extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell).
Comment: Correct, PowerShell_ISE has long since been retired, as perhaps should this post. As some people including myself use ISE occasionally, it may be worth keeping it, but I'd suggest anyone NOT experiencing the issues would, by definition not be reading this post.
Answer: <code>$versionMinimum = [Version]'5.0'

if ($versionMinimum -gt $PSVersionTable.PSVersion) {
    throw "You need Powershell Version $versionMinimum to run this script"
}
</code>


Make PHP FastCGI process write to a specific error log?

Question: I have a server running Lighttpd with three user's serving domains from it. Each user gets their own PHP FastCGI process for serving PHP content across all of their domains. Lighttpd allows me to write the access log files for each domain to unique log files. I also want to write PHP errors to three different log files (one for each user).
Each PHP process is reading its own php.ini (this has been verified by viewing phpinfo() output). Each php.ini specifies the log file to which it should write. For example:
error_reporting = E_ALL & ~E_NOTICE
display_errors = 0
log_errors = 1
html_errors = 0
fastcgi.logging = 1
error_log = /var/www/vhosts/example.com/logs/php_errors.log

If I set fastcgi.logging = 1 then the PHP errors, for all three users, always go to Lighttpd's error log. If I set fastcgi.logging = 0 then the PHP errors get written to the system STDERR. In this case, I can redirect the STDERR for each FastCGI process to whatever file I like, but I loose time stamping on the errors (which is less than ideal).
So, how do enable proper error logging for my PHP FastCGI processes through Lighttpd?
Answer: Lighttps supports only one error log. But it can be a program!
So try logging to your own script that splits the error log based on your own criteria. The syntax is:
server.errorlog = "|/path/to/script"

Comment: Would you care to elaborate on your solution? I see that Lighty supports logging to STDERR, a file, and syslog.
Comment: You can configure lighttpd as follows:

server.errorlog = "|/path/to/script"

This means that all your error lines will be piped to the stdin of that script, not written to a file. Google for "lighttpd cronolog" for discussion how this works. Unfortunately, cronolog is not a suitable program for your task, and you need to write your own script that receives log lines on stdin and dispatches them according to the user.
Comment: Ah, okay. I will look into that. Thank you. You should roll that into your answer. I will go ahead and accept it, though, since the comment finishes it off.
Comment: Note, this solution will not actually work for me since Lighttpd is only up to version 1.4.19 in Debian (Lenny). Using pipes for the error log is implemented in version 1.4.23 -- http://redmine.lighttpd.net/issues/show/296


Binomial proportion confidence interval when rigid bounds on population proportion (0.5 < p < 1)

Question: A standard problem is estimation of confidence intervals for a population proportion given that one has observed f successes out of n independent trials. There is a reasonable discussion of this problem at https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval and several R packages perform the calculation using a variety of methods (e.g. binom.confint in the package binom or bintol.int in the package interval). My problem is similar except that I know for certain that the population proportion lies in the range 0.5 to 1; within that range a uniform prior would be appropriate, although I am not wedded to a Bayesian approach. Of course particular small samples may nevertheless yield fewer successes than failures. Sample sizes are typically 10-30 trials, occasionally lower.
Ideally I would like an R function or some lines of code that would generate appropriate confidence limits. Otherwise some advice about other approaches (e.g. online calculators, programming in C) would be appreciated. My probability theory is rusty!
The motivation for this is analysing some genetic crosses following the rules of Mendelian genetics. I am crossing a heterozygote female with a homozygote recessive male and then with a homozygote dominant male. If the first male fathers all offspring, one expects a roughly 50:50 ratio of phenotypes (equal numbers of double recessives and hetoryzgotes); if the second male fathers all offspring, they will all exhibit the dominant phenotype. But sperm from both matings may be used, so any intermediate proportion between 0.5 and 1 is possible. This seems like a standard problem in genetics, which is what leads me to expect that there is a ready-made solution out there.
Many thanks!
Answer: Suppose you have 20 trials and observe 5 successes.
Using your prior, the following R code gives a 95% Bayesian posterior interval
$(.501, .630)$ for the proportion of successes.
Another run with a different seed gave $(.501, .629).$ [Maybe
for fewer than 10 successes, you'd prefer a one-sided
95% interval, $(.5, .609).]$
<code> set.seed(815)
 m = 10^7
 p = runif(m, .5, 1)  # prior
 x = rbinom(m, 20, p)
 pp = p[x == 5]
 length(pp)
 [1] 12951            # sufficient nr of cases
 hist(pp, prob=T, col="skyblue2", main="Posterior")
 q = as.numeric(quantile(pp, c(.025,.975)));  q
 [1] 0.5011254 0.6304784
 abline(v=q, col="red", lwd=2)
</code>

If you got 18 successes in 20, then the Bayesian interval
would be $(0.696, .970)$ and a frequentist Agresti-Coull interval $(0.684, .982).$
Comment: Solution is neat and understandable: great! But 2-tailed vs 1-tailed issue bothers me. When successes/trials is < 0.5, a 1-tailed CI makes sense. But also when successes/trials = 0.51: a 2-tailed CI excludes p=0.5, which is silly. 2-tailed CIs are appropriate when well away from 0.5 and 1, but if successes/trials=0.99, again a 1-tailed CI seems right. Shouldn't we shift how much of the 5% is in each tail outside the CI depending on the nearness of successes/trials to 0.5 and 1? This must be a standard problem: what's the phrase to search for? Or even can you suggest more nice code?
Comment: You asked for a 95% CI; I assumed you meant a 2-sided CI. Sometimes when the lower limit of a CI comes very close to a  boundary of permissible values, people like to use one-sided CIs. But usually, people make 'probability symmetric' two-sided CIs, putting half of the error probability in each tail. Sometimes with asymetrical dist'ns, such as exponential, people search for the allocation of probabilities in the tails that produces the shortest CI.(Also, when doing one-sided tests,  it is customary to use one-sided CIs.) Recognizing variations, one usually speaks of "**a** 95% CI" not **the.**
Comment: Mainly, I took followed your lead to discuss probability intervals based on posterior distn's. One style of interval is HPD (highest probability density). That would pick 95% of probability where posterior density is largest, also usually the shortest. Using my code you only have an estimate of posterior density. Maybe the idea will lead to what you're hinting at a couple of Comments before. // When the point est is < 1/2, HPD is close to one sided.
Comment: Helpful. Further useful discussion at https://stats.stackexchange.com/questions/4713/binomial-confidence-interval-estimation-why-is-it-not-symmetric. If I minimise width of CI, the relative sizes of the 2 tails shift as I want. This code added to yours achieves this:
 alpha <- 0.05;
 mm = 1000;
 lt = (0:mm)*alpha/mm;
 wci = as.numeric(quantile(pp, 1-alpha+lt))-as.numeric(quantile(pp, lt));
 i=which.min(wci);  as.numeric(quantile(pp, c(lt[i],1-alpha+lt[i])));
 i/mm # ~0=>1-tail;~0.5=>symmetric
Answer: Having learnt the principle from BruceET's answer, I have created another version that avoids simulation. Instead I use dbinom() to calculate the probabilty of getting the observed result over a regularly spaced array of p values. These values yield an unscaled discrete-valued pdf, which is integrated to create a cdf, and then linear interpolation is used to generate a continuous inverse cdf. I report the confidence limits such that the area in each tail is equal (green lines). But I then search systematically across values of the area in the left tail of the distribution (from 0 to alpha), finding the value that minimises the width of the 1-alpha confidence interval; the resulting confidence limits (red lines) are more satisfactory.
<code>> f <- 18 ; n <- 20 # observed f successes out of n trials
> alpha <- 0.05
>
> m = 10^5
> p=seq(0.5,1.0,1/m) # uniform prior
> pdf=dbinom(f,n,p) # not rescaled
> cdf=cumsum(pdf)  # "integration"
> cdf=cdf/cdf[1+m/2] # so now runs to 1
> invcdf <- approxfun(cdf,p) # function relies on linear interpolation
> scl = c(invcdf(alpha/2),invcdf(1-alpha/2)); scl # CLs with equal area in each tail
[1] 0.6964185 0.9695073
>
>  mm = 10^5  # this section minimises width of CI
>  lt = seq(0,alpha,1/mm)  # area in left tail (0 to alpha in steps of 1/m)
>  i = which.min(invcdf(1-alpha+lt)-invcdf(lt))
>  i/(mm*alpha)  # ~0 => 1-tailed; ~0.5 => symmetric
[1] 0.8854
>  cl = c(invcdf(lt[i]),invcdf(1-alpha+lt[i])); cl # CLs minimising width of CI
[1] 0.7235043 0.9823723
>
> plot(p,pdf,type="l", yaxt="n")
> abline(v=max(0.5,f/n),col="blue",lwd=4,lty=2) # observed
> abline(v=scl, col="green", lwd=1)
> abline(v=cl, col="red", lwd=2)
</code>


MySQL Sorting By Three Columns in DESC Order

Question: I am relatively new to MySQL and I am having difficultly trying to sort a table by three columns.
It is a database that has stored data for thousands of videos and I would like to create a tab on my website that lists recommended videos to the user.
If possible, it would be optimal to only sort the last 100 most recently added videos (records) which have been auto incremented by the 'key' column.
Out of the 100 ordered records, I will only actually retrieve five records from the database and store them into PHP variables.
I am trying to get it to sort the columns as follows.
key DESC
rating_score DESC
view_count DESC

I previously used another MySQL statement that sorts videos by two columns that works.
SELECT  `title`, `duration`, `rating_score`, `imageurl`, `player_url` FROM (SELECT * FROM `archived_videos` ORDER BY `key` DESC LIMIT 0,210) AS ttbl ORDER BY `rating_score` DESC

My current and modified version of the above MySQL statement that sorts by three columns is written as follows.
SELECT  `title`, `duration`, `rating_score`, `imageurl`, `player_url` FROM ((SELECT * FROM `archived_videos` ORDER BY `key` DESC LIMIT 0,100) AS ttbl (SELECT * FROM `archived_videos` ORDER BY `view_count` DESC) AS ttbl) ORDER BY `rating_score` DESC LIMIT 0,5

If someone who is fluent in MySQL could take a look at this you would be a life saver.
Comment: This comment is mostly for people thinking about answering.  The question seems to be a bit misleading.  The desired result is (I think) the 5 highest rated entries out of the 100 latest.  Just sorting by the `key` column would not get the desired result.
Answer: You can actually sort on multiple columns in a single SELECT statement, there's no need to use sub-queries:
SELECT
    title, duration, rating_score, imageurl, player_url
FROM
    archived_videos
ORDER BY
    key DESC,
    rating_score DESC,
    view_count DESC
LIMIT 5

The results/columns will be sorted in the order you list them. First, they'll sort by the key column, then these will be sorted upon the rating_score, then the view_count - each keeping the order set by the column prior.
UPDATE (top-5 of latest 100)
I mis-read the original question the first time around; If the desire is to select to top 5 videos out of the latest 100, you can use a single sub-query to get the latest 100 and then an outer query to get the top 5:
SELECT
    title, duration, rating_score, imageurl, player_url
FROM (
    SELECT
        title, duration, rating_score, imageurl, player_url
    FROM
        archived_videos
    ORDER BY
        key DESC
    LIMIT 100
    ) AS top_100
ORDER BY
    rating_score DESC,
    view_count DESC
LIMIT 5

Comment: See my comment on the original question
Comment: Thank you for putting in the time and effort to help me out I really appreciate it.
Answer: SELECT  `title`, `duration`, `rating_score`, `imageurl`, `player_url`
FROM (
    SELECT *
    FROM `archived_videos`
    ORDER BY `key` DESC
    LIMIT 100
) AS sub
ORDER BY `rating_score` DESC, `view_count` DESC
LIMIT 5

Comment: @user1769348 Glad it helped!  If this answers your question, [please mark it as the accepted answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work).