问:
Public Properties instead of PRIVATE fields
First just to clarify and avoid unnecessary duplicate tagging, this question is not a duplicate of this one, neither a duplicate of this other one or others I have already searched. Why? they all talk about public fields or private fields WITH the classical C#'s "properties".

My question is why should I write something like this (Public Properties)

```<code>class myClass{

public int AValue{get; set;}
}
</code>```

when I can write instead (Private fields  without any properties involved) (Just classic old C++ style way of writing things)

```<code>class myClass{
private int aValue;
public int getValue{ return aValue;}
public void setValue(int value){ aValue=value;}
</code>```

I am scratching my head, reading many many resources, answers and questions, and no one of them answer this question. They all talk about the advantages over public fiels (which I am not asking about) or about the advantages of the new automatic properties over the old ones (which I am not asking either).

I guess my question is why C# does not use the same way of writing that has worked well in Java or C++ that works well. I don't see any advantage. I would very much appreciate someone teaches me the advantage because afaik is not written anywhere else. (not even in my C# books)

答:
From my understanding the public properties that you are referring to are merely syntactic sugar wrapping the pattern that you describe above.

It comes down to readablity and platform standards I guess. While there is nothing wrong with the way that you are talking about, we also need to consider maintainability. To another .Net developer, that pattern does not fit what they are used to and could cause confusion.

And the there is the superficial reason, it is just a lot more code to write. Especially when you have something like a DTO.

Body:
First just to clarify and avoid unnecessary duplicate tagging, this question is not a duplicate of this one, neither a duplicate of this other one or others I have already searched. Why? they all talk about public fields or private fields WITH the classical C#'s "properties".

My question is why should I write something like this (Public Properties)

class myClass{

public int AValue{get; set;}
}

when I can write instead (Private fields  without any properties involved) (Just classic old C++ style way of writing things)

class myClass{
private int aValue;
public int getValue{ return aValue;}
public void setValue(int value){ aValue=value;}

I am scratching my head, reading many many resources, answers and questions, and no one of them answer this question. They all talk about the advantages over public fiels (which I am not asking about) or about the advantages of the new automatic properties over the old ones (which I am not asking either).

I guess my question is why C# does not use the same way of writing that has worked well in Java or C++ that works well. I don't see any advantage. I would very much appreciate someone teaches me the advantage because afaik is not written anywhere else. (not even in my C# books)


来源: stackexchange

问:
How to create groupby subplots in Pandas?
I've got a dataframe with timeseries data of crime with a facet on offence (which looks like the format below). What I'd like to perform a groupby plot on the dataframe so that it's possible to explore trends in crime over time.

```<code>    Offence                     Rolling year total number of offences       Month
0   Criminal damage and arson   1001                                        2003-03-31
1   Drug offences               66                                         2003-03-31
2   All other theft offences    617                                   2003-03-31
3   Bicycle theft               92                                    2003-03-31
4   Domestic burglary           282                                   2003-03-31
</code>```

I've got some code which does the job, but it's a bit clumsy and it loses the time series formatting that Pandas delivers on a single plot. (I've included an image to illustrate). Can anyone suggest an idiom for such plots that I can use?

I would turn to Seaborn but I can't work out how to format the xlabel as timeseries.

```<code>subs = []
for idx, (i, g) in enumerate(df.groupby("Offence")):
        subs.append({"data": g.set_index("Month").resample("QS-APR", how="sum").ix["2010":],
                     "title":i})

ax = plt.figure(figsize=(25,15))
for i,g in enumerate(subs):
    plt.subplot(5, 5, i)
    plt.plot(g['data'])
    plt.title(g['title'])
    plt.xlabel("Time")
    plt.ylabel("No. of crimes")
    plt.tight_layout()
</code>```

答:
Altair can work great in such cases.

```<code>import matplotlib.pyplot as plt
import pandas as pd
import quandl as ql

df = ql.get(["NSE/OIL.1", "WIKI/AAPL.1"], start_date="2013-1-1")
df.columns = ['OIL', 'AAPL']
df['year'] = df.index.year

from altair import *
</code>```

Viz #1- No color by year/No columns by year

```<code>Chart(df).mark_point(size=1).encode(x='AAPL',y='OIL').configure_cell(width=200, height=150)
</code>```

Viz #2- No color by year/columns by year

```<code>Chart(df).mark_point(size=1).encode(x='AAPL',y='OIL', column='year').configure_cell(width=140, height=70).configure_facet_cell(strokeWidth=0)
</code>```

Viz #3- Color by year

```<code>Chart(df).mark_point(size=1).encode(x='AAPL',y='OIL', color='year:N').configure_cell(width=140, height=70)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got a dataframe with timeseries data of crime with a facet on offence (which looks like the format below). What I'd like to perform a groupby plot on the dataframe so that it's possible to explore trends in crime over time.

    Offence                     Rolling year total number of offences       Month
0   Criminal damage and arson   1001                                        2003-03-31
1   Drug offences               66                                         2003-03-31
2   All other theft offences    617                                   2003-03-31
3   Bicycle theft               92                                    2003-03-31
4   Domestic burglary           282                                   2003-03-31

I've got some code which does the job, but it's a bit clumsy and it loses the time series formatting that Pandas delivers on a single plot. (I've included an image to illustrate). Can anyone suggest an idiom for such plots that I can use?

I would turn to Seaborn but I can't work out how to format the xlabel as timeseries.

subs = []
for idx, (i, g) in enumerate(df.groupby("Offence")):
        subs.append({"data": g.set_index("Month").resample("QS-APR", how="sum").ix["2010":],
                     "title":i})

ax = plt.figure(figsize=(25,15))
for i,g in enumerate(subs):
    plt.subplot(5, 5, i)
    plt.plot(g['data'])
    plt.title(g['title'])
    plt.xlabel("Time")
    plt.ylabel("No. of crimes")
    plt.tight_layout()

Body:
Altair can work great in such cases.

import matplotlib.pyplot as plt
import pandas as pd
import quandl as ql

df = ql.get(["NSE/OIL.1", "WIKI/AAPL.1"], start_date="2013-1-1")
df.columns = ['OIL', 'AAPL']
df['year'] = df.index.year

from altair import *

Viz #1- No color by year/No columns by year

Chart(df).mark_point(size=1).encode(x='AAPL',y='OIL').configure_cell(width=200, height=150)

Viz #2- No color by year/columns by year

Chart(df).mark_point(size=1).encode(x='AAPL',y='OIL', column='year').configure_cell(width=140, height=70).configure_facet_cell(strokeWidth=0)

Viz #3- Color by year

Chart(df).mark_point(size=1).encode(x='AAPL',y='OIL', color='year:N').configure_cell(width=140, height=70)

ContentLicense: CC BY-SA 3.0


问:
Wamp apache rotatelog weird issue
I am trying to use wamp apache's rotatelog function to organize daily logs. However, I noticed that the access log is written to two places. The first file is the original access_log.log and the second file is written to the defined rotated log file.

The code added to httpd.conf to enable rotatelog is as follow.

```<code>CustomLog "|C:/wamp64/bin/apache/apache2.4.23/bin/rotatelogs.exe C:/wamp64/backup/logs/apache/access_log/access_log_%d-%m-%y.log 86400" common
ErrorLog "|C:/wamp64/bin/apache/apache2.4.23/bin/rotatelogs.exe C:/wamp64/backup/logs/apache/error_log/error_log_%d-%m-%y.log 86400"
</code>```

Initially, I thought that enabling rotatelog will only write access log and error log to one file on a daily basics but it doesn't looks like it. Anyone know which part went wrong?

答: I just noticed that I need to comment out the original CustomLog and ErrorLog configuration in httpd.conf and then add in the codes that I shown in the question. That would configure apache to only write to 1 access log file and error log file.</p>

Title: Wamp apache rotatelog weird issue

Body:
I am trying to use wamp apache's rotatelog function to organize daily logs. However, I noticed that the access log is written to two places. The first file is the original access_log.log and the second file is written to the defined rotated log file.

The code added to httpd.conf to enable rotatelog is as follow.

CustomLog "|C:/wamp64/bin/apache/apache2.4.23/bin/rotatelogs.exe C:/wamp64/backup/logs/apache/access_log/access_log_%d-%m-%y.log 86400" common
ErrorLog "|C:/wamp64/bin/apache/apache2.4.23/bin/rotatelogs.exe C:/wamp64/backup/logs/apache/error_log/error_log_%d-%m-%y.log 86400"

Initially, I thought that enabling rotatelog will only write access log and error log to one file on a daily basics but it doesn't looks like it. Anyone know which part went wrong?


问:
Sending build log as content of the email from a Jenkins Job
I am using Jenking DSL Plugin/Groovy to send email once the job ran successful.

```<code>   static void sendEmail(Job job, String jobName) {
    job.with {
        publishers {
            extendedEmail {
                recipientList('xyzcoders@xyz.com')
                defaultSubject("Jenkins Job started : ${jobName}")
                defaultContent("See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/")
                contentType('text/html')
                triggers {
                    failure {
                        content("See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/")
                        contentType('text/html')
                        recipientList('xyzcoder@xyz.com')
                        subject("Build Failed in Jenkins: ${jobName}")
                    }
                    success {
                        content('See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/ ``` ${BUILD_LOG, maxLines=30, escapeHtml=false} ```')
                        contentType('text/html')
                        recipientList('xyzcoder@xyz.com')
                        subject("Build Success in Jenkins: ${jobName}")
                    }
                }
            }
        }
    }
}
</code>```

In the content section

```<code>content('See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/ ``` ${BUILD_LOG, maxLines=30, escapeHtml=false} ```')
</code>```

if i use singe quotation then i am able to print log as the content of the email but nor the job name and if i use double quotation then i able to print the job name but not the build log.

How can i print both the job name and build log in the email ?

答:
String interpolation only works with double quoted strings, so change the quotes to double quotes.

When you say that BUILD_LOG expansion doesn't work afterwards than the var is not expanded by Groovy but by Jenkins itself. So try the following:

```<code>content("See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/ " + '``` ${BUILD_LOG, maxLines=30, escapeHtml=false} ```')
</code>```

or you escape the $:

```<code>content("See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/ ``` \${BUILD_LOG, maxLines=30, escapeHtml=false} ```")
</code>```

Body:
I am using Jenking DSL Plugin/Groovy to send email once the job ran successful.

   static void sendEmail(Job job, String jobName) {
    job.with {
        publishers {
            extendedEmail {
                recipientList('xyzcoders@xyz.com')
                defaultSubject("Jenkins Job started : ${jobName}")
                defaultContent("See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/")
                contentType('text/html')
                triggers {
                    failure {
                        content("See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/")
                        contentType('text/html')
                        recipientList('xyzcoder@xyz.com')
                        subject("Build Failed in Jenkins: ${jobName}")
                    }
                    success {
                        content('See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/
 ${BUILD_LOG, maxLines=30, escapeHtml=false}
')
                        contentType('text/html')
                        recipientList('xyzcoder@xyz.com')
                        subject("Build Success in Jenkins: ${jobName}")
                    }
                }
            }
        }
    }
}

In the content section

content('See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/
 ${BUILD_LOG, maxLines=30, escapeHtml=false}
')

if i use singe quotation then i am able to print log as the content of the email but nor the job name and if i use double quotation then i able to print the job name but not the build log.

How can i print both the job name and build log in the email ?

Body:
String interpolation only works with double quoted strings, so change the quotes to double quotes.

When you say that BUILD_LOG expansion doesn't work afterwards than the var is not expanded by Groovy but by Jenkins itself. So try the following:

content("See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/ " + '<pre> ${BUILD_LOG, maxLines=30, escapeHtml=false} </pre>')

or you escape the $:

content("See the latest build in the jenkins job here https://jenkins.xyz.com/job/${jobName}/ <pre> \${BUILD_LOG, maxLines=30, escapeHtml=false} </pre>")


问:
PHP while loop modify last iteration
I am trying to generate a JSON file from PHP. So far I have the following output:

```<code>"students":[
    {"name": "John"},
    {"name": "Alex"},
    {"name": "Siri"},
]
</code>```

There is a comma after each student, when I clearly have to remove the final comma. Normally I would perform a while loop with an if statement. However, my database structure makes this situation different.

My PHP code looks like so:

```<code>    while ($getschools = $schools->fetch_assoc()){
        $findschools = $dbcon->query("SELECT *
            FROM school_".$getstate['texas']."
            WHERE students = '".$studentGPA['best']."'");
        while ($beststudents = $findschools->fetch_assoc()){
            $jsonfield.= '{"name":"'.$getstudent['firstname'].'"},';
        }
    }
</code>```

The code might have a few missing parts, but hopefully the context is clear. I am using php variables from previous fetch requests to acquire data from multiple tables.

In my example there are multiple tables corresponding to the schools in Texas. I am getting the firstnames of every student from those multiple schools (or tables). I am attempting to apply this information to a JSON output.

The $jsonfield line shows the loop portion of my code. I am trying to figure out how to implement a code like this in my example:

```<code>$i = 0;
$countstudents = $getschools->num_rows;
if ($i < $countstudents){
$jsonfield.=',';
}
</code>```

This way my commas are only applied to the parts of my data that are not the final iteration of my loop.

答:
```<code> while ($getschools = $schools-            >fetch_assoc()){
 $findschools = $dbcon->query("SELECT *     FROM school_".$getstate['texas']." WHERE      students = '".$studentGPA['best']."'");
   while ($beststudents = $findschools->fetch_assoc()){
  $jsonfield.= '{"name":"'.$getstudent['firstname'].'"},';
 $i = 0;
 $countstudents = $getschool->num_rows;
if($i+1 < $countstudents){  //if next index is    smaller than the count then add comma else don't and loop will be terminated
    $jsonfield.=',';
      }
   }
 }
</code>```

Title: PHP while loop modify last iteration

Body:
I am trying to generate a JSON file from PHP. So far I have the following output:

"students":[
    {"name": "John"},
    {"name": "Alex"},
    {"name": "Siri"},
]

There is a comma after each student, when I clearly have to remove the final comma. Normally I would perform a while loop with an if statement. However, my database structure makes this situation different.

My PHP code looks like so:

    while ($getschools = $schools->fetch_assoc()){
        $findschools = $dbcon->query("SELECT *
            FROM school_".$getstate['texas']."
            WHERE students = '".$studentGPA['best']."'");
        while ($beststudents = $findschools->fetch_assoc()){
            $jsonfield.= '{"name":"'.$getstudent['firstname'].'"},';
        }
    }

The code might have a few missing parts, but hopefully the context is clear. I am using php variables from previous fetch requests to acquire data from multiple tables.

In my example there are multiple tables corresponding to the schools in Texas. I am getting the firstnames of every student from those multiple schools (or tables). I am attempting to apply this information to a JSON output.

The $jsonfield line shows the loop portion of my code. I am trying to figure out how to implement a code like this in my example:

$i = 0;
$countstudents = $getschools->num_rows;
if ($i < $countstudents){
$jsonfield.=',';
}

This way my commas are only applied to the parts of my data that are not the final iteration of my loop.


问:
Confused with Type conversions in golang
I recently tried to learn golang. But I got confused with this code from https://tour.golang.org/basics/13.

```<code>package main

import (
    "fmt"
    "math"
)

func main() {
    var x, y int = 3, 4
    var f float64 = math.Sqrt(float64(x*x + y*y))
    var z uint = uint(f)
    fmt.Println(x, y, z)
}
</code>```

That one works well. Then I tried

var f = math.Sqrt(9 + 16)

which also works. But when I change it to var f = math.Sqrt(x*x + y*y) why is it not working? It says cannot use x * x + y * y (type int) as type float64 in argument to math.Sqrt

I have javascript background, and I somehow can't understand the code above.

答:
The math.Sqrt function signature:

```<code>func Sqrt(x float64) float64
</code>```

requires that you pass float64

In this case:

```<code>var f float64 = math.Sqrt(float64(x*x + y*y))
</code>```

You are converting to float64 directly

In this case:

```<code>var f = math.Sqrt(x*x + y*y)
</code>```

you are passing an int, when float64 is required.

In this case:

```<code>var f = math.Sqrt(9 + 16)
</code>```

The compiler is able to infer the type, and pass float64 for you.

Body:
I recently tried to learn golang. But I got confused with this code from https://tour.golang.org/basics/13.

package main

import (
    "fmt"
    "math"
)

func main() {
    var x, y int = 3, 4
    var f float64 = math.Sqrt(float64(x*x + y*y))
    var z uint = uint(f)
    fmt.Println(x, y, z)
}

That one works well. Then I tried

var f = math.Sqrt(9 + 16)

which also works. But when I change it to var f = math.Sqrt(x*x + y*y) why is it not working? It says cannot use x * x + y * y (type int) as type float64 in argument to math.Sqrt

I have javascript background, and I somehow can't understand the code above.

Body:
The math.Sqrt function signature:

func Sqrt(x float64) float64

requires that you pass float64

In this case:

var f float64 = math.Sqrt(float64(x*x + y*y))

You are converting to float64 directly

In this case:

var f = math.Sqrt(x*x + y*y)

you are passing an int, when float64 is required.

In this case:

var f = math.Sqrt(9 + 16)

The compiler is able to infer the type, and pass float64 for you.


问:
How do you rotate a two dimensional array?
Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.

```<code>[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
</code>```

Becomes:

```<code>[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
</code>```

Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?

答:
PHP Solution for clockwise & counterclockwise

```<code>$aMatrix = array(
    array( 1, 2, 3 ),
    array( 4, 5, 6 ),
    array( 7, 8, 9 )
    );

function CounterClockwise( $aMatrix )
{
    $iCount  = count( $aMatrix );
    $aReturn = array();
    for( $y = 0; $y < $iCount; ++$y )
    {
        for( $x = 0; $x < $iCount; ++$x )
        {
            $aReturn[ $iCount - $x - 1 ][ $y ] = $aMatrix[ $y ][ $x ];
        }
    }
    return $aReturn;
}

function Clockwise( $aMatrix )
{
    $iCount  = count( $aMatrix );
    $aReturn = array();
    for( $y = 0; $y < $iCount; ++$y )
    {
        for( $x = 0; $x < $iCount; ++$x )
        {
            $aReturn[ $x ][ $iCount - $y - 1 ] = $aMatrix[ $y ][ $x ];
        }
    }
    return $aReturn;
}

function printMatrix( $aMatrix )
{
    $iCount = count( $aMatrix );
    for( $x = 0; $x < $iCount; ++$x )
    {
        for( $y = 0; $y < $iCount; ++$y )
        {
            echo $aMatrix[ $x ][ $y ];
            echo " ";
        }
        echo "\n";
    }
}
printMatrix( $aMatrix );
echo "\n";
$aNewMatrix = CounterClockwise( $aMatrix );
printMatrix( $aNewMatrix );
echo "\n";
$aNewMatrix = Clockwise( $aMatrix );
printMatrix( $aNewMatrix );
</code>```

OwnerDisplayName: swilliams

Body:
Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.

[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]

Becomes:

[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]

Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?

LastEditorDisplayName: Jakub Šturc

Body:
PHP Solution for clockwise & counterclockwise

$aMatrix = array(
    array( 1, 2, 3 ),
    array( 4, 5, 6 ),
    array( 7, 8, 9 )
    );

function CounterClockwise( $aMatrix )
{
    $iCount  = count( $aMatrix );
    $aReturn = array();
    for( $y = 0; $y < $iCount; ++$y )
    {
        for( $x = 0; $x < $iCount; ++$x )
        {
            $aReturn[ $iCount - $x - 1 ][ $y ] = $aMatrix[ $y ][ $x ];
        }
    }
    return $aReturn;
}

function Clockwise( $aMatrix )
{
    $iCount  = count( $aMatrix );
    $aReturn = array();
    for( $y = 0; $y < $iCount; ++$y )
    {
        for( $x = 0; $x < $iCount; ++$x )
        {
            $aReturn[ $x ][ $iCount - $y - 1 ] = $aMatrix[ $y ][ $x ];
        }
    }
    return $aReturn;
}

function printMatrix( $aMatrix )
{
    $iCount = count( $aMatrix );
    for( $x = 0; $x < $iCount; ++$x )
    {
        for( $y = 0; $y < $iCount; ++$y )
        {
            echo $aMatrix[ $x ][ $y ];
            echo " ";
        }
        echo "\n";
    }
}
printMatrix( $aMatrix );
echo "\n";
$aNewMatrix = CounterClockwise( $aMatrix );
printMatrix( $aNewMatrix );
echo "\n";
$aNewMatrix = Clockwise( $aMatrix );
printMatrix( $aNewMatrix );


问:
Ambiguous reference to member `jsonObject(with:options:)` when trying to get data from json
I'm new to Swift and while making one of the tutorials (fairly old) which involves getting credentials from a server through php which returns a JSON, but I'm stuck with the error Ambiguous reference to member jsonObject(with:options:) in the json var, I've searched and trying applying the different solutions but to no avail. :(

Thank you for your time and help.

here is my code:

```<code>let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;

if((userEmail?.isEmpty)! || (userPassword?.isEmpty)!) {
    displayMyAlertMessage(userMessage: "All Fields are required.")
    return;
}

let myUrl = URL(string: "/UserLogin.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "email\(userEmail)&password=\(userPassword)";

request.httpBody = postString.data(using: String.Encoding.utf8);

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, URLResponse, error in

    if error != nil {
        //print = ("error=\(error)");
        return
    }

    var err: Error?
    var json = JSONSerialization.jsonObject(with: data, options: .mutableContainers, error: &err) as? NSDictionary

    if let parseJSON = json {
        var resultValue:String = parseJSON["status"] as String!;
        print("result: \(resultValue)")

        if(resultValue == "Success") {
            //Login Succesful
            UserDefaults.standard.set(true, forKey:"isUserLoggedIn");
            UserDefaults.standard.synchronize();
            self.dismiss(animated: true, completion: nil);

        }
    }
}

task.resume()
</code>```

答:
There are two major issues:

The actual error occurs because the response parameter in the completion block is wrong. Rather than the type URLResponse it must be a parameter label / variable.

```<code>let task = URLSession.shared.dataTask(with: request) {  data, response, error in
</code>```

Since you are using Swift 3 there is no error parameter in jsonObject(with. The method does throw, you need a do - catch block. And – as always – the option .mutableContainers is completely useless in Swift. Omit the parameter.

```<code>do {
    if let parseJSON = try JSONSerialization.jsonObject(with: data) as? [String:Any],
       let resultValue = parseJSON["status"] as? String {
          print("result: ", resultValue)

          if resultValue == "Success" {
              //Login Succesful
              UserDefaults.standard.set(true, forKey:"isUserLoggedIn")
              self.dismiss(animated: true, completion: nil)
          }
    }
} catch {
  print(error)
}
</code>```

Some other notes:

To check the text fields safely use optional binding

```<code>guard let userEmail = userEmailTextField.text, !userEmail.isEmpty, let userPassword = userPasswordTextField.text, !userPassword.isEmpty else {
    displayMyAlertMessage(userMessage: "All Fields are required.")
    return
}
</code>```

Declare Swift constants always as let (for example resultValue)

Do not use NSArray / NSDictionary in Swift. Use native types.

Do not use parentheses around if conditions and trailing semicolons. They are not needed in Swift.

UserDefaults.standard.synchronize() is not needed either.

String.Encoding.utf8 can be reduced to just .utf8.

Body:
I'm new to Swift and while making one of the tutorials (fairly old) which involves getting credentials from a server through php which returns a JSON, but I'm stuck with the error Ambiguous reference to member jsonObject(with:options:) in the json var, I've searched and trying applying the different solutions but to no avail. :(

Thank you for your time and help.

here is my code:

let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;

if((userEmail?.isEmpty)! || (userPassword?.isEmpty)!) {
    displayMyAlertMessage(userMessage: "All Fields are required.")
    return;
}

let myUrl = URL(string: "/UserLogin.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "email\(userEmail)&password=\(userPassword)";

request.httpBody = postString.data(using: String.Encoding.utf8);

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, URLResponse, error in

    if error != nil {
        //print = ("error=\(error)");
        return
    }

    var err: Error?
    var json = JSONSerialization.jsonObject(with: data, options: .mutableContainers, error: &err) as? NSDictionary

    if let parseJSON = json {
        var resultValue:String = parseJSON["status"] as String!;
        print("result: \(resultValue)")

        if(resultValue == "Success") {
            //Login Succesful
            UserDefaults.standard.set(true, forKey:"isUserLoggedIn");
            UserDefaults.standard.synchronize();
            self.dismiss(animated: true, completion: nil);

        }
    }
}

task.resume()

Body:
There are two major issues:

The actual error occurs because the response parameter in the completion block is wrong. Rather than the type URLResponse it must be a parameter label / variable.

let task = URLSession.shared.dataTask(with: request) {  data, response, error in

Since you are using Swift 3 there is no error parameter in jsonObject(with. The method does throw, you need a do - catch block. And – as always – the option .mutableContainers is completely useless in Swift. Omit the parameter.

do {
    if let parseJSON = try JSONSerialization.jsonObject(with: data) as? [String:Any],
       let resultValue = parseJSON["status"] as? String {
          print("result: ", resultValue)

          if resultValue == "Success" {
              //Login Succesful
              UserDefaults.standard.set(true, forKey:"isUserLoggedIn")
              self.dismiss(animated: true, completion: nil)
          }
    }
} catch {
  print(error)
}

Some other notes:

To check the text fields safely use optional binding

guard let userEmail = userEmailTextField.text, !userEmail.isEmpty, let userPassword = userPasswordTextField.text, !userPassword.isEmpty else {
    displayMyAlertMessage(userMessage: "All Fields are required.")
    return
}

Declare Swift constants always as let (for example resultValue)

Do not use NSArray / NSDictionary in Swift. Use native types.

Do not use parentheses around if conditions and trailing semicolons. They are not needed in Swift.

UserDefaults.standard.synchronize() is not needed either.

String.Encoding.utf8 can be reduced to just .utf8.


问:
Android Async Problems?
I have a function which returns a list after doing an operation on 700 images.
The function takes some time and hence the app freezes. How to overcome this problem?
I am returning a list of all the images to be displayed so I am stuck now.
Any suggestions with a code will be helpful.</p>

答:
Run your code in doInBackground() of Async.

You can also perform your task in async within a service. It will not disturb your app.(If task is too long)

you can get your result in onPostExecute().

Title: Android Async Problems?


问:
How to convert yuy2 to a BITMAP in C++
I'm using a security camera DLL to retreive the image from the camera. The DLL call a function of my program passing the image buffer as a parameter, but the image is in yuy2 format. I need to convert this buffer to RGB, but I tried every formula I found on Internet with no success. Every example I tried (including http://msdn.microsoft.com/en-us/library/aa904813(VS.80).aspx#yuvformats_2) gives me wrong colors.

I'm able to convert the buffer to a BW image using only the Y component of the pixel, but I really need the color picture. I debugged (assembly only) the DLL that shows the image in the screen and it uses DirectDraw to do this.

ContentLicense: CC BY-SA 2.5

Title: How to convert yuy2 to a BITMAP in C++

Body:
Using the information from the Microsoft link in the question:

for (int i = 0;  i < width/2;  ++i)
{
    int y0 = ptrIn[0];
    int u0 = ptrIn[1];
    int y1 = ptrIn[2];
    int v0 = ptrIn[3];
    ptrIn += 4;
    int c = y0 - 16;
    int d = u0 - 128;
    int e = v0 - 128;
    ptrOut[0] = clip(( 298 * c + 516 * d + 128) >> 8); // blue
    ptrOut[1] = clip(( 298 * c - 100 * d - 208 * e + 128) >> 8); // green
    ptrOut[2] = clip(( 298 * c + 409 * e + 128) >> 8); // red
    c = y1 - 16;
    ptrOut[3] = clip(( 298 * c + 516 * d + 128) >> 8); // blue
    ptrOut[4] = clip(( 298 * c - 100 * d - 208 * e + 128) >> 8); // green
    ptrOut[5] = clip(( 298 * c + 409 * e + 128) >> 8); // red
    ptrOut += 6;
}


答: The properties in c# are further encapsulated and eventually translated into an intermediate language of a private field and the corresponding Get Set method, so you don't have to be bothered</p>

Title: Public Properties instead of PRIVATE fields


问:
Elegantly Toggling Many Functions
Let's say I have a handful of functions that do things:

```<code>function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }
</code>```

And then just as many that disable their behaviors:

```<code>function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }
</code>```

Then I put all the 'do' functions in an object so I can dynamically access them by setting what:

```<code>var what = 'things';

var doing = {
    stuff:  function() { doStuff(); },
    things: function() { doThings(); },
    it:     function() { doIt(); },
    this:   function() { doThis(); },
    that:   function() { doThat(); }
};

doing[what](); //console logs 'doing things'
</code>```

Is there a way to go about enabling one do function while iterating through all the non-matching stop functions?

For example, if I do var what = 'this'; doing[what]();, I want it to not only doThis(); but also stopStuff(); stopThings(); stopIt(); stopThat();

I'm having trouble coming up with an elegant method that doesn't involve lengthy if statements or case/switch.

答:
Two way you can do it depending on the running a extra function cost.

Call all the stop function before starting a new do function.

OR filter the particular stop function.

```<code>            function doStuff() {
            console.log('doing stuff');
        }

        function doThings() {
            console.log('doing things');
        }

        function doIt() {
            console.log('doing it');
        }

        function doThis() {
            console.log('doing this');
        }

        function doThat() {
            console.log('doing that');
        }

        function stopStuff() {
            console.log('stopping stuff');
        }

        function stopThings() {
            console.log('stopping things');
        }

        function stopIt() {
            console.log('stopping it');
        }

        function stopThis() {
            console.log('stopping this');
        }

        function stopThat() {
            console.log('stopping that');
        }

        var what = 'things';

        var doing = {
            stuff: function() {
                doStuff();
            },
            things: function() {
                doThings();
            },
            it: function() {
                doIt();
            },
            this: function() {
                doThis();
            },
            that: function() {
                doThat();
            }
        };

        var stopping = {
            stuff: function() {
                stopStuff();
            },
            things: function() {
                stopThings();
            },
            it: function() {
                stopIt();
            },
            this: function() {
                stopThis();
            },
            that: function() {
                stopThat();
            }
        };

        var stopKeys = Object.keys(stopping);

        function stopsOthers(doing) {
            arr = stopKeys.filter(function(item) {
                return item !== doing;
            });
            arr.forEach(function(key) {
                stopping[key]();
            });
        }
        stopsOthers(what);
        doing[what]();
</code>```

Title: Elegantly Toggling Many Functions

Body:
Let's say I have a handful of functions that do things:

function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }

And then just as many that disable their behaviors:

function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }

Then I put all the 'do' functions in an object so I can dynamically access them by setting what:

var what = 'things';

var doing = {
    stuff:  function() { doStuff(); },
    things: function() { doThings(); },
    it:     function() { doIt(); },
    this:   function() { doThis(); },
    that:   function() { doThat(); }
};

doing[what](); //console logs 'doing things'

Is there a way to go about enabling one do function while iterating through all the non-matching stop functions?

For example, if I do var what = 'this'; doing[what]();, I want it to not only doThis(); but also stopStuff(); stopThings(); stopIt(); stopThat();

I'm having trouble coming up with an elegant method that doesn't involve lengthy if statements or case/switch.

Body:
Two way you can do it depending on the running a extra function cost.

Call all the stop function before starting a new do function.

OR filter the particular stop function.

            function doStuff() {
            console.log('doing stuff');
        }

        function doThings() {
            console.log('doing things');
        }

        function doIt() {
            console.log('doing it');
        }

        function doThis() {
            console.log('doing this');
        }

        function doThat() {
            console.log('doing that');
        }

        function stopStuff() {
            console.log('stopping stuff');
        }

        function stopThings() {
            console.log('stopping things');
        }

        function stopIt() {
            console.log('stopping it');
        }

        function stopThis() {
            console.log('stopping this');
        }

        function stopThat() {
            console.log('stopping that');
        }

        var what = 'things';

        var doing = {
            stuff: function() {
                doStuff();
            },
            things: function() {
                doThings();
            },
            it: function() {
                doIt();
            },
            this: function() {
                doThis();
            },
            that: function() {
                doThat();
            }
        };

        var stopping = {
            stuff: function() {
                stopStuff();
            },
            things: function() {
                stopThings();
            },
            it: function() {
                stopIt();
            },
            this: function() {
                stopThis();
            },
            that: function() {
                stopThat();
            }
        };

        var stopKeys = Object.keys(stopping);

        function stopsOthers(doing) {
            arr = stopKeys.filter(function(item) {
                return item !== doing;
            });
            arr.forEach(function(key) {
                stopping[key]();
            });
        }
        stopsOthers(what);
        doing[what]();


答:
Auto-accessors are syntactical sugar for exactly that. The generated code has a backing field and get/set methods. Fields don't have accessors, whereas properties do.

Public/private is about encapsulation/security, i.e. who should be able to access your information.


问:
Problems adding a COM component reference to a VB.NET project
I have a third party COM dll that I'm trying to add to a vb.net (2008 express) project. I put the dll in C:\WINDOWS\system32\ and registered it with "regsvr32 vxncom.dll". When I go to projects > add reference and go to the COM tab it shows up in the list of available components/libraries. But, when I select the library and hit ok, visual studio complains: "A reference to 'vxncom 4.0 Library' could not be added. Could not register the ActiveX type library 'C:\WINDOWS\system32\vxncom.dll'."

The project I am doing this in is an example provided by the folks who distribute the dll. The component also fails to be added when I start a new (blank) vb.net project.

UPDATE 1:

I ran dependency walker on the dll in question and here's what I got in the error log:

Error: At least one module has an unresolved import due to a missing export function in an implicitly dependent module.

The module in question seems to be libeay32.dll, but it already exists in C:\WINDOWS\system32.

UPDATE 2:

I went to the openssl site and downloaded and used their installer to update the libeay32.dll. I ran dependency walker again on vxncom.dll, and there were no errors. Went back to visual studio and it still didn't want to add the reference. Exact same error as before.

答: Assuming you haven't fixed it or have moved on to alternatives; and following on from jeffm's answer is libeay32.dll properly registered with the operating system? Re-installing / repairing usually fixes that type of problem (I see it a lot with MS Office and MapPoint where the COM objects occasionally unregister themselves for one reason or another.)</p>

OwnerDisplayName: symbollocks

LastEditorDisplayName: symbollocks


问:
Move files to new folder structure using Terminal
Simple question: I need to move images from an old directory structure to a new one using some shell script in Terminal. The old file structure is as follows:

```<code>Parent.Folder -- Folder1
                 Folder2
                 Folder3
</code>```

In each FolderX, we have more folders:

```<code>Folder1 -- CAM1
           CAM2
           CAM3
</code>```

In each CAM folder we have the images:

```<code>CAM1 -- image1.jpg
        image2.jpg
        image3.jpg
</code>```

I need to switch the folder structure, so that:

```<code>Parent.Folder -- CAM1
                 CAM2
                 CAM3
</code>```

Containing:

```<code>CAM1 -- Folder1 -- image1.jpg
                -- image2.jpg
                -- image3.jpg
     -- Folder2 -- ...etc...
     -- Folder3 -- ...etc...
</code>```

The script would need to be dynamic as I need to apply it to many data sets of different sizes.

Appreciate any assistance. Thanks in advance!

答:
```<code>$ cd parent.folder
$ find . -type f
./Folder3/CAM2/image3.jpg
./Folder3/CAM2/image2.jpg
./Folder3/CAM2/image1.jpg
./Folder3/CAM1/image3.jpg
./Folder3/CAM1/image2.jpg
./Folder3/CAM1/image1.jpg
./Folder2/CAM3/image3.jpg
./Folder2/CAM3/image2.jpg
./Folder2/CAM3/image1.jpg
./Folder2/CAM2/image3.jpg
./Folder2/CAM2/image2.jpg
./Folder2/CAM2/image1.jpg
./Folder2/CAM1/image3.jpg
./Folder2/CAM1/image2.jpg
./Folder2/CAM1/image1.jpg
./Folder1/CAM3/image3.jpg
./Folder1/CAM3/image2.jpg
./Folder1/CAM3/image1.jpg
./Folder1/CAM2/image3.jpg
./Folder1/CAM2/image2.jpg
./Folder1/CAM2/image1.jpg
./Folder1/CAM1/image3.jpg
./Folder1/CAM1/image2.jpg
./Folder1/CAM1/image1.jpg

$ for i in Folder*/CAM*/; do
    mkdir -p "$(basename $i)";
    mv "$i" "$(basename "$i")/$(dirname "$i")";
  done

 $ find . -type f
./CAM3/Folder2/image3.jpg
./CAM3/Folder2/image2.jpg
./CAM3/Folder2/image1.jpg
./CAM3/Folder1/image3.jpg
./CAM3/Folder1/image2.jpg
./CAM3/Folder1/image1.jpg
./CAM2/Folder3/image3.jpg
./CAM2/Folder3/image2.jpg
./CAM2/Folder3/image1.jpg
./CAM2/Folder2/image3.jpg
./CAM2/Folder2/image2.jpg
./CAM2/Folder2/image1.jpg
./CAM2/Folder1/image3.jpg
./CAM2/Folder1/image2.jpg
./CAM2/Folder1/image1.jpg
./CAM1/Folder3/image3.jpg
./CAM1/Folder3/image2.jpg
./CAM1/Folder3/image1.jpg
./CAM1/Folder2/image3.jpg
./CAM1/Folder2/image2.jpg
./CAM1/Folder2/image1.jpg
./CAM1/Folder1/image3.jpg
./CAM1/Folder1/image2.jpg
./CAM1/Folder1/image1.jpg
</code>```

Note that this code assumes certain folder structure that you have mentioned. If what you mentioned in the question is any different from reality, this might not work.

Body:
Simple question: I need to move images from an old directory structure to a new one using some shell script in Terminal. The old file structure is as follows:

Parent.Folder -- Folder1
                 Folder2
                 Folder3

In each FolderX, we have more folders:

Folder1 -- CAM1
           CAM2
           CAM3

In each CAM folder we have the images:

CAM1 -- image1.jpg
        image2.jpg
        image3.jpg

I need to switch the folder structure, so that:

Parent.Folder -- CAM1
                 CAM2
                 CAM3

Containing:

CAM1 -- Folder1 -- image1.jpg
                -- image2.jpg
                -- image3.jpg
     -- Folder2 -- ...etc...
     -- Folder3 -- ...etc...

The script would need to be dynamic as I need to apply it to many data sets of different sizes.

Appreciate any assistance. Thanks in advance!

Body:
$ cd parent.folder
$ find . -type f
./Folder3/CAM2/image3.jpg
./Folder3/CAM2/image2.jpg
./Folder3/CAM2/image1.jpg
./Folder3/CAM1/image3.jpg
./Folder3/CAM1/image2.jpg
./Folder3/CAM1/image1.jpg
./Folder2/CAM3/image3.jpg
./Folder2/CAM3/image2.jpg
./Folder2/CAM3/image1.jpg
./Folder2/CAM2/image3.jpg
./Folder2/CAM2/image2.jpg
./Folder2/CAM2/image1.jpg
./Folder2/CAM1/image3.jpg
./Folder2/CAM1/image2.jpg
./Folder2/CAM1/image1.jpg
./Folder1/CAM3/image3.jpg
./Folder1/CAM3/image2.jpg
./Folder1/CAM3/image1.jpg
./Folder1/CAM2/image3.jpg
./Folder1/CAM2/image2.jpg
./Folder1/CAM2/image1.jpg
./Folder1/CAM1/image3.jpg
./Folder1/CAM1/image2.jpg
./Folder1/CAM1/image1.jpg

$ for i in Folder*/CAM*/; do
    mkdir -p "$(basename $i)";
    mv "$i" "$(basename "$i")/$(dirname "$i")";
  done

 $ find . -type f
./CAM3/Folder2/image3.jpg
./CAM3/Folder2/image2.jpg
./CAM3/Folder2/image1.jpg
./CAM3/Folder1/image3.jpg
./CAM3/Folder1/image2.jpg
./CAM3/Folder1/image1.jpg
./CAM2/Folder3/image3.jpg
./CAM2/Folder3/image2.jpg
./CAM2/Folder3/image1.jpg
./CAM2/Folder2/image3.jpg
./CAM2/Folder2/image2.jpg
./CAM2/Folder2/image1.jpg
./CAM2/Folder1/image3.jpg
./CAM2/Folder1/image2.jpg
./CAM2/Folder1/image1.jpg
./CAM1/Folder3/image3.jpg
./CAM1/Folder3/image2.jpg
./CAM1/Folder3/image1.jpg
./CAM1/Folder2/image3.jpg
./CAM1/Folder2/image2.jpg
./CAM1/Folder2/image1.jpg
./CAM1/Folder1/image3.jpg
./CAM1/Folder1/image2.jpg
./CAM1/Folder1/image1.jpg

Note that this code assumes certain folder structure that you have mentioned. If what you mentioned in the question is any different from reality, this might not work.


问:
How to use OR operator in Linq
I want to use OR function in my linq query.
Ex:
Sql:

```<code>select * from tblusers where userid=1 and status='a' or status='b';
</code>```

Linq:

```<code>var result= _Repository.selectAll().where(x=>x.UserID==1 && x.status=="a" OR x.status=="B");
</code>```

It's does work for linq query. so does anyone have any idea?

答:
Or other approach with List.Contains, which generates sql query like

SELECT * FROM tblusers WHERE userid=1 AND status IN ('a','b');

```<code>var acceptedStatus = new List<string> { 'a', 'b' };
var result= _Repository.selectAll()
                       .Where(x => x.UserID == 1)
                       .Where(x => acceptedStatus.Contains(x.Status));
</code>```

Notice that instead of && operator you can use another Where function and chain them. Can be more readable then fit all conditions in one line.

Title: How to use OR operator in Linq

Body:
I want to use OR function in my linq query.
Ex:
Sql:

select * from tblusers where userid=1 and status='a' or status='b';

Linq:

var result= _Repository.selectAll().where(x=>x.UserID==1 && x.status=="a" OR x.status=="B");

It's does work for linq query. so does anyone have any idea?

Body:
Or other approach with List.Contains, which generates sql query like

SELECT * FROM tblusers WHERE userid=1 AND status IN ('a','b');

var acceptedStatus = new List<string> { 'a', 'b' };
var result= _Repository.selectAll()
                       .Where(x => x.UserID == 1)
                       .Where(x => acceptedStatus.Contains(x.Status));

Notice that instead of && operator you can use another Where function and chain them. Can be more readable then fit all conditions in one line.


问:
Send push notifications from server with FCM
Recently I asked a question on sending push notifications using GCM: Send push notifications to Android. Now that there is FCM, I am wondering how different it would be from the server side development. Coding wise, are they the same? Where can I find example FCM codes showing sending push notifications from server to Android device?

Do I need to download any JAR library for sending notifications to FCM using Java codes? The example codes in Send push notifications to Android shows sending push notifications using GCM and a server side GCM JAR file is required.

However, another example in https://www.quora.com/How-do-I-make-a-post-request-to-a-GCM-server-in-Java-to-push-a-notification-to-the-client-app shows sending push notifications using GCM and no server side GCM JAR file is required since it is just sending via an HTTP connection. Can the same codes be used for FCM? The URL used is "https://android.googleapis.com/gcm/send". What would be the equivalent URL for FCM?

答:
I have created a lib for FCM notification Server. Just use it like GCM lib.

For FCM Server use this code :

GCM Server URL-"android.googleapis.com/gcm/send"

FCM Server URL - "fcm.googleapis.com/fcm/send"

Append https with URL

Sender objSender = new Sender(gAPIKey);

or

Sender objSender = new Sender(gAPIKey,"SERVER_URL");

by DEFAULT FCM SERVER URL IS ASSIGNED

```<code>Message objMessage = new Message.Builder().collapseKey("From FCMServer").timeToLive(3).delayWhileIdle(false)
                .notification(notification)
                .addData("ShortMessage", "Sh").addData("LongMessage", "Long ")
                .build();
        objMulticastResult = objSender.send(objMessage,clientId, 4);
</code>```

Dependency need for this lib is same like GCM lib required (jsonsimple.jar).

Download lib from FCM_Server.jar

Body:
I have created a lib for FCM notification Server. Just use it like GCM lib.

For FCM Server use this code :

GCM Server URL-"android.googleapis.com/gcm/send"

FCM Server URL - "fcm.googleapis.com/fcm/send"

Append https with URL

Sender objSender = new Sender(gAPIKey);

or

Sender objSender = new Sender(gAPIKey,"SERVER_URL");

by DEFAULT FCM SERVER URL IS ASSIGNED

Message objMessage = new Message.Builder().collapseKey("From FCMServer").timeToLive(3).delayWhileIdle(false)
                .notification(notification)
                .addData("ShortMessage", "Sh").addData("LongMessage", "Long ")
                .build();
        objMulticastResult = objSender.send(objMessage,clientId, 4);

Dependency need for this lib is same like GCM lib required (jsonsimple.jar).

Download lib from FCM_Server.jar


问:
Replacing a pandas dataframe column
I have some code which is pulling data into a pandas dataframe.

```<code>df = df[["date","high","low","open","close"]]
</code>```

The data looks like this:

```<code>       date         high          low        open       close
0  1499140800  2615.390000  2600.000000  2610.58000  2603.00000
1  1499155200  2618.785462  2582.002100  2615.00000  2607.00000
2  1499169600  2617.674406  2550.314214  2607.00000  2554.55010
3  1499184000  2572.962113  2519.967440  2554.55010  2519.96744
4  1499198400  2595.654622  2516.000000  2519.96744  2580.00000
</code>```

I am wanting to convert the unix timestamp column with an actual datetime. Earlier in my code am having to import

```<code>from datetime import datetime
</code>```

and it seems to be giving me an error when I try to use datetime.datetime to convert. I can't just use import datetimebecause this gives me an error on my previous import which I need. So my question is twofold. How can I convert the timestamp into a datetime (possibly without using the datetime module?) and how can I overwrite the date column with the new date time before I save into a file?I have tried several approaches but none seem to be giving me any luck..

Title: Replacing a pandas dataframe column

Body:
I have some code which is pulling data into a pandas dataframe.

df = df[["date","high","low","open","close"]]

The data looks like this:

       date         high          low        open       close
0  1499140800  2615.390000  2600.000000  2610.58000  2603.00000
1  1499155200  2618.785462  2582.002100  2615.00000  2607.00000
2  1499169600  2617.674406  2550.314214  2607.00000  2554.55010
3  1499184000  2572.962113  2519.967440  2554.55010  2519.96744
4  1499198400  2595.654622  2516.000000  2519.96744  2580.00000

I am wanting to convert the unix timestamp column with an actual datetime. Earlier in my code am having to import

from datetime import datetime

and it seems to be giving me an error when I try to use datetime.datetime to convert. I can't just use import datetimebecause this gives me an error on my previous import which I need. So my question is twofold. How can I convert the timestamp into a datetime (possibly without using the datetime module?) and how can I overwrite the date column with the new date time before I save into a file?I have tried several approaches but none seem to be giving me any luck..

Body:
Try this:

In [2]: df
Out[2]:
         date         high          low        open       close
0  1499140800  2615.390000  2600.000000  2610.58000  2603.00000
1  1499155200  2618.785462  2582.002100  2615.00000  2607.00000
2  1499169600  2617.674406  2550.314214  2607.00000  2554.55010
3  1499184000  2572.962113  2519.967440  2554.55010  2519.96744
4  1499198400  2595.654622  2516.000000  2519.96744  2580.00000

In [3]: df['date'] = pd.to_datetime(df['date'], unit='s')

In [4]: df
Out[4]:
                 date         high          low        open       close
0 2017-07-04 04:00:00  2615.390000  2600.000000  2610.58000  2603.00000
1 2017-07-04 08:00:00  2618.785462  2582.002100  2615.00000  2607.00000
2 2017-07-04 12:00:00  2617.674406  2550.314214  2607.00000  2554.55010
3 2017-07-04 16:00:00  2572.962113  2519.967440  2554.55010  2519.96744
4 2017-07-04 20:00:00  2595.654622  2516.000000  2519.96744  2580.00000


问:
Set timezone for MYSQL NOW()
On my server i keep a log of operations and this is tracked using the timestamp generated by MYSQL NOW() function.But the problem is that the timestamp generated is in UTC and i want the NOW() function to generate the timestamp corresponding to my local time for Asia/Kolkata. I tried the SET timezone but it is not working

```<code>$queryt="SET time_zone='Asia/Kolkata'";
mysqli_query($mysqli, $queryt))
</code>```

What am i doing wrong?

答:
Your question is not clear but if you want to change date and time value from UTC to your time zone, you can use

```<code>CONVERT_TZ(date, 'UTC',  'Asia/Kolkata')
</code>```

You can select the UTC date and time value in your time zone:

```<code>SELECT CONVERT_TZ(date, 'UTC',  'Asia/Kolkata') AS local FROM table
</code>```

If CONVERT_TZ function does not work, you need to install time zones (time zones should be already stored in MySQL). One note is that you need to store UTC value in your database and later convert to whatever time zone you want.

Title: Set timezone for MYSQL NOW()

Body:
On my server i keep a log of operations and this is tracked using the timestamp generated by MYSQL NOW() function.But the problem is that the timestamp generated is in UTC and i want the NOW() function to generate the timestamp corresponding to my local time for Asia/Kolkata. I tried the SET timezone but it is not working

$queryt="SET time_zone='Asia/Kolkata'";
mysqli_query($mysqli, $queryt))

What am i doing wrong?

Body:
Your question is not clear but if you want to change date and time value from UTC to your time zone, you can use

CONVERT_TZ(date, 'UTC',  'Asia/Kolkata')

You can select the UTC date and time value in your time zone:

SELECT CONVERT_TZ(date, 'UTC',  'Asia/Kolkata') AS local FROM table

If CONVERT_TZ function does not work, you need to install time zones (time zones should be already stored in MySQL). One note is that you need to store UTC value in your database and later convert to whatever time zone you want.


问:
split string of spans into array of spans
I have a block of text wrapped in spans that I need to split into an array.

So currently I have

```<code>var s = `
   <span class="hoverable">c</span>
   <span class="hoverable">o</span>
   <span class="not-hoverable">o</span>`;
</code>```

I need

```<code>var s = [
   "<span class="hoverable">c</span>",
   "<span class="hoverable">o</span>",
   "<span class="not-hoverable">o</span>"];
</code>```

I've tried s.split(/<\/?span>/); to split accounting for  and closing  but

```<code>var s = [
  "<span class="hoverable">c",
  "<span class="hoverable">o",
  "<span class="not-hoverable">o",...]
</code>```

So it's not including the closing span.

答:
You can always use the DOM if you are working in a browser and the value is inside of an element. If it is not and you have a string then you can still use DOM dynamically. Finally, you can use regular expressions.

Here's a round up:

var s = ' ' +
  'c' +
  'o' +
  'o ';
var r2 = s.match(/(.*?)<\/span>/gm);
console.log("using regular expressions");
console.log(r2);

function findWithDOM() {
  console.log("using DOM");
  var elements = [].slice.call(document.querySelectorAll('#myDiv span'));
  console.log(elements);
}

function findWithDynamicDOM() {
  console.log("using Dynamic DOM");
  var element = document.createElement("div");
  element.innerHTML=s;
  var elements = [].slice.call(element.querySelectorAll('span'));
  console.log(elements);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="myDiv"><span class="hoverable">c</span>
  <span class="hoverable">o</span>
  <span class="not-hoverable">o</span>
</div>
<input id='btnFind' onclick='findWithDOM()' value='Find With DOM' type="button" />
<input id='btnFind' onclick='findWithDynamicDOM()' value='Find Dynamic DOM' type="button" /></code>```

Body:
I have a block of text wrapped in spans that I need to split into an array.

So currently I have

var s = `
   c
   o
   o`;

I need

var s = [
   "c",
   "o",
   "o"];

I've tried s.split(/<\/?span>/); to split accounting for  and closing  but

var s = [
  "c",
  "o",
  "o",...]

So it's not including the closing span.

Body:
You can always use the DOM if you are working in a browser and the value is inside of an element. If it is not and you have a string then you can still use DOM dynamically. Finally, you can use regular expressions.

Here's a round up:

var s = ' ' +
  '<span class="hoverable">c</span>' +
  '<span class="hoverable">o</span>' +
  '<span class="not-hoverable">o</span> ';
var r2 = s.match(/<span(.*?)>(.*?)<\/span>/gm);
console.log("using regular expressions");
console.log(r2);

function findWithDOM() {
  console.log("using DOM");
  var elements = [].slice.call(document.querySelectorAll('#myDiv span'));
  console.log(elements);
}

function findWithDynamicDOM() {
  console.log("using Dynamic DOM");
  var element = document.createElement("div");
  element.innerHTML=s;
  var elements = [].slice.call(element.querySelectorAll('span'));
  console.log(elements);
}

<div id="myDiv"><span class="hoverable">c</span>
  <span class="hoverable">o</span>
  <span class="not-hoverable">o</span>
</div>
<input id='btnFind' onclick='findWithDOM()' value='Find With DOM' type="button" />
<input id='btnFind' onclick='findWithDynamicDOM()' value='Find Dynamic DOM' type="button" />


问:
How to group all values by semicolon separated in SQL query
Please help how to achieve data as per shown in attached image

Highlighted rows actually group on Item Number field

Thanks in advance

答:
```<code>SELECT  t2.ItemNumber ,
        STUFF(( SELECT  ',' + CAST(TotalItem AS VARCHAR) + ' x ' + ItemName
                FROM    @MyTable t1
                WHERE   t1.ItemNumber = t2.ItemNumber
              FOR
                XML PATH('')
              ), 1, 1, '') AS NewDescription
FROM    @MyTable t2
GROUP BY t2.ItemNumber
</code>```

DEMO

Body:
SELECT  t2.ItemNumber ,
        STUFF(( SELECT  ',' + CAST(TotalItem AS VARCHAR) + ' x ' + ItemName
                FROM    @MyTable t1
                WHERE   t1.ItemNumber = t2.ItemNumber
              FOR
                XML PATH('')
              ), 1, 1, '') AS NewDescription
FROM    @MyTable t2
GROUP BY t2.ItemNumber

DEMO


问:
componentDidMount and componentDidUpdate error: Cannot dispatch in the middle of a dispatch
I got error of

```<code>Invariant Violation: Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.
</code>```

when using 2 lifecycle method of react to call APIs.

```<code>componentDidMount() {
    const action_id = this.context.router.params.action_id
    if(action_id) {
        this.getMsg(action_id)
    }
}

componentDidUpdate(prevContext) {
    const action_id = this.context.router.params.action_id
    if(!isEqual(prevContext.params.action_id, action_id)){
        this.getMsg(action_id)
    }
}
</code>```

Above step are needed, the code in componentDidMount call an endpoint to get a list msg, the componentDidUpdate detect whether user click back or navigate around, then call the Api. I've no clue how to solve it.

答:
The dispatcher cannot dispatch another action in middle of an action.
To avoid this you can use Promise in your action creater .

Eg:

```<code> return new Promise.Promise(function (resolve, reject) {
            resolve();
        }).then(() => {
            dispatcher.dispatch(your action );
        }).catch();
</code>```

Body:
I got error of

Invariant Violation: Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.

when using 2 lifecycle method of react to call APIs.

componentDidMount() {
    const action_id = this.context.router.params.action_id
    if(action_id) {
        this.getMsg(action_id)
    }
}

componentDidUpdate(prevContext) {
    const action_id = this.context.router.params.action_id
    if(!isEqual(prevContext.params.action_id, action_id)){
        this.getMsg(action_id)
    }
}

Above step are needed, the code in componentDidMount call an endpoint to get a list msg, the componentDidUpdate detect whether user click back or navigate around, then call the Api. I've no clue how to solve it.

Body:
The dispatcher cannot dispatch another action in middle of an action.
To avoid this you can use Promise in your action creater .

Eg:

 return new Promise.Promise(function (resolve, reject) {
            resolve();
        }).then(() => {
            dispatcher.dispatch(your action );
        }).catch();


问:
Is there a way to tell where to look in memory for the specific location of a property of an object?
So this question may be invalid, depending on my understanding,

But let's say we have an object on the heap, say at 0x618000001234

If I use Xcode's memory debugger, to view the memory at that address,
I just see a bunch of information, right?

Now as far as my understanding goes, the first thing you will find at that address is the isa pointer, which is a Class AKA objc_class

and it looks like that just takes up 8 bytes

So in this example:

It looks like the contents of isa is:
011DFFFF9C1B89F9

Great, fine and dandy

So let's say we have a class

```<code>@interface testClass : NSObject
@property int testIntProperty;
@end
</code>```

Assuming there is nothing in memory after the isa, and it goes straight into the properties,
if we looked at the location in memory, of an instance of testClass,
I would expect the first 8 bytes to be the isa, then the next 4 bytes to be the int property, and then the rest doesn't matter

So my question is:
In that example, we can tell that the testIntProperty will be located 8 bytes from the start of the object, just by looking at the header of the property

But is there a way to tell exactly where it's going to be, say if there are 10 properties, and you want to know where the 10th property is?

The reason why I'm asking, is because I want to look at a specific property's pointer, and I'm having a hard time finding it in memory.  At runtime, I get an EXC_BAD_ACCESS, with address 0x18, but I'm curious to actually look in memory at the location I expect that property to exist at, and I want to see the 0x18 in plain sight

答:
In the modern runtime you cannot assume the layout of a class is just the instance variables/properties in order; you can declare these in more than one place - interface and implementation, you have to know what padding is used, you don't know when property backing variables are processed, etc.

However you can easily determine the offset in the debugger. Assuming you are in an instance method of your testClass so self references it enter:

```<code>p (char *)&self->_testIntProperty - (char *)self
</code>```

and it will print the offset. The casts are required to keep the debugger happy.

HTH

Body:
So this question may be invalid, depending on my understanding,

But let's say we have an object on the heap, say at 0x618000001234

If I use Xcode's memory debugger, to view the memory at that address,
I just see a bunch of information, right?

Now as far as my understanding goes, the first thing you will find at that address is the isa pointer, which is a Class AKA objc_class

and it looks like that just takes up 8 bytes

So in this example:

It looks like the contents of isa is:
011DFFFF9C1B89F9

Great, fine and dandy

So let's say we have a class

@interface testClass : NSObject
@property int testIntProperty;
@end

Assuming there is nothing in memory after the isa, and it goes straight into the properties,
if we looked at the location in memory, of an instance of testClass,
I would expect the first 8 bytes to be the isa, then the next 4 bytes to be the int property, and then the rest doesn't matter

So my question is:
In that example, we can tell that the testIntProperty will be located 8 bytes from the start of the object, just by looking at the header of the property

But is there a way to tell exactly where it's going to be, say if there are 10 properties, and you want to know where the 10th property is?

The reason why I'm asking, is because I want to look at a specific property's pointer, and I'm having a hard time finding it in memory.  At runtime, I get an EXC_BAD_ACCESS, with address 0x18, but I'm curious to actually look in memory at the location I expect that property to exist at, and I want to see the 0x18 in plain sight

Body:
In the modern runtime you cannot assume the layout of a class is just the instance variables/properties in order; you can declare these in more than one place - interface and implementation, you have to know what padding is used, you don't know when property backing variables are processed, etc.

However you can easily determine the offset in the debugger. Assuming you are in an instance method of your testClass so self references it enter:

p (char *)&self->_testIntProperty - (char *)self

and it will print the offset. The casts are required to keep the debugger happy.

HTH


问:
Javascript: Client side filling in Input fields on Server side
(I'm scripting in Windows, for use in a Windows 7 gadget)  Hi there, I'm trying to log in to a page on a server machine from a client machine using a ServerXMLHTTP request.  I'm wondering if there's a way to fill in the input fields in the server's input fields and then making the server run the authorization on the information, and return the new URL.  However, right now the main question I have is how would I go about logging in?  Also, I tried passing the log in information in as parameters and it didn't seem to work out very well.</p>

```<code>this.requests[1].open("POST", "https://" + this.address, true);
this.requests[1].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
this.requests[1].send("username=user&password=pass");
</code>```

答:
according to http://it.toolbox.com/wiki/index.php/Sending_ServerXMLHTTP_login_credentials it looks like the username and password are the 4th and 5th parameters respectivly in the open function. So...

```<code>this.requests[1].open("post","https://"+this.address, true, "user_name", "p4ssword");
</code>```

Body:
(I'm scripting in Windows, for use in a Windows 7 gadget)  Hi there, I'm trying to log in to a page on a server machine from a client machine using a ServerXMLHTTP request.  I'm wondering if there's a way to fill in the input fields in the server's input fields and then making the server run the authorization on the information, and return the new URL.  However, right now the main question I have is how would I go about logging in?  Also, I tried passing the log in information in as parameters and it didn't seem to work out very well.

this.requests[1].open("POST", "https://" + this.address, true);
this.requests[1].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
this.requests[1].send("username=user&password=pass");

Body:
according to http://it.toolbox.com/wiki/index.php/Sending_ServerXMLHTTP_login_credentials it looks like the username and password are the 4th and 5th parameters respectivly in the open function. So...

this.requests[1].open("post","https://"+this.address, true, "user_name", "p4ssword");


答:
Adding my 2 cents in here, there is another way you can write your sql query in C# which more or less resembles the sql syntax.

```<code>var result = from x in _Repository.SelectAll() where x.UserID == 1 && (x.Status == "a" || x.Status == "B") select x;
</code>```

This syntax is Query Syntax/Expression where as your snippet is Method Syntax/Expression. Both will achieve same results. Also behind the scene, query syntax is compiled to Method syntax.

At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise.

Title: How to use OR operator in Linq

Body:
Adding my 2 cents in here, there is another way you can write your sql query in C# which more or less resembles the sql syntax.

var result = from x in _Repository.SelectAll() where x.UserID == 1 && (x.Status == "a" || x.Status == "B") select x;

This syntax is Query Syntax/Expression where as your snippet is Method Syntax/Expression. Both will achieve same results. Also behind the scene, query syntax is compiled to Method syntax.

At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise.


问:
Android- Images on RecyclerView GridLayout are at the bottom
This is my current code for Gridlayout:

```<code>image_list.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, true));
</code>```

When I do this, all this images are lined at the bottom, not the top. Anyway I could fix this? Thanks.

答:
Set reverselayout to false

```<code> //Like this
 image_list.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
</code>```

Documentation :

```<code> /**
 * @param context Current context, will be used to access resources.
 * @param spanCount The number of columns or rows in the grid
 * @param orientation Layout orientation. Should be {@link #HORIZONTAL} or {@link
 *                      #VERTICAL}.
 * @param reverseLayout When set to true, layouts from end to start.
 */
public GridLayoutManager(Context context, int spanCount, int orientation,
        boolean reverseLayout) {
    super(context, orientation, reverseLayout);
    setSpanCount(spanCount);
}
</code>```

Body:
This is my current code for Gridlayout:

image_list.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, true));

When I do this, all this images are lined at the bottom, not the top. Anyway I could fix this? Thanks.

Body:
Set reverselayout to false

 //Like this
 image_list.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));

Documentation :

 /**
 * @param context Current context, will be used to access resources.
 * @param spanCount The number of columns or rows in the grid
 * @param orientation Layout orientation. Should be {@link #HORIZONTAL} or {@link
 *                      #VERTICAL}.
 * @param reverseLayout When set to true, layouts from end to start.
 */
public GridLayoutManager(Context context, int spanCount, int orientation,
        boolean reverseLayout) {
    super(context, orientation, reverseLayout);
    setSpanCount(spanCount);
}


问:
Swift 3.0 Remove duplicates in Array of Dictionaries
I am working removing the duplicate Dictionaries in an array of Dictionaries in swift 3.0

The below is the

```<code>let Dict1 : [String : String] = ["messageTo":"Madhu"]
let Dict2 : [String : String] = ["messageTo":"Kiran"]
let Dict3 : [String : String] = ["messageTo":"Raju"]

var arrOfDict = [[String:String]]()
arrOfDict.append(Dict1)
arrOfDict.append(Dict2)
arrOfDict.append(Dict1)
arrOfDict.append(Dict3)
arrOfDict.append(Dict2
print(arrOfDict)

//prints [["messageTo": "Madhu"], ["messageTo": "Kiran"], ["messageTo": "Madhu"], ["messageTo": "Raju"], ["messageTo": "Kiran"]]
</code>```

As you can see there are 2 duplicate dictionaries in the arrOfDict.

can any one help me out in filtering the duplicates using Set or any other approach

答:
```<code>func removeDuplicates(_ arrayOfDicts: [[String: String]]) -> [[String: String]] {
var removeDuplicates = [[String: String]]()
var arrOfDict = [String]()
for dict in arrayOfDicts {
    if let name = dict["messageTo"], ! arrOfDict.contains(name) {
        removeDuplicates.append(dict)
        arrOfDict.append(name)
    }
}
return removeDuplicates
}
</code>```

Body:
I am working removing the duplicate Dictionaries in an array of Dictionaries in swift 3.0

The below is the

let Dict1 : [String : String] = ["messageTo":"Madhu"]
let Dict2 : [String : String] = ["messageTo":"Kiran"]
let Dict3 : [String : String] = ["messageTo":"Raju"]

var arrOfDict = [[String:String]]()
arrOfDict.append(Dict1)
arrOfDict.append(Dict2)
arrOfDict.append(Dict1)
arrOfDict.append(Dict3)
arrOfDict.append(Dict2
print(arrOfDict)

//prints [["messageTo": "Madhu"], ["messageTo": "Kiran"], ["messageTo": "Madhu"], ["messageTo": "Raju"], ["messageTo": "Kiran"]]

As you can see there are 2 duplicate dictionaries in the arrOfDict.

can any one help me out in filtering the duplicates using Set or any other approach


问:
how to tap in content view in didselectrow method in tableview in swift
I am new in ios I am making a project using table view in which I have expanded the table view cell which has 4 Content view.When the table is loaded only first content view show and when I select the row then all content view expands. But I also want that after expanding the all content view cell when I tap on fourth content view then I want to access the indexPath.row in the tapGESTUREAction method of the fourth view.
    this my code of expanding Cell which consists of 4 content view
      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                  print(YearArr.count)
            return YearArr.count;
        }</p>

```<code>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
        cell.selectionStyle = .none
             cell.lblGrossSal.text = EarnArr[indexPath.row]

         cell.lblTotlSal.text = netPayArr[indexPath.row]
         cell.lblmonthhName.text = YearArr[indexPath.row]
            print(selectedIndex,indexPath.row)
        let height = cell.bounds.height
        print(height)
       return cell;
    }

       func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
        cell.selectionStyle = .none

        if(selectedIndex == indexPath.row) {

                       return 190;
            return self.calculateHeight(selectedIndexPath: indexPath)
        } else {

                        return 50;
        }
           }
 // fourthView
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if(selectedIndex == indexPath.row) {
            selectedIndex = -1
                   } else {
            selectedIndex = indexPath.row

        }
        self.expandTableView.beginUpdates()
        //self.expandTableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic )
        self.expandTableView.endUpdates()

       }
    func calculateHeight(selectedIndexPath: IndexPath) -> CGFloat {
        let cell = self.expandTableView.cellForRow(at: selectedIndexPath) as! customCell
        cell.lblDeductSal.frame = self.cellSummaryLabelFrame(cell: cell, selectedIndexPath: selectedIndexPath)

        return 80 + 35 + 21 + 10 + cell.lblDeductSal.frame.size.height + 30
    }

    func cellSummaryLabelFrame(cell: customCell, selectedIndexPath: IndexPath) -> CGRect {
        print(DeductionArr[selectedIndexPath.row])
        cell.lblDeductSal.text = DeductionArr[selectedIndexPath.row]
        cell.lblDeductSal.numberOfLines = 0
        var labelFrame = cell.lblDeductSal.frame
        let maxSize = CGSize.init(width: cell.lblDeductSal.frame.size.width, height: CGFloat.greatestFiniteMagnitude)
        let requiredSize = cell.lblDeductSal.sizeThatFits(maxSize)
        labelFrame.size.height = requiredSize.height
        return labelFrame
    }
</code>```

答:
In heightForRowAt indexPath, you are using two return. The first one will execute. The calculated height method can't execute. And there is no need of tableView.dequeueReusableCell. That function only need the height of cell.

Example:

```<code>func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if(selectedIndex == indexPath.row) {
        return self.calculateHeight(selectedIndexPath: indexPath)
    } else {
        return 50;
    }
}
</code>```

And You can also use dynamic cell height, In your viewDidLoad:

```<code>tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44 //Default cell height
</code>```

And here NO NEED OF heightForRowAt indexPath method. The height will automatically calculate.

Body:
I am new in ios I am making a project using table view in which I have expanded the table view cell which has 4 Content view.When the table is loaded only first content view show and when I select the row then all content view expands. But I also want that after expanding the all content view cell when I tap on fourth content view then I want to access the indexPath.row in the tapGESTUREAction method of the fourth view.
    this my code of expanding Cell which consists of 4 content view
      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                  print(YearArr.count)
            return YearArr.count;
        }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
        cell.selectionStyle = .none
             cell.lblGrossSal.text = EarnArr[indexPath.row]

         cell.lblTotlSal.text = netPayArr[indexPath.row]
         cell.lblmonthhName.text = YearArr[indexPath.row]
            print(selectedIndex,indexPath.row)
        let height = cell.bounds.height
        print(height)
       return cell;
    }

       func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
        cell.selectionStyle = .none

        if(selectedIndex == indexPath.row) {

                       return 190;
            return self.calculateHeight(selectedIndexPath: indexPath)
        } else {

                        return 50;
        }
           }
 // fourthView
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if(selectedIndex == indexPath.row) {
            selectedIndex = -1
                   } else {
            selectedIndex = indexPath.row

        }
        self.expandTableView.beginUpdates()
        //self.expandTableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic )
        self.expandTableView.endUpdates()

       }
    func calculateHeight(selectedIndexPath: IndexPath) -> CGFloat {
        let cell = self.expandTableView.cellForRow(at: selectedIndexPath) as! customCell
        cell.lblDeductSal.frame = self.cellSummaryLabelFrame(cell: cell, selectedIndexPath: selectedIndexPath)

        return 80 + 35 + 21 + 10 + cell.lblDeductSal.frame.size.height + 30
    }

    func cellSummaryLabelFrame(cell: customCell, selectedIndexPath: IndexPath) -> CGRect {
        print(DeductionArr[selectedIndexPath.row])
        cell.lblDeductSal.text = DeductionArr[selectedIndexPath.row]
        cell.lblDeductSal.numberOfLines = 0
        var labelFrame = cell.lblDeductSal.frame
        let maxSize = CGSize.init(width: cell.lblDeductSal.frame.size.width, height: CGFloat.greatestFiniteMagnitude)
        let requiredSize = cell.lblDeductSal.sizeThatFits(maxSize)
        labelFrame.size.height = requiredSize.height
        return labelFrame
    }

Body:
In heightForRowAt indexPath, you are using two return. The first one will execute. The calculated height method can't execute. And there is no need of tableView.dequeueReusableCell. That function only need the height of cell.

Example:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if(selectedIndex == indexPath.row) {
        return self.calculateHeight(selectedIndexPath: indexPath)
    } else {
        return 50;
    }
}

And You can also use dynamic cell height, In your viewDidLoad:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44 //Default cell height

And here NO NEED OF heightForRowAt indexPath method. The height will automatically calculate.


问:
405 Method Not Allowed The method GET is not allowed for this resource (AppEngine, Python)
NOTE: I think I have found what's wrong in my code, I had not installed the request module. I'm investigating this now.

I'm banging my head against the wall with this appengine application. Tried the remedies given for similar questions to no avail. Maybe someone can spot what the issue is?

Here's what I'm doing:

1) I create a product in the app based on the user's input. Once written to the ndb I call a page to display the recently created product:

```<code>import requests
....
r = requests.post('products_display', data = {'find_id_txt':prod_id_txt})
</code>```

The request is routed through:

```<code>application = webapp2.WSGIApplication([
    ('/products_add', AddProduct),
    ('/products_display', DisplayProduct),
    ...
], config = session_params, debug = True)
</code>```

It then arrives at the correct handler and I get the 405 error (405 Method Not Allowed The method GET is not allowed for this resource). The browser shows this url:

```<code>http://localhost:8080/products_display
</code>```

This is the code of the handler (for the moment I just display a page to tell if the product was found or not).

```<code>class DisplayProduct(BaseHandler):
    # Finds a product on exact Prod_ID property
    def get(self):
        user = usermgmt.get_user(self)
        logout_url = users.create_logout_url(self.request.uri)
        access = usermgmt.get_auth("Products")
        client_name = usermgmt.get_client_subdomain()
        search_key = self.request.get('find_id_txt')
        find_query = models.Product.query(models.Product.prod_id == search_key, ancestor = get_products_key()).get()
        # Check if query returned a value
        if find_query:
            template_values = {
                'client_name': client_name,
                'user': user,
                'logout_url': logout_url,
                'alert_message': "Product1: " + search_key + " was found."
            }
            template = JINJA_ENVIRONMENT.get_template('alert-blue.html')
            self.response.write(template.render(template_values))
        else:
            template_values = {
                'client_name': client_name,
                'user': user,
                'logout_url': logout_url,
                'alert_message': "Product1: " + search_key + " could not be found."
            }
            template = JINJA_ENVIRONMENT.get_template('alert-yellow.html')
            self.response.write(template.render(template_values))
</code>```

I tried all possible combinations of sending a get, then a post request and changing get for post on the handler. Each time I logged out of the browser or use another one and still I get the error.

Here's the content of my app.yaml file:

```<code>#application: fpp-system
#version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:

- url: /categories.*
  script: categories.application
  login: required

- url: /calendar.*
  script: calendars.application
  login: required

- url: /images
  static_dir: images

- url: /products.*
  script: products.application
  login: required

- url: /signin.*
  script: signin.application

- url: /stylesheets
  static_dir: stylesheets

- url: /test.*
  script: test.application

- url: /units.*
  script: units.application
  login: required

- url: /.*
  script: main.application

libraries:
- name: webapp2
  version: latest
- name: jinja2
  version: latest
</code>```

The code is written using pydev on eclipse neon on Linux Ubuntu 16.04. Once it's debugged I can upload it to Google's cloud.

Thanks in advance for any tips!

ADDED AFTER 1ST COMMENTS:

a) Copied indentation correctly: def get(self) and following are now indented correctly.

b) Added contents of app.yaml

c) The get function works well when I call it from an html page to find a product, here's the code snippet with the form to ask for required info:

```<code> <form action="/products_display" method="post">
   <div><input value="" name="find_id_txt" size="15"></div>
   <div><input type="submit" value="Find"></div>
 </form><br>
</code>```

but it gives the 405 error when I call it programmatically with:

```<code>r = requests.post('products_display', data = {'find_id_txt':prod_id_txt})
</code>```

答:
Try this to troubleshoot:

```<code>import logging

class DisplayProduct(BaseHandler):
    def get:
        logging.info("this is a GET")

    def post:
        logging.info("this is a POST")
</code>```

Then, send your current POST.  Next, send a request to: http://localhost:8080/products_display?find_id_txt=test.  Hopefully, you'll see what is happening.

Body:
NOTE: I think I have found what's wrong in my code, I had not installed the request module. I'm investigating this now.

I'm banging my head against the wall with this appengine application. Tried the remedies given for similar questions to no avail. Maybe someone can spot what the issue is?

Here's what I'm doing:

1) I create a product in the app based on the user's input. Once written to the ndb I call a page to display the recently created product:

import requests
....
r = requests.post('products_display', data = {'find_id_txt':prod_id_txt})

The request is routed through:

application = webapp2.WSGIApplication([
    ('/products_add', AddProduct),
    ('/products_display', DisplayProduct),
    ...
], config = session_params, debug = True)

It then arrives at the correct handler and I get the 405 error (405 Method Not Allowed The method GET is not allowed for this resource). The browser shows this url:

http://localhost:8080/products_display

This is the code of the handler (for the moment I just display a page to tell if the product was found or not).

class DisplayProduct(BaseHandler):
    # Finds a product on exact Prod_ID property
    def get(self):
        user = usermgmt.get_user(self)
        logout_url = users.create_logout_url(self.request.uri)
        access = usermgmt.get_auth("Products")
        client_name = usermgmt.get_client_subdomain()
        search_key = self.request.get('find_id_txt')
        find_query = models.Product.query(models.Product.prod_id == search_key, ancestor = get_products_key()).get()
        # Check if query returned a value
        if find_query:
            template_values = {
                'client_name': client_name,
                'user': user,
                'logout_url': logout_url,
                'alert_message': "Product1: " + search_key + " was found."
            }
            template = JINJA_ENVIRONMENT.get_template('alert-blue.html')
            self.response.write(template.render(template_values))
        else:
            template_values = {
                'client_name': client_name,
                'user': user,
                'logout_url': logout_url,
                'alert_message': "Product1: " + search_key + " could not be found."
            }
            template = JINJA_ENVIRONMENT.get_template('alert-yellow.html')
            self.response.write(template.render(template_values))

I tried all possible combinations of sending a get, then a post request and changing get for post on the handler. Each time I logged out of the browser or use another one and still I get the error.

Here's the content of my app.yaml file:

#application: fpp-system
#version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:

- url: /categories.*
  script: categories.application
  login: required

- url: /calendar.*
  script: calendars.application
  login: required

- url: /images
  static_dir: images

- url: /products.*
  script: products.application
  login: required

- url: /signin.*
  script: signin.application

- url: /stylesheets
  static_dir: stylesheets

- url: /test.*
  script: test.application

- url: /units.*
  script: units.application
  login: required

- url: /.*
  script: main.application

libraries:
- name: webapp2
  version: latest
- name: jinja2
  version: latest

The code is written using pydev on eclipse neon on Linux Ubuntu 16.04. Once it's debugged I can upload it to Google's cloud.

Thanks in advance for any tips!

ADDED AFTER 1ST COMMENTS:

a) Copied indentation correctly: def get(self) and following are now indented correctly.

b) Added contents of app.yaml

c) The get function works well when I call it from an html page to find a product, here's the code snippet with the form to ask for required info:

 <form action="/products_display" method="post">

<input value="" name="find_id_txt" size="15">

<input type="submit" value="Find">

 </form>

but it gives the 405 error when I call it programmatically with:

r = requests.post('products_display', data = {'find_id_txt':prod_id_txt})

Body:
Try this to troubleshoot:

import logging

class DisplayProduct(BaseHandler):
    def get:
        logging.info("this is a GET")

    def post:
        logging.info("this is a POST")

Then, send your current POST.  Next, send a request to: http://localhost:8080/products_display?find_id_txt=test.  Hopefully, you'll see what is happening.


问:
How to Generate Custom JSESSIONID to avoid conflict
I have two application deployed in single glassfish server with 2 different domains(port 8080,9090) with same context path. Its creating issue when two application are open in single browser with in different tabs.What i found is due to JSESSIONID are getting interchange. Is there a way to avoid or generate JSESSIONID specific to application?

Note: i didn't find any solution . I am using glassfish,servlet 2.3 api.

答:
Manage to solve the above issue by generating Unique JSESSIONID name for both application

Added cookie-config under session-config

```<code> <session-config>
    <session-timeout>30</session-timeout>
    <cookie-config>
    <name>JSESSIONID_APPLICATION_NAME</name><!-- default is jsessionid -->
    </cookie-config>
  </session-config>
</code>```

with the above configuration, application will have unique jsessionid name example : JSESSIONID_APP1:xybo89aoa3fhjasdf ,JSESSIONID_APP2:abc1234hjadkf

Body:
Manage to solve the above issue by generating Unique JSESSIONID name for both application

Added cookie-config under session-config

 <session-config>
    <session-timeout>30</session-timeout>
    <cookie-config>
    <name>JSESSIONID_APPLICATION_NAME</name><!-- default is jsessionid -->
    </cookie-config>
  </session-config>

with the above configuration, application will have unique jsessionid name example : JSESSIONID_APP1:xybo89aoa3fhjasdf ,JSESSIONID_APP2:abc1234hjadkf


答:
Here's one way:</p>

```<code>SELECT
      it.[Item Number]
    , Values1 = STUFF(CAST((
        SELECT [text()] = ', ' +  CAST(it2.TotalItem AS varchar)    + ' x ' + it2.ItemName
        FROM dbo.Items it2
        WHERE it2.[Item Number] = it.[Item Number]
        FOR XML PATH(''), TYPE) AS VARCHAR(100)), 1, 2, '')

FROM (
    SELECT DISTINCT [Item Number]
    FROM dbo.Items
) it
</code>```

Title: How to group all values by semicolon separated in SQL query

Body:
Please help how to achieve data as per shown in attached image

Highlighted rows actually group on Item Number field

Thanks in advance

Body:
Here's one way:

SELECT
      it.[Item Number]
    , Values1 = STUFF(CAST((
        SELECT [text()] = ', ' +  CAST(it2.TotalItem AS varchar)    + ' x ' + it2.ItemName
        FROM dbo.Items it2
        WHERE it2.[Item Number] = it.[Item Number]
        FOR XML PATH(''), TYPE) AS VARCHAR(100)), 1, 2, '')

FROM (
    SELECT DISTINCT [Item Number]
    FROM dbo.Items
) it


问:
plot different color for different categorical levels
I have this data frame diamonds which is composed of variables like (carat, price, color), and I want to draw a scatter plot of price to carat for each color, which means different color has different color in the plot.

This is easy in R with ggplot:

```<code>ggplot(aes(x=carat, y=price, color=color),  #by setting color=color, ggplot automatically draw in different colors
       data=diamonds) + geom_point(stat='summary', fun.y=median)
</code>```

I wonder how could this be done in Python using matplotlib ?

PS:

I know about auxiliary plotting packages, such as seaborn and ggplot for python, and I don't prefer them, just want to find out if it is possible to do the job using matplotlib alone, ;P

答:
Using Altair.

```<code>from altair import *
import pandas as pd

df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')
</code>```

Body:
I have this data frame diamonds which is composed of variables like (carat, price, color), and I want to draw a scatter plot of price to carat for each color, which means different color has different color in the plot.

This is easy in R with ggplot:

ggplot(aes(x=carat, y=price, color=color),  #by setting color=color, ggplot automatically draw in different colors
       data=diamonds) + geom_point(stat='summary', fun.y=median)

I wonder how could this be done in Python using matplotlib ?

PS:

I know about auxiliary plotting packages, such as seaborn and ggplot for python, and I don't prefer them, just want to find out if it is possible to do the job using matplotlib alone, ;P

Body:
Using Altair.

from altair import *
import pandas as pd

df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')


问:
Set input values when one input value change JQuery
Now, when the 1st row value change, the 2nd and 3rd row change accordingly.
The problem is this's hard code, i don't know the no of rows as it's generated from the database.Any idea?Many thanks

$("#A1").keyup(function() {
    $("#B1").val($("#A1").val());
});

$("#A1").keyup(function() {
    $("#C1").val($("#A1").val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td><input type="text" id="A1" name="A" value=""></td>
</tr><br>
<tr>
<td><input type="text" id="B1" name="A" value=""></td>
</tr>
<br>
<tr>
<td><input type="text" id="C1" name="A" value=""></td>
</tr></code>```

答:
you can just select all inputs and update values for all.

$("#A1").keyup(function() {
    $("input").val($("#A1").val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td><input type="text" id="A1" name="A" value=""></td>
</tr><br>
<tr>
<td><input type="text" id="B1" name="A" value=""></td>
</tr>
<br>
<tr>
<td><input type="text" id="C1" name="A" value=""></td>
</tr></code>```

Also if you want to select a few you can select multiple ids separated by commas. like this:

```<code>$("#A1").keyup(function() {
    $("#B1, #C1").val($("#A1").val());
});
</code>```

Body:
Now, when the 1st row value change, the 2nd and 3rd row change accordingly.
The problem is this's hard code, i don't know the no of rows as it's generated from the database.Any idea?Many thanks

$("#A1").keyup(function() {
    $("#B1").val($("#A1").val());
});

$("#A1").keyup(function() {
    $("#C1").val($("#A1").val());
});

<input type="text" id="A1" name="A" value="">

<input type="text" id="B1" name="A" value="">

<input type="text" id="C1" name="A" value="">

Body:
you can just select all inputs and update values for all.

$("#A1").keyup(function() {
    $("input").val($("#A1").val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td><input type="text" id="A1" name="A" value=""></td>
</tr><br>
<tr>
<td><input type="text" id="B1" name="A" value=""></td>
</tr>
<br>
<tr>
<td><input type="text" id="C1" name="A" value=""></td>
</tr>

Also if you want to select a few you can select multiple ids separated by commas. like this:

$("#A1").keyup(function() {
    $("#B1, #C1").val($("#A1").val());
});