问:
how to copy files to remote server using scp2 in node js?
I want to copy the files from local server to remote server in Node js using scp2 package.  First of all.. Files uploaded to local server using multer after that copy or move that files to remote server.

My Code:

```<code>exports.newFileUpload =  function(req , res , next){

    var storage = multer.diskStorage({ //multers disk storage settings
      destination: function (req, file, cb) {
         cb(null, 'uploads/');
      },
      filename: function (req, file, cb) {
          var datetimestamp = Date.now();
          cb(null,  datetimestamp+ '-' +file.originalname);
      }
  });
        var upload = multer({ storage: storage, limits: { fieldSize: 25 * 1024 * 1024 }}).array('file');
        upload(req,res,function(err){
                console.log(req.body);
                console.log(req.files);
            if(err){
                res.json({error_code:1,err_desc:err});
                console.log("Error Occured", err);
                return;
            }else{

                client.scp(req.files[0].path, {
                    host: 'www.do********.in',
                    username: 'username',
                    password: '*********',
                    path: '/uploads/'
                }, function(err) {
                    console.log(req.files[0].path);
                    console.log("files uploaded in remote server");
                    res.json({error_code:0,err_desc:null});
                });
            }
        });
}
</code>```

file upload to local server is perfectly working, after that to remote server throwing error

Error:

```<code>{ date: 'Mon Nov 13 2017 01:00:22 GMT+0530 (India Standard Time)',
  process:
   { pid: 5664,
     uid: null,
     gid: null,
     cwd: 'D:\\sample',
     execPath: 'C:\\Program Files\\nodejs\\node.exe',
     version: 'v8.2.1',
     argv: [ 'C:\\Program Files\\nodejs\\node.exe', 'D:\\sample\\app.js' ],
     memoryUsage:
      { rss: 69619712,
        heapTotal: 45162496,
        heapUsed: 39166256,
        external: 149849 } },
  os: { loadavg: [ 0, 0, 0 ], uptime: 3537.1088452 },
  trace:
   [ { column: 11,
       file: 'util.js',
       function: 'Object.exports._errnoException',
       line: 1024,
       method: '_errnoException',
       native: false },
     { column: 20,
       file: 'util.js',
       function: 'exports._exceptionWithHostPort',
       line: 1047,
       method: '_exceptionWithHostPort',
       native: false },
     { column: 14,
       file: 'net.js',
       function: 'TCPConnectWrap.afterConnect [as oncomplete]',
       line: 1150,
       method: 'afterConnect [as oncomplete]',
       native: false } ],
  stack:[ 'Error: Can\'t set headers after they are sent.',
     '    at validateHeader (_http_outgoing.js:504:11)',
     '    at ServerResponse.setHeader (_http_outgoing.js:511:3)',
     '    at ServerResponse.header (D:\\sample\\node_modules\\express\\lib\\response.js:730:10)',
     '    at ServerResponse.send (D:\\sample\\node_modules\\express\\lib\\response.js:170:12)',
     '    at ServerResponse.json (D:\\sample\\node_modules\\express\\lib\\response.js:256:15)',
     '    at D:\\sample\\routes\\part.js:302:10',
     '    at Client.closeHandler (D:\\sample\\node_modules\\scp2\\lib\\scp.js:48:13)',
     '    at emitNone (events.js:105:13)',
     '    at Client.emit (events.js:207:7)',
     '    at Client.<anonymous> (D:\\sample\\node_modules\\scp2\\lib\\client.js:88:10)',
     '    at emitNone (events.js:105:13)',
     '    at Client.emit (events.js:207:7)',
     '    at Socket.<anonymous> (D:\\sample\\node_modules\\ssh2\\lib\\client.js:225:10)',
     '    at emitOne (events.js:115:13)',
     '    at Socket.emit (events.js:210:7)',
     '    at Pipe._handle.close [as _onclose] (net.js:549:12)' ] }
</code>```

Couldn't able to identify the error, awaiting  suggestions or possible ways to solve the problem.

Thanks in Advance !

答:
Uploading Files to remote server using multer is not possible directly, But we can play around with multer-sftp, scp, ssh techniques Methodologies

When Uploading Files to remote server using Node Js, We need to take care few things

Username and password should be correct

The Corresponding port number should be open in remote server

The Remote Directory Should have Write Access

Working Code using scp2 to move the files to remote server:

```<code>exports.newFileUpload =  function(req , res , next){

    var storage = multer.diskStorage({ //multers disk storage settings
      destination: function (req, file, cb) {
         cb(null, 'uploads/');
      },
      filename: function (req, file, cb) {
          var datetimestamp = Date.now();
          cb(null,  datetimestamp+ '-' +file.originalname);
      }
  });
        var upload = multer({ storage: storage, limits: { fieldSize: 25 * 1024 * 1024 }}).array('file');
        upload(req,res,function(err){
                console.log(req.body);
                console.log(req.files);
            if(err){
                res.json({error_code:1,err_desc:err});
                console.log("Error Occured", err);
                return;
            }else{

                client.scp(req.files[0].path, {
                    host: 'host',
                    username: 'username',
                    password: '*********',
                    path: '/uploads/'
                }, function(err) {
                    console.log(req.files[0].path);
                    console.log("files uploaded in remote server");
                });
            }
        });
}
</code>```

Note: Should install required packages as well as declare require things in code.

References: multer-sftp, scp2 , node-ssh

Body:
I want to copy the files from local server to remote server in Node js using scp2 package.  First of all.. Files uploaded to local server using multer after that copy or move that files to remote server.

My Code:

exports.newFileUpload =  function(req , res , next){

    var storage = multer.diskStorage({ //multers disk storage settings
      destination: function (req, file, cb) {
         cb(null, 'uploads/');
      },
      filename: function (req, file, cb) {
          var datetimestamp = Date.now();
          cb(null,  datetimestamp+ '-' +file.originalname);
      }
  });
        var upload = multer({ storage: storage, limits: { fieldSize: 25 * 1024 * 1024 }}).array('file');
        upload(req,res,function(err){
                console.log(req.body);
                console.log(req.files);
            if(err){
                res.json({error_code:1,err_desc:err});
                console.log("Error Occured", err);
                return;
            }else{

                client.scp(req.files[0].path, {
                    host: 'www.do********.in',
                    username: 'username',
                    password: '*********',
                    path: '/uploads/'
                }, function(err) {
                    console.log(req.files[0].path);
                    console.log("files uploaded in remote server");
                    res.json({error_code:0,err_desc:null});
                });
            }
        });
}

file upload to local server is perfectly working, after that to remote server throwing error

Error:

{ date: 'Mon Nov 13 2017 01:00:22 GMT+0530 (India Standard Time)',
  process:
   { pid: 5664,
     uid: null,
     gid: null,
     cwd: 'D:\\sample',
     execPath: 'C:\\Program Files\\nodejs\\node.exe',
     version: 'v8.2.1',
     argv: [ 'C:\\Program Files\\nodejs\\node.exe', 'D:\\sample\\app.js' ],
     memoryUsage:
      { rss: 69619712,
        heapTotal: 45162496,
        heapUsed: 39166256,
        external: 149849 } },
  os: { loadavg: [ 0, 0, 0 ], uptime: 3537.1088452 },
  trace:
   [ { column: 11,
       file: 'util.js',
       function: 'Object.exports._errnoException',
       line: 1024,
       method: '_errnoException',
       native: false },
     { column: 20,
       file: 'util.js',
       function: 'exports._exceptionWithHostPort',
       line: 1047,
       method: '_exceptionWithHostPort',
       native: false },
     { column: 14,
       file: 'net.js',
       function: 'TCPConnectWrap.afterConnect [as oncomplete]',
       line: 1150,
       method: 'afterConnect [as oncomplete]',
       native: false } ],
  stack:[ 'Error: Can\'t set headers after they are sent.',
     '    at validateHeader (_http_outgoing.js:504:11)',
     '    at ServerResponse.setHeader (_http_outgoing.js:511:3)',
     '    at ServerResponse.header (D:\\sample\\node_modules\\express\\lib\\response.js:730:10)',
     '    at ServerResponse.send (D:\\sample\\node_modules\\express\\lib\\response.js:170:12)',
     '    at ServerResponse.json (D:\\sample\\node_modules\\express\\lib\\response.js:256:15)',
     '    at D:\\sample\\routes\\part.js:302:10',
     '    at Client.closeHandler (D:\\sample\\node_modules\\scp2\\lib\\scp.js:48:13)',
     '    at emitNone (events.js:105:13)',
     '    at Client.emit (events.js:207:7)',
     '    at Client.<anonymous> (D:\\sample\\node_modules\\scp2\\lib\\client.js:88:10)',
     '    at emitNone (events.js:105:13)',
     '    at Client.emit (events.js:207:7)',
     '    at Socket.<anonymous> (D:\\sample\\node_modules\\ssh2\\lib\\client.js:225:10)',
     '    at emitOne (events.js:115:13)',
     '    at Socket.emit (events.js:210:7)',
     '    at Pipe._handle.close [as _onclose] (net.js:549:12)' ] }

Couldn't able to identify the error, awaiting  suggestions or possible ways to solve the problem.

Thanks in Advance !

Body:
Uploading Files to remote server using multer is not possible directly, But we can play around with multer-sftp, scp, ssh techniques Methodologies

When Uploading Files to remote server using Node Js, We need to take care few things

Username and password should be correct

The Corresponding port number should be open in remote server

The Remote Directory Should have Write Access

Working Code using scp2 to move the files to remote server:

exports.newFileUpload =  function(req , res , next){

    var storage = multer.diskStorage({ //multers disk storage settings
      destination: function (req, file, cb) {
         cb(null, 'uploads/');
      },
      filename: function (req, file, cb) {
          var datetimestamp = Date.now();
          cb(null,  datetimestamp+ '-' +file.originalname);
      }
  });
        var upload = multer({ storage: storage, limits: { fieldSize: 25 * 1024 * 1024 }}).array('file');
        upload(req,res,function(err){
                console.log(req.body);
                console.log(req.files);
            if(err){
                res.json({error_code:1,err_desc:err});
                console.log("Error Occured", err);
                return;
            }else{

                client.scp(req.files[0].path, {
                    host: 'host',
                    username: 'username',
                    password: '*********',
                    path: '/uploads/'
                }, function(err) {
                    console.log(req.files[0].path);
                    console.log("files uploaded in remote server");
                });
            }
        });
}

Note: Should install required packages as well as declare require things in code.

References: multer-sftp, scp2 , node-ssh


来源: stackexchange

问:
Resolving Youtube channel like https://youtube.com/c/xyz
It is fairly easy to request youtube channel or user info when you have a url like yourtube.com/channel/xyz or youtube.com/user/xyz because you can just strip the username/channelid from the url. However I have problems associating an url like https://youtube.com/c/xyz to any kind of resource.

It doesnt seem to be a user, nor a channel?

答:
In HTML there is something called the canonical link element. This is an element that you put on a page which is a duplicate of another page and the element points to the canonical or "master" copy of that content.

If you view the source of https://youtube.com/c/Rsmuk1 and search for "canonical" you find the element which points to the primary channel page.

```<code><link rel="canonical" href="https://www.youtube.com/channel/UCMi7-BZZX9x8CAhE-5juNyw">
</code>```

You could therefore retrieve the long url by requesting the page in a language of your choice and then parsing out that element. Here's an example in Python 3 using BeautifulSoup and requests

```<code>from bs4 import BeautifulSoup
import requests

document = requests.get('https://www.youtube.com/channel/UCMi7-BZZX9x8CAhE-5juNyw')

soup = BeautifulSoup(document.content, "lxml")
links = soup.findAll('link', rel='canonical')
for link in links:
    print(link['href'])

# Prints: https://www.youtube.com/channel/UCMi7-BZZX9x8CAhE-5juNyw
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In HTML there is something called the canonical link element. This is an element that you put on a page which is a duplicate of another page and the element points to the canonical or "master" copy of that content.

If you view the source of https://youtube.com/c/Rsmuk1 and search for "canonical" you find the element which points to the primary channel page.

<link rel="canonical" href="https://www.youtube.com/channel/UCMi7-BZZX9x8CAhE-5juNyw">

You could therefore retrieve the long url by requesting the page in a language of your choice and then parsing out that element. Here's an example in Python 3 using BeautifulSoup and requests

from bs4 import BeautifulSoup
import requests

document = requests.get('https://www.youtube.com/channel/UCMi7-BZZX9x8CAhE-5juNyw')

soup = BeautifulSoup(document.content, "lxml")
links = soup.findAll('link', rel='canonical')
for link in links:
    print(link['href'])

# Prints: https://www.youtube.com/channel/UCMi7-BZZX9x8CAhE-5juNyw


问:
Find string pairs
I was trying to practice a few string and algorithmic based questions and i stumbled across one which has the below wordings:

You have a string x of length N, which consists of small English letters. You have to find the number of sub-strings S in x such that 0 <= d < c < b < a <= N - 1 and x[a] == x[c] and x[b] == x[d].

For example:
x = "ababa"
The answer is s=2 since there are two strings which fulfill the above condition:
abab and
baba.

What is the best approach to solve this problem?

Thanks in advance.

答:
For the condition x[a] == x[c] and x[b] == x[d] to be true we need to consider two cases:

One is when x[a]== x[b] ie. the same character repeated 4 or more times, we call this case similarities, to handle this case we create a structure to store the character and its frequent, then when its frequent>=4 we have the pattern we are looking for. you can see below that it is handled separately in  the code. the number of possible combination could be calculated mathematically using:

```<code>C(n,r)=n!/((n−r)!r!) // r=4 here, and n is the frequency of the character.
</code>```

We calculate this for all the similarities and add the some to the total resulted by the non-similarities.

The other case is to look for two different characters x[a]!= x[b].

```<code>X="arbsatbuavb"    Then n=3 (a after b 3 times); S=n(n-1)/2=3
X="arbsatbuavbwaxb" Then n=4; S=n(n-1)/2=6
</code>```

Here we need to parse the array and look for every distinct occurrence of two characters putting them as keys to a dictionary structure <key,value> where the value here represents the number of occurrences of b after a (but no more Bs counted for that a), then for every key in the structure we use the following mathematical method to get the total number of sub-strings for non-similarities occurrences that fulfill the condition:

S =

Here is the algorithm implemented and its results:

```<code>public static void main(String[] args) {
    System.out.println("TOTAL S ="+ calculate("aaaaa"));
}

public static int calculate(String str) {
    int s = 0;
    Map<String, Integer> struct = new HashMap<String, Integer>();
    Map<String, String> indexes = new HashMap<String, String>();
    Map<String, String> similarities = new HashMap<String, String>();
    String[] x = str.split("(?!^)");// convert the string to array.

    //Handle similarities
    for (int i = 0; i < x.length; i++) {
        if (similarities.containsKey(x[i])) {
            similarities.put(x[i], similarities.get(x[i]) + "," + i); // "a": 1,3,7...
        } else {
            similarities.put(x[i], i + "");
        }
    }

    //Ignore similarities
    ArrayList<String> temp = new ArrayList<String>();
    for (int i = 0; i < x.length - 1; i++) {
        temp.clear();// this temp is important otherwise "cdxd" will count
                        // "cd" twice!!!
        for (int j = i + 1; j < x.length; j++) {
            if (!x[i].equals(x[j])) {// for example if "abcdamn" when reach the second a stop j and jump to the next i.
                if (struct.containsKey(x[i] + x[j])) { // NOTE x[i] + x[j] is a String
                    if (!temp.contains(x[j])) {

                        struct.put(x[i] + x[j], struct.get(x[i] + x[j]) + 1);
                        temp.add(x[j]);

                        //Update
                        indexes.put(x[i] + x[j],indexes.get(x[i] + x[j])+ ";"+i+","+j);

                    }
                }

                //UP I have excluded similarities ie. if we have the following "aaaaa" then we have c(5,4) =

                else {

                    struct.put(x[i] + x[j], 1); // NOTE x[i] + x[j] is a String
                    temp.add(x[j]);

                    //Update
                    indexes.put(x[i] + x[j], i+","+j);
                }
            } else {
              break;
            }
        }
    }
    // now compute the result when similarities ignored
    for (Map.Entry<String, Integer> entry : struct.entrySet()) {
        s += entry.getValue() * (entry.getValue() - 1) / 2;
    }

    //Update
    //calculating s taking similarities into account
    int simil=0;
    ArrayList<String> perm=new ArrayList<String>();
    System.out.println("String pairs of '"+str+"' :");
    System.out.println("Similarities ie.(aaaaa)");
    for (Map.Entry<String, String> entry : similarities.entrySet()) {
        if(entry.getValue().split(",").length>=4)
        {
            String[] indxsim=entry.getValue().split(",");
            simil+=factorial(indxsim.length)/(factorial(indxsim.length-4)*factorial(4));/*C(n,r)=n!/(n−r)!r!*/

          //show similarities results:12345=>1234;1235;1245;1345;2345
            for(int i=0;i<indxsim.length-3;i++)
                for(int j=i+1;j<indxsim.length-2;j++)
                    for(int k=j+1;k<indxsim.length-1;k++)
                        for(int l=k+1;l<indxsim.length;l++)
                        {
                            if(!perm.contains(indxsim[i]+indxsim[j]+indxsim[k]+indxsim[l]))//indxsim[i] is String
                            {
                                perm.add(indxsim[i]+indxsim[j]+indxsim[k]+indxsim[l]);
                                System.out.println(indxsim[i]+indxsim[j]+indxsim[k]+indxsim[l]);
                            }
                        }
        }
    }
    //show results by parsing indexes and calculating sub strings
    System.out.println("NON-Similarities (cd*cd*)");

    for (Map.Entry<String, String> entry : indexes.entrySet()) {
        if(entry.getValue().split(",").length>2)
        {
            String[] indx=entry.getValue().split(";");
            for (int i=0;i<indx.length-1;i++)
                for(int j=i+1;j<indx.length;j++)
                {
                    System.out.println(indx[i]+","+indx[j]);
                }
        }
    }
    s+=simil;
    return s;
}

  public static int factorial(int n) {
        if (n == 0) {
            return 1;
        }
        int fact = 1; // this  will be the result
        for (int i = 1; i <= n; i++) {
            fact *= i;
        }
        return fact;
    }
</code>```

RESULTS:
 Taken directly from the output of the program. __ indexes are Zero-based!

```<code>    String pairs of 'abababa' :
Similarities ie.(aaaaa)
0246
NON-Similarities (cd*cd*)
0,1,2,3
0,1,4,5
2,3,4,5
1,2,3,4
1,2,5,6
3,4,5,6
TOTAL S =7

    String pairs of 'www.google.com' :
Similarities ie.(aaaaa)
NON-Similarities (cd*cd*)
3,5,10,12
4,5,7,12
TOTAL S =2

 String pairs of 'hellothisisarandomtext' :
Similarities ie.(aaaaa)
NON-Similarities (cd*cd*)
0,4,6,16
0,5,6,18
7,8,9,10
1,5,19,21
4,5,16,18
0,1,6,19
TOTAL S =6

 String pairs of 'ababaaa' :
Similarities ie.(aaaaa)
0245
0246
0256
0456
2456
NON-Similarities (cd*cd*)
0,1,2,3
1,2,3,4
TOTAL S =7
</code>```

UPDATED ACCORDING TO COMMENTS

Regards.

Title: Find string pairs

Body:
For the condition x[a] == x[c] and x[b] == x[d] to be true we need to consider two cases:

One is when x[a]== x[b] ie. the same character repeated 4 or more times, we call this case similarities, to handle this case we create a structure to store the character and its frequent, then when its frequent>=4 we have the pattern we are looking for. you can see below that it is handled separately in  the code. the number of possible combination could be calculated mathematically using:

C(n,r)=n!/((n−r)!r!) // r=4 here, and n is the frequency of the character.

We calculate this for all the similarities and add the some to the total resulted by the non-similarities.

The other case is to look for two different characters x[a]!= x[b].

X="arbsatbuavb"    Then n=3 (a after b 3 times); S=n(n-1)/2=3
X="arbsatbuavbwaxb" Then n=4; S=n(n-1)/2=6

Here we need to parse the array and look for every distinct occurrence of two characters putting them as keys to a dictionary structure <key,value> where the value here represents the number of occurrences of b after a (but no more Bs counted for that a), then for every key in the structure we use the following mathematical method to get the total number of sub-strings for non-similarities occurrences that fulfill the condition:

S =

Here is the algorithm implemented and its results:

public static void main(String[] args) {
    System.out.println("TOTAL S ="+ calculate("aaaaa"));
}

public static int calculate(String str) {
    int s = 0;
    Map<String, Integer> struct = new HashMap<String, Integer>();
    Map<String, String> indexes = new HashMap<String, String>();
    Map<String, String> similarities = new HashMap<String, String>();
    String[] x = str.split("(?!^)");// convert the string to array.

    //Handle similarities
    for (int i = 0; i < x.length; i++) {
        if (similarities.containsKey(x[i])) {
            similarities.put(x[i], similarities.get(x[i]) + "," + i); // "a": 1,3,7...
        } else {
            similarities.put(x[i], i + "");
        }
    }

    //Ignore similarities
    ArrayList<String> temp = new ArrayList<String>();
    for (int i = 0; i < x.length - 1; i++) {
        temp.clear();// this temp is important otherwise "cdxd" will count
                        // "cd" twice!!!
        for (int j = i + 1; j < x.length; j++) {
            if (!x[i].equals(x[j])) {// for example if "abcdamn" when reach the second a stop j and jump to the next i.
                if (struct.containsKey(x[i] + x[j])) { // NOTE x[i] + x[j] is a String
                    if (!temp.contains(x[j])) {

                        struct.put(x[i] + x[j], struct.get(x[i] + x[j]) + 1);
                        temp.add(x[j]);

                        //Update
                        indexes.put(x[i] + x[j],indexes.get(x[i] + x[j])+ ";"+i+","+j);

                    }
                }

                //UP I have excluded similarities ie. if we have the following "aaaaa" then we have c(5,4) =

                else {

                    struct.put(x[i] + x[j], 1); // NOTE x[i] + x[j] is a String
                    temp.add(x[j]);

                    //Update
                    indexes.put(x[i] + x[j], i+","+j);
                }
            } else {
              break;
            }
        }
    }
    // now compute the result when similarities ignored
    for (Map.Entry<String, Integer> entry : struct.entrySet()) {
        s += entry.getValue() * (entry.getValue() - 1) / 2;
    }

    //Update
    //calculating s taking similarities into account
    int simil=0;
    ArrayList<String> perm=new ArrayList<String>();
    System.out.println("String pairs of '"+str+"' :");
    System.out.println("Similarities ie.(aaaaa)");
    for (Map.Entry<String, String> entry : similarities.entrySet()) {
        if(entry.getValue().split(",").length>=4)
        {
            String[] indxsim=entry.getValue().split(",");
            simil+=factorial(indxsim.length)/(factorial(indxsim.length-4)*factorial(4));/*C(n,r)=n!/(n−r)!r!*/

          //show similarities results:12345=>1234;1235;1245;1345;2345
            for(int i=0;i<indxsim.length-3;i++)
                for(int j=i+1;j<indxsim.length-2;j++)
                    for(int k=j+1;k<indxsim.length-1;k++)
                        for(int l=k+1;l<indxsim.length;l++)
                        {
                            if(!perm.contains(indxsim[i]+indxsim[j]+indxsim[k]+indxsim[l]))//indxsim[i] is String
                            {
                                perm.add(indxsim[i]+indxsim[j]+indxsim[k]+indxsim[l]);
                                System.out.println(indxsim[i]+indxsim[j]+indxsim[k]+indxsim[l]);
                            }
                        }
        }
    }
    //show results by parsing indexes and calculating sub strings
    System.out.println("NON-Similarities (cd*cd*)");

    for (Map.Entry<String, String> entry : indexes.entrySet()) {
        if(entry.getValue().split(",").length>2)
        {
            String[] indx=entry.getValue().split(";");
            for (int i=0;i<indx.length-1;i++)
                for(int j=i+1;j<indx.length;j++)
                {
                    System.out.println(indx[i]+","+indx[j]);
                }
        }
    }
    s+=simil;
    return s;
}

  public static int factorial(int n) {
        if (n == 0) {
            return 1;
        }
        int fact = 1; // this  will be the result
        for (int i = 1; i <= n; i++) {
            fact *= i;
        }
        return fact;
    }

RESULTS:
 Taken directly from the output of the program. __ indexes are Zero-based!

    String pairs of 'abababa' :
Similarities ie.(aaaaa)
0246
NON-Similarities (cd*cd*)
0,1,2,3
0,1,4,5
2,3,4,5
1,2,3,4
1,2,5,6
3,4,5,6
TOTAL S =7

    String pairs of 'www.google.com' :
Similarities ie.(aaaaa)
NON-Similarities (cd*cd*)
3,5,10,12
4,5,7,12
TOTAL S =2

 String pairs of 'hellothisisarandomtext' :
Similarities ie.(aaaaa)
NON-Similarities (cd*cd*)
0,4,6,16
0,5,6,18
7,8,9,10
1,5,19,21
4,5,16,18
0,1,6,19
TOTAL S =6

 String pairs of 'ababaaa' :
Similarities ie.(aaaaa)
0245
0246
0256
0456
2456
NON-Similarities (cd*cd*)
0,1,2,3
1,2,3,4
TOTAL S =7

UPDATED ACCORDING TO COMMENTS

Regards.


问:
Connecting to a remote Microsoft SQL server from Node.js
I was wondering if anyone was aware of a way to connect to a Microsoft SQL database from Node.js. I'm aware of the MySQL drivers, but I have data that I need to pull from a MS SQL database and would rather pull directly from Node.js rather than hack a PHP script of some sort in place.</p>

答:
I suspect you'll have to wrap your SQL Server with a JSON outputting web-service.  On the positive side, it should be relatively easy to do.

Be nice if the JavaScript engine in node.js could do this: (from How to connect to SQL Server database from JavaScript in the browser?):

```<code>var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I suspect you'll have to wrap your SQL Server with a JSON outputting web-service.  On the positive side, it should be relatively easy to do.

Be nice if the JavaScript engine in node.js could do this: (from How to connect to SQL Server database from JavaScript in the browser?):

var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close;


问:
Solaris package upgrade
I'm having a lot of trouble wrapping my head around how Solaris 11 does packaging. I understand that there is a yum type packaging approach, but I would expect there to be a rpm -i and rpm -U approach that allows a package to be delivered and then installed or upgrade.

For now I have tracked down how to make a package, ie pkgmk and pkgtrans. Given this I can create a "foo_1.0.pkg" file that can be installed like this:

pkgadd -d foo_1.0.pkg

However I can not figure out how to upgrade this package with "foo_2.0.pkg":

```<code>root@hostname # pkgadd -d foo_2.0.pkg

The following packages are available:
  1  foo     foo
             (x86) private_build

Select package(s) you wish to process (or 'all' to process
all packages). (default: all) [?,??,q]: all

Processing package instance <foo> from </root/foo_2.0.pkg>

foo(x86) private_build

Current administration requires that a unique instance of the <foo>
package be created.  However, the maximum number of instances of the
package which may be supported at one time on the same system has
already been met.

No changes were made to the system.
</code>```

What am I doing wrong? It would appear that i should use pkg update, but this seems to imply that I need to release my pkg in a repo.

答:
$UPDATE

This variable does not exist under most installation environments. If it does exist (with the value yes), it means that a PKG with the same name, version and architecture is already installed on the system or that the installing PKG will overwrite an installed PKG. The original BASEDIR is then used.
So, this variable you can use in preinstall or postinstall script for any updation.

Title: Solaris package upgrade

Body:
I'm having a lot of trouble wrapping my head around how Solaris 11 does packaging. I understand that there is a yum type packaging approach, but I would expect there to be a rpm -i and rpm -U approach that allows a package to be delivered and then installed or upgrade.

For now I have tracked down how to make a package, ie pkgmk and pkgtrans. Given this I can create a "foo_1.0.pkg" file that can be installed like this:

pkgadd -d foo_1.0.pkg

However I can not figure out how to upgrade this package with "foo_2.0.pkg":

root@hostname # pkgadd -d foo_2.0.pkg

The following packages are available:
  1  foo     foo
             (x86) private_build

Select package(s) you wish to process (or 'all' to process
all packages). (default: all) [?,??,q]: all

Processing package instance <foo> from </root/foo_2.0.pkg>

foo(x86) private_build

Current administration requires that a unique instance of the <foo>
package be created.  However, the maximum number of instances of the
package which may be supported at one time on the same system has
already been met.

No changes were made to the system.

What am I doing wrong? It would appear that i should use pkg update, but this seems to imply that I need to release my pkg in a repo.


问:
Powershell Get-FileMetaData not recognized
I am trying to use the PowerShell command 'Get-FileMetaData' however PowerShell ISE outputs the following error:

```<code>Get-FileMetaData : The term 'Get-FileMetaData' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-FileMetaData E:\Test_Output
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Get-FileMetaData:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code>```

The path is correct, I have also tried various existing paths. I cant find anything about what version this command requires, but using $PSVersionTable.PSVersion output states 'Major 5' so I believe I am using PS v5.

Has anyone else had issue with this command? I have found various forums mentioning its function, but cant find much on troubleshooting it.

Thanks for any help!

答:
That is not a core PowerShell cmdlet so I would expect that to fail for most people. As far as I know that comes from the Script Gallery. You need to download that first.

So if you want that to be loaded then take that module will need to be imported either manually or automatically.

You can read more about module loading on MSDN

Body:
I am trying to use the PowerShell command 'Get-FileMetaData' however PowerShell ISE outputs the following error:

Get-FileMetaData : The term 'Get-FileMetaData' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-FileMetaData E:\Test_Output
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Get-FileMetaData:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

The path is correct, I have also tried various existing paths. I cant find anything about what version this command requires, but using $PSVersionTable.PSVersion output states 'Major 5' so I believe I am using PS v5.

Has anyone else had issue with this command? I have found various forums mentioning its function, but cant find much on troubleshooting it.

Thanks for any help!


问:
SQL Stored Procedures not finishing when called from Python
I'm trying to call a stored procedure in my MSSQL database from a python script, but it does not run completely when called via python. This procedure consolidates transaction data into hour/daily blocks in a single table which is later grabbed by the python script. If I run the procedure in SQL studio, it completes just fine.

When I run it via my script, it gets cut short about 2/3's of the way through. Currently I found a work around, by making the program sleep for 10 seconds before moving on to the next SQL statement, however this is not time efficient and unreliable as some procedures may not finish in that time. I'm looking for a more elegant way to implement this.

Current Code:

```<code>cursor.execute("execute mySP")
time.sleep(10)
cursor.commit()
</code>```

The most related article I can find to my issue is here:
make python wait for stored procedure to finish executing

I tried the solution using Tornado and I/O generators, but ran into the same issue as listed in the article, that was never resolved. I also tried the accepted solution to set a runningstatus field in the database by my stored procedures. At the beginnning of my SP Status is updated to 1 in RunningStatus, and when the SP finished Status is updated to 0 in RunningStatus. Then I implemented the following python code:

```<code>    conn=pyodbc_connect(conn_str)
    cursor=conn.cursor()
    sconn=pyodbc_connect(conn_str)
    scursor=sconn.cursor()

    cursor.execute("execute mySP")
    cursor.commit()
    while 1:
        q=scursor.execute("SELECT Status FROM RunningStatus").fetchone()
        if(q[0]==0):
            break
</code>```

When I implement this, the same problem happens as before with my storedprocedure finishing executing prior to it actually being complete. If I eliminate my cursor.commit(), as follows, I end up with the connection just hanging indefinitely until I kill the python process.

```<code>    conn=pyodbc_connect(conn_str)
    cursor=conn.cursor()
    sconn=pyodbc_connect(conn_str)
    scursor=sconn.cursor()

    cursor.execute("execute mySP")
    while 1:
        q=scursor.execute("SELECT Status FROM RunningStatus").fetchone()
        if(q[0]==0):
            break
</code>```

Any assistance in finding a more efficient and reliable way to implement this, as opposed to time.sleep(10) would be appreciated.

答:
As OP found out,  inconsistent or imcomplete processing of stored procedures from application layer like Python may be due to straying from best practices of TSQL scripting.

As @AaronBetrand highlights in this Stored Procedures Best Practices Checklist blog, consider the following among other items:

Explicitly and liberally use BEGIN ... END blocks;

Use SET NOCOUNT ON to avoid messages sent to client for every row affected action, possibly interrupting workflow;

Use semicolons for statement terminators.

Example

```<code>CREATE PROCEDURE dbo.myStoredProc
AS
BEGIN
   SET NOCOUNT ON;

   SELECT * FROM foo;

   SELECT * FROM bar;
END
GO
</code>```

Body:
I'm trying to call a stored procedure in my MSSQL database from a python script, but it does not run completely when called via python. This procedure consolidates transaction data into hour/daily blocks in a single table which is later grabbed by the python script. If I run the procedure in SQL studio, it completes just fine.

When I run it via my script, it gets cut short about 2/3's of the way through. Currently I found a work around, by making the program sleep for 10 seconds before moving on to the next SQL statement, however this is not time efficient and unreliable as some procedures may not finish in that time. I'm looking for a more elegant way to implement this.

Current Code:

cursor.execute("execute mySP")
time.sleep(10)
cursor.commit()

The most related article I can find to my issue is here:
make python wait for stored procedure to finish executing

I tried the solution using Tornado and I/O generators, but ran into the same issue as listed in the article, that was never resolved. I also tried the accepted solution to set a runningstatus field in the database by my stored procedures. At the beginnning of my SP Status is updated to 1 in RunningStatus, and when the SP finished Status is updated to 0 in RunningStatus. Then I implemented the following python code:

    conn=pyodbc_connect(conn_str)
    cursor=conn.cursor()
    sconn=pyodbc_connect(conn_str)
    scursor=sconn.cursor()

    cursor.execute("execute mySP")
    cursor.commit()
    while 1:
        q=scursor.execute("SELECT Status FROM RunningStatus").fetchone()
        if(q[0]==0):
            break

When I implement this, the same problem happens as before with my storedprocedure finishing executing prior to it actually being complete. If I eliminate my cursor.commit(), as follows, I end up with the connection just hanging indefinitely until I kill the python process.

    conn=pyodbc_connect(conn_str)
    cursor=conn.cursor()
    sconn=pyodbc_connect(conn_str)
    scursor=sconn.cursor()

    cursor.execute("execute mySP")
    while 1:
        q=scursor.execute("SELECT Status FROM RunningStatus").fetchone()
        if(q[0]==0):
            break

Any assistance in finding a more efficient and reliable way to implement this, as opposed to time.sleep(10) would be appreciated.

Body:
As OP found out,  inconsistent or imcomplete processing of stored procedures from application layer like Python may be due to straying from best practices of TSQL scripting.

As @AaronBetrand highlights in this Stored Procedures Best Practices Checklist blog, consider the following among other items:

Explicitly and liberally use BEGIN ... END blocks;

Use SET NOCOUNT ON to avoid messages sent to client for every row affected action, possibly interrupting workflow;

Use semicolons for statement terminators.

Example

CREATE PROCEDURE dbo.myStoredProc
AS
BEGIN
   SET NOCOUNT ON;

   SELECT * FROM foo;

   SELECT * FROM bar;
END
GO

ContentLicense: CC BY-SA 4.0


问:
DynamoDB: Query on GSI (Global secondary index) does not return data
I am using the Serverless framework to setup the below table:

```<code>provider:
  name: aws
  runtime: nodejs6.10
  stage: dev
  region: ap-southeast-1
  environment:
    DYNAMODB_TABLE: "Itinerary-${self:provider.stage}"
    DYNAMODB_COUNTRY_INDEX: country_index
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}/index/${self:provider.environment.DYNAMODB_COUNTRY_INDEX}"
resources:
  Resources:
    ItineraryTable:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          -
            AttributeName: ID
            AttributeType: S
          -
            AttributeName: Country
            AttributeType: S
        KeySchema:
          -
            AttributeName: ID
            KeyType: HASH
        GlobalSecondaryIndexes:
          -
            IndexName: ${self:provider.environment.DYNAMODB_COUNTRY_INDEX}
            KeySchema:
              -
                AttributeName: Country
                KeyType: HASH
            Projection:
              ProjectionType: ALL
            ProvisionedThroughput:
              ReadCapacityUnits: 1
              WriteCapacityUnits: 1
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DYNAMODB_TABLE}
</code>```

Now, I am able to get to do a "get" to retrieve items from the DB by ID. However, if I try to do a "query" on the GSI, it returns nothing. There is no failure, but I never get data back.

The below is what my query looks like:

```<code>const dynamoDb = new AWS.DynamoDB.DocumentClient();

var params = {
    TableName: process.env.DYNAMODB_TABLE, // maps back to the serverless config variable above
    IndexName: process.env.DYNAMODB_COUNTRY_INDEX, // maps back to the serverless config variable above
    KeyConditionExpression: "Country=:con",
    ExpressionAttributeValues: { ":con" : "Portugal" }
};

dynamoDb.query(params, (error, result) => {
    // handle potential errors
    if (error) {
        console.error(error);
        callback(null, {
            statusCode: error.statusCode || 501,
            headers: { 'Content-Type': 'text/plain' },
            body: 'Couldn\'t fetch the Itineraries'+error,
        });
        return;
    }
}

var json_result = JSON.stringify(result.Item);
</code>```

I should add here that I can't get data if I do a filterless "scan" as well. If I try to search for items by index (or otherwise) on the AWS Dynamo web portal, I get results though.

I cannot figure out what it is that's going wrong here. Any light that someone can shed would be much appreciated.

答:
Ok, so I figured out the problem. There was a key statement missing in the question that I posted (because I thought it wasn't relevant), but which turned out to the problem.

I was just stringifying the results from the query using:

```<code>var json_result = JSON.stringify(result.Item);
</code>```

The above works for a "get", but for a query, it needs to be result.Items:

```<code>var json_result = JSON.stringify(result.Items);
</code>```

Silly on my part. Thank you for the help!

P.S. I have added the statement to the original question to be clear

Body:
I am using the Serverless framework to setup the below table:

provider:
  name: aws
  runtime: nodejs6.10
  stage: dev
  region: ap-southeast-1
  environment:
    DYNAMODB_TABLE: "Itinerary-${self:provider.stage}"
    DYNAMODB_COUNTRY_INDEX: country_index
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}/index/${self:provider.environment.DYNAMODB_COUNTRY_INDEX}"
resources:
  Resources:
    ItineraryTable:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          -
            AttributeName: ID
            AttributeType: S
          -
            AttributeName: Country
            AttributeType: S
        KeySchema:
          -
            AttributeName: ID
            KeyType: HASH
        GlobalSecondaryIndexes:
          -
            IndexName: ${self:provider.environment.DYNAMODB_COUNTRY_INDEX}
            KeySchema:
              -
                AttributeName: Country
                KeyType: HASH
            Projection:
              ProjectionType: ALL
            ProvisionedThroughput:
              ReadCapacityUnits: 1
              WriteCapacityUnits: 1
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DYNAMODB_TABLE}

Now, I am able to get to do a "get" to retrieve items from the DB by ID. However, if I try to do a "query" on the GSI, it returns nothing. There is no failure, but I never get data back.

The below is what my query looks like:

const dynamoDb = new AWS.DynamoDB.DocumentClient();

var params = {
    TableName: process.env.DYNAMODB_TABLE, // maps back to the serverless config variable above
    IndexName: process.env.DYNAMODB_COUNTRY_INDEX, // maps back to the serverless config variable above
    KeyConditionExpression: "Country=:con",
    ExpressionAttributeValues: { ":con" : "Portugal" }
};

dynamoDb.query(params, (error, result) => {
    // handle potential errors
    if (error) {
        console.error(error);
        callback(null, {
            statusCode: error.statusCode || 501,
            headers: { 'Content-Type': 'text/plain' },
            body: 'Couldn\'t fetch the Itineraries'+error,
        });
        return;
    }
}

var json_result = JSON.stringify(result.Item);

I should add here that I can't get data if I do a filterless "scan" as well. If I try to search for items by index (or otherwise) on the AWS Dynamo web portal, I get results though.

I cannot figure out what it is that's going wrong here. Any light that someone can shed would be much appreciated.

Body:
Ok, so I figured out the problem. There was a key statement missing in the question that I posted (because I thought it wasn't relevant), but which turned out to the problem.

I was just stringifying the results from the query using:

var json_result = JSON.stringify(result.Item);

The above works for a "get", but for a query, it needs to be result.Items:

var json_result = JSON.stringify(result.Items);

Silly on my part. Thank you for the help!

P.S. I have added the statement to the original question to be clear


问:
PHP Sending Automated Mail That Doesn't Goto The SPAM Folder?
I've always been a little troubled when it comes to sending mail through PHP functions.
But it hasn't really been a problem until my latest project.

I'm looking for the absolute best way of sending mail through PHP and not having it end up in the SPAM folder :/

I'm aware that it won't probably work 100% of the time,
I'm just looking for the best option.

Thanks :)

答: Use a libary like PHPMailer and make sure to fill out all email header fields correctly.</p>


问:
Ideal merge for different number of columns and rows in dataframe
Some example data of stucture:

```<code>df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e'))
df2 = data.frame(x=c('f', 'g', 'h'),y = c(0,1,0))
df3 = data.frame(x=c('i', 'j','k','l'), y = c(1,7,5,2,6), z = c(75,3,25,2,1))
</code>```

I have 3 different dataframes.

df1 has 22201 object and 121 variables
df2 has 8403 object and 68 variables
df3 has 50476 object and 157 variables

I try to merge them using merge and I receive this error:

```<code>Error in fix.by(by.x, x) :
  'by' must specify one or more columns as numbers, names or logical
</code>```

using cbind and I received this error:

```<code>Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 22201, 8403, 50476
</code>```

and rbind and I receive this error:

```<code>Error in rbind(deparse.level, ...) :
  numbers of columns of arguments do not match
</code>```

How can I merge dataframes with different number of rows and columns? I have to refer that columns have the same names in dataframes so in the merge I expect the number of columns be the highest numbers of columns of the dataframe which contains the most.

答:
dplyr is an evolution from plyr, so I'd use it instead.
bind_rows will achieve what you want:

```<code>library(dplyr)
bind_rows(df1, df2, df3, ...)
</code>```

One example:

```<code>tbl1 <- data_frame(var1 = c('a', 'b', 'c'),
                   var2 = c('x', 'y', 'z'))

tbl2 <- data_frame(var1 = c('e', 'd', 'g', 'h'))

tbl3 <- data_frame(var6 = 1,
                   var10 = 14)

> bind_rows(tbl1, tbl2, tbl3)
# A tibble: 8 x 4
   var1  var2  var6 var10
  <chr> <chr> <dbl> <dbl>
1     a     x    NA    NA
2     b     y    NA    NA
3     c     z    NA    NA
4     e  <NA>    NA    NA
5     d  <NA>    NA    NA
6     g  <NA>    NA    NA
7     h  <NA>    NA    NA
8  <NA>  <NA>     1    14
</code>```

Body:
Some example data of stucture:

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e'))
df2 = data.frame(x=c('f', 'g', 'h'),y = c(0,1,0))
df3 = data.frame(x=c('i', 'j','k','l'), y = c(1,7,5,2,6), z = c(75,3,25,2,1))

I have 3 different dataframes.

df1 has 22201 object and 121 variables
df2 has 8403 object and 68 variables
df3 has 50476 object and 157 variables

I try to merge them using merge and I receive this error:

Error in fix.by(by.x, x) :
  'by' must specify one or more columns as numbers, names or logical

using cbind and I received this error:

Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 22201, 8403, 50476

and rbind and I receive this error:

Error in rbind(deparse.level, ...) :
  numbers of columns of arguments do not match

How can I merge dataframes with different number of rows and columns? I have to refer that columns have the same names in dataframes so in the merge I expect the number of columns be the highest numbers of columns of the dataframe which contains the most.

Body:
dplyr is an evolution from plyr, so I'd use it instead.
bind_rows will achieve what you want:

library(dplyr)
bind_rows(df1, df2, df3, ...)

One example:

tbl1 <- data_frame(var1 = c('a', 'b', 'c'),
                   var2 = c('x', 'y', 'z'))

tbl2 <- data_frame(var1 = c('e', 'd', 'g', 'h'))

tbl3 <- data_frame(var6 = 1,
                   var10 = 14)

> bind_rows(tbl1, tbl2, tbl3)
# A tibble: 8 x 4
   var1  var2  var6 var10
  <chr> <chr> <dbl> <dbl>
1     a     x    NA    NA
2     b     y    NA    NA
3     c     z    NA    NA
4     e  <NA>    NA    NA
5     d  <NA>    NA    NA
6     g  <NA>    NA    NA
7     h  <NA>    NA    NA
8  <NA>  <NA>     1    14


问:
Composer [InvalidArgumentException] Could not find package mtibben/html2text
I have tried to install html2text via composer to my laravel application. Here is a link to the html2text repository. https://github.com/mtibben/html2text

I have tried composer require mtibben/html2text giving this error:

[InvalidArgumentException]

  Could not find package mtibben/html2text at any version for your
  minimum-stability (stable). Check the package spel   ling or your
  minimum-stability

Also I have tried composer require https://github.com/mtibben/html2text.git giving this error:

[UnexpectedValueException]

  Could not parse version constraint //github.com/mtibben/html2text.git:
  Invalid version string "//github.com/mtibben   /html2text.git"

How do I install html2text?

答:
Do you already have a composer.json file in your directory? If not, this could be the error, because in this file you will configure which version of the package you want to install in to your project.

The second exception gives a hint to that missing version!

If you have a composer.json file please add its content to your question, so that we can take a look at it.

Here you can find further informations:

https://getcomposer.org/doc/01-basic-usage.md#composer-json-project-setup


问:
Class wise precision and recall for multi class classification in Tensorflow?
Is there a way to get per class precision or recall when doing multiclass classification using tensor flow.

For example, If I have y_true and y_pred from each batch, is there a functional way to get precision or recall per class if I have more than 2 classes.

答: I believe TF does not provide such functionality yet. As per the docs (https://www.tensorflow.org/api_docs/python/tf/metrics/precision), it says both the labels and predictions will be cast to bool, and so it relates only to binary classification. Perhaps it's possible to one-hot encode the examples and it would work? But not sure about this.</p>


问:
PHPUnit RabbitMQ: write test for create connection function
I'm facing the following problem. I've wrote a function that create a connection object (AMQPConnection) given the required parameters. Now I want to write the corresponding unit test. I just don't know how to do it without having the RabbitMQ broker running. Here is the function in question:

public function getConnection($hostKey, array $params)
{
    $connection = null;
    try {

        $connection = new AMQPConnection(
            $params['host'],
            $params['port'],
            $params['username'],
            $params['password'],
            $params['vhost']
        );

        // set this server as default for next connection connectionAttempt
        $this->setDefaultHostConfig($hostKey, $params);

        return $connection;
    } catch (\Exception $ex) {

        if ($this->isAttemptExceeded()) {
            return $connection;
        } else {
            // increment connection connectionAttempt
            $this->setConnectionAttempt($this->getConnectionAttempt() + 1);

            return $this->getConnection($hostKey, $params);
        }
    }
}
```

答:
You should add an ability to change the class being instantiated.

Add an ability to change the connector class via constructor or setter, with a default AMQPConnector class by default. Use it to create a connector object. Example

Create a mocked connector class for unit tests. Example

Use it setting the mock class via constructor or setter in tests.  Example

You could also do assertions on what arguments are passed to the connector constructor.

Another way would be to use amqp interop so you are not coupled to any implementation. Much easier to tests as you deal with pure interfaces only.


问:
Checkbox value set with jquery not showing in POST
I've been looking for over an hour on the net, nothing showed up. I got some simple checkboxes, with a litle trick to style them, the classic hidden attribute and the label with the style. Nothing fancy.
All I want is to send those checkboxes values/checked status through POST for proccesing.
The problem is that whenever I change those values with jQuery, onClick, the inspector showes the changes, but in POST the input is not there anymore.
I've tried setting the "checked" attribute with $.prop(). It worked for the inspector, but didn't worked on POST.
Then I've changed to using values, setting all checkboxes as "checked" and changing the values with jQuery from 1 to 0 and back.
The inspector showes the values changing, but the POST shows nothing.

Here the HTML form :

```<code><form action="./ajax/process.php" enctype="multipart/form-data" method="post" id="admEmailParameteres1">
                    <input type="hidden" name="procesare" value="adm-process-parameters">

                    <input type="checkbox" id="sendConfEmailToClient" name="sendConfEmailToClient" value="<?= ($options['email_conf'] == 1 ? 1:0) ?>" class="hidden" checked>
                    <label for="sendConfEmailToClient" class="as-link tip label" onClick="toggleCheckSimple(this)" title="Trimite email de confirmare catre client la plasarea comenzii."><i class="fa fa-check label-check <?= ($options['email_conf'] == 1 ? 'active':'') ?>"></i> Client - email de confirmare la plasarea comenzii</label><br>

                    <input type="checkbox" id="sendAdvConfEmailToClient" name="sendAdvConfEmailToClient" value="<?= ($options['email_conf_sumar'] == 1 ? 1:0) ?>" class="hidden" checked>
                    <label for="sendAdvConfEmailToClient" class="as-link tip label" onClick="toggleCheckSimple(this)" title="Adauga si sumarul comenzii la email-ul de confirmare, trimis catre client la plasarea comenzii."><i class="fa fa-check label-check <?= ($options['email_conf_sumar'] == 1 ? 'active':'') ?>"></i> Client - adauga sumarul la email, la plasarea comenzii</label><br>

                    <input type="submit" class="btn btn-sm btn-success mb-5 " value="Salveaza modificarile" data-form="admEmailParameteres">
                </form>
</code>```

Here's the JS code:

```<code>function toggleCheckSimple(el){
$(el).find('.label-check').toggleClass('active');
var trg = $(el).attr('for');
if($('#'+trg).val() == 1){
    $('input[name="'+trg+'"]').val(0);
}else{
    $('input[name="'+trg+'"]').val(1);
}
</code>```

}

And in the PHP side, if I call:

```<code>echo '```';
        print_r($_POST);
        echo '```';
</code>```

The checkboxes are not there if they were changed with jQuery. If you don't touch them, they are there. Extremely strange adn upseting for me, as I am not a beginer. Can't figure this out.

答:
A checkbox always needs a value in the html. But this value will only send to php if you check the checkbox. So remove <?= ($options['email_conf'] == 1 ? 1:0) ?> from your code, and set the checked attribute only when $options['email_conf'] == 1.

This will be your code:

```<code><input type="checkbox" id="sendConfEmailToClient" name="sendConfEmailToClient" value="1" class="hidden" <?= echo ($options['email_conf'] == 1) ? 'checked' : '';  ?>>
</code>```

Body:
I've been looking for over an hour on the net, nothing showed up. I got some simple checkboxes, with a litle trick to style them, the classic hidden attribute and the label with the style. Nothing fancy.
All I want is to send those checkboxes values/checked status through POST for proccesing.
The problem is that whenever I change those values with jQuery, onClick, the inspector showes the changes, but in POST the input is not there anymore.
I've tried setting the "checked" attribute with $.prop(). It worked for the inspector, but didn't worked on POST.
Then I've changed to using values, setting all checkboxes as "checked" and changing the values with jQuery from 1 to 0 and back.
The inspector showes the values changing, but the POST shows nothing.

Here the HTML form :

<form action="./ajax/process.php" enctype="multipart/form-data" method="post" id="admEmailParameteres1">
                    <input type="hidden" name="procesare" value="adm-process-parameters">

                    <input type="checkbox" id="sendConfEmailToClient" name="sendConfEmailToClient" value="<?= ($options['email_conf'] == 1 ? 1:0) ?>" class="hidden" checked>
                    <i class="fa fa-check label-check <?= ($options['email_conf'] == 1 ? 'active':'') ?>"> Client - email de confirmare la plasarea comenzii

                    <input type="checkbox" id="sendAdvConfEmailToClient" name="sendAdvConfEmailToClient" value="<?= ($options['email_conf_sumar'] == 1 ? 1:0) ?>" class="hidden" checked>
                    <i class="fa fa-check label-check <?= ($options['email_conf_sumar'] == 1 ? 'active':'') ?>"> Client - adauga sumarul la email, la plasarea comenzii

                    <input type="submit" class="btn btn-sm btn-success mb-5 " value="Salveaza modificarile" data-form="admEmailParameteres">
                </form>

Here's the JS code:

function toggleCheckSimple(el){
$(el).find('.label-check').toggleClass('active');
var trg = $(el).attr('for');
if($('#'+trg).val() == 1){
    $('input[name="'+trg+'"]').val(0);
}else{
    $('input[name="'+trg+'"]').val(1);
}

}

And in the PHP side, if I call:

echo '
';
        print_r($_POST);
        echo '
';

The checkboxes are not there if they were changed with jQuery. If you don't touch them, they are there. Extremely strange adn upseting for me, as I am not a beginer. Can't figure this out.

Body:
A checkbox always needs a value in the html. But this value will only send to php if you check the checkbox. So remove <?= ($options['email_conf'] == 1 ? 1:0) ?> from your code, and set the checked attribute only when $options['email_conf'] == 1.

This will be your code:

<input type="checkbox" id="sendConfEmailToClient" name="sendConfEmailToClient" value="1" class="hidden" <?= echo ($options['email_conf'] == 1) ? 'checked' : '';  ?>>


问:
Can I store difference file types into SQL Server database?
I have created a vb.net project and a SQL Server database, I want to store my other created projects to the database with some of there description. I don't know can I do that or I can store my projects files into the database in the first place. I wanted to compress my projects files to a zip file and then store the zip file to the database but I don't know if I can store these files to the database which includes a lot of file types like (jar, java, sln, vb, c#, txt ...etc)?

Thanks for your help.

答:
Yes, you can store files in a SQL Server database table. I highly recommend you to compress them into a zip file.

First step is to create a table:

```<code>CREATE TABLE Files
(
     Id INT IDENTITY PRIMARY KEY,
     FileData VARBINARY(MAX) FILESTREAM  NULL,
     Name NVARCHAR(300)
)
</code>```

and then open your zip file as stream and Insert it into your table.

```<code>OpenFileDialog openFileDlg = new OpenFileDialog();
openFileDlg.InitialDirectory = Directory.GetCurrentDirectory();

if (openFileDlg.ShowDialog() == DialogResult.OK)
{
    FileInfo fi = new FileInfo(openFileDlg.FileName);
    FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
    BinaryReader rdr = new BinaryReader(fs);
    byte[] fileData = rdr.ReadBytes((int)fs.Length);
    rdr.Close();
    fs.Close();

    string cs = @"Data Source=<your server>;Initial Catalog=MyFsDb;Integrated Security=TRUE";

    using (SqlConnection con = new SqlConnection(cs))
    {
        con.Open();
        string sql = "INSERT INTO Files VALUES (@Data, @Name)";

        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.Parameters.Add("@Data", SqlDbType.Image, fileData.Length).Value = fileData;
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = fi.Name;

        cmd.ExecuteNonQuery();
        con.Close();
    }

    MessageBox.Show(fi.FullName, "File Inserted!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
</code>```

Source : MSDN

Body:
Yes, you can store files in a SQL Server database table. I highly recommend you to compress them into a zip file.

First step is to create a table:

CREATE TABLE Files
(
     Id INT IDENTITY PRIMARY KEY,
     FileData VARBINARY(MAX) FILESTREAM  NULL,
     Name NVARCHAR(300)
)

and then open your zip file as stream and Insert it into your table.

OpenFileDialog openFileDlg = new OpenFileDialog();
openFileDlg.InitialDirectory = Directory.GetCurrentDirectory();

if (openFileDlg.ShowDialog() == DialogResult.OK)
{
    FileInfo fi = new FileInfo(openFileDlg.FileName);
    FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
    BinaryReader rdr = new BinaryReader(fs);
    byte[] fileData = rdr.ReadBytes((int)fs.Length);
    rdr.Close();
    fs.Close();

    string cs = @"Data Source=<your server>;Initial Catalog=MyFsDb;Integrated Security=TRUE";

    using (SqlConnection con = new SqlConnection(cs))
    {
        con.Open();
        string sql = "INSERT INTO Files VALUES (@Data, @Name)";

        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.Parameters.Add("@Data", SqlDbType.Image, fileData.Length).Value = fileData;
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = fi.Name;

        cmd.ExecuteNonQuery();
        con.Close();
    }

    MessageBox.Show(fi.FullName, "File Inserted!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Source : MSDN


问:
JQuery Ajax , why in success i have error why?
Why in success I have error?</p>

```<code>$('#ck').click(function() {
  var StudentData = [{
    'Name': 'Ali',
    'Age': 27
  }, {
    'Name': 'Sam',
    'Age': 32
  }];

  $.ajax({
    url: "/Home/StudentInfo",
    data: JSON.stringify(StudentData),
    ...
    success: function(response) {
      alert(response[0].Name);
    },
    error: function() {
      alert("error");
    },
  });
});
</code>```

答:
Based on an excessively lengthy comment thread above, you claim to have this server-side code:

```<code>public JsonResult StudentInfo(List<object> StudentData)
{
    return Json(StudentData);
}
</code>```

So, you're returning a List<object> to your client-side code.  Then in your client-side code you try to access a property on an element in that list:

```<code>success: function (response) {
    alert(response[0].Name);
}
</code>```

Well, to put is simply, object doesn't contain a property called Name.  It never has, and it probably never will.  So you can't access a property that doesn't exist.  Hence, it's undefined in JavaScript.

It looks like you meant to define a class for your objects.  Something as simple as this:

```<code>public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}
</code>```

Then you can use that class in your action method:

```<code>public JsonResult StudentInfo(List<Student> StudentData)
{
    return Json(StudentData);
}
</code>```

Since Student does have a property called Name, you can use that property in your client-side code.

Body:
Why in success I have error?

$('#ck').click(function() {
  var StudentData = [{
    'Name': 'Ali',
    'Age': 27
  }, {
    'Name': 'Sam',
    'Age': 32
  }];

  $.ajax({
    url: "/Home/StudentInfo",
    data: JSON.stringify(StudentData),
    ...
    success: function(response) {
      alert(response[0].Name);
    },
    error: function() {
      alert("error");
    },
  });
});

Body:
Based on an excessively lengthy comment thread above, you claim to have this server-side code:

public JsonResult StudentInfo(List<object> StudentData)
{
    return Json(StudentData);
}

So, you're returning a List<object> to your client-side code.  Then in your client-side code you try to access a property on an element in that list:

success: function (response) {
    alert(response[0].Name);
}

Well, to put is simply, object doesn't contain a property called Name.  It never has, and it probably never will.  So you can't access a property that doesn't exist.  Hence, it's undefined in JavaScript.

It looks like you meant to define a class for your objects.  Something as simple as this:

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Then you can use that class in your action method:

public JsonResult StudentInfo(List<Student> StudentData)
{
    return Json(StudentData);
}

Since Student does have a property called Name, you can use that property in your client-side code.


问:
Python how to store "\" inside an arrey to use in a subprocess.call bash command
i have a python program that creates a bash command and then uses it in subprocess.call(command)

i wand to send it a file location with spaces.

```<code>import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] +=  "\\ is"
subprocess.call(command)
</code>```

but when it is used by subprocess it becomes a new directory with the name
 this\ is

this is the full code

```<code>import pyxhook
import subprocess

command = [""]
isActive = False
element = 0
isSpace = False

def OnKeyPress(event):
    global command
    global isActive
    global element
    global isSpace
    if event.Ascii == 96:
        if isActive == False:
            isActive = True
        elif isActive == True:
            subprocess.call(command)
            command = [""]
            element = 0
            isActive = False
    elif isActive == True:
        if event.Ascii == 32:
            if isSpace == False:
                command.append("")
                element += 1
            else:
                command[element] += " "
                isSpace = False
        elif event.Key == "BackSpace":
            command[element] = command[element][:-1]
        elif event.Key == "slash":
            command[element] += "/"
        elif event.Key == "Shift_L" :
            command = command
        elif event.Key =="Shift_R":
            command = command
        elif event.Key == "backslash":
            isSpace = True
            command[element] +=  "\\"
        else:
            command[element] += (event.Key)

#instantiate HookManager class
new_hook=pyxhook.HookManager()
#listen to all keystrokes
new_hook.KeyDown=OnKeyPress
#hook the keyboard
new_hook.HookKeyboard()
#start the session
new_hook.start()
</code>```

答:
Keep it simple:

```<code>path = "/home/matt/Desktop/this"
path += " is"
os.makedirs(path, exist_ok=True)
</code>```

If your Python is older than 3.2, remove exist_ok=True.

Body:
i have a python program that creates a bash command and then uses it in subprocess.call(command)

i wand to send it a file location with spaces.

import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] +=  "\\ is"
subprocess.call(command)

but when it is used by subprocess it becomes a new directory with the name
 this\ is

this is the full code

import pyxhook
import subprocess

command = [""]
isActive = False
element = 0
isSpace = False

def OnKeyPress(event):
    global command
    global isActive
    global element
    global isSpace
    if event.Ascii == 96:
        if isActive == False:
            isActive = True
        elif isActive == True:
            subprocess.call(command)
            command = [""]
            element = 0
            isActive = False
    elif isActive == True:
        if event.Ascii == 32:
            if isSpace == False:
                command.append("")
                element += 1
            else:
                command[element] += " "
                isSpace = False
        elif event.Key == "BackSpace":
            command[element] = command[element][:-1]
        elif event.Key == "slash":
            command[element] += "/"
        elif event.Key == "Shift_L" :
            command = command
        elif event.Key =="Shift_R":
            command = command
        elif event.Key == "backslash":
            isSpace = True
            command[element] +=  "\\"
        else:
            command[element] += (event.Key)

#instantiate HookManager class
new_hook=pyxhook.HookManager()
#listen to all keystrokes
new_hook.KeyDown=OnKeyPress
#hook the keyboard
new_hook.HookKeyboard()
#start the session
new_hook.start()

Body:
Keep it simple:

path = "/home/matt/Desktop/this"
path += " is"
os.makedirs(path, exist_ok=True)

If your Python is older than 3.2, remove exist_ok=True.


问:
Wordpress Visually Group / Separate Outputted Posts From Categories using query_posts
In my wordpress site, I'm outputting posts sorted by category ascending and this is working fine.

The code for accomplishing this so far is:

```<code><?php query_posts('cat=1,2,3&showposts=5&orderby=category&order=ASC'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
    <?php the_excerpt() ?>
  </li>
<?php endwhile; endif; ?>
</code>```

Right now all the posts are displayed as one group, sorted by category ascended which is great ... but I'm trying to visually separate the categories.

So, my code right now would work smth like:

```<code>Cat1 Post1 Cat1 Post2 Cat2 Post1 Cat2 Post2 Cat2 Post3 Cat3 Post1 ... and so on
</code>```

I want to separate them like this:

```<code>CATEGORY ONE:
Cat1 Post1 Cat1 Post2

CATEGORY TWO:
Cat2 Post1 Cat2 Post2 Cat2 Post3

CATEGORY THREE:
Cat3 Post1 ... and so on
</code>```

Is this a paramater I can add to the query_posts loop or something?  Seems like something easy to accomplish but I have no idea how to!  Any helps appreciated.

答: I ended up using three separate query_posts to accomplish this.</p>

Body:
In my wordpress site, I'm outputting posts sorted by category ascending and this is working fine.

The code for accomplishing this so far is:

<?php query_posts('cat=1,2,3&showposts=5&orderby=category&order=ASC'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<a href="<?php the_permalink() ?>"><?php the_title(); ?>
    <?php the_excerpt() ?>

<?php endwhile; endif; ?>

Right now all the posts are displayed as one group, sorted by category ascended which is great ... but I'm trying to visually separate the categories.

So, my code right now would work smth like:

Cat1 Post1 Cat1 Post2 Cat2 Post1 Cat2 Post2 Cat2 Post3 Cat3 Post1 ... and so on

I want to separate them like this:

CATEGORY ONE:
Cat1 Post1 Cat1 Post2

CATEGORY TWO:
Cat2 Post1 Cat2 Post2 Cat2 Post3

CATEGORY THREE:
Cat3 Post1 ... and so on

Is this a paramater I can add to the query_posts loop or something?  Seems like something easy to accomplish but I have no idea how to!  Any helps appreciated.


问:
redirect_uri_mismatch with Google Sign-In for server-side apps
I have a problem with my Google Sign in.
I follow the steps on Google Sign-In for server-side apps
After all this step, i have this html file that run on a server :

```<code><!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Article">
    <head>
        <link rel="stylesheet" href="theme.css">
        <!-- BEGIN Pre-requisites -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
        <!-- END Pre-requisites -->
        <script>
            function start() {
                gapi.load('auth2', function() {
                    auth2 = gapi.auth2.init({
                        client_id: 'CLIENT_ID'
                    });
                });
            }
        </script>
    </head>
    <body>
        <button id="googleBtn">Connect</button>
        <script>
            $('#googleBtn').click(function() {
                auth2.grantOfflineAccess().then(googleCallback);
            });
        </script>
        <script>
            function googleCallback(authResult) {
                if (authResult['code']) {
                    console.log(authResult);
                } else {
                    console.log(authResult);
                }
            }
        </script>
    </body>
</html>
</code>```

This first part work perfectly (I think), when I click on button, a window popup, I select an account and I get a code. So now, I want to get email and profile, so I make this request in nodejs to exchange the code with an access token.

```<code>var form = {
    code: 'XXXXXXXXXXXX',
    client_id: 'CLIENT_ID,
    client_secret: 'CLIENT',
    grant_type:'authorization_code'
};

var formData = querystring.stringify(form);
var contentLength = formData.length;

request({
    headers: {
      'Content-Length': contentLength,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    uri: 'https://www.googleapis.com/oauth2/v4/token',
    body: formData,
    method: 'POST'
  }, function (err, rep, body) {
    console.log(err);
    console.log(rep.statusCode);
    console.log(body);
  });
</code>```

But in response, I have this

```<code>{
 "error": "redirect_uri_mismatch",
 "error_description": "Bad Request"
}
</code>```

And I don't understand why, because I don't use any redirect_uri in primary request in html file. I have try some cases like add redirect_uri on Console API and in request, but I have the same result...

Can you help me ?

答:
You need to define your callback url to Google via console.developer.google.com

So you need to follow this steps for define the callback URL:

Go to console.developer.google.com

Select your project.

Click 'Credentials' on the left menu.

Click your client on the 'OAuth 2.0 client IDs' list.

Add your callback url to 'Authorized redirect URIs' list.

And done.

Body:
I have a problem with my Google Sign in.
I follow the steps on Google Sign-In for server-side apps
After all this step, i have this html file that run on a server :

<!DOCTYPE html>

        <link rel="stylesheet" href="theme.css">

        <button id="googleBtn">Connect</button>

This first part work perfectly (I think), when I click on button, a window popup, I select an account and I get a code. So now, I want to get email and profile, so I make this request in nodejs to exchange the code with an access token.

var form = {
    code: 'XXXXXXXXXXXX',
    client_id: 'CLIENT_ID,
    client_secret: 'CLIENT',
    grant_type:'authorization_code'
};

var formData = querystring.stringify(form);
var contentLength = formData.length;

request({
    headers: {
      'Content-Length': contentLength,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    uri: 'https://www.googleapis.com/oauth2/v4/token',
    body: formData,
    method: 'POST'
  }, function (err, rep, body) {
    console.log(err);
    console.log(rep.statusCode);
    console.log(body);
  });

But in response, I have this

{
 "error": "redirect_uri_mismatch",
 "error_description": "Bad Request"
}

And I don't understand why, because I don't use any redirect_uri in primary request in html file. I have try some cases like add redirect_uri on Console API and in request, but I have the same result...

Can you help me ?


问:
Formatting Dates & regional setting Excel VBA
This is super frustrating and it doesn't make sense to me.

This is in Excel 2010.

I've recorded a macro to format some data, containing date (DD/MM/YYYY). I import it, Excel sees it as text. So I use the "text to date" macro I have recorded, store into a VBA sub.

Here's the recorded macro:

```<code>Sub DateFormatting()
    Sheets("Donnees").Select
    Columns("H:H").Select
    Selection.TextToColumns Destination:=Range("H1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, OtherChar _
        :="/", FieldInfo:=Array(1, 4), TrailingMinusNumbers:=True
End Sub
</code>```

When I import my data, at first I have this. You can see it's seen as TEXT by Excel because it is left-aligned (Column H and I confirm it actually is):

Then I run the macro, and get this (column H):

You can see Excel sees it as Date, as it is right-aligned. If I convert it to "number" I see the underlying serial, as expected. So one would think it's fine. But it's really not:

If I run the macro AGAIN (and I would, because more data will be added to it later, so I need to make sure the newly imported data at the bottom of these will be correctly formatted as well), I get this:

So basically it changed the format from DD/MM/YYYY (which it is SUPPOSED to be) to MM/DD/YYYY (which is wrong). If I run that macro again on that data set, it switches back to DD/MM/YYYY.

But the WORST thing is that if I MANUALLY do the exact same thing (e.g. instead of running the macro, I manually go to "Data", "Text to columns" and select the EXACT same options), then it doesn't change. If the date is formatted as DD/MM/YYYY, it stays this way, and if it is formatted as MM/DD/YYYY (because of this stupid quirk), then it stays that way as well. I repeat it enough (and even re-recorded the macro a couple times) to be SURE I do the exact same things.

I know this is because of regional settings, but the file won't always be use on my computer, and I have no way of ensuring that the end user will have any specific regional settings. I need this file to be region-settings independant, basically.

MY QUESTION IS: How can I make sure that those dates are:

Formatted & recognized as date by Excel

Independant of the local regional settings of the users?

I know I could either to an intermediary import step (and format the data there, instead of in the main file), or then tweak the code so that only newly imported data have the macro applied.... But then I feel it's not reliable because how do I know Excel won't mess up the format?

Oh, because the Macro is a bit cryptic looking at the VBA:

I go to Data, Text to Column, choose "Delimited" (doesn't matter because I don't actually split it into columns), then "Delimiters" as default (doesn't matter again I'm not actually splitting the text into columns), then "Date" and in the dropdown "DYM" for DD/MM/YYYY

EDIT: Please see Ron Rosenfield's answer for full details. For completedness, here's the code I'll be running to import the data & format it at import, as opposed to importing it and then formatting it:

```<code>Sub importData()
Dim myFile As String
myFile = Sheet5.Cells(2, 5).Value 'My metadata sheet, containing name of file to import

Sheet1.Select  'Setting target sheet as active worksheet
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;C:\ChadTest\" & myFile, _
    Destination:=Sheet1.Cells(Sheet5.Cells(2, 1).Value, 1))
        .Name = "ExternalData_1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlOverwriteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 1252
If Sheet1.Cells(1, 1).Value = "" Then
  .TextFileStartRow = 1
Else
  .TextFileStartRow = 2
End If
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 4, 1, 1, 1, 4, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Sheet1.Select
    Application.WindowState = xlMinimized
    Application.WindowState = xlNormal
End Sub
</code>```

答:
Actually we had this problem quite a lot at work.
we figured out that the best way to work around this problem is to make sure the dates in the base data are in format "YYYY/MM/DD", this way it's recognized as the same date in either American or normal date format and it will actually correctly follow your regional settings to put a correct date in Excel...</p>

Body:
This is super frustrating and it doesn't make sense to me.

This is in Excel 2010.

I've recorded a macro to format some data, containing date (DD/MM/YYYY). I import it, Excel sees it as text. So I use the "text to date" macro I have recorded, store into a VBA sub.

Here's the recorded macro:

Sub DateFormatting()
    Sheets("Donnees").Select
    Columns("H:H").Select
    Selection.TextToColumns Destination:=Range("H1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, OtherChar _
        :="/", FieldInfo:=Array(1, 4), TrailingMinusNumbers:=True
End Sub

When I import my data, at first I have this. You can see it's seen as TEXT by Excel because it is left-aligned (Column H and I confirm it actually is):

Then I run the macro, and get this (column H):

You can see Excel sees it as Date, as it is right-aligned. If I convert it to "number" I see the underlying serial, as expected. So one would think it's fine. But it's really not:

If I run the macro AGAIN (and I would, because more data will be added to it later, so I need to make sure the newly imported data at the bottom of these will be correctly formatted as well), I get this:

So basically it changed the format from DD/MM/YYYY (which it is SUPPOSED to be) to MM/DD/YYYY (which is wrong). If I run that macro again on that data set, it switches back to DD/MM/YYYY.

But the WORST thing is that if I MANUALLY do the exact same thing (e.g. instead of running the macro, I manually go to "Data", "Text to columns" and select the EXACT same options), then it doesn't change. If the date is formatted as DD/MM/YYYY, it stays this way, and if it is formatted as MM/DD/YYYY (because of this stupid quirk), then it stays that way as well. I repeat it enough (and even re-recorded the macro a couple times) to be SURE I do the exact same things.

I know this is because of regional settings, but the file won't always be use on my computer, and I have no way of ensuring that the end user will have any specific regional settings. I need this file to be region-settings independant, basically.

MY QUESTION IS: How can I make sure that those dates are:

Formatted & recognized as date by Excel

Independant of the local regional settings of the users?

I know I could either to an intermediary import step (and format the data there, instead of in the main file), or then tweak the code so that only newly imported data have the macro applied.... But then I feel it's not reliable because how do I know Excel won't mess up the format?

Oh, because the Macro is a bit cryptic looking at the VBA:

I go to Data, Text to Column, choose "Delimited" (doesn't matter because I don't actually split it into columns), then "Delimiters" as default (doesn't matter again I'm not actually splitting the text into columns), then "Date" and in the dropdown "DYM" for DD/MM/YYYY

EDIT: Please see Ron Rosenfield's answer for full details. For completedness, here's the code I'll be running to import the data & format it at import, as opposed to importing it and then formatting it:

Sub importData()
Dim myFile As String
myFile = Sheet5.Cells(2, 5).Value 'My metadata sheet, containing name of file to import

Sheet1.Select  'Setting target sheet as active worksheet
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;C:\ChadTest\" & myFile, _
    Destination:=Sheet1.Cells(Sheet5.Cells(2, 1).Value, 1))
        .Name = "ExternalData_1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlOverwriteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 1252
If Sheet1.Cells(1, 1).Value = "" Then
  .TextFileStartRow = 1
Else
  .TextFileStartRow = 2
End If
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 4, 1, 1, 1, 4, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Sheet1.Select
    Application.WindowState = xlMinimized
    Application.WindowState = xlNormal
End Sub


问:
Gap at bottom of jumbo-tron cant remove
I am using the jumbo tron to show an hero image of  psd however there appears to be a gap at the bottom I have tried using margin-bottom:0px but that did not work.

.jumbotron
{

    background-image: url(image/background.png);
    background-repeat: no-repeat;
    -webkit-background-size:cover;
    -moz-background-size:cover;
    background-size: cover;
    padding: none !important;
    padding-bottom:none !important;
  margin-bottom: 0;

} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar navbar-inverse navbar-fixed-top">
    <div class="Brand">Dipped</div>
            <div class="navbar-inner">
                <ul class="nav navbar-nav navbar-right">
                    <li>Home</li>
                    <li>Services</li>
                    <li>Works</li>
                    <li>About</li>
                    <li>Contact</li>
                </ul>
            </div>
        </div>

 <div class="jumbotron">
     <div class="jumpbotron-inner text-center">
  <h1>We build well desgined websites</h1>
  <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
  <p>

      Get Started

    Learn More

  </p>
           <img src="image/browser.png">
     </div>
</div>

    </body>
</html></code>```

But as you see there is a big margin between the browser image and the bottom of the jumobo tron.

I am suing bootstrap 3.3.7 for reference

答:
Try these messing with these changes

```<code><span>
<a class="btn btn-primary btn-large">
  Get Started
</a>

  <a class="btn btn-primary btn-large">
Learn More
</a>
</span>

.jumbotron
</code>```

{

```<code>background-image: url(image/background.png);
background-repeat: no-repeat;
-webkit-background-size:cover;
-moz-background-size:cover;
background-size: cover;
padding-bottom: 0px;
margin-bottom: 0px;
</code>```

}

Title: Gap at bottom of jumbo-tron cant remove

Body:
I am using the jumbo tron to show an hero image of  psd however there appears to be a gap at the bottom I have tried using margin-bottom:0px but that did not work.

.jumbotron
{

    background-image: url(image/background.png);
    background-repeat: no-repeat;
    -webkit-background-size:cover;
    -moz-background-size:cover;
    background-size: cover;
    padding: none !important;
    padding-bottom:none !important;
  margin-bottom: 0;

}

Dipped

Home

Services

Works

About

Contact

We build well desgined websites

Class aptent taciti sociosqu ad litora torquent per conubia nostra.

      Get Started

    Learn More

But as you see there is a big margin between the browser image and the bottom of the jumobo tron.

I am suing bootstrap 3.3.7 for reference

Body:
Try these messing with these changes

<span>
<a class="btn btn-primary btn-large">
  Get Started
</a>

  <a class="btn btn-primary btn-large">
Learn More
</a>
</span>

.jumbotron

{

background-image: url(image/background.png);
background-repeat: no-repeat;
-webkit-background-size:cover;
-moz-background-size:cover;
background-size: cover;
padding-bottom: 0px;
margin-bottom: 0px;

}


问:
Map multiple rows to create new columns in a dataframe
I have two dataframes:

```<code>df1 = pd.DataFrame({'ID':pd.Series(['id1','id2','id3']),
                    'DoB':pd.Series(['15/2','12/3','25/12']),
                    'Surgery Date':pd.Series(['1/1','2/1','3/1'])})

df2 = {'1':pd.Series(['id1', 'test1', '45']),
        '2':pd.Series(['id1', 'test2', '423']),
        '3':pd.Series(['id1', 'test3', '5']),
        '4':pd.Series(['id2', 'test2', '421'])}
df2 = pd.DataFrame(df2)
df2 = df2.rename(index={0,:'id'})
df2 = df2.rename(index={1,:'test name'})
df2 = df2.rename(index={2,:'test value'})
</code>```

I would like to merge these two so that df1 contains a new column for each test name, with the tests value underneath, for each id. I.e.:

```<code>df1 = pd.DataFrame({'ID':pd.Series(['id1','id2','id3']),
                    'DoB':pd.Series(['15/2',12/3','25/12']),
                    'Surgery Date':pd.Series(['1/1','2/1','3/1']),
                    'Test1':pd.Series([45]),
                    'Test2':pd.Series([426,421])})
</code>```

Each ID has a different number of tests, and I'd like the code to work on a much larger database.

Cheers!

答:
I break down the steps ..</p>

```<code>df2=df2.T.set_index(['id','test name']).unstack()
df2.columns=df2.columns.droplevel()
df1.merge(df2,left_on='ID',right_index=True,how='left')
Out[457]:
     DoB   ID Surgery Date test1 test2 test3
0   15/2  id1          1/1    45   423     5
1   12/3  id2          2/1  None   421  None
2  25/12  id3          3/1   NaN   NaN   NaN
</code>```

Body:
I have two dataframes:

df1 = pd.DataFrame({'ID':pd.Series(['id1','id2','id3']),
                    'DoB':pd.Series(['15/2','12/3','25/12']),
                    'Surgery Date':pd.Series(['1/1','2/1','3/1'])})

df2 = {'1':pd.Series(['id1', 'test1', '45']),
        '2':pd.Series(['id1', 'test2', '423']),
        '3':pd.Series(['id1', 'test3', '5']),
        '4':pd.Series(['id2', 'test2', '421'])}
df2 = pd.DataFrame(df2)
df2 = df2.rename(index={0,:'id'})
df2 = df2.rename(index={1,:'test name'})
df2 = df2.rename(index={2,:'test value'})

I would like to merge these two so that df1 contains a new column for each test name, with the tests value underneath, for each id. I.e.:

df1 = pd.DataFrame({'ID':pd.Series(['id1','id2','id3']),
                    'DoB':pd.Series(['15/2',12/3','25/12']),
                    'Surgery Date':pd.Series(['1/1','2/1','3/1']),
                    'Test1':pd.Series([45]),
                    'Test2':pd.Series([426,421])})

Each ID has a different number of tests, and I'd like the code to work on a much larger database.

Cheers!

Body:
I break down the steps ..

df2=df2.T.set_index(['id','test name']).unstack()
df2.columns=df2.columns.droplevel()
df1.merge(df2,left_on='ID',right_index=True,how='left')
Out[457]:
     DoB   ID Surgery Date test1 test2 test3
0   15/2  id1          1/1    45   423     5
1   12/3  id2          2/1  None   421  None
2  25/12  id3          3/1   NaN   NaN   NaN