问:
unable to dequeue cell with identifier cell XX error - Cannot figure how to solve
i'm currently facing an error in my swift file that nothing from the other threads on this subject solved.

I created a tableview thanks to my NewsTableViewController, I created a prototype for my custom cells that I identified as cell in the main storyboard. The Controller is alone and linked with no segue just as a prototype for display like this:

Controller on the right is my table view controller that bugs

But when I execute the application, when I click on the button that launches the piece of code that instantiate the NewsTableViewController, I have the error

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell
  with identifier cell - must register a nib or a class for the
  identifier or connect a prototype cell in a storyboard'

The identifier of my prototype is good yet, so what is wrong?
Here is the code of my NewsTableViewController :

```<code>class NewsTableViewController: UITableViewController {

var listOfDisplays = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return listOfDisplays.count
}

func fetchEventsNames()
{
    let fetchRequest:NSFetchRequest<Events> = Events.fetchRequest()
    do {
        let results = try DataBaseControler.getContext().fetch(fetchRequest)
        for i in results as [Events]{ /* *dewraper les arguments (i.name)!*/
            listOfDisplays.append(i.title!)
        }
    }
    catch
    {
        print("errors\(error)")
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let identifier = "cell"
    let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! NewsTableViewCell
    cell.cellImage.image = UIImage(named: "rcbl.jpg")
    cell.cellLabel.text = listOfDisplays[indexPath.row]
    return(cell)
}
</code>```

Here is also the code of my NewsTableViewCells :

```<code>class NewsTableViewCell: UITableViewCell {

@IBOutlet weak var cellLabel: UILabel!
@IBOutlet weak var cellImage: UIImageView!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
</code>```

}

And then here is the piece of code where I call the constructor:

```<code>...
    switch (names[row])
        {
    case "Actualités":
        let destination = NewsTableViewController() // Your destination
        destination.listOfDisplays = ["test1", "TEST2"]
        navigationController?.pushViewController(destination, animated: true)...
</code>```

What should I do to solve this problem ? Thank you in advance guys.

答:
When you create the view controller like this:

```<code>let destination = NewsTableViewController() // Your destination
</code>```

you are just creating an instance of that class with none of the setup you have done in the storyboard.

You either need to instantiate one from the storyboard with something like this:

```<code>let storyboard = UIStoryboard(name: "Main", bundle: nil) // Use the appropriate story board name
let destination = storyboard.instantiateViewController(withIdentifier: "testtable") // Make sure you have allocated the correct storyboard id to the view controller
self.navigationController?.pushViewController(destination, animated: true)
</code>```

or you can register you cell class for the table view in the viewDidLoad() like this:

```<code>self.tableView.register(TestTableViewCell.self, forCellReuseIdentifier: "testcell") // Use the correct class and identifier.
</code>```

Body:
i'm currently facing an error in my swift file that nothing from the other threads on this subject solved.

I created a tableview thanks to my NewsTableViewController, I created a prototype for my custom cells that I identified as cell in the main storyboard. The Controller is alone and linked with no segue just as a prototype for display like this:

Controller on the right is my table view controller that bugs

But when I execute the application, when I click on the button that launches the piece of code that instantiate the NewsTableViewController, I have the error

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell
  with identifier cell - must register a nib or a class for the
  identifier or connect a prototype cell in a storyboard'

The identifier of my prototype is good yet, so what is wrong?
Here is the code of my NewsTableViewController :

class NewsTableViewController: UITableViewController {

var listOfDisplays = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return listOfDisplays.count
}

func fetchEventsNames()
{
    let fetchRequest:NSFetchRequest<Events> = Events.fetchRequest()
    do {
        let results = try DataBaseControler.getContext().fetch(fetchRequest)
        for i in results as [Events]{ /* *dewraper les arguments (i.name)!*/
            listOfDisplays.append(i.title!)
        }
    }
    catch
    {
        print("errors\(error)")
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let identifier = "cell"
    let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! NewsTableViewCell
    cell.cellImage.image = UIImage(named: "rcbl.jpg")
    cell.cellLabel.text = listOfDisplays[indexPath.row]
    return(cell)
}

Here is also the code of my NewsTableViewCells :

class NewsTableViewCell: UITableViewCell {

@IBOutlet weak var cellLabel: UILabel!
@IBOutlet weak var cellImage: UIImageView!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

And then here is the piece of code where I call the constructor:

...
    switch (names[row])
        {
    case "Actualités":
        let destination = NewsTableViewController() // Your destination
        destination.listOfDisplays = ["test1", "TEST2"]
        navigationController?.pushViewController(destination, animated: true)...

What should I do to solve this problem ? Thank you in advance guys.

Body:
When you create the view controller like this:

let destination = NewsTableViewController() // Your destination

you are just creating an instance of that class with none of the setup you have done in the storyboard.

You either need to instantiate one from the storyboard with something like this:

let storyboard = UIStoryboard(name: "Main", bundle: nil) // Use the appropriate story board name
let destination = storyboard.instantiateViewController(withIdentifier: "testtable") // Make sure you have allocated the correct storyboard id to the view controller
self.navigationController?.pushViewController(destination, animated: true)

or you can register you cell class for the table view in the viewDidLoad() like this:

self.tableView.register(TestTableViewCell.self, forCellReuseIdentifier: "testcell") // Use the correct class and identifier.


来源: stackexchange

问:
trying to see if i can animate the stars moving
i've been working on trying to animate the stars but i'm not sure how. I've tried using on multiple different techniques but at the end its still not working. it doesn't matter if you move that stars to much i just want them to move. any help would be appreciated thanks.</p>

```<code>var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

ctx.fillStyle = "rgb(0, 102, 204)";
ctx.strokeStyle = "rgb(0, 0, 0)";
ctx.linewidth = 3;

//making the background

ctx.fillRect(0, 0, 1000, 900);

//making the grass
ctx.fillStyle = "rgb(178, 255, 102)";

ctx.fillRect(0, 620, 1000, 280);

// draw the stars
ctx.fillStyle = "rgb(255, 255, 153)";
ctx.beginPath();
ctx.moveTo(80, 120);
ctx.lineTo(100, 100);
ctx.lineTo(80, 80);
ctx.lineTo(60, 100);
ctx.lineTo(80, 120);
ctx.fill();

 ctx.beginPath(); //star 2
ctx.moveTo(120, 220);
ctx.lineTo(140, 200);
ctx.lineTo(120, 180);
ctx.lineTo(100, 200);
ctx.lineTo(120, 220);
ctx.fill();

ctx.beginPath();// star 3
ctx.moveTo(60, 160);
ctx.lineTo(180, 40);
ctx.lineTo(160, 20);
ctx.lineTo(140, 40);
ctx.lineTo(160, 60);
ctx.fill();

ctx.beginPath();//star 4
ctx.moveTo(240, 140);
ctx.lineTo(260, 120);
ctx.lineTo(240, 100);
ctx.lineTo(220, 120);
ctx.lineTo(240, 140);
ctx.fill();

ctx.beginPath();//star 5
ctx.moveTo(300, 260);
ctx.lineTo(320, 240);
ctx.lineTo(300, 220);
 ctx.lineTo(280, 240);
ctx.lineTo(300, 260);
ctx.fill();

ctx.beginPath();//star 6
ctx.moveTo(380, 180);
ctx.lineTo(400, 160);
ctx.lineTo(380, 140);
ctx.lineTo(360, 160);
ctx.lineTo(380, 180);
ctx.fill();

ctx.beginPath();//star 7
ctx.moveTo(460, 80);
ctx.lineTo(480, 60);
ctx.lineTo(460, 40);
ctx.lineTo(440, 60);
ctx.lineTo(460, 80);
 ctx.fill();

 ctx.beginPath();//star 8
 ctx.moveTo(520, 160);
 ctx.lineTo(540, 140);
 ctx.lineTo(520, 120);
 ctx.lineTo(500, 140);
 ctx.lineTo(520, 160);
 ctx.fill();

 ctx.beginPath();//star 9
ctx.moveTo(620, 60);
ctx.lineTo(640, 40);
ctx.lineTo(620, 20);
ctx.lineTo(600, 40);
ctx.lineTo(620, 60);
ctx.fill();

ctx.beginPath();//star 10
ctx.moveTo(660, 180);
ctx.lineTo(680, 160);
ctx.lineTo(660, 140);
ctx.lineTo(640, 160);
ctx.lineTo(660, 180);
ctx.fill();

ctx.beginPath();//star 11
ctx.moveTo(600, 240);
ctx.lineTo(620, 220);
ctx.lineTo(600, 200);
ctx.lineTo(580, 220);
ctx.lineTo(600, 240);
ctx.fill();

ctx.beginPath();//star 12
ctx.moveTo(740, 80);
ctx.lineTo(760, 60);
ctx.lineTo(740, 40);
ctx.lineTo(720, 60);
ctx.lineTo(740, 80);
ctx.fill();

ctx.beginPath();//star 13
ctx.moveTo(820, 160);
ctx.lineTo(840, 140);
ctx.lineTo(820, 120);
ctx.lineTo(800, 140);
ctx.lineTo(820, 160);
ctx.fill();

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

答:
Take a look at window.requestAnimationFrame.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var i = 0;
var speed = 500;

var drawStar = function (x, y) {
  ctx.beginPath();
  ctx.moveTo(80 + x, 120 + y);
  ctx.lineTo(100 + x, 100 + y);
  ctx.lineTo(80 + x, 80 + y);
  ctx.lineTo(60 + x, 100 + y);
  ctx.closePath();
  ctx.fill();
};

var render = function () {
  i += 1;
  var offset = i % speed; // calculate how much the stars moved

  ctx.fillStyle = "rgb(0, 102, 204)";

  //making the background
  ctx.fillRect(0, 0, 400, 300);

  //making the grass
  ctx.fillStyle = "rgb(178, 255, 102)";
  ctx.fillRect(0, 200, 400, 100);

  // draw the stars
  ctx.fillStyle = "rgb(255, 255, 153)";
  drawStar(offset, 0);
  drawStar(offset + 100, 50);
  drawStar(offset + 160, 20);

  window.requestAnimationFrame(render); // call render again in about 33ms
};

render(); // call render for the first time```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas" width="400" height="300"></canvas></code>```

ContentLicense: CC BY-SA 3.0

Body:
i've been working on trying to animate the stars but i'm not sure how. I've tried using on multiple different techniques but at the end its still not working. it doesn't matter if you move that stars to much i just want them to move. any help would be appreciated thanks.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

ctx.fillStyle = "rgb(0, 102, 204)";
ctx.strokeStyle = "rgb(0, 0, 0)";
ctx.linewidth = 3;

//making the background

ctx.fillRect(0, 0, 1000, 900);

//making the grass
ctx.fillStyle = "rgb(178, 255, 102)";

ctx.fillRect(0, 620, 1000, 280);

// draw the stars
ctx.fillStyle = "rgb(255, 255, 153)";
ctx.beginPath();
ctx.moveTo(80, 120);
ctx.lineTo(100, 100);
ctx.lineTo(80, 80);
ctx.lineTo(60, 100);
ctx.lineTo(80, 120);
ctx.fill();

 ctx.beginPath(); //star 2
ctx.moveTo(120, 220);
ctx.lineTo(140, 200);
ctx.lineTo(120, 180);
ctx.lineTo(100, 200);
ctx.lineTo(120, 220);
ctx.fill();

ctx.beginPath();// star 3
ctx.moveTo(60, 160);
ctx.lineTo(180, 40);
ctx.lineTo(160, 20);
ctx.lineTo(140, 40);
ctx.lineTo(160, 60);
ctx.fill();

ctx.beginPath();//star 4
ctx.moveTo(240, 140);
ctx.lineTo(260, 120);
ctx.lineTo(240, 100);
ctx.lineTo(220, 120);
ctx.lineTo(240, 140);
ctx.fill();

ctx.beginPath();//star 5
ctx.moveTo(300, 260);
ctx.lineTo(320, 240);
ctx.lineTo(300, 220);
 ctx.lineTo(280, 240);
ctx.lineTo(300, 260);
ctx.fill();

ctx.beginPath();//star 6
ctx.moveTo(380, 180);
ctx.lineTo(400, 160);
ctx.lineTo(380, 140);
ctx.lineTo(360, 160);
ctx.lineTo(380, 180);
ctx.fill();

ctx.beginPath();//star 7
ctx.moveTo(460, 80);
ctx.lineTo(480, 60);
ctx.lineTo(460, 40);
ctx.lineTo(440, 60);
ctx.lineTo(460, 80);
 ctx.fill();

 ctx.beginPath();//star 8
 ctx.moveTo(520, 160);
 ctx.lineTo(540, 140);
 ctx.lineTo(520, 120);
 ctx.lineTo(500, 140);
 ctx.lineTo(520, 160);
 ctx.fill();

 ctx.beginPath();//star 9
ctx.moveTo(620, 60);
ctx.lineTo(640, 40);
ctx.lineTo(620, 20);
ctx.lineTo(600, 40);
ctx.lineTo(620, 60);
ctx.fill();

ctx.beginPath();//star 10
ctx.moveTo(660, 180);
ctx.lineTo(680, 160);
ctx.lineTo(660, 140);
ctx.lineTo(640, 160);
ctx.lineTo(660, 180);
ctx.fill();

ctx.beginPath();//star 11
ctx.moveTo(600, 240);
ctx.lineTo(620, 220);
ctx.lineTo(600, 200);
ctx.lineTo(580, 220);
ctx.lineTo(600, 240);
ctx.fill();

ctx.beginPath();//star 12
ctx.moveTo(740, 80);
ctx.lineTo(760, 60);
ctx.lineTo(740, 40);
ctx.lineTo(720, 60);
ctx.lineTo(740, 80);
ctx.fill();

ctx.beginPath();//star 13
ctx.moveTo(820, 160);
ctx.lineTo(840, 140);
ctx.lineTo(820, 120);
ctx.lineTo(800, 140);
ctx.lineTo(820, 160);
ctx.fill();

</script>

Body:
Take a look at window.requestAnimationFrame.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var i = 0;
var speed = 500;

var drawStar = function (x, y) {
  ctx.beginPath();
  ctx.moveTo(80 + x, 120 + y);
  ctx.lineTo(100 + x, 100 + y);
  ctx.lineTo(80 + x, 80 + y);
  ctx.lineTo(60 + x, 100 + y);
  ctx.closePath();
  ctx.fill();
};

var render = function () {
  i += 1;
  var offset = i % speed; // calculate how much the stars moved

  ctx.fillStyle = "rgb(0, 102, 204)";

  //making the background
  ctx.fillRect(0, 0, 400, 300);

  //making the grass
  ctx.fillStyle = "rgb(178, 255, 102)";
  ctx.fillRect(0, 200, 400, 100);

  // draw the stars
  ctx.fillStyle = "rgb(255, 255, 153)";
  drawStar(offset, 0);
  drawStar(offset + 100, 50);
  drawStar(offset + 160, 20);

  window.requestAnimationFrame(render); // call render again in about 33ms
};

render(); // call render for the first time

<canvas id="myCanvas" width="400" height="300"></canvas>


问:
Regular Expression validating with "at"
I know how to validate an email adress using regular expression, when the mail has the structure "blabla@foo.com"
The valid regular expression looks like this:

```<code>([\w\-]([\.\w])+[\w]+@([\w\-]+\.)+[A-Za-z]{2,4})
</code>```

But at my university, my professors do have websites in which their email adresses look like this: prof[at]foo.bla

What is the correct regular expression for this kind of emails? Changing @ to [at] didn't work.

Is there any tutorial for this kind of problems? Can you please recommend something?

答:
[ and ]] have special meaning in regular expressions, so you have to escape them to match literally. So replace @ with \[at\] in your regexp.

```<code>([\w\-]([\.\w])+[\w]+\[at\]([\w\-]+\.)+[A-Za-z]{2,4})
</code>```

You can find a regular expression tutorial at regular-expression.info.

Title: Regular Expression validating with "at"

Body:
I know how to validate an email adress using regular expression, when the mail has the structure "blabla@foo.com"
The valid regular expression looks like this:

([\w\-]([\.\w])+[\w]+@([\w\-]+\.)+[A-Za-z]{2,4})

But at my university, my professors do have websites in which their email adresses look like this: prof[at]foo.bla

What is the correct regular expression for this kind of emails? Changing @ to [at] didn't work.

Is there any tutorial for this kind of problems? Can you please recommend something?

Body:
[ and ]] have special meaning in regular expressions, so you have to escape them to match literally. So replace @ with \[at\] in your regexp.

([\w\-]([\.\w])+[\w]+\[at\]([\w\-]+\.)+[A-Za-z]{2,4})

You can find a regular expression tutorial at regular-expression.info.


问:
Displaying objects in IE Developer Tools console
I'm debugging my web application in Firefox, Chrome and Internet Explorer. With the latter I'm using Developer Tools to debug my scripts.

The problem I'm having is that when I write some expression in console window and it should return an object all I can see is a simple {...} which isn't really helpful.

Is it possible to make it work similar to Firebug or Chrome console that actually display object content. Chrome is the best in this regard, because you can directly traverse the whole object as in Visual Studio.

Anyway. Is it possible to make IE Developer Tools console to display object properties and their values?

答: What works for me and this may just be something they added recently but after you pull up the console log. Clear the log but leave the console open then refresh the page. As the page loads in, you should then be able to explore the objects. I am not sure why it needs to be done that way but it appears to work. </p>

ContentLicense: CC BY-SA 2.5


问:
reading a text file its size (nearly 4 miga )c#
I write a code to read many text files and grouped them in one file called  (all.txt), after that I read all.txt file to count the word frequency, and the result appears in richtextbox. the code work well but the problem when I run the program, part of result appears then the program is hang without responding. I think that may be from memory, my computer RAM is 4 GB  any help would be appreciated.
note:my code work well in small text file.here's part of my code :</p>

```<code>  StreamWriter w=new StreamWriter(@"C:\documents\all.txt");
            w.Write(all);
            w.Close();
</code>```

答: If your problem is reading a large file, try using MemoryMappedFile as indicated in here</p>

Body:
I write a code to read many text files and grouped them in one file called  (all.txt), after that I read all.txt file to count the word frequency, and the result appears in richtextbox. the code work well but the problem when I run the program, part of result appears then the program is hang without responding. I think that may be from memory, my computer RAM is 4 GB  any help would be appreciated.
note:my code work well in small text file.here's part of my code :

  StreamWriter w=new StreamWriter(@"C:\documents\all.txt");
            w.Write(all);
            w.Close();


问:
Setting a variable from a string inside a TXT file with a batch file
I'm attempting to create a batch file for my company's users to use to migrate files from their older 'personal folder' network share to our new OneDrive implementation.

The problem is, some of our users have change the default sync folder for OneDrive to whatever drive and path they wanted, instead of keeping the default (*c:\users\username*)...for example, the one I'm using to test my BAT file against is using:

D:\OneDrive - Business

However, it does still have to work when it contains more or less delimiters, like C:\OneDrive or C:\This Is Where I Foolishly Store Stuff.

At this point, I've tried using REG QUERY to output to a text file from the UserFolder key in the registry to get the path, and now I'm trying to extract this path FROM the text file in question and set it to a variable.  The text file that is created looks like the following:

```<code>HKEY_CURRENT_USER\SOFTWARE\Microsoft\OneDrive\Accounts\Business1
    UserFolder    REG_SZ    D:\OneDrive - Business
</code>```

What I want to do is set the "D:\OneDrive - Business" to a variable to use in a scripted MOVE command.

My code is so awful, that I will refrain from posting it unless someone decides its necessary to answer my question.

I'm sure that for at least a DOZEN of you, this is child's play, so I would really appreciate any help that is provided me!!!

Thanks!!

答:
You can combine the output of the [MSDN]: reg with [MSDN]: findstr (to filter out some useless data), and iterate over what's left using [SS64]: for.

Here's the code (it must be run from a batch file):

@echo off

set _KEY_NAME=HKEY_CURRENT_USER\SOFTWARE\Microsoft\OneDrive\Accounts\Business1
set _VALUE_NAME=UserFolder
set _VALUE_DATA=

for /f "tokens=1,2,*" %%f in ('reg query %_KEY_NAME% /v %_VALUE_NAME% /t REG_SZ 2^>NUL ^| findstr %_VALUE_NAME%') do (
    set _VALUE_DATA="%%h"
)

echo Data: %_VALUE_DATA%
```

<p>This is based on the fact that on my machine (<em>Win10</em>), <code>reg query %_KEY_NAME% /v %_VALUE_NAME% /t REG_SZ</code> (with different values for the <em>_KEY_NAME</em> and <em>_VALUE_NAME</em>), output:</p>

<blockquote>
```HKEY_CURRENT_USER\SOFTWARE\_DummyKey
    _DummyValue    REG_SZ    D:\OneDrive - Business
End of search: 1 match(es) found.
```

@EDIT0: After looking at @Mofi's solution, I realized that I had no error handling. Added some.

Body:
I'm attempting to create a batch file for my company's users to use to migrate files from their older 'personal folder' network share to our new OneDrive implementation.

The problem is, some of our users have change the default sync folder for OneDrive to whatever drive and path they wanted, instead of keeping the default (*c:\users\username*)...for example, the one I'm using to test my BAT file against is using:

D:\OneDrive - Business

However, it does still have to work when it contains more or less delimiters, like C:\OneDrive or C:\This Is Where I Foolishly Store Stuff.

At this point, I've tried using REG QUERY to output to a text file from the UserFolder key in the registry to get the path, and now I'm trying to extract this path FROM the text file in question and set it to a variable.  The text file that is created looks like the following:

HKEY_CURRENT_USER\SOFTWARE\Microsoft\OneDrive\Accounts\Business1
    UserFolder    REG_SZ    D:\OneDrive - Business

What I want to do is set the "D:\OneDrive - Business" to a variable to use in a scripted MOVE command.

My code is so awful, that I will refrain from posting it unless someone decides its necessary to answer my question.

I'm sure that for at least a DOZEN of you, this is child's play, so I would really appreciate any help that is provided me!!!

Thanks!!

Body:
You can combine the output of the [MSDN]: reg with [MSDN]: findstr (to filter out some useless data), and iterate over what's left using [SS64]: for.

Here's the code (it must be run from a batch file):

@echo off

set _KEY_NAME=HKEY_CURRENT_USER\SOFTWARE\Microsoft\OneDrive\Accounts\Business1
set _VALUE_NAME=UserFolder
set _VALUE_DATA=

for /f "tokens=1,2,*" %%f in ('reg query %_KEY_NAME% /v %_VALUE_NAME% /t REG_SZ 2^>NUL ^| findstr %_VALUE_NAME%') do (
    set _VALUE_DATA="%%h"
)

echo Data: %_VALUE_DATA%

This is based on the fact that on my machine (Win10), reg query %_KEY_NAME% /v %_VALUE_NAME% /t REG_SZ (with different values for the _KEY_NAME and _VALUE_NAME), output:

HKEY_CURRENT_USER\SOFTWARE\_DummyKey
    _DummyValue    REG_SZ    D:\OneDrive - Business
End of search: 1 match(es) found.

@EDIT0: After looking at @Mofi's solution, I realized that I had no error handling. Added some.


问:
Sort an integer array, keeping first in place
How would I sort arrays as follows:

```<code>[10, 7, 12, 3, 5, 6] --> [10, 12, 3, 5, 6, 7]

[12, 8, 5, 9, 6, 10] --> [12, 5, 6, 8, 9, 10]
</code>```

keeping array[0] in place

with the next highest integer(s) following (if there are any)

then ascending from the lowest integer

答:
Have a look at below snippet.

It is really simple. Just remove first element from the arrary into new array.

Sort rest of the array and check if max of this array is greater than first element.

If yes, then push it into to result arrary. Otherwise concat rest of the array with result array

var input1 = [10, 7, 12, 3, 5, 6];
var expected1 = [10, 12, 3, 5, 6, 7];

var input2 = [12, 8, 5, 9, 6, 10];
var expected2 = [12, 5, 6, 8, 9, 10];

function customSort(aInput) {
  var aResult = [aInput.shift()];
  aInput = aInput.sort(function(a, b) { return a - b;});
  if (aInput[aInput.length - 1] > aResult[0]) {
    var iMax = aInput.pop();
    aResult.push(iMax);
  }
  aResult = aResult.concat(aInput);
  return aResult;
}

console.log("Expected: ", expected1.toString());
console.log("Sorted: ", customSort(input1).toString());
console.log("Expected: ", expected2.toString());
console.log("Sorted: ", customSort(input2).toString());```

Body:
How would I sort arrays as follows:

[10, 7, 12, 3, 5, 6] --> [10, 12, 3, 5, 6, 7]

[12, 8, 5, 9, 6, 10] --> [12, 5, 6, 8, 9, 10]

keeping array[0] in place

with the next highest integer(s) following (if there are any)

then ascending from the lowest integer


问:
Remove Wrap Text from Access Query
I'm currently changing an access function so that instead of .xls files, it exports .xlsx. After completing this, the only formatting issue was that a wrap text was applied on all the cells exported (not sure if this is something that comes with converting to .xlsx)

I'm wondering if there's a way to remove the wrap text while the file is still in excel, or if there's a command I can add to my export query to make the cells not wrap text.

The command I use to create the data in Access is:

```<code>DoCmd.OpenQuery "Device Summary", acViewNormal, acEdit
</code>```

Then I export it to an .xlsx file

```<code>DoCmd.OutputTo acOutputQuery, "Device Summary", acFormatXLSX, Forms![BuildSheet]![Text2] & "-Summary.xlsx", True
</code>```

Thanks in advance

答:
I had to set the Access table column widths wide enough to display the data and then the export adopted those column widths. Save the query object with the column widths set.

Why objection to wrapped text?

There is actually no need to open the query object to export.

Title: Remove Wrap Text from Access Query

Body:
I'm currently changing an access function so that instead of .xls files, it exports .xlsx. After completing this, the only formatting issue was that a wrap text was applied on all the cells exported (not sure if this is something that comes with converting to .xlsx)

I'm wondering if there's a way to remove the wrap text while the file is still in excel, or if there's a command I can add to my export query to make the cells not wrap text.

The command I use to create the data in Access is:

DoCmd.OpenQuery "Device Summary", acViewNormal, acEdit

Then I export it to an .xlsx file

DoCmd.OutputTo acOutputQuery, "Device Summary", acFormatXLSX, Forms![BuildSheet]![Text2] & "-Summary.xlsx", True

Thanks in advance


问:
C - a NON INT function example?
Unfortunately all of the  " C function examples " I come across are about "int"s (numbers).

I need a STRING example of a function.

This is a INT example:  ( works )

```<code>int cube(int n){
return n*n*n;
}

int o=1;
o = cube(2);
</code>```

I want a STRING example. I attempted to modify the above .. but I FAILED.

```<code>char cube(char n){
return n;
}

char *o;
o = cube("string");
</code>```

答:
Remember that in C a string is a sequence of character values terminated by a 0-valued byte.  A char object only stores a single character value, not a string.

Strings are stored in arrays of char:

```<code>char str[6] = "Hello"; // {'H', 'e', 'l', 'l', 'o', 0}, so str must be *at least* 6 elements wide.
</code>```

Passing a string to a function means passing an array expression as the argument, which will "decay" to a pointer to the first element of the array:

```<code>foo( str );     // same as &str[0]
foo( "Hello" ); // string literals are array expressions as well
</code>```

Returning a string from a function means returning a pointer to the first element of the string.

```<code>char *foo( const char *str )
{
  char *result = do_something_with( str );
  return result;
}

char *bar = foo( "Hello" );
</code>```

You want to be careful, here - you can't do something like

```<code>char *foo( const char *str )
{
  char result[] = "some string";
  return result;
}
</code>```

The result array is local to foo, and will cease to exist once foo exits; that means the pointer value you return will be invalid, and attempting to use that value in the calling function will result in undefined behavior (your code may work as expected, it may crash, you may get funky output, etc.).

If you want to return a string (meaning a pointer to the first element of an array of char containing the string) from a function, then you have to make sure that the memory containing the string has a lifetime beyond that of the function, usually by using dynamic memory:

```<code>char *upcaseString( const char *str )
{
  size_t len = strlen( str );
  char *result = calloc( len + 1 );
  for ( size_t i = 0; i < len; i++ )
    result[i] = toupper( str[i] );

  return result;
}
</code>```

Alternately, pass the target buffer as an argument to the function:

```<code>void upcaseString( const char *lower, char *upper )
{
  while ( *lower )
    *upper++ = toupper( *lower++ );
}

int main( void )
{
  char lower[] = "hello";
  char upper[sizeof lower];

  upcaseString( lower, upper );
}
</code>```

Title: C - a NON INT function example?

Body:
Unfortunately all of the  " C function examples " I come across are about "int"s (numbers).

I need a STRING example of a function.

This is a INT example:  ( works )

int cube(int n){
return n*n*n;
}

int o=1;
o = cube(2);

I want a STRING example. I attempted to modify the above .. but I FAILED.

char cube(char n){
return n;
}

char *o;
o = cube("string");

Body:
Remember that in C a string is a sequence of character values terminated by a 0-valued byte.  A char object only stores a single character value, not a string.

Strings are stored in arrays of char:

char str[6] = "Hello"; // {'H', 'e', 'l', 'l', 'o', 0}, so str must be *at least* 6 elements wide.

Passing a string to a function means passing an array expression as the argument, which will "decay" to a pointer to the first element of the array:

foo( str );     // same as &str[0]
foo( "Hello" ); // string literals are array expressions as well

Returning a string from a function means returning a pointer to the first element of the string.

char *foo( const char *str )
{
  char *result = do_something_with( str );
  return result;
}

char *bar = foo( "Hello" );

You want to be careful, here - you can't do something like

char *foo( const char *str )
{
  char result[] = "some string";
  return result;
}

The result array is local to foo, and will cease to exist once foo exits; that means the pointer value you return will be invalid, and attempting to use that value in the calling function will result in undefined behavior (your code may work as expected, it may crash, you may get funky output, etc.).

If you want to return a string (meaning a pointer to the first element of an array of char containing the string) from a function, then you have to make sure that the memory containing the string has a lifetime beyond that of the function, usually by using dynamic memory:

char *upcaseString( const char *str )
{
  size_t len = strlen( str );
  char *result = calloc( len + 1 );
  for ( size_t i = 0; i < len; i++ )
    result[i] = toupper( str[i] );

  return result;
}

Alternately, pass the target buffer as an argument to the function:

void upcaseString( const char *lower, char *upper )
{
  while ( *lower )
    *upper++ = toupper( *lower++ );
}

int main( void )
{
  char lower[] = "hello";
  char upper[sizeof lower];

  upcaseString( lower, upper );
}


问:
are there any Query Optimization Tools for SQL Server?
Are there any tools that do Query Optimizations for SQL Server 2005 and above?

I've searched & didn't find anything.

What do you recommend?

If this Question was repeated before you can close it but I didn't see anything similar

答: In SSMS - Tools | Database Engine Tuning Advisor - Does not work on Express versions.</p>


问:
Difference between dates not a whole number
Why is this not giving me a whole number of days?</p>

```<code>difftime("2015-04-22", "2014-10-30")

Time difference of 173.9583 days
</code>```

答:
Use the Date class to avoid the extra complexity of timestamps, daylight savings time, etc.

```<code>> as.Date("2015-04-22") - as.Date("2014-10-30")
Time difference of 174 days
</code>```

Body:
Why is this not giving me a whole number of days?

difftime("2015-04-22", "2014-10-30")

Time difference of 173.9583 days

Body:
Use the Date class to avoid the extra complexity of timestamps, daylight savings time, etc.

> as.Date("2015-04-22") - as.Date("2014-10-30")
Time difference of 174 days


问:
PowerShell - Filter Get-ADUser to get disabled accounts only
I have a csv file which contains a list of user names with no header.  I want to end up with a second csv file which contains ONLY those user names that correspond to Active Directory users who are disabled.

I was playing around with a Get-Content and then ForEach-Object (%) loop to query the AD and return each SAM and the status of it's enabled property.

```<code>Get-Content users.csv | % {Get-ADUser $_ | Select-Object samaccountname,enabled}
</code>```

Although what I really need to do is look at each name and move ONLY the ones tied to disabled accounts to a new csv file.  Only I cant quite sort out how to accomplish this.

答:
you're almost there:

```<code>$users = @(gc users.csv | % {Get-ADUser $_ | select samaccountname,enabled})
$users | ? { -not($_.enabled) } | export-csv -notypeinformation $somecsv
</code>```

what we're doing:

Loop through the text file with the foreach-object loop and select
your desired AD user attributes and assign them to an array @().  They normally would return as an array but I always explicitly cast because if ONE result is returned, it's returned as a single object instead of a one-entry array.

Then we filters those users using the where-object alias (?) that
are not enabled and then send those to your "disabled_users.csv"

Body:
I have a csv file which contains a list of user names with no header.  I want to end up with a second csv file which contains ONLY those user names that correspond to Active Directory users who are disabled.

I was playing around with a Get-Content and then ForEach-Object (%) loop to query the AD and return each SAM and the status of it's enabled property.

Get-Content users.csv | % {Get-ADUser $_ | Select-Object samaccountname,enabled}

Although what I really need to do is look at each name and move ONLY the ones tied to disabled accounts to a new csv file.  Only I cant quite sort out how to accomplish this.

Body:
you're almost there:

$users = @(gc users.csv | % {Get-ADUser $_ | select samaccountname,enabled})
$users | ? { -not($_.enabled) } | export-csv -notypeinformation $somecsv

what we're doing:

Loop through the text file with the foreach-object loop and select
your desired AD user attributes and assign them to an array @().  They normally would return as an array but I always explicitly cast because if ONE result is returned, it's returned as a single object instead of a one-entry array.

Then we filters those users using the where-object alias (?) that
are not enabled and then send those to your "disabled_users.csv"


问:
Controlling GPIO's of ESP8266 (NodeMCU) using KAA Sandbox (0.10.0)
The tutorial is given for older version of KAA Sandbox. Can some please explain how to do the same in newest version (0.10.0).
    Particularly, which demo application should I fuse node-mcu with.</p>

答:
The ESP8266 sample application was not ready at the time of Kaa 0.10 Sandbox release. Thus, it was disabled on the Sandbox.

The new version is available in the Kaa Sample Applications GitHub
repository. You should use the Kaa SDK from the Kaa 0.10 Sandbox, but the code from the master branch.

It was planned to release Kaa 0.10.1 Sandbox where the application is again enabled, but the date of the release is not defined yet.


答:
You could save the value of the first element and use it in a condition for the first sorting delta. Then sort by the standard delta.

How it works (the sort order is from Edge)

```<code>              condition  numerical     sortFn
   a      b       delta      delta     result  comment
-----  -----  ---------  ---------  ---------  -----------------
   7     10*          1                     1  different section
  12*     7          -1                    -1  different section
  12*    10*          0          2          2  same section
  12*     7          -1                    -1  same section
   3      7           0         -4         -4  same section
   3     12*          1                     1  different section
   3      7           0         -4         -4  same section
   5      7           0         -2         -2  same section
   5     12*          1                     1  different section
   5      3           0          2          2  same section
   5      7           0         -2         -2  same section
   6      7           0         -1         -1  same section
   6      3           0          3          3  same section
   6      5           0          1          1  same section
   6      7           0         -1         -1  same section

* denotes elements who should be in the first section
</code>```

Elements of different section means one of the elements goes into the first and the other into the second section, the value is taken by the delta of the condition.

Elements of the same section means, both elements belongs to the same section. For sorting the delta of the values is returned.

function sort(array) {
    var first = array[0];
    array.sort(function (a, b) {
       return (a < first) - (b < first) || a - b;
    });
    return array;
}

console.log(sort([10, 7, 12, 3, 5, 6]));
console.log(sort([12, 8, 5, 9, 6, 10]));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Sort an integer array, keeping first in place

Body:
You could save the value of the first element and use it in a condition for the first sorting delta. Then sort by the standard delta.

How it works (the sort order is from Edge)

              condition  numerical     sortFn
   a      b       delta      delta     result  comment
-----  -----  ---------  ---------  ---------  -----------------
   7     10*          1                     1  different section
  12*     7          -1                    -1  different section
  12*    10*          0          2          2  same section
  12*     7          -1                    -1  same section
   3      7           0         -4         -4  same section
   3     12*          1                     1  different section
   3      7           0         -4         -4  same section
   5      7           0         -2         -2  same section
   5     12*          1                     1  different section
   5      3           0          2          2  same section
   5      7           0         -2         -2  same section
   6      7           0         -1         -1  same section
   6      3           0          3          3  same section
   6      5           0          1          1  same section
   6      7           0         -1         -1  same section

* denotes elements who should be in the first section

Elements of different section means one of the elements goes into the first and the other into the second section, the value is taken by the delta of the condition.

Elements of the same section means, both elements belongs to the same section. For sorting the delta of the values is returned.

function sort(array) {
    var first = array[0];
    array.sort(function (a, b) {
       return (a < first) - (b < first) || a - b;
    });
    return array;
}

console.log(sort([10, 7, 12, 3, 5, 6]));
console.log(sort([12, 8, 5, 9, 6, 10]));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to install XML::Parser without expat-devel?
XML::Parser fails to build on a quite fresh 64-bit Debian box.  After issuing cpan XML::Parser, cpan fails with lots of errors about Expat.c and Expat.xs:

```<code>[...]
Expat.xs:2182: error: ‘CallbackVector’ has no member named ‘skip_until’
Expat.c: In function ‘XS_XML__Parser__Expat_Do_External_Parse’:
Expat.c:2904: error: ‘XML_Parser’ undeclared (first use in this function)
Expat.c:2904: error: expected ‘;’ before ‘parser’
Expat.xs:2194: error: ‘parser’ undeclared (first use in this function)
make[1]: *** [Expat.o] Error 1
make[1]: Leaving directory `/root/.cpan/build/XML-Parser-2.41-rpV6ok/Expat'
make: *** [subdirs] Error 2
  TODDR/XML-Parser-2.41.tar.gz
  /usr/bin/make -- NOT OK
Running make test
  Can't test without successful make
Running make install
  Make had returned bad status, install seems impossible
</code>```

Message at the start of the output explains that expat-devel is needed for building.

Expat must be installed prior to building XML::Parser and I can't find
  it in the standard library directories. Install 'expat-devel' package with your
  OS package manager. See 'README'.

But expat-devel is not in Debian repository.

Is it possible to get over this without need to build/install expat from source?

答:
None of the above methods worked for me. I had the right environment variables setup but they were somehow not picked up by cpanm that I use to install perl modules. Expat was also installed.

Here is what I did to overcome the same problem that OP is reporting.
This is very close to what @LadyBuzz suggested.

Download the XML::Parser from cpan.org

Extract the tarball into directory and descend to it.

Open the Makefile.pl and edit the first lines to actually have the absolute paths to both: EXPATLIBPATH and EXPATINCPATH

Save the Makefile.pl, go up one level and create a new tarball with the Makefile.pl that you just edited.

Execute cpanm on the newly created tarball.

This resulted in successful installation of the module.

Body:
XML::Parser fails to build on a quite fresh 64-bit Debian box.  After issuing cpan XML::Parser, cpan fails with lots of errors about Expat.c and Expat.xs:

[...]
Expat.xs:2182: error: ‘CallbackVector’ has no member named ‘skip_until’
Expat.c: In function ‘XS_XML__Parser__Expat_Do_External_Parse’:
Expat.c:2904: error: ‘XML_Parser’ undeclared (first use in this function)
Expat.c:2904: error: expected ‘;’ before ‘parser’
Expat.xs:2194: error: ‘parser’ undeclared (first use in this function)
make[1]: *** [Expat.o] Error 1
make[1]: Leaving directory `/root/.cpan/build/XML-Parser-2.41-rpV6ok/Expat'
make: *** [subdirs] Error 2
  TODDR/XML-Parser-2.41.tar.gz
  /usr/bin/make -- NOT OK
Running make test
  Can't test without successful make
Running make install
  Make had returned bad status, install seems impossible

Message at the start of the output explains that expat-devel is needed for building.

Expat must be installed prior to building XML::Parser and I can't find
  it in the standard library directories. Install 'expat-devel' package with your
  OS package manager. See 'README'.

But expat-devel is not in Debian repository.

Is it possible to get over this without need to build/install expat from source?


问:
DBMS_SESSION.set_client_identifier equivalent in SQL Server
I'd like to know if there's a way to set client identifier context like in Oracle by using DBMS_SESSION.set_client_identifier and grab the value using a function.

I am trying to track data changes including who/which username made the changes.
My plan to create Triggers that capture the OLD value, NEW value, and the username.

The connection to the server is using pooled connection, so using the username that connects to the DB is not the answer.

Anyone has an idea?

答:
If you cannot use properties from the connection itself (since it's pooled) you will have to set some additional info after your call to connection.Open(). But if I read your question correctly, that's OK for you.

So what you can use is SQL Servers SET CONTEXT_INFO, which lets you store up to 128 arbitrary bytes in the session/connection context and which you can query thereafter with the CONTEXT_INFO() function. See the description >here<.

ContentLicense: CC BY-SA 4.0


问:
synchronization for the method that used inside thread run method
I want to perform parallel calculation for several sets of input values. Do I need to synchronize the calculate(a, b, inputIndex) method?

```<code>private static final String FORMULA = "(#{a} + #{b}) * (#{a} + #{b} * #{b} - #{a})";
private List<Pair<Integer, Integer>> input = Arrays.asList(
        new ImmutablePair<>(1, 2),
        new ImmutablePair<>(2, 2),
        new ImmutablePair<>(3, 1),
        new ImmutablePair<>(4, 2),
        new ImmutablePair<>(1, 5)
);
private List<String> output = new ArrayList<>(Arrays.asList("", "", "", "", ""));

public void calculate() {
    IntStream.range(0, input.size()).forEach(idx -> {
        Pair<Integer, Integer> pair = input.get(idx);

        Thread threadWrapper = new Thread(
                () -> this.calculate(pair.getLeft(), pair.getRight(), idx)
        );
        threadWrapper.start();
    });

    try {
        Thread.sleep(4000); // waiting for threads to finish execution just in case
        System.out.println("Calculation result => " + output);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void calculate(Integer a, Integer b, int inputIndex) {
    System.out.println("Thread with index " + inputIndex + " started calculation.");
    Evaluator eval = new Evaluator();
    eval.putVariable("a", a.toString());
    eval.putVariable("b", b.toString());

    try {
        String result = eval.evaluate(FORMULA);
        Thread.sleep(3000);
        output.set(inputIndex, result);
        System.out.println("Thread with index " + inputIndex + " done.");
    } catch (EvaluationException | InterruptedException e) {
        e.printStackTrace();
    }
}
</code>```

Because if the code of calculate method was inside run method of Runnable I wouldn't need to do that. (also I think I don't need synchronized collections there because for input I only get data by index and for output I put element into the certain position)

答:
It’s important to emphasize that trying the code and getting the correct output is not sufficient to prove the correctness of a program, especially not when multi-threading is involved. In your case it may happen to work by accident, for two reasons:

You have debug output statements, i.e. System.out.println(…), in your code, which is introducing thread synchronization, as in the reference implementation, PrintStream synchronizes internally

Your code is simple and doesn’t run long enough to get deeply optimized by the JVM

Obviously, both reasons may be gone if you use similar code in a production environment.

For getting a correct program, even changing calculate(Integer a, Integer b, int inputIndex) to a synchronized method is not sufficient. Synchronization is only sufficient for establishing happens-before relationships regarding threads synchronizing on the same object.

Your initiating method calculate() does not synchronize on the this instance and it also doesn’t perform any other action that could be sufficient to establish a happens-before relationship with the calculating threads (like calling Thread.join(). It only invokes Thread.sleep(4000), which obviously doesn’t even guaranty that the other threads completed within that time. Further, the Java Language Specification states explicitly:

It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to Thread.sleep or Thread.yield, nor does the compiler have to reload values cached in registers after a call to Thread.sleep or Thread.yield.

For example, in the following (broken) code fragment, assume that this.done is a non-volatile boolean field:

```<code>while (!this.done)
    Thread.sleep(1000);
</code>```

The compiler is free to read the field this.done just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of this.done.

Note that what has been said in the example about this.done applies to the array elements of the backing array of your list as well. Weren’t you using immutable String instances, the effects could be even worse.

But it isn’t necessary to make the entire method synchronized, only the data exchange must be thread safe. The cleanest solution is to make the entire method side effect free, i.e. turn the signature to String calculate(Integer a, Integer b) and let the method return the result instead of manipulating a shared data structure. If the method is side effect free, it doesn’t need any synchronization.

The caller has to assemble the result values to a List then, but since you are already using the Stream API, this operation comes for free:

```<code>private static final String FORMULA = "(#{a} + #{b}) * (#{a} + #{b} * #{b} - #{a})";
private List<Pair<Integer, Integer>> input = Arrays.asList(
        new ImmutablePair<>(1, 2),
        new ImmutablePair<>(2, 2),
        new ImmutablePair<>(3, 1),
        new ImmutablePair<>(4, 2),
        new ImmutablePair<>(1, 5)
);

public void calculate() {
    List<String> output = input.parallelStream()
            .map(pair -> this.calculate(pair.getLeft(), pair.getRight()))
            .collect(Collectors.toList());
    System.out.println("Calculation result => " + output);
}

private String calculate(Integer a, Integer b) {
    System.out.println(Thread.currentThread()+" does calculation of ("+a+","+b+")");
    Evaluator eval = new Evaluator();
    eval.putVariable("a", a.toString());
    eval.putVariable("b", b.toString());

    try {
        String result = eval.evaluate(FORMULA);
        Thread.sleep(3000);
        System.out.println(Thread.currentThread()+" with ("+a+","+b+") done.");
        return result;
    } catch (EvaluationException | InterruptedException e) {
        throw new RuntimeException(e);
    }
}
</code>```

Body:
I want to perform parallel calculation for several sets of input values. Do I need to synchronize the calculate(a, b, inputIndex) method?

private static final String FORMULA = "(#{a} + #{b}) * (#{a} + #{b} * #{b} - #{a})";
private List<Pair<Integer, Integer>> input = Arrays.asList(
        new ImmutablePair<>(1, 2),
        new ImmutablePair<>(2, 2),
        new ImmutablePair<>(3, 1),
        new ImmutablePair<>(4, 2),
        new ImmutablePair<>(1, 5)
);
private List<String> output = new ArrayList<>(Arrays.asList("", "", "", "", ""));

public void calculate() {
    IntStream.range(0, input.size()).forEach(idx -> {
        Pair<Integer, Integer> pair = input.get(idx);

        Thread threadWrapper = new Thread(
                () -> this.calculate(pair.getLeft(), pair.getRight(), idx)
        );
        threadWrapper.start();
    });

    try {
        Thread.sleep(4000); // waiting for threads to finish execution just in case
        System.out.println("Calculation result => " + output);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void calculate(Integer a, Integer b, int inputIndex) {
    System.out.println("Thread with index " + inputIndex + " started calculation.");
    Evaluator eval = new Evaluator();
    eval.putVariable("a", a.toString());
    eval.putVariable("b", b.toString());

    try {
        String result = eval.evaluate(FORMULA);
        Thread.sleep(3000);
        output.set(inputIndex, result);
        System.out.println("Thread with index " + inputIndex + " done.");
    } catch (EvaluationException | InterruptedException e) {
        e.printStackTrace();
    }
}

Because if the code of calculate method was inside run method of Runnable I wouldn't need to do that. (also I think I don't need synchronized collections there because for input I only get data by index and for output I put element into the certain position)

Body:
It’s important to emphasize that trying the code and getting the correct output is not sufficient to prove the correctness of a program, especially not when multi-threading is involved. In your case it may happen to work by accident, for two reasons:

You have debug output statements, i.e. System.out.println(…), in your code, which is introducing thread synchronization, as in the reference implementation, PrintStream synchronizes internally

Your code is simple and doesn’t run long enough to get deeply optimized by the JVM

Obviously, both reasons may be gone if you use similar code in a production environment.

For getting a correct program, even changing calculate(Integer a, Integer b, int inputIndex) to a synchronized method is not sufficient. Synchronization is only sufficient for establishing happens-before relationships regarding threads synchronizing on the same object.

Your initiating method calculate() does not synchronize on the this instance and it also doesn’t perform any other action that could be sufficient to establish a happens-before relationship with the calculating threads (like calling Thread.join(). It only invokes Thread.sleep(4000), which obviously doesn’t even guaranty that the other threads completed within that time. Further, the Java Language Specification states explicitly:

It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to Thread.sleep or Thread.yield, nor does the compiler have to reload values cached in registers after a call to Thread.sleep or Thread.yield.

For example, in the following (broken) code fragment, assume that this.done is a non-volatile boolean field:

while (!this.done)
    Thread.sleep(1000);

The compiler is free to read the field this.done just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of this.done.

Note that what has been said in the example about this.done applies to the array elements of the backing array of your list as well. Weren’t you using immutable String instances, the effects could be even worse.

But it isn’t necessary to make the entire method synchronized, only the data exchange must be thread safe. The cleanest solution is to make the entire method side effect free, i.e. turn the signature to String calculate(Integer a, Integer b) and let the method return the result instead of manipulating a shared data structure. If the method is side effect free, it doesn’t need any synchronization.

The caller has to assemble the result values to a List then, but since you are already using the Stream API, this operation comes for free:

private static final String FORMULA = "(#{a} + #{b}) * (#{a} + #{b} * #{b} - #{a})";
private List<Pair<Integer, Integer>> input = Arrays.asList(
        new ImmutablePair<>(1, 2),
        new ImmutablePair<>(2, 2),
        new ImmutablePair<>(3, 1),
        new ImmutablePair<>(4, 2),
        new ImmutablePair<>(1, 5)
);

public void calculate() {
    List<String> output = input.parallelStream()
            .map(pair -> this.calculate(pair.getLeft(), pair.getRight()))
            .collect(Collectors.toList());
    System.out.println("Calculation result => " + output);
}

private String calculate(Integer a, Integer b) {
    System.out.println(Thread.currentThread()+" does calculation of ("+a+","+b+")");
    Evaluator eval = new Evaluator();
    eval.putVariable("a", a.toString());
    eval.putVariable("b", b.toString());

    try {
        String result = eval.evaluate(FORMULA);
        Thread.sleep(3000);
        System.out.println(Thread.currentThread()+" with ("+a+","+b+") done.");
        return result;
    } catch (EvaluationException | InterruptedException e) {
        throw new RuntimeException(e);
    }
}


问:
Auto size a jQuery UI dialog in Internet Explorer
How can I autosize a jQuery UI dialog in Internet Explorer?

This code is OK in Firefox, but not in Internet Explorer.

```<code>$('#dialog2').dialog({
    autoResize: true,
    show: "clip",
    hide: "clip",
    height: 'auto',
    width: 'auto',
    autoOpen: false,
    modal: true,
    position: 'center',
    draggable: true,

    open: function (type, data) {
        $(this).parent().appendTo("form");

    },
    buttons: { "close": function () { $(this).dialog("close"); document.getElementById("<%=btnnew.ClientID%>").click(); } }
});
</code>```

My HTML element is a DIV.

答:
I'm having success with width: 'auto' sizing jQuery UI dialog using the following "patch" (for IE) :

```<code>(function($) {
var fixDialogAutoWidth = $.noop;
if ( $.browser.msie ) {
    fixDialogAutoWidth = function(content) {
        var dialog = $(content).parent('.ui-dialog');
        var width = dialog.innerWidth();
        if ( width ) dialog.css('width', width);
    }
}

var _init = $.ui.dialog.prototype._init;
$.ui.dialog.prototype._init = function() {
    // IE magick: (width: 'auto' not working correctly) :
    // http://dev.jqueryui.com/ticket/4437
    if ( this.options.width == 'auto' ) {
        var open = this.options.open;
        this.options.open = function() {
            fixDialogAutoWidth(this);
            if ( open ) open.apply(this);
        }
    }
    // yet another bug options.hide: 'drop' does not work
    // in IE http://dev.jqueryui.com/ticket/5615
    if ( $.browser.msie && this.options.hide == 'drop' ) {
        this.options.hide = 'fold';
    }
    return _init.apply(this); // calls open() if autoOpen
};
})(jQuery);
</code>```

Just load this code after jquery-ui.js has loaded ...

Note that according to the ticket http://dev.jqueryui.com/ticket/4437 we shouldn't be using width: 'auto' but I just couldn't live without it ... :)

Body:
How can I autosize a jQuery UI dialog in Internet Explorer?

This code is OK in Firefox, but not in Internet Explorer.

$('#dialog2').dialog({
    autoResize: true,
    show: "clip",
    hide: "clip",
    height: 'auto',
    width: 'auto',
    autoOpen: false,
    modal: true,
    position: 'center',
    draggable: true,

    open: function (type, data) {
        $(this).parent().appendTo("form");

    },
    buttons: { "close": function () { $(this).dialog("close"); document.getElementById("<%=btnnew.ClientID%>").click(); } }
});

My HTML element is a DIV.

Body:
I'm having success with width: 'auto' sizing jQuery UI dialog using the following "patch" (for IE) :

(function($) {
var fixDialogAutoWidth = $.noop;
if ( $.browser.msie ) {
    fixDialogAutoWidth = function(content) {
        var dialog = $(content).parent('.ui-dialog');
        var width = dialog.innerWidth();
        if ( width ) dialog.css('width', width);
    }
}

var _init = $.ui.dialog.prototype._init;
$.ui.dialog.prototype._init = function() {
    // IE magick: (width: 'auto' not working correctly) :
    // http://dev.jqueryui.com/ticket/4437
    if ( this.options.width == 'auto' ) {
        var open = this.options.open;
        this.options.open = function() {
            fixDialogAutoWidth(this);
            if ( open ) open.apply(this);
        }
    }
    // yet another bug options.hide: 'drop' does not work
    // in IE http://dev.jqueryui.com/ticket/5615
    if ( $.browser.msie && this.options.hide == 'drop' ) {
        this.options.hide = 'fold';
    }
    return _init.apply(this); // calls open() if autoOpen
};
})(jQuery);

Just load this code after jquery-ui.js has loaded ...

Note that according to the ticket http://dev.jqueryui.com/ticket/4437 we shouldn't be using width: 'auto' but I just couldn't live without it ... :)


问:
converting 2 sas datasets to 2 matrixes to perform division and multiply by thousand
Both the datasets have same number of columns and column names. I stored most of the column names in sorted_cols macro which is basically separated by space. One more additional column exists as ID in both the sas datasets.some of the values in these are null(.) aswell. To convert the datasets to matrix m1 I tried this.

```<code>proc iml
varNames = {&sorted_col};
use Sashelp.Class(OBS=31);
read all var varNames into m1;
close Sashelp.Class;
print m[colname=VarNames];
quit;
</code>```

obviously it is throwing errors.
I thought I should mention the dataset somewhere which I dont know where to add.The next step I thought would be easy by (m1/m2)*1000 where m1 and m2 being 2 matrices and storing in a new matrix. May be try to write it back to a dataset.I am prettty much naive in sas.
This is my objective one is the dataset1, two is dataset2 what I want to get is to do division of element1 from dataset2(two) by element 1 of dataset1(one).next do the cumulative adition of the previous answer over the column down.

答:
This isn't particularly difficult to do in base SAS.  Of course, in IML it's even easier, but if you're not familiar with IML there's no particular reason to go into it unless you want to learn it.

This is one way; there are some interesting options using weighting also, but I find this nice and simple and easy to read and understand.  First I initialize one and two, then do the work.  Edited to reflect your data, and some code changes, particularly to add the running total concept.  PROC MEANS at the bottom is the alternative to the running total - it would only work if you removed the running total (the two lines relating to tempsums), as with that in it's summing the running totals, which is not correct.

```<code>data one;
input (d_201409-d_201412) (:best.);
row_label = _n_-1;
datalines;
3768 7079 6933 8451
3768 7079 6933 8448
3768 7079 6933 8447.4
3768 7079 6933 8447
3768 7079 6933 8447
3768 7079 6933 8445.86667
;;;;
run;

data two;
input (d_201409-d_201412) (:best.);
row_label = _n_-1;
datalines;
. 1 . 1
. 4 . 1
. . . .
. . 1 .
1 . . 1
. . 1 1
;;;;
run;

%let vars=d_201409-d_201412;

data one_div_two;
  set one;    *dividend first, then divisor;
  array vars &vars.;
  array tempstore[1000] _temporary_;  *1000 is arbitrary, something large as or larger than &vars size;
  array tempsums[1000] _temporary_;  *same idea;
    do _i = 1 to dim(vars);  *store dividend in temporary array;
    tempstore[_i] = vars[_i];
  end;
  set two;
  do _i = 1 to dim(vars);  *now we divide original number by stored dividend;
    vars[_i] = 1000 * divide(vars[_i],tempstore[_i]);
    tempsums[_i] = sum(tempsums[_i],vars[_i]);       *store away the running total;
    vars[_i] = tempsums[_i];                         *and retrieve it;
  end;
run;

proc means data=one_div_two noprint;   *and we summarize.  Could do this in the above step too, but easier here.;
  var &vars.;
  output out=id_Summ sum=;
run;
</code>```

Body:
Both the datasets have same number of columns and column names. I stored most of the column names in sorted_cols macro which is basically separated by space. One more additional column exists as ID in both the sas datasets.some of the values in these are null(.) aswell. To convert the datasets to matrix m1 I tried this.

proc iml
varNames = {&sorted_col};
use Sashelp.Class(OBS=31);
read all var varNames into m1;
close Sashelp.Class;
print m[colname=VarNames];
quit;

obviously it is throwing errors.
I thought I should mention the dataset somewhere which I dont know where to add.The next step I thought would be easy by (m1/m2)*1000 where m1 and m2 being 2 matrices and storing in a new matrix. May be try to write it back to a dataset.I am prettty much naive in sas.
This is my objective one is the dataset1, two is dataset2 what I want to get is to do division of element1 from dataset2(two) by element 1 of dataset1(one).next do the cumulative adition of the previous answer over the column down.

Body:
This isn't particularly difficult to do in base SAS.  Of course, in IML it's even easier, but if you're not familiar with IML there's no particular reason to go into it unless you want to learn it.

This is one way; there are some interesting options using weighting also, but I find this nice and simple and easy to read and understand.  First I initialize one and two, then do the work.  Edited to reflect your data, and some code changes, particularly to add the running total concept.  PROC MEANS at the bottom is the alternative to the running total - it would only work if you removed the running total (the two lines relating to tempsums), as with that in it's summing the running totals, which is not correct.

data one;
input (d_201409-d_201412) (:best.);
row_label = _n_-1;
datalines;
3768 7079 6933 8451
3768 7079 6933 8448
3768 7079 6933 8447.4
3768 7079 6933 8447
3768 7079 6933 8447
3768 7079 6933 8445.86667
;;;;
run;

data two;
input (d_201409-d_201412) (:best.);
row_label = _n_-1;
datalines;
. 1 . 1
. 4 . 1
. . . .
. . 1 .
1 . . 1
. . 1 1
;;;;
run;

%let vars=d_201409-d_201412;

data one_div_two;
  set one;    *dividend first, then divisor;
  array vars &vars.;
  array tempstore[1000] _temporary_;  *1000 is arbitrary, something large as or larger than &vars size;
  array tempsums[1000] _temporary_;  *same idea;
    do _i = 1 to dim(vars);  *store dividend in temporary array;
    tempstore[_i] = vars[_i];
  end;
  set two;
  do _i = 1 to dim(vars);  *now we divide original number by stored dividend;
    vars[_i] = 1000 * divide(vars[_i],tempstore[_i]);
    tempsums[_i] = sum(tempsums[_i],vars[_i]);       *store away the running total;
    vars[_i] = tempsums[_i];                         *and retrieve it;
  end;
run;

proc means data=one_div_two noprint;   *and we summarize.  Could do this in the above step too, but easier here.;
  var &vars.;
  output out=id_Summ sum=;
run;


问:
PHP UPDATE data where there are ID matches
I'm passing an id from a URL from the previous page and then try to update database values in the row of that id. I feel like I'm close. I'm able to update the value librarian_fname when I add into the update query the specific id number, but when I try and pass that value through the code, it must not be picking it up because it won't update when I use id = '$id'. Not sure what I'm doing wrong. And I am still learning so forgive me if this isn't perfect.

```<code><?php
$id = $_GET['id'];
echo $id;
?>
    <?php
  // This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
        foreach ($params as &$var) {
            // check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
            is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
            unset($var);
        }
}

// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);

            $librarian_fname = $_POST['librarian_fname'];
            $id = $_POST['id'];
 ?>

        <?php
         if(isset($_POST['add'])) {
            $dbhost = 'localhost';
            $dbuser = '';
            $dbpass = '';
            $conn = mysql_connect($dbhost, $dbuser, $dbpass);

            if(! $conn ) {
               die('Could not connect: ' . mysql_error());
            }
            $sql = "UPDATE table SET librarian_fname = '$librarian_fname' WHERE id = '$id'";
            mysql_select_db('Events');
            $result = mysql_query( $sql, $conn );

            if(! $result ) {
               die('Could not enter data: ' . mysql_error());
            }

            mysql_close($conn);
            header("Location: search.php");
         }

         else {
            ?>

            <?php
// define variables and set to empty values
$librarian_fname = $id = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $librarian_fname = test_input($_POST["librarian_fname"]);
  $id = test_input($_POST["id"]);
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
                    <legend><b>Appointment Topic</b></legend>
                    <input type="hidden" name="id" value="<? echo $id; ?>">
                    <label for="librarian_fname">First Name <em>*</em></label>
                    <input type="text" name="librarian_fname" size="50" required="no" validateat="onsubmit" message="Please enter your first name."> input name = "add" type = "submit" id = "add" value = "Submit">
                </form>
                <?php
         }
      ?>
</code>```

答:
I think one of the issues may be that TABLE is a MySQL reserved word.

https://dev.mysql.com/doc/refman/5.5/en/keywords.html

If we want to use a reserved word as an identifier (e.g. table name) it must be escaped. The normative pattern in MySQL to escape identifiers is to enclose them in single backtick characters, e.g.

```<code> UPDATE `table` SET
</code>```

That works whether the identifier is a reserved word or not. Better would be to use a different name for the table.

Be aware that the code appears to be vulnerable to SQL Injection. Potentially unsafe values incorporated into the text of a SQL statement must be properly escaped (e.g. using mysqli_real_escape_string)

https://xkcd.com/327/

The preferred pattern is to not incorporate values into the SQL text, and instead use a prepared statement with bind placeholders.

Body:
I'm passing an id from a URL from the previous page and then try to update database values in the row of that id. I feel like I'm close. I'm able to update the value librarian_fname when I add into the update query the specific id number, but when I try and pass that value through the code, it must not be picking it up because it won't update when I use id = '$id'. Not sure what I'm doing wrong. And I am still learning so forgive me if this isn't perfect.

<?php
$id = $_GET['id'];
echo $id;
?>
    <?php
  // This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
        foreach ($params as &$var) {
            // check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
            is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
            unset($var);
        }
}

// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);

            $librarian_fname = $_POST['librarian_fname'];
            $id = $_POST['id'];
 ?>

        <?php
         if(isset($_POST['add'])) {
            $dbhost = 'localhost';
            $dbuser = '';
            $dbpass = '';
            $conn = mysql_connect($dbhost, $dbuser, $dbpass);

            if(! $conn ) {
               die('Could not connect: ' . mysql_error());
            }
            $sql = "UPDATE table SET librarian_fname = '$librarian_fname' WHERE id = '$id'";
            mysql_select_db('Events');
            $result = mysql_query( $sql, $conn );

            if(! $result ) {
               die('Could not enter data: ' . mysql_error());
            }

            mysql_close($conn);
            header("Location: search.php");
         }

         else {
            ?>

            <?php
// define variables and set to empty values
$librarian_fname = $id = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $librarian_fname = test_input($_POST["librarian_fname"]);
  $id = test_input($_POST["id"]);
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
                    <legend>Appointment Topic</legend>
                    <input type="hidden" name="id" value="<? echo $id; ?>">
                    First Name *
                    <input type="text" name="librarian_fname" size="50" required="no" validateat="onsubmit" message="Please enter your first name."> input name = "add" type = "submit" id = "add" value = "Submit">
                </form>
                <?php
         }
      ?>

Body:
I think one of the issues may be that TABLE is a MySQL reserved word.

https://dev.mysql.com/doc/refman/5.5/en/keywords.html

If we want to use a reserved word as an identifier (e.g. table name) it must be escaped. The normative pattern in MySQL to escape identifiers is to enclose them in single backtick characters, e.g.

 UPDATE `table` SET

That works whether the identifier is a reserved word or not. Better would be to use a different name for the table.

Be aware that the code appears to be vulnerable to SQL Injection. Potentially unsafe values incorporated into the text of a SQL statement must be properly escaped (e.g. using mysqli_real_escape_string)

https://xkcd.com/327/

The preferred pattern is to not incorporate values into the SQL text, and instead use a prepared statement with bind placeholders.


问:
Cakephp Formhelper : disable required on textarea
I am trying to disable the required on that text input in my form.
However, even with

['required' => false], ['allowEmpty' => true]
which remove "required=required" from the HTML, I still get greeted with a 'This field cannot be left empty' when I try to make it be empty.

This string is located in Validator.php from what I see, but even though I tried editing or deleting what I thought was causing this, I did not find my way through.
I'm using cakephp 3.0.2
Here's my little form :

```<code><?php
echo $this->Form->create($schedule);
echo $this->Form->input('year', [array('type' => 'text', 'readonly' => 'readonly')]);
echo $this->Form->input('month',[array('type' => 'text', 'readonly' => 'readonly')]);
echo $this->Form->input('text', ['required' => false], ['allowEmpty' => true]);
echo $this->Form->button(__('Save'));
echo $this->Form->end();
?>
</code>```

Thanks for the time you'll give me.

答:
How is your model defined? Do you have a

```<code>public $validate = array()
</code>```

defined?  Are you sure you did not set required=true there, and did you set 'allowEmpty  => true there? Because that's where that validation belongs rather than in the form, so you should first check you're not contradicting yourself.

Body:
I am trying to disable the required on that text input in my form.
However, even with

['required' => false], ['allowEmpty' => true]
which remove "required=required" from the HTML, I still get greeted with a 'This field cannot be left empty' when I try to make it be empty.

This string is located in Validator.php from what I see, but even though I tried editing or deleting what I thought was causing this, I did not find my way through.
I'm using cakephp 3.0.2
Here's my little form :

<?php
echo $this->Form->create($schedule);
echo $this->Form->input('year', [array('type' => 'text', 'readonly' => 'readonly')]);
echo $this->Form->input('month',[array('type' => 'text', 'readonly' => 'readonly')]);
echo $this->Form->input('text', ['required' => false], ['allowEmpty' => true]);
echo $this->Form->button(__('Save'));
echo $this->Form->end();
?>

Thanks for the time you'll give me.

Body:
How is your model defined? Do you have a

public $validate = array()

defined?  Are you sure you did not set required=true there, and did you set 'allowEmpty  => true there? Because that's where that validation belongs rather than in the form, so you should first check you're not contradicting yourself.


问:
Trick to run different pre/post build events when building with MSBuild or from Visual Studio IDE
Don't ask me why, but does anyone know any trick to put in the pre/post build event command that will run different commands if the project is being built from command line with MSBuild or from inside the Visual Studio IDE?</p>

答:
The easiest solution would be to define build targets that are conditioned on the $(BuildingInVisualStudio) property that visual studio sets to true when buildinging.

```<code><Target Name="SpecialPreBuild" BeforeTargets="BeforeBuild" Condition="'$(BuildingInVisualStudio)' != 'true'">
  <Exec Command="some-command.exe --magic" />
  <Copy SourceFiles="foo.txt" DestinationFolder="bin\$(Configuration)\bar" />
</Target>

<Target Name="SpecialPostBuild" AfterTargets="AfterBuild" Condition="'$(BuildingInVisualStudio)' != 'true'">
  <Exec Command="some-other-command.exe --magic" />
</Target>
</code>```

If you want to skip these targets in other IDEs / editors as well, you could introduce a custom property as well and change the Condition attributes above to

```<code>Condition="'$(PerformSpecialLogic)' == 'true'"
</code>```

That way no "default" builds will execute these targets and you could build with the following arguments in your build script / CI definition:

```<code>msbuild /p:PerformSpecialLogic=true
</code>```

Body:
The easiest solution would be to define build targets that are conditioned on the $(BuildingInVisualStudio) property that visual studio sets to true when buildinging.

<Target Name="SpecialPreBuild" BeforeTargets="BeforeBuild" Condition="'$(BuildingInVisualStudio)' != 'true'">
  <Exec Command="some-command.exe --magic" />
  <Copy SourceFiles="foo.txt" DestinationFolder="bin\$(Configuration)\bar" />
</Target>

<Target Name="SpecialPostBuild" AfterTargets="AfterBuild" Condition="'$(BuildingInVisualStudio)' != 'true'">
  <Exec Command="some-other-command.exe --magic" />
</Target>

If you want to skip these targets in other IDEs / editors as well, you could introduce a custom property as well and change the Condition attributes above to

Condition="'$(PerformSpecialLogic)' == 'true'"

That way no "default" builds will execute these targets and you could build with the following arguments in your build script / CI definition:

msbuild /p:PerformSpecialLogic=true


问:
Selecting Data Between Two Dates For Manually Inserted Dates
```<code>            SELECT * FROM users
            WHERE birthday BETWEEN '08-06' AND  '15-06'
</code>```

This is my query to select data between two dates. I know this is duplicate question but their is slight problem to my situation.

The Dates which I m storing are manually inserted to db using dropdown list which is varchar datatype

Problem: The Results for this query only selects data using date(dd) values and not compares whole date string

This is the result i m getting which selects data from month 7 as well

```<code>    bday
   09-06-1985
   08-06-1990
   09-07-1991
</code>```

答:
Like other people write in comments, it's always best to use datetime data type for date. You can compare your varchar date like this</p>

```<code>SELECT * FROM users
WHERE STR_TO_DATE(birthday, '%d-%m')
  BETWEEN STR_TO_DATE('08-06', '%d-%m')
    AND STR_TO_DATE('15-06', '%d-%m')
</code>```

Body:
            SELECT * FROM users
            WHERE birthday BETWEEN '08-06' AND  '15-06'

This is my query to select data between two dates. I know this is duplicate question but their is slight problem to my situation.

The Dates which I m storing are manually inserted to db using dropdown list which is varchar datatype

Problem: The Results for this query only selects data using date(dd) values and not compares whole date string

This is the result i m getting which selects data from month 7 as well

    bday
   09-06-1985
   08-06-1990
   09-07-1991

Body:
Like other people write in comments, it's always best to use datetime data type for date. You can compare your varchar date like this

SELECT * FROM users
WHERE STR_TO_DATE(birthday, '%d-%m')
  BETWEEN STR_TO_DATE('08-06', '%d-%m')
    AND STR_TO_DATE('15-06', '%d-%m')


问:
Sort list by name, date and hierarchy
I want to sort the following list in the following order:

first by object without any parent

then by name

by year

by month

related objects should come directly after by the criteria (2-4).

So what I want to achieve is basically a tree structure as a flat list.

This is what I've come up with until now, but can't figure out how to implement the parent relation.

```<code>function monthYearCheck(a, b) {
    if(a.year < b.year) {
        return -1;
    } else if(a.year > b.year) {
        return 1;
    } else {
        if(a.month < b.month) {
            return -1;
        } else if(a.month > b.month) {
            return 1;
        } else {
            return 0;
        }
    }
}

var sortedArray = nonSortedArray.sort(function (a, b) {
    if(a.name === b.name) {
        return monthYearCheck(a, b);
    } else if(a.name < b.name) {
        return -1;
    } else if(a.name > b.name) {
        return 1;
    }
});
</code>```

This is the array before sorting:

```<code>[{
    name: "Bottom",
    id: 4,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 16
},{
    name: "Topp",
    id: 12,
    month: 6,
    year: 2016,
    value: 24
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 5,
    year: 2016,
    value: 14
},{
    name: "Middle2",
    id: 118,
    parentId: 104,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp",
    id: 12,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Topp2",
    id: 104,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 2
}]
</code>```

This is what I want to achieve:

```<code>[{
    name: "Topp",
    id: 12,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp",
    id: 12,
    month: 6,
    year: 2016,
    value: 24
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 5,
    year: 2016,
    value: 14
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Bottom",
    id: 4,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 16
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 2
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp2",
    id: 104,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Middle2",
    id: 118,
    parentId: 104,
    month: 6,
    year: 2016,
    value: 4
}]
</code>```

答:
You can use the following:

```<code>var sortedArray = nonSortedArray.sort(function (a, b) {
    return compareParentID(a.parentId, b.parentID) || a.name.localeCompare(b.name) || a.year.localeCompare(b.year) || a.month.localeCompare(b.month);
});

function compareParentID(a, b) {
    if (a == null && b != null)
        return -1;

    if (a != null && b == null)
        return 1;

    return a - b;
}
</code>```

If the name elements are not equal then it sorts them by the name.

This compares each column. If the name elements are equal, then it goes on to compare the year elements, etc.

Just chain more || clauses for each extra element you want to compare, in the order you want to compare them in.

Title: Sort list by name, date and hierarchy

Body:
I want to sort the following list in the following order:

first by object without any parent

then by name

by year

by month

related objects should come directly after by the criteria (2-4).

So what I want to achieve is basically a tree structure as a flat list.

This is what I've come up with until now, but can't figure out how to implement the parent relation.

function monthYearCheck(a, b) {
    if(a.year  b.year) {
        return 1;
    } else {
        if(a.month  b.month) {
            return 1;
        } else {
            return 0;
        }
    }
}

var sortedArray = nonSortedArray.sort(function (a, b) {
    if(a.name === b.name) {
        return monthYearCheck(a, b);
    } else if(a.name  b.name) {
        return 1;
    }
});

This is the array before sorting:

[{
    name: "Bottom",
    id: 4,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 16
},{
    name: "Topp",
    id: 12,
    month: 6,
    year: 2016,
    value: 24
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 5,
    year: 2016,
    value: 14
},{
    name: "Middle2",
    id: 118,
    parentId: 104,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp",
    id: 12,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Topp2",
    id: 104,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 2
}]

This is what I want to achieve:

[{
    name: "Topp",
    id: 12,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp",
    id: 12,
    month: 6,
    year: 2016,
    value: 24
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 5,
    year: 2016,
    value: 14
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Bottom",
    id: 4,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 16
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 2
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp2",
    id: 104,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Middle2",
    id: 118,
    parentId: 104,
    month: 6,
    year: 2016,
    value: 4
}]

Body:
You can use the following:

var sortedArray = nonSortedArray.sort(function (a, b) {
    return compareParentID(a.parentId, b.parentID) || a.name.localeCompare(b.name) || a.year.localeCompare(b.year) || a.month.localeCompare(b.month);
});

function compareParentID(a, b) {
    if (a == null && b != null)
        return -1;

    if (a != null && b == null)
        return 1;

    return a - b;
}

If the name elements are not equal then it sorts them by the name.

This compares each column. If the name elements are equal, then it goes on to compare the year elements, etc.

Just chain more || clauses for each extra element you want to compare, in the order you want to compare them in.


问:
how to create a new observable subscription based on existing observable in rxjs?
I need to do something as the following line in my project(from
https://github.com/devyumao/angular2-busy)

```<code>ngOnInit() {
    this.busy = this.http.get('...').subscribe();
}
</code>```

In my project, I am making request based on route change as the following:

```<code>ngOnInit(): void {
    this.activatedRoute
        .params
        .map(params => params['queryString'])
        .flatMap(id => this.http.(''))
        .subscribe(result => this.data = result);
}
</code>```

It seems I need to create a new subscription every time there is a change in route. I am not sure how to do it.

I am looking for rxjs solution only (without using Promise).

Thanks!

derek

答:
I would globally (in your main component for example) register on route changes this way and trigger your request in the associated callback:

```<code>this.router.events
  .filter(event => event instanceof NavigationStart)
  // or NavigationEnd
  .subscribe(event => {
    this.http.post('').subscribe();
  });
</code>```

This way you subscribe once on changes.

If you want to have access to route params, you need to inject the ActivateRoute instance as well and subscribe on its params attribute.

For this, I would leverage the combineLatest method of the Observable class, like described below:

```<code>export class AppComponent {

  constructor(private router: Router, private route: ActivatedRoute) {
    Observable.combineLatest(
      this.router.events
        .filter(event => event instanceof NavigationStart),
      this.route.params
    )
    .subscribe(data => {
      const event = data[0];
      const params = data[1];
      (...)
    });
  }
}
</code>```

Don't forget to add this:

```<code>import 'rxjs/add/observable/combineLatest';
</code>```

Body:
I need to do something as the following line in my project(from
https://github.com/devyumao/angular2-busy)

ngOnInit() {
    this.busy = this.http.get('...').subscribe();
}

In my project, I am making request based on route change as the following:

ngOnInit(): void {
    this.activatedRoute
        .params
        .map(params => params['queryString'])
        .flatMap(id => this.http.(''))
        .subscribe(result => this.data = result);
}

It seems I need to create a new subscription every time there is a change in route. I am not sure how to do it.

I am looking for rxjs solution only (without using Promise).

Thanks!

derek

Body:
I would globally (in your main component for example) register on route changes this way and trigger your request in the associated callback:

this.router.events
  .filter(event => event instanceof NavigationStart)
  // or NavigationEnd
  .subscribe(event => {
    this.http.post('').subscribe();
  });

This way you subscribe once on changes.

If you want to have access to route params, you need to inject the ActivateRoute instance as well and subscribe on its params attribute.

For this, I would leverage the combineLatest method of the Observable class, like described below:

export class AppComponent {

  constructor(private router: Router, private route: ActivatedRoute) {
    Observable.combineLatest(
      this.router.events
        .filter(event => event instanceof NavigationStart),
      this.route.params
    )
    .subscribe(data => {
      const event = data[0];
      const params = data[1];
      (...)
    });
  }
}

Don't forget to add this:

import 'rxjs/add/observable/combineLatest';


问:
Try-Catch with fluent expressions
This LINQ query expression fails with Win32Exception "Access is denied":

```<code>Process.GetProcesses().Select(p => p.MainModule.FileName)
</code>```

And this fails with IOException "The device is not ready":

```<code>DriveInfo.GetDrives().Select(d => d.VolumeLabel)
</code>```

What is the best way to filter out inaccessible objects and avoid exceptions?

答:
Write an extension method!

```<code>void Main()
{
    var volumeLabels =
        DriveInfo
        .GetDrives()
        .SelectSafe(dr => dr.VolumeLabel);
}

// Define other methods and classes here

public static class LinqExtensions
{
    public static IEnumerable<T2> SelectSafe<T,T2>(this IEnumerable<T> source, Func<T,T2> selector)
    {
        foreach (var item in source)
        {
            T2 value = default(T2);
            try
            {
                value = selector(item);
            }
            catch
            {
                continue;
            }
            yield return value;
        }
    }
}
</code>```

This way you can customise any behaviour you want, and you don't have to create bulky and hacky where clauses, this way you could even get it to return an alternative value if there's an exception.

Title: Try-Catch with fluent expressions

Body:
This LINQ query expression fails with Win32Exception "Access is denied":

Process.GetProcesses().Select(p => p.MainModule.FileName)

And this fails with IOException "The device is not ready":

DriveInfo.GetDrives().Select(d => d.VolumeLabel)

What is the best way to filter out inaccessible objects and avoid exceptions?

Body:
Write an extension method!

void Main()
{
    var volumeLabels =
        DriveInfo
        .GetDrives()
        .SelectSafe(dr => dr.VolumeLabel);
}

// Define other methods and classes here

public static class LinqExtensions
{
    public static IEnumerable<T2> SelectSafe<T,T2>(this IEnumerable<T> source, Func<T,T2> selector)
    {
        foreach (var item in source)
        {
            T2 value = default(T2);
            try
            {
                value = selector(item);
            }
            catch
            {
                continue;
            }
            yield return value;
        }
    }
}

This way you can customise any behaviour you want, and you don't have to create bulky and hacky where clauses, this way you could even get it to return an alternative value if there's an exception.


问:
Qt: Does a QReadWriteLock work as shown?
I have four threads that need to be syncronized. In order to achieve this, I am looking to pass each thread the same bool array. Each thread will change the 'corresponding' value to true once it has reached a certain point in the thread, then constantly check to see if the rest of the values are true. If so, enter the loop... An example

```<code>//above thread init stuff
oLock->lockForWrite();
abSync[iThreadNum] = true;  //iThreadNum = {0...3} depending on whats set
oLock->unlock();

bool bSynced = false;
while (!bSynced)
{
    oLock->lockForRead();
    if (abSync[0] && abSync[1] && abSync[2] && abSync[3])
        bSynced = true;
    oLock->unlock();
}

//below thread run and finish
</code>```

Does the QReadWriteLock work as described above? Will it in fact lock the variable for the write (as each thread goes through) but not for the read? A quick look at the documentation suggests that QReadWriteLock will only block at lockForRead() if there is a write lock but not a read lock which is what I want above.

Also, I understand the above will suck down CPU cycles as its going through the loop and that is the wanted behavior. Using a Sleep is not good enough for our needs.

答: I don't know what your margin is for "running at the same time", but threads don't run at the same time and it is hard to predict what the offsets will be.  What you try to achieve is a threading barrier, which should be done with condition variables (QWaitCondition), but even that doesn't guarantee starting at the same time, just that they won't start before all have finished previous work (but that can be alright is your margin is big enough).</p>

Body:
I have four threads that need to be syncronized. In order to achieve this, I am looking to pass each thread the same bool array. Each thread will change the 'corresponding' value to true once it has reached a certain point in the thread, then constantly check to see if the rest of the values are true. If so, enter the loop... An example

//above thread init stuff
oLock->lockForWrite();
abSync[iThreadNum] = true;  //iThreadNum = {0...3} depending on whats set
oLock->unlock();

bool bSynced = false;
while (!bSynced)
{
    oLock->lockForRead();
    if (abSync[0] && abSync[1] && abSync[2] && abSync[3])
        bSynced = true;
    oLock->unlock();
}

//below thread run and finish

Does the QReadWriteLock work as described above? Will it in fact lock the variable for the write (as each thread goes through) but not for the read? A quick look at the documentation suggests that QReadWriteLock will only block at lockForRead() if there is a write lock but not a read lock which is what I want above.

Also, I understand the above will suck down CPU cycles as its going through the loop and that is the wanted behavior. Using a Sleep is not good enough for our needs.