问:
On MSVC why does the warning "unreferenced formal parameter" does not appear for std::string?
I have a function with three unused arguments:

```<code>#include <string>

void Test(int b, std::string a, int c)
{
}

int main()
{
    return 0;
}
</code>```

When compiling it on level 4 in Visual Studio 2017,  I get warnings for b and c:

```<code>1>consoleapplication2.cpp(8): warning C4100: 'c': unreferenced formal parameter
1>consoleapplication2.cpp(8): warning C4100: 'b': unreferenced formal parameter
</code>```

Why don't I get the same warning for std::string a?

答:
It is an implementation-dependent warning.

I have tested your codes on gcc and clang, both warn a, b, and c:

clang:

```<code>prog.cc:5:15: warning: unused parameter 'b' [-Wunused-parameter]
void Test(int b, std::string a, int c)
              ^
prog.cc:5:30: warning: unused parameter 'a' [-Wunused-parameter]
void Test(int b, std::string a, int c)
                             ^
prog.cc:5:37: warning: unused parameter 'c' [-Wunused-parameter]

void Test(int b, std::string a, int c)
                                    ^
3 warnings generated.
</code>```

gcc:

```<code>prog.cc: In function 'void Test(int, std::__cxx11::string, int)':
prog.cc:5:15: warning: unused parameter 'b' [-Wunused-parameter]
void Test(int b, std::string a, int c)
          ~~~~^
prog.cc:5:30: warning: unused parameter 'a' [-Wunused-parameter]
void Test(int b, std::string a, int c)
                 ~~~~~~~~~~~~^
prog.cc:5:37: warning: unused parameter 'c' [-Wunused-parameter]
void Test(int b, std::string a, int c)
                        ~~~~~~~~~~~~^
</code>```

So, maybe it is just msvc's negligence.

Body:
I have a function with three unused arguments:

#include <string>

void Test(int b, std::string a, int c)
{
}

int main()
{
    return 0;
}

When compiling it on level 4 in Visual Studio 2017,  I get warnings for b and c:

1>consoleapplication2.cpp(8): warning C4100: 'c': unreferenced formal parameter
1>consoleapplication2.cpp(8): warning C4100: 'b': unreferenced formal parameter

Why don't I get the same warning for std::string a?

Body:
It is an implementation-dependent warning.

I have tested your codes on gcc and clang, both warn a, b, and c:

clang:

prog.cc:5:15: warning: unused parameter 'b' [-Wunused-parameter]
void Test(int b, std::string a, int c)
              ^
prog.cc:5:30: warning: unused parameter 'a' [-Wunused-parameter]
void Test(int b, std::string a, int c)
                             ^
prog.cc:5:37: warning: unused parameter 'c' [-Wunused-parameter]

void Test(int b, std::string a, int c)
                                    ^
3 warnings generated.

gcc:

prog.cc: In function 'void Test(int, std::__cxx11::string, int)':
prog.cc:5:15: warning: unused parameter 'b' [-Wunused-parameter]
void Test(int b, std::string a, int c)
          ~~~~^
prog.cc:5:30: warning: unused parameter 'a' [-Wunused-parameter]
void Test(int b, std::string a, int c)
                 ~~~~~~~~~~~~^
prog.cc:5:37: warning: unused parameter 'c' [-Wunused-parameter]
void Test(int b, std::string a, int c)
                        ~~~~~~~~~~~~^

So, maybe it is just msvc's negligence.


来源: stackexchange

问:
WinForms WebBrowser - FireBug Inspect Element-like highlighting
Basically, I need to load any HTML document in WebBrowser control and allow users to visually select one or more HTML DOM elements (in order to get their XPaths, but that's another story).

Hovering an element will highlight it with color A, moving mouse out will restore it's visual state.

Clicking an element will highlight it with color B, clicking again previously clicked element will restore it's visual state.

To summarize, it should behave like the FireBug Inspect Element feature, or like the Dapp Factory Select Content feature.

A naive approach would be to use HtmlElement.Style property like in the example below, but obviously I can't because the element could already have the border style set in the same manner in which case it should not be removed on MouseLeave:

```<code>void Document_MouseOver(object sender, HtmlElementEventArgs e)
{
    // what if e.FromElement.Style already contains "border: solid 1px Red;" ?
    e.FromElement.Style = "border: solid 1px Red; " + e.FromElement.Style;
    [...]
}
</code>```

Possibly I could achieve this by setting/unsetting a custom CSS class (like one would do using JavaScript in the same case), but HtmlElement does not seem to expose such a property, and how would I inject CSS class definitions anyway?

Update: it is actually possible to set the CSS class with HtmlElement.SetAttribute("className"); to inject CSS classes, check for example C#: Best way to inject CSS into MSHTML instance?.

Any ideas on how to achieve this are welcome. Thank you.

答: Trying to paint does not work with WebBrowser,I think the FormElement.Style that you already use is the way to go.</p>

ContentLicense: CC BY-SA 2.5

Body:
Basically, I need to load any HTML document in WebBrowser control and allow users to visually select one or more HTML DOM elements (in order to get their XPaths, but that's another story).

Hovering an element will highlight it with color A, moving mouse out will restore it's visual state.

Clicking an element will highlight it with color B, clicking again previously clicked element will restore it's visual state.

To summarize, it should behave like the FireBug Inspect Element feature, or like the Dapp Factory Select Content feature.

A naive approach would be to use HtmlElement.Style property like in the example below, but obviously I can't because the element could already have the border style set in the same manner in which case it should not be removed on MouseLeave:

void Document_MouseOver(object sender, HtmlElementEventArgs e)
{
    // what if e.FromElement.Style already contains "border: solid 1px Red;" ?
    e.FromElement.Style = "border: solid 1px Red; " + e.FromElement.Style;
    [...]
}

Possibly I could achieve this by setting/unsetting a custom CSS class (like one would do using JavaScript in the same case), but HtmlElement does not seem to expose such a property, and how would I inject CSS class definitions anyway?

Update: it is actually possible to set the CSS class with HtmlElement.SetAttribute("className"); to inject CSS classes, check for example C#: Best way to inject CSS into MSHTML instance?.

Any ideas on how to achieve this are welcome. Thank you.


问:
create_Task(): The application called an interface that was marshalled for a different thread
I have a UWP UI that calls native code that takes a while to execute.  Upon completion, the UI needs updating.  This is my code:

```<code>auto runOpti = create_task([this] { runOptimation(); });
runOpti.then([this]{postOptimation(); });
</code>```

The postOptimation routine includes the line:

```<code>backwordCheckBox->IsChecked = params->backwards;
</code>```

Executing this like gives the error in the title.

How do I get the postOptimation to run in the UI thread?

Thanks

答:
Use the Invoke method of the Dispatcher property: backwordCheckBox->Dispatcher->Invoke.

It's been quiet a while since I did anything with .net and I don't recall right off how to create an Action from a lambda, but that's how you'd do this.

ContentLicense: CC BY-SA 3.0

Body:
I have a UWP UI that calls native code that takes a while to execute.  Upon completion, the UI needs updating.  This is my code:

auto runOpti = create_task([this] { runOptimation(); });
runOpti.then([this]{postOptimation(); });

The postOptimation routine includes the line:

backwordCheckBox->IsChecked = params->backwards;

Executing this like gives the error in the title.

How do I get the postOptimation to run in the UI thread?

Thanks


问:
How to add images to a wordpress theme when working on MAMP?
I am new to MAMP and I am developing a theme I designed. However I can't seem to get the images to render. I am using a clear theme I got from starkerstheme.com
When adding an image directly to the code I used:

```<code><img src="<?= $theme ?>/images/logo.png"/>
</code>```

But the image is not showing up, also I tried to add it to the media library and it's still not rendering.

答:
```<code><?php echo get_template_directory_uri(); ?>
</code>```

as suggested gets the PARENT theme, which is OK but if you've developed a child theme (as recommended by WordPress people) you need:

```<code><img src="<?php echo get_stylesheet_directory_uri(); ?>/img/Logo.png">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to MAMP and I am developing a theme I designed. However I can't seem to get the images to render. I am using a clear theme I got from starkerstheme.com
When adding an image directly to the code I used:

<img src="<?= $theme ?>/images/logo.png"/>

But the image is not showing up, also I tried to add it to the media library and it's still not rendering.

Body:
<?php echo get_template_directory_uri(); ?>

as suggested gets the PARENT theme, which is OK but if you've developed a child theme (as recommended by WordPress people) you need:

<img src="<?php echo get_stylesheet_directory_uri(); ?>/img/Logo.png">


问:
How to union two collections without overriding any value
I am trying to get the union of two collections without overriding any value:

First Collection:

```<code>Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"
   ]]}
</code>```

Second Collection

```<code>Collection {#246 ▼
  #items: array [▼
    0 => array [▼
  "status": "Reminder",
  "letterPaymentAmount": 4300,
  "BankAccountNo": "SEK",
  "Date": "2017-08-15T16:01:30",
  "DueDate": "2017-08-30T00:00:00",
  "ocr": "3000002406",
  "lastDatePayDay": "30",
  "lastDatePayMonth": "Aug",
  "Country": "Singapore",
  "Customer": "TickTack"
   ]]}
</code>```

I want to acomplish this:

```<code>Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"],
    1=> [
      "status": "Reminder",
      "letterPaymentAmount": 4300,
      "BankAccountNo": "SEK",
      "Date": "2017-08-15T16:01:30",
      "DueDate": "2017-08-30T00:00:00",
      "ocr": "3000002406",
      "lastDatePayDay": "30",
      "lastDatePayMonth": "Aug",
      "Country": "Singapore",
      "Customer": "TickTack"  ]]}
</code>```

I do not want to override any existing key or value just add them together.

I have tried union() but that overrides the existing keys and does not take keys that do not exist in first collection .

Any help would be much appreciated

答:
Have you used concat()? An example is the following:

```<code>    $col1 = collect([
        ['abc' => 1, 'dec' => 2],
        ['abc' => 1, 'dec' => 6]
    ]);
    $col2 = collect([
        ['abc' => 3, 'dec' => 4, 'acd' => 2],
        ['abc' => 1, 'dec' => 8, 'acd' => 6],
    ]);

    return $col1->concat($col2);
</code>```

Note: if you use this on a collection without nested array then you might get different result from this one.

Body:
I am trying to get the union of two collections without overriding any value:

First Collection:

Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"
   ]]}

Second Collection

Collection {#246 ▼
  #items: array [▼
    0 => array [▼
  "status": "Reminder",
  "letterPaymentAmount": 4300,
  "BankAccountNo": "SEK",
  "Date": "2017-08-15T16:01:30",
  "DueDate": "2017-08-30T00:00:00",
  "ocr": "3000002406",
  "lastDatePayDay": "30",
  "lastDatePayMonth": "Aug",
  "Country": "Singapore",
  "Customer": "TickTack"
   ]]}

I want to acomplish this:

Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"],
    1=> [
      "status": "Reminder",
      "letterPaymentAmount": 4300,
      "BankAccountNo": "SEK",
      "Date": "2017-08-15T16:01:30",
      "DueDate": "2017-08-30T00:00:00",
      "ocr": "3000002406",
      "lastDatePayDay": "30",
      "lastDatePayMonth": "Aug",
      "Country": "Singapore",
      "Customer": "TickTack"  ]]}

I do not want to override any existing key or value just add them together.

I have tried union() but that overrides the existing keys and does not take keys that do not exist in first collection .

Any help would be much appreciated

Body:
Have you used concat()? An example is the following:

    $col1 = collect([
        ['abc' => 1, 'dec' => 2],
        ['abc' => 1, 'dec' => 6]
    ]);
    $col2 = collect([
        ['abc' => 3, 'dec' => 4, 'acd' => 2],
        ['abc' => 1, 'dec' => 8, 'acd' => 6],
    ]);

    return $col1->concat($col2);

Note: if you use this on a collection without nested array then you might get different result from this one.


问:
Set array size equal to number of files in a folder
I'm trying to create a google script that counts the number of files in a folder, then assigns this number to a variable that can be used to define the size of an array.

ID folder

get files in folder

set counter = filecount

use counter to define array size

my attempt:

```<code>function setarraytofilecount() {
var dealspsfolderid = "ID goes here";
var dealspsfolder = DriveApp.getFolderById(dealspsfolderid);
var ssfiles = dealspsfolder.getFiles();

var count, file;

count = 0;

while (ssfiles.hasNext()) {
count++;
file = ssfiles.next();
}

var nesteddata = new Array(count);
</code>```

I'm expecting to create an array with a size equal to the number of files in the folder, but I don't believe this is what is happening.

The script runs, there is more after this I'm leaving out for simplicity. I think the problem may be that I cannot use the variable count in new Array(), is that correct?

Here is the whole script:

```<code>function autoUpdateFiles() {

// set the folder to pull files from
var dealspsfolderid = "removed";
var dealspsfolder = DriveApp.getFolderById(dealspsfolderid);
var ssfiles = dealspsfolder.getFiles();
var trackerurl = "removed";
var sstoupdate = SpreadsheetApp.openByUrl(trackerurl);

// set the sheet to update
var sheettoupdate = sstoupdate.getSheetByName('AutoTracker');

// indicates current deal row
var rowcounter = 0;

// get number of files in the folder which we can use to define array size
var count,file;//Define variables without assigning a value
count = 0;
while (ssfiles.hasNext()) {
 count++;
 file = ssfiles.next();
}

// nested array of row data arrays. i.e. each index is an array of a row
var nesteddata = new Array();
nesteddata.length = count;
for(i = 0; i < nesteddata.length; i++){
  nesteddata[i] = new Array(158);
}

// nested array of row data arrays. i.e. each index is an array of a row
var URLarray = new Array();
URLarray.length = count;
for(i = 0; i < URLarray.length; i++){
 URLarray[i] = new Array(1);
}

// iterate through each file
while (ssfiles.hasNext()) {

// pull the next file
var file = ssfiles.next();

// get the url
Logger.log(file.getUrl());

// activate the sheet
var spreadsheet = SpreadsheetApp.open(file);
var activesheet = spreadsheet.getSheets()[0].activate();

// pull values from the files
// ranges are ROW, COLUMN
var URL = file.getUrl();
var colC = activesheet.getRange(3, 3, 158 ,3).getValues();

// transition the vertical multidimensional array returned into flat array for a row
for(var i = 0; i < colC.length; i++){
   nesteddata[rowcounter][i]=colC[i][0];
  }

 for(var i = 0; i < URLarray.length; i++){
   URLarray[rowcounter]= [URL];
  }
rowcounter ++;
}

// write out to the sheet
sheettoupdate.getRange(2,1,nesteddata.length,1).setValues(URLarray);
sheettoupdate.getRange(2,2,nesteddata.length,158).setValues(nesteddata);
</code>```

答:
You can use the length property to set the number of elements in an array:

```<code>var nesteddata = new Array();

nesteddata.length = count;
Logger.log(nesteddata);
Logger.log(nesteddata.length);
</code>```

The array will look like this:

[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]

It will have the number of elements in it, with all the elements having a null value

Body:
I'm trying to create a google script that counts the number of files in a folder, then assigns this number to a variable that can be used to define the size of an array.

ID folder

get files in folder

set counter = filecount

use counter to define array size

my attempt:

function setarraytofilecount() {
var dealspsfolderid = "ID goes here";
var dealspsfolder = DriveApp.getFolderById(dealspsfolderid);
var ssfiles = dealspsfolder.getFiles();

var count, file;

count = 0;

while (ssfiles.hasNext()) {
count++;
file = ssfiles.next();
}

var nesteddata = new Array(count);

I'm expecting to create an array with a size equal to the number of files in the folder, but I don't believe this is what is happening.

The script runs, there is more after this I'm leaving out for simplicity. I think the problem may be that I cannot use the variable count in new Array(), is that correct?

Here is the whole script:

function autoUpdateFiles() {

// set the folder to pull files from
var dealspsfolderid = "removed";
var dealspsfolder = DriveApp.getFolderById(dealspsfolderid);
var ssfiles = dealspsfolder.getFiles();
var trackerurl = "removed";
var sstoupdate = SpreadsheetApp.openByUrl(trackerurl);

// set the sheet to update
var sheettoupdate = sstoupdate.getSheetByName('AutoTracker');

// indicates current deal row
var rowcounter = 0;

// get number of files in the folder which we can use to define array size
var count,file;//Define variables without assigning a value
count = 0;
while (ssfiles.hasNext()) {
 count++;
 file = ssfiles.next();
}

// nested array of row data arrays. i.e. each index is an array of a row
var nesteddata = new Array();
nesteddata.length = count;
for(i = 0; i < nesteddata.length; i++){
  nesteddata[i] = new Array(158);
}

// nested array of row data arrays. i.e. each index is an array of a row
var URLarray = new Array();
URLarray.length = count;
for(i = 0; i < URLarray.length; i++){
 URLarray[i] = new Array(1);
}

// iterate through each file
while (ssfiles.hasNext()) {

// pull the next file
var file = ssfiles.next();

// get the url
Logger.log(file.getUrl());

// activate the sheet
var spreadsheet = SpreadsheetApp.open(file);
var activesheet = spreadsheet.getSheets()[0].activate();

// pull values from the files
// ranges are ROW, COLUMN
var URL = file.getUrl();
var colC = activesheet.getRange(3, 3, 158 ,3).getValues();

// transition the vertical multidimensional array returned into flat array for a row
for(var i = 0; i < colC.length; i++){
   nesteddata[rowcounter][i]=colC[i][0];
  }

 for(var i = 0; i < URLarray.length; i++){
   URLarray[rowcounter]= [URL];
  }
rowcounter ++;
}

// write out to the sheet
sheettoupdate.getRange(2,1,nesteddata.length,1).setValues(URLarray);
sheettoupdate.getRange(2,2,nesteddata.length,158).setValues(nesteddata);

Body:
You can use the length property to set the number of elements in an array:

var nesteddata = new Array();

nesteddata.length = count;
Logger.log(nesteddata);
Logger.log(nesteddata.length);

The array will look like this:

[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]

It will have the number of elements in it, with all the elements having a null value


问:
Handle SIGTERM with the cluster module
Hi there where can i find the source code for signal handling when using the cluster module? I want to handle a SIGTERM so that i can "graceful" close the http server but as soon as the master process receives this signal the http server stops listening.

"Termination" handler (This function gets called when SIGTERM or SIGINT)

```<code>function handleTermination(httpServer?: http.Server) {
    if (Store.receive<symbol, boolean>(STORE_KEYS.isTerminating)) {
        return
    }

    Store.store<symbol, boolean>(STORE_KEYS.isTerminating, true)

    if (httpServer) {
        if (!httpServer.listening || isDevelopment) {
            closeAll()
            process.exit(0)
            return
        }

        setTimeout(() => {
            if (process.env.GRACEFUL_SHUTDOWN !== undefined) {
                gracefulCloseSockets()
            }

            httpServer.close(endProcess)
        }, 5000)
    } else {
        endProcess()
    }
}
</code>```

Example router handler

```<code>function timerHandler(_req: RequestObject, respond: ResponseHandler) {
    setTimeout(() => respond('ok'), 2000)
}
</code>```

答:
I've solved my problem. Here's the code which solved my problem.

master.js

```<code>function close(callback) {
  if (!cluster.isMaster) {
    return
  }

  const promiseArray = []
  const workerIds = Object.keys(cluster.workers)

  for (const workerId of workerIds) {
    const worker = cluster.workers[workerId]

    worker.send('shutdown')
    worker.disconnect()

    promiseArray.push(new Promise((resolve) => {
      let resolved = false

      worker.once('exit', () => (!resolved && resolve(), resolved = true))
      setTimeout(() => (!resolved && resolve(), worker.kill('SIGTERM'), resolved = true), 4000)
    }))
  }

  Promise.all(promiseArray).then(callback)
}
</code>```

worker.js

```<code>function terminateWorker(server) {
  if (server && server.listening) {
    Store.store(STORE_KEYS.isTerminating, true)
    gracefulCloseSockets()
    server.close(endProcess)
  } else {
    endProcess()
  }
}
</code>```

Explanation

When the master receives a "SIGTERM" he calls the close function (excerpt above)

The worker receives the "shutdown" message and calls the terminateWorker function (excerpt above). This function closes the http.Server and waits for all sockets to finish.

Title: Handle SIGTERM with the cluster module

Body:
Hi there where can i find the source code for signal handling when using the cluster module? I want to handle a SIGTERM so that i can "graceful" close the http server but as soon as the master process receives this signal the http server stops listening.

"Termination" handler (This function gets called when SIGTERM or SIGINT)

function handleTermination(httpServer?: http.Server) {
    if (Store.receive<symbol, boolean>(STORE_KEYS.isTerminating)) {
        return
    }

    Store.store<symbol, boolean>(STORE_KEYS.isTerminating, true)

    if (httpServer) {
        if (!httpServer.listening || isDevelopment) {
            closeAll()
            process.exit(0)
            return
        }

        setTimeout(() => {
            if (process.env.GRACEFUL_SHUTDOWN !== undefined) {
                gracefulCloseSockets()
            }

            httpServer.close(endProcess)
        }, 5000)
    } else {
        endProcess()
    }
}

Example router handler

function timerHandler(_req: RequestObject, respond: ResponseHandler) {
    setTimeout(() => respond('ok'), 2000)
}

Body:
I've solved my problem. Here's the code which solved my problem.

master.js

function close(callback) {
  if (!cluster.isMaster) {
    return
  }

  const promiseArray = []
  const workerIds = Object.keys(cluster.workers)

  for (const workerId of workerIds) {
    const worker = cluster.workers[workerId]

    worker.send('shutdown')
    worker.disconnect()

    promiseArray.push(new Promise((resolve) => {
      let resolved = false

      worker.once('exit', () => (!resolved && resolve(), resolved = true))
      setTimeout(() => (!resolved && resolve(), worker.kill('SIGTERM'), resolved = true), 4000)
    }))
  }

  Promise.all(promiseArray).then(callback)
}

worker.js

function terminateWorker(server) {
  if (server && server.listening) {
    Store.store(STORE_KEYS.isTerminating, true)
    gracefulCloseSockets()
    server.close(endProcess)
  } else {
    endProcess()
  }
}

Explanation

When the master receives a "SIGTERM" he calls the close function (excerpt above)

The worker receives the "shutdown" message and calls the terminateWorker function (excerpt above). This function closes the http.Server and waits for all sockets to finish.


问:
Select2: add new tag dynamically using code
I'm using select2 for tagging and I have it setup such that a user can add new tags as well. The issue that I'm dealing with is validating the user entry and adding the sanitized tag to selection.

To be more specific, when a user enters a space in a tag, i use formatNoMatches to display a js link to sanitize the tag and then add the tag programmatically. This code seems to run without errors but when  sanitize is called all selections of the input are cleared.

Any clues where i might be going wrong?

```<code>var data=[{id:0,tag:'enhancement'},{id:1,tag:'bug'},{id:2,tag:'duplicate'},{id:3,tag:'invalid'},{id:4,tag:'wontfix'}];
function format(item) { return item.tag; }

function sanitize(a){

    $("#select").select2('val',[{
        id: -1,
        tag: a
      }]);

      console.log(a);
};

$("#select").select2({
  tags: true,
  // tokenSeparators: [",", " "],
  createSearchChoice: function(term, data) {
    return term.indexOf(' ') >= 0 ?  null :
    {
        id: term,
        tag: term
      };
  },
  multiple: true,
  data:{ results: data, text: function(item) { return item.tag; } },  formatSelection: format, formatResult: format,
  formatNoMatches: function(term) { return "\"" + term + "\" <b>Is Invalid.</b> <a onclick=\"sanitize('"+ term +"')\">Clear Invalid Charecters</a>" }
});
</code>```

答:
Only this solution works for me:</p>

```<code>function convertObjectToSelectOptions(obj){
    var htmlTags = '';
    for (var tag in obj){
        htmlTags += '<option value="'+tag+'" selected="selected">'+obj[tag]+'</option>';
    }
    return htmlTags;
}
var tags = {'1':'dynamic tag 1', '2':'dynamic tag 2'}; //merge with old if you need
$('#my-select2').html(convertObjectToSelectOptions(tags)).trigger('change');
</code>```

Body:
I'm using select2 for tagging and I have it setup such that a user can add new tags as well. The issue that I'm dealing with is validating the user entry and adding the sanitized tag to selection.

To be more specific, when a user enters a space in a tag, i use formatNoMatches to display a js link to sanitize the tag and then add the tag programmatically. This code seems to run without errors but when  sanitize is called all selections of the input are cleared.

Any clues where i might be going wrong?

var data=[{id:0,tag:'enhancement'},{id:1,tag:'bug'},{id:2,tag:'duplicate'},{id:3,tag:'invalid'},{id:4,tag:'wontfix'}];
function format(item) { return item.tag; }

function sanitize(a){

    $("#select").select2('val',[{
        id: -1,
        tag: a
      }]);

      console.log(a);
};

$("#select").select2({
  tags: true,
  // tokenSeparators: [",", " "],
  createSearchChoice: function(term, data) {
    return term.indexOf(' ') >= 0 ?  null :
    {
        id: term,
        tag: term
      };
  },
  multiple: true,
  data:{ results: data, text: function(item) { return item.tag; } },  formatSelection: format, formatResult: format,
  formatNoMatches: function(term) { return "\"" + term + "\" Is Invalid. Clear Invalid Charecters" }
});

Body:
Only this solution works for me:

function convertObjectToSelectOptions(obj){
    var htmlTags = '';
    for (var tag in obj){
        htmlTags += '<option value="'+tag+'" selected="selected">'+obj[tag]+'</option>';
    }
    return htmlTags;
}
var tags = {'1':'dynamic tag 1', '2':'dynamic tag 2'}; //merge with old if you need
$('#my-select2').html(convertObjectToSelectOptions(tags)).trigger('change');


问:
If value is in another dataframe, replace multiple columns with NA
I have two data.frames like this:

```<code>#df1
ID     a1      a2     a3      b1      b2      b3     Date
3xy    Evan    Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    Mark    Seth   12/5

#df2
Name
Evan
Mark
</code>```

If a name from any of the "a" columns appears in df2$Name, I want to replace all of the "a" columns with NA. Same for the "b" columns. My desired output would look like this:

```<code>ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      NA     NA     Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    NA       NA      NA     12/5
</code>```

I've found several other posts that appear to be on similar topics, but I haven't found a way to get this to work. I've been able to replace the names in df1 that appear in df2 with NA using the code below, but haven't figured out how to replace the other columns that begin with the same letter:

```<code>df1[apply(df1, 2, function(df1) df1 %in% df2$Name)] <- NA
</code>```

Gives me an output like this:

```<code>ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    NA      Seth   12/5
</code>```

I also keep trying different ifelse statements, but no success.

答:
We can split the dataset based on the 'a', and 'b' columns, then loop through rows and assign the rows to NA values if there is any match with the 'name' column of 'df2'

```<code>nm1 <- names(df1)[c(-1, -8)]
lst <- lapply(split.default(df1[nm1], sub("\\d+", "", nm1)), function(x) {
         x[apply(x, 1, function(y) any(y %in% df2$Name)),] <- NA
     x})
df1[nm1] <- do.call(cbind, unname(lst))
df1
#   ID   a1   a2   a3   b1   b2   b3 Date
#1 3xy <NA> <NA> <NA>  Ben  Bob Alex 12/3
#2 4lm John Bill  Sue <NA> <NA> <NA> 12/5
</code>```

Or another option is melt/dcast from data.table

```<code>library(data.table)
dcast(melt(setDT(df1), measure = patterns("^a\\d+", "^b\\d+"),
    value.name = c('a', 'b'))[, c('a', 'b') := lapply(.SD, function(x)
  replace(x, any(x %in% df2$Name), NA)), ID, .SDcols = a:b][],
        ID + Date ~ variable, value.var = c('a', 'b'), sep='')
#    ID Date   a1   a2  a3  b1  b2   b3
#1: 3xy 12/3   NA   NA  NA Ben Bob Alex
#2: 4lm 12/5 John Bill Sue  NA  NA   NA
</code>```

Body:
I have two data.frames like this:

#df1
ID     a1      a2     a3      b1      b2      b3     Date
3xy    Evan    Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    Mark    Seth   12/5

#df2
Name
Evan
Mark

If a name from any of the "a" columns appears in df2$Name, I want to replace all of the "a" columns with NA. Same for the "b" columns. My desired output would look like this:

ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      NA     NA     Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    NA       NA      NA     12/5

I've found several other posts that appear to be on similar topics, but I haven't found a way to get this to work. I've been able to replace the names in df1 that appear in df2 with NA using the code below, but haven't figured out how to replace the other columns that begin with the same letter:

df1[apply(df1, 2, function(df1) df1 %in% df2$Name)] <- NA

Gives me an output like this:

ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    NA      Seth   12/5

I also keep trying different ifelse statements, but no success.

Body:
We can split the dataset based on the 'a', and 'b' columns, then loop through rows and assign the rows to NA values if there is any match with the 'name' column of 'df2'

nm1 <- names(df1)[c(-1, -8)]
lst <- lapply(split.default(df1[nm1], sub("\\d+", "", nm1)), function(x) {
         x[apply(x, 1, function(y) any(y %in% df2$Name)),] <- NA
     x})
df1[nm1] <- do.call(cbind, unname(lst))
df1
#   ID   a1   a2   a3   b1   b2   b3 Date
#1 3xy <NA> <NA> <NA>  Ben  Bob Alex 12/3
#2 4lm John Bill  Sue <NA> <NA> <NA> 12/5

Or another option is melt/dcast from data.table

library(data.table)
dcast(melt(setDT(df1), measure = patterns("^a\\d+", "^b\\d+"),
    value.name = c('a', 'b'))[, c('a', 'b') := lapply(.SD, function(x)
  replace(x, any(x %in% df2$Name), NA)), ID, .SDcols = a:b][],
        ID + Date ~ variable, value.var = c('a', 'b'), sep='')
#    ID Date   a1   a2  a3  b1  b2   b3
#1: 3xy 12/3   NA   NA  NA Ben Bob Alex
#2: 4lm 12/5 John Bill Sue  NA  NA   NA


问:
Enabling ssl in mongodb replicaset without certificates
I am trying to set up a mongodb 2.6.8 replicaset using ssl. I compiled mongo manually with ssl support and enabled ssl in my configuration as follows:

```<code>sslMode=requireSSL
sslPEMKeyFile=/etc/ssl/mongodb.pem
sslCAFile=/etc/ssl/client.pem
sslWeakCertificateValidation=true
replSet=rs0
</code>```

I created the mongodb.pem and client.pem files bu running openssl as follows on each server:

```<code># openssl req -new -x509 -days 365 -nodes -out mongodb-cert.crt -keyout mongodb-cert.key -subj '/C=US/ST=MA/L=Waltham/CN=<fully qualified domain name>'
# cat mongodb-cert.key mongodb-cert.crt > mongodb.pem
# openssl req -new -x509 -days 365 -nodes -out client-cert.crt -keyout client-cert.key -subj '/C=US/ST=MA/L=Waltham/CN=<fully qualified domain name>'
# cat client-cert.key client-cert.crt > client.pem
</code>```

On each server I can confirm that the certificates and ssl is working because on each of my servers I can do the following:

```<code>mongo --ssl --sslPEMKeyFile=/etc/ssl/client.pem --sslCAFile=/etc/ssl/mongodb.pem <fully qualified domain name>
</code>```

drops me into the mongo shell.

On the primary node, I can do rs.initiate() and rs.status() and it looks fine:

```<code>> rs.initiate()
{
    "info2" : "no configuration explicitly specified -- making one",
    "me" : "<fqdn node 1>:27017",
    "info" : "Config now saved locally.  Should come online in about a minute.",
    "ok" : 1
}
> rs.status()
{
    "set" : "rs0",
    "date" : ISODate("2015-04-02T20:25:27Z"),
    "myState" : 1,
    "members" : [
        {
            "_id" : 0,
            "name" : "<fqdn node 1>:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 23,
            "optime" : Timestamp(1428006318, 1),
            "optimeDate" : ISODate("2015-04-02T20:25:18Z"),
            "electionTime" : Timestamp(1428006318, 2),
            "electionDate" : ISODate("2015-04-02T20:25:18Z"),
            "self" : true
        }
    ],
    "ok" : 1
}
</code>```

However, when I attempt to add the second member, I get the dreaded 13144 error:

```<code>rs0:PRIMARY> rs.add("<fqdn node 2>:27017")
{
    "errmsg" : "exception: need most members up to reconfigure, not ok : <fqdn node 2>:27017",
    "code" : 13144,
    "ok" : 0
}
</code>```

I should also note that connecting between the two hosts works fine, i.e., while on node 1:

```<code>mongo --ssl --host <fqdn node 2>
</code>```

or while on node 2:

```<code>mongo --ssl --host <fqdn node 1>
</code>```

both work.

How do I pass in the ssl option and/or the certificates to the rs.add() command?

I don't actually care about passing the certificates (which is why I specified sslWeakCertificateValidation=true); I'm more concerned about making sure the communication between the nodes is in ssl.

答:
It's difficult to be certain what was wrong, but I've got a few observations:

You may have got that error if the other mongod process was started without the replSet=rs0 item in its configuration

You may have got that error because the servers cannot communicate on port 27017, e.g. if a firewall is blocking them. It's worth verifying the connectivity by, on each server, connecting the mongo client to the other server.

There is a problem with your mongod.pem file. You have created it by concatenating the server's private key and certificate; but it should not contain the key. It should be just an ascending chain of certificates, starting with the server and ending with the root. If the server is self-certified, then there is no need to concatenate anything else.

Body:
I am trying to set up a mongodb 2.6.8 replicaset using ssl. I compiled mongo manually with ssl support and enabled ssl in my configuration as follows:

sslMode=requireSSL
sslPEMKeyFile=/etc/ssl/mongodb.pem
sslCAFile=/etc/ssl/client.pem
sslWeakCertificateValidation=true
replSet=rs0

I created the mongodb.pem and client.pem files bu running openssl as follows on each server:

# openssl req -new -x509 -days 365 -nodes -out mongodb-cert.crt -keyout mongodb-cert.key -subj '/C=US/ST=MA/L=Waltham/CN=<fully qualified domain name>'
# cat mongodb-cert.key mongodb-cert.crt > mongodb.pem
# openssl req -new -x509 -days 365 -nodes -out client-cert.crt -keyout client-cert.key -subj '/C=US/ST=MA/L=Waltham/CN=<fully qualified domain name>'
# cat client-cert.key client-cert.crt > client.pem

On each server I can confirm that the certificates and ssl is working because on each of my servers I can do the following:

mongo --ssl --sslPEMKeyFile=/etc/ssl/client.pem --sslCAFile=/etc/ssl/mongodb.pem <fully qualified domain name>

drops me into the mongo shell.

On the primary node, I can do rs.initiate() and rs.status() and it looks fine:

> rs.initiate()
{
    "info2" : "no configuration explicitly specified -- making one",
    "me" : "<fqdn node 1>:27017",
    "info" : "Config now saved locally.  Should come online in about a minute.",
    "ok" : 1
}
> rs.status()
{
    "set" : "rs0",
    "date" : ISODate("2015-04-02T20:25:27Z"),
    "myState" : 1,
    "members" : [
        {
            "_id" : 0,
            "name" : "<fqdn node 1>:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 23,
            "optime" : Timestamp(1428006318, 1),
            "optimeDate" : ISODate("2015-04-02T20:25:18Z"),
            "electionTime" : Timestamp(1428006318, 2),
            "electionDate" : ISODate("2015-04-02T20:25:18Z"),
            "self" : true
        }
    ],
    "ok" : 1
}

However, when I attempt to add the second member, I get the dreaded 13144 error:

rs0:PRIMARY> rs.add("<fqdn node 2>:27017")
{
    "errmsg" : "exception: need most members up to reconfigure, not ok : <fqdn node 2>:27017",
    "code" : 13144,
    "ok" : 0
}

I should also note that connecting between the two hosts works fine, i.e., while on node 1:

mongo --ssl --host <fqdn node 2>

or while on node 2:

mongo --ssl --host <fqdn node 1>

both work.

How do I pass in the ssl option and/or the certificates to the rs.add() command?

I don't actually care about passing the certificates (which is why I specified sslWeakCertificateValidation=true); I'm more concerned about making sure the communication between the nodes is in ssl.


问:
Cannot read property 'state' of undefined with ReactJS and bcryptjs
I'm trying to use the bcryptjs library to hash passwords in my project, but when I add the functions necessary for the hashing process, I face some errors. I'm following the instructions in this link : bcryptjs instructions.

The idea is, when I call the SubmitClick function I have to hash the password provided, and then, using a fetch, add this to my database. Here is the code for my CreateUser.js page:

```<code>import React, { Component } from 'react';
import bcrypt from 'bcryptjs';

class CreateUser extends Component {

  constructor(props){
    super(props);
    this.state={
      id:'',
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:''
    }
  }

  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {

      bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(this.state.password, salt, function(err, hash) {
              console.log(hash);
          });
      });

      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      })
      .then(response => response.json())
      .then(parsedJSON => this.setState({id : parsedJSON._id}, function(){
        this.props.history.push({
          pathname : '/get',
          state : { id : this.state.id }
        });
      }))
      .catch(error => alert('Check your data! Some of the values passed aren`t valid'))
    }
  }

  changeID(parsedJSON){
    this.setState({id : parsedJSON._id})
  }

  changeEmail(event){
    this.setState({email : event.target.value})
  }

  changeFname(event){
    this.setState({first_name : event.target.value})
  }

  changeLname(event){
    this.setState({last_name : event.target.value})
  }

  changePhone(event){
    this.setState({personal_phone : event.target.value})
  }

  changePassword(event){
    this.setState({password : event.target.value})
  }

  changeReTPassword(event){
    this.setState({reTypepassword : event.target.value})
  }

  render() {
    return (
      <div id="layout">
        <div id="main">
          <div className="App-header">
              <label htmlFor="title">Create User</label>
          </div>
          <div className="content" id="content">
            <div className="infos">
              <input id="email" type="text" name="email" placeholder="Email"
              onChange = {(event)=> this.changeEmail(event)}/>
            </div>
            <div className="infos">
              <input id="f_name" type="text" name="F_name" placeholder="First Name"
              onChange = {(event)=> this.changeFname(event)}/>
            </div>
            <div className="infos">
              <input id="l_name" type="text" name="L_name" placeholder="Last Name"
              onChange = {(event)=> this.changeLname(event)}/>
            </div>
            <div className="infos">
              <input id="phone" type="text" name="L_name" placeholder="Personal Phone"
              onChange = {(event)=> this.changePhone(event)}/>
            </div>
            <div className="infos">
              <input id="senha" type="password" name="senha" placeholder="Password"
              onChange = {(event)=> this.changePassword(event)}/>
            </div>
            <div className="infos">
              <input id="senha" type="password" name="senha" placeholder="Re-type password"
              onChange = {(event)=> this.changeReTPassword(event)}/>
            </div>
            <div className="buttons">
              <button type="submit" onClick={(event) => this.SubmitClick()} className="buttonsUser">Submit</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default CreateUser;
</code>```

If I remove the following part of the code, the code works perfectly, without hashing:

```<code>  bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(this.props.password, salt, function(err, hash) {
          console.log(hash);
      });
  });
</code>```

But with that part, I'm facing this error:

```<code>> CreateUser.js:26 Uncaught TypeError: Cannot read property 'state' of undefined
    at CreateUser.js:26
    at bcrypt.js:155
    at run (setImmediate.js:40)
    at runIfPresent (setImmediate.js:69)
    at onGlobalMessage (setImmediate.js:109)
</code>```

I've search throughout the StackOverflow questions and found some questions similar to mine, and I have tried to use the solutions proposed in each one, but nothing changed. Here are the questions links for reference: Question1 Question2 Question3 Question4

I tried to bind my functions in the class constructor, as showed bellow, but got the same error.

```<code>  constructor(props){
    super(props);
    this.SubmitClick = this.SubmitClick.bind(this);
    this.state={
      id:'',
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:''
    }
  }
</code>```

I tried to bind my functions inline, in this case nothing really happened when I clicked the button, which is weird.

```<code>    <div className="buttons">
      <button type="submit" onClick={(event) => this.SubmitClick.bind(this)} className="buttonsUser">Submit</button>
    </div>
</code>```

I have no clue what is going wrong with my code, any suggestions ?

答:
You need to bind the callback or this will not be set:

```<code>  bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash);
      });
  }.bind(this));
</code>```

Or use an arrow function:

```<code>  bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash);
      });
  });
</code>```

Body:
I'm trying to use the bcryptjs library to hash passwords in my project, but when I add the functions necessary for the hashing process, I face some errors. I'm following the instructions in this link : bcryptjs instructions.

The idea is, when I call the SubmitClick function I have to hash the password provided, and then, using a fetch, add this to my database. Here is the code for my CreateUser.js page:

import React, { Component } from 'react';
import bcrypt from 'bcryptjs';

class CreateUser extends Component {

  constructor(props){
    super(props);
    this.state={
      id:'',
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:''
    }
  }

  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {

      bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(this.state.password, salt, function(err, hash) {
              console.log(hash);
          });
      });

      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      })
      .then(response => response.json())
      .then(parsedJSON => this.setState({id : parsedJSON._id}, function(){
        this.props.history.push({
          pathname : '/get',
          state : { id : this.state.id }
        });
      }))
      .catch(error => alert('Check your data! Some of the values passed aren`t valid'))
    }
  }

  changeID(parsedJSON){
    this.setState({id : parsedJSON._id})
  }

  changeEmail(event){
    this.setState({email : event.target.value})
  }

  changeFname(event){
    this.setState({first_name : event.target.value})
  }

  changeLname(event){
    this.setState({last_name : event.target.value})
  }

  changePhone(event){
    this.setState({personal_phone : event.target.value})
  }

  changePassword(event){
    this.setState({password : event.target.value})
  }

  changeReTPassword(event){
    this.setState({reTypepassword : event.target.value})
  }

  render() {
    return (

              Create User

              <input id="email" type="text" name="email" placeholder="Email"
              onChange = {(event)=> this.changeEmail(event)}/>

              <input id="f_name" type="text" name="F_name" placeholder="First Name"
              onChange = {(event)=> this.changeFname(event)}/>

              <input id="l_name" type="text" name="L_name" placeholder="Last Name"
              onChange = {(event)=> this.changeLname(event)}/>

              <input id="phone" type="text" name="L_name" placeholder="Personal Phone"
              onChange = {(event)=> this.changePhone(event)}/>

              <input id="senha" type="password" name="senha" placeholder="Password"
              onChange = {(event)=> this.changePassword(event)}/>

              <input id="senha" type="password" name="senha" placeholder="Re-type password"
              onChange = {(event)=> this.changeReTPassword(event)}/>

              <button type="submit" onClick={(event) => this.SubmitClick()} className="buttonsUser">Submit</button>

    );
  }
}

export default CreateUser;

If I remove the following part of the code, the code works perfectly, without hashing:

  bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(this.props.password, salt, function(err, hash) {
          console.log(hash);
      });
  });

But with that part, I'm facing this error:

> CreateUser.js:26 Uncaught TypeError: Cannot read property 'state' of undefined
    at CreateUser.js:26
    at bcrypt.js:155
    at run (setImmediate.js:40)
    at runIfPresent (setImmediate.js:69)
    at onGlobalMessage (setImmediate.js:109)

I've search throughout the StackOverflow questions and found some questions similar to mine, and I have tried to use the solutions proposed in each one, but nothing changed. Here are the questions links for reference: Question1 Question2 Question3 Question4

I tried to bind my functions in the class constructor, as showed bellow, but got the same error.

  constructor(props){
    super(props);
    this.SubmitClick = this.SubmitClick.bind(this);
    this.state={
      id:'',
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:''
    }
  }

I tried to bind my functions inline, in this case nothing really happened when I clicked the button, which is weird.

      <button type="submit" onClick={(event) => this.SubmitClick.bind(this)} className="buttonsUser">Submit</button>

I have no clue what is going wrong with my code, any suggestions ?

Body:
You need to bind the callback or this will not be set:

  bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash);
      });
  }.bind(this));

Or use an arrow function:

  bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash);
      });
  });


问:
Creating image upload facility in php on one.com
I am trying to create a simple file upload facility for my website using php, I believe most of the code is fine. I'm using one.com and I have an assets folder which then has an image folder inside this is where I want the images to be uploaded to. I am unsure of what to put for the file image path though.When I try and upload an image the 'Done' is echoed to the page but my image doesn't appear in the folder.</p>

```<code>if(isset($_POST['submit'])){

// GETTING INFO FROM FILE WE'VE UPLOADED
$file = $_FILES['image'];
$fileName = $_FILES['image']['name'];
$fileTmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileError = $_FILES['image']['error'];
$fileType = $_FILES['image']['type'];
//Splitting the filename on the extension
$fileExt= explode ('.', $fileName);
//Getting the extension from the file and tolower so we can find out if it is an allowed file type
$fileActualExt = strtolower(end($fileExt));
//File types that we are going to allow
$allowed = array('jpg','jpeg','png');

if(in_array($fileActualExt, $allowed)){
    if($fileError === 0){
        $fileNameNew = uniqid('', true).".".$fileActualExt;

        $fileDestination = '/assets/images/'.$fileName;   //PROBLEM??

        move_uploaded_file($FileTmpName, $fileDestination);
        echo"Done?";
    }else{
        echo "There was an error?";
    }}
    else {
    echo "You cannot upload files of this type";
}}
</code>```

答:
Does PHP have permission to write to that directory?

You aren't checking for errors on move_uploaded_file(), you are just echoing "Done?".

Check the permissions on the images directory, then check the file has been moved.

```<code>if(move_uploaded_file($FileTmpName, $fileDestination)){
   //File was moved
}else{
  //Error
}
</code>```

Also, try changing

```<code> $fileDestination = '/assets/images/'.$fileName;   //PROBLEM??
</code>```

to

```<code>$fileDestination = 'assets/images/'.$fileNameNew;   //PROBLEM??
</code>```

Hope that helps!

Body:
I am trying to create a simple file upload facility for my website using php, I believe most of the code is fine. I'm using one.com and I have an assets folder which then has an image folder inside this is where I want the images to be uploaded to. I am unsure of what to put for the file image path though.When I try and upload an image the 'Done' is echoed to the page but my image doesn't appear in the folder.

if(isset($_POST['submit'])){

// GETTING INFO FROM FILE WE'VE UPLOADED
$file = $_FILES['image'];
$fileName = $_FILES['image']['name'];
$fileTmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileError = $_FILES['image']['error'];
$fileType = $_FILES['image']['type'];
//Splitting the filename on the extension
$fileExt= explode ('.', $fileName);
//Getting the extension from the file and tolower so we can find out if it is an allowed file type
$fileActualExt = strtolower(end($fileExt));
//File types that we are going to allow
$allowed = array('jpg','jpeg','png');

if(in_array($fileActualExt, $allowed)){
    if($fileError === 0){
        $fileNameNew = uniqid('', true).".".$fileActualExt;

        $fileDestination = '/assets/images/'.$fileName;   //PROBLEM??

        move_uploaded_file($FileTmpName, $fileDestination);
        echo"Done?";
    }else{
        echo "There was an error?";
    }}
    else {
    echo "You cannot upload files of this type";
}}

Body:
Does PHP have permission to write to that directory?

You aren't checking for errors on move_uploaded_file(), you are just echoing "Done?".

Check the permissions on the images directory, then check the file has been moved.

if(move_uploaded_file($FileTmpName, $fileDestination)){
   //File was moved
}else{
  //Error
}

Also, try changing

 $fileDestination = '/assets/images/'.$fileName;   //PROBLEM??

to

$fileDestination = 'assets/images/'.$fileNameNew;   //PROBLEM??

Hope that helps!


问:
How can I query for multiple properties not known in advance using Expando?
I'm making an application in which a user can create categories to put items in them. The items share some basic properties, but the rest of them are defined by the category they belong to. The problem is that both the category and it's special properties are created by the user.

For instance, the user may create two categories: books and buttons. In the 'book' category he may create two properties: number of pages and author. In the buttons category he may create different properties: number of holes and color.

Initially, I placed these properties in a JsonProperty inside the Item. While this works, it means that I query the Datastore just by specifying the category that I am looking for and then I have to filter the results of the query in the code. For example, if I'm looking for all the books whose author is Carl Sagan, I would query the Item class with category == books and the loop through the results to keep only those that match the author.

While I don't really expect to have that many items per category (probably in the hundreds, unlikely to get to one thousand), this looks inefficient. So I tried to use ndb.Expando to make those special properties real properties that are indexed. I did this, adding the corresponding special properties to the item when putting it to the Datastore. So if the user creates an Item in the 'books' category and previously created in that category the special property 'author', an Item is saved with the special property expando_author = author in it. It worked as I expected until this point (dev server).

The real problem though became visible when I did some queries. While they worked in the dev server, they created composite indexes for each special/expando property, even if the query filters were equality only. And while each category can have at most five properties, it is evident that it can easily get out of control.

Example query:

```<code>items = Item.query()
for p in properties:
    items = items.filter(ndb.GenericProperty(p)==properties[p])
items.fetch()
</code>```

Now, since I don't know in advance what the properties will be (though I will limit it to 5), I can't build the indexes before uploading the application, and even if I knew it would probably mean having more indexes that I'm comfortable with. Is Expando the wrong tool for what I'm trying to do? Should I just keep filtering the results in the code using the JsonProperty? I would greatly appreciate any advice I can get.

PD. To make this post shorter I omitted a few details about what I did, if you need to know something I may have left out just ask in the comments.

答:
Consider storing category's properties in a single list property prefixed with category property name.

Like  (forget me I forgot exact Python syntax, switched to Go)

```<code>class Item():
  props = StringListProperty()

book = Item(category='book', props=['title:Carl Sagan'])
button = Item(category='button', props=['wholes:5'])
</code>```

Then you can do have a single composite index on category+props and do queries like this:

```<code>def filter_items(category, propName, propValue):
  Item.filter(Item.category == category).filter(Item.props==propName+':'+propValue)
</code>```

And you would need a function on Item to get property values cleaned up from prop names.

Body:
I'm making an application in which a user can create categories to put items in them. The items share some basic properties, but the rest of them are defined by the category they belong to. The problem is that both the category and it's special properties are created by the user.

For instance, the user may create two categories: books and buttons. In the 'book' category he may create two properties: number of pages and author. In the buttons category he may create different properties: number of holes and color.

Initially, I placed these properties in a JsonProperty inside the Item. While this works, it means that I query the Datastore just by specifying the category that I am looking for and then I have to filter the results of the query in the code. For example, if I'm looking for all the books whose author is Carl Sagan, I would query the Item class with category == books and the loop through the results to keep only those that match the author.

While I don't really expect to have that many items per category (probably in the hundreds, unlikely to get to one thousand), this looks inefficient. So I tried to use ndb.Expando to make those special properties real properties that are indexed. I did this, adding the corresponding special properties to the item when putting it to the Datastore. So if the user creates an Item in the 'books' category and previously created in that category the special property 'author', an Item is saved with the special property expando_author = author in it. It worked as I expected until this point (dev server).

The real problem though became visible when I did some queries. While they worked in the dev server, they created composite indexes for each special/expando property, even if the query filters were equality only. And while each category can have at most five properties, it is evident that it can easily get out of control.

Example query:

items = Item.query()
for p in properties:
    items = items.filter(ndb.GenericProperty(p)==properties[p])
items.fetch()

Now, since I don't know in advance what the properties will be (though I will limit it to 5), I can't build the indexes before uploading the application, and even if I knew it would probably mean having more indexes that I'm comfortable with. Is Expando the wrong tool for what I'm trying to do? Should I just keep filtering the results in the code using the JsonProperty? I would greatly appreciate any advice I can get.

PD. To make this post shorter I omitted a few details about what I did, if you need to know something I may have left out just ask in the comments.

Body:
Consider storing category's properties in a single list property prefixed with category property name.

Like  (forget me I forgot exact Python syntax, switched to Go)

class Item():
  props = StringListProperty()

book = Item(category='book', props=['title:Carl Sagan'])
button = Item(category='button', props=['wholes:5'])

Then you can do have a single composite index on category+props and do queries like this:

def filter_items(category, propName, propValue):
  Item.filter(Item.category == category).filter(Item.props==propName+':'+propValue)

And you would need a function on Item to get property values cleaned up from prop names.


问:
NSIS script failed - invalid verbose level

I try to create NSIS installer with ListView (downloaded here). However after script running I got failure message:

```<code>!verbose: Invalid verbose level
Error in macro __NSD_LV_InsertColumn_Call on macroline 2
Error in script "E:\Data\installer.nsi" on line 35 -- aborting creation process
</code>```

CommCtrl.nsh was copied to NSIS Include folder. Is there necessary any header file or plugin? Could anybody help me please?

答:
Seems like there is a bug in that 3rd-party header file.

Try something like this:

```<code>!include "CommCtrl.nsh"
!ifndef _COMMCTRL_NSH_VERBOSE
!define _COMMCTRL_NSH_VERBOSE ${_COMMCTRL_VERBOSE}
!endif
</code>```

Body:
I try to create NSIS installer with ListView (downloaded here). However after script running I got failure message:

!verbose: Invalid verbose level
Error in macro __NSD_LV_InsertColumn_Call on macroline 2
Error in script "E:\Data\installer.nsi" on line 35 -- aborting creation process

CommCtrl.nsh was copied to NSIS Include folder. Is there necessary any header file or plugin? Could anybody help me please?

Body:
Seems like there is a bug in that 3rd-party header file.

Try something like this:

!include "CommCtrl.nsh"
!ifndef _COMMCTRL_NSH_VERBOSE
!define _COMMCTRL_NSH_VERBOSE ${_COMMCTRL_VERBOSE}
!endif


问:
Using arrays to generate a players score
I'm trying to use the array method to keep track of scores on my game, I'm having difficulty in doing so when I try to compile and run.</p>

```<code>import java.util.Scanner;
import java.io.*;

public class score
{

    public static void main (String[]args)
    {

    Scanner scan = new Scanner(System.in);

    int [] arrPlayer = new int[7];

    System.out.println("Please Enter Your Score");
    arrPlayer[0]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[1]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[2]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[3]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[4]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[5]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[6]=scan.nextInt();

    System.out.println("Player 1 : Score: "arrPlayer[0];
    System.out.println("Player 1 : Score: "arrPlayer[1];
    System.out.println("Player 1 : Score: "arrPlayer[2];
    System.out.println("Player 1 : Score: "arrPlayer[3];
    System.out.println("Player 1 : Score: "arrPlayer[4];
    System.out.println("Player 1 : Score: "arrPlayer[5];
    System.out.println("Player 1 : Score: "arrPlayer[6];

    for(int i=0;i<7;i++);

    }

}
</code>```

答:
You can do like that</p>

```<code>  for(int i=0; i<7; I++){
      System.out.println("player            score1 :"+arrayplayer[i]);
     }
</code>```

Body:
I'm trying to use the array method to keep track of scores on my game, I'm having difficulty in doing so when I try to compile and run.

import java.util.Scanner;
import java.io.*;

public class score
{

    public static void main (String[]args)
    {

    Scanner scan = new Scanner(System.in);

    int [] arrPlayer = new int[7];

    System.out.println("Please Enter Your Score");
    arrPlayer[0]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[1]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[2]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[3]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[4]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[5]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[6]=scan.nextInt();

    System.out.println("Player 1 : Score: "arrPlayer[0];
    System.out.println("Player 1 : Score: "arrPlayer[1];
    System.out.println("Player 1 : Score: "arrPlayer[2];
    System.out.println("Player 1 : Score: "arrPlayer[3];
    System.out.println("Player 1 : Score: "arrPlayer[4];
    System.out.println("Player 1 : Score: "arrPlayer[5];
    System.out.println("Player 1 : Score: "arrPlayer[6];

    for(int i=0;i<7;i++);

    }

}

Body:
You can do like that

  for(int i=0; i<7; I++){
      System.out.println("player            score1 :"+arrayplayer[i]);
     }


答:
You are loosing the context in callback method passed to genSalt:

```<code>bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash);
    });
});
</code>```

Solution:

One way is use arrow function here also:

```<code>bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(this.state.password, salt, (err, hash) => {
          console.log(hash);
    });
});
</code>```

Or use .bind(this):

```<code>bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash);
    });
}.bind(this));
</code>```

Or use extra variable, and use that variable in place of this:

```<code>SubmitClick(){
    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    }else {

        let that = this;    //here

        bcrypt.genSalt(10, function(err, salt) {
            bcrypt.hash(that.state.password, salt, function(err, hash) {
                console.log(hash);
            });
        });
    }
    .....
}
</code>```

Title: Cannot read property 'state' of undefined with ReactJS and bcryptjs

Body:
You are loosing the context in callback method passed to genSalt:

bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash);
    });
});

Solution:

One way is use arrow function here also:

bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(this.state.password, salt, (err, hash) => {
          console.log(hash);
    });
});

Or use .bind(this):

bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(this.state.password, salt, function(err, hash) {
          console.log(hash);
    });
}.bind(this));

Or use extra variable, and use that variable in place of this:

SubmitClick(){
    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    }else {

        let that = this;    //here

        bcrypt.genSalt(10, function(err, salt) {
            bcrypt.hash(that.state.password, salt, function(err, hash) {
                console.log(hash);
            });
        });
    }
    .....
}


问:
Is `-1` correct for using as maximum value of an unsigned integer?
Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

```<code>unsigned short i = -1; // unsigned short max
</code>```

can easily be changed to any other type, like

```<code>unsigned long i = -1; // unsigned long max
</code>```

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.

答:
The technical side has been covered by other answers; and while you focus on technical correctness in your question, pointing out the cleanness aspect again is important, because imo that’s the much more important point.

The major reason why it is a bad idea to use that particular trickery is: The code is ambiguous. It is unclear whether someone used the unsigned trickery intentionally or made a mistake and actually wanted to initialize a signed variable to -1. Should your colleague mention a comment after you present this argument, tell him to stop being silly. :)

I’m actually slightly baffled that someone would even consider this trick in earnest. There’s an unambigous, intuitive and idiomatic way to set a value to its max in C: the _MAX macros. And there’s an additional, equally unambigous, intuitive and idiomatic way in C++ that provides some more type safety: numeric_limits. That -1 trick is a classic case of being clever.

Body:
Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

unsigned short i = -1; // unsigned short max

can easily be changed to any other type, like

unsigned long i = -1; // unsigned long max

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.


问:
Is it possible to rotate an image in Storyboard or do you have to do it programmatically?
Assume you have a triangle image you want to use at different angles (e.g., 180 degrees, 90 degrees).

Is it possible to rotate the triangle image within Storyboard, or do you need to do it programmatically?

答: It is possible to set layer.transform.rotation.z in User Defined Runtime Attributes. Check this answer: https://stackoverflow.com/a/32150954/2650588


问:
Drupal: a question about t() function
I've added the following text in the t() function in page.tpl.php page.

```<code><?php echo t('Some random text to translate.'); ?>
</code>```

Now when I go to admin/build/translate/search to translate the string drupal cannot find it.

I've refreshed all caches, and also the "Refresh" tab in internationalization module.

thanks

答: The t() function, to save on performance for single-language sites, won't store the string in the database until it is requested from another language. View the page in one of the non-default languages in order to populate the database (t() calls locale() to do this), thus making the string available for translation.</p>

Title: Drupal: a question about t() function

Body:
I've added the following text in the t() function in page.tpl.php page.

<?php echo t('Some random text to translate.'); ?>

Now when I go to admin/build/translate/search to translate the string drupal cannot find it.

I've refreshed all caches, and also the "Refresh" tab in internationalization module.

thanks


问:
How to add Calendar, Date-Picker?
I need to add a Calendar Date Picker in Excel 2013.

I found that the MonthView and the DT Picker are no longer in the ActiveX menu and the links for a CAB file that supposedly contains these does not work. There are instruction documents, but they rely on a control that doesn't exist.

I have an Excel Addin that does what I want, but I want to do this with VBA rather than install the Addin on every machine that will use this.

答:
Using DTPicker (Date Picker) element in VBA Excel Module makes your work unsharable. That happened to me many times. I usually share my works with mates and they weren't able to proceed whenever they have been encountered with DTPicker missing library problems.

Installing Microsoft Common Control 2 SP6 and then Register its service is not an everyone's cup of tea. So, Instead of using DTPicker element, I have developed my own Date Picker which is more convenient, easy and applicable.

here's the link to the Form File.
https://www.dropbox.com/s/bwxtkw03kytcv8v/Form%20Files.rar?dl=0

Steps to use this Form

Import it

Now, in your USERFORM, in Date area (textbox), execute my form file with double-click event.

enter image description here

Title: How to add Calendar, Date-Picker?


问:
Java thread.getContext().getClassLoader() uniqueness
How unique is the thread context's classloader. Is it reset everytime a thread is started?

Can we always be sure that 2 parallel threads will never have the same context classloader?

I see some frameworks like Axis relying on this to get and set run-time setting variables.

答:
How unique is the thread context's classloader.

Not even remotely.

Is it reset everytime a thread is started?

When a thread is created, it doesn’t have context loader that can be reset. It will inherit the parent thread’s context loader. Starting the thread doesn’t change its context loader.

Can we always be sure that 2 parallel threads will never have the same context classloader?

That would be actually very unlikely. As said, threads inherit the parent’s loader by default, so unless someone calls setContextClassLoader explicitly with a different loader, the default application class loader, as returned by ClassLoader.getSystemClassLoader() will be the used by all threads. Even in environments with different class loaders, it’s unlikely to have as much class loaders as threads.

I see some frameworks like Axis relying on this to get and set run-time setting variables.

It’s the main use of the feature, frameworks using the current thread’s context class loader by convention, but of course, for loading classes and resources, not to assume uniqueness of these loaders. The JVM never uses this context class loader on its own, as symbolic references found in a class are resolved through the defining class loader of that class. The same applies for Class.forName(String) (without a class loader argument). It requires code actively invoking getContextClassLoader() and using the returned loader for class loading, to make this feature relevant.

Don’t confuse class loaders with ThreadLocal variables.


问:
Scaladoc: @group tag not showing in API documentation
I'm trying to organise the members of a class in my library API documentation using @groupname and @group tags,  but it doesn't work (I'm using sbt 0.13.11)

My toy build.sbt:

```<code>name := "test"
scalaVersion := "2.10.5"
</code>```

My toy code src/main/scala/test.scala:

```<code>package test
/** Test class
 *
 * @groupname print Printer
 * @groupname throw Thrower
 */
class TestClass {
  /** @group print */
  def trivialPrint: Unit = print("Hello")
  /** @group throw */
  def trivialError: Unit = throw new Exception("Hello")
}
</code>```

sbt doc compiles an API doc where both my functions are in the "Value Members" group of the class (cf. screenshot). What am I doing wrong?

答:
At least for Scala 2.11.x, it seems like we do still need to ask for it specifically. Consider the following in your build.sbt:

```<code>  /* Normal scalac options */
  scalacOptions := Seq(
    "-deprecation",
    "-Ypartial-unification",
    "-Ywarn-value-discard",
    "-Ywarn-unused-import",
    "-Ywarn-dead-code",
    "-Ywarn-numeric-widen"
  )

  /* Only invoked when you do `doc` in SBT */
  scalacOptions in (Compile, doc) += "-groups"
</code>```

And then your example as you have it should work.

Body:
I'm trying to organise the members of a class in my library API documentation using @groupname and @group tags,  but it doesn't work (I'm using sbt 0.13.11)

My toy build.sbt:

name := "test"
scalaVersion := "2.10.5"

My toy code src/main/scala/test.scala:

package test
/** Test class
 *
 * @groupname print Printer
 * @groupname throw Thrower
 */
class TestClass {
  /** @group print */
  def trivialPrint: Unit = print("Hello")
  /** @group throw */
  def trivialError: Unit = throw new Exception("Hello")
}

sbt doc compiles an API doc where both my functions are in the "Value Members" group of the class (cf. screenshot). What am I doing wrong?

Body:
At least for Scala 2.11.x, it seems like we do still need to ask for it specifically. Consider the following in your build.sbt:

  /* Normal scalac options */
  scalacOptions := Seq(
    "-deprecation",
    "-Ypartial-unification",
    "-Ywarn-value-discard",
    "-Ywarn-unused-import",
    "-Ywarn-dead-code",
    "-Ywarn-numeric-widen"
  )

  /* Only invoked when you do `doc` in SBT */
  scalacOptions in (Compile, doc) += "-groups"

And then your example as you have it should work.


问:
Rows more narrow than the UITableView itself
How can I create a UITableView with grouped style such that the cells are a different width than the table view is?

For instance, the table view is width 768 (iPad width) but I want the cells to be only 500 wide.

答:
I'd simply create a UITableView that was 500 wide but had a transparent background. You could then put whatever background you want behind that in a UIImageView, etc.

Something like...

```<code>[myTableView setBackgroundColor:[UIColor clearColor]];
[myTableView setBackgroundView:nil];
[myTableView setOpaque:NO];
</code>```

...should hopefully do the trick.

Body:
I'd simply create a UITableView that was 500 wide but had a transparent background. You could then put whatever background you want behind that in a UIImageView, etc.

Something like...

[myTableView setBackgroundColor:[UIColor clearColor]];
[myTableView setBackgroundView:nil];
[myTableView setOpaque:NO];

...should hopefully do the trick.


问:
use rollaply without current row
I have a simple data.frame where I want to compute some summary statistics on a rolling basis. For example, a rolling median over a window of five observations (2 lags, current one and 2 ahead) is achieved by

```<code>library(dplyr)
x <- data.frame("vals" = rnorm(3e04))
y <- x %>%
         mutate(med5 = rollapply(data = vals,
                width = 5,
                FUN = median,
                align = "center",
                fill = NA,
                na.rm = TRUE))
</code>```

However, I would like to exclude the current row from this computation. I found the following approach:

```<code>z <- x %>%
      mutate(N=1:n()) %>%
      do(data.frame(., prmed = sapply(.$N, function(i) median(.$vals[.$N %in% c((i - 2):(i - 1), (i + 1):(i + 2))]))))
</code>```

This does what I want, if I subsequently set the first two values to NA.

So far so good, the only problem is that the latter approach is terribly slow compared to rollapply.

Is there a way to achieve the outcome of the latter with the speed of the former?

答:
A solution based on excluding the third number of the five, which is the current row of the calculation.</p>

```<code>library(dplyr)
library(zoo)

set.seed(124)

x <- data.frame("vals" = rnorm(3e04))
y <- x %>%
  mutate(med5 = rollapply(data = vals,
                          width = 5,
                          FUN = function(x) median(x[-3], na.rm = TRUE),
                          align = "center",
                          fill = NA))

head(y)
#          vals      med5
# 1 -1.38507062        NA
# 2  0.03832318        NA
# 3 -0.76303016 0.1253147
# 4  0.21230614 0.3914015
# 5  1.42553797 0.4562678
# 6  0.74447982 0.4562678
</code>```

Title: use rollaply without current row

Body:
I have a simple data.frame where I want to compute some summary statistics on a rolling basis. For example, a rolling median over a window of five observations (2 lags, current one and 2 ahead) is achieved by

library(dplyr)
x <- data.frame("vals" = rnorm(3e04))
y <- x %>%
         mutate(med5 = rollapply(data = vals,
                width = 5,
                FUN = median,
                align = "center",
                fill = NA,
                na.rm = TRUE))

However, I would like to exclude the current row from this computation. I found the following approach:

z <- x %>%
      mutate(N=1:n()) %>%
      do(data.frame(., prmed = sapply(.$N, function(i) median(.$vals[.$N %in% c((i - 2):(i - 1), (i + 1):(i + 2))]))))

This does what I want, if I subsequently set the first two values to NA.

So far so good, the only problem is that the latter approach is terribly slow compared to rollapply.

Is there a way to achieve the outcome of the latter with the speed of the former?

Body:
A solution based on excluding the third number of the five, which is the current row of the calculation.

library(dplyr)
library(zoo)

set.seed(124)

x <- data.frame("vals" = rnorm(3e04))
y <- x %>%
  mutate(med5 = rollapply(data = vals,
                          width = 5,
                          FUN = function(x) median(x[-3], na.rm = TRUE),
                          align = "center",
                          fill = NA))

head(y)
#          vals      med5
# 1 -1.38507062        NA
# 2  0.03832318        NA
# 3 -0.76303016 0.1253147
# 4  0.21230614 0.3914015
# 5  1.42553797 0.4562678
# 6  0.74447982 0.4562678


问:
VBA loop to show summary without pivot table
I am having problem in crating a loop to have summary on my table data.
To make my question clear refer to below image.

Thank you in advance.

答:
This is probably massively overkill but will be quick if you've got a large data set that you're working on (which I'm guessing you are otherwise you could do this easily by hand or using a pivot table). Please have a look at the comments and update where stated. It will currently output to cell E2 on the activesheet but I recommend updating ActiveSheet to your actual sheet name and E2 to your desired location

```<code>Public Sub Example()
    Dim rng As Range
    Dim tmpArr As Variant
    Dim Dict As Object, tmpDict As Object
    Dim i As Long, j As Long
    Dim v, key

    Set Dict = CreateObject("Scripting.Dictionary")

    ' Update to your sheet here
    With ActiveSheet
        ' You may need to modify this depending on where you range is stored
        Set rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 2))

        tmpArr = rng.Value

        For i = LBound(tmpArr, 1) To UBound(tmpArr, 1)
            ' Test if value exists in dictionary. If not add and set up the dictionary item
            If Not Dict.exists(tmpArr(i, 1)) Then
                Set tmpDict = Nothing
                Set tmpDict = CreateObject("Scripting.Dictionary")
                Dict.Add key:=tmpArr(i, 1), Item:=tmpDict
            End If
            ' Set nested dictionary to variable so we can edit it
            Set tmpDict = Nothing
            Set tmpDict = Dict(tmpArr(i, 1))

            ' Test if value exists in nested Dictionary, add if not and initiate counter
            If Not tmpDict.exists(tmpArr(i, 2)) Then
                tmpDict.Add key:=tmpArr(i, 2), Item:=1
            Else
                ' Increment counter if it already exists
                tmpDict(tmpArr(i, 2)) = tmpDict(tmpArr(i, 2)) + 1
            End If
            ' Write nested Dictionary back to Main dictionary
            Set Dict(tmpArr(i, 1)) = tmpDict
        Next i

        ' Repurpose array for output setting to maximum possible size (helps with speed of code)
        ReDim tmpArr(LBound(tmpArr, 2) To UBound(tmpArr, 2), LBound(tmpArr, 1) To UBound(tmpArr, 1))
        ' Set starting counters for array
        i = LBound(tmpArr, 1)
        j = LBound(tmpArr, 2)
        ' Convert dictionary and nested dictionary to flat output
        For Each key In Dict
            tmpArr(j, i) = key
            i = i + 1
            For Each v In Dict(key)
                tmpArr(j, i) = v
                tmpArr(j + 1, i) = Dict(key)(v)
                i = i + 1
            Next v
        Next key
        ' Reshape array to actual size
        ReDim Preserve tmpArr(LBound(tmpArr, 1) To UBound(tmpArr, 1), LBound(tmpArr, 2) To i - 1)
        ' Change this to the starting cell of your output
        With .Cells(2, 5)
            Range(.Offset(0, 0), .Cells(UBound(tmpArr, 2), UBound(tmpArr, 1))) = Application.Transpose(tmpArr)
        End With
    End With
End Sub
</code>```

Body:
This is probably massively overkill but will be quick if you've got a large data set that you're working on (which I'm guessing you are otherwise you could do this easily by hand or using a pivot table). Please have a look at the comments and update where stated. It will currently output to cell E2 on the activesheet but I recommend updating ActiveSheet to your actual sheet name and E2 to your desired location

Public Sub Example()
    Dim rng As Range
    Dim tmpArr As Variant
    Dim Dict As Object, tmpDict As Object
    Dim i As Long, j As Long
    Dim v, key

    Set Dict = CreateObject("Scripting.Dictionary")

    ' Update to your sheet here
    With ActiveSheet
        ' You may need to modify this depending on where you range is stored
        Set rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 2))

        tmpArr = rng.Value

        For i = LBound(tmpArr, 1) To UBound(tmpArr, 1)
            ' Test if value exists in dictionary. If not add and set up the dictionary item
            If Not Dict.exists(tmpArr(i, 1)) Then
                Set tmpDict = Nothing
                Set tmpDict = CreateObject("Scripting.Dictionary")
                Dict.Add key:=tmpArr(i, 1), Item:=tmpDict
            End If
            ' Set nested dictionary to variable so we can edit it
            Set tmpDict = Nothing
            Set tmpDict = Dict(tmpArr(i, 1))

            ' Test if value exists in nested Dictionary, add if not and initiate counter
            If Not tmpDict.exists(tmpArr(i, 2)) Then
                tmpDict.Add key:=tmpArr(i, 2), Item:=1
            Else
                ' Increment counter if it already exists
                tmpDict(tmpArr(i, 2)) = tmpDict(tmpArr(i, 2)) + 1
            End If
            ' Write nested Dictionary back to Main dictionary
            Set Dict(tmpArr(i, 1)) = tmpDict
        Next i

        ' Repurpose array for output setting to maximum possible size (helps with speed of code)
        ReDim tmpArr(LBound(tmpArr, 2) To UBound(tmpArr, 2), LBound(tmpArr, 1) To UBound(tmpArr, 1))
        ' Set starting counters for array
        i = LBound(tmpArr, 1)
        j = LBound(tmpArr, 2)
        ' Convert dictionary and nested dictionary to flat output
        For Each key In Dict
            tmpArr(j, i) = key
            i = i + 1
            For Each v In Dict(key)
                tmpArr(j, i) = v
                tmpArr(j + 1, i) = Dict(key)(v)
                i = i + 1
            Next v
        Next key
        ' Reshape array to actual size
        ReDim Preserve tmpArr(LBound(tmpArr, 1) To UBound(tmpArr, 1), LBound(tmpArr, 2) To i - 1)
        ' Change this to the starting cell of your output
        With .Cells(2, 5)
            Range(.Offset(0, 0), .Cells(UBound(tmpArr, 2), UBound(tmpArr, 1))) = Application.Transpose(tmpArr)
        End With
    End With
End Sub


问:
React-native-fbsdk building error
I am using to react-native-fbsdk. But last time when i tried to build my project on Android I have this error.

```<code>  Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/home/deema/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/home/deema/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/home/deema/Desktop/work/projects/dacebookTest/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           dacebookTest:react-native-fbsdk:unspecified
     > Could not find com.android.support:appcompat-v7:27.0.1.
</code>```

There are more same errors with com.android.support v 27.
I tried to create new empty project and I have same errors.

答:
Try replacing

```<code>node_modules/react-native-fbsdk/android/build.gradle
</code>```

with

```<code>compile('com.facebook.android:facebook-android-sdk:4.28.0')
</code>```

Title: React-native-fbsdk building error

Body:
I am using to react-native-fbsdk. But last time when i tried to build my project on Android I have this error.

  Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/home/deema/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/home/deema/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/home/deema/Desktop/work/projects/dacebookTest/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           dacebookTest:react-native-fbsdk:unspecified
     > Could not find com.android.support:appcompat-v7:27.0.1.

There are more same errors with com.android.support v 27.
I tried to create new empty project and I have same errors.

Body:
Try replacing

node_modules/react-native-fbsdk/android/build.gradle

with

compile('com.facebook.android:facebook-android-sdk:4.28.0')


问:
Why does C# array not have Count property?

Possible Duplicate:

  count vs length vs size in a collection

Really strange:

C# arrays such as the following

```<code>double[] test = new double[1];
</code>```

support the Length property to get the size of the array. But arrays also implement an IList interface:

```<code>IList<double> list = test;
</code>```

However, the IList interface provides also a Count property. How come the array ("test" in this case) doesn't?

Edit: Thanks to all of you who pointed out that it is in fact the ICollection interface (not IList) which provides the Count property, and also that this is due to explicit implementation of the interface.

答:
It was a design choice about Naming, not semantics.

Arrays have a Length property, as does the String.

Length signals immutable: You cannot Add to or Remove from an array.

Lists and other containers have a Count property that can usually change.

Oh, and if you call  list.Append(1.1); you will get a not supported exception.

Body:
Possible Duplicate:

  count vs length vs size in a collection

Really strange:

C# arrays such as the following

double[] test = new double[1];

support the Length property to get the size of the array. But arrays also implement an IList interface:

IList<double> list = test;

However, the IList interface provides also a Count property. How come the array ("test" in this case) doesn't?

Edit: Thanks to all of you who pointed out that it is in fact the ICollection interface (not IList) which provides the Count property, and also that this is due to explicit implementation of the interface.