问:
Convert XSLT 1.0 to 2.0
I need help converting an XSLT 1.0 file to 2.0 (so I can use the XSLT 2.0 replace() function call).

I've Googled, searched different books and SO with no success. I tried changing version="1.0" to 2.0 and changing html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" to simply html but this all just results in XSLTProcessor errors.

Any help is greatly appreciated. Thanks in advance.

Here is my XSLT:

```<code><?xml version="1.0" encoding="ISO-8859-1" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="no"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" encoding="ISO-8859-1" />
<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<xsl:element name="meta">
<xsl:attribute name="name">description</xsl:attribute>
<xsl:attribute name="content"><xsl:value-of select="EventList/title"/></xsl:attribute>
</xsl:element>
<xsl:element name="link"><xsl:attribute name="rel">alternate</xsl:attribute><xsl:attribute name="type">application/rss+xml</xsl:attribute><xsl:attribute name="title">RSS</xsl:attribute><xsl:attribute name="href"><xsl:value-of select="EventList/rssURL"/></xsl:attribute></xsl:element>
</head>
<body>
 <xsl:apply-templates select="EventList" />
</body>
</html>
</xsl:template>
<xsl:template match="EventList">
 <xsl:choose>
  <xsl:when test="Event">
   <xsl:apply-templates select="Event"/>
  </xsl:when>
  <xsl:otherwise>
   <div class="eventItem">
    <div class="eventItemText">
     <p>There are currently no events posted for this category.</p>
    </div>
   </div>
  </xsl:otherwise>
 </xsl:choose>
</xsl:template>
<!-- List -->
<xsl:template match="Event">
 <li>
  <!-- Title -->
  <xsl:if test="eventStatus = 2"><xsl:value-of select="eventStatusString"/> - </xsl:if>
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/e/?d=<xsl:value-of select="replace(detailpath,'/events/','')"/></xsl:attribute><xsl:attribute name="id"><xsl:value-of select="eventID"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="title" disable-output-escaping="yes"/>
  </xsl:element>
  <!-- Date and time -->
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:choose>
    <xsl:when test="repeatRuleID > 0">
     Ongoing <xsl:value-of select="repeatRuleText"/> from <xsl:value-of select="beginDate"/> through <xsl:value-of select="repeatUntilDate"/>.
     <xsl:if test="repeatRuleID=99">See details for exact dates and times.</xsl:if>
    </xsl:when>
    <xsl:otherwise>
     <xsl:if test="string(beginDay)"><xsl:value-of select="beginDay"/>, </xsl:if>
     <xsl:value-of select="beginDate"/>.
    </xsl:otherwise>
   </xsl:choose>
   <xsl:if test="repeatRuleID!=99">
    <xsl:if test="string(beginTime)">
     <xsl:text disable-output-escaping="yes"></xsl:text><xsl:value-of select="beginTime"/>.
    </xsl:if>
   </xsl:if>
  </xsl:element>
  <!-- Location -->
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="locationText"/>
  </xsl:element>
 </li>
</xsl:template>
</xsl:stylesheet>
</code>```

答:
While you're converting the code, you should get rid of those ugly disable-output-escaping="yes" attributes. They are almost certainly not wanted. The use of this attribute usually indicates that it was written by a novice with a poor understanding of the language. This also applies to the use of verbose constructs like

```<code><xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/e/?d=<xsl:value-of select="replace(detailpath,'/events/','')"/></xsl:attribute><xsl:attribute name="id"><xsl:value-of select="eventID"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="title" disable-output-escaping="yes"/>
  </xsl:element>
</code>```

that could be replaced by the much more readable

```<code><a href="http://events.stanford.edu/e/e/?d={replace(detailpath,'/events/','')}"
   id="{@eventID}" rel="external">
  <xsl:value-of select="title"/>
</a>
</code>```

Generally, some refactoring is long overdue for this code.

Title: Convert XSLT 1.0 to 2.0

Body:
I need help converting an XSLT 1.0 file to 2.0 (so I can use the XSLT 2.0 replace() function call).

I've Googled, searched different books and SO with no success. I tried changing version="1.0" to 2.0 and changing html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" to simply html but this all just results in XSLTProcessor errors.

Any help is greatly appreciated. Thanks in advance.

Here is my XSLT:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="no"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" encoding="ISO-8859-1" />
<xsl:template match="/">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<xsl:element name="meta">
<xsl:attribute name="name">description</xsl:attribute>
<xsl:attribute name="content"><xsl:value-of select="EventList/title"/></xsl:attribute>
</xsl:element>
<xsl:element name="link"><xsl:attribute name="rel">alternate</xsl:attribute><xsl:attribute name="type">application/rss+xml</xsl:attribute><xsl:attribute name="title">RSS</xsl:attribute><xsl:attribute name="href"><xsl:value-of select="EventList/rssURL"/></xsl:attribute></xsl:element>

 <xsl:apply-templates select="EventList" />

</xsl:template>
<xsl:template match="EventList">
 <xsl:choose>
  <xsl:when test="Event">
   <xsl:apply-templates select="Event"/>
  </xsl:when>
  <xsl:otherwise>

There are currently no events posted for this category.

  </xsl:otherwise>
 </xsl:choose>
</xsl:template>

<xsl:template match="Event">

  <xsl:if test="eventStatus = 2"><xsl:value-of select="eventStatusString"/> - </xsl:if>
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/e/?d=<xsl:value-of select="replace(detailpath,'/events/','')"/></xsl:attribute><xsl:attribute name="id"><xsl:value-of select="eventID"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="title" disable-output-escaping="yes"/>
  </xsl:element>

  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:choose>
    <xsl:when test="repeatRuleID > 0">
     Ongoing <xsl:value-of select="repeatRuleText"/> from <xsl:value-of select="beginDate"/> through <xsl:value-of select="repeatUntilDate"/>.
     <xsl:if test="repeatRuleID=99">See details for exact dates and times.</xsl:if>
    </xsl:when>
    <xsl:otherwise>
     <xsl:if test="string(beginDay)"><xsl:value-of select="beginDay"/>, </xsl:if>
     <xsl:value-of select="beginDate"/>.
    </xsl:otherwise>
   </xsl:choose>
   <xsl:if test="repeatRuleID!=99">
    <xsl:if test="string(beginTime)">
     <xsl:text disable-output-escaping="yes"></xsl:text><xsl:value-of select="beginTime"/>.
    </xsl:if>
   </xsl:if>
  </xsl:element>

  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="locationText"/>
  </xsl:element>

</xsl:template>
</xsl:stylesheet>

Body:
While you're converting the code, you should get rid of those ugly disable-output-escaping="yes" attributes. They are almost certainly not wanted. The use of this attribute usually indicates that it was written by a novice with a poor understanding of the language. This also applies to the use of verbose constructs like

<xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/e/?d=<xsl:value-of select="replace(detailpath,'/events/','')"/></xsl:attribute><xsl:attribute name="id"><xsl:value-of select="eventID"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="title" disable-output-escaping="yes"/>
  </xsl:element>

that could be replaced by the much more readable

<a href="http://events.stanford.edu/e/e/?d={replace(detailpath,'/events/','')}"
   id="{@eventID}" rel="external">
  <xsl:value-of select="title"/>
</a>

Generally, some refactoring is long overdue for this code.


来源: stackexchange

问:
UIDatePicker Click done and display text
I would like to get the date after the UIPicker pop-up and straight away click done button to display the date on "dobTxt.text" without scroll and select the date from UIDatePicker. How to do it?

```<code>   func doneBtnForDate(){

    if (dobTxt.text == "Please select your DOB"){
         //let selectedDate = How to get picker date without scroll it?
         dobTxt.text = selectedDate
    }

    picker.isHidden = true
    toolBar2.isHidden = true
    datePicker.isHidden = true
}
</code>```

答:
Please try this:</p>

```<code>func doneBtnForDate()
{
    if (dobTxt.text == "Please select your DOB")
    {
         let dateFormatter = DateFormatter()
         dateFormatter.dateFormat = "dd/MM/yyyy"
         dobTxt.text = dateFormatter.string(from: datePicker.date)
    }

    picker.isHidden = true
    toolBar2.isHidden = true
    datePicker.isHidden = true
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to get the date after the UIPicker pop-up and straight away click done button to display the date on "dobTxt.text" without scroll and select the date from UIDatePicker. How to do it?

   func doneBtnForDate(){

    if (dobTxt.text == "Please select your DOB"){
         //let selectedDate = How to get picker date without scroll it?
         dobTxt.text = selectedDate
    }

    picker.isHidden = true
    toolBar2.isHidden = true
    datePicker.isHidden = true
}

Body:
Please try this:

func doneBtnForDate()
{
    if (dobTxt.text == "Please select your DOB")
    {
         let dateFormatter = DateFormatter()
         dateFormatter.dateFormat = "dd/MM/yyyy"
         dobTxt.text = dateFormatter.string(from: datePicker.date)
    }

    picker.isHidden = true
    toolBar2.isHidden = true
    datePicker.isHidden = true
}


问:
How to show coverage color on the code in Eclipse?
I run my application with coverage mode, but, a file don't have color on the code.
Is there a macro (or an other solution) to show color of coverage in Eclipse ?</p>

答:
Your question implies that you have the EclEmma installed in your Eclipse, otherwise I suppose that the coverage mode you mentioned would not be accessible. In case it's installed you should see the EclEmma configuration button near the Run Configuration button in the Eclipse toolbar. It looks like Run button, with a coloured bar at the right bottom corner . Click it to see the drop-down list and choose Coverage Configurations.... You will see a dialog that looks like Run Configurations but it has an additional tab marked Coverage. Open it and check the only checkbox found there.
After it's checked, you can run your code in the coverage mode by pressing the Coverage button in the Coverage Configurations dialog or just by choosing the required configuration from the drop-down list of the EclEmma toolbar button.

Note that the coverage colors might be not seen in the editor if they are not properly set in the Eclipse preferences (General->Editors->Text Editors->Annotations, Full Coverage, No Coverage and Partial Coverage).

For more detail see the EclEmma website.


问:
Alter PHP Array
I'm need an array of all the folders in a directory, im using laravel to get an array of folders in the directory using the below code.

Storage::allDirectories('/public');

this returns an array like below.

```<code>$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];
</code>```

I need a way to remove duplicate parent directories, so for example Images will be remove if Images/Proof/Another exists or something like that, i just need to build an array of a directory and its subfolders as one array, if that makes sense.

so for example:

```<code>$directories = [
    ["Gallery"],
    ["Images/Proof/Another"],
];
</code>```

Or something like this, I can't think of a way to get this to work.

I'm building a custom media manager component if anyone was wondering, some exist but i have no control over them so i built my own.

all help is appreciated.

Can you post the code you have tried so far

For 1 i can't get my head around the logic, thats why im asking what i've done "Which i dont see how it would help at all"

```<code>foreach (Storage::allDirectories('/public') as $folder)
{
    $all_folders[] = $exploded('/',$folder);
}
</code>```

Im trying to separate the array into smaller arrays and check each exploded bit against another. But this has me running in circles.

答:
Do like below (Easiest way):-

```<code>$final_array = [];

foreach($directories as $dir){
  $final_array[explode('/',$dir)[0]] = $dir;

}
$final_array =array_values($final_array);
</code>```

Output:- https://eval.in/912417

Or:-

```<code>$final_array = [];

foreach($directories as $dir){
  $final_array[explode('/',$dir)[0]][0] = $dir;

}
$final_array =array_values($final_array);
</code>```

Output:-https://eval.in/912418

Title: Alter PHP Array

Body:
I'm need an array of all the folders in a directory, im using laravel to get an array of folders in the directory using the below code.

Storage::allDirectories('/public');

this returns an array like below.

$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];

I need a way to remove duplicate parent directories, so for example Images will be remove if Images/Proof/Another exists or something like that, i just need to build an array of a directory and its subfolders as one array, if that makes sense.

so for example:

$directories = [
    ["Gallery"],
    ["Images/Proof/Another"],
];

Or something like this, I can't think of a way to get this to work.

I'm building a custom media manager component if anyone was wondering, some exist but i have no control over them so i built my own.

all help is appreciated.

Can you post the code you have tried so far

For 1 i can't get my head around the logic, thats why im asking what i've done "Which i dont see how it would help at all"

foreach (Storage::allDirectories('/public') as $folder)
{
    $all_folders[] = $exploded('/',$folder);
}

Im trying to separate the array into smaller arrays and check each exploded bit against another. But this has me running in circles.

Body:
Do like below (Easiest way):-

$final_array = [];

foreach($directories as $dir){
  $final_array[explode('/',$dir)[0]] = $dir;

}
$final_array =array_values($final_array);

Output:- https://eval.in/912417

Or:-

$final_array = [];

foreach($directories as $dir){
  $final_array[explode('/',$dir)[0]][0] = $dir;

}
$final_array =array_values($final_array);

Output:-https://eval.in/912418


问:
PHP: Number of rows actually changed after mssql UPDATE query
In PHP, mysql_affected_rows() tells me how many rows in a table where changed after a MySQL UPDATE statement. It only counts rows where values actually changed.

The MSSQL equivalent, mssql_rows_affected(), however, returns the number of rows where the WHERE clause of the UPDATE statement is true, even if nothing in those rows actually changes.

Is there a way to determine the number of rows that were actually changed in MSSQL?

答:
You can use mysql_affected_rows

```<code>int mysql_affected_rows ([ resource $link_identifier ] )
</code>```

More information at : http://php.net/manual/en/function.mysql-affected-rows.php

ContentLicense: CC BY-SA 2.5

Body:
You can use mysql_affected_rows

int mysql_affected_rows ([ resource $link_identifier ] )

More information at : http://php.net/manual/en/function.mysql-affected-rows.php


问:
DataSet Table giving "there is no row in position 0" error
I am trying to retrieve an image from my database to appear as the background of my windows form. But the error "There are no rows at position 0" keeps appearing. I have tested it on other forms with the same code and it works fine. May I know what's wrong with the code below?</p>

```<code>cmd = new SqlCommand("select Background from Employee where EmployeeName='" + label10.Text + "'", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);

            if (ds.Tables[0].Rows[0]["Background"] != System.DBNull.Value)
            {
            MemoryStream ms = new MemoryStream((Byte[])ds.Tables[0].Rows[0]["Background"]);
            this.BackgroundImage = new Bitmap(ms);
</code>```

答:
The exception message itself is pretty straightforward: DataTable inside DataSet contains no rows so that you can't pull any data from it. The && operator can check both row existence & DBNull.Value condition (row count checking must be on the left):

```<code>if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Rows[0]["Background"] != DBNull.Value)
{
    // do another stuff
}
</code>```

NB: You can simplify usage of DataAdapter and DataSet by using standard SqlDataReader and  DataTable.Load method like this example:

```<code>using (SqlConnection con = new SqlConnection(...))
{
    using (SqlCommand cmd = new SqlCommand("select Background from Employee where EmployeeName = @Name", con))
    {
        cmd.Parameters.AddWithValue("@Name", label10.Text);

        var dt = new DataTable();
        using (SqlDataReader dr = cmd.ExecuteReader())
        {
            dt.Load(dr); // fill DataTable from reader
        }

        if (dt.Rows.Count > 0 && dt.Rows[0]["Background"] != DBNull.Value)
        {
            using (MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Background"]))
            {
                this.BackgroundImage = new Bitmap(ms);
            }
            // do another stuff
        }
        else
        {
            // do another stuff
        }
    }
}
</code>```

Body:
I am trying to retrieve an image from my database to appear as the background of my windows form. But the error "There are no rows at position 0" keeps appearing. I have tested it on other forms with the same code and it works fine. May I know what's wrong with the code below?

cmd = new SqlCommand("select Background from Employee where EmployeeName='" + label10.Text + "'", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);

            if (ds.Tables[0].Rows[0]["Background"] != System.DBNull.Value)
            {
            MemoryStream ms = new MemoryStream((Byte[])ds.Tables[0].Rows[0]["Background"]);
            this.BackgroundImage = new Bitmap(ms);

Body:
The exception message itself is pretty straightforward: DataTable inside DataSet contains no rows so that you can't pull any data from it. The && operator can check both row existence & DBNull.Value condition (row count checking must be on the left):

if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Rows[0]["Background"] != DBNull.Value)
{
    // do another stuff
}

NB: You can simplify usage of DataAdapter and DataSet by using standard SqlDataReader and  DataTable.Load method like this example:

using (SqlConnection con = new SqlConnection(...))
{
    using (SqlCommand cmd = new SqlCommand("select Background from Employee where EmployeeName = @Name", con))
    {
        cmd.Parameters.AddWithValue("@Name", label10.Text);

        var dt = new DataTable();
        using (SqlDataReader dr = cmd.ExecuteReader())
        {
            dt.Load(dr); // fill DataTable from reader
        }

        if (dt.Rows.Count > 0 && dt.Rows[0]["Background"] != DBNull.Value)
        {
            using (MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Background"]))
            {
                this.BackgroundImage = new Bitmap(ms);
            }
            // do another stuff
        }
        else
        {
            // do another stuff
        }
    }
}


问:
Updating state within setTimeout (React & React-Native)
What I've been trying to achieve are to update state and to update the same state again, based on Javascript's timer.

The reason why I can't achieve this seems to be the nature of state in React.js.

Here is a snippet of my experimentation...

```<code>render() {
    if (this.props.hasError) {
        setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
    }
    return (
      <View>
        <Blah warning={this.state.showWarning} />
      </View>
    );
}
</code>```

So, the objective is to change state for only just a few seconds if there is a specific props provided.

This approach seems to hit the limit of updating states, if this.props.hasError gets updated too frequently.

Apologies if this question is too basic.
Any suggestion will be appreciated.

答:
you are using function inside timeout this will change its scope use arow function </p>

<p>btw i have modify your code accordingly </p>

```<code>componentWillReceiveProps(nextProps) {
    if(nextProps.hasError != this.props.hasError){
        this.setState({
            showWarning:nextProps.hasError
        });
        setTimeout(()=> {
            this.setState({
                showWarning:!this.props.showWarning
            });
        }, 3000);
    }
}

render() {
    return (
      <View>
        {this.state.showWarning?<Blah warning={this.state.showWarning} />:null}
      </View>
    );
}
</code>```

Body:
What I've been trying to achieve are to update state and to update the same state again, based on Javascript's timer.

The reason why I can't achieve this seems to be the nature of state in React.js.

Here is a snippet of my experimentation...

render() {
    if (this.props.hasError) {
        setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
    }
    return (
      <View>
        <Blah warning={this.state.showWarning} />
      </View>
    );
}

So, the objective is to change state for only just a few seconds if there is a specific props provided.

This approach seems to hit the limit of updating states, if this.props.hasError gets updated too frequently.

Apologies if this question is too basic.
Any suggestion will be appreciated.

Body:
you are using function inside timeout this will change its scope use arow function

btw i have modify your code accordingly

componentWillReceiveProps(nextProps) {
    if(nextProps.hasError != this.props.hasError){
        this.setState({
            showWarning:nextProps.hasError
        });
        setTimeout(()=> {
            this.setState({
                showWarning:!this.props.showWarning
            });
        }, 3000);
    }
}

render() {
    return (
      <View>
        {this.state.showWarning?<Blah warning={this.state.showWarning} />:null}
      </View>
    );
}


问:
Combine multiple text rows with identical column
I need to combine rows with 1 column being the same and the rest is of type nvarchar.

TempTable

```<code>Id | Key          | Description1 | Description2
 1 | 60287F58-4631| Lorem Ipsum  | dolor sit amet
 2 | 60287F58-4631| consectetur  | adipiscing elit
 3 | 74553234-7543| Test test    | test test
</code>```

I need to get this result:

```<code>Key          | DescriptionCombined
60287F58-4631| Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543| Test test, test test
</code>```

I know that group by will not work because Description1 and Description2 are different between common rows. I started experimenting with for xml path(''), but this combines every row. I guess I need to first extract groups with the same key and then apply for xml path(''), but I cannot get this to work.

```<code>select ',' + t1.Description1, t1.Description2 from TempTable t1
for xml path('')
</code>```

Body:
I need to combine rows with 1 column being the same and the rest is of type nvarchar.

TempTable

Id | Key          | Description1 | Description2
 1 | 60287F58-4631| Lorem Ipsum  | dolor sit amet
 2 | 60287F58-4631| consectetur  | adipiscing elit
 3 | 74553234-7543| Test test    | test test

I need to get this result:

Key          | DescriptionCombined
60287F58-4631| Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543| Test test, test test

I know that group by will not work because Description1 and Description2 are different between common rows. I started experimenting with for xml path(''), but this combines every row. I guess I need to first extract groups with the same key and then apply for xml path(''), but I cannot get this to work.

select ',' + t1.Description1, t1.Description2 from TempTable t1
for xml path('')

Body:
You can use OUTER APPLY

DECLARE @TempTable TABLE(Id INT,  [Key]  VARCHAR(20), Description1  VARCHAR(20) , Description2  VARCHAR(20) )
INSERT INTO @TempTable VALUES
( 1 ,'60287F58-4631', 'Lorem Ipsum',  'dolor sit amet'),
( 2 ,'60287F58-4631', 'consectetur',  'adipiscing elit'),
( 3 ,'74553234-7543', 'Test test',    'test test')

select [Key], MAX(STUFF(X.DescriptionCombined,1,1,'')) DescriptionCombined
    FROM @TempTable T1
    OUTER APPLY ( SELECT ', ' + Description1 +', '+ Description2
                    FROM @TempTable T2 WHERE T1.[Key] = T2.[Key] FOR XML PATH('') ) X ( DescriptionCombined )
GROUP BY [Key]

Result:

Key                  DescriptionCombined
-------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
60287F58-4631         Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543         Test test, test test


问:
How to differentiate if the command was incorrect or the result is empty for nodejs child_process.execSync
```<code>try {
    var output = child_process.execSync(cmd);
} catch (ex) {
    return 0
}
return output.toString()
</code>```

so I want to differentiate the cases when cmd="lx -a", which is a incorrect command and the case when cmd="ls /home/dir", and /home/dir is a empty directory, so it will generate nothing or empty string.
When I tried it, it seems both cases will be caught by nodejs as exception.

How to differentiate? I thought I can write code like

```<code>if (ex.message.indexOf("not found") >= 0)
</code>```

But it will only cover one case when the command itself is incorrect, what if the parameter is wrong? Or other situations when the error message does not include "not found"?

答:
From the docs for the method:

If the process times out, or has a non-zero exit code, this method
  will throw. The Error object will contain the entire result from
  child_process.execSync().

So, in case of the non-existent command - it will throw an Error.
Otherwise it will return an empty string in output.
Set output to undefined before the try, so you could check it for the case of trowing an error.

Body:
try {
    var output = child_process.execSync(cmd);
} catch (ex) {
    return 0
}
return output.toString()

so I want to differentiate the cases when cmd="lx -a", which is a incorrect command and the case when cmd="ls /home/dir", and /home/dir is a empty directory, so it will generate nothing or empty string.
When I tried it, it seems both cases will be caught by nodejs as exception.

How to differentiate? I thought I can write code like

if (ex.message.indexOf("not found") >= 0)

But it will only cover one case when the command itself is incorrect, what if the parameter is wrong? Or other situations when the error message does not include "not found"?


问:
Tar archive: How reliable is append?
I noticed that the -a option in TAR allows appending files to an existing archive. How reliable is this for creating incremented backups of a set folder?
Is there anyone here who can share their experiences?

From the TAR manual:

```<code> -A, --catenate, --concatenate
       append tar files to an archive
</code>```

答:
Since tar is a Tape Archive the last file will physically be appended to the archive, with an header. There is no index table which could cause issues.

Thus it's very reliable. Even if the process gets interrupted halfway you can seek the archive until the last complete entry and delete everything after it and everything will be as if you never tried to append to the archive.

Title: Tar archive: How reliable is append?

Body:
I noticed that the -a option in TAR allows appending files to an existing archive. How reliable is this for creating incremented backups of a set folder?
Is there anyone here who can share their experiences?

From the TAR manual:

 -A, --catenate, --concatenate
       append tar files to an archive


问:
Python: Numpy slicing indepth explnation
I found the following code in a conway's game of life clone.
I don't understand how exactly the following code is run. Can someone give an in depth explanation in how the Code is executed?</p>

```<code>def iterate(Z):
    # find number of neighbors that each square has
    N = np.zeros(Z.shape)
    N[1:, 1:] += Z[:-1, :-1]
    N[1:, :-1] += Z[:-1, 1:]
    N[:-1, 1:] += Z[1:, :-1]
    N[:-1, :-1] += Z[1:, 1:]
    N[:-1, :] += Z[1:, :]
    N[1:, :] += Z[:-1, :]
    N[:, :-1] += Z[:, 1:]
    N[:, 1:] += Z[:, :-1]
    # a live cell is killed if it has fewer than 2 or more than 3 neighbours.
    part1 = ((Z == 1) & (N < 4) & (N > 1))
    # a new cell forms if a square has exactly three members
    part2 = ((Z == 0) & (N == 3))
    return (part1 | part2).astype(int)
</code>```

Body:
I found the following code in a conway's game of life clone.
I don't understand how exactly the following code is run. Can someone give an in depth explanation in how the Code is executed?

def iterate(Z):
    # find number of neighbors that each square has
    N = np.zeros(Z.shape)
    N[1:, 1:] += Z[:-1, :-1]
    N[1:, :-1] += Z[:-1, 1:]
    N[:-1, 1:] += Z[1:, :-1]
    N[:-1, :-1] += Z[1:, 1:]
    N[:-1, :] += Z[1:, :]
    N[1:, :] += Z[:-1, :]
    N[:, :-1] += Z[:, 1:]
    N[:, 1:] += Z[:, :-1]
    # a live cell is killed if it has fewer than 2 or more than 3 neighbours.
    part1 = ((Z == 1) & (N < 4) & (N > 1))
    # a new cell forms if a square has exactly three members
    part2 = ((Z == 0) & (N == 3))
    return (part1 | part2).astype(int)

Body:
Add a print(N) line after all the N+= lines, and try various Z arrays.

For example

Define a small z with a block of 1s in the middle:

In [29]: z = np.zeros((10,10),int)
In [31]: z[4:6,4:6]=1
In [34]: z[4:8,5]=1

In [35]: z
Out[35]:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

pass it to the function:

In [36]: iterate(z)
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  1.  2.  2.  1.  0.  0.  0.]
 [ 0.  0.  0.  2.  3.  3.  2.  0.  0.  0.]
 [ 0.  0.  0.  2.  4.  4.  3.  0.  0.  0.]
 [ 0.  0.  0.  1.  4.  3.  3.  0.  0.  0.]
 [ 0.  0.  0.  0.  2.  1.  2.  0.  0.  0.]
 [ 0.  0.  0.  0.  1.  1.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]

N has counted the number of neighbors that are 1.  Check the counts yourself.

Out[36]:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

Try various patterns, repeat the iterate and watch the pattern change.  Some die away, some move in an order fashion, some 'blink', etc.

In a line like:

N[1:, 1:] += Z[:-1, :-1]

the RHS is an upper left portion (here 9x9); LHS is a bottom right, again 9x9.  There are 8 N+= expressions, calculating the 8 neighbors (in a 3x3 block, minus the center).  With this offset slicing it can do the count for all points in Z at once.

For a start, a 1 row array might be easier to visualize

In [47]: z = np.zeros((1,10),int)
In [49]: z[0,4:7]=1
In [50]: z
Out[50]: array([[0, 0, 0, 0, 1, 1, 1, 0, 0, 0]])
In [51]: iterate(z)
[[ 0.  0.  0.  1.  1.  2.  1.  1.  0.  0.]]
Out[51]: array([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0]])

I think this works best if all the edge values of z are 0.

This array creates the glider that is animated on https://en.wikipedia.org/wiki/Glider_(Conway%27s_Life)

In [64]: z = np.zeros((10,10),int)
In [65]: z[1,2]=1;z[2,3]=1;z[3,1:4]=1


问:
(Laravel & Nginx) CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’
I have SPA which located at localhost:8080 and an API at dev.mywebsite, both are running on local server. I tried to use ajax but it returned 'Access-Control-Allow-Origin' twice, screenshot attached. I have no idea why this happen.

Below is my nginx configuration:

```<code># Default server configuration
#
server {
    # Port
    listen 80;
    listen [::]:80;

    # Server Name
    server_name dev.narpandi;

    # Logging
    rewrite_log on;

    # Location of public directory
    root /var/www/personal-website/public;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
      try_files $uri $uri/ /index.php?$query_string;
        }

    # Remove trailing slash to please routing system
    if (!-d $request_filename) {
      rewrite ^/(.+)/$ /$1 permanent;
    }

    location ~* \.php$ {
      fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
      fastcgi_index index.php;
      fastcgi_split_path_info ^(.+\.php)(.*)$;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      include /etc/nginx/fastcgi_params;

          set $cors "";

          if ($http_origin ~* 'http://localhost:8080')
          {
            set $cors "true";
          }

          if ($cors = 'true')
          {
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,Pragma,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
          }

          #if ($request_method = 'OPTIONS')
          #{
            #return 204;
          #}
    }

    # Disable all htaccess
    location ~ /\.ht {
      deny all;
    }
}
</code>```

Did I miss something? Thank you for your help.

-Edited-

Decided to remove Nginx CORS configuration and use barryvdh/laravel-cors because you can specify which routes have CORS by adding middleware.

Here is my code:

config/cors.php

```<code><?php

return [
    'supportsCredentials' => false,
    'allowedOrigins' => ['http://yourwebsite.com'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,
];
</code>```

app/Http/Middleware/Cors.php

```<code><?php

namespace App\Http\Middleware;

class Cors
{
  public function handle($request, Closure $next)
  {
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  }
}
</code>```

app/Http/Kernel.php

```<code>protected $routeMiddleware = [
  ...
  'cors' => \Barryvdh\Cors\HandleCors::class
];
</code>```

And finally use it in your routes:

```<code>Route::group(['prefix' => 'about', 'middleware' => [ ..., 'cors']],  function(){
  ...
});
</code>```

Thank you for the help and sorry for the inconvenience.

答:
You are using both NGINX cors and barryvdh/laravel-cors. Both create a header.

Delete the NGINX one should work.

Body:
I have SPA which located at localhost:8080 and an API at dev.mywebsite, both are running on local server. I tried to use ajax but it returned 'Access-Control-Allow-Origin' twice, screenshot attached. I have no idea why this happen.

Below is my nginx configuration:

# Default server configuration
#
server {
    # Port
    listen 80;
    listen [::]:80;

    # Server Name
    server_name dev.narpandi;

    # Logging
    rewrite_log on;

    # Location of public directory
    root /var/www/personal-website/public;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
      try_files $uri $uri/ /index.php?$query_string;
        }

    # Remove trailing slash to please routing system
    if (!-d $request_filename) {
      rewrite ^/(.+)/$ /$1 permanent;
    }

    location ~* \.php$ {
      fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
      fastcgi_index index.php;
      fastcgi_split_path_info ^(.+\.php)(.*)$;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      include /etc/nginx/fastcgi_params;

          set $cors "";

          if ($http_origin ~* 'http://localhost:8080')
          {
            set $cors "true";
          }

          if ($cors = 'true')
          {
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,Pragma,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
          }

          #if ($request_method = 'OPTIONS')
          #{
            #return 204;
          #}
    }

    # Disable all htaccess
    location ~ /\.ht {
      deny all;
    }
}

Did I miss something? Thank you for your help.

-Edited-

Decided to remove Nginx CORS configuration and use barryvdh/laravel-cors because you can specify which routes have CORS by adding middleware.

Here is my code:

config/cors.php

<?php

return [
    'supportsCredentials' => false,
    'allowedOrigins' => ['http://yourwebsite.com'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,
];

app/Http/Middleware/Cors.php

<?php

namespace App\Http\Middleware;

class Cors
{
  public function handle($request, Closure $next)
  {
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  }
}

app/Http/Kernel.php

protected $routeMiddleware = [
  ...
  'cors' => \Barryvdh\Cors\HandleCors::class
];

And finally use it in your routes:

Route::group(['prefix' => 'about', 'middleware' => [ ..., 'cors']],  function(){
  ...
});

Thank you for the help and sorry for the inconvenience.


问:
Reset ID and secret key for accounts-facebook in Meteor?
I installed accounts-facebook and facebook-config-ui in my Meteor project. I was having some issues getting it to work so I deleted my app from https://developers.facebook.com/apps/ to start again.

However in my Meteor app Im getting the same error and I don't have an option to add a new ID and secret key. GIT isn't showing me anything on the file system so Ive no idea how to change this.

This is my error:

Can't Load URL: The domain of this URL isn't included in the app's
  domains. To be able to load this URL, add all domains and subdomains
  of your app to the App Domains field in your app settings.

答: This data is stored in the database. Simple delete those tables. </p>


问:
MySQL date and datetime formats unrecognised by Data Studio
I've linked Google data studio with a MySQL database using the standard connector. Almost everything works fine except for date and datetime fields.

I have these 2 fields in phpmyadmin (field name, field type, output):

Validated_date datetime 2017-09-27 12:31:04

Expiration_date date 2017-12-24

In Data Studio I've set these types, but none of them are recognised:

Validated_date  Date Hour (YYYYMMDDHH)

Expiration_date Date (YYYYMMDD)

I tried to format the field with date_format in my SELECT:

```<code>DATE_FORMAT(p.Expiration_date, '%Y%m%d') AS "Expiration Date"
</code>```

I even tried other date_formats but they're never recognised as dates in Data Studio:

```<code>DATE_FORMAT(p.Expiration_date, '%Y/%m/%d') AS "Expiration Date"
DATE_FORMAT(p.Expiration_date, '%Y-%m-%d') AS "Expiration Date"
</code>```

Any idea?

答:
I had the same issue. My approach to solve this is to modify the date format within Google Data Studio by creating a new dimension, reformatting the mySQL Datetime into the desired format.

In your example you use DATE_FORMAT. I wonder if you apply this in Data Studio (which does not know DATE_FORMAT) or in mySQL?. If you do it in data studio and leave your mySQL/phpmyadmin untouched you can use this:

```<code>TODATE(your-date-field, 'DEFAULT_DASH', '%Y%m%d')
</code>```

This will take the date format YYYY-MM-DD with optional time in HH:ii:ss and reformat it into YYYYMMDD which works with data studio.

Body:
I've linked Google data studio with a MySQL database using the standard connector. Almost everything works fine except for date and datetime fields.

I have these 2 fields in phpmyadmin (field name, field type, output):

Validated_date datetime 2017-09-27 12:31:04

Expiration_date date 2017-12-24

In Data Studio I've set these types, but none of them are recognised:

Validated_date  Date Hour (YYYYMMDDHH)

Expiration_date Date (YYYYMMDD)

I tried to format the field with date_format in my SELECT:

DATE_FORMAT(p.Expiration_date, '%Y%m%d') AS "Expiration Date"

I even tried other date_formats but they're never recognised as dates in Data Studio:

DATE_FORMAT(p.Expiration_date, '%Y/%m/%d') AS "Expiration Date"
DATE_FORMAT(p.Expiration_date, '%Y-%m-%d') AS "Expiration Date"

Any idea?

Body:
I had the same issue. My approach to solve this is to modify the date format within Google Data Studio by creating a new dimension, reformatting the mySQL Datetime into the desired format.

In your example you use DATE_FORMAT. I wonder if you apply this in Data Studio (which does not know DATE_FORMAT) or in mySQL?. If you do it in data studio and leave your mySQL/phpmyadmin untouched you can use this:

TODATE(your-date-field, 'DEFAULT_DASH', '%Y%m%d')

This will take the date format YYYY-MM-DD with optional time in HH:ii:ss and reformat it into YYYYMMDD which works with data studio.


问:
Second thread doesn't update gui until first finishes
My program takes awhile to launch, so I want to create a "loading" screen for it (just a frame that appears instantly so users know it's doing something). That means a frame or JOptoinPane can be run in a separate thread immediately (see attempt below). The delay is simulated in the code below by the Thread.sleep(3000).

The problem is that the JOptoinPane appears, but stays blank until the 3 second delay is over, at which point it shows up as normal. Same behavior if it is changed to another frame. The frame loads but is empty until the time is up

A loading screen that doesn't load until the rest of the program does isn't very helpful :D. How can I fix this?

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class LoadingTry implements Runnable{

    private JFrame frame;

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LoadingTry window = new LoadingTry();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    Thread thread1 = new Thread () {
        public void run () {
            JOptionPane.showMessageDialog(null, "Intializing...");

        }
    };

    public LoadingTry() {
        thread1.start();

        initialize();
    }

    private void initialize() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {}
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void run() {}

}
</code>```

答:
Figured it out. Remove parts of this:

```<code>EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LoadingTry window = new LoadingTry();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
</code>```

change it to:

```<code>                try {
                    LoadingTry window = new LoadingTry();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
        });
</code>```

You can also replace the JOptionPane with a jframe and have an effective static splash screen

Body:
My program takes awhile to launch, so I want to create a "loading" screen for it (just a frame that appears instantly so users know it's doing something). That means a frame or JOptoinPane can be run in a separate thread immediately (see attempt below). The delay is simulated in the code below by the Thread.sleep(3000).

The problem is that the JOptoinPane appears, but stays blank until the 3 second delay is over, at which point it shows up as normal. Same behavior if it is changed to another frame. The frame loads but is empty until the time is up

A loading screen that doesn't load until the rest of the program does isn't very helpful :D. How can I fix this?

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class LoadingTry implements Runnable{

    private JFrame frame;

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LoadingTry window = new LoadingTry();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    Thread thread1 = new Thread () {
        public void run () {
            JOptionPane.showMessageDialog(null, "Intializing...");

        }
    };

    public LoadingTry() {
        thread1.start();

        initialize();
    }

    private void initialize() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {}
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void run() {}

}

Body:
Figured it out. Remove parts of this:

EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LoadingTry window = new LoadingTry();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

change it to:

                try {
                    LoadingTry window = new LoadingTry();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
        });

You can also replace the JOptionPane with a jframe and have an effective static splash screen


问:
How to execute curl command using python 3.6 windows
I have a curl command, Which works on my UNIX server.I want to execute it using python script.
curl comma:

curl -X POST -H "Content-type: application/vnd.appd.cntrl+json;v=1" -d '{"name":"Suppression_Testing","timeRange": {"startTimeMillis": "2017-12-25T04:16:30+0000","endTimeMillis": "2017-12-26T06:16:30+0000"},"affects": {"type": "APP"}}' --user api@adgm-nonprod:ac@123

https://apcn.adm.com/controller/api/accounts/3/applications/61/actionsuppressions

I tried import os and executed curl butI am getting error as POST invalid syntax.
Also I tried using subprocess

subprocess.Popen(curl 0) but no luck. Can anyone help me?

Many Thanks,
Apurva Acharya

答:
you can use python , subprocess module to do this</p>

```<code>from subprocess import Popen
command='''curl -X POST -H "Content-type: application/vnd.appd.cntrl+json;v=1" -d '{"name":"Suppression_Testing","timeRange": {"startTimeMillis": "2017-12-25T04:16:30+0000","endTimeMillis": "2017-12-26T06:16:30+0000"},"affects": {"type": "APP"}}' --user api@adgm-nonprod:ac@123'''

#use shell=True , this will allow you to run the command in a single string on a shell like environment

proc=Popen(command,shell=True)
</code>```

Body:
you can use python , subprocess module to do this

from subprocess import Popen
command='''curl -X POST -H "Content-type: application/vnd.appd.cntrl+json;v=1" -d '{"name":"Suppression_Testing","timeRange": {"startTimeMillis": "2017-12-25T04:16:30+0000","endTimeMillis": "2017-12-26T06:16:30+0000"},"affects": {"type": "APP"}}' --user api@adgm-nonprod:ac@123'''

#use shell=True , this will allow you to run the command in a single string on a shell like environment

proc=Popen(command,shell=True)


问:
Nullpointerexception when validation fails JSF using convertor
I'm using OmniFaces' omnifaces.SelectItemsConverter so I can show an object's string value in a selectOneMenu. Everything works fine until a verification fails (f:validateDoubleRange). Once that verification fails it doesn't matter what I do, I get a NullPointerException in the equals method of the object I showed in the selectOneMenu.

This is the equals method:

```<code>@Override
public boolean equals(Object obj) {
    Car other = (Car) obj;
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    if (!number.equals(other.number))
        return false;
    return true;
}
</code>```

This is where I use the OmniFaces' convertor

```<code><h:selectOneMenu id="id_1" value="#{myBean.car}" converter="omnifaces.SelectItemsConverter">
    <f:selectItems value="#{myBean.cars}" />
</h:selectOneMenu>
</code>```

And this is the validation that causes the NullPointerException

```<code><h:inputText id="nom" value="#{myBean.num}"
                style="height: 24px; "><f:validateDoubleRange minimum="0.0"/></h:inputText>
</code>```

I get the exception in this line:

```<code>if (!number.equals(other.number))
</code>```

other.number is OK, but number is null

Why is this.number null?

答:
Root cause

The root cause of the problem is JSF default handling of input component states after validation fails on any of input components inside view.

It is very well explained in this accepted answer.

Solution

So in your particular case, as previously mentioned answer suggests, you need to instruct JSF to reset input component states (the most important for h:selectOneMenu) and pull/refresh their values from backing bean model after validation fails.

If you are using JSF 2.2 and up, you can do it, for example, like this

```<code><h:commandButton value="Submit"  actionListener="#{myBean.onSubmit()}" >
    <f:ajax execute=":form:nom :form:id_1"
            render=":form:messages :form:id_1"
            resetValues="true"/>
</h:commandButton>
</code>```

UPDATE: If you are pre-JSF 2.2, you can do it using Primefaces p:ajax, for example, like this (and again solution and explanation can be found in referenced accepted answer as well as in Primefaces showcase )

```<code><h:commandButton value="Submit"  actionListener="#{dtSelectionView.onSubmit()}">
       <p:ajax process="@form" update="@form" resetValues="true" />
</h:commandButton>
</code>```

(although I would not recommend to import Primefaces solely for this purpose... it is better to explore other possibilities)

Actual cause why this.number is null

I've noticed that, if you try to submit after validation failed for the 1st time (and if you do not reset input values of h:selectOneMenu), some of following classes creates new Car object calling default constructor (and initializing number property to default value which in your case equals null)

```<code>Severe:   java.lang.NullPointerException
    at entities.Car.equals(Car.java:107)
    at javax.faces.component.UIInput.compareValues(UIInput.java:1224)
    at javax.faces.component.UIInput.validate(UIInput.java:990)
    at javax.faces.component.UIInput.executeValidate(UIInput.java:1248)
    at javax.faces.component.UIInput.processValidators(UIInput.java:712)
    at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:575)
    at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1689)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
    at javax.faces.component.UIForm.visitTree(UIForm.java:371)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
    at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:403)
    at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:266)
    at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:57)
    at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:219)
    at org.omnifaces.context.OmniPartialViewContext.processPartial(OmniPartialViewContext.java:139)
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1193)
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
</code>```

Frankly speaking, I cannot explain where and why this happens because it exceeds my knowledge on this subject.

Body:
I'm using OmniFaces' omnifaces.SelectItemsConverter so I can show an object's string value in a selectOneMenu. Everything works fine until a verification fails (f:validateDoubleRange). Once that verification fails it doesn't matter what I do, I get a NullPointerException in the equals method of the object I showed in the selectOneMenu.

This is the equals method:

@Override
public boolean equals(Object obj) {
    Car other = (Car) obj;
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    if (!number.equals(other.number))
        return false;
    return true;
}

This is where I use the OmniFaces' convertor

<h:selectOneMenu id="id_1" value="#{myBean.car}" converter="omnifaces.SelectItemsConverter">
    <f:selectItems value="#{myBean.cars}" />
</h:selectOneMenu>

And this is the validation that causes the NullPointerException

<h:inputText id="nom" value="#{myBean.num}"
                style="height: 24px; "><f:validateDoubleRange minimum="0.0"/></h:inputText>

I get the exception in this line:

if (!number.equals(other.number))

other.number is OK, but number is null

Why is this.number null?

Body:
Root cause

The root cause of the problem is JSF default handling of input component states after validation fails on any of input components inside view.

It is very well explained in this accepted answer.

Solution

So in your particular case, as previously mentioned answer suggests, you need to instruct JSF to reset input component states (the most important for h:selectOneMenu) and pull/refresh their values from backing bean model after validation fails.

If you are using JSF 2.2 and up, you can do it, for example, like this

<h:commandButton value="Submit"  actionListener="#{myBean.onSubmit()}" >
    <f:ajax execute=":form:nom :form:id_1"
            render=":form:messages :form:id_1"
            resetValues="true"/>
</h:commandButton>

UPDATE: If you are pre-JSF 2.2, you can do it using Primefaces p:ajax, for example, like this (and again solution and explanation can be found in referenced accepted answer as well as in Primefaces showcase )

<h:commandButton value="Submit"  actionListener="#{dtSelectionView.onSubmit()}">
       <p:ajax process="@form" update="@form" resetValues="true" />
</h:commandButton>

(although I would not recommend to import Primefaces solely for this purpose... it is better to explore other possibilities)

Actual cause why this.number is null

I've noticed that, if you try to submit after validation failed for the 1st time (and if you do not reset input values of h:selectOneMenu), some of following classes creates new Car object calling default constructor (and initializing number property to default value which in your case equals null)

Severe:   java.lang.NullPointerException
    at entities.Car.equals(Car.java:107)
    at javax.faces.component.UIInput.compareValues(UIInput.java:1224)
    at javax.faces.component.UIInput.validate(UIInput.java:990)
    at javax.faces.component.UIInput.executeValidate(UIInput.java:1248)
    at javax.faces.component.UIInput.processValidators(UIInput.java:712)
    at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:575)
    at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1689)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
    at javax.faces.component.UIForm.visitTree(UIForm.java:371)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
    at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:403)
    at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:266)
    at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:57)
    at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:219)
    at org.omnifaces.context.OmniPartialViewContext.processPartial(OmniPartialViewContext.java:139)
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1193)
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)

Frankly speaking, I cannot explain where and why this happens because it exceeds my knowledge on this subject.


答:
You can just filter array using array_filter function.

```<code><?php
$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];

$filtered = array_filter($directories, function($v) use ($directories) {
  foreach($directories as $dir) {
        if(strpos($dir, $v . "/") === 0) {
          return false;
        }
  }
  return true;
});
var_dump($filtered);
</code>```

Not so elegant, but clear to read.

Title: Alter PHP Array

Body:
I'm need an array of all the folders in a directory, im using laravel to get an array of folders in the directory using the below code.

Storage::allDirectories('/public');

this returns an array like below.

$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];

I need a way to remove duplicate parent directories, so for example Images will be remove if Images/Proof/Another exists or something like that, i just need to build an array of a directory and its subfolders as one array, if that makes sense.

so for example:

$directories = [
    ["Gallery"],
    ["Images/Proof/Another"],
];

Or something like this, I can't think of a way to get this to work.

I'm building a custom media manager component if anyone was wondering, some exist but i have no control over them so i built my own.

all help is appreciated.

Can you post the code you have tried so far

For 1 i can't get my head around the logic, thats why im asking what i've done "Which i dont see how it would help at all"

foreach (Storage::allDirectories('/public') as $folder)
{
    $all_folders[] = $exploded('/',$folder);
}

Im trying to separate the array into smaller arrays and check each exploded bit against another. But this has me running in circles.

Body:
You can just filter array using array_filter function.

<?php
$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];

$filtered = array_filter($directories, function($v) use ($directories) {
  foreach($directories as $dir) {
        if(strpos($dir, $v . "/") === 0) {
          return false;
        }
  }
  return true;
});
var_dump($filtered);

Not so elegant, but clear to read.


问:
How to use elements from a second list within lapply()
I have two lists, for example:

```<code>L1 <- list(A=1:3, B=4:6)
L2 <- list(A=2, B=3)
</code>```

and I want the elements of the first list to be repeated by the numers in the second list, resulting in:

```<code>>L3
$A
[1] 1 2 3 1 2 3

$B
[1] 4 5 6 4 5 6 4 5 6
</code>```

I tried with lapply() but I cannot figure out the right times argument:

```<code>L3 <- lapply(L1, function(x) rep(x, L2))
</code>```

Certainly quite easy to solve, but I don't get it right now.

答:
Here is one solution:</p>

```<code>lapply(names(L1), function(x) rep(L1[[x]], L2[[x]]))
</code>```

Body:
I have two lists, for example:

L1 <- list(A=1:3, B=4:6)
L2 <- list(A=2, B=3)

and I want the elements of the first list to be repeated by the numers in the second list, resulting in:

>L3
$A
[1] 1 2 3 1 2 3

$B
[1] 4 5 6 4 5 6 4 5 6

I tried with lapply() but I cannot figure out the right times argument:

L3 <- lapply(L1, function(x) rep(x, L2))

Certainly quite easy to solve, but I don't get it right now.

Body:
Here is one solution:

lapply(names(L1), function(x) rep(L1[[x]], L2[[x]]))


问:
PostgreSQL converting multiple rows to json array in json_build_object
There are two tables in relation one-to-many:

```<code>CREATE TABLE user (
  id bigserial PRIMARY KEY,
  name varchar(255) NOT NULL UNIQUE,
)

CREATE TABLE user_pets (
  id bigserial PRIMARY KEY,
  user_id int8 FOREIGN KEY REFERENCES user(id),
  name varchar(255)
)
</code>```

user.id is generated by DEFAULT.

Another table containing json of users and their pets:

```<code>CREATE TABLE user_json (
  user_id int8 FOREIGN KEY REFERENCES user(id),
  full_info json
)
</code>```

I want my json look like this:

```<code>{
  "id": 1,
  "name": "John",
  "pets": [
    {
      "id": 1,
      "user": 1,
      "name": "Kitty"
    },
    {
      "id": 2,
      "user": 1,
      "name": "Cat"
    }
  ]
}
</code>```

I'm using json_build_object to process user, but I don't know how to convert multiple rows to array of pets:

```<code>json_build_object(
  'id', user.id,
  'name', user.name,
  'pets', --WHAT SHALL I PASS HERE?
)
</code>```

Postgres 10

答:
In the end, this worked for me:</p>

```<code>WITH all_pets AS (
  SELECT *
  FROM pets
  WHERE pets.user_id = 1
)
INSERT INTO user_json (full_info)
SELECT
json_build_object(
  'id', user.id,
  'name', user.name,
  'pets', (
    SELECT json_agg(all_pets)
    FROM pets
  )
)
FROM user
WHERE user.id = 1;
</code>```

Body:
There are two tables in relation one-to-many:

CREATE TABLE user (
  id bigserial PRIMARY KEY,
  name varchar(255) NOT NULL UNIQUE,
)

CREATE TABLE user_pets (
  id bigserial PRIMARY KEY,
  user_id int8 FOREIGN KEY REFERENCES user(id),
  name varchar(255)
)

user.id is generated by DEFAULT.

Another table containing json of users and their pets:

CREATE TABLE user_json (
  user_id int8 FOREIGN KEY REFERENCES user(id),
  full_info json
)

I want my json look like this:

{
  "id": 1,
  "name": "John",
  "pets": [
    {
      "id": 1,
      "user": 1,
      "name": "Kitty"
    },
    {
      "id": 2,
      "user": 1,
      "name": "Cat"
    }
  ]
}

I'm using json_build_object to process user, but I don't know how to convert multiple rows to array of pets:

json_build_object(
  'id', user.id,
  'name', user.name,
  'pets', --WHAT SHALL I PASS HERE?
)

Postgres 10

Body:
In the end, this worked for me:

WITH all_pets AS (
  SELECT *
  FROM pets
  WHERE pets.user_id = 1
)
INSERT INTO user_json (full_info)
SELECT
json_build_object(
  'id', user.id,
  'name', user.name,
  'pets', (
    SELECT json_agg(all_pets)
    FROM pets
  )
)
FROM user
WHERE user.id = 1;


问:
Replicate Pl/Sql Base64 decoding to java
I have the following Oracle statement which I need to convert to Java.

```<code>select utl_encode.base64_decode('2B563967613057553550327651324B6A50756C38766F3149424E69644B6D69394A5872736C773D3D') from dual;
</code>```

Output should be :

```<code>F95F606B4594E4FDAF4362A33EE97CBE8D4804D89D2A68BD257AEC97.
</code>```

I tried using Base64.decodeBase64 but the output is not same as above.

Also tried the following link

Replicate Base64 decoding of Java in PL/SQL
but not very much helpful.

Java output :

d81e7adfdebbeb5df4e7be79df9e74df6efae75df6e01e80e74ef9e82dfcefae85df5e3de36e04ebdeb8e01e83ebddfde00e7cef6ef7e82efbdc3dc3

Can anybody help.

答:
The input you provided is the hexadecimal representation of a Base64 string, not the actual Base64 string. The following code will give the result you are looking for:

```<code>    String data = "2B563967613057553550327651324B6A50756C38766F3149424E69644B6D69394A5872736C773D3D";

    // Quick-n-dirty method to convert hex string back to bytes
    // Doesn't work if hex string has leading zeros, but for this case that doesn't apply
    BigInteger bi = new BigInteger(data,16);
    byte[] bdata = bi.toByteArray();

    // Let's look at the real Base64 string...
    String temp = new String(bdata);
    System.out.println("The base64 string is:          " + temp);

    // Now decode the base64 string back to bytes
    byte[] result = Base64.getDecoder().decode(bdata);

    // Finally print the hex representation of the decoded value
    System.out.print("The decoded value (in hex) is: ");
    for (byte b : result)
        System.out.printf("%02x", 0x000000ff & (int)b);
    System.out.println();
</code>```

This outputs:

```<code>The base64 string is:          +V9ga0WU5P2vQ2KjPul8vo1IBNidKmi9JXrslw==
The decoded value (in hex) is: f95f606b4594e4fdaf4362a33ee97cbe8d4804d89d2a68bd257aec97
</code>```

Body:
I have the following Oracle statement which I need to convert to Java.

select utl_encode.base64_decode('2B563967613057553550327651324B6A50756C38766F3149424E69644B6D69394A5872736C773D3D') from dual;

Output should be :

F95F606B4594E4FDAF4362A33EE97CBE8D4804D89D2A68BD257AEC97.

I tried using Base64.decodeBase64 but the output is not same as above.

Also tried the following link

Replicate Base64 decoding of Java in PL/SQL
but not very much helpful.

Java output :

d81e7adfdebbeb5df4e7be79df9e74df6efae75df6e01e80e74ef9e82dfcefae85df5e3de36e04ebdeb8e01e83ebddfde00e7cef6ef7e82efbdc3dc3

Can anybody help.

Body:
The input you provided is the hexadecimal representation of a Base64 string, not the actual Base64 string. The following code will give the result you are looking for:

    String data = "2B563967613057553550327651324B6A50756C38766F3149424E69644B6D69394A5872736C773D3D";

    // Quick-n-dirty method to convert hex string back to bytes
    // Doesn't work if hex string has leading zeros, but for this case that doesn't apply
    BigInteger bi = new BigInteger(data,16);
    byte[] bdata = bi.toByteArray();

    // Let's look at the real Base64 string...
    String temp = new String(bdata);
    System.out.println("The base64 string is:          " + temp);

    // Now decode the base64 string back to bytes
    byte[] result = Base64.getDecoder().decode(bdata);

    // Finally print the hex representation of the decoded value
    System.out.print("The decoded value (in hex) is: ");
    for (byte b : result)
        System.out.printf("%02x", 0x000000ff & (int)b);
    System.out.println();

This outputs:

The base64 string is:          +V9ga0WU5P2vQ2KjPul8vo1IBNidKmi9JXrslw==
The decoded value (in hex) is: f95f606b4594e4fdaf4362a33ee97cbe8d4804d89d2a68bd257aec97


问:
data conversion in python
I have crawled data online. these data are saved in a mongodb. the day is always before month and year. I just need the month and year.I want to remove the number in front of the month, the data frame are not the same,like:

20-21 May 2008,
19 March 2008,
16-17 September 2010,
5 September 2011,

these data are saved as strings in python, is there any function to remove the numbers of day in python? these are about 3000 data,so I think I need a cycle to deal the problem.

答:
Because the info you want to remove is all numeric, white space, and possibly a hyphen, you can easily do this for each date with this:

```<code>month_year = days_month_year.lstrip('0123456789- \t')
</code>```

This should be reasonably reliable, since you want to keep the string starting with the month, which is always going to be alphabetic.

There are, of course, many different ways to do this.  You could also do regular expressions to extract out what you want, but the above is the simplest.

```<code>>>> s = '20-21 May 2008'
>>> s.lstrip('0123456789- \t')
'May 2008'
</code>```

Title: data conversion in python

Body:
Because the info you want to remove is all numeric, white space, and possibly a hyphen, you can easily do this for each date with this:

month_year = days_month_year.lstrip('0123456789- \t')

This should be reasonably reliable, since you want to keep the string starting with the month, which is always going to be alphabetic.

There are, of course, many different ways to do this.  You could also do regular expressions to extract out what you want, but the above is the simplest.

>>> s = '20-21 May 2008'
>>> s.lstrip('0123456789- \t')
'May 2008'


问:
How to add right arrow for sub-child and down arrow for child menu
I have a php form. Here drop down menu is created with php mysql. Menu is simple menu. I need to add right arrow for sub-child and down arrow for child menu with css. I am unable to modify the css. Plz suggest me how to make this drop down menu more attractive.

```<code><style>
ul {list-style: none; padding: 0;  margin: 0; background: #1bc2a2;}
ul li {display: block; position: relative; float: left; background: #1bc2a2;}
li ul { display: none; }
ul li a {display: block; padding: 1em; text-decoration: none; white-space: nowrap; color: #fff;}
ul li a:hover { background: #2c3e50; }
li:hover > ul {display: block; position: absolute;}
li:hover li { float: none; }
li:hover a { background: #1bc2a2; }
li:hover li a:hover { background: #2c3e50; }
.main-navigation li ul li { border-top: 0; }
ul ul ul {left: 100%; top: 0;}
ul:before, ul:after {content: " "; display: table;}
ul:after { clear: both; }
</style>
</code>```

This is database table.

```<code>CREATE TABLE tbl_menu(
        id INT AUTO_INCREMENT PRIMARY KEY,
        label VARCHAR(20) NOT NULL,
        parent INT DEFAULT NULL
);

INSERT INTO tbl_menu VALUES
(1,'ELECTRONICS',0),
(2,'TELEVISIONS',1),
(3,'COMPUTER',1),
(4,'DELL',3),
(5,'LCD',2),
(6,'PLASMA',2),
(7,'FLASH',6),
(8,'BIKE',0),
(9,'MOTORCYCLE',8),
(10,'SCOOTER',8),
(11,'BAJAJ',9),
(12,'MAHINDRA',10);
</code>```

This is php query.

```<code><?php
$con=mysqli_connect("localhost","root","","nfs");
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

function get_menu_tree($parent)
{
    global $con;
    $menu = "";
    $sqlquery = " SELECT * FROM tbl_menu where parent='" .$parent . "' ";
    $res=mysqli_query($con,$sqlquery);
    while($row=mysqli_fetch_array($res,MYSQLI_ASSOC))
    {
           $menu .="<li><a href='#'>".$row['label']."</a>";

           $menu .= "<ul>".get_menu_tree($row['id'])."</ul>"; //call  recursively

           $menu .= "</li>";

    }

    return $menu;
}

?>
 <ul class="main-navigation">
          <?php echo get_menu_tree(0); ?>
 </ul>
</code>```

答:
Try adding this::</p>

```<code>ul li {position: relative;}
ul li::after {content: "▼"; position: absolute; top: 10px; right: 10px; font-size: 20px;}
</code>```

Body:
I have a php form. Here drop down menu is created with php mysql. Menu is simple menu. I need to add right arrow for sub-child and down arrow for child menu with css. I am unable to modify the css. Plz suggest me how to make this drop down menu more attractive.

This is database table.

CREATE TABLE tbl_menu(
        id INT AUTO_INCREMENT PRIMARY KEY,
        label VARCHAR(20) NOT NULL,
        parent INT DEFAULT NULL
);

INSERT INTO tbl_menu VALUES
(1,'ELECTRONICS',0),
(2,'TELEVISIONS',1),
(3,'COMPUTER',1),
(4,'DELL',3),
(5,'LCD',2),
(6,'PLASMA',2),
(7,'FLASH',6),
(8,'BIKE',0),
(9,'MOTORCYCLE',8),
(10,'SCOOTER',8),
(11,'BAJAJ',9),
(12,'MAHINDRA',10);

This is php query.

<?php
$con=mysqli_connect("localhost","root","","nfs");
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

function get_menu_tree($parent)
{
    global $con;
    $menu = "";
    $sqlquery = " SELECT * FROM tbl_menu where parent='" .$parent . "' ";
    $res=mysqli_query($con,$sqlquery);
    while($row=mysqli_fetch_array($res,MYSQLI_ASSOC))
    {
           $menu .="
".$row['label']."";

           $menu .= "
".get_menu_tree($row['id'])."
"; //call  recursively

           $menu .= "
";

    }

    return $menu;
}

?>

          <?php echo get_menu_tree(0); ?>

Body:
Try adding this::

ul li {position: relative;}
ul li::after {content: "▼"; position: absolute; top: 10px; right: 10px; font-size: 20px;}


问:
How to get index and the range of a div element from a group of divs using jQuery
If I have a group of tokenized divs like the following.

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<div> Barrack </div>
<div> Obama </div>
<div> was </div>
<div> the </div>
<div> president </div>
<div> of </div>
<div> the </div>
<div> United </div>
<div> States </div>
<div> from </div>
<div> the </div>
<div> year </div>
<div> 2012 </div>
<div> to </div>
<div> 2016 </div>
<div> . </div>

<button id="btnClick"> Click me </button>

<script>
$(function(){

$('#btnClick').click(function(){
var selection = window.getSelection();
alert(selection);
});

});
</script>
</code>```

I have tried the above

1) I want to get the index of divs when I click on multiple divs on mouse click event.
Example is if I click on div which contains Barrack and 2012, I am not able to get the selected div's index.

2) If I select the div which contains both Barrack and Obama
I want the range of the div, something like:
startIndex -> 0 and length -> 2.
Where startIndex = "Barrack" is the 0th div and it ranges 2 divs Barrack and Obama.

答:
Use the slice function of jQuery.

```<code>.slice( start [, end ] )
</code>```

start ➡ An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.

end ➡ An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from
  the end of the set. If omitted, the range continues until the end of
  the set.

For your case, to select only Barack & Obama from multiple div elements, I would write something like:

```<code>$( "div" ).slice(0, 1).css( "background-color", "red" );
</code>```

jQuery.slice() method

Body:
If I have a group of tokenized divs like the following.

 Barrack

 Obama

 was

 the

 president

 of

 the

 United

 States

 from

 the

 year

 2012

 to

 2016

 .

<button id="btnClick"> Click me </button>

I have tried the above

1) I want to get the index of divs when I click on multiple divs on mouse click event.
Example is if I click on div which contains Barrack and 2012, I am not able to get the selected div's index.

2) If I select the div which contains both Barrack and Obama
I want the range of the div, something like:
startIndex -> 0 and length -> 2.
Where startIndex = "Barrack" is the 0th div and it ranges 2 divs Barrack and Obama.

Body:
Use the slice function of jQuery.

.slice( start [, end ] )

start ➡ An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.

end ➡ An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from
  the end of the set. If omitted, the range continues until the end of
  the set.

For your case, to select only Barack & Obama from multiple div elements, I would write something like:

$( "div" ).slice(0, 1).css( "background-color", "red" );

jQuery.slice() method


问:
Matlab Draw a line of pixels (Vector to Raster image)
Really basic, I have a series of points while will create a line. I would like to turn that line into a series of pixels on a plane

```<code>x = [10 33 50];
y = [50 30 9];

imshow(BW); hold on;
plot(x,y)
</code>```

I originally had an idea of drawing the line by using poly2mask and expand it by drawing the line  from a 90 angle.

```<code>scalefactor = .08;

X1 = XData(1,1) - scalefactor*abs(YData(1,2) - YData(1,1));
X2 = XData(1,1) + scalefactor*abs(YData(1,2) - YData(1,1));
X3 = XData(1,2) + scalefactor*abs(YData(1,2) - YData(1,1));
X4 = XData(1,3) + scalefactor*abs(YData(1,2) - YData(1,3));
X5 = XData(1,3) - scalefactor*abs(YData(1,2) - YData(1,3));
X6 = XData(1,2) - scalefactor*abs(YData(1,2) - YData(1,1));

Y1 = YData(1,1) - scalefactor*abs(XData(1,2) - XData(1,1));
Y2 = YData(1,1) + scalefactor*abs(XData(1,2) - XData(1,1));
Y3 = YData(1,2) + scalefactor*abs(XData(1,2) - XData(1,1));
Y4 = YData(1,3) + scalefactor*abs(XData(1,2) - XData(1,3));
Y5 = YData(1,3) - scalefactor*abs(XData(1,2) - XData(1,3));
Y6 = YData(1,2) - scalefactor*abs(XData(1,2) - XData(1,1));

Xvect = [X1 X2 X3 X4 X5 X6];
Yvect = [Y1 Y2 Y3 Y4 Y5 Y6];

Lineimg = poly2mask(Xvect,Yvect,400,500);
</code>```

Problem with this was that if the line turned upside down, it would pretty much disappear. Now I'm thinking of just drawing a line of pixels and then diluting it. Question is how to draw the line.

答:
I am sorry for the inconvenience. I personally admire the founder of MATLAB who develops a toolbox from a teaching aid and who shares it with his students to build a company. The basic idea of MATLAB is building mathematical models. So, I think mathematical model is the key.

We continue the story, and We will load a built-in figure and draw a line on it.

```<code>I = imread('peppers.png');
</code>```

Then, three points are given.

```<code>x = [173 206 347];
y = [0 192 384];
</code>```

We consider whether a line can pass these points. If you randomly choose three points in a plane, generically, they are non-collinear. This is called in general position. However, an arc can do this job. We fit these points with an arc.

```<code>Trial>> p = polyfit(x,y,1);
</code>```

P is the mathematical model of the line that you want. The X coordinate of the line that we are about to draw is from zero to 521 which equals the figure.

```<code>Line_x1 = [0 521];
</code>```

The mathematical model p is used to calculate the Y coordinates.

```<code>Line_y1 = polyval(p,Line_x1);
</code>```

Now we have enough information to draw the line.

```<code>RGB = insertShape(I,'Line',[Line_x1(1) Line_y1(1) Line_x1(2) Line_y1(2)],'LineWidth',5);
imshow(RGB);
</code>```

It is not exactly pass the given points; however, it is the line that is nearest these points from in the viewpoint of the polynomial curve fitting.

Body:
Really basic, I have a series of points while will create a line. I would like to turn that line into a series of pixels on a plane

x = [10 33 50];
y = [50 30 9];

imshow(BW); hold on;
plot(x,y)

I originally had an idea of drawing the line by using poly2mask and expand it by drawing the line  from a 90 angle.

scalefactor = .08;

X1 = XData(1,1) - scalefactor*abs(YData(1,2) - YData(1,1));
X2 = XData(1,1) + scalefactor*abs(YData(1,2) - YData(1,1));
X3 = XData(1,2) + scalefactor*abs(YData(1,2) - YData(1,1));
X4 = XData(1,3) + scalefactor*abs(YData(1,2) - YData(1,3));
X5 = XData(1,3) - scalefactor*abs(YData(1,2) - YData(1,3));
X6 = XData(1,2) - scalefactor*abs(YData(1,2) - YData(1,1));

Y1 = YData(1,1) - scalefactor*abs(XData(1,2) - XData(1,1));
Y2 = YData(1,1) + scalefactor*abs(XData(1,2) - XData(1,1));
Y3 = YData(1,2) + scalefactor*abs(XData(1,2) - XData(1,1));
Y4 = YData(1,3) + scalefactor*abs(XData(1,2) - XData(1,3));
Y5 = YData(1,3) - scalefactor*abs(XData(1,2) - XData(1,3));
Y6 = YData(1,2) - scalefactor*abs(XData(1,2) - XData(1,1));

Xvect = [X1 X2 X3 X4 X5 X6];
Yvect = [Y1 Y2 Y3 Y4 Y5 Y6];

Lineimg = poly2mask(Xvect,Yvect,400,500);

Problem with this was that if the line turned upside down, it would pretty much disappear. Now I'm thinking of just drawing a line of pixels and then diluting it. Question is how to draw the line.

Body:
I am sorry for the inconvenience. I personally admire the founder of MATLAB who develops a toolbox from a teaching aid and who shares it with his students to build a company. The basic idea of MATLAB is building mathematical models. So, I think mathematical model is the key.

We continue the story, and We will load a built-in figure and draw a line on it.

I = imread('peppers.png');

Then, three points are given.

x = [173 206 347];
y = [0 192 384];

We consider whether a line can pass these points. If you randomly choose three points in a plane, generically, they are non-collinear. This is called in general position. However, an arc can do this job. We fit these points with an arc.

Trial>> p = polyfit(x,y,1);

P is the mathematical model of the line that you want. The X coordinate of the line that we are about to draw is from zero to 521 which equals the figure.

Line_x1 = [0 521];

The mathematical model p is used to calculate the Y coordinates.

Line_y1 = polyval(p,Line_x1);

Now we have enough information to draw the line.

RGB = insertShape(I,'Line',[Line_x1(1) Line_y1(1) Line_x1(2) Line_y1(2)],'LineWidth',5);
imshow(RGB);

It is not exactly pass the given points; however, it is the line that is nearest these points from in the viewpoint of the polynomial curve fitting.


问:
js Change variable will affect to original variable
I am sorry I do not know how to explain, but the situation is like this example.

After I instant a new function c, and change the value this.i will directly affect to a.

How can I solve this issue?? I do no know change this.i will affect to a.

http://jsbin.com/iPIkomu/1/edit

```<code>var a = { c: 1 };

var b = function(){
  this.i = a;

  this.i.c = 2;
};

var c = function(){
   this.i = a;

   alert(this.i.c);

};

c.prototype.set = function(){
  this.i.c = 4;

  alert(a.c);
};

d =new c();

d.set();
</code>```

答:
Use this

```<code>let person1 = { name: 'Vitor', birthYear: 1995 };
// ES6 method
let person2 = Object.assign({}, person1);
</code>```

In case of ArrayObject

```<code>let person1 = [{ name: 'Vitor', birthYear: 1995 },
              { name: 'Mark', birthYear: 1998 }];
// ES6 method
let person2 = Object.assign([], person1);
</code>```

Refere to:
https://hackernoon.com/javascript-reference-and-copy-variables-b0103074fdf0

Body:
I am sorry I do not know how to explain, but the situation is like this example.

After I instant a new function c, and change the value this.i will directly affect to a.

How can I solve this issue?? I do no know change this.i will affect to a.

http://jsbin.com/iPIkomu/1/edit

var a = { c: 1 };

var b = function(){
  this.i = a;

  this.i.c = 2;
};

var c = function(){
   this.i = a;

   alert(this.i.c);

};

c.prototype.set = function(){
  this.i.c = 4;

  alert(a.c);
};

d =new c();

d.set();

Body:
Use this

let person1 = { name: 'Vitor', birthYear: 1995 };
// ES6 method
let person2 = Object.assign({}, person1);

In case of ArrayObject

let person1 = [{ name: 'Vitor', birthYear: 1995 },
              { name: 'Mark', birthYear: 1998 }];
// ES6 method
let person2 = Object.assign([], person1);

Refere to:
https://hackernoon.com/javascript-reference-and-copy-variables-b0103074fdf0


问:
Django OAuth- Separate Resource and Authorization Server
I'm using Django Oauth Library.

I want to have different Auth and Resource Server.

On Auth Server, following is my setting.

```<code>INSTALLED_APPS = [
    ...

    'oauth2_provider',
    'rest_framework',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

# ############## OAUTH SETTINGS ###################

OAUTH2_PROVIDER = {
    'SCOPES': {'users': 'user details', 'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups', 'introspection': 'introspection'},
    'ACCESS_TOKEN_EXPIRE_SECONDS': 86400,  # 1 Day.
}
</code>```

On my Resource Server

```<code>INSTALLED_APPS = [
    ...

    'oauth2_provider',
    'rest_framework',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

# ############## OAUTH SETTINGS ###################

OAUTH2_PROVIDER = {
'RESOURCE_SERVER_INTROSPECTION_URL': 'http://localhost:8000/o/introspect/',
'RESOURCE_SERVER_AUTH_TOKEN': '3yUqsWtwKYKHnfivFcJu',
</code>```

}

Question 1)

How do I obtain RESOURCE_SERVER_AUTH_TOKEN?

Question 2)

Upon introspecting the token, Auth Server returns 403 Forbidden Error in the console logs.

Following is the flow to obtain the access token.

I get the client_id, client_secret, grant_type and scopes from the client POST request onto the Resource Server. I call the AuthServer from the Resource Server and return the response back to the client.

What exactly am I missing over here?

答:
According django-oauth-toolkit implementation, Resource server first tries to check whether access token is available in its db or not.

If access token is not present, it will check introspection URL and introspection token are available in settings. If introspection settings is available then resource server tries to validate the user token with an introspection endpoint.

So the issue seems to be that AUTH SERVER and DRF might be returing 403 Forbidden since the permission is set as IsAuthenticated. This could be either due to invalid token or invalid user.

So create a user for the resource server and then create an application for the resource server user.

creating the application,

```<code>client_type=Application.CLIENT_CONFIDENTIAL
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE
</code>```

And generate a token through the admin site and update the resource server INTROSPECTION setting with the newly created token. Make sure you put the appropriate scopes while creating the token.

Body:
I'm using Django Oauth Library.

I want to have different Auth and Resource Server.

On Auth Server, following is my setting.

INSTALLED_APPS = [
    ...

    'oauth2_provider',
    'rest_framework',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

# ############## OAUTH SETTINGS ###################

OAUTH2_PROVIDER = {
    'SCOPES': {'users': 'user details', 'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups', 'introspection': 'introspection'},
    'ACCESS_TOKEN_EXPIRE_SECONDS': 86400,  # 1 Day.
}

On my Resource Server

INSTALLED_APPS = [
    ...

    'oauth2_provider',
    'rest_framework',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

# ############## OAUTH SETTINGS ###################

OAUTH2_PROVIDER = {
'RESOURCE_SERVER_INTROSPECTION_URL': 'http://localhost:8000/o/introspect/',
'RESOURCE_SERVER_AUTH_TOKEN': '3yUqsWtwKYKHnfivFcJu',

}

Question 1)

How do I obtain RESOURCE_SERVER_AUTH_TOKEN?

Question 2)

Upon introspecting the token, Auth Server returns 403 Forbidden Error in the console logs.

Following is the flow to obtain the access token.

I get the client_id, client_secret, grant_type and scopes from the client POST request onto the Resource Server. I call the AuthServer from the Resource Server and return the response back to the client.

What exactly am I missing over here?

Body:
According django-oauth-toolkit implementation, Resource server first tries to check whether access token is available in its db or not.

If access token is not present, it will check introspection URL and introspection token are available in settings. If introspection settings is available then resource server tries to validate the user token with an introspection endpoint.

So the issue seems to be that AUTH SERVER and DRF might be returing 403 Forbidden since the permission is set as IsAuthenticated. This could be either due to invalid token or invalid user.

So create a user for the resource server and then create an application for the resource server user.

creating the application,

client_type=Application.CLIENT_CONFIDENTIAL
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE

And generate a token through the admin site and update the resource server INTROSPECTION setting with the newly created token. Make sure you put the appropriate scopes while creating the token.


问:
PHP: Number of rows actually changed after mssql UPDATE query
In PHP, mysql_affected_rows() tells me how many rows in a table where changed after a MySQL UPDATE statement. It only counts rows where values actually changed.

The MSSQL equivalent, mssql_rows_affected(), however, returns the number of rows where the WHERE clause of the UPDATE statement is true, even if nothing in those rows actually changes.

Is there a way to determine the number of rows that were actually changed in MSSQL?

答:
You can add a clause to your WHERE condition to not update a row if it doesn't change:</p>

```<code>UPDATE yourtable
SET foo = 'bar'
WHERE yourcondition
AND foo <> bar
</code>```

Body:
You can add a clause to your WHERE condition to not update a row if it doesn't change:

UPDATE yourtable
SET foo = 'bar'
WHERE yourcondition
AND foo <> bar


问:
GIT: how to stash a file after being edited locally
I've run "git add file" on local file and now I'm trying stash the action.

```<code>git status

\# On branch feature/something

\# Changes to be committed:

\#   (use "git reset HEAD <file>..." to unstage)

\#  modified:   utils.py
</code>```

When I run git diff utils.py response is Empty

How do I stash this changes I've done locally
Thanks!

答:
Well it's simpler than I thought,

running command:

"git stash"

will stash changes on all edited/added files in git repository

Body:
I've run "git add file" on local file and now I'm trying stash the action.

git status

\# On branch feature/something

\# Changes to be committed:

\#   (use "git reset HEAD <file>..." to unstage)

\#  modified:   utils.py

When I run git diff utils.py response is Empty

How do I stash this changes I've done locally
Thanks!


问:
Meaning of module's instances in /proc/modules
I have used cat /proc/modules to list the modules details.

Below a module shows as 4 instances are present:

```<code>poe_isr 3046 4 - Live 0xc37e1000 (O)
</code>```

What does it mean? How do I see where these instances are being used?

Next module is showing as 0 instances and Live:

```<code>adcmods 1565 0 - Live 0xc37dd000 (P)
</code>```

What does it mean? The module is not loaded but still Live?

答:
Not sure why some descriptions (like this one) name the third column of /proc/modules output as a "number of instances", but this is actually a module's reference count.

If a module has a positive (non-zero) reference count, then it cannot be unloaded with /sbin/rmmod (the command prints "ERROR: Module X is in use").

If some module's references are obtained by other modules, then a comma-separated list of these modules is printed as 4th column (instead of - character).

If the module's reference is obtained by non-module "objects", one should use other methods for listing these objects. E.g. a filesystem module is normally referenced by the filesystem's mounts, so one needs to check output of /usr/bin/mount.

Body:
I have used cat /proc/modules to list the modules details.

Below a module shows as 4 instances are present:

poe_isr 3046 4 - Live 0xc37e1000 (O)

What does it mean? How do I see where these instances are being used?

Next module is showing as 0 instances and Live:

adcmods 1565 0 - Live 0xc37dd000 (P)

What does it mean? The module is not loaded but still Live?

ContentLicense: CC BY-SA 4.0


问:
TypeScript complains with and without lib
I'm trying to add an async function in a TypeScript project. The code looks like this:

```<code>chrome.tabs.onUpdated.addListener(async (id, c, t) => { ... });
</code>```

TypeScript complains:

error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your --lib option

When I add lib: ['es2015'] to tsconfig, TypeScript starts complaining about all calls to console.log saying that console is undefined.

答:
The default libs for es5 are DOM,ES5, so if you specify es2015 you will also need to add dom explicitly as console is defined in the dom library. Sample tsconfig.json:

```<code>{
    "compilerOptions": {
        "target": "es5",
        "lib": [
            "es2015",
            "dom"
        ]
    }
}
</code>```

Typescript has a modular approach to the default libraries, so you can include only what is available based on your environment.

Body:
I'm trying to add an async function in a TypeScript project. The code looks like this:

chrome.tabs.onUpdated.addListener(async (id, c, t) => { ... });

TypeScript complains:

error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your --lib option

When I add lib: ['es2015'] to tsconfig, TypeScript starts complaining about all calls to console.log saying that console is undefined.

Body:
The default libs for es5 are DOM,ES5, so if you specify es2015 you will also need to add dom explicitly as console is defined in the dom library. Sample tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "lib": [
            "es2015",
            "dom"
        ]
    }
}

Typescript has a modular approach to the default libraries, so you can include only what is available based on your environment.