问:
Managing an objects Constructors across multiple software versions
I'm designing a library where I am debating if I should use a constructor to initialize objects in the api's model.  My considerations are:

By using a constructor I can enforce what data is required to have a valid object according to the model.

However, by using a constructor I am curious as to how to maintain the code as it is modified in order to maintain this requirement without breaking existing code across the code base.

I could avoid using constructors in the object design, but I need the library to communicate to the developer using it which fields are required in order for the object to satisfy its model.

How can I create an object model that expresses the requirement of particular properties being initialized as well as provide scalability as it relates to code maintenance?

```<code>dim objV1 as new ObjectOfSomeType(Param1, Param2, Param3)
</code>```

VS

```<code>dim objV1 as new ObjectOfSomeType()

objV1.Property1 = Param1
objV1.Property2 = Param2
objV1.Property3 = Param3
</code>```

答:
The minimum required initial state for an object, i.e., data required for the object to behave in a deterministic way, should be set during construction.

If you question the capability of clients using your API to successfully construct your objects then you should publish a class containing the Factory Method Pattern and encourage and/or restrict the use of that.

Body:
I'm designing a library where I am debating if I should use a constructor to initialize objects in the api's model.  My considerations are:

By using a constructor I can enforce what data is required to have a valid object according to the model.

However, by using a constructor I am curious as to how to maintain the code as it is modified in order to maintain this requirement without breaking existing code across the code base.

I could avoid using constructors in the object design, but I need the library to communicate to the developer using it which fields are required in order for the object to satisfy its model.

How can I create an object model that expresses the requirement of particular properties being initialized as well as provide scalability as it relates to code maintenance?

dim objV1 as new ObjectOfSomeType(Param1, Param2, Param3)

VS

dim objV1 as new ObjectOfSomeType()

objV1.Property1 = Param1
objV1.Property2 = Param2
objV1.Property3 = Param3


来源: stackexchange

问:
Commands out of sync; you can't run this command now
I am trying to execute my PHP code, which calls two MySQL queries via mysqli, and get the error "Commands out of sync; you can't run this command now".

Here is the code I am using

```<code><?php
$con = mysqli_connect("localhost", "user", "password", "db");
if (!$con) {
    echo "Can't connect to MySQL Server. Errorcode: %s\n". Mysqli_connect_error();
    exit;
}
$con->query("SET NAMES 'utf8'");
$brand ="o";
$countQuery = "SELECT ARTICLE_NO FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE % ? %";
if ($numRecords = $con->prepare($countQuery)) {
    $numRecords->bind_param("s", $brand);
    $numRecords->execute();
    $data = $con->query($countQuery) or die(print_r($con->error));
    $rowcount = $data->num_rows;
    $rows = getRowsByArticleSearch("test", "Auctions", " ");
    $last = ceil($rowcount/$page_rows);
}  else {

print_r($con->error);
}
foreach ($rows as $row) {
    $pk = $row['ARTICLE_NO'];
    echo '<tr>' . "\n";
    echo '<td><a href="#" onclick="updateByPk(\'Layer2\', \'' . $pk . '\')">'.$row['USERNAME'].'</a></td>' . "\n";
    echo '<td><a href="#" onclick="updateByPk(\'Layer2\', \'' . $pk . '\')">'.$row['shortDate'].'</a></td>' . "\n";
    echo '<td><a href="#" onclick="deleterec(\'Layer2\', \'' . $pk . '\')">DELETE RECORD</a></td>' . "\n";
    echo '</tr>' . "\n";
}
function getRowsByArticleSearch($searchString, $table, $max) {
    $con = mysqli_connect("localhost", "user", "password", "db");
    $recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;
    if ($getRecords = $con->prepare($recordsQuery)) {
        $getRecords->bind_param("s", $searchString);
        $getRecords->execute();
        $getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);
        while ($getRecords->fetch()) {
            $result = $con->query($recordsQuery);
            $rows = array();
            while($row = $result->fetch_assoc()) {
                $rows[] = $row;
            }
            return $rows;
        }
    }
}
</code>```

I have tried reading up on this, but I am unsure of what to do. I have read about store result and free result, however these have made no difference when using them. I am unsure at exactly which point this error is being caused, and would like to know why it is being caused, and how to fix it.

Going by my debug statements, the first if loop for countQuery is not even being entered, because of an error in my sql syntax near near '% ? %'. However if I just select * instead of trying to limit based on a LIKE clause, I still get the command out of sync error.

答:
Once you used

```<code>stmt->execute();
</code>```

You MAY close it to use another query.

```<code>stmt->close();
</code>```

This problem was hunting me for hours. Hopefully, it will fix yours.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to execute my PHP code, which calls two MySQL queries via mysqli, and get the error "Commands out of sync; you can't run this command now".

Here is the code I am using

<?php
$con = mysqli_connect("localhost", "user", "password", "db");
if (!$con) {
    echo "Can't connect to MySQL Server. Errorcode: %s\n". Mysqli_connect_error();
    exit;
}
$con->query("SET NAMES 'utf8'");
$brand ="o";
$countQuery = "SELECT ARTICLE_NO FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE % ? %";
if ($numRecords = $con->prepare($countQuery)) {
    $numRecords->bind_param("s", $brand);
    $numRecords->execute();
    $data = $con->query($countQuery) or die(print_r($con->error));
    $rowcount = $data->num_rows;
    $rows = getRowsByArticleSearch("test", "Auctions", " ");
    $last = ceil($rowcount/$page_rows);
}  else {

print_r($con->error);
}
foreach ($rows as $row) {
    $pk = $row['ARTICLE_NO'];
    echo '
' . "\n";
    echo ''.$row['USERNAME'].'	' . "\n";
    echo ''.$row['shortDate'].'	' . "\n";
    echo 'DELETE RECORD	' . "\n";
    echo '
' . "\n";
}
function getRowsByArticleSearch($searchString, $table, $max) {
    $con = mysqli_connect("localhost", "user", "password", "db");
    $recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;
    if ($getRecords = $con->prepare($recordsQuery)) {
        $getRecords->bind_param("s", $searchString);
        $getRecords->execute();
        $getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);
        while ($getRecords->fetch()) {
            $result = $con->query($recordsQuery);
            $rows = array();
            while($row = $result->fetch_assoc()) {
                $rows[] = $row;
            }
            return $rows;
        }
    }
}

I have tried reading up on this, but I am unsure of what to do. I have read about store result and free result, however these have made no difference when using them. I am unsure at exactly which point this error is being caused, and would like to know why it is being caused, and how to fix it.

Going by my debug statements, the first if loop for countQuery is not even being entered, because of an error in my sql syntax near near '% ? %'. However if I just select * instead of trying to limit based on a LIKE clause, I still get the command out of sync error.

LastEditorDisplayName: Iraimbilanja

Body:
Once you used

stmt->execute();

You MAY close it to use another query.

stmt->close();

This problem was hunting me for hours. Hopefully, it will fix yours.

ContentLicense: CC BY-SA 4.0


问:
HMACSHA256 and MD5 generated hash are different than the openssl dgst generated hash
I am connecting to a REST API server which uses HMAC authentication. Tried with Hash generated from command 'OpenSSL dgst' which successfully connected/authenticated to the server.

But using HMACSHA256 and MD5(System.Security.Cryptography) from C#/.NET generates a code that is different from one generated by OpenSSL dgst shell script command and the authentication fails

```<code>INPUT='teststring'

HMAC_KEY='ASDFGHJKL'

echo "${INPUT}" | openssl dgst -md5 -binary | openssl enc -base64 -A >> log.txt

printf '%s\n' "${INPUT}" | openssl dgst -binary -sha256 -hmac "${HMAC_KEY}" | openssl enc -base64 -A >> log.txt;
</code>```

Generates the successful hash to connect to the server by postman or fiddler

```<code>String hmacKey = "ASDFGHJKL";
String md5InputString = "teststring";
String hmacInputString = "teststring\n";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(hmacKey);
MD5 md5 = MD5.Create();
HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
byte[] utf8EncodedDataBytes = encoding.GetBytes(md5InputString);
byte[] md5HashBytes = md5.ComputeHash(utf8EncodedDataBytes);
string base64md5HashString = Convert.ToBase64String(md5HashBytes);

byte[] utf8EncodedHMACBytes = encoding.GetBytes(hmacInputString);
byte[] hmasha256HashBytes = hmacsha256.ComputeHash(utf8EncodedHMACBytes);
string base64sha256HashString = Convert.ToBase64String(hmasha256HashBytes);

Console.WriteLine("MD5 hash string - " + base64md5HashString);
Console.WriteLine("SHA256 hash string - " + base64sha256HashString);
Console.ReadLine();
</code>```

The c# code above generates a different hash compared to the one generated from OpenSSL dgst command

答:
The MD5 and SHA256 matches in both cases for the above code. I am still struggling to solve the issue with hashing which is related to the same question.

```<code> # we read some dummy data that will be hashed
#PAYLOAD='teststring'
read -r -d '' PAYLOAD << EOF
{
  "type": "MatchType",
  "membershipId": "1234567890",
  "givenName": "FirstName",
  "surname": "LastName"
}
EOF
HMAC_KEY='ADf3TSCGjNd4Zj29'
# the verb
VERB='POST'
# the full resource URL
RESOURCE='/v1/member/profile/validate'
# a generated timestamp used to prevent replay
TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
CONTENT_TYPE='application/json'
# generate the content length
CONTENT_LENGTH=$( echo -n "${PAYLOAD}" | wc -c )
CONTENT_DIGEST=$(echo -n "${PAYLOAD}" | openssl dgst -md5 -binary | openssl enc -base64 -A)
printf  "\nPayload MD5 hash input string\n"  >> log.txt;
echo -n "${PAYLOAD}"  >> log.txt;
printf  "\nMD5 Base64Encoded string\n"  >> log.txt;
echo -n "${PAYLOAD}" | openssl dgst -md5 -binary | openssl enc -base64 -A >> log.txt

printf  "\nHMAC hash input string\n"  >> log.txt;
printf '%s\n%s\n%s\n%s\n%s' "${VERB}""${TIMESTAMP}""${RESOURCE}""${CONTENT_TYPE}""${CONTENT_DIGEST}"  >> log.txt;
printf  "\nHMAC Base64Encoded string\n"  >> log.txt;
printf '%s\n%s\n%s\n%s\n%s' "${_VERB}""${_TIMESTAMP}""${_RESOURCE}""${_CONTENT_TYPE}""${_CONTENT_DIGEST}" | openssl dgst -binary -sha256 -hmac "${HMAC_KEY}" | openssl enc -base64 -A >> log.txt;

</code>```

This outputs

Payload MD5 hash input string

{
  "type": "MatchType",
  "membershipId": "1234567890",
  "givenName": "FirstName",
  "surname": "LastName"
}

MD5 Base64Encoded string

MkY18c4MmVoS2r66DSNgRQ==

HMAC hash input string

POST2019-06-01T14:04:47Z/v1/member/profile/validateapplication/jsonMkY18c4MmVoS2r66DSNgRQ==

HMAC Base64Encoded string

BlfQhEyX5tRDl7bpDS0PVmFUm4QBn3r7KazOIfG/1JQ=

```<code>string hmacKey = "ADf3TSCGjNd4Zj29";
string stringjsonData = "{\"type\": \"MatchType\",\"membershipId\": \"1234567890\",\"givenName\": \"FirstName\",\"surname\": \"LastName\"}";
//string stringjsonData = "teststring";
int jsonStringLength = stringjsonData.Length;
string verb = "POST";
string datetime = "2019-06-01T14:04:47Z";
string url = "/v1/member/profile validate";
string contenttype = "application/json";

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(hmacKey);
MD5 hmacmd5 = MD5.Create();
HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);

byte[] utf8EncodedMD5DataBytes = encoding.GetBytes(stringjsonData);
byte[] hmacmd5HashBytes = hmacmd5.ComputeHash(utf8EncodedMD5DataBytes);
string base64md5HashString = Convert.ToBase64String(hmacmd5HashBytes);

string sha256Input = verb + "\n " + datetime + "\n " + url + "\n " + contenttype + "\n " + base64md5HashString;

byte[] utf8EncodedSHA256DataBytes = encoding.GetBytes(sha256Input);
byte[] hmasha256HashBytes = hmacsha256.ComputeHash(utf8EncodedSHA256DataBytes);
string base64sha256HashString = Convert.ToBase64String(hmasha256HashBytes);

Console.ReadLine();

</code>```

The Hash generated from c# code are

MD5 Base64Encoded string     RrKDQmKSdDnByqlFiMcTOA==

SHA256 Base64Encoded string    J9S5IrnFuzwZrCqAVxcaL30xDCrZnyBpu9NHGFpHSQw=

Please note I am using the exact date from the output of the script as the date in the C# program.

Body:
I am connecting to a REST API server which uses HMAC authentication. Tried with Hash generated from command 'OpenSSL dgst' which successfully connected/authenticated to the server.

But using HMACSHA256 and MD5(System.Security.Cryptography) from C#/.NET generates a code that is different from one generated by OpenSSL dgst shell script command and the authentication fails

INPUT='teststring'

HMAC_KEY='ASDFGHJKL'

echo "${INPUT}" | openssl dgst -md5 -binary | openssl enc -base64 -A >> log.txt

printf '%s\n' "${INPUT}" | openssl dgst -binary -sha256 -hmac "${HMAC_KEY}" | openssl enc -base64 -A >> log.txt;

Generates the successful hash to connect to the server by postman or fiddler

String hmacKey = "ASDFGHJKL";
String md5InputString = "teststring";
String hmacInputString = "teststring\n";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(hmacKey);
MD5 md5 = MD5.Create();
HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
byte[] utf8EncodedDataBytes = encoding.GetBytes(md5InputString);
byte[] md5HashBytes = md5.ComputeHash(utf8EncodedDataBytes);
string base64md5HashString = Convert.ToBase64String(md5HashBytes);

byte[] utf8EncodedHMACBytes = encoding.GetBytes(hmacInputString);
byte[] hmasha256HashBytes = hmacsha256.ComputeHash(utf8EncodedHMACBytes);
string base64sha256HashString = Convert.ToBase64String(hmasha256HashBytes);

Console.WriteLine("MD5 hash string - " + base64md5HashString);
Console.WriteLine("SHA256 hash string - " + base64sha256HashString);
Console.ReadLine();

The c# code above generates a different hash compared to the one generated from OpenSSL dgst command

Body:
The MD5 and SHA256 matches in both cases for the above code. I am still struggling to solve the issue with hashing which is related to the same question.

 # we read some dummy data that will be hashed
#PAYLOAD='teststring'
read -r -d '' PAYLOAD << EOF
{
  "type": "MatchType",
  "membershipId": "1234567890",
  "givenName": "FirstName",
  "surname": "LastName"
}
EOF
HMAC_KEY='ADf3TSCGjNd4Zj29'
# the verb
VERB='POST'
# the full resource URL
RESOURCE='/v1/member/profile/validate'
# a generated timestamp used to prevent replay
TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
CONTENT_TYPE='application/json'
# generate the content length
CONTENT_LENGTH=$( echo -n "${PAYLOAD}" | wc -c )
CONTENT_DIGEST=$(echo -n "${PAYLOAD}" | openssl dgst -md5 -binary | openssl enc -base64 -A)
printf  "\nPayload MD5 hash input string\n"  >> log.txt;
echo -n "${PAYLOAD}"  >> log.txt;
printf  "\nMD5 Base64Encoded string\n"  >> log.txt;
echo -n "${PAYLOAD}" | openssl dgst -md5 -binary | openssl enc -base64 -A >> log.txt

printf  "\nHMAC hash input string\n"  >> log.txt;
printf '%s\n%s\n%s\n%s\n%s' "${VERB}""${TIMESTAMP}""${RESOURCE}""${CONTENT_TYPE}""${CONTENT_DIGEST}"  >> log.txt;
printf  "\nHMAC Base64Encoded string\n"  >> log.txt;
printf '%s\n%s\n%s\n%s\n%s' "${_VERB}""${_TIMESTAMP}""${_RESOURCE}""${_CONTENT_TYPE}""${_CONTENT_DIGEST}" | openssl dgst -binary -sha256 -hmac "${HMAC_KEY}" | openssl enc -base64 -A >> log.txt;

This outputs

Payload MD5 hash input string

{
  "type": "MatchType",
  "membershipId": "1234567890",
  "givenName": "FirstName",
  "surname": "LastName"
}

MD5 Base64Encoded string

MkY18c4MmVoS2r66DSNgRQ==

HMAC hash input string

POST2019-06-01T14:04:47Z/v1/member/profile/validateapplication/jsonMkY18c4MmVoS2r66DSNgRQ==

HMAC Base64Encoded string

BlfQhEyX5tRDl7bpDS0PVmFUm4QBn3r7KazOIfG/1JQ=

string hmacKey = "ADf3TSCGjNd4Zj29";
string stringjsonData = "{\"type\": \"MatchType\",\"membershipId\": \"1234567890\",\"givenName\": \"FirstName\",\"surname\": \"LastName\"}";
//string stringjsonData = "teststring";
int jsonStringLength = stringjsonData.Length;
string verb = "POST";
string datetime = "2019-06-01T14:04:47Z";
string url = "/v1/member/profile validate";
string contenttype = "application/json";

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(hmacKey);
MD5 hmacmd5 = MD5.Create();
HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);

byte[] utf8EncodedMD5DataBytes = encoding.GetBytes(stringjsonData);
byte[] hmacmd5HashBytes = hmacmd5.ComputeHash(utf8EncodedMD5DataBytes);
string base64md5HashString = Convert.ToBase64String(hmacmd5HashBytes);

string sha256Input = verb + "\n " + datetime + "\n " + url + "\n " + contenttype + "\n " + base64md5HashString;

byte[] utf8EncodedSHA256DataBytes = encoding.GetBytes(sha256Input);
byte[] hmasha256HashBytes = hmacsha256.ComputeHash(utf8EncodedSHA256DataBytes);
string base64sha256HashString = Convert.ToBase64String(hmasha256HashBytes);

Console.ReadLine();

The Hash generated from c# code are

MD5 Base64Encoded string     RrKDQmKSdDnByqlFiMcTOA==

SHA256 Base64Encoded string    J9S5IrnFuzwZrCqAVxcaL30xDCrZnyBpu9NHGFpHSQw=

Please note I am using the exact date from the output of the script as the date in the C# program.


问:
How to create a shadow in a boxview
I need to create a Box view like material design card with shadow drop

I have written a custom render to add the shadow effect in android. but in iOS, it's not working

答:
you could have put your BoxView inside a frame and enabled the HasShadow property of it</p>
```<code><Frame ConnerRadius="5" HasShadow="true">
<BoxView/>
</Frame>
</code>```

Title: How to create a shadow in a boxview

Body:
you could have put your BoxView inside a frame and enabled the HasShadow property of it

<Frame ConnerRadius="5" HasShadow="true">
<BoxView/>
</Frame>


问:
Java Client-Server application throws "java.net.SocketException: Connection reset" exception
I was trying to create a Client-Server application where the client generates a random number and sends to the server n strings. The connection is closed sending the string "BYE". After that the server has to calculate the total length of the received strings and print it.

The problem is that when my client tries to connect to the server this one throws "java.net.SocketException: Connection reset" exception and crashes.

Here's my Client code:

```<code>
import java.net.*;
import java.io.*;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ClientStringa {

    public static void main(String[] args) {
        try{
            Socket socket = new Socket("localhost", 5555);
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            Random r = new Random();

            int N = r.nextInt(100);

            for(int i=1;i<=N;i++){
                out.println("String" +i);
            }
            out.flush();
        }
        catch (IOException ex) {
            Logger.getLogger(ClientStringa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
</code>```

My Server code:

```<code>
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ServerStringa {
    public static void main(String[] args) {
        try {
            ServerSocket socket = new ServerSocket(5555);

            while(true){
                System.out.println("Waiting for client connections...");
                Socket client = socket.accept();    //connessione dei client
                ThreadStringa thread = new ThreadStringa(client);
                thread.start();
            }

        } catch (IOException ex) {
            Logger.getLogger(ServerStringa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
</code>```

And my Thread code (since the server must be able to answer more clients):

```<code>
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadStringa extends Thread{
    Socket client;

    public ThreadStringa(Socket client) {
        this.client = client;
    }

    public void run(){
        try {
           // DataInputStream input = new DataInputStream(client.getInputStream());
            String message;
            int sum=0;

            InputStream input = client.getInputStream();
            InputStreamReader input2 = new InputStreamReader(input);
            BufferedReader in = new BufferedReader(input2);

            while((message= in.readLine()) != null){
                if(message.equals("BYE")){
                    break;
                }
                sum+=message.length();
            }

            System.out.println("Total length of received strings: " + sum);
            input.close();
            client.close();
        }
        catch (IOException ex) {
            Logger.getLogger(ThreadStringa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
</code>```

The full error I get on the server console is:

```<code>java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
        at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
        at sun.nio.cs.StreamDecoder.read(Unknown Source)
        at java.io.InputStreamReader.read(Unknown Source)
        at java.io.BufferedReader.fill(Unknown Source)
        at java.io.BufferedReader.readLine(Unknown Source)
        at java.io.BufferedReader.readLine(Unknown Source)
        at serverstringa.ThreadStringa.run(ThreadStringa.java:27)
</code>```

答:
Instead of PrintWriter in client program, you should use DataOutputStream to communicate with Server in socket programming. Also remember to perform close() from client side. I have only modified your client program, you can check this.</p>

```<code>import java.net.*;
import java.io.*;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ClientStringa {

    public static void main(String[] args) {
        try{
            Socket socket = new Socket("localhost", 5555);
            DataOutputStream out=new DataOutputStream(socket.getOutputStream());
//            PrintWriter out = new PrintWriter(socket.getOutputStream());
            Random r = new Random();
            int N = r.nextInt(100);
            for(int i=1;i<=N;i++){
//                out.println("String" +i);
                out.writeUTF("String" +i);
            }
            out.flush();
            out.close();
        }
        catch (IOException ex) {
            Logger.getLogger(ClientStringa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
</code>```

Body:
I was trying to create a Client-Server application where the client generates a random number and sends to the server n strings. The connection is closed sending the string "BYE". After that the server has to calculate the total length of the received strings and print it.

The problem is that when my client tries to connect to the server this one throws "java.net.SocketException: Connection reset" exception and crashes.

Here's my Client code:

import java.net.*;
import java.io.*;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ClientStringa {

    public static void main(String[] args) {
        try{
            Socket socket = new Socket("localhost", 5555);
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            Random r = new Random();

            int N = r.nextInt(100);

            for(int i=1;i<=N;i++){
                out.println("String" +i);
            }
            out.flush();
        }
        catch (IOException ex) {
            Logger.getLogger(ClientStringa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

My Server code:

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ServerStringa {
    public static void main(String[] args) {
        try {
            ServerSocket socket = new ServerSocket(5555);

            while(true){
                System.out.println("Waiting for client connections...");
                Socket client = socket.accept();    //connessione dei client
                ThreadStringa thread = new ThreadStringa(client);
                thread.start();
            }

        } catch (IOException ex) {
            Logger.getLogger(ServerStringa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

And my Thread code (since the server must be able to answer more clients):

import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadStringa extends Thread{
    Socket client;

    public ThreadStringa(Socket client) {
        this.client = client;
    }

    public void run(){
        try {
           // DataInputStream input = new DataInputStream(client.getInputStream());
            String message;
            int sum=0;

            InputStream input = client.getInputStream();
            InputStreamReader input2 = new InputStreamReader(input);
            BufferedReader in = new BufferedReader(input2);

            while((message= in.readLine()) != null){
                if(message.equals("BYE")){
                    break;
                }
                sum+=message.length();
            }

            System.out.println("Total length of received strings: " + sum);
            input.close();
            client.close();
        }
        catch (IOException ex) {
            Logger.getLogger(ThreadStringa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

The full error I get on the server console is:

java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
        at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
        at sun.nio.cs.StreamDecoder.read(Unknown Source)
        at java.io.InputStreamReader.read(Unknown Source)
        at java.io.BufferedReader.fill(Unknown Source)
        at java.io.BufferedReader.readLine(Unknown Source)
        at java.io.BufferedReader.readLine(Unknown Source)
        at serverstringa.ThreadStringa.run(ThreadStringa.java:27)

Body:
Instead of PrintWriter in client program, you should use DataOutputStream to communicate with Server in socket programming. Also remember to perform close() from client side. I have only modified your client program, you can check this.

import java.net.*;
import java.io.*;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ClientStringa {

    public static void main(String[] args) {
        try{
            Socket socket = new Socket("localhost", 5555);
            DataOutputStream out=new DataOutputStream(socket.getOutputStream());
//            PrintWriter out = new PrintWriter(socket.getOutputStream());
            Random r = new Random();
            int N = r.nextInt(100);
            for(int i=1;i<=N;i++){
//                out.println("String" +i);
                out.writeUTF("String" +i);
            }
            out.flush();
            out.close();
        }
        catch (IOException ex) {
            Logger.getLogger(ClientStringa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


问:
Webbrowser, detect if there is a PDF reader installed?
Is there a way to check if the user has installed a PDF reader?
Maybe with a ActiveX component?

Could you please help me?

答:
No, I don't think so - but you could always direct your links through Google's PDF reader by default - which will work for everyone.

http://docs.google.com/viewer

Please be aware that this will channel your PDF files through Google's servers, so you will lose an element of security.


问:
How to preserve collection view scroll position after changing ViewController in SWIFT
The problem is: after scrolling the collectionView and clicking on an item another viewController is presented via navigationController. When I tap on the 'Back' button (top-left) the collection view scrolls to top, but I want it to keep the "scroll position" that it had before changing view controller.

I tried adding

automaticallyAdjustsScrollViewInsets = false

Thank you

答:
automaticallyAdjustsScrollViewInsets has nothing to do with what you are dealing with.
The collectionView should not scroll back to top by itself. You are probably calling reloadData() in viewDidAppear or viewWillAppear which triggers the behavior you are describing.


问:
Trying to generate subset of a string using recursion method
Trying to implement an algorithm using recursion in python. looks like something is missing which I am not able to debug.

My approach is to have two branches of recursion and passing an element at every recursion. details below:

```<code>## input pattern : "ab"
## output pattern : ["", "a", "b", "ab"]
</code>```

Recursion tree will look like following for this pattern

```<code>#           "ab" [ROOT]
#                   |
#           -a           +a
#           |             |
#       -b      +b    -b    +b
# =>    ""      "b"     "a"     "ab"
</code>```

my existing code is below: it is not working as expected.

```<code>def gen_subset(slist):
    def helper(slist,i,temp,out):
        if len(slist) == i:
            out.append(temp)
            return()
        else:
            helper(slist,i+1,temp,out)
            temp.append(slist[i])
            helper(slist,i+1,temp,out)

    out = []
    helper(slist,0,[],out)
    return out

s = "ab"
print (gen_subset([c for c in s]))
</code>```

this code produces the wrong result.

Output

```<code>[['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b']]
</code>```

am I missing anything here?

答:
Change temp.append(slist[i]) to temp = temp + [slist[i]].

This is happening because temp.append() modifies the temp variable in-place.

Instead we need to pass a copy of temp to the next recursion call.

Body:
Trying to implement an algorithm using recursion in python. looks like something is missing which I am not able to debug.

My approach is to have two branches of recursion and passing an element at every recursion. details below:

## input pattern : "ab"
## output pattern : ["", "a", "b", "ab"]

Recursion tree will look like following for this pattern

#           "ab" [ROOT]
#                   |
#           -a           +a
#           |             |
#       -b      +b    -b    +b
# =>    ""      "b"     "a"     "ab"

my existing code is below: it is not working as expected.

def gen_subset(slist):
    def helper(slist,i,temp,out):
        if len(slist) == i:
            out.append(temp)
            return()
        else:
            helper(slist,i+1,temp,out)
            temp.append(slist[i])
            helper(slist,i+1,temp,out)

    out = []
    helper(slist,0,[],out)
    return out

s = "ab"
print (gen_subset([c for c in s]))

this code produces the wrong result.

Output

[['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b']]

am I missing anything here?


问:
Test does run on the selenium grid in local works correctly)
I am trying to run the code below in selenium GRID (executing the "local" code, works correctly), follows code snippet:

```<code>SuiteTest.xml:
</code>```

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="SuiteTest" verbose="1" thread-count="2" parallel="tests">
        <test name="FIREFOX Test">
        <parameter name="browser" value="FIREFOX" />
        <classes>
            <class name="test.CN01_CT01_IncluirConteudoMP3" />
            <class name="test.CN01_CT02_IncluirConteudoMP4" />
        </classes>
    </test>

        <test name="CHROME Test">
        <parameter name="browser" value="CHROME" />
        <classes>
            <class name="test.CN01_CT01_IncluirConteudoMP3" />
            <class name="test.CN01_CT02_IncluirConteudoMP4" />
        </classes>
    </test>
</suite>
```

<p>BaseTest:</p>

<pre class="lang-java prettyprint-override"><code>public class BaseTest {

    protected static ExtentReports extent;
    public static String testName;

    @Parameters({ "browser" })
    @BeforeMethod
    public void BeforeTest(Method method, Browsers browser) throws IOException, BiffException {

        Propriedades.browser = browser;
        String browserStr = browser.toString();
        System.out.println("Before ........" + method.getName());
        //Recuperar nome do Teste
        testName = method.getName() + "-" + browserStr;
        // Realizando Login
        LoginPage.realizarLogin();
        //Iniciar o relatorio
        extent = ExtentReport.StartReport(testName);

    }

    @AfterMethod
    public void finaliza(ITestResult result) throws IOException {
        System.out.println("After ........");

        //Validar Resultado dos Testes
        ExtentReport.ResultTest(result, testName);

        // Realizar Logout
        LoginPage.realizarLogout();

        // Fechando Browser
        if (Propriedades.FECHAR_BROWSER) {
            killDriver();
        }
    }

    @AfterSuite
    public static void finalizaTudo(){
        DriverFactory.killDriver();
        extent.flush();
        System.out.println("AfterSuite........");
        System.out.println(ExtentReport.diretorioReport);
        //DriverFactory.executeChrome(ExtentReport.diretorioReport);
    }

}
</code>```

BasePage:

public class BasePage {

    protected static DSL dsl;

    static List<String> result = Ambiente.dadosAmbiente();
    static String url = result.get(0);
    protected static String user = result.get(1);
    protected static String pass = result.get(2);

    public BasePage() {
        dsl = new DSL();
    }

}
```

<p>DSL:</p>

<pre class="lang-java prettyprint-override"><code>public class DSL {

    public void clicarRadio(By by) {
        getDriver().findElement(by).click();
    }

Other methods to access the screen elements (Text, Click, Button, Radio, Combo and etc.)

(...)

}
</code>```

DriveFactory:

public class DriverFactory {

    static WebDriver driver;

    private DriverFactory() {
    }

    public static WebDriver getDriver() {

        if(Propriedades.tipoExecucao == TipoExecucao.LOCAL){

                if (driver == null) {
                    switch (Propriedades.browser) {
                    case CHROME:
                        executeChrome(BasePage.url);
                        break;
                    case FIREFOX:
                        executeFirefox(BasePage.url);
                        break;
                    case IE:
                        executeIE(BasePage.url);
                        break;
                    case EDGE:
                        executeEgde(BasePage.url);
                        break;
                    }
                    driver.manage().window().maximize();
                }
        }

        if(Propriedades.tipoExecucao == TipoExecucao.GRID) {

            DesiredCapabilities cap = null;
                switch (Propriedades.browser) {
                case CHROME:
                    cap = DesiredCapabilities.chrome();
                    break;
                case FIREFOX:
                    cap = DesiredCapabilities.firefox();
                    break;
                case IE:
                    cap = DesiredCapabilities.internetExplorer();
                    break;
                case EDGE:
                    cap = DesiredCapabilities.edge();
                    break;
                }

                try {
                    driver = new RemoteWebDriver(new URL("http://192.168.0.72:4444/wd/hub"), cap);
                } catch (MalformedURLException e) {
                    System.err.println("Falha ao conectar ao GRID");
                }
                driver.manage().window().maximize();
                driver.get(BasePage.url);
                System.out.println("Abriu Browser Grid");
    }

        return driver;
}

    public static void killDriver() {
        if (driver != null) {
            driver.close();
            driver.quit();
            driver = null;
        }
    }
}
```

<p>Test - Class:</p>

<p>Test classes, just to check that execution is logging in and logout.</p>

<pre class="lang-java prettyprint-override"><code>@Test
public void CN01_CT02_IncluirConteudoMp4(){

assertEquals("123", "123");
}

@Test

public void CN01_CT01_IncluirConteudoMp3() throws InterruptedException, AWTException{

assertEquals("123", "123456");
}
</code>```

Configuration Grid

Config (Json) - Hub:

```<code>{
  "port": 4444,
  "newSessionWaitTimeout": -1,
  "servlets" : [],
  "withoutServlets": [],
  "custom": {},
  "capabilityMatcher": "org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
  "registry": "org.openqa.grid.internal.DefaultGridRegistry",
  "throwOnCapabilityNotPresent": true,
  "cleanUpCycle": 5000,
  "role": "hub",
  "debug": false,
  "browserTimeout": 0,
  "timeout": 1800
}
</code>```

NodeChrome:

```<code>{
    "capabilities": [
        {
            "browserName": "chrome",
            "maxInstances": 1,
            "webdriver.chrome.driver": "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
        }
    ],
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 1,
    "port": 5555,
    "register": true,
    "registerCycle": 5000,
    "hub": "http://192.168.0.72:4444",
    "nodeStatusCheckTimeout": 5000,
    "nodePolling": 5000,
    "role": "node",
    "unregisterIfStillDownAfter": 60000,
    "downPollingLimit": 1,
    "debug": false,
    "servlets": [
    ],
    "withoutServlets": [

    ],
    "custom": {
    }
}
</code>```

NodeFirefox:

```<code>{
    "capabilities": [
        {
            "browserName": "firefox",
            "maxInstances": 1,
            "webdriver.gecko.driver": "C:/Program Files/Mozilla Firefox/firefox.exe"
        }
    ],
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 1,
    "port": 5556,
    "register": true,
    "registerCycle": 5000,
    "hub": "http://192.168.0.72:4444",
    "nodeStatusCheckTimeout": 5000,
    "nodePolling": 5000,
    "role": "node",
    "unregisterIfStillDownAfter": 60000,
    "downPollingLimit": 1,
    "debug": false,
    "servlets": [

    ],
    "withoutServlets": [

    ],
    "custom": {
    }
}
</code>```

When executing the code using Selenium GRID, the system opens two browsers but does not log in, problem occurs (apparently sync problem).

Example:

The login field is filled in "twice" and "Invalid Login" is returned.

Code is executed using the Eclipse IDE.
Run (SuiteTest.xml) - Run with TestNG

答: The problem lies in your test code. Your DriverFactory is initialising a static data member in driver. Now when you run your tests in parallel via your suite xml file, your tests are really competing with each other and end up overwriting the static data member. You need to refactor your test code. There's no problem with either the Selenium Grid or TestNG for that matter here.

Body:
I am trying to run the code below in selenium GRID (executing the "local" code, works correctly), follows code snippet:

SuiteTest.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="SuiteTest" verbose="1" thread-count="2" parallel="tests">
        <test name="FIREFOX Test">
        <parameter name="browser" value="FIREFOX" />
        <classes>
            <class name="test.CN01_CT01_IncluirConteudoMP3" />
            <class name="test.CN01_CT02_IncluirConteudoMP4" />
        </classes>
    </test>

        <test name="CHROME Test">
        <parameter name="browser" value="CHROME" />
        <classes>
            <class name="test.CN01_CT01_IncluirConteudoMP3" />
            <class name="test.CN01_CT02_IncluirConteudoMP4" />
        </classes>
    </test>
</suite>

BaseTest:

public class BaseTest {

    protected static ExtentReports extent;
    public static String testName;

    @Parameters({ "browser" })
    @BeforeMethod
    public void BeforeTest(Method method, Browsers browser) throws IOException, BiffException {

        Propriedades.browser = browser;
        String browserStr = browser.toString();
        System.out.println("Before ........" + method.getName());
        //Recuperar nome do Teste
        testName = method.getName() + "-" + browserStr;
        // Realizando Login
        LoginPage.realizarLogin();
        //Iniciar o relatorio
        extent = ExtentReport.StartReport(testName);

    }

    @AfterMethod
    public void finaliza(ITestResult result) throws IOException {
        System.out.println("After ........");

        //Validar Resultado dos Testes
        ExtentReport.ResultTest(result, testName);

        // Realizar Logout
        LoginPage.realizarLogout();

        // Fechando Browser
        if (Propriedades.FECHAR_BROWSER) {
            killDriver();
        }
    }

    @AfterSuite
    public static void finalizaTudo(){
        DriverFactory.killDriver();
        extent.flush();
        System.out.println("AfterSuite........");
        System.out.println(ExtentReport.diretorioReport);
        //DriverFactory.executeChrome(ExtentReport.diretorioReport);
    }

}

BasePage:

public class BasePage {

    protected static DSL dsl;

    static List<String> result = Ambiente.dadosAmbiente();
    static String url = result.get(0);
    protected static String user = result.get(1);
    protected static String pass = result.get(2);

    public BasePage() {
        dsl = new DSL();
    }

}

DSL:

public class DSL {

    public void clicarRadio(By by) {
        getDriver().findElement(by).click();
    }

Other methods to access the screen elements (Text, Click, Button, Radio, Combo and etc.)

(...)

}

DriveFactory:

public class DriverFactory {

    static WebDriver driver;

    private DriverFactory() {
    }

    public static WebDriver getDriver() {

        if(Propriedades.tipoExecucao == TipoExecucao.LOCAL){

                if (driver == null) {
                    switch (Propriedades.browser) {
                    case CHROME:
                        executeChrome(BasePage.url);
                        break;
                    case FIREFOX:
                        executeFirefox(BasePage.url);
                        break;
                    case IE:
                        executeIE(BasePage.url);
                        break;
                    case EDGE:
                        executeEgde(BasePage.url);
                        break;
                    }
                    driver.manage().window().maximize();
                }
        }

        if(Propriedades.tipoExecucao == TipoExecucao.GRID) {

            DesiredCapabilities cap = null;
                switch (Propriedades.browser) {
                case CHROME:
                    cap = DesiredCapabilities.chrome();
                    break;
                case FIREFOX:
                    cap = DesiredCapabilities.firefox();
                    break;
                case IE:
                    cap = DesiredCapabilities.internetExplorer();
                    break;
                case EDGE:
                    cap = DesiredCapabilities.edge();
                    break;
                }

                try {
                    driver = new RemoteWebDriver(new URL("http://192.168.0.72:4444/wd/hub"), cap);
                } catch (MalformedURLException e) {
                    System.err.println("Falha ao conectar ao GRID");
                }
                driver.manage().window().maximize();
                driver.get(BasePage.url);
                System.out.println("Abriu Browser Grid");
    }

        return driver;
}

    public static void killDriver() {
        if (driver != null) {
            driver.close();
            driver.quit();
            driver = null;
        }
    }
}

Test - Class:

Test classes, just to check that execution is logging in and logout.

@Test
public void CN01_CT02_IncluirConteudoMp4(){

assertEquals("123", "123");
}

@Test

public void CN01_CT01_IncluirConteudoMp3() throws InterruptedException, AWTException{

assertEquals("123", "123456");
}

Configuration Grid

Config (Json) - Hub:

{
  "port": 4444,
  "newSessionWaitTimeout": -1,
  "servlets" : [],
  "withoutServlets": [],
  "custom": {},
  "capabilityMatcher": "org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
  "registry": "org.openqa.grid.internal.DefaultGridRegistry",
  "throwOnCapabilityNotPresent": true,
  "cleanUpCycle": 5000,
  "role": "hub",
  "debug": false,
  "browserTimeout": 0,
  "timeout": 1800
}

NodeChrome:

{
    "capabilities": [
        {
            "browserName": "chrome",
            "maxInstances": 1,
            "webdriver.chrome.driver": "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
        }
    ],
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 1,
    "port": 5555,
    "register": true,
    "registerCycle": 5000,
    "hub": "http://192.168.0.72:4444",
    "nodeStatusCheckTimeout": 5000,
    "nodePolling": 5000,
    "role": "node",
    "unregisterIfStillDownAfter": 60000,
    "downPollingLimit": 1,
    "debug": false,
    "servlets": [
    ],
    "withoutServlets": [

    ],
    "custom": {
    }
}

NodeFirefox:

{
    "capabilities": [
        {
            "browserName": "firefox",
            "maxInstances": 1,
            "webdriver.gecko.driver": "C:/Program Files/Mozilla Firefox/firefox.exe"
        }
    ],
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 1,
    "port": 5556,
    "register": true,
    "registerCycle": 5000,
    "hub": "http://192.168.0.72:4444",
    "nodeStatusCheckTimeout": 5000,
    "nodePolling": 5000,
    "role": "node",
    "unregisterIfStillDownAfter": 60000,
    "downPollingLimit": 1,
    "debug": false,
    "servlets": [

    ],
    "withoutServlets": [

    ],
    "custom": {
    }
}

When executing the code using Selenium GRID, the system opens two browsers but does not log in, problem occurs (apparently sync problem).

Example:

The login field is filled in "twice" and "Invalid Login" is returned.

Code is executed using the Eclipse IDE.
Run (SuiteTest.xml) - Run with TestNG


问:
jQuery UI Datepicker Slow During Typing
I've heard all these great experiences of how great and elegant jQuery is, but I'm 0 for 2 trying to implement jQuery controls in real world projects due to poor performance.  I am running into a similar problem as Richard this time.  The jQuery UI DatePicker failed User Acceptance Testing in an ASP.NET application I'm working on because while typing in the textbox, there is some lag specifically when entering in the last two numbers.  (e.g. '1/1/2010').

Does anyone know of an option/approach that would stop jQuery UI from interfering with the user's typing in the textbox that it's tied to?

答:
To expand on what Jason said, you can override the method outside the base ui file by doing this

```<code>jQuery(function(){
  jQuery.datepicker._doKeyUp = function(event) {
    var inst = jQuery.datepicker._getInst(event.target);
    if(jQuery.datepicker._datepickerShowing) {
        if(inst.input.val() != inst.lastVal) {
            try {
                var date = jQuery.datepicker.parseDate(jQuery.datepicker._get(inst, 'dateFormat'),
                                                       (inst.input ? inst.input.val() : null),
                                                       jQuery.datepicker._getFormatConfig(inst));
                if(date) { // only if valid
                    jQuery.datepicker._setDateFromField(inst);
                    jQuery.datepicker._updateAlternate(inst);
                    jQuery.datepicker._updateDatepicker(inst);
                }
            }
            catch (event) {
                jQuery.datepicker.log(event);
            }
        }
     }
      return true;
    }
 });
</code>```

.......

ContentLicense: CC BY-SA 2.5

Title: jQuery UI Datepicker Slow During Typing

Body:
To expand on what Jason said, you can override the method outside the base ui file by doing this

jQuery(function(){
  jQuery.datepicker._doKeyUp = function(event) {
    var inst = jQuery.datepicker._getInst(event.target);
    if(jQuery.datepicker._datepickerShowing) {
        if(inst.input.val() != inst.lastVal) {
            try {
                var date = jQuery.datepicker.parseDate(jQuery.datepicker._get(inst, 'dateFormat'),
                                                       (inst.input ? inst.input.val() : null),
                                                       jQuery.datepicker._getFormatConfig(inst));
                if(date) { // only if valid
                    jQuery.datepicker._setDateFromField(inst);
                    jQuery.datepicker._updateAlternate(inst);
                    jQuery.datepicker._updateDatepicker(inst);
                }
            }
            catch (event) {
                jQuery.datepicker.log(event);
            }
        }
     }
      return true;
    }
 });

.......


问:
Interpretation of Training, Testing (Dev) and Validation Score in Machine Learning
I have trained a Machine Learnig Model using Sklearn and looked at different scores for the traing, testing (dev) and validation set.

Here are the scores:

Accuracy on Train: 94.5468%
Accuracy on Test: 74.4646%
Accuracy on Validation: 65.6548%
Precision on Train: 96.7002%
Precision on Test: 85.2289%
Precision on Validation: 79.7178%
F1-Score on Train: 96.9761%
F1-Score on Test: 85.6203%
F1-Score on Validation: 79.6747%

I am having some problems with Interpretation of the scores. Is it normal, that the Model has a much worse result on the validation set?

Do you have thoughts on those results?

答:
As you explained in the comments, your test set is the set you used to tune your parameters and the validation set is the set that your model didn't use for training.

Considering that, it's natural that your Validation scores are lower than other scores.

When you're training a machine learning model, you show the training set to your model, that's why your model get's the best scores on training set, i.e. samples it has already seen and knows the answer for.

You use validation set to tune your parameters (e.g. degree of complexity in regression and so on) so your parameters are fine tuned for your validation sets but your model has not been trained on them. (for this you used the term test set, and to be fair they are sometimes used that way)

finally you have the least score on your test set which is natural since the parameters are not exactly tuned for the test set and the model has never seen them before.

if there is a huge hap between your training and test results, your model might have become overfit and there are ways to avoid that.

hope this helped ;)


问:
Flutter - Keep page static throughout lifecycle of app?
I have created an AppDrawer widget to wrap my primary drawer navigation and reference it in a single place, like so:

class AppDrawer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: new ListView(
          children: <Widget>[
            new ListTile(
              title: new Text("Page1"),
              trailing: new Icon(Icons.arrow_right),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => Page1.singleInstance));
              }
            ),
            new ListTile(
              title: new Text("Page2"),
              trailing: new Icon(Icons.arrow_right),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new Page2("Page 2")));
              }
            ),
          ]
        ),
      );
  }
}
```

<p>I have also created a custom AppScaffold widget, which simply returns a consistent AppBar, my custom AppDrawer, and body:</p>

<pre class="lang-dart prettyprint-override"><code>class AppScaffold extends StatelessWidget {
  final Widget body;
  final String pageTitle;

  AppScaffold({this.body, this.pageTitle});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(title: new Text(pageTitle), backgroundColor: jet),
      drawer: AppDrawer(),
      body: body
    );
  }
}
</code>```

I have created two pages: Page1, and Page2.  They are simple right now, and look something like this:

class Page1 extends StatelessWidget {
  final String pageText;

  Page1(this.pageText);

  static Page1 get singleInstance => Page1("Page1");

  Widget build(BuildContext context) {
    return AppScaffold(
      pageTitle: this.pageText,
      body: SafeArea(
        child: Stack(
          children: <Widget>[
            Center(child: SomeCustomWidget())
          ],
        )
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  final String pageText;

  Page2(this.pageText);

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      pageTitle: this.pageText,
      body: SafeArea(
        child: Stack(
          children: <Widget>[
            Center(child: SomeOtherCustomWidget())
          ],
        )
      ),
    );
  }
}
```

When I run my app, I can see the navbar and drawer correctly.  I can click on the links in the drawer to navigate between my pages.  However, each time I navigate to a page, all of the widgets on that page get reset to their initial state.  I want to ensure that the widgets do not get reset.  Another way to think of this is: I only want one instance of each page throughout the lifecycle of the app, instead of creating them new whenever a user navigates to them.

I tried creating a static instance of Page1 that the Drawer uses when the onTap event is fired, but this does not work. Am I thinking about this incorrectly?  Do I need to convert to a Stateful widget?

答:
Oh, you're in for a treat... This will be kinda long (sorry) but please read all of it before making decisions and taking action - I promise I am saving you time.

There are many different solutions to this problem, but in general what you're asking about is state management (which is really software engineering, more info here - Understanding state management, and why you never will).

I'll try my best to explain what is happening in your specific case...

Problem:

Think of Navigator as a List of application states, which you can manipulate via its various methods (i.e. pop(), push(), etc.), with this in mind it is clear what is happening - on a button press you're actually removing the current state (page) and right after that you're pushing a new instance of your state (page).

Solution(s):

As I said, there are many solutions to this problem, for example, you may be tempted to store the state (the changes you made to a particular "page") somewhere in a var and inject that var when navigating between "pages", when creating a new instance of that page, but you'll soon run into other problems. This is why I don't think anyone can provide a simple solution to this problem...

First, may I suggest you some useful reads on the matter:
Flutter official docs on state management - When you get to the "Options" section of this, the fun part begins and can quickly get overwhelming, but fear not :P

Be sure to read the medium article mentioned in the start of my answer too, I found it really helpful.

These reads will be more than enough to help you make a decision, plus there are a ton of articles on Medium and YouTube videos touching on the matter of state management with Flutter (even some from the authors of the framework) - just search for "State management with Flutter".

Now my own personal opinion:

If it's a really simple use case and you don't plan to grow (which is almost never the case, trust me), you can just use StatefulWidgets in combination with setState() and maybe InheritedWidget (for dependency injection down the tree, or like React guys call it "lifting state up"). Or instead of the above, maybe have a look at scoped_model, which kinda abstracts all of this for you (tho, I haven't played with it).

What I use right now for a real world project is bloc and flutter_bloc (BLoC = Business Logic Component), I will not get into the details of it, but basically it takes the idea of scoped_model one step further, without over-complicating abstractions. bloc is responsible for abstracting away the "business logic" of your application and flutter_bloc to "inject" the state in your UI and react to state changes (official Flutter position on the matter is that UI = f(State)).
A BLoC has an input and an output, it takes in events as an input (can be user input, or other, any type of event really) and produces a state. In summary that's it about bloc.
A great way to get started is BLoC's official documentation. I highly recommend it. Just go through everything.

(p.s. This may be my personal opinion, but in the end state management in Flutter is all based on some form of using InheritedWidget and setState() in response to user input or other external factors that should change the application state, so I think the BLoC pattern is really on point with abstracting those :P)

Body:
I have created an AppDrawer widget to wrap my primary drawer navigation and reference it in a single place, like so:

class AppDrawer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: new ListView(
          children: <Widget>[
            new ListTile(
              title: new Text("Page1"),
              trailing: new Icon(Icons.arrow_right),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => Page1.singleInstance));
              }
            ),
            new ListTile(
              title: new Text("Page2"),
              trailing: new Icon(Icons.arrow_right),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new Page2("Page 2")));
              }
            ),
          ]
        ),
      );
  }
}

I have also created a custom AppScaffold widget, which simply returns a consistent AppBar, my custom AppDrawer, and body:

class AppScaffold extends StatelessWidget {
  final Widget body;
  final String pageTitle;

  AppScaffold({this.body, this.pageTitle});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(title: new Text(pageTitle), backgroundColor: jet),
      drawer: AppDrawer(),
      body: body
    );
  }
}

I have created two pages: Page1, and Page2.  They are simple right now, and look something like this:

class Page1 extends StatelessWidget {
  final String pageText;

  Page1(this.pageText);

  static Page1 get singleInstance => Page1("Page1");

  Widget build(BuildContext context) {
    return AppScaffold(
      pageTitle: this.pageText,
      body: SafeArea(
        child: Stack(
          children: <Widget>[
            Center(child: SomeCustomWidget())
          ],
        )
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  final String pageText;

  Page2(this.pageText);

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      pageTitle: this.pageText,
      body: SafeArea(
        child: Stack(
          children: <Widget>[
            Center(child: SomeOtherCustomWidget())
          ],
        )
      ),
    );
  }
}

When I run my app, I can see the navbar and drawer correctly.  I can click on the links in the drawer to navigate between my pages.  However, each time I navigate to a page, all of the widgets on that page get reset to their initial state.  I want to ensure that the widgets do not get reset.  Another way to think of this is: I only want one instance of each page throughout the lifecycle of the app, instead of creating them new whenever a user navigates to them.

I tried creating a static instance of Page1 that the Drawer uses when the onTap event is fired, but this does not work. Am I thinking about this incorrectly?  Do I need to convert to a Stateful widget?


问:
How to represent a buffer as linked list in C
I have preallocated buffer (array of chars) to which strings are being written, it looks like this:
"This\0buffer\0contains\0strings\00000..."

I want to be able to remove the last string, so I came up with the idea to represent each string in the buffer as a linked list node with pointers to its start and end, so I would just find the last node and fill the region it holds with zeros.

```<code>struct node
{
  char *str_start;
  char *str_end;
  struct node *next;
};
</code>```

It looks like a very common problem, however, I failed to find such implementations anywhere.

The question is: Is there some data structure for my usecase I overlooked, or is there a better solution to do this?

Note: This is to be used in the kernel module, so maybe it's already implemented in kernel

答:
You could use a 2 dimensional array (considering the buffer is preallocated and you know of a maximum size for every string).

That would make enforcing string sizes easier, hence your code more secure.

Body:
I have preallocated buffer (array of chars) to which strings are being written, it looks like this:
"This\0buffer\0contains\0strings\00000..."

I want to be able to remove the last string, so I came up with the idea to represent each string in the buffer as a linked list node with pointers to its start and end, so I would just find the last node and fill the region it holds with zeros.

struct node
{
  char *str_start;
  char *str_end;
  struct node *next;
};

It looks like a very common problem, however, I failed to find such implementations anywhere.

The question is: Is there some data structure for my usecase I overlooked, or is there a better solution to do this?

Note: This is to be used in the kernel module, so maybe it's already implemented in kernel


问:
How can I instantiate a lambda closure type in C++11/14?
I'm aware that there's no default constructor for lambda closure type. But does that mean it's impossible to instantiate it after it being passed as a template parameter?

Consider the following minimal example:

```<code>#include <iostream>

template <typename FuncType>
std::pair<int,int> DoSomething() {
    return FuncType()(std::make_pair(1,1));
}

int main() {
    auto myLambda = [](std::pair<int,int> x) {
        return std::make_pair(x.first*2,x.second*2);
    };
    std::pair<int,int> res = DoSomething<decltype(myLambda)>();
    return 0;
}
</code>```

For performance reasons, I can't use std::function to avoid virtual pointer calls. Is there a way to do this? I need to instantiate that lambda once and use it many times inside that function.

How does the standard library make it work when decltype(myLambda) is passed to something like std::map comparators in the template parameter?

答:
I'm aware that there's no default constructor for lambda closure type.

Yes, this is true until C++20. (Note that since C++20 if no captures are specified, the closure type has a defaulted default constructor.)

Closure types are not DefaultConstructible. Closure types have a deleted (until C++14) no (since C++14) default constructor.  (until C++20)

And

How does the standard library make it work when decltype(myLambda) is passed to something like std::map comparators in the template parameter?

There's nothing special for the standard library. If you specify a non-DefaultConstructible lambda as the comparator type for std::map, you have to pass an object to the constructor, std::map will initialized its comparator via copy; lambda has copy and move constructor.

You can change your code to the same way as std::map's constructor:

```<code>template <typename FuncType>
std::pair<int,int> DoSomething(const FuncType& f = FuncType()) {
    // auto z(f);   // you can take a copy if necessary
    return f(std::make_pair(1,1));
}
</code>```

then

```<code>auto myLambda = [](std::pair<int,int> x) {
    return std::make_pair(x.first*2,x.second*2);
};
std::pair<int,int> res = DoSomething<decltype(myLambda)>(myLambda);
</code>```

LIVE

Body:
I'm aware that there's no default constructor for lambda closure type. But does that mean it's impossible to instantiate it after it being passed as a template parameter?

Consider the following minimal example:

#include <iostream>

template <typename FuncType>
std::pair<int,int> DoSomething() {
    return FuncType()(std::make_pair(1,1));
}

int main() {
    auto myLambda = [](std::pair<int,int> x) {
        return std::make_pair(x.first*2,x.second*2);
    };
    std::pair<int,int> res = DoSomething<decltype(myLambda)>();
    return 0;
}

For performance reasons, I can't use std::function to avoid virtual pointer calls. Is there a way to do this? I need to instantiate that lambda once and use it many times inside that function.

How does the standard library make it work when decltype(myLambda) is passed to something like std::map comparators in the template parameter?

Body:
I'm aware that there's no default constructor for lambda closure type.

Yes, this is true until C++20. (Note that since C++20 if no captures are specified, the closure type has a defaulted default constructor.)

Closure types are not DefaultConstructible. Closure types have a deleted (until C++14) no (since C++14) default constructor.  (until C++20)

And

How does the standard library make it work when decltype(myLambda) is passed to something like std::map comparators in the template parameter?

There's nothing special for the standard library. If you specify a non-DefaultConstructible lambda as the comparator type for std::map, you have to pass an object to the constructor, std::map will initialized its comparator via copy; lambda has copy and move constructor.

You can change your code to the same way as std::map's constructor:

template <typename FuncType>
std::pair<int,int> DoSomething(const FuncType& f = FuncType()) {
    // auto z(f);   // you can take a copy if necessary
    return f(std::make_pair(1,1));
}

then

auto myLambda = [](std::pair<int,int> x) {
    return std::make_pair(x.first*2,x.second*2);
};
std::pair<int,int> res = DoSomething<decltype(myLambda)>(myLambda);

LIVE


问:
Add my app to AutoStart apps list in android programmatically
I want my app to be in the autostart list after installation.

I know when I install an app like (whatsapp) it goes automatically to the autostart list.
I want my app to be the same

I tried the code in this question
How to Autostart an Android Application?

but unfortunately non of the answers actually made the app autostart.

Not sure if I am doing something wrong

the reason that I need the app be autostart is just to get notifications from the webservice. as the app does not get notifications unless its open or autostart is on

would appreciate your help

thanks

答:
Few popular apps run in background without being killed during memory cleanup cycle (many of the popular OEMs customize the stack ROM for battery/memory optimization), because they are "White listed" by these manufactures. For your app you can whitelist it either manually (via corresponding "settings" for the devices) or pragmatically by redirecting users to the corresponding settings page to white list the app.

Please have a look for details here


问:
Problem with UIImageView loading via OperationQueue
I load a UIImageView using an NSOperationQueue.

The load fetches an image from the Internet and then adds it to an image view.  The problem I have is that the method finishes but it takes about 3 seconds later for the image view to actually either show the image or remove the image view from the superview...

```<code>- (void)viewDidLoad { NSLog(@"AirportDetailView: viewDidLoad");
    [super viewDidLoad];
    [self.activity startAnimating];
    self.queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadImage) object:NULL];
    [self.queue addOperation:operation];
    [operation release];
}

-(void)loadImage {
        [myAp ImageForAp];

        NSLog(@"ImageFor Ap Ended, %@",myAp.ApDiagram);

        [self.activity stopAnimating];

        if (myAp.ApDiagram==NULL) {
            NSLog(@"Finally Gets Here");
            [self.Diagram removeFromSuperview];
        }
        else {
            NSLog(@"Finally Gets Here with Diag");
            [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal];
        }

    }
</code>```

The NSLOG shows a delay between the first two log statements of about 3 seconds can't understand why....

Updated with my Latest Code......

```<code>-(void)loadImage {

    [myAp ImageForAp];

    NSLog(@"ImageFor Ap Ended, %@",myAp.ApDiagram);

    [self performSelectorOnMainThread:@selector(UpdateUI) withObject:nil waitUntilDone:NO];
}

-(void)UpdateUI {

    [self.activity stopAnimating];

    if (myAp.ApDiagram==NULL) {
        NSLog(@"Finally Gets Here");
        [self.Diagram removeFromSuperview];
    }
    else {
        NSLog(@"Finally Gets Here with Diag");
        [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal];
    }
}
</code>```

答:
Make sure that the loadImage method is being run on the main thread. All UI operations need to happen on the main thread to work as expected. Your code will need to look similar to this.

```<code>-(void)loadImage {
    [myAp ImageForAp];
    [self performSelectorOnMainThread:@selector(UpdateUI) withObject:nil waitUntilDone:NO];
}

-(void)UpdateUI {
    [self.activity stopAnimating];

    if (myAp.ApDiagram==NULL) {
        [self.Diagram removeFromSuperview];
    }
    else {
        [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal];
    }
}
</code>```

There is also a possible memory leak inside of viewDidLoad.

self.queue = [NSOperationQueue new]; should be changed to

self.queue = [[[NSOperationQueue alloc] init] autorelease];

Body:
I load a UIImageView using an NSOperationQueue.

The load fetches an image from the Internet and then adds it to an image view.  The problem I have is that the method finishes but it takes about 3 seconds later for the image view to actually either show the image or remove the image view from the superview...

- (void)viewDidLoad { NSLog(@"AirportDetailView: viewDidLoad");
    [super viewDidLoad];
    [self.activity startAnimating];
    self.queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadImage) object:NULL];
    [self.queue addOperation:operation];
    [operation release];
}

-(void)loadImage {
        [myAp ImageForAp];

        NSLog(@"ImageFor Ap Ended, %@",myAp.ApDiagram);

        [self.activity stopAnimating];

        if (myAp.ApDiagram==NULL) {
            NSLog(@"Finally Gets Here");
            [self.Diagram removeFromSuperview];
        }
        else {
            NSLog(@"Finally Gets Here with Diag");
            [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal];
        }

    }

The NSLOG shows a delay between the first two log statements of about 3 seconds can't understand why....

Updated with my Latest Code......

-(void)loadImage {

    [myAp ImageForAp];

    NSLog(@"ImageFor Ap Ended, %@",myAp.ApDiagram);

    [self performSelectorOnMainThread:@selector(UpdateUI) withObject:nil waitUntilDone:NO];
}

-(void)UpdateUI {

    [self.activity stopAnimating];

    if (myAp.ApDiagram==NULL) {
        NSLog(@"Finally Gets Here");
        [self.Diagram removeFromSuperview];
    }
    else {
        NSLog(@"Finally Gets Here with Diag");
        [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal];
    }
}

Body:
Make sure that the loadImage method is being run on the main thread. All UI operations need to happen on the main thread to work as expected. Your code will need to look similar to this.

-(void)loadImage {
    [myAp ImageForAp];
    [self performSelectorOnMainThread:@selector(UpdateUI) withObject:nil waitUntilDone:NO];
}

-(void)UpdateUI {
    [self.activity stopAnimating];

    if (myAp.ApDiagram==NULL) {
        [self.Diagram removeFromSuperview];
    }
    else {
        [self.Diagram setBackgroundImage:myAp.ApDiagram forState:UIControlStateNormal];
    }
}

There is also a possible memory leak inside of viewDidLoad.

self.queue = [NSOperationQueue new]; should be changed to

self.queue = [[[NSOperationQueue alloc] init] autorelease];


问:
The variables I updated in my forEach, return to their original value
I am trying to query, that would get all of the earning and withdrawal amount and sum, but somehow after the forEach loop is done and exits, all of the updated values I placed in a variable return to their original values.</p>

```<code>  var withdrawbalance = 0;
  var totalearning = 0;

  userplans.forEach((up) => {
    DepositEarning.findOne({deposit: up.deposit._id})
      .then(depositearning => {
        withdrawbalance += parseInt(depositearning.WithdrawableBalance, 10);
      });
    Earning.findOne({deposit: up.deposit._id})
      .then(earnings => {
        totalearning += parseInt(earnings.Earning, 10);
    });
  })

  console.log(withdrawbalance);
  console.log(totalearning);
</code>```

答: I think the reason could be that DepositEarning.findOne() and Earning.findOne() are both async functions. This means that they don't return immediately with a value, hence your variables are still the same after the loop.</p>

Body:
I am trying to query, that would get all of the earning and withdrawal amount and sum, but somehow after the forEach loop is done and exits, all of the updated values I placed in a variable return to their original values.

  var withdrawbalance = 0;
  var totalearning = 0;

  userplans.forEach((up) => {
    DepositEarning.findOne({deposit: up.deposit._id})
      .then(depositearning => {
        withdrawbalance += parseInt(depositearning.WithdrawableBalance, 10);
      });
    Earning.findOne({deposit: up.deposit._id})
      .then(earnings => {
        totalearning += parseInt(earnings.Earning, 10);
    });
  })

  console.log(withdrawbalance);
  console.log(totalearning);


问:
Google smart lock showing all my phone accounts in an app instead the ones previously used
I'm developing an app and 've implemented smart lock.

The problem is that at first, having several google accounts in my phone, when I press login, a smart lock modal appears saying.. Continue with.. And then a list of all my accounts appear (even if I didn't use those accounts in my app, or in any other app, for example I have one for google calendar exclusively, and it shows) at the end I press none of the above. Then I enter the credentials and they are correctly saved.

After that, everything works as expected, meaning that after closing the app and reopened, the smart lock correctly autocomplete the credentials and I correctly enter.

I wonder what I'm missing, if I enter to spotify they just show the accounts where I previously login, not all.

I've found some extra info but apparently no valid answers.

Smart Lock multi account resolution always showing up

Smart Lock shows accounts not from my app

Just in case the question is not clear.. How can I filter the previously used accounts in my domain or app? Or how can take out that modal (now it's acting just like autofiller in case  any of the shown emails matches the one you're looking for.

答:
I think what you're looking for is here

https://developers.google.com/identity/smartlock-passwords/android/associate-apps-and-sites

Add that json file and the application, and you would be set


问:
Modify Ms-Access Table Structure
I have an access table with certain structure and I want to copy it to a table with a different structure. The structure of the original table is:

```<code>col1-ddate(datetime)
col2-type(text)
col3-vvalue(number).
</code>```

Each 3 rows have the same date. The type has repeated 3 values(sys, dia, pul).
Now I want to insert this table data to a new(temporary) table which has the following structure

```<code>col1-ddate(datetime)
col2-sys(number)
col3-dia(number)
col4-Pul(number)
</code>```

How can I do that?

答:
If I've understood correctly, a SQL query using conditional aggregation should achieve what you are looking for, grouping by the datetime field, e.g.:

select
    col1-ddate,
    max(iif(col2-type = "sys", col3-vvalue, null)) as col2-sys,
    max(iif(col2-type = "dia", col3-vvalue, null)) as col3-dia,
    max(iif(col2-type = "pul", col3-vvalue, null)) as col4-pul
into
    NewTemporaryTable
from
    YourTable
group by
    col1-ddate
```

Change YourTable to the name of your existing table.

Title: Modify Ms-Access Table Structure

Body:
I have an access table with certain structure and I want to copy it to a table with a different structure. The structure of the original table is:

col1-ddate(datetime)
col2-type(text)
col3-vvalue(number).

Each 3 rows have the same date. The type has repeated 3 values(sys, dia, pul).
Now I want to insert this table data to a new(temporary) table which has the following structure

col1-ddate(datetime)
col2-sys(number)
col3-dia(number)
col4-Pul(number)

How can I do that?

Body:
If I've understood correctly, a SQL query using conditional aggregation should achieve what you are looking for, grouping by the datetime field, e.g.:

select
    col1-ddate,
    max(iif(col2-type = "sys", col3-vvalue, null)) as col2-sys,
    max(iif(col2-type = "dia", col3-vvalue, null)) as col3-dia,
    max(iif(col2-type = "pul", col3-vvalue, null)) as col4-pul
into
    NewTemporaryTable
from
    YourTable
group by
    col1-ddate

Change YourTable to the name of your existing table.