问:
Run callback function after forEach is done
In the project, I have a loop going through a list of urls. It downloads file from every url and do some post process over the downloaded file.

After the all the process done (both download process and post process), I want to execute a callback function. Because post process includes some streaming task, it has close event. If the last item can be identified, I can pass the callback function to the close event. However, since the loop is async, I can't track which item is done at last.

For now, I use a 5 second timeout to make sure the callback is executed after the whole process. Obviously, this is not sustainable. What's a good way to handle this?

loop code:

```<code>exports.processArray = (items, process, callback) => {
    var todo = items.concat();
    setTimeout(function() {
        process(todo.shift());
        if(todo.length > 0) {
          // execute download and post process each second
          // however it doesn't guarantee one start after previous one done
          setTimeout(arguments.callee, 1000);
        } else {
          setTimeout(() => {callback();}, 5000);
        }
    }, 1000);
};

processArray(
  // First param, the array
  urlList,
  // Second param, download and post process
  (url) => {
    if(url.startsWith('http')) {
      getDataReg(url, uid);
    }
    else if(url.startsWith('ftp')) {
      getDataFtp(url, uid);
    }
    else {
      console.log('not a valid resource');
    }
  },
  // Third param, callback to be executed after all done
  () => {
    Request.get(`${config.demouri}bound=${request.query.boundary};uid=${uid}`, {
      method: 'GET',
      auth: auth
    })
    .on('response', (response) => {
      console.log('response event emmits');
      zipFiles(uid)
      .then((path) => {
        reply.file(path, { confine: false, filename: uid + '.zip', mode: 'inline'}).header('Content-Disposition');
      });
    });
  }
);
</code>```

Download and post process:

```<code>exports.getDataFtp = (url, uid) => {
  console.log('get into ftp');
  var usefulUrl = url.split('//')[1];
  var spliter = usefulUrl.indexOf('/');
  var host = usefulUrl.substring(0, spliter);
  var dir = usefulUrl.substring(spliter+1, usefulUrl.length);
  var client = new ftp();
  var connection = {
    host: host
  };
  var fileNameStart = dir.lastIndexOf('/') + 1;
  var fileNameEnd = dir.length;
  var fileName = dir.substring(fileNameStart, fileNameEnd);
  console.log('filename: ', fileName);

  client.on('ready', () => {
    console.log('get into ftp ready');
    client.get(dir, (err, stream) => {
      if (err) {
        console.log('get file err:', err);
        return;
      } else{
        console.log('get into ftp get');
        stream.pipe(fs.createWriteStream(datadir + `download/${uid}/${fileName}`));
        stream.on('end', () => {
          console.log('get into ftp close');
          unzipData(datadir + `download/${uid}/`, fileName, uid);
          client.end();
        });
      }
    });
  });
  client.connect(connection);
};

exports.getDataReg = (url, uid) => {
  console.log('get into http');
    var fileNameStart = url.lastIndexOf('/') + 1;
  var fileNameEnd = url.length;
  var fileName = url.substring(fileNameStart, fileNameEnd);
    var file = fs.createWriteStream(datadir + `download/${uid}/${fileName}`);
    if (url.startsWith('https')) {
    https.get(url, (response) => {
      console.log('start piping file');
      response.pipe(file);
      file.on('finish', () => {
        console.log('get into http finish');
        unzipData(datadir + `download/${uid}/`, fileName, uid);
      });
    }).on('error', (err) => { // Handle errors
      fs.unlink(datadir + `download/${uid}/${fileName}`);
      console.log('download file err: ', err);
    });
    } else {
    http.get(url, (response) => {
      console.log('start piping file');
      response.pipe(file);
      file.on('finish', () => {
        unzipData(datadir + `download/${uid}/`, fileName, uid);
      });
    }).on('error', (err) => {
      fs.unlink(datadir + `download/${uid}/${fileName}`);
      console.log('download file err: ', err);
    });
    }
};

function unzipData(path, fileName, uid) {
  console.log('get into unzip');
  console.log('creating: ', path + fileName);
    fs.createReadStream(path + fileName)
    .pipe(unzip.Extract({path: path}))
    .on('close', () => {
    console.log('get into unzip close');
    var filelist = listFile(path);
    filelist.forEach((filePath) => {
      if (!filePath.endsWith('.zip')) {
        var components = filePath.split('/');
        var component = components[components.length-1];
        mv(filePath, datadir + `processing/${uid}/${component}`, (err) => {
          if(err) {
            console.log('move file err: ');
          } else {
            console.log('move file done');
          }
        });
      }
    });
    fs.unlink(path + fileName, (err) => {});
    });
}
</code>```

答:
In general, since nodejs does not appear to have implemented Streams Standard to be Promise based, at least from what can gather; but rather, uses an event based or callback mechanism, you can use Promise constructor within function call, to return a fulfilled Promise object when a specific event has been dispatched

```<code>const doStuff = (...args) => new Promise((resolve, reject)) => {
  /* define and do stream stuff */
  doStreamStuff.on(/* "close", "end" */, => {
    // do stuff
    resolve(/* value */)
  })
});

doStuff(/* args */)
.then(data => {})
.catch(err => {})
</code>```

Body:
In the project, I have a loop going through a list of urls. It downloads file from every url and do some post process over the downloaded file.

After the all the process done (both download process and post process), I want to execute a callback function. Because post process includes some streaming task, it has close event. If the last item can be identified, I can pass the callback function to the close event. However, since the loop is async, I can't track which item is done at last.

For now, I use a 5 second timeout to make sure the callback is executed after the whole process. Obviously, this is not sustainable. What's a good way to handle this?

loop code:

exports.processArray = (items, process, callback) => {
    var todo = items.concat();
    setTimeout(function() {
        process(todo.shift());
        if(todo.length > 0) {
          // execute download and post process each second
          // however it doesn't guarantee one start after previous one done
          setTimeout(arguments.callee, 1000);
        } else {
          setTimeout(() => {callback();}, 5000);
        }
    }, 1000);
};

processArray(
  // First param, the array
  urlList,
  // Second param, download and post process
  (url) => {
    if(url.startsWith('http')) {
      getDataReg(url, uid);
    }
    else if(url.startsWith('ftp')) {
      getDataFtp(url, uid);
    }
    else {
      console.log('not a valid resource');
    }
  },
  // Third param, callback to be executed after all done
  () => {
    Request.get(`${config.demouri}bound=${request.query.boundary};uid=${uid}`, {
      method: 'GET',
      auth: auth
    })
    .on('response', (response) => {
      console.log('response event emmits');
      zipFiles(uid)
      .then((path) => {
        reply.file(path, { confine: false, filename: uid + '.zip', mode: 'inline'}).header('Content-Disposition');
      });
    });
  }
);

Download and post process:

exports.getDataFtp = (url, uid) => {
  console.log('get into ftp');
  var usefulUrl = url.split('//')[1];
  var spliter = usefulUrl.indexOf('/');
  var host = usefulUrl.substring(0, spliter);
  var dir = usefulUrl.substring(spliter+1, usefulUrl.length);
  var client = new ftp();
  var connection = {
    host: host
  };
  var fileNameStart = dir.lastIndexOf('/') + 1;
  var fileNameEnd = dir.length;
  var fileName = dir.substring(fileNameStart, fileNameEnd);
  console.log('filename: ', fileName);

  client.on('ready', () => {
    console.log('get into ftp ready');
    client.get(dir, (err, stream) => {
      if (err) {
        console.log('get file err:', err);
        return;
      } else{
        console.log('get into ftp get');
        stream.pipe(fs.createWriteStream(datadir + `download/${uid}/${fileName}`));
        stream.on('end', () => {
          console.log('get into ftp close');
          unzipData(datadir + `download/${uid}/`, fileName, uid);
          client.end();
        });
      }
    });
  });
  client.connect(connection);
};

exports.getDataReg = (url, uid) => {
  console.log('get into http');
    var fileNameStart = url.lastIndexOf('/') + 1;
  var fileNameEnd = url.length;
  var fileName = url.substring(fileNameStart, fileNameEnd);
    var file = fs.createWriteStream(datadir + `download/${uid}/${fileName}`);
    if (url.startsWith('https')) {
    https.get(url, (response) => {
      console.log('start piping file');
      response.pipe(file);
      file.on('finish', () => {
        console.log('get into http finish');
        unzipData(datadir + `download/${uid}/`, fileName, uid);
      });
    }).on('error', (err) => { // Handle errors
      fs.unlink(datadir + `download/${uid}/${fileName}`);
      console.log('download file err: ', err);
    });
    } else {
    http.get(url, (response) => {
      console.log('start piping file');
      response.pipe(file);
      file.on('finish', () => {
        unzipData(datadir + `download/${uid}/`, fileName, uid);
      });
    }).on('error', (err) => {
      fs.unlink(datadir + `download/${uid}/${fileName}`);
      console.log('download file err: ', err);
    });
    }
};

function unzipData(path, fileName, uid) {
  console.log('get into unzip');
  console.log('creating: ', path + fileName);
    fs.createReadStream(path + fileName)
    .pipe(unzip.Extract({path: path}))
    .on('close', () => {
    console.log('get into unzip close');
    var filelist = listFile(path);
    filelist.forEach((filePath) => {
      if (!filePath.endsWith('.zip')) {
        var components = filePath.split('/');
        var component = components[components.length-1];
        mv(filePath, datadir + `processing/${uid}/${component}`, (err) => {
          if(err) {
            console.log('move file err: ');
          } else {
            console.log('move file done');
          }
        });
      }
    });
    fs.unlink(path + fileName, (err) => {});
    });
}

Body:
In general, since nodejs does not appear to have implemented Streams Standard to be Promise based, at least from what can gather; but rather, uses an event based or callback mechanism, you can use Promise constructor within function call, to return a fulfilled Promise object when a specific event has been dispatched

const doStuff = (...args) => new Promise((resolve, reject)) => {
  /* define and do stream stuff */
  doStreamStuff.on(/* "close", "end" */, => {
    // do stuff
    resolve(/* value */)
  })
});

doStuff(/* args */)
.then(data => {})
.catch(err => {})


来源: stackexchange

问:
tensorflow installation problems
I tried installing tensorflow on my ubuntu 14.04 64bit machine:

```<code>sudo pip2 install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.6.0-cp27-none-linux_x86_64.whl
</code>```

for python 2.7

When I run import tensorflow as tf in the console I get error

Error importing tensorflow.  Unless you are using bazel, you should
  not try to import tensorflow from its source directory; please exit
  the tensorflow source tree, and relaunch your python interpreter from
  there.

Google didn't provide a good answer to this, any thoughts?

答:
I ran in to a similar issue and it turned out it was because the protobuf dependency wasn't met, or there was an issue with protobuf. I would uninstall protobuf:

```<code>>> sudo pip uninstall protobuf
</code>```

Then re-install:

```<code>>> sudo pip install --upgrade protobuf
</code>```

If that doesn't work, try uninstalling and re-installing both protobuf and tensorflow. If you are building from source, check out this issue on GitHub

ContentLicense: CC BY-SA 3.0

Title: tensorflow installation problems

Body:
I tried installing tensorflow on my ubuntu 14.04 64bit machine:

sudo pip2 install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.6.0-cp27-none-linux_x86_64.whl

for python 2.7

When I run import tensorflow as tf in the console I get error

Error importing tensorflow.  Unless you are using bazel, you should
  not try to import tensorflow from its source directory; please exit
  the tensorflow source tree, and relaunch your python interpreter from
  there.

Google didn't provide a good answer to this, any thoughts?

Body:
I ran in to a similar issue and it turned out it was because the protobuf dependency wasn't met, or there was an issue with protobuf. I would uninstall protobuf:

>> sudo pip uninstall protobuf

Then re-install:

>> sudo pip install --upgrade protobuf

If that doesn't work, try uninstalling and re-installing both protobuf and tensorflow. If you are building from source, check out this issue on GitHub


问:
How do I add social media icons to my code?
This is the code i have so far.
At the end of the email, I would like to provide social icons like these ones that i found free online. And to lead them to corresponding links i have. Minus the skype.

https://codepen.io/anon/pen/QgjeXw

```<code>function sendEmails() {
  var allData,counter,emailAddress,fourRowsOfData,i,lastRow,
      message,messageStart,messageEnd,numRows,
      row,sheet,startRow,studentName,subject;

  //USER INPUT
  startRow = 2;  // First row of data to process
  numRows = 4;   // Number of rows to process
  subject = "Camp Pursuit: Report Card ";
  messageStart = "Dear Parents,"+'\n' +'\n' +
  "Every week at Camp Pursuit, we ask the teachers to make observations about how the kiddos did." +'\n' +
  "We know that one week isn't enough to truly know a child, so we call this our " +"Glows, Grows, & Apropos." +'\n' +
    "Meaning..." + '\n' +'\n' +
    "Glows: Positive things the teacher noticed" +'\n' +
    "Grows: Areas for continued growth" +'\n' +
    "Apropos: Ways to continue your son/daughter's enrichment" +'\n' +
    "We hope you appreciate seeing what the teachers saw last week, and perhaps you can use some of"+'\n' +
    "the recommendations for further enrichment this summer.  Feel free to let us know your thoughts on the camp through our anonymous online survey."+'\n' +
     "Your feedback helps us improve the experience for all kiddos! "+'\n' +
"Survey Link: https://docs.google.com/forms/d/1g4LvA9a8sdKECr1yvp5uOoPnvKACFm3HvbTBfvQGRyo/viewform?usp=send_form" +'\n' +
"We look forward to seeing your child at our programs throughout the year!" +'\n' +
"Sincerely, "+'\n' +
"The Camp Pursuit Team"
+'\n';
  //END USER INPUT

  sheet = SpreadsheetApp.getActiveSheet();
  lastRow = sheet.getLastRow();

  allData = sheet.getRange(startRow, 1, lastRow-startRow, 10);// Get All data first

  counter = 0;

  while (counter < lastRow-startRow) {
    Logger.log('counter: ' + counter)

    fourRowsOfData = sheet.getRange(startRow + counter, 1, numRows, 6).getValues();
    emailAddress = fourRowsOfData[0][0];  // First column of first row
    Logger.log('emailAddress: ' + emailAddress)

    studentName = fourRowsOfData[0][1];

    messageEnd = "";//Reset on every outer loop

    for (i = 0; i < numRows; i++) {//loop numRows times - once for each row
        row = fourRowsOfData[i];

        messageEnd = messageEnd + '\n' +
            "Class: " + row[2] + '\n' +'\n' +
              "Glows: " + row[3]+ '\n' +
              "Grows: " + row[4] +'\n' +
                "Apropos: " + row[5] +'\n';
    }

    message = messageStart + "\n" + studentName + "\n" + messageEnd;

    MailApp.sendEmail(emailAddress, subject, message);//Send the email outside of inner loop
    counter+=numRows;//Increment counter by number of rows to process
  }
}
</code>```

答:
I don't think you will be able to use examples from codepen as they involve lots of code (e.g. for displaying hover states, etc). However, you could save the buttons as images and store them in your Drive or elsewhere.

The next step is to get the blob for your image from external URL

```<code>var imageBlob = UrlFetchApp.fetch(yourImageUrl).getBlob();
</code>```

or from Drive

```<code>   var imageBlob = DriveApp.getFileById(yourFileId).getBlob();
</code>```

Build the string for the html body of your email. Use 'br' tags for line breaks. Wrap your images in 'a' tags to get them to link to external websites. In 'src' attribute of the 'img' tag, create a unique id for your image blob and put it after 'cid'.

```<code>var body = "<h1> Header </h1> <br />" +
            "<a href='www.example.com'><img src='cid:uid' /></a> Image <br />" +
            "Content";
</code>```

Instead of string parameters, pass the following object to MailApp.sendEmail() method. At runtime, the script will parse the string stored in 'body' variable and create html output, using cid identifiers to retrieve images from inlineImages object. The property names of 'inlineImages' object must match the ids you put created for your images in 'body'

```<code>MailApp.sendEmail({
    to: "recipient@example.com",
    subject: "subject",
    htmlBody: body,
    inlineImages: {

      uid: imageBlob

    }

});
</code>```

Concatenating the string to produce html body is not the best solution though. Consider creating a reusable html template using HtmlService https://developers.google.com/apps-script/guides/html/

Body:
This is the code i have so far.
At the end of the email, I would like to provide social icons like these ones that i found free online. And to lead them to corresponding links i have. Minus the skype.

https://codepen.io/anon/pen/QgjeXw

function sendEmails() {
  var allData,counter,emailAddress,fourRowsOfData,i,lastRow,
      message,messageStart,messageEnd,numRows,
      row,sheet,startRow,studentName,subject;

  //USER INPUT
  startRow = 2;  // First row of data to process
  numRows = 4;   // Number of rows to process
  subject = "Camp Pursuit: Report Card ";
  messageStart = "Dear Parents,"+'\n' +'\n' +
  "Every week at Camp Pursuit, we ask the teachers to make observations about how the kiddos did." +'\n' +
  "We know that one week isn't enough to truly know a child, so we call this our " +"Glows, Grows, & Apropos." +'\n' +
    "Meaning..." + '\n' +'\n' +
    "Glows: Positive things the teacher noticed" +'\n' +
    "Grows: Areas for continued growth" +'\n' +
    "Apropos: Ways to continue your son/daughter's enrichment" +'\n' +
    "We hope you appreciate seeing what the teachers saw last week, and perhaps you can use some of"+'\n' +
    "the recommendations for further enrichment this summer.  Feel free to let us know your thoughts on the camp through our anonymous online survey."+'\n' +
     "Your feedback helps us improve the experience for all kiddos! "+'\n' +
"Survey Link: https://docs.google.com/forms/d/1g4LvA9a8sdKECr1yvp5uOoPnvKACFm3HvbTBfvQGRyo/viewform?usp=send_form" +'\n' +
"We look forward to seeing your child at our programs throughout the year!" +'\n' +
"Sincerely, "+'\n' +
"The Camp Pursuit Team"
+'\n';
  //END USER INPUT

  sheet = SpreadsheetApp.getActiveSheet();
  lastRow = sheet.getLastRow();

  allData = sheet.getRange(startRow, 1, lastRow-startRow, 10);// Get All data first

  counter = 0;

  while (counter < lastRow-startRow) {
    Logger.log('counter: ' + counter)

    fourRowsOfData = sheet.getRange(startRow + counter, 1, numRows, 6).getValues();
    emailAddress = fourRowsOfData[0][0];  // First column of first row
    Logger.log('emailAddress: ' + emailAddress)

    studentName = fourRowsOfData[0][1];

    messageEnd = "";//Reset on every outer loop

    for (i = 0; i < numRows; i++) {//loop numRows times - once for each row
        row = fourRowsOfData[i];

        messageEnd = messageEnd + '\n' +
            "Class: " + row[2] + '\n' +'\n' +
              "Glows: " + row[3]+ '\n' +
              "Grows: " + row[4] +'\n' +
                "Apropos: " + row[5] +'\n';
    }

    message = messageStart + "\n" + studentName + "\n" + messageEnd;

    MailApp.sendEmail(emailAddress, subject, message);//Send the email outside of inner loop
    counter+=numRows;//Increment counter by number of rows to process
  }
}

Body:
I don't think you will be able to use examples from codepen as they involve lots of code (e.g. for displaying hover states, etc). However, you could save the buttons as images and store them in your Drive or elsewhere.

The next step is to get the blob for your image from external URL

var imageBlob = UrlFetchApp.fetch(yourImageUrl).getBlob();

or from Drive

   var imageBlob = DriveApp.getFileById(yourFileId).getBlob();

Build the string for the html body of your email. Use 'br' tags for line breaks. Wrap your images in 'a' tags to get them to link to external websites. In 'src' attribute of the 'img' tag, create a unique id for your image blob and put it after 'cid'.

var body = "<h1> Header </h1> <br />" +
            "<a href='www.example.com'><img src='cid:uid' /></a> Image <br />" +
            "Content";

Instead of string parameters, pass the following object to MailApp.sendEmail() method. At runtime, the script will parse the string stored in 'body' variable and create html output, using cid identifiers to retrieve images from inlineImages object. The property names of 'inlineImages' object must match the ids you put created for your images in 'body'

MailApp.sendEmail({
    to: "recipient@example.com",
    subject: "subject",
    htmlBody: body,
    inlineImages: {

      uid: imageBlob

    }

});

Concatenating the string to produce html body is not the best solution though. Consider creating a reusable html template using HtmlService https://developers.google.com/apps-script/guides/html/


问:
Can specific Delphi hints be disabled?
In Delphi, you can use compiler directives to disable specific warnings, such as

```<code>{$WARN USE_BEFORE_DEF OFF}
</code>```

But when I tried to do that with a specific hint, whose underscore_style_name I got out of the helpfile, the compiler said it doesn't know what {$HINT} is.  So is there any way to do this?

答:
Best I can think of is to surround the subject of the hint with a conditional define, and use the same conditional define around the code that may or may not be needed, as shown below:

If you have this:

```<code>procedure MyProc;
var
  i : integer;
begin
  DoSomething;
  //SomethingWith_i_IsCommentedOut;
end;
</code>```

You will get:
Hint: variable "i" is declared but never used

So try this instead:

```<code>procedure MyProc;
  {$IFDEF USE_THE_I_PROCEDURE}
var
  i : integer;
  {$ENDIF}
begin
  DoSomething;
  {$IFDEF USE_THE_I_PROCEDURE}
  SomethingWith_i_IsCommentedOut;
  {$ENDIF}
end;
</code>```

Now you can turn the define on or off, and you should never get a hint.

OwnerDisplayName: Mason Wheeler

ContentLicense: CC BY-SA 2.5

Title: Can specific Delphi hints be disabled?

Body:
In Delphi, you can use compiler directives to disable specific warnings, such as

{$WARN USE_BEFORE_DEF OFF}

But when I tried to do that with a specific hint, whose underscore_style_name I got out of the helpfile, the compiler said it doesn't know what {$HINT} is.  So is there any way to do this?

Body:
Best I can think of is to surround the subject of the hint with a conditional define, and use the same conditional define around the code that may or may not be needed, as shown below:

If you have this:

procedure MyProc;
var
  i : integer;
begin
  DoSomething;
  //SomethingWith_i_IsCommentedOut;
end;

You will get:
Hint: variable "i" is declared but never used

So try this instead:

procedure MyProc;
  {$IFDEF USE_THE_I_PROCEDURE}
var
  i : integer;
  {$ENDIF}
begin
  DoSomething;
  {$IFDEF USE_THE_I_PROCEDURE}
  SomethingWith_i_IsCommentedOut;
  {$ENDIF}
end;

Now you can turn the define on or off, and you should never get a hint.

OwnerDisplayName: kogus


问:
Memory Consistency || Thread interference || Php
I have a question regarding Memcache and session lock for user session.
I want to lock or do something that will prevent Thread Interference for user session...

We have a situation like so:

If server is at max, user is redirected to "free" server, but a this point some of data are wrong...

So does anybody has any sugestions :?

答:
If you want to spread your sessions across multiple servers I would recommend using consistent hashing, as it reduces the number of misses when you add/delete servers.

Memcached does not support locking, but I believe a the new memcached module has a workaround that provides support for locking. I have however not used it yet.


问:
Avoid Angular2 to systematically submit form on button click
Ok so maybe this is unclear. Get this form:

```<code><form (ngSubmit)="submit()" #crisisForm="ngForm">
   <input type="text" name="name" [(ngModel)]="crisis.name">
   <button type="submit">Submit</button>
   <button type="button" (click)="preview()">Preview</button>
   <button type="reset" (click)="reset()">Reset</button>
</form>
</code>```

Why do all buttons trigger the submit() function ? And how to avoid that ?

答: Set type="button" in the button that you don't want to execute submit.

Body:
Ok so maybe this is unclear. Get this form:

<form (ngSubmit)="submit()" #crisisForm="ngForm">
   <input type="text" name="name" [(ngModel)]="crisis.name">
   <button type="submit">Submit</button>
   <button type="button" (click)="preview()">Preview</button>
   <button type="reset" (click)="reset()">Reset</button>
</form>

Why do all buttons trigger the submit() function ? And how to avoid that ?


问:
CircleCI/Sauce Labs proxy works but does not run Grunt task
I am trying to integrate with Sauce Labs to run my project's Protractor tests, using CircleCI's guide as a basis. The tests are wrapped in a Grunt task, which runs flawlessly on my machine:

```<code>grunt.registerTask('test:protractor', [
    'ngconstant:dev',
    'modernizr:prod',
    'sass',
    'protractor'
]);
</code>```

This is my circle.yml file:

```<code>dependencies:
  pre:
    - sudo apt-get update; sudo apt-get install ruby-sass
    - npm install -g bower
    - bower install
  post:
    - wget https://saucelabs.com/downloads/sc-latest-linux.tar.gz
    - tar -xzf sc-latest-linux.tar.gz

test:
  override:
    - cd sc-*-linux && ./bin/sc --user $SAUCE_USERNAME --api-key $SAUCE_ACCESS_KEY --readyfile ~/sauce_is_ready:
        background: true
    # Wait for tunnel to be ready
    - while [ ! -e ~/sauce_is_ready ]; do sleep 1; done
    - grunt test:protractor
        background: true
  post:
    - killall --wait sc  # wait for Sauce Connect to close the tunnel
</code>```

The Sauce Connect proxy clearly works according to build output:

```<code>30 May 18:18:46 - Started scproxy on port 35557.
30 May 18:18:46 - Please wait for 'you may start your tests' to start your tests.
30 May 18:19:03 - Provisioned tunnel:4b38b707d2174ebf9714f05cd8c06f79
30 May 18:19:03 - Using no proxy for connecting to tunnel VM.
30 May 18:19:03 - Starting Selenium listener...
30 May 18:19:03 - Establishing secure TLS connection to tunnel...
30 May 18:19:03 - Selenium listener started on port 4445.
30 May 18:19:04 - Sauce Connect is up, you may start your tests.
</code>```

But at that point, it totally stalls. No effort to call grunt test:protractor, no activity whatsoever. After 10 minutes I killed the build.

What am I missing from this configuration to run Protractor tests through the Sauce Labs proxy?

答:
Maybe you forgot to install grunt</p>

```<code>dependencies:
  pre:
    - npm install -g grunt
</code>```

Body:
I am trying to integrate with Sauce Labs to run my project's Protractor tests, using CircleCI's guide as a basis. The tests are wrapped in a Grunt task, which runs flawlessly on my machine:

grunt.registerTask('test:protractor', [
    'ngconstant:dev',
    'modernizr:prod',
    'sass',
    'protractor'
]);

This is my circle.yml file:

dependencies:
  pre:
    - sudo apt-get update; sudo apt-get install ruby-sass
    - npm install -g bower
    - bower install
  post:
    - wget https://saucelabs.com/downloads/sc-latest-linux.tar.gz
    - tar -xzf sc-latest-linux.tar.gz

test:
  override:
    - cd sc-*-linux && ./bin/sc --user $SAUCE_USERNAME --api-key $SAUCE_ACCESS_KEY --readyfile ~/sauce_is_ready:
        background: true
    # Wait for tunnel to be ready
    - while [ ! -e ~/sauce_is_ready ]; do sleep 1; done
    - grunt test:protractor
        background: true
  post:
    - killall --wait sc  # wait for Sauce Connect to close the tunnel

The Sauce Connect proxy clearly works according to build output:

30 May 18:18:46 - Started scproxy on port 35557.
30 May 18:18:46 - Please wait for 'you may start your tests' to start your tests.
30 May 18:19:03 - Provisioned tunnel:4b38b707d2174ebf9714f05cd8c06f79
30 May 18:19:03 - Using no proxy for connecting to tunnel VM.
30 May 18:19:03 - Starting Selenium listener...
30 May 18:19:03 - Establishing secure TLS connection to tunnel...
30 May 18:19:03 - Selenium listener started on port 4445.
30 May 18:19:04 - Sauce Connect is up, you may start your tests.

But at that point, it totally stalls. No effort to call grunt test:protractor, no activity whatsoever. After 10 minutes I killed the build.

What am I missing from this configuration to run Protractor tests through the Sauce Labs proxy?

Body:
Maybe you forgot to install grunt

dependencies:
  pre:
    - npm install -g grunt


问:
How to send image file via Alamofire?
I want to send an image to the server and I'm using this code:

```<code>Alamofire.upload(
            .POST,
            "https://api.mysite.com/image",
            multipartFormData: { multipartFormData in
                if let _ = image {
                    if let imageData = UIImageJPEGRepresentation(image!, 1.0) {
                        multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.png", mimeType: "image/png")
                    }
                }
            }, encodingCompletion: {
                encodingResult in

                switch encodingResult {
                case .Success(let upload, _, _):
                    upload.responseJSON { response in
                        switch response.result {
                        case .Success:
                            debugPrint(response)
                        case .Failure(let error):
                            print(error)
                        }

                    }
                case .Failure(let encodingError):
                    print(encodingError)
                }
            }
        )
</code>```

but in response I get:

```<code>[Result]: SUCCESS: (
"",
    {
    file =         {
        error = 1;
        name = "file.png";
        size = 0;
        "tmp_name" = "";
        type = "";
    };
</code>```

so my file is not sending to the server. What is the wrong in my code?

答:
```<code>let imageData = UIPNGRepresentation(image)!

Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
  debugPrint(response)
}
</code>```

from:

https://github.com/Alamofire/Alamofire#uploading-data

Title: How to send image file via Alamofire?

Body:
I want to send an image to the server and I'm using this code:

Alamofire.upload(
            .POST,
            "https://api.mysite.com/image",
            multipartFormData: { multipartFormData in
                if let _ = image {
                    if let imageData = UIImageJPEGRepresentation(image!, 1.0) {
                        multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.png", mimeType: "image/png")
                    }
                }
            }, encodingCompletion: {
                encodingResult in

                switch encodingResult {
                case .Success(let upload, _, _):
                    upload.responseJSON { response in
                        switch response.result {
                        case .Success:
                            debugPrint(response)
                        case .Failure(let error):
                            print(error)
                        }

                    }
                case .Failure(let encodingError):
                    print(encodingError)
                }
            }
        )

but in response I get:

[Result]: SUCCESS: (
"",
    {
    file =         {
        error = 1;
        name = "file.png";
        size = 0;
        "tmp_name" = "";
        type = "";
    };

so my file is not sending to the server. What is the wrong in my code?

Body:
let imageData = UIPNGRepresentation(image)!

Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
  debugPrint(response)
}

from:

https://github.com/Alamofire/Alamofire#uploading-data


问:
Circular iterator / generator for list of custom class items
Say I have a custom class:

```<code>public class CustomClass {
    private String name;
    private String data;

    public CustomClass(String name, String data) {
        this.name = name;
        this.data = data;
    }
}
</code>```

I also have a list of my custom class objects:

```<code>CustomClass[] list = new CustomClass[] {
    new CustomClass("Item 1", "data"),
    new CustomClass("Item 2", "data"),
    new CustomClass("Item 3", "data"),
    new CustomClass("Item 4", "data"),
    new CustomClass("Item 5", "data"),
};
</code>```

How can I create an iterator (or, rather, generator) to iterate through the list K times (K > list.length) giving me next element every time?

I prefer an "inline" solution (without creating any new classes).

Say, I need to get my CustomClass list items one after another K = 7 times. The solution should retrieve me following CustomClass objects:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

答:
A simple way to do this is:</p>

```<code>import com.google.common.collect.Iterables
import com.google.common.collect.Iterators;

Integer[] arr = {1,2,3,4,5};
Iterator<Integer> iter = Iterators.limit(Iterables.cycle(arr).iterator(),7) ;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Say I have a custom class:

public class CustomClass {
    private String name;
    private String data;

    public CustomClass(String name, String data) {
        this.name = name;
        this.data = data;
    }
}

I also have a list of my custom class objects:

CustomClass[] list = new CustomClass[] {
    new CustomClass("Item 1", "data"),
    new CustomClass("Item 2", "data"),
    new CustomClass("Item 3", "data"),
    new CustomClass("Item 4", "data"),
    new CustomClass("Item 5", "data"),
};

How can I create an iterator (or, rather, generator) to iterate through the list K times (K > list.length) giving me next element every time?

I prefer an "inline" solution (without creating any new classes).

Say, I need to get my CustomClass list items one after another K = 7 times. The solution should retrieve me following CustomClass objects:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

Body:
A simple way to do this is:

import com.google.common.collect.Iterables
import com.google.common.collect.Iterators;

Integer[] arr = {1,2,3,4,5};
Iterator<Integer> iter = Iterators.limit(Iterables.cycle(arr).iterator(),7) ;


问:
How to obtain FB user id that is valid for messenger link
There are a lot of ways how I we can get FB user id`s but the question is not about that.

I have implemented facebook login and retrieved user id many time. So far I was concerned only with authorizing users so I used user id to mach it against my database.

However know I need to use this id to created a link to users facebook profile. Dead simple:

```<code>'https://www.facebook.com/'+id
</code>```

However when I tried to link to users messenger acount:

```<code>'https://www.facebook.com/messages/t/'+id
</code>```

the link is broken.

When using tools like findmyfbid.com I can get user id whichs differs from one that I obtained from Facebook login. And this id works well for both FB profile and messenger links.

My question is - how to obtain (if it is even possible) that id in order to create a working messenger link.

Here is code example that I used to obtain facebook id from facebook login:

```<code>$fb = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.2',
  ]);

try {
  // Returns a `Facebook\FacebookResponse` object
  $response = $fb->get('/me?fields=id,name', '{access-token}');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$user = $response->getGraphUser();

echo 'Name: ' . $user['id'];
</code>```

答: That's not possible because if it as, it would be abused by spammers. Facebook protects against it.</p>

Body:
There are a lot of ways how I we can get FB user id`s but the question is not about that.

I have implemented facebook login and retrieved user id many time. So far I was concerned only with authorizing users so I used user id to mach it against my database.

However know I need to use this id to created a link to users facebook profile. Dead simple:

'https://www.facebook.com/'+id

However when I tried to link to users messenger acount:

'https://www.facebook.com/messages/t/'+id

the link is broken.

When using tools like findmyfbid.com I can get user id whichs differs from one that I obtained from Facebook login. And this id works well for both FB profile and messenger links.

My question is - how to obtain (if it is even possible) that id in order to create a working messenger link.

Here is code example that I used to obtain facebook id from facebook login:

$fb = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.2',
  ]);

try {
  // Returns a `Facebook\FacebookResponse` object
  $response = $fb->get('/me?fields=id,name', '{access-token}');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$user = $response->getGraphUser();

echo 'Name: ' . $user['id'];


问:
In Javascript, how do I automatically move the cursor to the next text box when the current one is full?
Suppose I have two HTML textboxes on my web page:

```<code><input type='text' id='txt1' maxlength='5' />
<input type='text' id='txt2' maxlength='5' />
</code>```

Each textbox allows the user to type up to five characters.  How can I use Javascript with or without jQuery to automatically move the cursor from txt1 to txt2 when the user types five charcters into txt1?

答:
The idea is to handle the keydown event and check if the maximum length has been reached; if so, focus the next control.

```<code>document.getElementById('txt1').onkeydown = function() {
  if (this.value.length == this.maxLength)
    document.getElementById('txt2').focus();
}
</code>```

Body:
Suppose I have two HTML textboxes on my web page:

<input type='text' id='txt1' maxlength='5' />
<input type='text' id='txt2' maxlength='5' />

Each textbox allows the user to type up to five characters.  How can I use Javascript with or without jQuery to automatically move the cursor from txt1 to txt2 when the user types five charcters into txt1?

Body:
The idea is to handle the keydown event and check if the maximum length has been reached; if so, focus the next control.

document.getElementById('txt1').onkeydown = function() {
  if (this.value.length == this.maxLength)
    document.getElementById('txt2').focus();
}


问:
Converting an AES256 Encryption algorithm in Java to PHP
Hi everyone i'm hitting a major roadblock with trying to integrate an API that uses AES256 encryption from a Java example to PHP, this is the Java version that is present in the documentation.

```<code>package com.partner.carrier.library;

import java.io.UnsupportedEncodingException;

import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.RijndaelEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Base64;

import com.partner.config.ConfigData;

public class AES {
    private static byte[] _sessionKey = "YOUR-KEY".getBytes();
    private static byte[] _initialVector = "INITVECTOREXAMPLE".getBytes();
        private static int _keySize = 256;
        private static int _blockSize = 128;

    public static String Encrypt(String txt)
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RijndaelEngine(_blockSize)), new ZeroBytePadding());
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(_sessionKey, 0, (_keySize / 8)), _initialVector, 0, (_blockSize / 8));
        cipher.init(true, ivAndKey);

        try {
            byte[] decoded = txt.trim().getBytes("UTF-8");
            byte[] encoded  = new byte[cipher.getOutputSize(decoded.length)];
            int len = cipher.processBytes(decoded, 0, decoded.length, encoded, 0);

            cipher.doFinal(encoded, len);
            return new String(Base64.encode(encoded));
        }
        catch (DataLengthException | IllegalStateException | InvalidCipherTextException | UnsupportedEncodingException e) {
            return null;
        }
    }
</code>```

}

From this i can gather that i should run something in PHP like this

```<code>openssl_encrypt($data, "aes-256-cbc", “YOURKEY”, null, "INITVECTOREXAMPLE");
</code>```

And then i should convert the result of that to Base64 and return it? Is this correct? The ZeroBytePadding() calls and all of that are really confusing to me.

Thank you in advance for your help! :)

答:
Solved the problem using this excellent class

http://aesencryption.net/#PHP-aes-encryption-example

Just tweaked it slightly and there i go, now it works fine.

```<code>$encoder = new AES($data, "PRIVATEKEYHERE", 128, "cbc", "INITIALVECTORIFANY");
$_SESSION['ENCRYPTED_DATA'] = $encoder->encrypt();
</code>```

Hope this helps someone later down the line :) Thanks!

Body:
Hi everyone i'm hitting a major roadblock with trying to integrate an API that uses AES256 encryption from a Java example to PHP, this is the Java version that is present in the documentation.

package com.partner.carrier.library;

import java.io.UnsupportedEncodingException;

import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.RijndaelEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Base64;

import com.partner.config.ConfigData;

public class AES {
    private static byte[] _sessionKey = "YOUR-KEY".getBytes();
    private static byte[] _initialVector = "INITVECTOREXAMPLE".getBytes();
        private static int _keySize = 256;
        private static int _blockSize = 128;

    public static String Encrypt(String txt)
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RijndaelEngine(_blockSize)), new ZeroBytePadding());
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(_sessionKey, 0, (_keySize / 8)), _initialVector, 0, (_blockSize / 8));
        cipher.init(true, ivAndKey);

        try {
            byte[] decoded = txt.trim().getBytes("UTF-8");
            byte[] encoded  = new byte[cipher.getOutputSize(decoded.length)];
            int len = cipher.processBytes(decoded, 0, decoded.length, encoded, 0);

            cipher.doFinal(encoded, len);
            return new String(Base64.encode(encoded));
        }
        catch (DataLengthException | IllegalStateException | InvalidCipherTextException | UnsupportedEncodingException e) {
            return null;
        }
    }

}

From this i can gather that i should run something in PHP like this

openssl_encrypt($data, "aes-256-cbc", “YOURKEY”, null, "INITVECTOREXAMPLE");

And then i should convert the result of that to Base64 and return it? Is this correct? The ZeroBytePadding() calls and all of that are really confusing to me.

Thank you in advance for your help! :)

Body:
Solved the problem using this excellent class

http://aesencryption.net/#PHP-aes-encryption-example

Just tweaked it slightly and there i go, now it works fine.

$encoder = new AES($data, "PRIVATEKEYHERE", 128, "cbc", "INITIALVECTORIFANY");
$_SESSION['ENCRYPTED_DATA'] = $encoder->encrypt();

Hope this helps someone later down the line :) Thanks!


问:
SQLCMD Session Run SQL Script
I'm still pretty new to SQL Server but have a ton of experience with Oracle. How do I run a SQL script while I'm inside a SQLCMD session? Is their something analogous to "SQL>@C:[mypath]\myscript.sql" (Oracle) for SQL Server?

I'm sick of opening scripts and running them using bloated SQL Server Studio.

答:
I found what I was looking for. You can use this in SQLCMD and in SSMS Query as long as you open it up in "SQLCMD Mode"

```<code>:r [path]\myscript.sql
</code>```

TransactSQL to run another TransactSQL script

Thanks for your responses. Much thanks.

Title: SQLCMD Session Run SQL Script

Body:
I found what I was looking for. You can use this in SQLCMD and in SSMS Query as long as you open it up in "SQLCMD Mode"

:r [path]\myscript.sql

TransactSQL to run another TransactSQL script

Thanks for your responses. Much thanks.


问:
Annotation of the class is loaded in web server is com.sun.proxy.$Proxy52?
I have a problem with the annotation of the class is loaded in web server(using maven and jersey) . When i got the annotation of the loaded class, the type of annotation is com.sun.proxy.$Proxy52 and i cannot cast to our defined type. But if i loaded that class in a normal java project, the type of annotation is our defined type.

code loaded class:

```<code> URLClassLoader cl = URLClassLoader.newInstance(new URL[]{Paths.get("C:\\HelloWorld.jar").toUri().toURL()});
 addURLToSystemClassLoader(new URL("file:///C:/HelloWorld.jar"));

Class c = cl.loadClass("NewHelloWorldPackage1.Doc_NewDocument1");
Annotation[] aaaa = c.getAnnotations(); // the type of each annotation in aaaa is com.sun.proxy.$Proxy52
</code>```

and the class to load:

```<code>import a.b.OtxElement;

@OtxElement((a.b.OtxElementTypes.Otx))
public class Doc_NewDocument1 {
  //something to do here...
}
</code>```

Please tell me what is the difference? I need to get our defined type.

答: The fact that you get a proxy in front of your annotation type should not matter. It might actually mislead you into believing that this is the cause for problems you are having. If stuff like "isAnnotationPresent(..)" fails, it is not due to that proxy, it is because you have loaded the annotation class multiple times using multiple classloaders. For example, Jetty gives priority to the WebApp classloader by default. So if your Jetty server instance (or Tomcat or whatever) already has loaded the annotation class, and the annotation is on your WebApp's classpath, too, you can have problems like "getAnnotation()" not returning anything. Just make sure that the library containing your annotation is not loaded twice.</p>

Body:
I have a problem with the annotation of the class is loaded in web server(using maven and jersey) . When i got the annotation of the loaded class, the type of annotation is com.sun.proxy.$Proxy52 and i cannot cast to our defined type. But if i loaded that class in a normal java project, the type of annotation is our defined type.

code loaded class:

 URLClassLoader cl = URLClassLoader.newInstance(new URL[]{Paths.get("C:\\HelloWorld.jar").toUri().toURL()});
 addURLToSystemClassLoader(new URL("file:///C:/HelloWorld.jar"));

Class c = cl.loadClass("NewHelloWorldPackage1.Doc_NewDocument1");
Annotation[] aaaa = c.getAnnotations(); // the type of each annotation in aaaa is com.sun.proxy.$Proxy52

and the class to load:

import a.b.OtxElement;

@OtxElement((a.b.OtxElementTypes.Otx))
public class Doc_NewDocument1 {
  //something to do here...
}

Please tell me what is the difference? I need to get our defined type.


问:
How can I remove a chunk of text from a Javascript string?
I am trying to analyze a piece of text via JavaScript and, reading up, have learned that parsing HTML with Regex is quite evil. I'd like to remove a more sinister part of my text before I analyze it.

If I've got a chunk of text like the item below, how might I (1) slice everything from [caption] to [/caption] and (2) store that text in a new var?

```<code>Sed rutrum enim sit amet sem fringilla egestas placerat mauris pretium. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ultricies egestas malesuada. Etiam rhoncus eros a leo imperdiet vitae tincidunt purus laoreet. Mauris ut mauris quam, sed pharetra urna. Etiam eu enim mauris, vitae bibendum orci. Quisque ac sapien massa, at dignissim tellus.

[caption id="blah" align="alignleft" width="123" caption="Lorem ipsum dolor sit, consectetur adipiscing elit."]<a href="http://www.google.com/something"><img title="Lorem ipsum dolor sit, consectetur adipiscing elit." src="http://google.com/something/else.png" alt="Lorem ipsum dolor sit, consectetur adipiscing elit." width="345" /></a>[/caption]

Aenean faucibus mi sit amet leo suscipit nec egestas leo ultrices. Integer tincidunt, urna quis varius accumsan, urna quam congue nulla, ut ornare orci purus in ligula. Suspendisse varius, tellus aliquam tincidunt, ante semper elit, sit amet tincidunt elit augue eget odio. Vivamus sit amet tincidunt massa. Sed nunc ligula, feugiat quis volutpat congue, eleifend in tellus. Curabitur ut dictum felis. Nunc sodales euismod leo, in commodo elit ornare hendrerit. Cras luctus eros id nisl vestibulum elementum. Maecenas ut neque turpis. Donec ornare hendrerit rutrum. Non nibh leo, dictum ullamcorper dui.
</code>```

答:
If you're parsing plain text there is no way to do it easier than with regex, at least there is no built-in functions in js to do it.

If you're parsing HTML in browser, there is much easy way to do it using DOM tree and functions for DOM, afaik it's recommended way to do it. And js frameworks like jQuery make this task as easy as it could be.

If you're parsing HTML on server-side, e.g. by node.js, there're also libraries for creating and working with DOM like jsdom, and again you can do it by using DOM functions.

Body:
I am trying to analyze a piece of text via JavaScript and, reading up, have learned that parsing HTML with Regex is quite evil. I'd like to remove a more sinister part of my text before I analyze it.

If I've got a chunk of text like the item below, how might I (1) slice everything from [caption] to [/caption] and (2) store that text in a new var?

Sed rutrum enim sit amet sem fringilla egestas placerat mauris pretium. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ultricies egestas malesuada. Etiam rhoncus eros a leo imperdiet vitae tincidunt purus laoreet. Mauris ut mauris quam, sed pharetra urna. Etiam eu enim mauris, vitae bibendum orci. Quisque ac sapien massa, at dignissim tellus.

[caption id="blah" align="alignleft" width="123" caption="Lorem ipsum dolor sit, consectetur adipiscing elit."][/caption]

Aenean faucibus mi sit amet leo suscipit nec egestas leo ultrices. Integer tincidunt, urna quis varius accumsan, urna quam congue nulla, ut ornare orci purus in ligula. Suspendisse varius, tellus aliquam tincidunt, ante semper elit, sit amet tincidunt elit augue eget odio. Vivamus sit amet tincidunt massa. Sed nunc ligula, feugiat quis volutpat congue, eleifend in tellus. Curabitur ut dictum felis. Nunc sodales euismod leo, in commodo elit ornare hendrerit. Cras luctus eros id nisl vestibulum elementum. Maecenas ut neque turpis. Donec ornare hendrerit rutrum. Non nibh leo, dictum ullamcorper dui.


答:
Just use a random index (in your case 2 because you have 3 dimensions):

```<code>import numpy as np

Space_Position = np.array(Space_Position)

random_index1 = np.random.randint(0, Space_Position.shape[0])
random_index2 = np.random.randint(0, Space_Position.shape[1])

Space_Position[random_index1, random_index2]  # get the random element.
</code>```

The alternative is to actually make it 2D:

```<code>Space_Position = np.array(Space_Position).reshape(-1, 2)
</code>```

and then use one random index:

```<code>Space_Position = np.array(Space_Position).reshape(-1, 2)      # make it 2D
random_index = np.random.randint(0, Space_Position.shape[0])  # generate a random index
Space_Position[random_index]                                  # get the random element.
</code>```

If you want N samples with replacement:

```<code>N = 5

Space_Position = np.array(Space_Position).reshape(-1, 2)                # make it 2D
random_indices = np.random.randint(0, Space_Position.shape[0], size=N)  # generate N random indices
Space_Position[random_indices]  # get N samples with replacement
</code>```

or without replacement:

```<code>Space_Position = np.array(Space_Position).reshape(-1, 2)  # make it 2D
random_indices = np.arange(0, Space_Position.shape[0])    # array of all indices
np.random.shuffle(random_indices)                         # shuffle the array
Space_Position[random_indices[:N]]  # get N samples without replacement
</code>```

Title: how to randomly sample in 2D matrix in numpy

Body:
I have a 2d array/matrix like this, how would I randomly pick the value from this 2D matrix, for example getting value like [-62, 29.23]. I looked at the numpy.choice but it is built for 1d array.

The following is my example with 4 rows and 8 columns

Space_Position=[
      [[-62,29.23],[-49.73,29.23],[-31.82,29.23],[-14.2,29.23],[3.51,29.23],[21.21,29.23],[39.04,29.23],[57.1,29.23]],

      [[-62,11.28],[-49.73,11.28],[-31.82,11.28],[-14.2,11.28],[3.51,11.28],[21.21,11.28] ,[39.04,11.28],[57.1,11.8]],

      [[-62,-5.54],[-49.73,-5.54],[-31.82,-5.54] ,[-14.2,-5.54],[3.51,-5.54],[21.21,-5.54],[39.04,-5.54],[57.1,-5.54]],

      [[-62,-23.1],[-49.73,-23.1],[-31.82,-23.1],[-14.2,-23.1],[3.51,-23.1],[21.21,-23.1],[39.04,-23.1] ,[57.1,-23.1]]
      ]

In the answers the following solution was given:

random_index1 = np.random.randint(0, Space_Position.shape[0])
random_index2 = np.random.randint(0, Space_Position.shape[1])
Space_Position[random_index1][random_index2]

this indeed works to give me one sample, how about more than one sample like what np.choice() does?

Another way I am thinking is to tranform the matrix into a array instead of matrix like,

Space_Position=[
      [-62,29.23],[-49.73,29.23],[-31.82,29.23],[-14.2,29.23],[3.51,29.23],[21.21,29.23],[39.04,29.23],[57.1,29.23], .....   ]

and at last use np.choice(), however I could not find the ways to do the transformation, np.flatten() makes the array like

Space_Position=[-62,29.23,-49.73,29.2, ....]

Body:
Just use a random index (in your case 2 because you have 3 dimensions):

import numpy as np

Space_Position = np.array(Space_Position)

random_index1 = np.random.randint(0, Space_Position.shape[0])
random_index2 = np.random.randint(0, Space_Position.shape[1])

Space_Position[random_index1, random_index2]  # get the random element.

The alternative is to actually make it 2D:

Space_Position = np.array(Space_Position).reshape(-1, 2)

and then use one random index:

Space_Position = np.array(Space_Position).reshape(-1, 2)      # make it 2D
random_index = np.random.randint(0, Space_Position.shape[0])  # generate a random index
Space_Position[random_index]                                  # get the random element.

If you want N samples with replacement:

N = 5

Space_Position = np.array(Space_Position).reshape(-1, 2)                # make it 2D
random_indices = np.random.randint(0, Space_Position.shape[0], size=N)  # generate N random indices
Space_Position[random_indices]  # get N samples with replacement

or without replacement:

Space_Position = np.array(Space_Position).reshape(-1, 2)  # make it 2D
random_indices = np.arange(0, Space_Position.shape[0])    # array of all indices
np.random.shuffle(random_indices)                         # shuffle the array
Space_Position[random_indices[:N]]  # get N samples without replacement


问:
phpmyadmin import error of memory
I am facing below error message while I am trying to import a large file using phpmyadmin. What is the solution in this regard ?? Thanks

答: Try set upload_max_filesize, post_max_size , max_file_uploads and memory_limit to -1 in php.ini  and then restart your Apache server. If it did not work, try to set the mentioned parameters to -1 right on top of your codes.</p>

Title: phpmyadmin import error of memory


问:
SQL Find Values Between *
I have a strange request, I thikn.
I have a system which I need to retrieve data from - its SQL based. The field in question has a multitude of data in it, but I specifically only need 1 or 2 values.

In the example below, the field contains values contained in "*". I need to retrieve the value for AQISPremIdProcessType_Hidden which is "N2725/D". Is this possible through a SQL script?

```<code>AQISEntityIds_Hidden=CN0001MB*AQISPremIdProcessType_Hidden=N2725/D*CPQuestionGenDate_Hidden=20/01/2017
</code>```

答:
I think that there may be a problem in your database design. Of course, I may be wrong but would there be a way to design a table with the following columns?

```<code>AQISEntityIds_Hidden | AQISPremIdProcessType_Hidden | CPQuestionGenDate_Hidden
</code>```

How do you insert the values into your database? Do you use PHP?

Your string is twice delimited type with '*' and '=' as delimiters. So, if you use PHP, you could explode the string to get the desired values and store them in seperate fields in a table. That way, you could handle the values much easier (and this is the purpose of a database).

Again, I am sorry if the above is not possible in your project. I write this answer, just in case you  could fix some things in your whole code approach and database design to make things work easier.

Title: SQL Find Values Between *

Body:
I have a strange request, I thikn.
I have a system which I need to retrieve data from - its SQL based. The field in question has a multitude of data in it, but I specifically only need 1 or 2 values.

In the example below, the field contains values contained in "*". I need to retrieve the value for AQISPremIdProcessType_Hidden which is "N2725/D". Is this possible through a SQL script?

AQISEntityIds_Hidden=CN0001MB*AQISPremIdProcessType_Hidden=N2725/D*CPQuestionGenDate_Hidden=20/01/2017

Body:
I think that there may be a problem in your database design. Of course, I may be wrong but would there be a way to design a table with the following columns?

AQISEntityIds_Hidden | AQISPremIdProcessType_Hidden | CPQuestionGenDate_Hidden

How do you insert the values into your database? Do you use PHP?

Your string is twice delimited type with '*' and '=' as delimiters. So, if you use PHP, you could explode the string to get the desired values and store them in seperate fields in a table. That way, you could handle the values much easier (and this is the purpose of a database).

Again, I am sorry if the above is not possible in your project. I write this answer, just in case you  could fix some things in your whole code approach and database design to make things work easier.


问:
Can Boost ASIO be used to build low-latency applications?
Can Boost ASIO be used to build low-latency applications, such as HFT (High Frequency Trading)?

So Boost.ASIO uses platform-specific optimal demultiplexing mechanism: IOCP, epoll, kqueue, poll_set, /dev/poll

Also can be used Ethernet-Adapter with TOE (TCP/IP offload engine) and OpenOnload (kernel-bypass BSD sockets).

But can Low-latency application be built by using Boost.ASIO + TOE + OpenOnload?

答:
I evaluated Boost Asio for use in high frequency trading a few years ago.  To the best of my knowledge the basics are still the same today.  Here are some reasons why I decided not to use it:

Asio relies on bind() style callbacks.  There is some overhead here.

It is not obvious how to arrange certain low-level operations to occur at the right moment or in the right way.

There is rather a lot of complex code in an area which is important to optimize.  It is harder to optimize complex, general code for specific use cases.  Thinking that you will not need to look under the covers would be a mistake.

There is little to no need for portability in HFT applications.  In particular, having "automatic" selection of a multiplexing mechanism is contrary to the mission, because each mechanism must be tested and optimized separately--this creates more work rather than reducing it.

If a third-party library is to be used, others such as libev, libevent, and libuv are more battle-hardened and avoid some of these downsides.

Related: C++ Socket Server - Unable to saturate CPU


问:
jQuery .each to target only first h4 to add to aria-label
The following add all the h4 text to the aria-label (thanks Tyler). I want to only add the h4 text relevant to each label.

```<code>var prodname = $(".checkbox").closest("tr").find("td.product-shortdesc h4:first").text();
        $("td.select .checkbox").attr("aria-label", prodname);
</code>```

Currently adds

```<code><input class="checkbox" type="checkbox" style="" aria-label="name_1 name_2 name_3">
</code>```

Thanks for any help

答:
Use the each method
https://api.jquery.com/each/</p>

```<code>$(".checkbox").each(function(){
  var prodname = $(this).closest("tr").find("td.product-shortdesc h4:first").text();
  $(this).attr("aria-label", prodname);
});
</code>```

Body:
The following add all the h4 text to the aria-label (thanks Tyler). I want to only add the h4 text relevant to each label.

var prodname = $(".checkbox").closest("tr").find("td.product-shortdesc h4:first").text();
        $("td.select .checkbox").attr("aria-label", prodname);

Currently adds

<input class="checkbox" type="checkbox" style="" aria-label="name_1 name_2 name_3">

Thanks for any help

Body:
Use the each method
https://api.jquery.com/each/

$(".checkbox").each(function(){
  var prodname = $(this).closest("tr").find("td.product-shortdesc h4:first").text();
  $(this).attr("aria-label", prodname);
});


问:
ListView displays nothing
I would like to send selected item from listview to another listview with sharedprefences. I can save item but cannot see this item another listview. Activity class

```<code>TextView textUrun = (TextView) view.findViewById(R.id.textUrun);
            TextView textFiyat = (TextView) view.findViewById(R.id.textFiyat);
            String yemek = textUrun.getText().toString();
            String fiyat = textFiyat.getText().toString();
            DataProvider dataProvider = new DataProvider(yemek,fiyat);
            list.add(dataProvider);
            String jsonurun = gson.toJson(list);
            SharedPreferences sharedPreferences = getSharedPreferences("yemekbilgi", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("yemek",jsonurun);
            editor.apply();
            Toast.makeText(getApplicationContext(),"Listeye Kaydedildi",Toast.LENGTH_LONG).show();
</code>```

This is list class which should display items.Listele1

```<code>SharedPreferences sharedPreferences = getSharedPreferences("urun1", Context.MODE_PRIVATE);
    List<DataProvider> list;
    String jsonurun = sharedPreferences.getString("liste1", "");
    Gson gson = new Gson();
    DataProvider[] providers = gson.fromJson(jsonurun, DataProvider[].class);
    list = Arrays.asList(providers);
    listDataAdapter = new ListDataAdapter(getApplicationContext(), list);
    listView = (ListView) findViewById(R.id.liste1);
    listView.setAdapter(listDataAdapter);
</code>```

Finally,this is Adapter Class

```<code>public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();

public ListDataAdapter(@NonNull Context context,List<DataProvider> list) {
    super(context, R.layout.be_layout, list);
}

static class LayoutHandler{
    TextView ad,fiyat;
}

@Override
public void add(@Nullable Object object) {
    super.add(object);
    list.add(object);
}

@Override
public int getCount() {
    return list.size();
}

@Nullable
@Override
public Object getItem(int position) {
    return list.get(position);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View view = convertView;
    LayoutHandler layoutHandler;
    if (view == null){
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.child_layout,parent,false);
        layoutHandler = new LayoutHandler();
        layoutHandler.ad = (TextView) view.findViewById(R.id.textUrun);
        layoutHandler.fiyat = (TextView) view.findViewById(R.id.textFiyat);
        view.setTag(layoutHandler);
    }
    else
        layoutHandler = (LayoutHandler) view.getTag();
    DataProvider dataProvider = (DataProvider) this.getItem(position);
    layoutHandler.ad.setText(dataProvider.getAd());
    layoutHandler.fiyat.setText(dataProvider.getFiyat());
    return view;
}
</code>```

}

答:
```<code>    list = new ArrayList<DataProvider>();
    listView = (ListView) findViewById(R.id.liste1);
    listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.child_layout,list);
    gson = new Gson();

    SharedPreferences sharedPreferences = getSharedPreferences("yemekbilgi", Context.MODE_PRIVATE);
    String yemek = sharedPreferences.getString("yemek","");
    Type type = new TypeToken<List<DataProvider>>(){}.getType();
    list.addAll(gson.fromJson(yemek,type));
    listView.setAdapter(listDataAdapter);
    listDataAdapter.notitifyDataSetChanged();
</code>```

Title: ListView displays nothing

Body:
I would like to send selected item from listview to another listview with sharedprefences. I can save item but cannot see this item another listview. Activity class

TextView textUrun = (TextView) view.findViewById(R.id.textUrun);
            TextView textFiyat = (TextView) view.findViewById(R.id.textFiyat);
            String yemek = textUrun.getText().toString();
            String fiyat = textFiyat.getText().toString();
            DataProvider dataProvider = new DataProvider(yemek,fiyat);
            list.add(dataProvider);
            String jsonurun = gson.toJson(list);
            SharedPreferences sharedPreferences = getSharedPreferences("yemekbilgi", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("yemek",jsonurun);
            editor.apply();
            Toast.makeText(getApplicationContext(),"Listeye Kaydedildi",Toast.LENGTH_LONG).show();

This is list class which should display items.Listele1

SharedPreferences sharedPreferences = getSharedPreferences("urun1", Context.MODE_PRIVATE);
    List<DataProvider> list;
    String jsonurun = sharedPreferences.getString("liste1", "");
    Gson gson = new Gson();
    DataProvider[] providers = gson.fromJson(jsonurun, DataProvider[].class);
    list = Arrays.asList(providers);
    listDataAdapter = new ListDataAdapter(getApplicationContext(), list);
    listView = (ListView) findViewById(R.id.liste1);
    listView.setAdapter(listDataAdapter);

Finally,this is Adapter Class

public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();

public ListDataAdapter(@NonNull Context context,List<DataProvider> list) {
    super(context, R.layout.be_layout, list);
}

static class LayoutHandler{
    TextView ad,fiyat;
}

@Override
public void add(@Nullable Object object) {
    super.add(object);
    list.add(object);
}

@Override
public int getCount() {
    return list.size();
}

@Nullable
@Override
public Object getItem(int position) {
    return list.get(position);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View view = convertView;
    LayoutHandler layoutHandler;
    if (view == null){
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.child_layout,parent,false);
        layoutHandler = new LayoutHandler();
        layoutHandler.ad = (TextView) view.findViewById(R.id.textUrun);
        layoutHandler.fiyat = (TextView) view.findViewById(R.id.textFiyat);
        view.setTag(layoutHandler);
    }
    else
        layoutHandler = (LayoutHandler) view.getTag();
    DataProvider dataProvider = (DataProvider) this.getItem(position);
    layoutHandler.ad.setText(dataProvider.getAd());
    layoutHandler.fiyat.setText(dataProvider.getFiyat());
    return view;
}

}


问:
Regex to match not start of line
I have the following XML tag

```<code><list message="2 < 3">
</code>```

I want to replace the < in the text with <

Need a regex to match < if it doesn't appear at the start of line.

答:
@duncan's method works fine if you just want to replacing, but it doesn't match the <.
and all the lookbehind wont work if you a using javascript. because javascript doesn't support lookbehind, unless you turn on the --harmony flag in nodejs or experimental javascript features in chrome.
But lookahead will work here, which is:

/(?!^)</

will match the < which is not at the begining of a line.
and the replacing will be:

'<list message="2 < 3">'.replace(/(?!^)</, '<')

Title: Regex to match not start of line

Body:
I have the following XML tag

<list message="2 < 3">

I want to replace the < in the text with <

Need a regex to match < if it doesn't appear at the start of line.

Body:
@duncan's method works fine if you just want to replacing, but it doesn't match the <.
and all the lookbehind wont work if you a using javascript. because javascript doesn't support lookbehind, unless you turn on the --harmony flag in nodejs or experimental javascript features in chrome.
But lookahead will work here, which is:

/(?!^)</

will match the < which is not at the begining of a line.
and the replacing will be:

'<list message="2 < 3">'.replace(/(?!^)</, '&lt;')


问:
Silverstripe CMS gives File size zero error
I have designed a page that has upload attachments ... one image and another PDF.
The data is created in the database, however, when trying to upload a file of either type I get a server error "File Size is zero bytes".
A search of this forum yielded entries that indicate it is a permission issue of site assets folder or assets/Uploads folder. I have checked both and the permissions are correct.
The search on other platforms seems to indicate file size issues are from the PHP5.6 php.ini file settings. Both are correct and set to a value well above the 8Mb default.
The Apache2 log looks like:

```<code>[Tue Jun 06 15:11:57.167558 2017] [:error] [pid 26971] [client 192.168.1.73:50192] PHP Warning:  mkdir(): Permission denied in /var/www/html/ss/framework/filesystem/Filesystem.php on line 53, referer: http://192.168.1.70/ss/index.php/admin/pages/edit/show/23
[Tue Jun 06 15:11:57.170810 2017] [:error] [pid 26971] [client 192.168.1.73:50192] PHP Warning:  copy(/var/www/html/ss/assets/Uploads/news-attachments/the-satern-ring.pdf): failed to open stream: Permission denied in /var/www/html/ss/framework/filesystem/Upload.php on line 207, referer: http://192.168.1.70/ss/index.php/admin/pages/edit/show/23
</code>```

This code also seems to indicate a permission issue. The folders all have the owner as root group as root and drw-rw----, files can be uploaded manually but not through the CMS.

So where do I look now?

Environment:
SS v3.6.0 theme bootstrap
OS Linux Mint 18.1
Apache 2.4 PHP 5.6

答:
This can occur when framework does not have permission to write files to the server. If this is the case, when we upload images through the CMS the file can not be written to assets and the CMS returns a  "File size zero error". The website also cannot combine files (such as JavaScript and CSS files) and cannot create new resampled images.

To help investigate this problem we can run the SilverStripe install wizard. The install wizard will notify us of issues preventing SilverStripe from running correctly.

To run the install wizard we visit http://www.example.com/install.php

The install.php is usually deleted after the site is installed, so if it is missing we will need to replace it. We can download the file from github. Here is the install.php file for SilverStripe 3.6: https://github.com/silverstripe/silverstripe-installer/blob/3.6/install.php

Once downloaded we upload this to the root directory of our webserver. Once this is done we can visit the install.php URL.

Here is a screenshot showing an example of the file permission issue warnings that the install wizard outputs:

What we want to do now is fix up all the warnings that the install wizard is reporting.

If this is a shared hosting environment we might not have the ability to fix these issues ourselves. In this case we should be able to send the install.php link to hosting support asking them fix the issues.

Once all the issues are fixed the site should work correctly. Make sure to delete the install.php when we are done.

Body:
I have designed a page that has upload attachments ... one image and another PDF.
The data is created in the database, however, when trying to upload a file of either type I get a server error "File Size is zero bytes".
A search of this forum yielded entries that indicate it is a permission issue of site assets folder or assets/Uploads folder. I have checked both and the permissions are correct.
The search on other platforms seems to indicate file size issues are from the PHP5.6 php.ini file settings. Both are correct and set to a value well above the 8Mb default.
The Apache2 log looks like:

[Tue Jun 06 15:11:57.167558 2017] [:error] [pid 26971] [client 192.168.1.73:50192] PHP Warning:  mkdir(): Permission denied in /var/www/html/ss/framework/filesystem/Filesystem.php on line 53, referer: http://192.168.1.70/ss/index.php/admin/pages/edit/show/23
[Tue Jun 06 15:11:57.170810 2017] [:error] [pid 26971] [client 192.168.1.73:50192] PHP Warning:  copy(/var/www/html/ss/assets/Uploads/news-attachments/the-satern-ring.pdf): failed to open stream: Permission denied in /var/www/html/ss/framework/filesystem/Upload.php on line 207, referer: http://192.168.1.70/ss/index.php/admin/pages/edit/show/23

This code also seems to indicate a permission issue. The folders all have the owner as root group as root and drw-rw----, files can be uploaded manually but not through the CMS.

So where do I look now?

Environment:
SS v3.6.0 theme bootstrap
OS Linux Mint 18.1
Apache 2.4 PHP 5.6


问:
Assembly Management in .NET, can we create our own "Assembly caches"?
Currently we have a group of projects deployed on a server running .NET.  Most of the projects reference Assemblies between them.  However since most developers for various reasons won't be given access to the GAC, we were wondering is there an easy way to create local "Assembly Caches" where groups of assemblies can be stored and used away from the Global Assembly Cache by projects with the know-how to access this cache?  We thought about uniting the projects under one big project and creating one big bin directory, but we were wondering if someone has tried something else.  Thanks!</p>

答: You could hook assembly resolve and implement custom behaviour to your hearts' content.</p>


问:
Java - Constructor with predifined value for inheritance
In order to make my question clearer, I have simplified names and values, since my code is pretty long and has a lot of variables and methods.
This problem equals my problem exactly:

I'm trying to create a class B that has two constructors, and inherits another class named A.

This is a simplified view of A:

```<code>public class A {

    int value1;
    List<SpecialItem> itemList;

    public SampleClass(int value1, List<SpecialItem> itemList) {
        this.value1 = value1;
        this.itemList = itemList;
    }
</code>```

Now, this is a simplified view of B:

```<code>public class B {

    public SampleClass(int value1, List<SpecialItem> itemList) {
        super(value1,itemList);
    }

    public SampleClass(int value1) {
        ???
    }
</code>```

Now, the problem is that I want to create a second constructor for B (where the ??? are) that doesn't receive a predefined itemList, but creates its own list. (the object SpecialItem is another class in the same package of the project).

Of course, I am having a problem with defining that constructor, since it does not apply for A's constructor.

My goals are:

Do not give the opportunity to initiate an instance of A without a
given itemList.

Have a constructor for B which doesn't give an itemList, but instead I create the one I want and "plant" it in B. For example - that list will have only one object of the type SpecialItem that is created by parameters I give to it.

One thing I though is to create a private/package visibility constructor for A without the itemList and then use that as "super", but I'm not sure whether it is the best solution.

Would love your ideas and feedback,

Thanks.

答:
It seems like you are needing to pass a default list to the constructor of the superclass. I would do it this way:

```<code>public class B {

    private static final List<SpecialItem> DEFAULT_ITEM_LIST =
        new ArrayList<>(Arrays.asList(new SpecialItem()));

    public SampleClass(int value1, List<SpecialItem> itemList) {
        super(value1, itemList);
    }

    public SampleClass(int value1) {
        this(value1, DEFAULT_ITEM_LIST);
    }
}
</code>```

The second constructor of B delegates to the first one, which in turn calls the constructor of the superclass A. Both the first constructor of B and the constructor of A require a List<SpecialItem> as its second argument. For this, we are using the DEFAULT_ITEM_LIST, which has been defined as a private static final member in B.

Note that I've used new ArrayList<>(Arrays.asList(...)) instead of just Arrays.asList(...). This is because the list returned by Arrays.asList cannot be structurally modified (elements cannot be added to or removed from it, though they can be replaced by others). The constructor of ArrayList that receives another List allows to create a common, mutable List out of another list.

Body:
In order to make my question clearer, I have simplified names and values, since my code is pretty long and has a lot of variables and methods.
This problem equals my problem exactly:

I'm trying to create a class B that has two constructors, and inherits another class named A.

This is a simplified view of A:

public class A {

    int value1;
    List<SpecialItem> itemList;

    public SampleClass(int value1, List<SpecialItem> itemList) {
        this.value1 = value1;
        this.itemList = itemList;
    }

Now, this is a simplified view of B:

public class B {

    public SampleClass(int value1, List<SpecialItem> itemList) {
        super(value1,itemList);
    }

    public SampleClass(int value1) {
        ???
    }

Now, the problem is that I want to create a second constructor for B (where the ??? are) that doesn't receive a predefined itemList, but creates its own list. (the object SpecialItem is another class in the same package of the project).

Of course, I am having a problem with defining that constructor, since it does not apply for A's constructor.

My goals are:

Do not give the opportunity to initiate an instance of A without a
given itemList.

Have a constructor for B which doesn't give an itemList, but instead I create the one I want and "plant" it in B. For example - that list will have only one object of the type SpecialItem that is created by parameters I give to it.

One thing I though is to create a private/package visibility constructor for A without the itemList and then use that as "super", but I'm not sure whether it is the best solution.

Would love your ideas and feedback,

Thanks.

Body:
It seems like you are needing to pass a default list to the constructor of the superclass. I would do it this way:

public class B {

    private static final List<SpecialItem> DEFAULT_ITEM_LIST =
        new ArrayList<>(Arrays.asList(new SpecialItem()));

    public SampleClass(int value1, List<SpecialItem> itemList) {
        super(value1, itemList);
    }

    public SampleClass(int value1) {
        this(value1, DEFAULT_ITEM_LIST);
    }
}

The second constructor of B delegates to the first one, which in turn calls the constructor of the superclass A. Both the first constructor of B and the constructor of A require a List<SpecialItem> as its second argument. For this, we are using the DEFAULT_ITEM_LIST, which has been defined as a private static final member in B.

Note that I've used new ArrayList<>(Arrays.asList(...)) instead of just Arrays.asList(...). This is because the list returned by Arrays.asList cannot be structurally modified (elements cannot be added to or removed from it, though they can be replaced by others). The constructor of ArrayList that receives another List allows to create a common, mutable List out of another list.


问:
Regular Expressions - Select the Second Match
I have a txt file with  and  between words that I would like to remove using Editpad

For example, I'd like to keep when it's like this:

```<code><i>Phrases and words.</i>
</code>```

And I'd like to remove the  and  tags inside the phrase, when it's like this:

```<code><i>Phrases</i>and<i> words.</i>
<i>Phrases</i>and <i>words.</i>
</code>```

I was trying to do that using regex, but I couldn't do it.

As the tag is followed by space or a word character I could find when the line has the double tag with

```<code>/ <i>|<\/i> /
</code>```

but this way I can't just press replace for nothing, I have to edit line by line I search.

There's anyway to accomplish that?

* Edited *

Another example of lines found on the subtitle text

```<code><i>- find me on the chamber.</i>
- What? <i>Go. Go, go, go!</i>
</code>```

答:
Rule number one: you can't parse html with regex.

That being said, if you know each line follows a certain pattern, you can usually hack something together to work. ;)

If I've understood correctly, it looks like you can simply remove all  and  that aren't either at the beginning or end of the lines. In that case, one method you could try is the following regex:

```<code>(?<=.)\<\/?i\>(?=.)
</code>```

This will match the tags, with a lookahead and behind to make sure  that we aren't at the end/start of a line (by checking if another character exists in front/behind. (Note that typically matched characters in a lookahead/behind won't be replaced when you search/replace.)

Disclaimer: this works on regex101, but notepad++ may have some differences to the pcre regex style.

update to work with Editpad

EDIT: since this question is actually wanting to know how to do this in Editpad, below is a modified alternative:

Try searching for the regex: (.)\<\/?i\>(.). This will match (and capture) exactly one character before and after the  tags.

When replacing, use backreferences to replace the entire match with the two captured characters - a replacement string of \1\2 should work.

Body:
I have a txt file with  and  between words that I would like to remove using Editpad

For example, I'd like to keep when it's like this:

Phrases and words.

And I'd like to remove the  and  tags inside the phrase, when it's like this:

Phrasesand words.
Phrasesand words.

I was trying to do that using regex, but I couldn't do it.

As the tag is followed by space or a word character I could find when the line has the double tag with

/ |<\/i> /

but this way I can't just press replace for nothing, I have to edit line by line I search.

There's anyway to accomplish that?

* Edited *

Another example of lines found on the subtitle text

- find me on the chamber.
- What? Go. Go, go, go!

Body:
Rule number one: you can't parse html with regex.

That being said, if you know each line follows a certain pattern, you can usually hack something together to work. ;)

If I've understood correctly, it looks like you can simply remove all <i> and </i> that aren't either at the beginning or end of the lines. In that case, one method you could try is the following regex:

(?<=.)\<\/?i\>(?=.)

This will match the tags, with a lookahead and behind to make sure  that we aren't at the end/start of a line (by checking if another character exists in front/behind. (Note that typically matched characters in a lookahead/behind won't be replaced when you search/replace.)

Disclaimer: this works on regex101, but notepad++ may have some differences to the pcre regex style.

update to work with Editpad

EDIT: since this question is actually wanting to know how to do this in Editpad, below is a modified alternative:

Try searching for the regex: (.)\<\/?i\>(.). This will match (and capture) exactly one character before and after the <i> tags.

When replacing, use backreferences to replace the entire match with the two captured characters - a replacement string of \1\2 should work.


问:
What rules do I need to enforce each method parameter on a new line with CheckStyle and Closing parenthesis and Opening method bracket on a new line
I've been working in a new package that has an unusual coding style and no way to enforce it. For example:

```<code>public void doSomething(
        String foo,
        Integer bar
) {
    // do stuff
}
</code>```

and

```<code>public void doSomething(
) {
    // do stuff
}
</code>```

I've looked at all the CheckStyle rules here http://checkstyle.sourceforge.net/checks.html and nothing really pops out as providing that capability

I'm trying to enforce style rules like:

Parameters start on line following method name

One parameter per line

Closing parenthesis for parameters and opening bracket for method body
are on the same line

Is anyone aware of a set of rules that would allow me to enforce this or have an idea on how to implement a way to enforce this style?

答:
Parameters start on line following method name

  One parameter per line

  Closing parenthesis for parameters and opening bracket for method body are on the same line

There is no check in Checkstyle that will validate and enforce what you want.

how to implement a way to enforce this style

The best way is to create your own check in a 3rd party jar for Checkstyle. Most of your requirements have to do with 2 tokens not appearing on the same line So, all you need to do is find the tokens you are interested in and check their line position relative to each other and produce a violation when warranted.

I recommend reading the following:

http://checkstyle.sourceforge.net/writingchecks.html

http://checkstyle.sourceforge.net/cmdline.html#Usage_by_Classpath_update

If you are successful with your check(s), you might want to consider posting them at https://github.com/sevntu-checkstyle/sevntu.checkstyle .

Body:
I've been working in a new package that has an unusual coding style and no way to enforce it. For example:

public void doSomething(
        String foo,
        Integer bar
) {
    // do stuff
}

and

public void doSomething(
) {
    // do stuff
}

I've looked at all the CheckStyle rules here http://checkstyle.sourceforge.net/checks.html and nothing really pops out as providing that capability

I'm trying to enforce style rules like:

Parameters start on line following method name

One parameter per line

Closing parenthesis for parameters and opening bracket for method body
are on the same line

Is anyone aware of a set of rules that would allow me to enforce this or have an idea on how to implement a way to enforce this style?


问:
With SQL Server how to get the most recent date while summing on amount and the sum of the amount is greater than 0?
I have a transaction table:

```<code>CREATE TABLE [dbo].[Trans](
[ID] [char](6) NOT NULL,
[PersonID] [char](6) NULL,
[TransCode] [char](2) NULL,
[TransDesc] [char](45) NULL,
[TransDate] [datetime] NULL,
[TransAmount] [numeric](18, 2) NULL)
</code>```

What I want is the date and amount of the most recent payment made by each person.  Payments are defined by the TransCode (see the WHERE clause below).

There can be multiple transactions on any given day, so I want the sum of transactions on the most recent day.  Also there can be "reversal" transactions that could make the sum of the transactions on the most recent day be 0 (zero) -- I don't want these to be in the results (hence the "HAVING   (SUM(TransAmount) > 0)" below).

Here is my most recent attempt, that is not working, but I don't know why!

```<code>SELECT  PersonID, MAX(TransDate) AS LastPaymentDate, TotalAmount
FROM    (SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS TotalAmount
GROUP BY PersonID, TotalAmount
ORDER BY PersonID
</code>```

When I run the inner query I get what expect, a list of amounts summed by date, for each person.  The outer query though, for some reason, is returning multiple rows for each person.  It should only return one row for each person :-(

Can someone one tell me what I am doing wrong?

Please let me know if there is any additional information you may need to understand the problem better.

Thank you in advance for any help you can provide,

Ben

答:
I believe this will work nice (but I didn't test it.)

```<code>WITH PersonDateSum AS
(
  SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate
)
SELECT PersonID, LastPaymentDate, TotalAmount
FROM PersonDateSum
WHERE ROW_NUMBER() OVER  (PARTITION BY PersonID, LastPaymentDate ORDER BY PersonID, LastPaymentDate DESC) = 1
ORDER BY PersonID
</code>```

If you are having speed issues I suggest you put your trans code select items in a table and join on it, it will be faster than using the IN statement.

Body:
I have a transaction table:

CREATE TABLE [dbo].[Trans](
[ID] [char](6) NOT NULL,
[PersonID] [char](6) NULL,
[TransCode] [char](2) NULL,
[TransDesc] [char](45) NULL,
[TransDate] [datetime] NULL,
[TransAmount] [numeric](18, 2) NULL)

What I want is the date and amount of the most recent payment made by each person.  Payments are defined by the TransCode (see the WHERE clause below).

There can be multiple transactions on any given day, so I want the sum of transactions on the most recent day.  Also there can be "reversal" transactions that could make the sum of the transactions on the most recent day be 0 (zero) -- I don't want these to be in the results (hence the "HAVING   (SUM(TransAmount) > 0)" below).

Here is my most recent attempt, that is not working, but I don't know why!

SELECT  PersonID, MAX(TransDate) AS LastPaymentDate, TotalAmount
FROM    (SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS TotalAmount
GROUP BY PersonID, TotalAmount
ORDER BY PersonID

When I run the inner query I get what expect, a list of amounts summed by date, for each person.  The outer query though, for some reason, is returning multiple rows for each person.  It should only return one row for each person :-(

Can someone one tell me what I am doing wrong?

Please let me know if there is any additional information you may need to understand the problem better.

Thank you in advance for any help you can provide,

Ben

Body:
I believe this will work nice (but I didn't test it.)

WITH PersonDateSum AS
(
  SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate
)
SELECT PersonID, LastPaymentDate, TotalAmount
FROM PersonDateSum
WHERE ROW_NUMBER() OVER  (PARTITION BY PersonID, LastPaymentDate ORDER BY PersonID, LastPaymentDate DESC) = 1
ORDER BY PersonID

If you are having speed issues I suggest you put your trans code select items in a table and join on it, it will be faster than using the IN statement.


问:
Given list of births and deaths, determine years where most people were alive
I have a dictionary of people with their respective births and deaths.

I want to figure out which year had the most people alive.

My currently algorithm appends every year lived by every person into an array and then return the highest occurence. I have a hunch that there is a much neater way to achieve this.

Here is my makeshift brute implementation:

```<code>var people = [ "Nicolas": (birth: 1900, death: 1975),
                "Vladimir": (birth: 1970, death: 2000),
                "Julius": (birth: 1950, death: 1985),
                "Alexander": (birth: 1900, death: 1920),
                "Obama": (birth: 1910, death: 1920),
                "George": (birth: 1915, death: 1920),
                "Benjamin": (birth:  1919, death: 1925)]

var yearsArray = [Int]()
var yearOccurrences: [Int:Int] = [:]

for life in people.values {
    var birth = life.birth
    var death = life.death

    for year in birth..<death {
        yearsArray.append(year)
    }
}
for year in yearsArray {
    yearOccurrences[year] = (yearOccurrences[year] ?? 0) + 1
}

(yearOccurrences as! NSDictionary).allKeysForObject(yearOccurrences.values.maxElement()!)
</code>```

Expected results are 1919 and 1920.

Looking for a more concise and elegant solution in terms of either code or process

答:
You can simplify your solution by doing the yearOccurences and maximum in the first pass through:

```<code>var people = [ "Nicolas": (birth: 1900, death: 1975),
               "Vladimir": (birth: 1970, death: 2000),
               "Julius": (birth: 1950, death: 1985),
               "Alexander": (birth: 1900, death: 1920),
               "Obama": (birth: 1910, death: 1920),
               "George": (birth: 1915, death: 1920),
               "Benjamin": (birth:  1919, death: 1925),
               "Donald": (birth:  1918, death: 1918)]

var yearsArray: [Int] = []
var yearOccurrences: [Int:Int] = [:]
var maxPop = 0

for person in people.values {
    let birth = person.birth
    let death = person.death

    for year in birth...death {
        let count = (yearOccurrences[year] ?? 0) + 1
        yearOccurrences[year] = count

        if count > maxPop {
            maxPop = count
            // Clear the years
            yearsArray = [year]
        } else if count == maxPop {
            // Append the year
            yearsArray.append(year)
        }
    }
}

print ("Max population \(maxPop) in year\(yearsArray.count > 0 ? "s" : ""): \(yearsArray)")
</code>```

Max population 5 in years: [1918, 1919, 1920]

Also note- the loop from birth...death is inclusive. A person is assumed to be alive the year they died. It also solves the problem of a person dying the same year they were born (e.g. Donald above).

This has complexity of O(N*Y) where N is number of people and Y is the max lifespan of a person. Assuming Y is finite, we can reduce this to just O(N).

Body:
I have a dictionary of people with their respective births and deaths.

I want to figure out which year had the most people alive.

My currently algorithm appends every year lived by every person into an array and then return the highest occurence. I have a hunch that there is a much neater way to achieve this.

Here is my makeshift brute implementation:

var people = [ "Nicolas": (birth: 1900, death: 1975),
                "Vladimir": (birth: 1970, death: 2000),
                "Julius": (birth: 1950, death: 1985),
                "Alexander": (birth: 1900, death: 1920),
                "Obama": (birth: 1910, death: 1920),
                "George": (birth: 1915, death: 1920),
                "Benjamin": (birth:  1919, death: 1925)]

var yearsArray = [Int]()
var yearOccurrences: [Int:Int] = [:]

for life in people.values {
    var birth = life.birth
    var death = life.death

    for year in birth..<death {
        yearsArray.append(year)
    }
}
for year in yearsArray {
    yearOccurrences[year] = (yearOccurrences[year] ?? 0) + 1
}

(yearOccurrences as! NSDictionary).allKeysForObject(yearOccurrences.values.maxElement()!)

Expected results are 1919 and 1920.

Looking for a more concise and elegant solution in terms of either code or process

Body:
You can simplify your solution by doing the yearOccurences and maximum in the first pass through:

var people = [ "Nicolas": (birth: 1900, death: 1975),
               "Vladimir": (birth: 1970, death: 2000),
               "Julius": (birth: 1950, death: 1985),
               "Alexander": (birth: 1900, death: 1920),
               "Obama": (birth: 1910, death: 1920),
               "George": (birth: 1915, death: 1920),
               "Benjamin": (birth:  1919, death: 1925),
               "Donald": (birth:  1918, death: 1918)]

var yearsArray: [Int] = []
var yearOccurrences: [Int:Int] = [:]
var maxPop = 0

for person in people.values {
    let birth = person.birth
    let death = person.death

    for year in birth...death {
        let count = (yearOccurrences[year] ?? 0) + 1
        yearOccurrences[year] = count

        if count > maxPop {
            maxPop = count
            // Clear the years
            yearsArray = [year]
        } else if count == maxPop {
            // Append the year
            yearsArray.append(year)
        }
    }
}

print ("Max population \(maxPop) in year\(yearsArray.count > 0 ? "s" : ""): \(yearsArray)")

Max population 5 in years: [1918, 1919, 1920]

Also note- the loop from birth...death is inclusive. A person is assumed to be alive the year they died. It also solves the problem of a person dying the same year they were born (e.g. Donald above).

This has complexity of O(N*Y) where N is number of people and Y is the max lifespan of a person. Assuming Y is finite, we can reduce this to just O(N).