TextBox within DataTemplate, on GotFocus cannot assign SelectionStart?

Question: I have a logic with my textbox which says, on focus move the selection start to the last character, so that the editing person can just continue writing.
This worked perfectly with this:
    private void TextBox_GotFocus(object sender, EventArgs e)
    {
        var textBox = sender as TextBox;
        if (textBox == null) return;

        textBox.SelectionStart = textBox.Text.Length;
    }

and

and
<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <TextBox Name="SomeTextBox" Text="{Binding Path=Pressure, UpdateSourceTrigger=PropertyChanged}" Padding="2,0,0,0" />
        <DataTemplate.Triggers>
            <Trigger SourceName="SomeTextBox" Property="IsVisible" Value="True">
                <Setter TargetName="SomeTextBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=SomeTextBox}"/>
            </Trigger>
        </DataTemplate.Triggers>
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

but when I moved this to:
<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <ContentControl Content="{Binding Path=Pressure, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ContentTemplate="{StaticResource DataGridTextBoxEdit}" />
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

and a reusable template:
    <DataTemplate x:Key="DataGridTextBoxEdit">
        <TextBox Name="TextBox" Text="{Binding Content, RelativeSource={RelativeSource AncestorType=ContentControl}}" Padding="2,0,0,0" />
        <DataTemplate.Triggers>
            <Trigger SourceName="TextBox" Property="IsVisible" Value="True">
                <Setter TargetName="TextBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=TextBox}"/>
            </Trigger>
        </DataTemplate.Triggers>
    </DataTemplate>

it just stopped working. The GotFocus event fires off, however I simply cannot assign anything to SelectionStart, it just doesn't save it. Tried even hardcoding:
    private void TextBox_GotFocus(object sender, EventArgs e)
    {
        var textBox = sender as TextBox;
        if (textBox == null) return;

        textBox.SelectionStart = 5;
    }

but didn't work. It's also worth to note that Text is empty, only DataContext is filled at this point, however as the SelectionStart is not taking anything (saving), it's no good to me.
What am I doing wrong?
Kind regards,
Vladan
Answer: At the point where the TextBox gets focus it does not have any text yet, this means the handler fires before the DataGrid assigns the value. One way to get arround this is to check for the first text change and then do the selection change, e.g.
private void TextBox_GotFocus(object sender, EventArgs e)
{
    var textBox = sender as TextBox;
    if (textBox == null) return;

    var desc = DependencyPropertyDescriptor.FromProperty(TextBox.TextProperty, typeof(TextBox));
    EventHandler handler = null;
    handler = new EventHandler((s, _) =>
        {
            desc.RemoveValueChanged(textBox, handler);
            textBox.SelectionStart = textBox.Text.Length;
        });
    desc.AddValueChanged(textBox, handler);
}

(This code may not be very clean, use at own risk)


String variable sends null to httppost

Question: String sends null to httppost even though has value in it. I already looked up on the internet but I still wasn´t able to find the solution.
This is how I get the data
            tr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerForContextMenu(tr);
                openContextMenu(tr);
                TableRow t = (TableRow) v;
                firstTextView = (TextView) t.getChildAt(2);
                secondTextView = (TextView) t.getChildAt(4);
                thirdTextView = (TextView) t.getChildAt(5);
                fourthTextView = (TextView) t.getChildAt(7);

                strProgram = firstTextView.getText().toString();
                strShour = secondTextView.getText().toString();
                strEhour = thirdTextView.getText().toString();
                strStatus = fourthTextView.getText().toString();
                System.out.println(strProgram+" "+strShour+" "+strEhour+" "+strStatus);

            }
        });

And this is the method of httppost
public void cancelClass() {
    try{
        String p = firstTextView.getText().toString();
        String s = secondTextView.getText().toString();
        String e = thirdTextView.getText().toString();
        System.out.println(p+" "+s+" "+e+" ");

        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://192.168.1.105/my_folder_inside_htdocs/cancelClass.php"); // make sure the url is correct.
        //add your data
        nameValuePairs = new ArrayList<NameValuePair>();
        // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
        nameValuePairs.add(new BasicNameValuePair("strProgram",p));
        nameValuePairs.add(new BasicNameValuePair("strShour",s));
        nameValuePairs.add(new BasicNameValuePair("strEhour",e));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        //Execute HTTP Post Request
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String response = httpclient.execute(httppost, responseHandler);
        System.out.println("Response : " + response);

        if(response.equalsIgnoreCase("No Such Timetable")){
            Toast.makeText(getApplicationContext(),"Database problem", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(getApplicationContext(),"Timetable found", Toast.LENGTH_SHORT).show();
        }

    }catch(Exception e){
        System.out.println("Exception : " + e.getMessage());
    }
}

And this is my php file
mysql_select_db($database_localhost, $localhost);

$program = $_POST['strProgram'];
$startHour = $_POST['strShour'];
$endHour = $_POST['strEhour'];
$query_search = "select * from diptimetable where program = '".$program."' AND startHours = '".$startHour."' AND endHours = '".$endHour."'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec) and mysql_fetch_assoc($query_exec) ;
//echo $rows;
 if($rows == 0) {
 echo "No Such Timetable";
 }
 else  {
    echo "Timetable found";
}
mysql_close();

And this is my logcat
02-17 23:25:00.883  25644-25644/com.eztimetable I/System.out﹕ DIP6A 11:00 AM 12:00 PM Have class
02-17 23:25:00.883  25644-25644/com.eztimetable I/System.out﹕ DIP6A 11:00 AM 12:00 PM
02-17 23:25:00.883  25644-25644/com.eztimetable I/System.out﹕ Exception : null

As you can see in the LogCat , the String variable has value in it, but it still sends null to nameValuePairs. I don't know where my mistake is. If someone can help me, I am very grateful. Thank you very much for your help. Sorry for the bad English.
okay this is my updated logcat
and i already find the solution
02-17 23:57:10.493  27161-27161/com.eztimetable W/System.err﹕ android.os.NetworkOnMainThreadException
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:112)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at java.net.Socket.connect(Socket.java:843)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:653)
02-17 23:57:10.513  27161-27161/com.eztimetable W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at com.eztimetable.LecturerTimetable$3.run(LecturerTimetable.java:330)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.app.Activity.runOnUiThread(Activity.java:4893)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at com.eztimetable.LecturerTimetable.cancelClass(LecturerTimetable.java:311)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at com.eztimetable.LecturerTimetable.onContextItemSelected(LecturerTimetable.java:293)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.app.Activity.onMenuItemSelected(Activity.java:2693)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:350)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.support.v7.app.ActionBarActivity.onMenuItemSelected(ActionBarActivity.java:155)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3894)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:983)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.widget.AdapterView.performItemClick(AdapterView.java:299)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.widget.AbsListView.performItemClick(AbsListView.java:1158)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.widget.AbsListView$PerformClick.run(AbsListView.java:2949)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.widget.AbsListView$3.run(AbsListView.java:3683)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.os.Looper.loop(Looper.java:149)
02-17 23:57:10.523  27161-27161/com.eztimetable W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5257)
02-17 23:57:10.533  27161-27161/com.eztimetable W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
02-17 23:57:10.533  27161-27161/com.eztimetable W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
02-17 23:57:10.533  27161-27161/com.eztimetable W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-17 23:57:10.533  27161-27161/com.eztimetable W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
02-17 23:57:10.533  27161-27161/com.eztimetable W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)

Comment: Which sting variable? You have so many.
Comment: `String variable sends null` how do you know that?
Comment: at the logcat @njzk2
Answer: Cannot see much wrong in your code but instead of writing e.getMessage() into LogCat :
} catch (Exception e) {
    System.out.println("Exception : " + e.getMessage());
}

You might get more meaningful trace if use :
} catch (Exception e) {
    e.printStackTrace();
}

Comment: OMG.. i never thought of this lol.. Thx man I found the solution in here when see the log .. [link](http://stackoverflow.com/questions/25093546/android-os-networkonmainthreadexception-at-android-os-strictmodeandroidblockgua)

String variable sends null to httppost


Prove that $A+I$ is invertible if $A$ is nilpotent

Question:
Possible Duplicate:
Units and Nilpotents

Given $A^{2012}=0$ prove that $A+I$ is invertible and find an expression for $(A+I)^{-1}$ in terms of $A$. ($I$ is the identity matrix).
Comment: @ugoolm If you are asking for help with your MATH 1115 assignment due this monday, you should provide a bit more context and where you are stuck.
Comment: On the other hand, if I + A not invertible there is a v so that $0 = (I + A) v$, so $Av = -v, A^{2012}v = v, $ A not nilpotent.
Comment: I think it would be sufficient with a hint like "Do you remember the proof of the geometric formula?".
Comment: Please don't do this. There's nothing wrong with a closed question while an impenetrable non-question has no value whatsoever.
Comment: Special case of the [method of simpler multiples](https://math.stackexchange.com/a/3224776/242), namely $$\color{#c00}{A^n = 0}\ \Rightarrow\ \dfrac{1}{A-c}\, =\, \dfrac{A^{n-1}+\cdots + c^{n-1}}{\color{#c00}{A^n}-c^n}\, =\, -c^{-n}(A^{n-1}+\cdots + c^{n-1})$$
Answer: You can easily prove that if $A^n=0$:
$$\left(A+I\right)\left(I-A+A^2-...+(-1)^n A^{n-1}\right) = I +(-1)^{n-1} A^n = I$$
Thus proving that $A+I$ is invertible for any nilpotent $A$.
Comment: Maybe you should add that $n=2012$, otherwise it seems that $A^n=0$ for every $n>1$.
Comment: I think you meant $(-1)^{\mathbf{n-1}} A^{n-1}$ in your second bracket.
Comment: @Siminore - fixed, thanks!
Comment: Special case of the [method of simpler multiples](https://math.stackexchange.com/a/3224776/242), namely $$\color{#c00}{A^n = 0}\ \Rightarrow\ \dfrac{1}{A-c}\, =\, \dfrac{A^{n-1}+\cdots + c^{n-1}}{\color{#c00}{A^n}-c^n}\, =\, -c^{-n}(A^{n-1}+\cdots + c^{n-1})$$
Answer: More generally: A (square) matrix $A$ is invertible if and only if $\lambda=0$ is not an eigenvalue.
Independently of this, we have that if $\lambda$ is an eigenvalue of $A$, then $\lambda+\mu$ is an eigenvalue of $A+\mu I$: if $\mathbf{x}$ is an eigenvector of $A$ corresponding $\lambda$, then $(A+\mu I)\mathbf{x} = A\mathbf{x}+\mu I\mathbf{x} = \lambda\mathbf{x}+\mu\mathbf{x} = (\lambda+\mu)\mathbf{x}$.
Also independently of all of this, if $\lambda$ is an eigenvalue of $A$, then $\lambda^n$ is an eigenvalue of $A^n$. (Careful, though, this one is not reversible: a rotation of $90^{\circ}$ of the plane has no eigenvalues over $\mathbb{R}$, but its square has eigenvalue $-1$. The square of the identity has $(-1)^2$ as an eigenvalue, but the identity does not have $-1$ as an eigenvalue).
So:
$$\begin{align*}
A+I\text{ is invertible}&\iff 0\text{ is not an eigenvalue of }A+I\\
&\iff -1\text{ is not an eigenvalue of }A.
\end{align*}$$
And if $A^n=0$ for some $n\gt 0$, then $-1$ is not an eigenvalue of $A$.
Comment: @CloudJR: I already did: if $\lambda$ is an eigenvalues of $A$, then $\lambda^n$ is an eigenvalue of $A^n$. What are the eigenvalues of the zero matrix?
Comment: the statements of this answer hold whenever $\operatorname{rank} A=\infty$?
Comment: Please explain the last step $A^=0$ then -1 is not an eigenvalue
Comment: @ arturo Magidin got it .thanks
Answer: Hint: the series $\sum_{j=0}^{+\infty}(-1)^jA^j$ has only finitely many terms. In fact, it works it there is a positive integer $p$ such that $A^p=0$.
Answer: A matrix $A$ is nilpotent if and only if all its eigenvalues are zero. It is not hard also to see that the eigenvalues of $A+I$ will all be equal to $1$ (when we add $I$ to any matrix, we just shift its spectrum by 1). Thus $A+I$ is invertible,
since all its eigenvalues are non-zero.
Comment: You want to be careful: you can have a matrix for which all eigenvalues are $0$, but the matrix is not nilpotent (because it doesn't have "enough" eigenvalues); e.g., the $3\times 3$ matrix over $\mathbb{R}$ given by $$\left(\begin{array}{rrr}0 & -1 & 0\\1 & 0 & 0\\0 & 0 & 0\end{array}\right).$$ The characteristic polynomial is $t(t^2+1)$, so the only (real) eigenvalue is $0$, but the matrix is not nilpotent. So it depends on how you interpret "all its eigenvalues" (true if that means "in an algebraic closure of the ground field").
Comment: @ArturoMagidin: Agreed. I was thinking about the algebraic closure.


How to be with identical in content classes using by Realm

Question: I need to create many identical in content classes like the class below
public abstract class AbstractListModel  extends RealmObject {
@PrimaryKey
private String id;
private String name;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

If I will extend this class in another, it seems I'll have a lot of empty classes, 'cause they have only 2 fields (id and name) wich contains in the mother-class.
public class LectureHallListModel extends AbstractListModel {
//@PrimaryKey
//private String id;
//private String name;

//public String getId() {
//    return id;
//}

//public void setId(String id) {
//    this.id = id;
//}

//public String getName() {
//    return name;
//}

//public void setName(String name) {
//    this.name = name;
//}
}

Are the any way to add to a DB several identical in content tables without creation empty classes?Thank you!
Answer: Inheritance of fields (technically from any class that is not directly RealmObject) is not supported by Realm.
You would need the following setup:
public interface AbstractListModel {
    String getId();
    void setId(String id);
    String getName();
    void setName(String name);
}

And
public class LectureHallListModel extends RealmObject implements AbstractListModel {
    @PrimaryKey
    private String id;
    private String name;

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }
}

Comment: Its sad. Thank you very much
Comment: Thank you. But anyway, as I understood I should create many identical classes for the diferrent data-models (tables in future). Can I create only one model and do something with it to create many tables?
Comment: `Can I create only one model and do something with it to create many tables?` no


How to find the coefficient of $x^8$ in the following:

Question: I need to find the coefficient of $x^8$ in the following using generating functions:
$$\frac{(1+x)^2}{1-3x} $$
I attempted to write out three different generating functions adding together to give the numerator with a common denominator of $1-3x$. But this has led me no where. Any hints would be appreciated, even in the general way.
Answer: Use the geometric series to expand the denominator (assuming $|x|<\frac13$) and then multiply with $(1+x)^2$. More specifically $$\begin{align*}\frac{(1+x)^2}{1-3x}&=(x^2+2x+1)\cdot\frac{1}{1-3x}=(x^2+2x+1)\sum_{n=0}^{\infty}(3x)^n=\\&=(x^2+2x+1)\left(1+3x+(3x)^2+\ldots+(3x)^6+(3x)^7+(3x)^8+\ldots\right)=\\&=\ldots+x^2\cdot(3x)^6+2x\cdot(3x)^7+(3x)^8+\ldots=\\&=\left(3^6+2\cdot3^7+3^8\right)x^8+\ldots\end{align*}$$ where in the last equations I wrote only the terms concerning $x^8$. So the requested coefficient is equal to $$3^6+2\cdot3^7+3^8$$ assuming $|x|<\frac13$.
Comment: @Frumpy You are welcome! Do not worry, earlier today, I could not solve a probability exercise that someone else solved with a very nice way, so today I feel pretty stupid too...
Comment: Ahh, how simple that was; yet I could not think of that on my own. Makes me feel pretty stupid. Thank you.
Answer: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left( #1 \right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
\begin{align}
\mbox{With}\ \verts{x} < {1 \over 3}\,;\qquad{\pars{1 + x}^{2} \over 1 - 3x}&=
\pars{1 + 2x + x^{2}}\sum_{n = 0}^{\infty}\pars{3x}^{n}
=\sum_{n = 0}^{\infty}\bracks{3^{n}x^{n} + 2\times 3^{n}x^{n + 1}
+ 3^{n}x^{n + 2}}
\end{align}

Solution:
  $$
3^{8} + 2\times 3^{7} + 3^{6} = 3^{6}\times 16 = \color{#00f}{\Large 11664}
$$


Azure routing through point-to-site then site-to-site

Question: I did have a good hunt around for a similar post but couldn't find the same scenario.  I am trying to connect to a 3rd party URL from an on-prem machine, through Azure.  So:
on-prem -> (point-to-site) -> Azure VPN Gateway -> (site-to-site) -> 3rd party URL

Point to site address space: 172.16.0.0/24
Azure vnet address space: 10.3.0.0/16
3rd party address space: 10.100.0.0/16

I have put a VM in the Azure network as a middleman for testing, and I can connect from on-prem to the VM, and from the VM to the 3rd party site, however for some reason I can't get all the way through.  The weirdest part is that the 3rd party IP resolves correctly from the hostname, I just can't connect to the URL (it's HTTPS/443 if that matters).  If I run a tracert from on-prem I can see that 'tracert VM' first hop goes straight to the VPN gateway, however 'tracert 3rdparty' goes to my router->isp->fail, so it seems my routing is messed up somehow.
I would have thought this would be pretty standard routing for the VPN gateway, but hopefully there's a way to make this work as it's vital to the project I'm working on.  I'm happy to try custom routes, or whatever it takes. Appreciate any suggestions.
Comment: I'm pretty sure the routing is not automatic with the VPN gateways, so you may need to actually build a router in Azure and have that forward the packets.
Answer: Thanks for the replies.  After playing around a bit and some help from Microsoft support, apparently what I had to do was enable BGP on both gateways (Azure and 3rd party), and add a custom route on my on-prem machine.
To add the custom route, after downloading the VPN client from the Azure portal from the VPN Gateway blade and unzipping and installing, edit the routes.txt file %AppData%\Microsoft\Network\Connections\Cm\yourGuid\routes.txt. Add a route to the 3rd party network address space (in my case 10.100.0.0/16) that goes through the Azure router (10.3.200.5).
In our case we also wanted Azure web apps to be able to do the same thing through integrating with the VNet, in which case we also had to uncheck the 'IKEv2 VPN' checkbox in the Azure gateway point-to-site blade.
Comment: I would make a comment, but I have not enough reputation yet. Sorry...
I came along a [similar problem](https://serverfault.com/questions/993728/azure-site-to-point-vpn-accessing-ressources-connected-through-site-to-site-vpn). I don't know to which IP adresse I have to route my traffic. So, where can I (or did you) find the address of the azure router?
Comment: [M4SX5](https://serverfault.com/users/436041/m4sx5) It's been a long time since I posted this, and the new gateways are slightly different, but when you create a VPN gateway you assign it to a public IP resource (new or existing).  From memory your routes.txt file would have `route add   ` so in this case
`route add 10.100.0.0 MASK 255.255.0.0 10.3.200.5`
Comment: @Jason do you have the information required for the BGP element of the fix? I have a Draytek router on-premise and can't get from client P2S VPN to the on-premise infrastructure, I can only hit the azure machines.
Comment: Can you ping from the Azure machine to on-prem router or machines? Double check your NSGs to ensure traffic (especially ICMP for testing ping) is allowed.
Comment: Sorry for slow reply, Yes. If I am in Azure, I can ping the on-prem machines, even RDP to them, and from on-prem to Azure. The issue is when the clients connect via VPN to Azure. They can see/ping/rdp Azure, but not on-prem. Annoying!


What does this recursive algorithm do?

Question: I have an algorithm :
def generate (last, cur):
   if (cur>100):
      print cur
   return generate(cur, last+cur)

I have two questions:

What will this function print?

And, how to modify this function, so that it prints original output but in reverse order?
Comment: Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it. See http://stackoverflow.com/help/on-topic
Comment: you did not try what it  prints ?
Comment: Maybe you want to elaborate a bit further. Have you actually tried to execute the algorithm?
Comment: If the code you show is Python code, please remember to indent it properly. Depending on indentation the code can do different things. Also add the Python language tag.
Comment: I have no laptop with me, just help me with solution please, not with clever words
Comment: The problem is that without proper indentation then the code you show could literally behave in three or four different ways. If you want us to be able to help you in any way we need to know the proper code.
Comment: Guys, faster please
Comment: This is given code, nothing more
Answer: If the function generate() is called with parameters 1,1, it prints the fibonacci series starting with the first value exceeding 100, that is 144
Output:
144
233
377
610
987
1597
.... till maximum stack depth is reached..

Answer: Okay, this prints fibonacci series.
Comment: For values greater than 100.

What does this recursive algorithm do?


Remover caracteres especiais mantendo os acentos

Question: Tenho essa função abaixo:
<?php
    $titulo = "Notícia Com Ácêntös";
    $titulo_novo = preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'),  array('', '-', ''), $titulo);

    echo $titulo_novo; // Retorna: Notcia-Com-cnts
?>

Notem que ela está removendo os acentos, eu quero que só remova os caracteres especiais, mas mantenha os acentos e ç (cedilha).
Preciso dessa função para renomear as imagens que faço o upload, por exemplo:
Converter isso:
"Símbolo cachaça & foguete.com.jpg"

Para isso:
"Símbolo-cachaça-foguete-com.jpg"

Comment: Não me parece o ideal, só esta lhe parecendo isso porque resolveu parte do que você já queria, de qualquer forma o que eu disse já se aplica, mesmo em preg_replace, basta você DELIMITAR o que precisa que seja removido, ao invés de "ignorar", basta fazer o replace de &, _, . e espaços e por fim quando ficar se ficar hifens em sequencia faça um outro replace só para remover as sequencias que irão surgir.
Comment: Acentos utf8 e latin1 (iso-8859-1, windows-1252, etc) não são os mesmos, quero dizer `á` do utf--8 não é a mesma coisa que `á` do latin1, se parecem, mas não são iguais. Logo a própria ideia que aplicar algo da forma que você deseja vai ser algo falho, portanto não tem como resolver dessa forma que você deseja.
Comment: Para o resultado esperado me parece que nem de regex você precisa, bastaria talvez usar o https://www.php.net/manual/pt_BR/function.strtr.php, lembrando de separar a extensão do resto da string, o que pode ser feito com `pathinfo` ou até substr + strrpos
Comment: Dessa forma eu teria que identificar tudo o que eu quero substituir, quero alguma coisa automática que eu fale o que eu quero que não altere, e todo o resto suma. acho que o preg_replace é o ideal mas não estou fazendo direito.
Comment: Olha só, usei o exemplo do "&","." só como exemplo mesmo, pois tem uma infinidades de caracteres que os usuários podem nomear as imagens antes de enviar, pra eu fazer uma lista de todos o código iria ficar muito grande, entendeu?
Answer: Criei um exemplo, isso que gostaria?
$titulos = [
    'Notícia ÷ 2×2 äëïöü',
    'Notícia Com Ácêntös',
    'Símbolo cachaça & foguete.com'
];

foreach($titulos as $titulo) {
    $novo_titulo = preg_replace('/[^\p{L}\p{M}]+/u', '-', $titulo);

    echo $novo_titulo . PHP_EOL;
}

Exemplo: aqui
Comment: Não querendo ser chato (mas fazer o quê... toda resposta é referência para futuros visitantes) mas só funcionou no teste por mera coincidência. O encoding do source é o primeiro problema de todos e não foi considerado. Fora isso, a regex está errada, além de deixar passar caracteres especiais que ficam entre `À` e `ü` ) Exemplo: `÷` https://ideone.com/e2KQMU. Você pode [edit] o post e corrigir os problemas a qualquer momento, um dos princípios do site é sempre dar espaço para melhorar os posts e agregar pra comunidadee). E, em unicode ainda tem a falta de normalização.
Comment: Olá Jeff. Se o script PHP for salvo com windows-1252 ou equivalente e os arquivos .jpg no sistema operacional estiverem com seus nomes em UTF-8, isso irá falhar. cc @AlexFonseca
Comment: Sem levar em conta os problemas de encoding já mencionados, daria para "simplificar" para `preg_replace('/[^\p{L}\p{M}]+/u', '-', $titulo)`. O *lookahead* me parece desnecessário, pois para negar um caractere basta `[^...]` - e usei as [Unicode Properties](https://www.php.net/manual/en/regexp.reference.unicode.php) para pegar letras e diacríticos (os acentos, caso a string esteja em NFD). Claro que ainda não resolve o caso do `algo.com.jpg` que pelo exemplo da pergunta deveria ficar `algo-com.jpg` (somente o último ponto não é trocado), mas já melhora um pouco...
Comment: Olá pessoal, de fato a regex anterior não cobria todo o range que necessitava. Muito obrigado @hkotsubo pela sua contribuição.
Comment: Sobre o problema de encoding realmente pode acontecer. quais opções teriam para resolver esse problema? Infelizmente não consigo ajudar sem efetuar alguns testes e entender o cenário :/
Answer: Obrigado @Jeff.Dev
Era exatamente o que eu queria, só dei uma minimizada nele e pronto, ficou perfeito!
<?php
$removerEspeciais = 'Notícia Com Ácêntös';
$removerEspeciais = preg_replace(['#(?![A-Za-zÀ-ü0-9.]).#i', '#[-]{1,}#i'], ['-', '-'], $removerEspeciais);
echo $removerEspeciais;
?>


SQL: Dúvida no Relacionamento entre Tabelas

Question: Estou criando um sistema académico que consiste em um tipo de cardápio de restaurante virtual, para isso, criei três tabelas no banco:
Tabela de Itens do Cardápio:
CREATE TABLE ITEMS(
    ID INT PRIMARY KEY NOT NULL,
    NOME VARCHAR(20) NOT NULL,
    DESCRICAO VARCHAR(20),
    PRECO FLOAT NOT NULL
)

Tabela de Pedidos:
CREATE TABLE PEDIDO(
    NUMERO INT PRIMARY KEY NOT NULL,
    MESA INT NOT NU NULL,
    VALORTOTAL FLOAT
)

Tabela onde registro os Itens do Pedido, no qual:

ID_PEDIDO = FK de Pedido,
ID_ITEM = FK de Item

CREATE TABLE ITEM_PEDIDO(
    ID INT PRIMARY KEY NOT NULL,
    ID_PEDIDO INT NOT NULL,
    ID_ITEM INT NOT NULL,
    QTD_ITEM INT
 )

Minha dúvida é a seguinte:
No sistema, o usuário poderá escolher um item ou mais para seu pedido, assim como a quantidade deste item. Ao final do pedido, deverá retornar o preço total do mesmo.

Sendo assim, devo deixar a QTD_ITEM na tabela ITEM_PEDIDO?
  Quanto ao PREÇO, devo deixar na tabela ITEM ou incluo também na tabela  ITEM_PEDIDO?
Answer: Tudo que é relacionado ao que foi/será comprado deve ficar dentro da tabela ITEM_PEDIDO se for relacionado ao ITEM. Sendo assim o PRECO, como é do ITEM e não tem relação com o pedido, deve ser colocado na tabela ITEM e a QTD_ITEM que tem relação com o que foi consumido deverá estar na tabela ITEM. O cálculo do valor total será o seguinte:
SELECT P.NUMERO,
       SUM(IP.QTD_ITEM * I.PRECO) AS VALOR_TOTAL
  FROM PEDIDO P
       INNER JOIN ITEM_PEDIDO IP ON IP.ID_PEDIDO ON P.NUMERO
       INNER JOIN ITEMS I ON I.ID = IP.ID_ITEM
 WHERE P.NUMERO = 'X'
 GROUP BY P.NUMERO

Caso queira manter um preço histórico de ITEM, sugiro a criação de uma tabela com os preços com a data vigente da seguinte forma:
╔════════════════════════════╗
║         ITEM_PRECO         ║
╠═════════════════╦══════════╣
║ ID_ITEM         ║ INTEIRO  ║
║ INICIO_VIGENCIA ║ DATA     ║
║ FINAL_VIGENCIA  ║ DATA     ║
║ PRECO           ║ NUMÉRICO ║
╚═════════════════╩══════════╝

E a adição da coluna DATA_PEDIDO na tabela PEDIDO. Sendo assim o cálculo ficaria da seguinte forma:
SELECT P.NUMERO,
       SUM(IP.QTD_ITEM * IP.PRECO) AS VALOR_TOTAL
  FROM PEDIDO P
       INNER JOIN ITEM_PEDIDO IP ON IP.ID_PEDIDO ON P.NUMERO
       INNER JOIN ITEMS I ON I.ID = IP.ID_ITEM
       INNER JOIN ITEM_PRECO IP ON IP.ID_ITEM = I.ID
                               AND P.DATA_PEDIDO BETWEEN IP.INICIO_VIGENCIA AND IP.FINAL_VIGENCIA
 WHERE P.NUMERO = 'X'
 GROUP BY P.NUMERO;

Assim você poderá fazer alterações de preço sem maiores problemas e sem precisar replicar dados.
Comment: Muito obrigado @Sorack! Me ajudou muito!
Agora só me resta uma dúvida:
No JAVA, eu tenho uma classe para cada seção do cardápio.
Por exemplo: Uma classe para Bebidas, outra para Saladas, outra para Sobremesas e assim por diante.
Posso deixar no banco uma tabela única para elas, que é o caso da tabela ITEM, ou deverei "subdividir" esta ITEM em várias tabelas, tais como: TABELA BEBIDAS, TABELA SALADAS, etc.
Para cada classe no JAVA, necessariamente preciso de uma tabela?
Comment: @EduardoR não necessariamente. Se os atributos forem iguais e só o comportamento diferente não vejo porque criar várias tabelas.
Comment: Foi o que pensei mesmo, @Sorack! Obrigado por sanar minha dúvida.
Answer:
Quanto ao PREÇO, devo deixar na tabela ITEM ou incluo também na tabela ITEM_PEDIDO?

Inclua também na tabela ITEM_PEDIDO.
A tabela ITEMS contém qual é o preço vigente para cada item. Já para cada item de pedido deve-se manter tanto a quantidade de unidades pedidas como também qual era o preço vigente no momento do pedido. E o motivo é bem simples: os preços variam ao longo do tempo.
Suponha que o item A tenha preço $10 no dia D1 e que no dia D2 tenha o preço $20. Se um pedido P1 de 3 unidades para o item A foi realizado no dia D1, então o valor do pedido, para esse item, foi de $30. Se o valor do preço do item ficar armazenado somente na tabela ITEMS e se no dia D2 for consultar quanto foi o valor do pedido P1, a consulta retornará $60 para o item A, o que está errado! Por isso que nos sistemas comerciais de pedidos para cada item sempre é armazenado o valor unitário do item no momento do pedido.
Observação adicionais:

não utilize tipo de dados float para armazenar valores monetários;
na tabela ITEM_PEDIDO não é necessário criar uma coluna específica
para ser a chave primária. A chave usual é {ID_PEDIDO, SEQ_ITEM}, onde SEQ_ITEM é um número sequencial, para cada pedido.
Comment: @EduardoR: Fique atento ao detalhe que o preço de cada item é temporal.


Drush: difference between pm-update pm-updatecode

Question: What's the difference between pm-update and pm-updatecode? I reviewed this in the Drush documentation, but they sound the same.
Answer: pm-update also runs the update.php script to take care of any database schema changes that a module may need (same as drush updatedb), pm-updatecode doesn't.  Under many/most circumstances, you can just run pm-update.


How do I include extra assemblies in my package when publishing a project?

Question: The .dlls are all in the project's bin folder when packaging happens, though they get there by complicated means I'd rather not get into. I just need to get them into the package. Looking at the build output, I'm guessing I need to edit the PackageUsingManifest step, though I'm not sure how.
Comment: Simple set the property "Copy Local" to true, of all dll you want to include. To see the DLL and properties, select the project and click "show all files". They are under the tag "references".
Comment: That's why I meant by complicated means - these assemblies aren't actually referenced by this project.
Answer: A package is an atomic deliverable that is self-sufficient.
This is intended to be easily distributed and parametrized.
So if you are using package with external dependencies you probably just want to use a simple zip file instead of the deploy packaging functionality.
Therefore if you have other assemblies referenced you may want to create a solution libs folder where you will store external references and link your appropriate projects with those references.
Your dll will then all be available in your output folder if you set theme to be 'Copy Local = true'
Then you will be able to package you assembly (project) with msbuild (target package).
msbuild /t:package MyProject\MyProject.csproj or msbuild /t:package MySolution.sln


How to create a hyperlink in an Outlook appointment?

Question: I am trying to add a formatted value, from Excel to an appointment in Outlook, based on:
HTMLBody Workaround For OlAppointment Object?
I get the following error:

"Run-time error '287': Application-defined or object-defined error"

I also need to create a hyperlink in an appointment, using link in one cell and text I want to be visible in another.
Sub MakeApptWithRangeBody()

    Dim olApp As Outlook.Application
    Dim olApt As Outlook.AppointmentItem

    Const wdPASTERTF As Long = 1

    Set olApp = Outlook.Application
    Set olApt = olApp.CreateItem(olAppointmentItem)

    With olApt
        .Start = Now + 1
        .End = Now + 1.2
        .Subject = "Test Appointment"
        .Location = 18
        'Sheet1.ListObjects(1).Range.Copy
        ThisWorkbook.Worksheets("Sheet1").Range("D2").Copy
        .Display
        .GetInspector.WordEditor.Windows(1).Selection.PasteAndFormat wdPASTERTF
    End With

    End Sub

Comment: I can't reproduce your issue, your code works fine. And as for your second question, just write the text you want to display in cell D2 on your worksheet and insert the hyperlink to that text. Then it will show up like you want it to in your appointment.
Comment: Then I Guess I'm missing a Reference in vba, but do not know which one. Could you help me with this?
Comment: Well you wouldn't get a run-time error if you were missing a reference - but you do need to have Microsoft Outlook 16.0 Object Library enabled. What line are you getting the run-time error on?
Comment: .GetInspector.WordEditor.Windows(1).Selection.PasteAndFormat wdPASTERTF
Answer: I think you are getting this error because of security settings in Outlook which is generally controlled by the IT Administrators in any organization if you are using an official Outlook Email account
you could try below
.Body = ThisWorkbook.Worksheets("Sheet1").Range("D2").Value

in place of
ThisWorkbook.Worksheets("Sheet1").Range("D2").Copy

and remove the below line
.GetInspector.WordEditor.Windows(1).Selection.PasteAndFormat wdPASTERTF

Comment: Do you know which Security settings?
Makro allowed in outlook?
If .body is used i can not implement formated text. Also the pastertf enable a security problem in the settings for the organisation (i think)
Answer: You also need to activate the "Microsoft Word Object Library" in the references. Outlook is using Word as editor and this line of code
.GetInspector.WordEditor.Windows(1).Selection.PasteAndFormat wdPASTERTF

is using Word VBA code (in the editor). So you need the Word reference too not only the one for Outlook.
To create a hyperlink you can check the Hyperlinks.Add method which should work (not tested):
With olApt
    .Start = Now + 1
    .End = Now + 1.2
    .Subject = "Test Appointment"
    .Location = 18
    'Sheet1.ListObjects(1).Range.Copy
    ThisWorkbook.Worksheets("Sheet1").Range("D2").Copy
    .Display

    Dim Sel As Object
    Set Sel = .GetInspector.WordEditor.Windows(1).Selection

    Sel.PasteAndFormat wdPASTERTF
    Sel.Hyperlinks.Add Anchor:=Sel.Range, Address:="http:\\www.microsoft.com"

End With

Comment: Thanks, this explains alot! I get a server not available when I use you example above. Any ideas?
Comment: @orjansj in which line? The example worked for me. See the screenshot: `aaaaaaa` was in cell D2.
Comment: Thanks, but the line with pasterft enable a security problem, due to outlook settings in the organisation. Maybe it works with unformatted text that I Implement with a hyperlink, but i do not know how


Falha na Conexão FTP em C#

Question: Estou desenvolvendo uma aplicação Console em c# que realiza a conexão com um servidor FTP (ou pelo menos deveria), tenho o seguinte código:
Classe FTPConnection
class FTPConnection
{
    private Connection con;
    private FtpWebRequest ftp;

    public FTPConnection(Connection c)
    {
        con = c;
    }

    public bool TestConnection(){
        string host = "ftp://" + con.Host;
        if (con.Port != null) host += ":" + con.Port;
        ftp = (FtpWebRequest)FtpWebRequest.Create( host );
        ftp.Credentials = new NetworkCredential(con.User, con.Pass);
        try
        {
            WebResponse response = ftp.GetResponse();
            Util.Success("Conexão realizada com sucesso!");
        }
        catch (WebException e)
        {
            Util.Error("Falha na conexão: " + host);
            Util.Warning(e.Message);
            return false;
        }

        return true;
    }
}

Execução do Método
Connection con = new Connection();
con.Host = "127.0.0.1";
con.User = "carlos";
con.Pass = "123123";
con.Port = "21";

FTPConnection FTPc = new FTPConnection(con);
if (!FTPc.TestConnection())
{
    Util.Warning("Não foi possível conectar com os dados informados...");
}
else
{
    Util.Success("Exito no teste de conexão.");
}

O retorno sempre é:

Falha na conexão: ftp://127.0.0.1:21
  O URI solicitado é inválido para o comando de FTP.
  Não foi possível conectar com os dados informados...

Estou utilizando o FileZilla Server do XAMPP. O log de conexão dele quanto tento uma conexão é o seguinte:

(000013)18/05/2015 17:28:07 - (not logged in) (127.0.0.1)> Connected, sending welcome message...
  (000013)18/05/2015 17:28:07 - (not logged in) (127.0.0.1)> 220-FileZilla Server version 0.9.41 beta
  (000013)18/05/2015 17:28:07 - (not logged in) (127.0.0.1)> 220-written by Tim Kosse (firstname.lastname@example.com)
  (000013)18/05/2015 17:28:07 - (not logged in) (127.0.0.1)> 220 Please visit http://sourceforge.net/projects/filezilla/
  (000013)18/05/2015 17:28:07 - (not logged in) (127.0.0.1)> disconnected.

Utilizando o FileZilla Client eu conecto normalmente com os mesmos dados de conexão:
Host: 127.0.0.1
User: carlos
Pass: 123123
Port: 21

Não sei se esse método ftp.GetResponse(); é o correto para teste de conexão. Estou tentando utiliza-lo para testar a conexão. Se alguém souber o que está errado e puder adicionar um código de teste de conexão e um exemplo de conexão real (pois ainda não cheguei nessa parte) com envio de arquivos, na resposta eu agradeço.
Answer: Resolvi o problema da conexão adicionando o método do Request.
request.Method = WebRequestMethods.Ftp.ListDirectory;

Falha na Conexão FTP em C#


Como colocar dois registros de uma tabela em outra como um só no select Banco MySql

Question: Como colocar dois registros de uma tabela em outra como um só no select Banco MySql?
SELECT TURMA.turma_id, TURMA.turma_nome, PROF.prof_name
from turma TURMA LEFT JOIN professor_materia PROF_MAT
ON TURMA.turma_id=PROF_MAT.prom_mat LEFT JOIN professor PROF
ON PROF_MAT.prom_prof=PROF.prof_id

ele está retornando assim:

Gostaria que retorna-se Assim:
turma_id   |  turma_nome     |  prof_name
1          |  1º ANO A       |  PROFESSOR DE MATEMATICA, DANIEL
2          |  2º ANO         |  NULL

Desde já agradeço.
Answer: Neste caso basta usar um GROUP BY com a função GROUP_CONCAT, ex:
SELECT
    MIN(TURMA.turma_id) AS turma_id,
    TURMA.turma_nome,
    GROUP_CONCAT(PROF.prof_name SEPARATOR ', ') AS prof_name
FROM
    turma TURMA
    LEFT JOIN professor_materia PROF_MAT ON TURMA.turma_id = PROF_MAT.prom_mat
    LEFT JOIN professor PROF ON PROF_MAT.prom_prof=PROF.prof_id
GROUP BY
    TURMA.turma_nome

O GROUP BY agrupa o resultado e o GROUP_CONCAT concatena os resultados agrupados de uma coluna.
Para ler mais sobre GROUP BY e GROUP_CONCAT: https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat


Initializing a 4bit input in system verilog

Question: Assume I have input logics suchs as: x = 0, y= 1,z = 0,k = 1;
I have an output: output [3:0] reg result; I want it to become 1010(kzyx) in binary. I tried
assign result = 4'kzyx;

How do I do this?
Answer: You can simply concatenate this signals using {}:
assign result = {k,z,y,x};

A concatenation is the result of the joining together of bits resulting from one or more expressions (see more in IEEE1800-2017, ch. 11.4.12).
PS Notice that if you use assign, you should define your output as wire, not a reg.


Some confusion about proof of why continuous derivative in a region implies continuous partial derivative

Question: I am trying to understand the proof below:
screenshot, transcribed below

8.4.2 Continuously differentiable functions
Definition 8.4.5. Let $U \subset \mathbb{R}^{n}$ be open. We say $f: U \rightarrow \mathbb{R}^{m}$ is continuously differentiable or
$C^{1}(U)$, if $f$ is differentiable and $f^{\prime}: U \rightarrow
 L\left(\mathbb{R}^{n}, \mathbb{R}^{m}\right)$ is continuous.
Proposition 8.4.6. Let $U \subset \mathbb{R}^{n}$ be open and $f: U \rightarrow \mathbb{R}^{m} .$ The function $f$ is continuously
differentiable if and only if the partial derivatives $\frac{\partial
 f_{j}}{\partial x_{\ell}}$ exist for all $j$ and $\ell$ and are continuous.
Without continuity the theorem does not hold. Just because partial derivatives exist does not mean that $f$ is differentiable, in fact, $f$ may not even be continuous. See the exercises for the last section and also for this section.
Proof. We proved that if $f$ is differentiable, then the partial derivatives exist. The partial derivatives are the entries of the matrix of $f^{\prime}(x) .$ If $f^{\prime}: U \rightarrow L\left(\mathbb{R}^{n}, \mathbb{R}^{m}\right)$ is continuous, then the entries are continuous, and hence the partial derivatives are continuous.

In single variable calculus, the functions are from R to R and the derivative is also a function from R to R, but in the multi variable case, the derivative is a linear map, and if it exist, it is the Jacobian matrix. Now according to the definition, to say that the derivative is continuous in a region means that the mapping from U to $L(R^n,R^m)$ is continuous. So we are mapping points of $R^n$ to the space of linear transformations and we are saying that if this mapping is continuous, then the partial derivatives are continuous in the region. First, I'm not even sure what it means for a mapping from $R^n$ to  $L(R^n,R^m)$ to be continuous. Don't we need to define a norm on the space of linear transformation first? Second, why would the continuity of that mapping imply that the partial derivatives, which are mapping from $R^n$ to R, are continuous?
Comment: please don't use screenshots of plain text; i have transcribed the image
Comment: When you post excerpts like this, you should always **cite the source**. (And this will also help to [provide context](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question#9960) to your question.)
Answer: The space $\mathbb{R}^{n \times m}$ of real-valued $n \times m$ matrices is a normed vector space, and is of (finite!) dimension $nm$, so in fact every norm on it is equivalent. There are several commonly used matrix norms, most of which can be seen as extensions of the vector norms we know and love.
For your second question, recall that a function into a product is continuous if and only if it is continuous in each of its components. Considering the derivative $f'$ to be a function into $nm$ components, if $f'$ is continuous, all of its components must be as well.
However, we know that if $f'$ exists, its components are just the partials!
Answer: You claim that "the derivative is a linear map, and if it exist, it is the Jacobian matrix". There is some confusion here, since linear maps and matrices are distinct things. What happens is that the Jacobian matrix of $f'(p)$ is the matrix of $f'(p)$ with respect to the standard bases.
Now, let us talk about your main questions. Yes, it is natural to define first a norm on $L(\Bbb R^n,\Bbb R^m)$. It doesn't really matter which norm, since $L(\Bbb R^n,\Bbb R^m)$ is finite-dimensional and, on a finite-dimensional real vector space all norms are equivalent. And, no matter which norm you will take, each map$$\begin{array}{ccc}L(\Bbb R^n,\Bbb R^m)&\longrightarrow&\Bbb R\\f&\mapsto &a_{ij}(f),\end{array}$$will be continuous, where $a_{ij}(f)$ is the entry of the matrix of $f$ with respect to the standard bases which belongs to the $i$th row and to the $j$th column. But if $f=f'(p)$, then $a_{ij}(f)=\frac{\partial f_j}{\partial x_i}$.
Comment: thanks! By the way, if we do not use the standard basis, does the Jacobian matrix still represent the derivative or does it get a lot more complicated?
Comment: *By definition*, the Jacobian matrix is the matrix of $f'(p)$ with respect to the standard basis. So, if we use some other basis, all that we'll get is some matrix which is similar to the Jacobian matrix.


How do I find out my host name and IP address on Ubuntu?

Question: I know Windows has the ipconfig command to find out information about my host name and ip address.  On Ubuntu I tried:
tpconfig - was not installed on my machine
iwconfig - did not give useful info
ifconfig - gave the stuff below:
inet addr:188.8.131.52  Bcast:220.127.116.11
I am behind a firewall.  Are these my IP addresses? Or what do they represent?
Also, does every computer have a host name?  If so, how do I find that out?
Thanks,
Alex
Answer: The inet address is your IP address. It is not one of the 3 private ip address ranges so it is a external IP that can be accessed for the outside.
If you have an IP inside the following ranges
10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255

Then the IP is behind a NAT, and cant be accessed from the outside without port forwarding of some kind setup. Since your IP is not in any of those ranges it is a public ip and can be accessed through the internet as long as the firewall in front of it is not explicitly blocking packets.
The Bcast address is the broadcast address  of your subnet (the network that you are on), this IP is not assigned to to you alone and is the same for everyone on your subnet. A broadcast address  is the last IP in a subnet, it is not assignable to any host but rather used by many networking protocols.
You can find out your hostname by running the hostname command or cat /etc/hostname
Answer: The "inet addr" is indeed your IP address (it's an abbreviation of "internet address"); the "Bcast" part of that is the broadcast address for the subnet you are in (you can generally ignore this entirely).
You may or may not have a hostname as far as other computers are concerned. In Linux, the hostname command will tell you what your computer thinks it is called. This hostname may (or may not) work to contact your computer from another on your local network; it almost certainly will not work from outside your network.
You can also try a reverse DNS lookup on your IP address by reversing the octets in your address and appending .in-addr.arpa in an nslookup command; using the IP address you've entered here, it would be nslookup 18.104.22.168.in-addr.arpa, which may or may not return something useful/meaningful depending on how your network is setup.
Answer: Either ifconfig or ip addr show will give you your box's IP address. Not necessarily the address you use to talk to the world, though, if your default gateway performs NAT.
To see your computer's name, type hostname. All computers must have a hostname. But do not confuse a 'hostname' with a 'DNS name' (e.g., electra.example.com, hornet.example.net). The latter depends on the configuration of the DNS server.
You can find out if your computer has a DNS name by using dig or nslookup, and searching for the PTR record of your reversed IP address. E.g., if your computer's address is 10.2.3.5, search for 184.108.40.206.in-addr.arpa.


calculate number of sits in a valid row (combinatorial question)

Question: I am trying to solve some basic question in computer science although the problem is that I can't figure out how to calculate the combinatorial equation to solve my problem.
Consider a row with with $x$ chairs. in first place (from left to right) should always be a person, next should be maximum 4 empty spaces and then another person and so on. It is possible for the row to have only one place which will be occupied or a place and two, three or four empty spaces and so on. Example for valid rows:
p - - - - p - - - - p - -
p - - - - p -
p - -
p

Example of invalid rows:
- p - - -
p - - - - -
p - p
p - - p
p - - - p

How can I build an equation to calculate the number of occupied chairs?
EDIT:
the following table:
total    not-empty chairs
1        1
2        1
3        1
4        1
5        1
6        2
7        2
8        2
9        2
10       2
11       3
12       3

Comment: There isn't a unique answer.  A row with $4$ chairs could have anywhere from $1$ to $4$ occupied chairs.
Answer: It is $\lceil \frac{x}{5} \rceil$ - this means $\frac{x}{5}$ rounded up to the closest integer.
Comment: This would be the minimum number of occupied chairs.  It could be any number from this to $x$.
Comment: Yes, I meant minimum of that.


IIS 8.5 permission problems

Question: I have a Java program (running on a Windows 7 virtual machine) that uses JAAS and GSSAPI to get a resource (like, index.html etc.) from IIS (running on a Windows 2012 R2 virtual machine)
It authenticates (using Kerberos) with an Active Directory domain controller (on a second Windows 2012 R2 virtual machine).
All the virtual machines are on the same domain and use the domain controller for their DNS.
There are three active directory users:

Administrator (the default admin, obviously)
testuser (a domain user)
testuser2 (another domain user)

As far as I can tell, testuser and testuser2 are the same (although there may be something I haven't noticed that's different).
Using the program, I'm able to log in as all three of the above users (i.e. there are authentication requests/responses w/ it seeming like it's logged in correctly - wrong passwords cause it to fail etc.). When I try to get the resource, though, only Administrator and testuser2 are able to get it. testuser, however, receives this response:
<code>HTTP/1.1 401 Unauthorized
Content-Type: text/html
Server: Microsoft-IIS/8.5
WWW-Authenticate: Negotiate
Date: Tue, 03 Jan 2017 06:14:15 GMT
Content-Length: 58
You do not have permission to view this directory or page.
</code>
As I said, there seems to be no difference between the two test users.
Additionally, when I navigate to the IIS's location in Google Chrome, I'm able to log in as all three users and view the resource (and it uses kerberos to authenticate, as far as I can tell from the network traces).
I'm really lost. Thanks in advance :)
Answer: This isn't really an explanation of what was wrong or anything, but when we deleted testuser and re-made it as before it worked. I can only assume that it mustn't have had some permissions that testuser2 had (testuser was older and had been there from fairly early on, so maybe we changed something).

IIS 8.5 permission problems


Return only the highest-valued row

Question: I'm trying to find a solution to only returns the highest-valued row from a SQL query
I have a query that joins two tables together and then checks how many times the id matches within the different tables (within 'athelete' the id param is unique).
SELECT t.athlete_id, count(a.id) as 'Number of activities' FROM training_session t
    INNER JOIN athlete a ON t.athlete_id = a.id
    WHERE t.athlete_id = a.id
    GROUP BY a.id

The following table is returned
athlete_id    Number of activities
1                         4
2                         1
3                         1
4                         1
5                         1
6                         1

The issued problem is that I only want to return the row with the highest number of activities. According to the table above this should be
athlete_id = 1 since it has the greatest amount of activities.
I would appreciate some pointers on how I could improve my query to match these queries.
Answer: Use ORDER BY and LIMIT:
SELECT t.athlete_id, count(*) as `Number of activities`
FROM training_session t INNER JOIN
     athlete a
     ON t.athlete_id = a.id
GROUP BY t.athlete_id
ORDER BY COUNT(*) DESC
LIMIT 1;

I don't think a JOIN is needed for this query:
SELECT t.athlete_id, COUNT(*) as `Number of activities`
FROM training_session t
GROUP BY t.athlete_id
ORDER BY COUNT(*) DESC
LIMIT 1;

And if you want all rows in the event of ties, then this requires a bit more work.  I would recommend ranking functions:
SELECT *
FROM (SELECT t.athlete_id, COUNT(*) as `Number of activities`,
             RANK() OVER (ORDER BY COUNT(*) DESC) as seqnum
      FROM training_session t
      GROUP BY t.athlete_id
     ) t
WHERE seqnum = 1;

Comment: Thanks, this was definitely some interesting solutions. Interesting to see someone with more experience building up the queries and see how you can layer them to form the solution.

This will work perfectly!

Return only the highest-valued row


Diretiva para detectar click fora de um elemento?

Question: No AngularJS, temos a diretive ngClick, que serve para executar uma ação quando um elemento é clicado.
Eu gostaria de criar uma diretiva, chamada ngClickout para que, quando o clique ocorrer fora do elemento, executar uma ação.
Como posso fazer isso? Eu não tenho muita "intimidade" ainda com o angular.element (e não quero usar jQuery).
Comment: Qual seria a finalidade desse evento? Podes dar algum exemplo prático? Queres, por exemplo, disparar o "clique" em um `input file` ao clicar em uma `div`?
Comment: @CelsomTrindade para algo parecido com o que eu fazia no jQuery. Eu costumava estender o jQuery e criar uma função chamada `clickOut`, para reutilizar em qualquer elemento que eu desejasse: quando clicar fora, executar uma ação.  Por exemplo, eu poderia mudar o valor de uma variável ao clicar fora desse "determinado elemento"
Answer: O método mais simples de se criar uma diretiva que obtenha o resultado que você procura, seria usar o element.bind('click'); que irá detectar o clique no elemento.
Apenas um detalhe antes de demonstrar o código, é interessante que você não use o prefixo ng, por convenção, para evitar que venha a ter conflito com outras diretivas nativas do Angular. Por isso, recomendo que use seu próprio prefixo, como wm.
Então veja um exemplo básico de diretiva para detectar o clique:
.directive('wmClick', function() {
    return {
        restrict: 'A',
        link: function(scope, element) {
            element.bind('click', function(e) {
                //Execute sua função aqui
            });
        }
    }
});

<button wm-click type="button">Clique aqui</button>

Com isso, ao clicar no botão, você irá chamar o evento da diretiva. Eu costumo usar isso quando possuo alguma função comum ao app todo, como por exemplo, o log out de um usuário. Então ao invés de declarar um controller global só para essa finalidade, eu crio uma diretiva.
Agora, caso você precise propagar alguma mudança de valores, como dito nos comentários, vai precisar usar o $scope.$digest() ou $scope.$apply(), dependendo se a mudança é dentro da mesma diretiva ou em escopo global. Veja o exemplo:
.directive('wmClick', function($scope) {
    return {
        restrict: 'A',
        link: function(scope, element) {
            element.bind('click', function(e) {
                //Execute sua função aqui

                $scope.meuNome = 'Novo Nome';
                $scope.$digest(); //Para aplicar a mudança dentro da própria diretiva
                $scope.$apply(); //Para aplicar a mudança fora da diretiva
            });
        }
    }
});

Editado: Respondendo a questão do comentário
No caso de você querer propagar um evento clicando no body para remover um elemento de sua tela, como um modal, por exemplo, eu recomendaria o uso de eventos aliado ao $document assim você pode inclusive detectar o uso da tecla ESC, veja o exemplo:
.directive('wmClick', function($document, $scope) {
    return {
        restrict: 'A',
        link: function(scope, element) {
            //Usado para clique diretamente no elemento
            element.bind('click', function(e) {
                //Execute sua função aqui

                $scope.meuNome = 'Novo Nome';
                $scope.$digest(); //Para aplicar a mudança dentro da própria diretiva
                $scope.$apply(); //Para aplicar a mudança fora da diretiva
            });

            //Usado para detectar clique no body ou tecla "ESC"
            var close = function() {
                scope.$apply(function() {
                    scope.valor = false;
                });
            };

            $document.on('click', close); //Detecta um clic no documento e chama a função

            $document.on('keyup', function(e) { //Detecta o uso da tecla "ESC" e chama a função
                if (e.keyCode === 27) {
                    close();
                }
            });

            scope.$on('$destroy', function() {
                $document.off('click', close);
                $document.off('keyup', close);
            });
        }
    }
});

Comment: Entendi a ideia. Mas vamos supor que eu queria fazer um elemento "desaparecer" ao clicar no "body" ao invés de clicar no próprio elemento.   No angular tem algum jeito de detectar isso? Tipo isso [aqui](http://jsfiddle.net/rv29hm0x/)
Comment: @WallaceMaxters atualizei minha resposta. Basicamente você precisa "ouvir" o evento do documento ao invés do elemento específico.


What model is my audition guitar and why is the name slayer engraved into the side

Question:
I bought this guitar and neither me nor the guy I bought it from knew anything about it I was hoping someone else might
Comment: It's possible that the "Slayer" mention on the guitar is a reference to the band [Slayer](https://en.wikipedia.org/wiki/Slayer).
Answer: It's an Audition semi-acoustic (no specific model, unless there's a sticker under the upper F-hole). Made in Japan by Teisco during the 1960's, and sold by Woolworths.


Transpose my R Dataset for association analysis

Question: I am sort of a newbie with R and data manipulation and I am trying to transpose the UCI words dataset. The default dataset is currently structured as so.

Where the first column is the document number, the second column is the word number referencing another text file and the last column is the number of times the word occurs in the document. (For now, we can forget about the third column and I know how to drop it from the dataset.)
What I am trying to do is to transpose the dataset so that I can have each document's words in one row. So a simple example would be like this.

I tried using the t() function but it would transpose the entire dataset all together which is not what I want. I looked in using the dplyr package to help with the data manipulation but I am not getting any solid leads. If you guys have any sources or a particular direction you can nudge me towards accomplishing this that would helpfull.
Thank you!
Comment: What you're looking for is the `dcast` function in the `reshape2` package and similar.
Answer: Here's a solution using the tidyverse package (which includes dplyr). The trick is to first add another column to differentiate entries with the same value in the first column (document number) and then just change the data to wide format using pivot_wider.
library(tidyverse)

# Your data
df <- read.csv(text = "num word
1 61
2 76
1 89
3 211
3 296", sep = " ")

df %>%
  # Group by num
  group_by(num) %>%
  # Add a rownumber to differentiate entries for the same first column value
  mutate(rownum = row_number()) %>%
  # Change data to wide format
  pivot_wider(id = num,
              names_from = rownum,
              values_from = word)

Comment: Okay let me try it this way, My dataset is actually 36,000 rows long. So Ill have to edit the read.table() code from your example.
Comment: Yes. Additionally, you should change the column names so they match the ones in your data (i.e., "num" or "word").
Comment: I dont think its right, Im getting this error.

Error in UseMethod("group_by") : no applicable method for 'group_by' applied to an object of class "function"
4.

group_by(., V1)
3.

mutate(., rownum = row_number())
2.

pivot_wider(., id = V1, names_from = rownum, values_from = V2)
1.

df %>% group_by(V1) %>% mutate(rownum = row_number()) %>% pivot_wider(id = V1, names_from = rownum, values_from = V2)
Comment: Could you post part of your data using `dput`? It will be easier to help with that.
Answer: So I was able to figure out how to accomplish this task. Hopefully, it helps other DS's in the future.
data <- read.table("docword.kos.txt", sep = " ")

data <- data %>% select(V1, V2)

trans <- data %>%
         group_by(V1) %>%
         summarise(words = paste(V2, collapse = ","))

trans <- trans %>% select(words)

What I ended up doing is using the tidyr package to perform some data wrangling and group my dataset by the first column. Then I exported and re uploaded the dataset after making some slight adjustments in notepad (Replaced the " from the generated csv file)
write.csv(trans, "~\trend.csv", row.names = FALSE)


Easier method of setting up Winbind auth in LMDE?

Question: Some GNU/Linux distros (CentOS comes to mind) have a neat Authentication Config tool, in which you may specify which auth methods (files, NIS, Winbind etc) to use. You specify the needed parameters (e.g. realm, server address) and it does everything for you under the hood. Linux Mint Debian Edition doesn't seem to have one.
I'm trying to have LMDE Betsy clients login against a Samba classic PDC (not AD) which is already working just fine for Windows clients. It seems I'd have to do a fair amount of pitfall-ridden config editing. Worse, the Samba Wiki has instructions only for joining an AD, not a PDC.
Is there an easier, already-scripted way to do this in this distro? Did I fail to find some tool that's right in front of my nose?
[EDIT] Progress: I got to the point where wbinfo -u lists domain users but getent passwd doesn't, and I can't login with domain users. The only changes I made to non-Samba files were to include winbind in nsswitch.conf:
passwd:         compat winbind
group:          compat winbind

Here's my smb.conf:
[global]
   netbios name = MAQUINA128
   workgroup = PCOMLAB
   realm = PCOMLAB.INTRANET
   security = domain
   dns proxy = no
   log file = /var/log/samba/log.%m
   max log size = 1000
   syslog = 0
   panic action = /usr/share/samba/panic-action %d
   server role = member server
   passdb backend = tdbsam
   obey pam restrictions = yes
   unix password sync = yes
   passwd program = /usr/bin/passwd %u
   passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
   pam password change = yes
   map to guest = bad user
   usershare allow guests = yes
[homes]
   comment = Home Directories
   browseable = no
   read only = yes
   create mask = 0700
   directory mask = 0700
   valid users = %S
[printers]
   comment = All Printers
   browseable = no
   path = /var/spool/samba
   printable = yes
   guest ok = no
   read only = yes
   create mask = 0700
[print$]
   comment = Printer Drivers
   path = /var/lib/samba/printers
   browseable = yes
   read only = yes
   guest ok = no

Answer: What packages have you installed ?
On some distros (like ubuntu 16.04) installing winbind is not sufficient 'cause it installs only the daemon and tools.
On ubuntu 16.04, even if you put 'winbind' in nsswitch.conf
# getent passwd

return only local users until you install the package libnss-winbind.
# apt install libnss-winbind

and the package libpam-winbind for authentication part.
Hope this will help you,
Regards,
Bruno


How can 1 more feature disrupt a Random Forest's confusion matrix?

Question: I'm trying to predict a binary variable with both random forests and logistic regression. I've got unbalanced classes (approx 1.5% of Y=1), so i'm calling class_weight = "auto" on both RF and LR.
I have approx 600 features and 262,871 lines.
Here is the code :
model_rf = RandomForestClassifier(n_estimators = 500,
                                  max_depth = None,
                                  bootstrap = True,
                                  criterion = "entropy",
                                  class_weight = "auto",
                                  n_jobs=-1)

# -- Features importance
forest = model_rf.fit(X_train[:,:580], Y_train)
imp_list = list(zip(db.columns[1:], np.transpose(forest.feature_importances_)))
imp_list.sort(key=operator.itemgetter(1), reverse=True)
imp_rf = pd.DataFrame(imp_list, columns=['features', 'imp'])
imp_rf[:20].plot(kind='barh', x='features', color='darkgreen')

Confusion matrix are not so bad for both RF and LR

After adding 8 features
Feature impotances tend to say that the 8 new features are good (way better than the rest).

The confusion matrix becomes very bad

Adding 1 simulated feature
My first thought was 'the model is overfitting'. But before trying to tune the RF, I removed all the 8 new variables and replaced them with 1 simulated random feature uncorrelated with the rest of the dataset.

The variable was of course not 'important' on the RF
(WHAT?) the confusion matrix was bad again.

How can 1 simple variable qualify as not important on 500 trees can disrupt the whole model ?

And again, the logit was stable :

What do you guys think ?
Thanks for lending me your neurons.
Answer: Classification accuracy is not a good metric when your dataset is unbalanced. You should use AUC.
The default feature importance techniques in random forests are based on classification accuracy. You should use feature importances based on AUCs: An AUC-based permutation variable importance measure for random forests. If your use R you can find their method implemented in the package party.
Comment: I guess that classification accuracy is not a good metric after all. Try to repeat everything with AUC. Look up for Prof. Frank Harrell answers about classification accuracy: he often showed to be strongly against its use.
Comment: I just tuned my parameters using ``roc_auc`` as a metric and I obtained an AUC = 82,5. So my guess is that the default parameters were not optimised. Thank you. About the feature importances, I posted a question referring to your article [here](http://stackoverflow.com/questions/31289011/auc-base-features-importance-using-random-forest) for a scikit-learn implementation.
Comment: You right. AUC is the metric I use to compare my models indeed. Features importance plot was just to add some information to my post. Moreover if I follow you correctly : adding 8 features which enhanced classification accuracy (in Y=0) implies that they are more often selected in each split of the RF and so, disrupt the AUC. But then, what's happening with the add of 1 simulated feature - which is clearly not boosting classification accuracy ?
Comment: Just a brief comment. The accuracy associated to the random forest confusion matrix are respectively: 0.78, 0.97, and 0.99. However, you notice the last two confusion matrices look worse than the first. Feature importance based on "decrease in accuracy" might be unreliable here just because accuracy is unreliable.


How to fit Graded Response Model with lme4::glmer

Question: Thanks to Rijmen et al.(2003), we can fit GRM to the data with lme4::glmer.
I think Rasch model is straightforward, with data.frame with columns like this
 response  person  item
 0         1      1
 0         1      2
 1         1      3
 ...
 1         2      1
 0         2      2

we can fit Rasch model like this
 glmer(response ~ -1 + item + (1|person), data=   , family="binomial")

But how about GRM? The data would be like this
 response  person  item
 2         1      1
 4         1      2
 3         1      3
 ...
 1         2      1
 4         2      2
 ...

For a Likert scale (1 to 5). I thought converting the data like this
 response  person item  category
 1          1    1       2
 0          1    1       3
 1          1    2       4
 0          1    2       5

Because for person1, item1, the response is 2, which means that for response 2, it's yes and for response 3, it's no.
The model would be
 response ~ item:category + (1|person)

But I am not quite sure this is the right way to do...
Note: person, item, category variables are all factors
According to De Boeck et al. (2011), GRM cannot be fitted with lmer
which is rather in contrast to Rijmen et al(2003).
=== ADDED
Now I think I am pretty sure it will work, at least for GRM with no slope parameter.
Data should be coded like this.
response  person item  category
 0          1    1       1
 1          1    1       2
 1          1    1       3
 1          1    1       4
 1          1    1       5  (which is always true so should be omitted.)

for 1-5 category(ordinal) answer.
Main benefit of using GLMM for IRT model is you can put other covariates
(person, item, person-item) into the model.
And for GRM, you can set the difference between the ordinal response is the same,
which can't be handled by ordinary GRM function, for example, ltm::grm.
(Oh, I see ordinal::clmm can handle this, but I doubt it can be useful for a model like this)
  response ~ item + (1 + category|person)

or this
  response ~ item + (-1 + category|item) + (1|person)

in this case, category is integer and would be better if coded as -2, -1, 0, 1, 2.
References
Rijmen, F., Tuerlinckx, F., De Boeck, P., & Kuppens, P. (2003). A nonlinear mixed model framework for item response theory. Psychological methods, 8(2), 185.
De Boeck, P., Bakker, M., Zwitser, R., Nivard, M., Hofman, A., Tuerlinckx, F., & Partchev, I. (2011). The estimation of item response models with the lmer function from the lme4 package in R. Journal of Statistical Software, 39(12), 1-28.
====
Here's my source.
library(ltm)
#Science[c(1,3,4,7)]
Sci.df <- Science[c(1,3,4,7)] # Comfort, Work, Future, Benefit
Sci.df$id = 1:nrow(Sci.df)

Sci.long <- reshape(Sci.df, varying=colnames(Sci.df[-5]),
                v.names="Response", timevar="item", idvar=c("id"), direction="long")
Sci.long$id <- as.factor(Sci.long$id)
Sci.long$item <- as.factor(Sci.long$item)

library(ordinal)
Sci.long.clmm <- clmm(Response ~ (1|id)+item, data=Sci.long, threshold="flexible",     nAGQ=-21)
summary(Sci.long.clmm)

Positive1=as.integer(Sci.long$Response)<=1
    Positive2=as.integer(Sci.long$Response)<=2
Positive3=as.integer(Sci.long$Response)<=3

Sci.long.sep1=Sci.long
Sci.long.sep1$Response=1; Sci.long.sep1$Positive=Positive1

Sci.long.sep2=Sci.long
Sci.long.sep2$Response=2; Sci.long.sep2$Positive=Positive2

Sci.long.sep3=Sci.long
Sci.long.sep3$Response=3; Sci.long.sep3$Positive=Positive3

Sci.long.sep = rbind(Sci.long.sep1, Sci.long.sep2, Sci.long.sep3)

Sci.long.sep$Response=as.factor(Sci.long.sep$Response)

Sci.long.sep.glmm <- glmer(Positive ~ -1 + Response + item + (1|id), data=Sci.long.sep, family=binomial,
                       nAGQ=21, control=glmerControl(optimizer="optimx",
                       optCtrl=list(method="nlminb"), check.conv.grad= .makeCC("warning", tol = 1e-4, relTol = NULL) ))
summary(Sci.long.sep.glmm)

I tried my best to make it same for clmm and glmer... but the log likelihood is different.
logLik = -1730.6 for glmer
logLik = -1633.5 for clmm
and the parameters r not the same but similar.
Does anyone know why the log likehoods are different?
Comment: 1st comment: As far as I know, Rijmen et al. *do not* say that one can fit a GRM using `lme4::glmer()`, and indeed I don't see how one could--please provide a page reference in Rijmen et al. if you disagree. 2nd comment: I *think* you can fit GRM in `ordinal::clmm()`, although I haven't personally looked into it closely. 3rd comment: I don't know what your actual question is. Please edit your question to very clearly state what it is you want to know or are confused about.
Comment: I'm pretty sure you can't fit GRM in glmer, as the gl stands for generalized linear and the GRM is a generalized nonlinear model. This means the structural part of the model is not a linear predictor but is of the form $a*(b+c)$ with $a,b,c$ unknown. Linear would be something like $b+c$ (e.g., a Rasch model). I therefore agree with de Boeck.
Comment: @Momo, I guess you're right. Sorry for not mentioning. I thought of GRM with constrained slope parameter.
Comment: @Jake Westfall, As far as I figure, he is alluding that Polytomous Data can be modeled by GLMM(Generalized Linear Mixed Model, I am not referring to any particular package here). See page 191 of Rijmen et al.(2003) $L_{nij}=x_{nij} beta + z'_{nij} theta _n$ So everything's fine here. Link function and linear predictors
Comment: @Jake Westfall, I guess I am wrong about the way of implementing my data. For each category, the code should be 0 and 1 and the only category the subject selected should be 1. and the logit function should be different, that is cumulative logit function. So I guess I have to redefine link function...???
Comment: @Jake Westfall, Rijmen et al.(2003) says, "The mixed logistic regression model can handle polytomous responses by ..." and I thought mixed logistic regression model can be covered by GLMM...
Answer: For anyone who might be curious about the same thing,
clmm can fit GRM with slope 1... but I don't think clmm can allow different slopes for different items.
Here's the code.
library(ltm) # For data Science
library(ordinal)

# Science to Long format
head(ltm::Science)

Sci <- ltm::Science;
Sci$id <- 1:nrow(Sci)
    Sci.long <- reshape(Sci, varying = list(1:7), v.names = "resp", idvar="id",     direction="long",
                        timevar="item")
    Sci.long$item <- factor(Sci.long$item, labels=colnames(ltm::Science))
head(Sci.long)

Sci.clmm <- clmm(resp ~ item + (1|id), data = Sci.long, link = "logit", threshold = "flexible",
                 nAGQ=-31,
                 control = list(method = "nlminb", trace = 1,  # trace : 1=outer op, -1=inner op.
                              maxIter = 1000, gradTol = 1e-5, maxLineIter = 1000,  useMatrix = FALSE,
                              innerCtrl = "giveError"))

Sci.clmm2 <- clmm2(location = resp ~ item , data = Sci.long, random = factor(id), link = "logistic", threshold = "flexible",
                 nAGQ=-31,
                 control = clmm2.control(method = "nlminb", trace = 1,  # trace : 1=outer op, -1=inner op.
                                maxIter = 1000, gradTol = 1e-5, maxLineIter = 1000))

library(mirt)

model = "F1 = 1 - 7
COV = F1 * F1
START = (1-7, a1, 1)
FIXED = (1-7, a1)
CONSTRAIN = (1-7, d1), (1-7, d2), (1-7, d3)
"
#as.numeric(as.character(ltm::Science))

Science2 <- sapply(ltm::Science, as.numeric)

Sci.mirt <- mirt(Science2, mirt.model(model), itemtype="grsm", TOL=1e-5, quadpts = 31)

# COMPARE The Result from mirt and clmm/clmm2
coef(Sci.mirt)
Sci.clmm
Sci.clmm2

So the results are identical, one thing to give heed to is that mixed model allows free random effect variance, but IRT model assumes variance of theta = 1.
> coef(Sci.mirt)
$Comfort
    a1    d1    d2     d3 c
par  1 3.642 1.642 -0.888 0

$Environment
        a1    d1    d2     d3      c
    par  1 3.642 1.642 -0.888 -0.292
    ...
    $GroupPars
    MEAN_1 COV_11
par      0  0.679

> Sci.clmm
Cumulative Link Mixed Model fitted with the Gauss-Hermite
quadrature approximation with 31 quadrature points

formula: resp ~ item + (1 | id)
data:    Sci.long

 link  threshold nobs logLik   AIC     niter   max.grad
 logit flexible  2744 -3072.83 6165.66 1119(3) 1.04e-03

Random effects:
 Groups Name        Variance Std.Dev.
 id     (Intercept) 0.6788   0.8239
Number of groups:  id 392

Coefficients:
itemEnvironment        itemWork      itemFuture  itemTechnology            itemIndustry     itemBenefit
        -0.2922         -0.9476         -0.2901         -0.2036          0.4632         -0.6788

Thresholds:
strongly disagree|disagree             disagree|agree       agree|strongly     agree
                   -3.6419                    -1.6420                         0.8886
> Sci.clmm2
Cumulative Link Mixed Model fitted with the Gauss-Hermite
quadrature approximation with 31 quadrature points

Call:
clmm2(location = resp ~ item, random = factor(id), data = Sci.long,
    link = "logistic", control = clmm2.control(method = "nlminb",
        trace = 1, maxIter = 1000, gradTol = 1e-05, maxLineIter = 1000),
    nAGQ = -31, threshold = "flexible")

Random effects:
                 Var   Std.Dev
factor(id) 0.6788056 0.8238966

Location coefficients:
itemEnvironment        itemWork      itemFuture  itemTechnology        itemIndustry     itemBenefit
     -0.2922101      -0.9476163      -0.2901400      -0.2035440           0.4631815      -0.6788248

No Scale coefficients

Threshold coefficients:
strongly disagree|disagree             disagree|agree       agree|strongly agree
                -3.6419330                 -1.6420389                      0.8885574

log-likelihood: -3072.828
AIC: 6165.656

And one way to use glmer to fit GRM is mention as
"An approximate ML estimation method for CLMs" in
https://cran.r-project.org/web/packages/ordinal/vignettes/clm_intro.pdf


Printing an object string value located on JSON file using JAVA Jackson

Question: I will keep it simple - trying to print the username ('user') value of this JSON file with JACKSON:
{
"creds" : {
          "user": "Y9CJG1756",
          "pass": "12222#$1"
 },
"env": {
        "qa": {
               "url": "https://www.walla.com/"
         }
  }
}

I'm running this function but could only find a way to print the entire string of the object 'creds' instead of just the user name.
public static void isJsonStringWorks(String filePath) {
    try {
        JsonNode objectValue;

        byte[] jsonData = Files.readAllBytes(Paths.get(filePath));

        ObjectMapper objectMapper = new ObjectMapper();

        JsonNode rootNode = objectMapper.readTree(jsonData);
        objectValue = rootNode.get("creds");
        System.out.println("object is: " + objectValue + " ,\n" + rootNode);
    } catch (Exception e) {
        System.out.println("Could not read the JSON file");
    }

}

Really appreciate the help.
Comment: did you try with objectValue.get('user').textValue() ?
Comment: What value  System.out.println("object is: " + objectValue + " ,\n" + rootNode); is printing ?
Comment: System.out.println("object is: " + objectValue.get("user") + " ,\n" + rootNode);
Answer: The correct code would be:
objectValue = rootNode.get("creds").get("user").asText()

Also you shall consider the following options:

Introduce Java representation of your data model and read source JSON string as Java object (using objectMapper.readValue(...) method). After that it will be possible to access values like usual Java beans (root.getCreds().getUser())
Using JsonPath to access "deep" values inside JSON to simplify JSON values lookup. For example creds/user value could be obtained like:
String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
String value = JsonPath.read(document, "$.creds.user")

Answer: you are on right route.
You can call objectValue.get('user')


Cumulative distribution function of normal distribution as a series

Question: According to Wikipedia the cumulative distribution function of the standard normal distribution can be approximated with the following series:
$\frac12 + \frac{1}{\sqrt{2\pi}} e^{\frac{-x^2}{2}} [x + \frac{x^3}{3} + \frac{x^5}{{3} * {5}} + ... + \frac{x^{2n+1}}{(2n+1)!!} + ...]$
Can a series be used to approximate a normal distribution if $mu$ is not 0 and/or $\sigma$ is not 1?
Here is an R function that implements the above series for the standard normal.  However, I cannot figure out how to modify this series if $mu$ is not 0 and/or $\sigma$ is not 1:
my.cdf.function <- function(x) {
     n <- 201
     my.seq <- seq(1,n,by=2)
     my.cdf.series <- sum(sapply(1:length(my.seq), function(i) {x^my.seq[i] / cumprod(my.seq[1:i])[i]}))
     cdf.x = 1/2 + 1/((2 * pi)^0.5) * (exp(1)^((-x^2)/2)) * my.cdf.series
     return(cdf.x)
}

my.data <- data.frame(x = seq(-5,5,by=0.01))
my.output <- apply(my.data, 1, my.cdf.function)

pnorm.cdf <- pnorm(my.data$x, mean = 0, sd = 1)

all.equal(round(my.output,8), round(pnorm.cdf,8))
#[1] TRUE

plot(my.data$x, my.output)

EDIT
Here is an alternative approach, also from Wikipedia, that works for the standard normal, but I have not been able to get it to work if $mu$ is not 0 and/or $\sigma$ is not 1:
$\Phi(x) = \frac12 + \frac{1}{\sqrt{2\pi}} \sum_{k=0}^n \frac{(-1)^k x^{2k+1}}{2^k k! (2k+1)}$
Here is R code:
x1 <- -5.5
x2 <-  4
sigma <- 1
mu    <- 0
n <- 0:200
y1 <- 0.5+(1/((2*pi)^0.5))*sum((((-1)^n)*(x1^(2*n+1)))/((2^n)*(2*n+1)*factorial(n)))
y2 <- 0.5+(1/((2*pi)^0.5))*sum((((-1)^n)*(x2^(2*n+1)))/((2^n)*(2*n+1)*factorial(n)))
y2-y1
#[1] 0.9999683

pnorm(4, 0, 1)
#[1] 0.9999683

Comment: $P[X<x]=P[\frac{X-\mu}{\sigma}<\frac{x-\mu}{\sigma}]=\Phi\left( \frac{x-\mu}{\sigma}\right)$
Comment: I'm not sure if my comment makes sense. To find $P[X<x]$ for any normally distributed random variable with mean $\mu$ and standard deviation $\sigma$, start by calculating $y=\frac{x-\mu}{\sigma}$, then evaluate the standard normal distribution function, $\Phi(y)$. You are done.
Comment: @JohnL Thank you.  I got a modified version of the first R function to work with your approach.  If you want to post your comment as an answer I will accept it.  Otherwise I might go head and post the revised R function as an answer tomorrow.
Answer: @John L essentially answered my question in a comment.  He wrote: "To find $P[X<x]$ for any normally distributed random variable with mean $μ$ and standard deviation $σ$, start by calculating $y=\frac{x−μ}{σ}$, then evaluate the standard normal distribution function, $Φ(y)$. You are done."
I had been confused erroneously thinking I also needed to use $\frac{1}{\sigma\sqrt{2\pi}}$.
Here is modified R code that implements John's approach.
# cdf of normal

mu <- 2
sigma <- 2

my.cdf.function <- function(x) {
     y <- (x - mu) / sigma
     n <- 201
     my.seq <- seq(1,n,by=2)
     my.cdf.series <- sum(sapply(1:length(my.seq), function(i) {y^my.seq[i] / cumprod(my.seq[1:i])[i]}))
     cdf.x = 1/2 + 1/((2 * pi)^0.5) * (exp(1)^((-y^2)/2)) * my.cdf.series
     return(cdf.x)
}

my.data <- data.frame(x = seq(-5.5,10,by=0.01))
my.output <- apply(my.data, 1, my.cdf.function)

pnorm.cdf <- pnorm(my.data$x, mean = 2, sd = 2)

all.equal(round(my.output,8), round(pnorm.cdf,8))
#[1] TRUE

jpeg(file="myplot3.jpeg")
plot(my.data$x, my.output)
dev.off()

Comment: Please _accept_ your own answer (perfectly OK to do so) bu clicking on the check mark in the left margin. This will stop the "Community"bot from throwing it into the queue of questions with no answers or answers with no votes whatsoever.


React Transmit textarea data to add a new post

Question: Hello fellow programmers! I don't understand how to extract text from textarea and use it to add new blog posts. It should be like this:

User enters information in textarea
Clicks on AddPost button
Information on the page is updated and new post is added to the page list.

I am just starting to learn React. Thanks for your help. Here is the code I tried to write:

import styles from "./Blog.module.css"
import React from "react"

let addPost = () => {
    let text = textAreaRef.current.value

}

let textAreaRef = React.createRef()

const Blogger = (props) => {
    return (

            {props.text}

    )

}
const Blog = () => {
    return (

                <textarea ref={textAreaRef}></textarea>
                <button onClick={addPost}>Add Post</button>

                <Blogger />

    )
}
export default Blog
Answer: You need to learn more about hooks
Try this:
import React, { useState } from 'react';

const Blogger = ({ posts }) => {
  return
{posts && posts.map((post) =>
{post}
)}
;
};

const Blog = () => {
  const [posts, setPosts] = useState([]);
  const [data, setData] = useState();

  const addPost = () => {
    setPosts([...posts, data]);
  };

  return (

        <textarea
          value={data}
          onChange={(e) => setData(e.target.value)}
        ></textarea>
        <button onClick={addPost}>Add Post</button>

        <Blogger posts={posts} />

  );
};
export default Blog;


ScrollView problem in Motorola Milestone

Question: I have multiple listviews, all of them with scrollbars. Everything works great, tested in alot of emulators and a couple of phones... except in Motorola Milestone with 2.1. As i said, i tried it with the emulator in 2.1 and newer (i'm using 1.6 SDK) and i had no problem whatsoever, except when i try it with a physical Milestone. There, the scrollbar doesn't shows and, more important, i can't even scroll on the ListView.
Anyone has a clue on why is this happening?
Comment: What if you try the Milestone emulator http://developer.motorola.com/ ? If the error happens there it will be easier to debug; if it does not, it could be a problem on that specific handset.
Comment: Just tried it, it works fine on the Milestone emulator, so what could it be!?
Answer: Turns out it was a 2.x thing. My layout had
<code><scrollview>
    <listview/>
</scrollview>
</code>
so my scroll stopped working. The phones i had in that time where all 1.x, the only with a 2.x system was the Milestone and hence the illusion that it was a Milestone problem. Weird thing is, in 2.x emulator it worked fine, so i assumed it wasn't a 2.x problem, i thought that simulator behavor would be consistent with phone behavor.


Python re.findall() not working as expected - Finding string between anchors

Question: I have text I need to parse which has this pattern:
Lorem ipsum, baby shark, do do doo

    Host: MyHostName

Blah, Blah

I am trying to isolate the line Host: MyHostName
In regex101 this regex works well (?<=Host:).*?(?=$) but for some reason Python's re.findall() keeps returning an empty list. I have tweaked it in several ways but I cannot seem to get it to work.
Is there something I am overlooking here???
(Note: I am using Python 3.6)
EDIT   My code in context
import re
pattern = r'(?<=Host:)(.*)(?=$)'
data = """
        Lorem Ipsum...
          Host: MyHostName
        """

x = re.findall(pattern, data)

Comment: Please show the whole code you used.
Comment: add multiline as in my answer
Comment: You don't need `(?=$)`, just use `$`, it doesn't match anything. And why use the non-greedy `.*?`, especially since you seem to want to the end of the line ?
Comment: @LogicalKip  when I convert to just `$` is returns empty again.
Comment: You do not need `$` in the first place. Use `pattern = r'Host:\s*(.+)'`
Answer: import re

regex = r"(?<=Host:).*?(?=$)"

test_str = ("Lorem ipsum, baby shark, do do doo\n\n"
    "    Host: MyHostName\n\n"
    "Blah, Blah")

matches = re.findall(regex, test_str, re.MULTILINE)

print(matches)

Comment: - This seems to work. I have several other regexs that are working fine without MULTILINE - Why do I need it here? ?
Comment: in case of multilines the pattern character '$' matches at the end of the string and at the end of each line
Comment: I will, I am just trying to understand what is happening here first
Answer: I would keep it simple and just use the following regex pattern:
\bHost: \S+

Script:
text = """Lorem ipsum, baby shark, do do doo

    Host: MyHostName

Blah, Blah"""

matches = re.findall(r'\bHost: \S+', text)
print(matches)

This prints:
['Host: MyHostName']

Comment: - This works, but I wanted to point out that it returns `[Host: MyHostName]` not `['MyHostName`]


GoLang - How to initialize value to *time.Time

Question: I have a struct defined in some device.go file
type Payload struct {
    ...
    Timestamp *time.Time  `json:"timestamp,omitempty"`
    ...
}

Now I want to Initialize this struct in some other file and I'm trying this:
payload:= &device.Payload{
    ....
    Timestamp: time.Now(), // throws error
    ... //other initializations work fine
}

cannot use time.Now() (value of type time.Time) as *time.Time value in
struct literal

I want to initialize the variable as the current UTC time. I'm new to golang. How do I do that?
Answer: time.Now() returns a value of type time.Time, which is not *time.Time.
Note that you also cannot take the address of the return values of function calls, you can't do &time.Now() either. For details, see How to get the pointer of return value from function call?
What you may do is use a variable of type time.Time and take its address:
var t = time.Now()

payload:= &device.Payload{
    Timestamp: &t,
}

Another "popular" option is to create a helper function to return the address of a time.Time value (to which you may pass the return value of a function call directly):
func timePtr(t time.Time) *time.Time {
    return &t
}

payload:= &device.Payload{
    Timestamp: timePtr(time.Now()),
}

For details and other options, see How do I do a literal *int64 in Go?
I assume you want a pointer because you want to allow "missing time" option, which is necessary for the encoding/json package to respect a "missing time" (details: JSON omitempty With time.Time Field). Note that in other cases it may not be necessary to automatically turn to pointer: you may use the zero value of time.Time (which is a struct) to indicate the "missing time" state. To easily tell if a time.Time is its zero value, you may use Time.IsZero(). See related: Idiomatic way to represent optional time.Time in a struct
Answer: time.Now() returns a Time value, but your struct is looking for a pointer. Change your struct to
type Payload struct {
    ...
    Timestamp time.Time  `json:"timestamp,omitempty"`
    ...
}

from the docs (https://pkg.go.dev/time#Time):

Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time.


Product of a Schwartz function and a function with polynomial bonuded derivatives is schwartz?

Question: Is true the following?: If $f\in\mathcal{S}(\mathbb{R}^n)$ and $g\in\mathcal{C}^{\infty}(\mathbb{R})$ with $|g^{k}(|x|)|\leq p_k(x)$ all $k$ where $p_k(x)$ is a polynomial then $f(x)g(|x|)$ is in $\mathcal{S}(\mathbb{R}^n)?$
Comment: What did you try? Do you know how to write down the derivatives of $fg$?
Answer: Yes, as long as $g(|x|)\in C^\infty(\mathbb{R}^n).$
We only need to varify the condition
$$
\sup_{x\in \mathbb{R}^n} |x^\alpha\partial^\beta(f(x)g(|x|))|<\infty,\quad \forall \alpha,\beta\in \mathbb{N}^n.
$$
We have $$|\partial^\alpha (f(x)g(|x|))|\le \sum_{\beta+\gamma=\alpha} |\partial^\beta f(x) \partial^\gamma g(|x|)|$$
Notice that $|\partial^\alpha |x||\le C_{\alpha}$ when $|x|\ge 1$, see here. So $$|\partial^\alpha g(|x|)|\le \sum_{\beta\le \alpha} C_\beta' |g^{(|\beta|)}(|x|)|\le \widetilde{C_\alpha}\sum_{\beta\le\alpha}|p_{|\beta|}(|x|)|\le \widetilde{C_\alpha}|P_\alpha(x)|$$
At last
$$
\begin{aligned}
|x^\alpha \partial^\beta(f(x)g(|x|))|&\le |x^\alpha|\sum_{\gamma\le \beta} |\partial^\gamma f(x)| \widetilde{C_{\gamma}}|P_{\gamma}(x)|\le \sum_{\gamma\le \beta} \widetilde{C_\gamma} |\widetilde{P_\gamma}(x)| |\partial^\gamma f(x)|
\end{aligned}
$$
By $f(x)\in \mathcal{S}(\mathbb{R}^n)$, we have
$$
\sup_{x\in \mathbb{R}^n \setminus B_1} |x^\alpha\partial^\beta(f(x)g(|x|))|<\infty,\quad \forall \alpha,\beta\in \mathbb{N}^n.
$$
If $g(|x|)$ is truely smooth, so is $f(x)g(|x|)$. Then $\sup_{x\in B_1} |x^\alpha\partial^\beta(f(x)g(|x|))|<\infty$ of course. And finally we have $f(x)g(|x|)\in \mathcal{S}(\mathbb{R}^n).$ But $g(|x|)$ won't be smooth on $\mathbb{R}^n$ easily for arbitrary $g(x)\in C^\infty(\mathbb{R})$. A necessary condition is $g^{(k)}(0)=0,$ $\forall k\ge 1.$ I'm not sure whether it's sufficient.
As $\mathcal{S}(\mathbb{R}^n)\subset C^\infty(\mathbb{R}^n),$ it should be varified at first, actually. It depends on $g$.