$n$-to-$1$ near zero of holomorphic function

Question: Can someone explain to me why a holomorphic function that grows like a polynomial of degree $n$ is $n$-to-$1$ near it's roots? I keep reading this fact on this site, but I can't find an explanation.
Comment: Do you mean, a holomorphic function that has a zero of order $n$ is $n$-to-one near that zero?  That follows from the argument principle.
Comment: I think that's what I mean - it's on the answer here http://math.stackexchange.com/questions/29758/entire-1-1-function.

I don't know the argument principle.
Comment: Correction, I do know the argument principle.
Comment: in your cited answer he mentions $n+1$ to one for derivative of order $n$.
Comment: Indeed, I'll edit my question.
Answer: As indicated in the comments, this is a consequence of the argument principle.
Here's the basic idea. Suppose $f$ has a zero of order $n$ at $a$. Then we may write $$f(z)=(z-a)^n g(z)$$ where $g$ is analytic and non-zero on a neighborhood of $a$. So on a suitably small disc we write $z=re^{i\theta}+a$, whence $$f( re^{i\theta}+a) =r^n e^{in\theta}g( re^{i\theta}+a).$$ The exponential  tells us that every full rotation in the domain gives $n$ rotations in the image. Boundedness of $g$ away from zero assures it makes no net contributions: the arguments of its values stay inside an interval of size strictly less than $2\pi$.
Answer: The proof from the argument principle works like this.
Suppose $\Gamma$ is a positively oriented simple closed contour, let's say a circle, and $f$ is analytic in a
domain that includes $\Gamma$ and its interior.  Then the sum of the orders of the zeros of $f$ inside $\Gamma$ is
$$ \dfrac{1}{2\pi i} \int_\Gamma  \dfrac{f'(z)}{f(z)}\; dz$$
If you replace $f(z)$ by $f(z) - w$ you get the sum of the orders of the zeros of $f(z) - w$.  Now the crucial  point is that in some neighbourhood of $0$ (in fact in
the connected component of ${\mathbb C} \backslash f(\Gamma)$ containing $0$)
$\frac{1}{2\pi i} \int_{\Gamma} \frac{f'(z)}{f(z)-w}\; dz$ is constant.
So for $w$ near $0$, $f(z) = w$ has the same number of solutions (counted by order) inside $\Gamma$ as does $f(z) = 0$.  If we avoid points $z$  where $f'(z) = 0$ (of which there are only finitely many inside $\Gamma$) the solutions of
$f(z) = w$ all have order $1$.
In particular, if $\Gamma$ contains a single zero $p$  of $f$ and it has order $n$, this says that there is a neighbourhood $V$ of $0$ such that for every  $w$ in $V$ except $0$, $f(z) = w$ has exactly $n$ solutions inside $\Gamma$.  If
$W$ is the part of $f^{-1}(V)$ inside $\Gamma$, then $f$ is $n$-to-one
from $W \backslash \{p\}$ to $V \backslash \{0\}$.
Comment: Because it's a continuous function (off $f(\Gamma)$) of $w$ that takes on only integer values.


Unicode problem Django-Python-URLLIB-MySQL

Question: I am fetching a webpage (http://autoweek.com) and trying to process it but getting encoding error. Autoweek declares "iso-8859-1" encoding and has the word "Nürburgring" (u with umlaut)
I do:
# -*- encoding: utf-8 -*-
import urllib
webpage = urllib.urlopen(feed.crawl_url).read()
webpage.decode("utf-8")

it gives me the following error:
'utf8' codec can't decode bytes in position 7768-7773: unsupported Unicode code range"

if I bypass .decode step and do some parsing with lxml library, it raises an error when I am saving parsed title to database:
'utf8' codec can't decode bytes in position 45-50: unsupported Unicode code range

My database has character set utf8 and collation utf-general-ci
My settings:
 Django
 Python 2.4.3
 MySQL 5.0.22
 MySQL-python 1.2.1
 mod_python 3.2.8
Answer: If the webpage declares encoding iso-8859-1, can't you just do webpage.decode("iso-8859-1")?
At that point, webpage is decoded for your app. When it is written into the database, the mapping there should handle the char-to-utf8 encoding.
To get the correct encoding, either tell the webserver that you only accept, say, UTF-8 and then that's what you'll (hopefully) always get, since just about everyone reads UTF-8 (or you could try it with ISO-8859-1); or use .info to inspect the encoding name of the stream returned.
See urllib2 - The Missing Manual and Quick reference to HTTP headers for details.
Comment: No. It's the only solution, unless you want to throw away the incorrect characters. And it's honestly not very complicated.
Comment: I need serialize this solution for all pages (of different encodings) I am fetching. So I have to fetch, extract encoding (if it's declared) and then decode.

Any easier solution?
Comment: +1 you need to decode using iso-8859-1. I've verified this against your URL and it works fine.
Answer: autoweek.com seems confused about it's own encoding. It declares conflicting charset definitions:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

and later...
<meta charset=iso-8859-1"/>.

iso-8859-1 is the correct one since this is returned in the header from the web server and by the .info() method (and it actually decodes), but this demonstrates that you can't necessarily rely on the Content-Type declaration in web pages. You should follow the method described by lavinio.


Read and Remove invalid characters from xml outside xml elements in C# Linq to Xml

Question: I am facing a problem while reading xml in C# linq to xml.
When I try to read xml document by using following statement:
XDocument xdoc = XDocument.Load(path);

It throws an exception like this.
Data at the root level is invalid. Line 1, position 1.
When I open the xml file that I was trying to read, I found an invalid character before xml declaration. Here is the declaration:
?<?xml version="1.0" encoding="utf-8"?>

I know the question mark at the start of declarations shouldn't be there.
I have three questions
1) How to read this invalid xml in C# linq to xml?
2) How to remove such kind of invalid characters any where in the xml in C#?
3) How to prevent these kind of invalid characters while creating the xml in c# linq to xml?
xml sample:      ?<?
hex equivalent : 3f 3c 3f
And here is the code that I am using to create it:
XDocument xdoc = new XDocument();
xdoc.Add(new XElement("TaskAlert"));
AddParentNodeInTaskAlertXml(ref xdoc, userId);
and so on......

I couldn't understand the reason why it add such kind of characters sometime.
Here is some code that I am using to create or load the file:
public static void CreateUpdateTaskAlertXmlFile(int userId)
        {
            try
            {
                string path = string.Format("{0}\\{1}\\{2}", Application.StartupPath, "Configuration",
                                            "TaskAlert.xml");
                if (userId.Equals(0))
                    userId = Utility.Application.CurrentUser.UserId;

                XDocument xdoc;
                LoadTaskAlertXml(out xdoc, path, userId);
                xdoc.Save(path);
            }
            catch (Exception exception)
            {
                MSLib.HandleException(exception);
            }
        }

        public static void LoadTaskAlertXml(out XDocument xdoc, string path, int userId)
        {
            xdoc = null;
            TaskCollection tasks = TaskEntity.GetOverDueTasks(userId);
            if (!File.Exists(path))
            {
                CreateTaskAlertXml(userId.ToString(), ref xdoc);
                AddOverDueTasksInTaskAlertXml(xdoc, userId.ToString(), tasks, false);
            }
            else
            {
                xdoc = XDocument.Load(path);

                XElement userElement =
                    xdoc.Descendants("User").Where(x => x.Attribute("Id").Value.Equals(userId.ToString())).
                        SingleOrDefault();

                if (userElement == null)
                {
                    AddParentNodeInTaskAlertXml(ref xdoc, userId.ToString());
                    AddOverDueTasksInTaskAlertXml(xdoc, userId.ToString(), tasks, false);
                }
                else
                    AddOverDueTasksInTaskAlertXml(xdoc, userId.ToString(), tasks, true);
            }
        }

Comment: possible duplicate of [Disable XML validation when using XDocument](http://stackoverflow.com/questions/5497572/disable-xml-validation-when-using-xdocument)
Comment: @Naveed: As Jon already said, please provide us with the hex value of the first character.
Comment: hex value of first character is 3f
Comment: Is this a Unicode byte-order mark, then converted as unknown character back to ASCII encoding -- which then gets turned into "?"  This happens quite often when you're simplistically converting Unicode texts into ASCII format by converting each character.
Comment: Thanks Stephen Chung. I am simply creating the file using code that is mentioned in my post. I am not mentioning any encoding format while creating the file. By default it is created with utf-8 encoding.
Comment: @Naveed: Your code doesn't create any files. It creates an in-memory object. Please show the code to actually create the file.
Comment: Why are you using an out parameter for a method which has a void return type? Just make LoadTaskAlertXml return XDocument...
Answer: LINQ to XML wouldn't create an invalid file to start with, so question 3 is moot.
LINQ to XML is only designed to read valid XML. You should find out why you've ended up with invalid XML to start with, and fix the root cause. It's generally a bad idea to try to fix an already-invalid file, especially without understanding the root cause to start with - you never know what other problems might be lurking round the corner.
I suspect that the extra character was originally a byte order mark, but that it's been mangled by something else. If you can give us more information about how you've created the file in the first place, that would help a lot. LINQ to XML can read files which start with a valid BOM with no problems.
I suggest you look at the file in a binary editor and edit your question with exactly the bytes at the start of the file. A valid UTF-8 BOM would be 0xEF, 0xBB, 0xBF.
EDIT: It sounds like the bug is in the way you're creating the file. For example, this should be absolutely fine:
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument doc = new XDocument();
        doc.Add(new XElement("Test"));
        doc.Save("test.xml");
    }
}

That creates a file with a valid byte order mark. Please show an equivalent program which doesn't, or investigate exactly what you're doing with the file, e.g. copying via FTP.
As an aside, do you really need to use ref in your call to AddParentNodeInTaskAlertXml? It seems unlikely to me. See my parameter passing article if you're not quite sure what ref really means.
Comment: @Naveed: Please update your original question with your XML file. It will be more readable.
Comment: @Naveed: Posting XML into a comment isn't going to help. You should edit your question showing the *binary* data at the start of the file, as hex. It's the first character that's relevant, and we need to know what it's like at a binary level, not what your text editor shows it as.
Comment: hex value of first character is 3f.
Comment: @Naveed: In that case it's definitely *not* a valid BOM. How did the file get created in the first place?
Comment: @Naveed: You've shown the code you've used to create an XDocument, but not how you've then saved it. A short but *complete* program which demonstrates the problem would be useful... are you by any chance explicitly using Encoding.ASCII anywhere?
Comment: I am saving the file using xdoc.Save(path); Not using any encoding while creating or updating the file. Thanx..
Comment: @Naveed: And is the file being copied anywhere somehow? I'm afraid I simply don't believe that LINQ to XML is creating an invalid file like that. Please show a *complete* program which generates an invalid file. It only needs a single element. I'll edit my answer to show what I mean.
Comment: It doesn't create the wrong xml first time. It is a very rare case. I am manipulating the xml file wile tasks are added, updated or snoozed. And it works perfectly. Some times only for some users, might be during updating, it added some invalid characters in the xml and then it starts throwing exceptions. I am simply saving the xml after updating it using the syntax xdoc.Save(path); This error is one of them that i have posted. This xml is send to us from our client today and i have seen this issue.
Comment: @Naveed: My guess is that your client has loaded the file in a text editor and then saved it as ASCII. Are you saying you can't actually reproduce this problem yourself? If so, it would really have been useful to say so to start with...
Comment: I am really unable to reproduce it. As i already mention that it is very rare. Well it is dynamically created always.
Comment: @Naveed: Well it certainly sounds to me like the file has been messed up outside LINQ to XML. I simply don't believe that LINQ to XML would create a broken BOM like that.
Comment: Thanks Jon for your participation. Let me sort out the problem and will update here if  i am able to fix it. Thank you so much once again..
Comment: I am having this same issue... some xml files have invalid characters and some files(majority) are okay... all files are created by the same application
Comment: @iroegbu: I suggest you ask a new question with more details. My guess is that you're applying an incorrect encoding, but we need more information, and the comments of this question aren't the best place to give that information.
Comment: sorry, I've fixed it though... File was corrupted during transfer. Thanks.


Batch file to run PowerShell Script Only Works Once

Question: So I'm trying to create a batch file to run a PowerShell script while bypassing the execution policy.  Oddly, it worked a single time, but without me editing anything, it will not run again.  I've created other files thinking maybe my file somehow got corrupted, but nothing...  Any chance someone sees anything blatantly wrong with this?
@echo off
Powershell.exe -Command "& {Start-Process Powershell.exe -ArgumentList '-ExecutionPolicy Bypass -File %~dp0File.ps1' -Verb RunAs}"
PAUSE

The *.ps1 file works by itself if I click through the prompts.  Also, if I manually set the execution policy in PowerShell to Bypass, this batch file still does not work.  This is not a process I usually need to take, so I'm curious if anyone sees anything wrong with how this is written?
Comment: Wow ... that's new. ;-)  ... you're using one command line interface to start another command line interface to start the second command line interface again.   ;-)  You could simply use a link with the command line you need. Like `Powershell -ep bypass -file 'Your Powershell script'`  ... and you cannot bypass the Execution Policy for scripts from inside a script. ;-)
Comment: @ChristopherCass ... wow, that's even worse. It sounds like the tail's wagging the dog. ;-)  No offense ... I'd recommend that you try to get some help from a trained person. I'm pretty sure there must be a cleaner way to do whatever you do.
Comment: Is it getting stuck on the pause without user input?
Comment: Your example seems to work for me.
Comment: I'm not seeing the pause at all.  I see a CMD window pop up for a moment, a PowerShell window pop up for a moment, and then they both vanish with seemingly nothing happening.  But the  pause is after the PowerShell line, so shouldn't it pause after that runs?
Comment: `PAUSE` will occur after the `powershell` command, but if that starts a process in a new window, and that process ends, then you'll see the window appear, disappear, and then the "Press Enter to continue... :" prompt.
Comment: @Olaf got me in the right place, thanks.  My bigger issue was that I'm also having to call another PowerShell script from within my PowerShell script...  So my bat file now gathers the current execution policy, dumps that into a temporary txt file, then runs a command to change the entire system to bypass as opposed to just one script, runs all the scripts I need to run, then finally uses the txt file I created at the beginning to create another script to change the execution policy back to what it was before I started.  I'm certain there is a better way to do this, but this worked.
Comment: I'm certain there is, but there are no resources for me at the moment other than Google and I'm in a time crunch.  It worked, so maybe in the future I'll be able to clean it up, but it does what I need for now.
Answer: If this is just to run your script, what I personally do is create a shortcut of the script and then modify the Target of the shortcut:
Target: Powershell.exe -ExecutionPolicy Bypass -File "C:\scriptpath\script.ps1"
If you want your script to be executed as Administrator you can add this to the top of the main script:
$myInvoke="-file `"$($MyInvocation.ScriptName)`""
Start-Process "$PSHome\powershell.exe" -Verb Runas -ArgumentList $myInvoke -EA 'Stop'

If the shortcut will always be in the same folder as your script you can also leave Start In blank and change the path for Powershell.exe -ExecutionPolicy Bypass -File ".\script.ps1" by doing so if you copy the entire folder to a different location, the shortcut will still work.


Erro ao montar String com parâmetro .NET

Question: Então galera, estou desenvolvendo um projeto com .NET Core Razor, e estou montando uma string la, da seguinte maneira:
string TotalInformacoes = "";
TotalInformacoes += (!String.IsNullOrEmpty(cl_1.Trim()) ? "/CLIENTE:" + cl_1 : "");
TotalInformacoes += "ÿ";

cl_1 é um parametro que estou recebendo quando executo um post, e no caso deste teste, estou deixando o campo vazio propositalmente. É um input type text.
quando eu debugo o código consigo ver que o cl_1 está nulo, mas por algum motivo, está dando este erro no meu navegador:

NullReferenceException: Object reference not set to an instance of an
  object.

E me mostra em vermelho esta linha:
TotalInformacoes += (!String.IsNullOrEmpty(cl_1.Trim()) ? "/CLIENTE:" + cl_1 : "";

Como esta no print:

EDIT1: Código do OnPost:
public IActionResult OnPost(string cl_1, string dt_in)
{
    string TotalInformacoes = "";
    TotalInformacoes = checkDataInicial == "1" ? "/DI:" + dt_in : "";
    TotalInformacoes += (!String.IsNullOrEmpty(cl_1.Trim()) ? "/CLIENTE:" + cl_1 : "");
    TotalInformacoes += "ÿ";

    return Page();
}

Input:
<input name="cl_1" id="cl_1" class="form-control pl-2" type="text">
<input type="date" class="form-control" id="dt_in" name="dt_in">

Comment: A sua pergunta também não tem o código necessário para identificar onde está o erro. Com uma pergunta genérica a resposta acaba sendo genérica. Essas respostas tem um problema igual e explicação porque o erro ocorre, então assim você consegue resolver no seu código. lendo isso aprenderá que esse erro sempre é gerado em outro lugar, e aí poderá aprender não cometê-lo mais que é o mais importante que uma solução pontual.
Comment: Antes que perguntem, este input não está como required
Comment: @Maniero, acho que o link que vc passou não tem a resposta do que eu preciso. O erro é o mesmo, mas são situações diferentes, inclusive o dele é em um get. Eu consigo ver o valor desta minha variável, através de um debug.
Comment: O meu erro está neste local sim. Se eu comento a linha, o post é feito normalmente @Maniero
Comment: @Maniero, editei a pergunta colocando o código.
Comment: @Lima, veja que você não está recebendo nada para `cl_1` em seu método, debugue o seu código, veja que que se você atribuir um valor default para o parâmetro, o erro não vai acontecer `OnPost(string cl_1="")`...Mas isso ainda não fará o seu código funcionar... talvez um `[FromBody]` ajude, mas leia as outras perguntas apontadas pelo Maniero e entenda o que você está fazendo.
Answer: O erro ocorre pois o parâmetro esta null, conforme você mencionou, e você esta chamando o String.IsNullOrEmpty mas na hora de passar o campo no parâmetro do método você chama o Trim, então a primeira coisa a ser executada é o Trim, e o Trim espera que o valor nunca seja null, por isso você o erro de NullReferenceException.
Você pode usar o IsNullOrWhiteSpace, que verifica se o texto não e nulo e não é apenas espaços em branco:
(!String.IsNullOrWhiteSpace(cl_1) ? "/CLIENTE:" + cl_1 : "");

Caso queira saber melhor o que esses métodos fazem, você pode ver o fonte deles aqui:
IsNullOrEmpty
IsNullOrWhiteSpace
Comment: Funcionou... então o erro estava no meu `Trim()` não no `IsNullOrEmpty`. Entendi, obrigado


Theorem about closed prenex wf.

Question: This question is from Introduction to Mathematical Logic by Elliot Mendelson , page 94 , exercise 2.58(a).The problem goes something like this ,

Show that a closed prenex wf $(\forall x_1)...(\forall x_n)(\exists y_1)...(\exists y_m)\mathscr B$ with $m \geq 0$ and $n \geq 1$ , is logically valid if and only if it is true for every interpretation with a domain of n objects.

Here , $\mathscr B$ is any wf that contains no quantifiers , function letters , or individual constants.
My attempt:
($\rightarrow$)
If $(\forall x_1)...(\forall x_n)(\exists y_1)...(\exists y_m)\mathscr B$ is logically valid , then it true for every interpretation. Then , it is true for every interpretation with a domain of $n$ objects.
($\leftarrow$)
Here , $(\forall x_1)...(\forall x_n)(\exists y_1)...(\exists y_m)\mathscr B$ is true for every interpretation with an domain of $n$ objects.I have to prove that $(\forall x_1)...(\forall x_n)(\exists y_1)...(\exists y_m)\mathscr B$ is logically valid.Here are the following things I tried so far:
(1) Induction on $m$.
(2) Induction on $n$.
(3) A two layer induction on both $m$ and $n$.
(4) Using theorem (VIII) in page 61.
(5) Showing that $\mathscr B$ is an instance of a tautology
(6) "Maybe" I could show that the predicate letters in $\mathscr B$ are in the
form $A^n(x_1,...,x_p,y_1,...,y_q)$ where $p \leq n$ and $q \leq m$. And  then  It could help me prove the main theorem (idk).
(7) Shufflling the quantifiers $(\forall x)$ and $(\exists y)$ somehow.
(8) First trying to prove that $\vdash \mathscr D$ (where $\mathscr D$ is $(\forall x_1)...(\forall x_n)(\exists y_1)...(\exists y_m)\mathscr B$ ) and then prove that $\mathscr D$ is logically valid (using Gödel's completeness theorem).
(9) [Hint from @spaceisdarkgreen] Trying to prove the contrapositive of the original statement.
(10) Using exercise 2.55 (a) [If a wf is not $k$-valid , then it is not $(k+1)$ valid]
But so far I did not get anywhere. Can someone give me a hint about this? Also is my proof for the ($\to$) case correct?
Comment: It is probably easiest to approach from the contrapositive: show that if the sentence is not valid (i.e. there's some interpretation where it's not true), then you can construct an interpretation on a domain with $n$ objects where it is not true.
Comment: @spaceisdarkgreen I now tried to prove the contra-positive , but it still seems complicated and I am still stuck. Anyway , Thanks for the advice.
Comment: I'd suggest trying this straightforwardly: if you have an interpretation with more than n objects, and want to check for a specific $x_1\ldots x_n$ in that interpretation that $\exists y_1 \ldots \exists y_n B$.

How can you use the hypothesis to find such $y_1 \ldots y_n$ in the interpretation with more than $n$ objects?
Answer: I'll elaborate on my comment: Suppose you have an interpretation with more than $n$ objects, and want to check for a specific $x_1,\ldots,x_n$ that $\exists y_1\cdots\exists y_n B$. Restrict the interpretation to just $x_1,\ldots,x_n$. By the hypothesis, there are $y_1,\ldots,y_n$ in this restriction that (with the $x$s) satisfy $B$. Because of the restrictions on $B$, $x_1,\ldots,x_n,y_1,\ldots,y_n$ satisfy $B$ in the original interpretation as well.
Comment: I am having some difficulty understanding your answer. Are you trying to prove that if the wf $(\forall x_1)...(\forall x_n)(\exists y_1)...(\exists y_m)\mathscr B$ is k-valid , then it is logically valid?
Comment: I'm proving that if it is $n$-valid, then it is logically valid. This is specifically the $\Leftarrow$ direction of the problem. Note that this $n$ has to be the same as the number of universal quantifiers at the beginning, so you can restrict to the substructure which only contains $x_1,\ldots , x_n$.
Comment: But I cant seem to relate your proof with the original problem. Like , I cant seem to understand that what are the premisses and conclusion of your proof.
Comment: wait, I seem to understand what you are trying to prove. Can you show me a proof of the line "Because of the restriction on $B$ , $x_1 , ... , x_n , y_1 , ... , y_n$ satisfy $B$ in the original interpretation as well."
Answer: Since the question is old and the questioner has, most likely, completed the problem, forgot or abandoned, I think it is appropriate to post a full solution of mine for anyone searching for it or just to check theirs. I am not a trained mathematician, so take it with a grain of salt. If it has blatant mistakes, I strongly encourage you to comment on it, so no one would be deluded.
Denote the prenex with $\mathscr C$ and assume it is true for any interpretation with $n$ elements in its domain.
If $M$ has fewer than $n$ elements in $D$, let $s$ be a sequence in it. If it does not satisfy $\mathscr C$, it would not satisfy it for some model of $n$ objects having $D$ as a subset of its domain and interpreting atomics as in $M$ for this subset. So $s$ must satisfy $\mathscr C$.
Now suppose $M$ has more than $n$ elements and some $s$ does not satisfy $\mathscr C$. Then it satisfies $(\exists x_1)\dots(\exists x_n)(\forall y_1)\dots(\forall y_m)\neg\mathscr B$. Let $s'$ be different from $s$ in at most $s(x_1), \dots, s(x_n)$ places that satisfies $(\forall y_1)\dots(\forall y_m)\neg\mathscr B$. Now, if we make an interpretation with a domain consisting solely of these $s'(x_1), \dots, s'(x_n)$ (adding any others to make $n$, if some are not distinct; it is possible, since the others do not change the following inference) that interprets atomics in $\mathscr C$ similarly, we would have a contradiction, since it has $n$ elements and $\mathscr C$ must be true in it (because $s'$ with out-of-domain elements replaced with any of available would satisfy $(\forall y_1)\dots(\forall y_m)\neg\mathscr B$ and $(\exists y_1)\dots(\exists y_m)\mathscr B$, here is a contradiction).

Theorem about closed prenex wf.


How to include "Host Component" of HyperV in backup with wbadmin?

Question: I'm trying to set up a script to run the backups of my Virtual Machines only using WBADMIN, I've got as fas as being able to backup all the VMs using the new -HyperV switch, however I also want to backup the HyperV Host Component. Does anyone have any experience in doing this or can point me to some documentation (the Microsoft one neglects this new -HyperV switch)
This is my powershell script if your interested:
#Constant Variables
$Day = Get-Date
$Day = $Day.DayOfWeek
$Date = Get-Date -format hhmmddMMyyyy
$Server = hostname

#Set Paths
$BackupPath =  "\\backup\Backups\" + $Server + "\" +$Day
$LogPath = "\\backup\Backups\" + $Server + "\Logs\" + $Date +".txt"

# SELECT Virtual Machines
$VMList = $null
$VMs = Get-VM | Select-Object VMId
for ($i = 0 ; $i -lt $VMs.length ; $i++) {
    $VMList = $VMList + '"' + $VMs[$i].VMId + '"' +","
}
$VMList =  $VMList.Substring(0,$VMList.Length - 1)

#Run Backup
WBADMIN START BACKUP -backupTarget:$BackupPath -hyperv:$VMList -Quiet

Comment: Good question.  I see the gui choice, but nothing yet related to wbadmin cli.
Comment: Ok so I've found some actual microsoft documentation on this but it still doesn't mention the 'host component'. While its not the end of the world as all of my hosts are identical it would be easier to be able to restore it if required!
http://blogs.msdn.com/b/virtual_pc_guy/archive/2013/02/25/backing-up-hyper-v-virtual-machines-from-the-command-line.aspx
Answer: So i finally figured out that you need to ditch WBADMIN and start using the WBbackup CMDLETS in powershell instead, heres how you can do it
#Constant Variables
$Day = Get-Date
   #Use this for Backups in Evening
    $Day = ($Day.AddDays(1)).DayOfWeek

    #Use this for Backups in the Morning
    #$Day = $Day.DayOfWeek

$Date = Get-Date -format hhmmddMMyyyy
$Server = hostname
$Target = '\\backup\backups\'+$Server+'\'+$Day
$VirtualMachines = Get-WBVirtualMachine

$DailyFullWB = New-WBPolicy
$BackupTarget = New-WBBackupTarget -NetworkPath $Target
Set-WBPolicy -Policy $DailyFullWB
Add-WBBackupTarget -Policy $DailyFullWB -Target $BackupTarget -Force
Add-WBVirtualMachine -Policy $DailyFullWB -VirtualMachine $VirtualMachines
Start-WBBackup -Policy $DailyFullWB -AllowDeleteOldBackups -Force

Answer: Actually the solution is too easy to believe, and yes, it's nowhere documented. You actually "just" need to include the string "Host Component" in your VMlist (parameter --hyperv).
Just remember that it includes a space, and you thus you need to quote the string.
E.g. like that:
wbadmin start backup -backupTarget:$BackupPath -hyperv:"$VMList,Host Component" -quiet

At least with Windows Server 2016 this worked.


Exibir ou Ocultar Campos para Pessoa Física ou Pessoa Jurídica

Question: Eu tenho um formulário que cadastra Clientes, e possui a opção de ser Pessoa Física ou Pessoa Jurídica, sendo que cada um possui alguns campos diferentes.
Pensei em usar um @Html.RadioButton com a opção Pessoa Física e Pessoa Jurídica.
Quando houvesse um clique em uma das opções aparece-se as campos respectivos.
Como faço isso?
Comment: O caminho seria usando jQuery. Quer uma resposta em jQuery?
Comment: Olá para você fazer isso com o minimo de dor de cabeça, o mais correto é usar JavaScript para fazer um controle visual de mostrar e esconder os campos do form.

Se você fosse fazer direto no Razor (linguagem da view @Html.AlgumaCoisa) daria trabalho porque as duas opções seria ou dar um post no form e retornar ele mesmo com diferentes campos, ou usar um UpdatePanel que para esse caso eu acho besteira.

Porém o padrão mais usado (você pode conferir em muitos sites que possuem cadastros) é ter os dois forms, pessoa física e jurídica, e seu radiobutton apenas habilita o form certo
Comment: Sugestão, se possível evite o uso de javascript, declare os 2 menus como visible false , e quando selecionado no radiobuttom , checkbox, coloque visible true para os mesmo.
Answer: Para isso você pode usar jquery, usando classes, assim:

$( document ).ready(function() {
     $(".campoPessoaJuridica, .campoPessoaFisica").hide();
});

$("input:radio[name=tipo]").on("change", function () {
    if($(this).val() == "pessoaFisica")
    {
     $(".campoPessoaFisica").show();
        $(".campoPessoaJuridica").hide();
    }
    else if($(this).val() == "pessoaJuridica")
    {
     $(".campoPessoaFisica").hide();
        $(".campoPessoaJuridica").show();
    }
});

    <input type="radio" name="tipo" value="pessoaFisica">Pessoa Física</input>
    <input type="radio" name="tipo" value="pessoaJuridica">Pessoa Jurídica</input>

Nome:
        <input type="text" id="nome">

Razão Social:
        <input type="text" id="razaoSocial">

Fiddle = http://jsfiddle.net/henriquedpereira/tmedhg8g/


What does the notation -S mean if S is a set?

Question: As the title says, what does the notation $-S$ mean if $S$ is a set? For instance, in the context of something like $S \cup -S = F$, where $F$ is a field and $S$ is a subset of $F$?
Thanks in advance.
Comment: In this precise situation, $-S=\{-s,\,s \in S\}$.
Comment: Straight-forward answer. Thank you.
Answer: A possible interpretation in sets is $-S=\{x\in F : x \not \in S\}$ and this satisfies $S \cup -S = F$
But you say $F$ is field.  So another possible interpretation is $-S=\{x\in F : -x  \in S\}$, which need not satisfy $S \cup -S = F$
Given this ambiguity, it should be clear that a definition needs to be given by the user


Mysql query that performs sums between different tables

Question: I am struggling to make a query in a custom service function in Drupal 7, which should make 3 sums. In each table (3), there are 2 records saved with the following values:

field_data_field_monto_15pts with field [field_monto_15pts_value] data: 5 and 6
field_data_field_monto_14pts with field [field_monto_14pts_value] data: 3 and 4
field_data_field_monto_13pts with field [field_monto_13pts_value] data: 1 and 2

The service function that performs the query and returns data in the JSON format is the following.
<code>$cantidad = db_query('
  SELECT SUM(field_monto_15pts_value) AS 15pts,
         SUM(field_monto_14pts_value) AS 14pts,
         SUM(field_monto_13pts_value) AS 13pts
  FROM {field_data_field_monto_15pts},  {field_data_field_monto_14pts},  {field_data_field_monto_13pts}')
  ->fetchAssoc();

return $cantidad;
</code>
What I expect from the function is the following values.
<code>{
  "15pts": "11",
   "14pts": "7",
   "13pts": "3"
}
</code>
What the function returns is this.
<code>{
   "15pts": "44",
   "14pts": "28",
   "13pts": "12"
}
</code>
What is wrong in the code I am using?
Answer: Well ... Since no one had this problem, or nobody has a solution, I put the solution that I have given on the site https://www.drupal.org/node/2898276
The problem is how I wrote the query to the database. A Cartesian product is produced. After rewriting the query was solved. It was finally written:
<code>$lo_que_che= db_query('SELECT (SELECT SUM(field_monto_15pts_value) AS 15pts FROM {field_data_field_monto_15pts}) 15pts, (SELECT SUM(field_monto_14pts_value) AS 14pts FROM {field_data_field_monto_14pts}) 14pts, SUM(field_monto_13pts_value) AS 13pts FROM field_data_field_monto_13pts}') ->fetchAssoc();  return $lo_que_che;
</code>


Finding the length of a triangle given one side and the ratio the median and angle bisector cut the altitude.

Question: A median BK, an angular bisector BE and an altitude AD are drawn in a triangle ABC. Find the
side AC if it is known that the line BK and BE divide the line segment AD into 3 equal parts and
if AB = 4cm. Find the length of AC.

Currently, I am able to work out that BD=2 by angle bisector theorem and that,since,sin BAD= 1/2; BAD=30 and angle ABC=60 but after that I'm unable to work it out further.
Comment: https://imgur.com/a/czyAJEl
Comment: I think converting to a coordinate system works. Setting $B$ as the origin, $A$ is at $(2,2 \sqrt 3)$, and $M$ is at $(2,4/ \sqrt 3)$. Then $AK$ has slope $2/ \sqrt 3$. $K$ must be at $(x_1, 1/ \sqrt 3)$, since its y-coordinate must be halfway between the y-coordinate of $A$ and $C$, which is at $(2x_1,0)$. Now find the point on $AK$ that has that y-coordinate.  I suspect, though I haven't gone all the way through, that the triangle is obtuse.
Comment: Gah, I didn't see a mistake until after the edit window. $K$ is at $(x_1, \sqrt 3)$, not $1/\sqrt 3$.
Comment: HINT. Point $C$ must be on the left of $D$. It turns out that $C$ is the midpoint of $BD$.
Comment: Pardon for the innaccuracy of the diagram.
Comment: Since $\overline{AD}$ is an altitude, $\angle BDA = \angle CDA = 90°$. Did you mean $\angle ABD$ perchance?
Comment: Yes, my mistake, I meant angle BAD
Comment: @Intelligentipauca yes i'm certain the text is correct, but I also suspect the question is wrong
Answer:
I can help you with the construction, and you should be able to do the rest. Forget about the length of $AB$ for now.

Draw altitude $AH$ , draw the baseline (where points $B$ and $C$ should lie), and draw the midline (where point $K$ should lie). Mark points $X$ and $Y$, which divide $AH$ into 3 equal segments.

Draw circle $c$ with center $X$ and radius $XH$.

$X$ is on the bisector of $\widehat{ABC}$, so $AB$ should be tangent to circle $c$. Draw $AB$.

Draw $BY$. It meets the midline at $K$, the midpoint of $AC$.

Draw $AK$ and extend it to meet the baseline at $C$.

Now, can you do the rest?
Comment: Oh, this is *beautiful.* It's where my algebra comment leads, but without the algebra. I love seeing a good construction, and hopefully OP can follow it readily. Also a tip of the hat to Geogebra, I assume.
Comment: @EricSnyder Thanks a lot. You correctly noted that the triangle is obtuse. As for the image, I made it with AutoCAD.


Using energy method to existence and uniquesness the following PDE .

Question:
Approach : Find the energy functional :
$\int_\Omega \nabla u \nabla v \int_\Omega |u| u.v -\int_\Omega fu=0 \forall u \in H_0^1(\Omega) \cap L^3(\Omega)$
$\implies E(u)=\int_\Omega\frac{1}{2} |\nabla u|^2+\frac{1}{3} |u|^3 -fu  dx$
If $u$ solves $\min_{u \in A} E(u)$ with $A={}u\in H_0^1( \Omega)\cap L^3(\Omega)$ then for any $v\in A$ we have
$0=\frac{d}{d\epsilon}E(u+\epsilon v)=\int\frac {d}{d\epsilon}|\nabla(u+\epsilon v)|^2 +\frac{1}{3} |u+\epsilon v|^3 -f(u+\epsilon v)dx$
$$=\int(\nabla u. \nabla v +|u|v -fv)  dx$$
Remark: There seems to be a problem while differentiating with respect to $\epsilon$ the term $|u+\epsilon v|^3$ , how do I resolve it ?
Next : Can I say that $u$ is a weak solution now ? If I could then would proceed further this way  If
$A$ is not a null set , then $\exists (u_k)_{k\in \mathbb N} \subset A$
$$\lim_{k\to\infty}u_k=\inf_{u\in A} E(u)$$
Assume $u_k$ is not bounded in $H_0^1 $
$$E(u_k)\ge \int_\Omega \frac {|\nabla u_k|^2}{2}-fu_k dx  \ge \frac{1}{2} ||\nabla u||_{L^2}-C ||f||_{L^2} ||\nabla u_k||_{L^2(\Omega)}$$
I am stuck now , How do I proceed further ?
Thanks.
Answer: Concerning the differentiation of $\epsilon\mapsto |u+\epsilon v|^3$. The function $g(x)=|x|^3$ is in $C^2(\mathbb R)$ with $g\,'(x)=3x|x|$ and $g\,''(x)=6|x|$. Notably, $g$ is convex, which makes the entire functional $E$ convex; we need this for its lower semicontinuity with respect to the weak convergence in $A$.
But to begin with, we want to show that $E$ is bounded from below on $A$; otherwise the entire approach is doomed. The only question is what to do with $\int-fu$: suppressing the urge to use Holder's inequality, I would write $-fu\ge -\frac12f^2-\frac12 u^2$. Here the integral of $f^2$ is a finite constant and $u^2\le \frac12|u|^3+8$ pointwise. It follows that $E$ is bounded from below: $E(u)\ge \int (\frac12|\nabla u|^2+\frac{1}{12}|u|^3-\frac12f^2-8)$ or something of the kind. Note that I bounded $u^2$ by a small multiple of $|u|^3$ in order to have some of the cubic term left over. This will be useful in a moment.
Pick a minimizing sequence $u_k\in A$ as you've done already. The lower bound for $E(u)$ in the previous paragraph tells us that $\int|\nabla u_k|^2$ and $\int|u_k|^3$ are uniformly bounded. Thus, the sequences is bounded in $H_0^1$ and in $L^3$. Pick a weakly convergent subsequence in $H_0^1$; extract from it a weakly convergent subsequence in $L^3$. The lower semicontinuity of $E$ implies $E(u)=\min_A E$ where $u$ is the weak limit.
And yes, having $\int (\nabla u\cdot\nabla v +\frac13 u|u|v-fv)=0$ for all test functions $v$ (you only need to consider $C^\infty$-smooth $v$ with compact support) means that $u$ is a weak solution; this is what weak solution means. The boundary condition $u=0$ is automatically fulfilled since we work in $H_0^1$ all the time.
Comment: Sir , what is meant by lower semicontinuous functional ? Is there a relation with convexity of the functional ?
Comment: @Theorem It means a functional that is [lower semicontinuous](http://en.wikipedia.org/wiki/Semi-continuity). And yes, there is a [relation](http://en.wikipedia.org/wiki/Direct_method_in_the_calculus_of_variations),


How to create a wrapper cookbook for a supermarket cookbook?

Question: I am trying to use Chef to create an environment in an Ubuntu Server Machine (18.04) that must contain PostgreSQL and MsBuild (I will deploy an asp.net core app). There are already cookbooks for setting up postgres in the supermarket, but I can't use them. I am following this tutorial
First I created a new wrapper cookbook:
chef generate cookbook my_postgres

Then I changed the metadata.rb to look like this:
name 'my_postgres'
maintainer 'The Authors'
maintainer_email 'firstname.lastname@example.com'
license 'All Rights Reserved'
description 'Installs/Configures my_postgres'
long_description 'Installs/Configures my_postgres'
version '0.1.0'
chef_version '>= 13.0'
depends 'postgresql'

And my default.rb file is as follows:
#
# Cookbook:: my_postgres
# Recipe:: default
#
# Copyright:: 2020, The Authors, All Rights Reserved.
include_recipe 'postgresql::default'

But when I run the recipe:
sudo chef-client --local-mode default.rb

I receive the following message:
[2020-02-23T16:19:26+00:00] WARN: No config file found or specified on command line, using command line options.
[2020-02-23T16:19:26+00:00] WARN: No cookbooks directory found at or above current directory.  Assuming /home/hermano/my_postgres/recipes.
Starting Chef Client, version 14.7.17
resolving cookbooks for run list: []
Synchronizing Cookbooks:
Installing Cookbook Gems:
Compiling Cookbooks...
[2020-02-23T16:19:28+00:00] WARN: MissingCookbookDependency:
Recipe `postgresql::default` is not in the run_list, and cookbook 'postgresql'
is not a dependency of any cookbook in the run_list.  To load this recipe,
first add a dependency on cookbook 'postgresql' in the cookbook you're
including it from in that cookbook's metadata.

Running handlers:
[2020-02-23T16:19:28+00:00] ERROR: Running exception handlers
Running handlers complete
[2020-02-23T16:19:28+00:00] ERROR: Exception handlers complete
Chef Client failed. 0 resources updated in 01 seconds
[2020-02-23T16:19:28+00:00] FATAL: Stacktrace dumped to /home/hermano/.chef/local-mode-cache/cache/chef-stacktrace.out
[2020-02-23T16:19:28+00:00] FATAL: Please provide the contents of the stacktrace.out file if you file a bug report
[2020-02-23T16:19:28+00:00] FATAL: Chef::Exceptions::CookbookNotFound: Cookbook postgresql not found. If you're loading postgresql from another cookbook, make sure y

make sure you configure the dependency in your metadata
What Am I missing?
Answer: Your issue should be on your current working directory from where you execute your command that according to your output line     [2020-02-23T16:19:26+00:00] WARN: No cookbooks directory found at or above current directory.  Assuming /home/hermano/my_postgres/recipes. should be /home/hermano/my_postgres/recipes
According to the documentation you have to create a directory named cookbooks and put there your cookbooks directory:
/home/hermano/cookbooks
/home/hermano/cookbooks/my_postgres

Then you should set your cwd on the cookbooks directory and execute the following:
cd /home/hermano/cookbooks
sudo chef-client --local-mode --runlist "my_postgres::default.rb"

Comment: I feel so stupid. That was it, thank you very much.


Check if a point is in the interior of the convex hull of some other points in high dimensions, and lower-bounding the largest enclosed ball

Question: Given $m$ points $P=\{p_0, p_1, ..., p_m\}$ in high dimensions (e.g. 100), it is known that computing (or even representing) their convex hull $\text{conv}(P)$ is generally intractable due to the exponential dependence on dimensions. In this case, I wonder:

Is there an efficient algorithm to check whether some other given point $\tilde{p}$ is an interior point in the convex hull (i.e. there is a small ball centered at $\tilde{p}$ and lies in $\text{conv}(P)$)? I know we can construct a linear programming problem to check if a point lies inside the convex hull, but my question here is to further check if the convex hull has "volume" and if $\tilde{p}$ lies in its interior.
Following 1, can we compute or efficiently lower-bounding the largest enclosed (inscribed) ball centered at $\tilde{p}$ and lies in $\text{conv}(P)$?

I'm an amateur in geometry and I appreciate any potential solutions or suggestions. Thank you for your time!
The same question posted on mathoverflow.
Answer: Does the interior point algorithm finds an ellipsoid as the result? I mean we can define a convex program with being in convex hull of $P_i$s and objective function as the distance between the variable point and $\tilde{p}$. The interior point algorithm on this mathematical program will return an ellipsoid, if possible?
Comment: Is this what you are seeking for?
https://apps.dtic.mil/dtic/tr/fulltext/u2/a153542.pdf
Comment: Thanks for your answer! I may not be clear on describing the problem but in question 2 I am looking for the largest inscribed ball within that convex hull. In this sense, to construct the optimization problem we may need exponentially many constraints since the number of faces of the polytope generally has an exponential dependence on dimensions.

And for question 1, the interior point method may work in the relative interior of the convex hull, but I also wonder if we can check if the convex hull really has "volume". Thanks!
Comment: Thanks for the reference! I took a look from Google cached file, yet it seems that in this paper the polytope is given by linear inequalities. In my problem the inequalities (hyperplanes) needed to represent the polytope may be exponentially many given points in high dimensions, so I guess that way won't work directly. I'll see if the problem can be constructed in some other way.


Setting custom screen name for bottom sheet screen for Firebase Analytics

Question: I have an activity with a sliding bottom sheet. I want to track how long does the user views the bottom sheet or the main activity screen.
I'm trying to use FirebaseAnalytics#setCurrentScreen(Activity activity, String screenName, String screenClassOverride) so that when the bottom sheet is shown. I specify the screenName with
FirebaseAnalytics.setCurrentScreen(activity, "bottom_sheet", null);

Then when the bottom sheet is closed I call
FirebaseAnalytics.setCurrentScreen(activity, null, null);

to revert to the main activity's name.
However I get a log from FA:

W/FA: setCurrentScreen cannot be called with the same class and name

If anyone can tell me how to properly set the screen name that would be great.
Answer: The screenName is whatever you want to use to identify your Activity/Fragment/Dialog...
You should use setCurrentScreen in this way:
FirebaseAnalytics.setCurrentScreen(activity, "bottom_sheet", this.getClass().getSimpleName());

or
FirebaseAnalytics.setCurrentScreen(activity, "bottom_sheet", MyActivity.class.getSimpleName());

Remember that Firebase Analytics records your current Activity automatically, look at follow setCurrentScreen info from official Firebase docs:

Note that screen reporting is enabled automatically and records the class name of the current Activity for you without requiring you to call this function. The class name can optionally be overridden by calling this function in the onResume callback of your Activity and specifying the screenClassOverride parameter.

You can found this and more documentation here
Now, you are getting that error message

W/FA: setCurrentScreen cannot be called with the same class and name

When you are setting same screenName and screenClassOverride in setCurrentScreen()
Using Log.d in where you are calling that method can help you to see if you are calling same thing twice or more. But I guess you don't have to worry about it (it's a warning). I have been seen it in my current project and everything is working fine.
Comment: but care, I'm facing [this problem](http://stackoverflow.com/q/41792641/1332549) all event using setCurrentScreen are been recorded under `view_item`


Is it possible to do Fizz Buzz in deep learning?

Question: After reading a joke Fizz Buzz in Tensorflow, I am curious to know if it is possible to do such simple task correctly with deep learning. Any theoretical explanation for the reason we can or we cannot?
It is modulo operation, if we can do Fizz Buzz, maybe deep learning also can be used in number theory, such as finding prime numbers?
Comment: It's a very, very big jump from computing a modulo operation to use in modern number theory.
Comment: Please add the problem description into body of your question.
Answer: As the author of the linked blog post, I am happy to say that (with the correct choice of hyperparameters and a little luck) Fizz Buzz can be completely learned by a neural network with one hidden layer.
I spent some time investigating why it works, and the reason is somewhat interesting. It hinges upon the binary representation of the input and the following observation:

if two numbers differ by a multiple of 15, then they belong to the same fizzbuzz "class" (as-is / fizz / buzz / fizzbuzz)

It turns out that there are a number of ways in which you can reverse two bits in a 10-digit binary number and get a number that differs by a multiple of 15. For example, if you start with some number x and turn on the 128 bit and turn off the 8 bit, you get x + 120. There are many other such examples.
And if you have a linear function of the bits that puts the identical weights on those two bits, it will produce the same output for x and x + 128.
As there are many such bit pairs, it turns out that the neural network basically

learns a bunch of equivalence classes (for example, one would contain x, x + 120, and a few other numbers), and
"memorizes" the correct answer for each equivalence class

And so it turns out that when you train the model on the numbers 101 to 1023, you've got enough equivalence classes to predict correctly on 1 to 100.
(This is not formal, of course, this is just a high-level summary of what I learned when I investigated the network.)
--
As to your question about finding prime numbers, I'd be surprised if an approach like this worked. My sense is that the nice "same modulo 15" structure of this problem is what makes the neural net work, and it's hard to think of anything analogous for e.g. finding prime numbers.
Answer: Let me answer the question in a meme way.
Why (always) deep learning? All neural nets do is linear regression (x*w+b) with some non-linearity around the (intermediate) response.

Lets talk machine learning, better yet, optimization. The obvious general class of problems you are referring to is function approximation (not regression per se). So, why not to use method that was developed to do exactly this: writing programs. In theory, yes, you can use 'artificial intelligence' methods to create programs and one of them, given enough data and time, can theoretically be FizzBuzz. Or a programm that computes prime numbers (and that program could be theoretically the same when written by a human). -- No deep learning here --.
Learning from data
Well, can we learn from data? Yes, we can. But first we need to understand data and to engineer some features. Because only one numeric feature is not expressive enough... (for now).
Some code incoming:
library(tidyverse)

theData <- data_frame(a = as.double(1:100),
                      a3 = as.double(a %% 3 == 0),
                      a5 = as.double(a %% 5 == 0),
                      cl = case_when((a3 > 0) & (a5 > 0) ~ 'FizzBuzz',
                                     a3 > 0 ~ 'Fizz',
                                     a5 > 0 ~ 'Buzz',
                                     TRUE ~ 'Number')) %>%
  mutate(cl = factor(cl))

Now we have a numerical feature a (numbers) and a3 and a5 te help with the decision ...

... tree. (╯°□°)╯︵ ┻━┻ again not deep learning here. But a stacked model: first level is DT and scond level is (using Viola-Jones-Cascades or simple filter on the Number response) a plain old linear regression with the solution $y=a$.
The DT first:
treeModel <- rpart::rpart(cl ~ ., theData,
                          control = rpart::rpart.control(minsplit = 5))
rattle::fancyRpartPlot(treeModel, caption = '')

THAT IS CRAZY! A simple decision tree learned FizzBuzz! But did it?
Apply some test data:
testData <- data_frame(a = as.double(200:300),
                      a3 = as.double(a %% 3 == 0),
                      a5 = as.double(a %% 5 == 0),
                      cl = case_when((a3 > 0) & (a5 > 0) ~ 'FizzBuzz',
                                     a3 > 0 ~ 'Fizz',
                                     a5 > 0 ~ 'Buzz',
                                     TRUE ~ 'Number'))

predictions <- predict(treeModel, testData, type = 'class')
table(testData$cl, predictions)

        predictions
         Buzz Fizz FizzBuzz Number
Buzz       14    0        0      0
Fizz        0   27        0      0
FizzBuzz    0    0        7      0
Number      0    0        0     53

Perfect on test set for numbers 200 to 300!
Well, the second layer is easy:
lmModel <- lm(arep ~ a - 1, mutate(theData, arep = a))

The error estimating the number is
testData %>%
  mutate(pred = predict(treeModel, ., type = 'class')) %>%
  filter(pred == 'Number') %>%
  mutate(apred = predict(lmModel, .),
         error = a - apred) %>%
  pull(error) %>%
  summary()

     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
5.684e-14 5.684e-14 5.684e-14 5.684e-14 5.684e-14 5.684e-1

... well very close to 0. Tada!
We learned FizzBuzz from data!
Derp learning
Probably you can do the same stuff with deep learning. You can also do stacked models with LSTM layers and convolution (ya know, because of modulo 3 and 5), and with a huge amount of data you may have a chance to generalize some patterns... yeah... no.
So hope this answer helps to clarify that yes it is possible. And no, you don't need deep learning to do the job. And now, from a single feature a even deep learning will not be able to learn FizzBuzz.
As for prime numbers... if you compute/engineer as many features as there are prime numbers, you can learn them from data, too. ¯_(ツ)_/¯
Comment: Honestly, it needs just a few lines of if-else code, so any machine learning is overkill... As I understood the question, it was rather if deep learning can not fail it as the example failed (obviously yes).
Comment: this doesn't answer the question
Comment: @aaaaaa because the question is specifically about deep learning?
Comment: the Q is not "how to solve this problem" but how can ML help and whether it can help. Great, you showed the Whole Internet that you can write FizzBuzz program. That is not the point. Your only ref to actual question is "with a huge amount of data you may have a chance to generalize some patterns... yeah... no."
Comment: So what's again wrong with showing that and how ML can solve it? Or GP and DT is not ML?


DNA test at scene of crime

Question: A DNA sample has been taken at the scene of the crime. Statistically, the probability of an arbitrary individual's DNA profile to coincide with the one taken at the scene is 0.000001 (0.0001%, i.e. one in a million). A DNA test is carried out among 20 suspects, one of which is definitely the culprit. The probability of the test to give the wrong result is 0.00001 (0.001%).
Of all 20 tested suspects, only one gets a positive result. What is the probability of him being innocent?
Answer: Let $X$ be the Bernoulli random variable which value is $1$ if the test is positive on the culprit, and let $Y$ be the random number of positive tests on the 19 innocent people ($Y$ obeys a binomial law and is independent from $X$).
The probability that you are looking for is
\begin{equation}
P(X = 0 | X + Y = 1) = \frac{P(X = 0 \text{ and } X + Y = 1)}{P(X + Y = 1)}
= \frac{P(X=0) P(Y=1)}{P(X=0)P(Y=1) + P(X=1)P(Y=0)}
\end{equation}
The rest should be easy.

DNA test at scene of crime


How can I create named-instance of Microsoft SQL Server on Ubuntu

Question: I used the official tutorial to create a default instance
https://learn.microsoft.com/en-us/sql/linux/sql-server-linux-setup-ubuntu
but now I want to create a named-instance and can't find how to do that
Comment: I wonder who downvotes questions about a *developer-only* preview that has more documentation in SO Docs than Microsoft's own docs site? It's definitely *not* an administration question - there are no administration tools available yet!
Comment: Can you check the parameters of `sqlservr-setup` ? `apt-get install` only installs the package. Assuming this is implemented, the functionality should be available through `sqlservr-setup`
Comment: `sudo /opt/mssql/bin/sqlservr-setup --help
Microsoft(R) SQL Server(R) Setup

This utility helps configure Microsoft(R) SQL Server(R).
Without options this tool will perform interactive configuration.

Usage: sqlservr-setup [--help] [--accept-eula] [--reset-sa-password]
                      [--set-sa-password] [--start-service]
                      [--enable-service] [--stop-service]
                      [--disable-service]

Options:
  --help                  This help screen.

  --accept-eula           Accept EULA
`
Comment: `
  --reset-sa-password     Reset SA password interactively
  --set-sa-password       Set SA password from SA_PASSWORD environment variable

  --start-service         Start the SQL Server service
  --enable-service        Enable the SQL Server service to start at boot

  --stop-service          Stop the SQL Server service
  --disable-service       Disable the SQL Server service from starting at boot
`
Comment: @PanagiotisKanavos, I added the help of this command from the termainal. can't see any relevant config. should I search in other place?
Answer: SQL Server on Linux doesn't support the notion of "multi-instance", so there are no named instances on Linux.
You can see that its Windows only feature here: https://learn.microsoft.com/en-us/sql/sql-server/install/work-with-multiple-versions-and-instances-of-sql-server?view=sql-server-ver15


Can I change the proposal distribution in random-walk MH MCMC without affecting Markovianity?

Question: Random walk Metropolis-Hasitings with symmetric proposal
$q(x|y)= g(|y-x|)$  has the property that the acceptance probability
$$P(accept\ y) = \min\{1, f(y)/f(x)\}$$
does not depend on proposal $g(\cdot)$.
Does that mean that I can change the $g(\cdot)$ as a function of previous performance of the chain, without affecting the markovianity of the chain?
Of particular interest to me is the adjustment of the scaling of Normal proposal as a function of acceptance rate.
Would also greatly  appreciate if someone can point out to the adaptation algorithms used in practice for this type of problem.
Many thanks.
[edit: Starting with the references given by robertsy and wok I found the following references on MH adaptive algorithms:
Andrieu, Christophe, and Éric Moulines. 2006.
On the Ergodicity Properties of Some Adaptive MCMC Algorithms. The Annals of Applied Probability 16, no. 3: 1462-1505. http://www.jstor.org/stable/25442804.
Andrieu, Christophe, and Johannes Thoms.
2008. A tutorial on adaptive MCMC. Statistics and Computing 18, no. 4 (12): 343-373. doi:10.1007/s11222-008-9110-y. Link.
Atchadé, Y., G. Fort, E. Moulines, and P. Priouret. 2009.
Adaptive Markov Chain Monte Carlo: Theory and Methods. Preprint.
Atchadé, Yves. 2010.
Limit theorems for some adaptive MCMC algorithms with subgeometric kernels. Bernoulli 16, no. 1 (February): 116-154. doi:10.3150/09-BEJ199.   Link.
Cappé, O., S. J Godsill, and E. Moulines. 2007.
An overview of existing methods and recent advances in sequential Monte Carlo. Proceedings of the IEEE 95, no. 5: 899-924.
Giordani, Paolo. 2010.
Adaptive Independent Metropolis–Hastings by Fast Estimation of Mixtures of Normals. Journal of Computational and Graphical Statistics 19, no. 2 (6): 243-259. doi:10.1198/jcgs.2009.07174. http://pubs.amstat.org/doi/abs/10.1198/jcgs.2009.07174.
Latuszynski, Krzysztof, Gareth O Roberts, and Jeffrey S Rosenthal. 2011.
Adaptive Gibbs samplers and related MCMC methods. 1101.5838 (January 30). http://arxiv.org/abs/1101.5838.
Pasarica, C., and A. Gelman. 2009.
Adaptively scaling the Metropolis algorithm using expected squared jumped distance. Statistica Sinica.
Roberts, Gareth O. 2009.
Examples of Adaptive MCMC. Journal of Computational and Graphical Statistics 18, no. 2 (6): 349-367. doi:10.1198/jcgs.2009.06134. http://pubs.amstat.org/doi/abs/10.1198/jcgs.2009.06134.
]
Comment: How come you don't have +100 bonus from your SO record?
Comment: @mbq, probably because I created this account long ago when I was 0 on OS as well...pity, 100 on CW looks like a big deal, since you must be a real chap to answer stuff in here :)
Comment: You can get the bonus by clearing all associations and then associating accounts again.
Answer: I think that this paper from Heikki Haario et al. will give you the answer you need. The markovianity of the chain is affected by the adaptation of the proposal density, because then a new proposed value depends not only of the previous one but on the whole chain. But it seems that the sequence has still the good properties if great care is taken.
Comment: thanks robertsy, for good reference. indeed the process is not markov. Even if acceptance probability is independent of the past, the transition kernel of the process is a function of the proposal density and thus depends on the whole chain.
Answer: You can improve the acceptance rate using delayed rejection as described in Tierney, Mira (1999). It is based on a second proposal function and a second acceptance probability, which guarantees the Markov chain is still reversible with the same invariant distribution: you have to be cautious since "it is easy to construct adaptive methods that might seem to work but in fact sample from the wrong distribution".
Answer: The approaches suggested by users wok and robertsy cover the most commonly cited examples of what you're looking for that I know of.  Just to expand on those answers, Haario and Mira wrote a paper in 2006 that combines the two approaches, an approach they call DRAM (delayed rejection adaptive Metropolis).
Andrieu has a nice treatment of various different adaptive MCMC approaches (pdf) which covers Haario 2001 but also discusses various alternatives that have been proposed in recent years.
Answer: This is a bit of a shameless plug of a publication of mine, but we do exactly this in this work (arxiv). Amongst other things, we propose adapting the variance of the exponential distribution to improve the acceptance (step S3.2 in algorithm in the paper).
In our case, asymptotically the adaptation does not change the proposal distribution (which in the paper is when $f \rightarrow 1$). Thus, asymptotically, the process is still Markovian in the same spirit as the Wang-Landau algorithm. We numerically verify that the process is ergodic and the chain samples from the target distribution we choose (e.g. left bottom panel of Fig. 4).
We don't use information about the acceptance rate, but we obtain an acceptance independent of the quantity we are interested in (equivalent to the energy of a spin system, bottom-right of Fig. 4).


How to use imported constant

Question: I have a file of constant variable like
export const root="http://localhost:3000";
export const noderoot="http://localhost:5000";

I had imported it in my file like
import {root,noderoot} from '../../../assets/admin/js/constant.js'

and i am trying to use it like
axios.get({noderoot}+'admin/')

but it's getting as object not as string and i am not getting my data
Answer: Don't be hard in yourself, sometimes the answer is so simple, just remove the {}
axios.get(noderoot+'/admin/')

Comment: If i am looking in network it's giving me http://3000/admin/undefined/admin
Comment: It's saying undefined to noderoot
Comment: do a console.log(noderoot) , to see if you get the correct value
Comment: MAYBE you should add +     '/admin'   and it isn't the fault of the variable
Comment: It's saying undefined in console as well
Comment: try checking your path if it is correct or not, the code is correct the path may be a problem
Comment: my conclusion :  ../../../assets/admin/js/constant.js    this is not correct , check it again
Comment: No that path is correct because if i remove something then it's giving me error of module not found
Comment: can you tell me how to use listen in axios.get
Comment: Can you reproduce your problem in here https://stackblitz.com/fork/react   i will help 100%
Answer: constant
export const root="http://localhost:3000";
export const noderoot="http://localhost:5000";

imported in other files
import {root,noderoot} from '../../../assets/admin/js/constant'

Ways to access
axios.get(noderoot+'/admin/')

Or
axios.get(`${noderoot}/admin/`)

How to use imported constant


SSR computation for multiple linear regression on book by Douglas

Question: `I am reading the book "Introduction to linear regression analysis" 5th by Douglas.
In the chapter 3 for the multiple linear regression for model $y = X\beta+\epsilon$, it computed $SSR = \hat{\beta}'X'y - \frac{(\sum_1^n{y_i})^2}{n}$ which I believe it is right. Here SSR is the regression sum of squares (i.e the variance from the model)
But just several pages later when discussing regression on subset, it claimed the $SSR = \hat{\beta}'X'y$ without any proof on the same model.
I am confused about the second equation, and believe it is false. But all late discussion is base on the second SSR equation. Can anyone explains what happens here?
Clarification:
If first comment below is true, then we know the first column of X is constant $(1,1,\cdots,1)$, so it indicates $\sum{y_i} = 0$, then under this condition the above two equations are the same, no trouble.
The question is still unsolved. Any help will be appreciated
Comment: It looks like if $X$ is orthogonal to $y$--which can happen--then by definition $\hat\beta^\prime X^\prime y = \hat\beta^\prime(0) = 0$, making $SSR$ negative.  That doesn't seem possible, so we ought to suspect a problem with your *first* formula.  Are you sure you have transcribed it correctly?
Comment: Please register &/or merge your accounts (you can find information on how to do this in the **My Account** section of our [help]). Then you will be able to edit & comment on your own question.
Answer: The first one is actually SSR comparing to the model which has only intercept without regressors and it's mean y.
That is actually SSR(beta|beta0).
The second one is SSR increased due to betas given no model or Y=0.
I would recommend you to check my answer for more information.
https://stats.stackexchange.com/a/361086/212274


Retrieving Data From Server Android

Question: I need to make an app, that it android based.
What I need to do is as follows:
1) A user Logins in to the app (Server);
2) A Chat Menu is shown with users that are connedted;
3) when the user connects the server checks to see if he is single(don't mind this if statment);
4) if the user is single a green icon is add'd next to his nickname;
I just need to to know the basic guidline to do such a thing, Do I need a database on the server?, if so can you direct me to a good tutorial about such thing?
any help would be more than good for me.
Kind Reggards
Boaz.
Answer: Yes, the simplest way to do this is to use a server that keeps track of the states of the logged in users. Your question is not Android specific, and you could e.g. use a general Java based solution modified to fit your needs. Here is a simple example/tutorial.
Comment: You're welcome. Remember to set it as the accepted answer if you feel that it answers your question.

Retrieving Data From Server Android


Weird bug when copying from sql server management studio to excel in windows 7

Question: I run a query in SQL management studio (results to grid), then select all results and copy with headers. Then I paste into Excel.
The result: two specific records are put together on one row in Excel.
With two specific I mean that I first got 26000+ records, then after discovering this bug, changed the query to get just these two records, and still had the same phenomenon occurring, this did not happen in any of the other 26000 records.
I'm running management studio 2008 on a windows 7 machine connected to SQL Server 2000 running on a Windows 2003 server. I tried copying to both Excel 2003 and Excel 2007 and it happens in both cases.
It seems that it has something to do with double quotes. The fourth field (of type varchar(50))has double quotes for both lines (and many more), but it's not the first or last character. The sixth field (of type varchar(1000)) in the first of the two records has double quotes as first character. The fourth field of the first record appears normally. All the fields from the sixth field of the first record upto (inclusive) the fourth field of the second record appear in the same cell in excel. But the double quotes at the end of the sixth field in the first record and in the fourth field of the second record are removed. The characters after the double quotes in the fourth field of the second record still remain in that same cell. The rest of the fields of the second record appear in consecutive columns in Excel.
When pasting in notepad the data does appear normally.
I can't give the exact data, but it's something of the following form:
<code>    float   varchar(50) varchar(50) varchar(50) datetime    varchar(50) varchar(1000)   varchar(50)
    1.1 text    text    text"text   2012-01-01 00:00:00.000 text    "text   text
    1.1 text    text    text"text   2012-01-01 00:00:00.000 text    text    text
</code>
Has anyone encountered this bug before? What is the offending application? SQL Server management studio 2008, Windows 7, both versions of Excel, sql server 2000, Windows 2003? If it is SQL server, does it also happen internally in SQL server?
Comment: 26K records seems like a lot to cut and paste. I suggest you use DTS, SSIS or put the query into a data connection in Excel and pull the records in that way.
Answer: I know this is a very old question but i happened to run into the same issue just now and it was because of the " character. I just removed that in my query with a replace syntax and it worked. PS i also removed all CR LR data as well.
(REPLACE(REPLACE(REPLACE(REPLACE(, CHAR(9), ''), CHAR(10), ''), CHAR(13), ''), CHAR(34), ''))
Answer: No need to worry about anything. Its solution is simple, Just dont select all columns using *, you have to write column names ...be it be all columns but you have to mention column names in select, Then it will surely work .. I have tested and it works just fine..Cheers:)


How To Make a Clone Follow A Turtle

Question: I am making a snake game. I have created a clone every time I touch the fruit. It creates a clone but I need that clone to follow the player on the back of the head. Then I need the other clone that gets created when I touch the fruit again to connect to the back of the clone.
This is the code for the turtle.clone()
    if player.distance(fruit) < 22:
      fruit.goto(randint(-180,0),randint(0,180))
      score = score + 1
      #Sound
      os.system("afplay Sound.wav&")
      #Writing Score
      turtle.clear()
      turtle.write(f"Score = {score}", font=("Arial", 16, "normal"))
      Body_Parts = Body_Parts + 1
      #Add Turtle
      player.clone()

      #Adding To Table
      Parts.append(f"Body{Body_Parts}")
      print(Parts)

Under the player.clone() I want to add the code you help me with.
Thanks for the help.
Answer: turtle.clone()

clones the turtle, if you want to make it follow you can do something like
xc = fruit.xcor()
yc = fruit.ycor()
"make the clone lets say that you made the clone "clone""
while .....:
      clone.setx(xc-10)
      clone.sety(yc-10)

How To Make a Clone Follow A Turtle


Where can I find Android Push Notification Settings in back4app

Question: I'm trying to send a push notification to my app using Parse back{4}app by following this tutorial. But when I get to step 3, they say to edit android push notification settings in the dashboard, but I cannot find this option in my dashboard.
Another thing I didn't understand is the last part of step 1, changing the red code with my own. What am I supposed to change this to?
<category android:name="**dominwong4.scm.back4apppushnotificationcloudcode**" />

It's from from this code:

 <meta-data android:name="com.parse.push.gcm_sender_id"
 android:value="id:966437188652" />
 <service android:name="com.parse.PushService" />
 <receiver android:name="com.parse.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
 <intent-filter>
 <action android:name="com.google.android.c2dm.intent.RECEIVE" />
 <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
 <category android:name="**dominwong4.scm.back4apppushnotificationcloudcode**" />
 </intent-filter>
 </receiver>
 <receiver android:name="com.parse.ParsePushBroadcastReceiver" android:exported="false">
 <intent-filter>
 <action android:name="com.parse.push.intent.RECEIVE" />
 <action android:name="com.parse.push.intent.OPEN" />
 <action android:name="com.parse.push.intent.DELETE" />
 </intent-filter>
 </receiver>

Answer: You change it to the package name of your application. There's a link at the top of that page to a github project.
If you look in there, you'd see code with
package dominwong4.scm.back4apppushnotificationcloudcode;

The instructions assume you've used a package name that identifies your own app when you created a project
Can't help with the dashboard... Haven't used Back4App
Comment: Thanks!! This seriously helped me ^_^
Answer: Regarding the push notification settings, after the changes to Back4App's site, it's located by following these steps:
After Login in your Back4App Account, click on "Features" below your AppName. Then you'll search for "Android Push notification" and click on "Server".
That should bring up the Push Notification settings for Android.
Checking the Online Chat is a great idea too, seems very useful.


Is this a possible attack on database?

Question: In the logs (Drupal 7), I have seen the next entry (I have edited some compromised info). It seems a failed (only I hope it actually failed) attempt to access the login account. I have tried to replicate the error, but cannot have the same error entry with failed login/password, so I am very worried that it originated in some possible breach of Drupal 7 security.
<code>PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
'Crap' AND status = 1' at line 1: SELECT * FROM {users} WHERE name = :name_0, :name_1 AND status = 1; Array ( [:name_0] => FcUk
 [:name_1] => Crap )
in user_login_authenticate_validate() (line xxxx of /[HOME_ROOT]/[PUBLIC_HTML_PATH]modules/user/user.module).
</code>
Comment: Please see https://www.drupal.org/drupalsa05FAQ#comment-9255523
Comment: Appears this is an attempt of no good - https://www.drupal.org/node/2403335
Comment: Yes, thanks for the link. The problem is that it is a PDO database exception, when all attemps of injection should stop at Drupal interface level and send another type of error (failed login). This is extremely serious and embarrasing for Drupal, is it possible that we will live another breach of security as when 7.34, where hundreds of thousends of sites were possibly comprosimed?
Answer: I asked a member of the Drupal security team about this and he referred me to https://www.drupal.org/drupalsa05FAQ#comment-9255523.
This points to a user attempting to exploit SA CORE 2014 005, but failing due to the site being patched. Cesar's attempt to reproduce triggers the PDOException, but does not (and cannot) result in actual SQL injection.
Comment: Also this was fixed in https://www.drupal.org/node/2380053 which was included in 7.36.
Answer: There is indeed a very serious vulnerability in 7.35. Strongly recommended to upgrade. The hack attempt can be reproduced by using Chrome navigator, F12 and inspect element on the field name of the Drupal web login page. We copy the line of the input name, we set the name of the HTML elements to name[0] and name[1], respectively, and with any value filled, we submit. Potentially extremely serious and a shame of biblical proportions that this bug survived until 2015.
Comment: The SQL injection problem was patched in https://www.drupal.org/SA-CORE-2014-005 / Drupal 7.32, which was 15 October 2014.  None of other other security releases since then (I'm counting five) have had to do with SQL injection.  If you think you have found a legitimate security problem, please escalate to https://www.drupal.org/security-team/report-issue

Is this a possible attack on database?


Linux Ubuntu - Two NICs separate lan

Question: I have this /etc/network/interfaces (IPs on eth1 are fake)
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 10.0.2.15
netmask 255.255.255.0
broadcast 10.0.2.255
gateway 10.0.2.2

auto eth1
iface eth1 inet static
address 18.104.22.168
netmask 255.255.255.0
broadcast 184.108.40.206
gateway 22.214.171.124

I use eth0 to connect to the internet while on eth1 I configured a public IP to a web server.
The connection to internet works fine if i keep up only eth0 and to the other side the web server works fine too if i keep up only eth1. They work perfectly as intended.
The problem is that I want both networks on at the same time and use exclusively eth0 to surf the internet / download updates and so on and I want to route all the traffic incoming to 18.104.22.168 to just that network.
How can I do that? I searched many tutorials but can't find a working solution or maybe I am doing something wrong. I do not want to reroute traffic from one interface to another, I would like to keep them separate and reroute traffic based on what IP they are coming from.
Is this possible?
I already tried
route add -host 18.104.22.168 dev eth1

Thank you in advance.
Comment: I wrote 2 gateways because atm I am working disabling either one or another interface whenever I need to run an apt-get update or so. Most of the time eth0 is shut and the webserver is working fine. What I want is:
every traffic from and to 18.104.22.168 must go through eth1 (and therefore throught 126.96.36.199)
every traffic from and to the internet and my machine EXCEPT the ones on 184.108.40.206 network must flow through eth0. Is this possible?
Answer: Your immediate problem is that you declare a default gateway on both entries. I suppose that this will result in whichever comes up last to "win" and be default gateway.
However, if you remove the one on eth1, you will have the problem that the box will reply on eth0, even if the packet arrived on eth1. In order to tell the box to reply on a particular interface, you need to do what is commonly referred to as source routing.
I have the following set of commands on a box:
/sbin/ip rule add from 220.127.116.11/24 tab 1 priority 500
/sbin/ip route add default via 220.127.116.11 dev eth2 tab 1
/sbin/ip route flush cache

The first line tells the box to look in table "1" for info on packets that go out from IP 18.104.22.168. The second line creates table "1" saying that the default gateway in that table is 18.104.22.168. The last line ensures that this takes effect immediately.
For more info, see e.g. http://lartc.org/howto/lartc.rpdb.html
Comment: I try this solution and let you know. It seems easy.
Comment: I removed the last gateway from config and run those commands in sequence

`
/sbin/ip rule add from 126.96.36.199/24 tab 1 priority 500
/sbin/ip route add default via 18.104.22.168 dev eth1 tab 1
/sbin/ip route flush cache
`

but nothing works
Comment: Not sure what the effect will be if you name the whole subnet in the rule. I think you want /sbin/ip rule add from 123.123.123.*45*/24 tab 1 priority 500
Answer: Having two default gateways with the same metric results in a lottery for which one will be used. This explains your problems.
You can either follow the advice from Bittrance or make sure that your two default routes have different metrics. In that case the one with the smaller metric will be used unless the route is down. However, this only works if the second default gateway actually DOES provide a route to the public Internet.
In order to set up two default routes with different metrics, use the metric keyword in the ip route add command.
I personally would remove the gateway instructions from the interfaces file and rather add post-up commands.
EDIT
Based on your additional comment, I am a little confused as to what exactly you want to achieve and how this network is set up.
Clearly the interface with the public IP must be connected directly to the Internet (presumably through a device provided by your ISP). If this server is also your default gateway to the Internet, i.e. all requests for public IP address must flow through this server, then the server must be configured as a router (i.e. IP forwarding must be enabled, and all other devices on the network must have the private IP of this server as their default gateway).
If your network has another computer which provides the default internet access, then that device must be set as the default gateway on all other network devices, and your server should not have a default route at all on its internal interface (eth0), since it is directly connected to that network.
Comment: Public interface 188.8.131.52--[SERVER]--10.0.2.15 Private interface.

The box is a VirtualBox Ubuntu in which the 1st interface eth0 is natted to the main server and used to surf the internet freely. It's on a private network.

The second one is bridged to a public interface directly connected to the internet without natting, behind a firewall.

What I ask is to keep networks separate. The traffic from and to 188.8.131.52 must flow through eth1. Everything else should go to eth0. The default gateway so should be the one on eth0.
Comment: You could try source based routing, but that has gone out of fashion a long time ago. Nowadays IP routing is primarily destination based, and in your case it simply doesn't make any sense to route your "normal" internet traffic through a different gateway than the traffic coming in through a specific public IP.
Comment: http://wiki.openvz.org/Source_based_routing Tried this too. No ways of making it work. I think I'll keep enabling and disabling the eth.
Answer: You can not have two default gateways. Choose either one.
If you are looking to use two ISP's simultanously then you need BGP.
Answer: Could this answer to another question also lead to your answer?

Setting up two NICs on two separate LANs provides error

Linux Ubuntu - Two NICs separate lan


Hierarchy view not being respected - UI Route (Ionic)

Question: I am working on an Ionic app and I have implemented an on-boarding screen with 3 slides, some text, and  tag to go directly to the start screen.
Now I have noticed that when I hit the  tag I am redirected to the correct view but the nav bar on top has a back button where there should be a hamburger menu icon.
Not sure if I am implementing the routing system right. What is the right why to use routing and respect the hierarchical view?

Html code (on-boarding):
<ion-view view-title="WNRS" hide-nav-bar="true">
  <ion-content scroll="false" has-header="true" class="has-header">
      <ion-slide-box on-slide-changed="slideChanged(index)">
          <ion-slide>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque semper, sapien ac hendrerit porttitor, ipsum ante ultrices ipsum, eu congue arcu libero id enim.

Play

          </ion-slide>
          <ion-slide>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque semper, sapien ac hendrerit porttitor, ipsum ante ultrices ipsum, eu congue arcu libero id enim.

Play

          </ion-slide>
          <ion-slide>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque semper, sapien ac hendrerit porttitor, ipsum ante ultrices ipsum, eu congue arcu libero id enim.

Play

          </ion-slide>
      </ion-slide-box>
  </ion-content>
</ion-view>

Part of the app.js code (routing part):
// Routes
app.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider

  .state('app', {
    cache: false,
    url: '/app',
    abstract: true,
    templateUrl: 'components/sidebar_menu/menu.html'
  })

  .state('app.walkthrough', {
    url: '/walkthrough',
    views: {
       'menuContent': {
          templateUrl: 'views/walkthrough/walkthrough.html',
          controller: 'WalkthroughCtrl'
        }
      }
  })

  .state('app.base1', {
    url: '/base1',
    views: {
       'menuContent': {
          templateUrl: 'views/base1/base1.html',
          controller: 'Base1Ctrl'
        }
      }
  })

  .state('app.base2', {
    url: '/base2',
    views: {
       'menuContent': {
          templateUrl: 'views/base2/base2.html',
          controller: 'Base2Ctrl'
        }
      }
  })

  .state('app.base3', {
    url: '/base3',
    views: {
       'menuContent': {
          templateUrl: 'views/base3/base3.html',
          controller: 'Base3Ctrl'
        }
      }
  })

  .state('app.add_question', {
    url: '/add_question',
    views: {
      'menuContent': {
        templateUrl: 'views/add_question/add_question.html',
        controller: 'AddQuestionCtrl'
      }
    }
  })

  $urlRouterProvider.otherwise('/app/walkthrough');
});

Answer: Two Choices: 1. Make the walkthrough page the parent, and base1, base2, base3 should be child page. But even in this way, if you switch from base1 to base2, you will still see the "back" button on base2 page.
Or you can simply customize the ion-nav-bar in base1, base2, base3 like this:
<ion-view>
  <ion-nav-bar>
    <ion-nav-buttons side="left">
      <button class="button your-hambuger" menu-toggle="left">
      </button>
    </ion-nav-buttons>
    <ion-nav-title>
        Base1
    </ion-nav-title>
  </ion-nav-bar>
  <ion-content>
    Some content
  </ion-content>
</ion-view>

Update: if you want to disable back button on base1 for example, you can add below code to your base1 controller:
.controller('Base1Ctrl', ['$scope', function ($scope) {
    //add below code to disable back button
    $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
        viewData.enableBack = false;
    });
}])

Update2: if you want to do some custimization on the nav bar. I think choice 2 is the only option. First go to your menu.html and remove ion-nav-bar part. Copy this part to the pages where you want to show ion-nav-bar with a hamburger icon.  For those pages you want to show back button, you can add ion-header-bar code to that page:
<ion-view view-title="Base2">
  <ion-header-bar class="bar-stable" id="nav-bar">
    <button ng-click="goState()" class="button back-button buttons button-clear header-item">

      Base1
    </button>

Base2

    <button ng-click="goState2()" class="button back-button buttons button-clear header-item">
      Base3

    </button>
  </ion-header-bar>
  <ion-content>
     Base2 content
  </ion-content>
</ion-view>

You can add the goState() function in base2 controller or just give an ui-sref to that button
Comment: i just wanted to test option 2 out of curiosity. and then i don' see a nav bar only the title. More interested in option 1. So i should delete the app route which is now the parent correct?
Comment: You can see the title, that means there is a bar, maybe the background is white...  For 1st choice, I still don't think you need to mess up the state. You can try to disable the back button before entering base123 page
Comment: Updated answer showing how to disable back button when switching state
Comment: mmm, i dont really want to disable back button because i need it i just want it to say back instead of base 1, base 2 or base 3. see this link -> https://gyazo.com/d721f22ae71e1a81727b01b133d3b681 This is when i am in view base 2 normally it should say back but instead is says base 1
Comment: In my view base 1 there is an ion-slide-box consisting of 12 slides on the last slide a button shows that enables the user to go to view 2 (base 2). in my controller of base 1, i have this bit of code for linking to view 2: $scope.goToBase2 = function () {
        $rootScope.setGameBase(2);
        $rootScope.setGameLevel(0);
        $state.go('app.base2');
    };
Comment: So you want back button and hamburger icon on base2 at the same time?
Comment: mmmm, your update to explanation is not really working for me. if i implement the nav bar in the pages where i want a back button then it will do that but the title will not show.
Comment: Just update the answer with full customized header bar example
Comment: The ion-nav-bar in menu.html acts like a global header bar. If you want different nav-bar in different pages, you need to delete this global bar and create specific ones.


Zen subtheme region templates not being used?

Question: In a subtheme of Zen, I've got a templates folder that has region.tpl.php and region--footer.tpl.php that are copied from the main Zen theme. However, the custom region file is not being used for the regions of my theme; I even changed the contents of the region--footer.tpl.php file to just be <?php exit("Hi!"); to see if it's being called at all, and it appears to not be.
I've cleared the theme cache (it's set to clear every page load); what am I missing to get that custom region template to actually apply?
Answer: A few things to check on that might be causing your error:

Is the footer region populated with a box or content? If no, the region won't show.
Have you edited the region--footer.tpl.php of the main Zen theme or your subtheme? Editing the wrong one won't show the result.
Is the footer properly actived (not commented) in your subthemes's .info file? (regions[footer] = Footer)
Comment: Thank you, Apex; indeed I didn't have anything in my footer region. For one other custom area, it looks like my issue was that the name of the region had a hyphen in the name, which Zen/Drupal doesn't like. Changing the machine_name of the region to have an underscore instead (and change the custom region template's name) made it start applying.
Comment: You're most welcome ^^
Comment: Upvote? Could use the extra features on this exchange ;)


Add multiple collection objects values for equal keys

Question: I have multiple objects in a collection instance having same keys but different values. I need a way to add quantity field key values in the same objects.
[
    0 => {
      +"product_id": 1
      +"quantity": "50"
      +"price": "25.00"
    },
    1 => {
      +"product_id": 3
      +"quantity": "50"
      +"price": "75.00"
    },
    2 => {
      +"product_id": 2
      +"quantity": "50"
      +"price": "50.00"
    },
    3 => {
      +"product_id": 3
      +"quantity": "50"
      +"price": "75.00"
    }
]

Resulting Instance should have the quantities added in the same item keys as follows.
[
    0 => {
      +"product_id": 1
      +"quantity": "50"
      +"price": "25.00"
    },
    1 => {
      +"product_id": 2
      +"quantity": "50"
      +"price": "50.00"
    }
    2 => {
      +"product_id": 3
      +"quantity": "100"
      +"price": "75.00"
    }
]

I have tried to iterate through all the objects and add/edit object as follows. I'm not sure whether this is the best practice way in a Laravel collection.
$newItems = [];

$items->each(function ($item, $key) use ($newItems) {
    $existId = array_column($newItems, 'id');
    if($existId){
        // add quantity to the existing item
    } else {
        // push item to items array
    }
});

Comment: Just a little sidenote: It seems like in your last code block you use `$items` for what should be 2 different variables and because of it you'll get the error that `each` doesn't exist on an array.
Comment: It appears again in `use ($items)` and `array_column($items` ;)
Comment: @camille are your problem solve ?
Comment: @RobinDeSchepper sorry, It was a typo
Answer: You can use the collection method reduce to create a new collection where you either add items that aren't in the new collection yet, or sum up their quantities:
$total = $items->reduce(
  // The function that will insert or add the items together.
  function ($carry, $item) {
    if ($carry->has($item->product_id)) {
      $carry[$item->product_id]->quantity += $item->quantity;
    } else {
      $carry[$item->product_id] = $item;
    }
    return $carry;
  },
  // The initial empty collection that will be filled up every iteration.
  collect([])
);


Cron job not running on specified time

Question: I've a cron job that should run every day at 1700 hours from Saturday to Sunday. However, it runs on the system at 0100 hours instead.
The schedule descriptor string used to define the table for this particular job in question is: 0 17 * * 0-6
The system on which this crontab exists is CentOS 5.2 with ISC Cron V4.1 running on it. I did, recently, change the timezone on the system from PDT to BST by creating a symbolic link at /etc/localtime pointing to /usr/share/zoneinfo/GB. However, I do not believe that to have caused this problem as I remember the cron job running at 0100 hours before.
Any insights? I'd appreciate any help I could get on this. Thank you.
Comment: possible duplicate of https://serverfault.com/questions/214234/crontab-not-running-at-specific-time-but-runs-every-min/1006318#1006318
Answer: Crond is likely still in the old timezone, restart it (from a shell with the right timezone) to pick up the new TZ variable.
Comment: You really should not change timezones on a running system without rebooting the system.
Comment: "However, I do not believe that to have caused this problem as I remember the cron job running at 0100 hours before".  Right, because it was running it at 1700PDT.  And it probably still is.

Cron job not running on specified time


Cremona SV-1220 missing sound post?

Question: I purchased a Cremona SV-1220 violin today at a yard sale. It didn't have any strings on it. I purchased some at a local guitar shop that had some in stock. I was watching a video on the internet about how to string the violin. It mentioned not to take off all the strings at once because the sound post could come lose and that would require a repair by a professional.
I don't see a sound post in this violin. Do all violins have a sound post? If so I guess it is gone. It does look to me however that there is a support on the left side. Perhaps this model does not use a sound post?
Answer: Yes, all violins have a sound post.  It is positioned under the right foot of the bridge.  There's also a reinforcing strip of wood called the Bass Bar glued under the left foot.   This won't fall off if there's no string tension pushing  the bridge down, but the sound post very likely will.  And it seems yours has.
It's only a glorified bit of dowel.  Supplying and fitting a replacement is a skilled job, but not a big one. It will probably cost about the same as the set of strings you bought.

Cremona SV-1220 missing sound post?


Markov Chains: Enlarge State Space & Long-time Probability

Question: I can't figure out how to solve this. I've looked at many examples to help, but nothing seems to.
Let S and C denote a Sunny day and a Cloudy day, respectively. Suppose that the weather on the given day depends on the past weather only through the weather on the two immediately preceding days according to the following conditional probabilities: The probability that a day is sunny given that the immediately preceding two days were sunny is P(S|S,S) = .8. The probability that a day is sunny given that the immediately preceding day was sunny and the day before was cloudy is P(S|C,S) = .6.The probability that a day is sunny given that the immediately preceding day was cloudy and the day before was sunny is P(S|S,C) = .4. Similarly, P(S|C,C) = .1, P=(C|S,S) =.2, P(C|C,S) = .4, P(C|S,C) = .6, P(C|C,C) = .9. Let n = 0 denote the initial day (day 0), let n = 1 denote the 1st day, and so on. We also know the following two initial probabilities: Prob(the initial day is cloudy, the first day is sunny) = .1 and Prob (the initial day is cloudy, the first day is cloudy) = .9.
a.) What is the probability that the second and third day will be cloudy? b.) What is the probability that the third day will be cloudy? c.) What is the long-term probability that a day will be cloudy?
Update
$$
        \begin{matrix}
 &(S,S)& (S,C) &(C,S) & (C,C)\\
   (S,S)&    .8 & .2 & 0 & 0 \\
    (S,C)&     0 & 0 & .4 & .6 \\
    (C,S)&   .6 & .4 & 0 & 0 \\
       (C,C)& 0 & 0 & .1 & .9 \\
        \end{matrix}
$$
Comment: Hint: The question defines a four-state Markov chain on the states $\{(S,S), (S,C), (C,S), (C,C)\}$.  For instance, "$P(S|C,S)=0.6$" means the chance of a transition from $(C,S)$ to $(S,S)$ is $0.6$.
Comment: Yes, it does make sense--but it required you to explain it. Anyway, "$\Pr(R_3=C,R_2=C,R_1=j_1,R_0=j_0)$" would refer to a *two-step* transition. The first step would go from $(j_1,j_0)$ on day $1$ to $(C,j_1)$ on day $2$. The second step would go from $(C,j_1)$ to $(C,C)$ on day $3$. The idea is that one transition still occurs each day, but the *states* record the information from the *past two days,* not just the immediately previous day. Note this means that some transitions cannot occur directly, such as $(C,C)\to (S,S)$. That's why your matrix has eight zeros in it.
Comment: I have the transition matrix.
  SS SC CS CC
SS.8 .2  0  0
SC 0  0 .4 .6
CS.6 .4  0  0
CC 0  0 .1 .9

I'm having problems setting up Prob(R2=C, R3=C). Can I take the summation over j in [C,S] of Prob(R3=C, R2=C, R1=j1, R0=j0).

By doing this I get .753 for the first answer. Is this correct?
Comment: What do you mean by "R3", "R2", "R1", "R0", "j1", and "j0"?
Comment: R3= third day, R2=second day,..., j1 will be either {C or S} for R1, and j0 will be either {C or S} for R0. Does that make sense?
Comment: Is finding the stated probability above the right set-up to solve Prob(R2=C, R3=C)?
Answer: I solved a similar question when i was a student and found this article  helpful both to build a general understanding of Markov processes and as a reference for practical applications of the concept. A method that will should solve the problem you outlined is described on page 3, also consider looking at questions 52-61 in the book to test understanding (answers provided in the appendix).
Comment: This is very helpful. We did not learn the tree method in class, so I found this extremely useful. Thank you!

I just have another question. When I'm looking to find the long-run to be cloudy, I sent my matrix to a high power. The results is [3/11 1/1 1/11 6/11] in each row. Each column is represented by (S,S) (S,c) (C,S) (C,C). Do I consider only the (C,C) result or (C,C) + (S,C) for the longrun being cloudy?
Comment: By sending the matrix to higher powers you will most likely find the long-run probabilities or, at least, a close approximation of them. However, if you want to arrive at the exact distribution, you will have to solve it analytically. Here is how: [steady-state calculation](https://www.youtube.com/watch?v=cP3c2PJ4UHg). If you only consider the (C,C) you will "only" find the long run probability of a cloudy day following a cloudy day, so, taking the probability of a cloudy day following a sunny day (S,C) into account as well will do the trick.