问:
Check if something in a dictionary is the same as the max value in that dictionary?
How can I check if something in a dictionary is the same as the max in that dictionary. In other words, get all the max values instead of the max value with lowest position.
I have this code which returns the max variable name and value:

```<code>d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark, 'g_codww2': g_codww2, 'g_bfront2': g_bfront2, 'g_reddead2': g_reddead2, 'g_fifa18': g_fifa18, 'g_motogp17': g_motogp17, 'g_elderscrolls': g_elderscrolls, 'g_crashbandicoot': g_crashbandicoot}
print("g_dirt4", g_dirt4, "g_destiny2", g_destiny2, "g_southpark", g_southpark, "g_codww2", g_codww2, "g_bfront2", g_bfront2, "g_reddead2", g_reddead2, "g_fifa18", g_fifa18, "g_motogp17", g_motogp17, "g_elderscrolls", g_elderscrolls, "g_crashbandicoot", g_crashbandicoot)
print (max(d.items(), key=lambda x: x[1]))
</code>```

Now it prints the variable with the highest value plus the value itself, but what if there are two or three variables with the same max value? I would like to print all of the max values.

Edit:

The user has to fill in a form, which adds values to the variables in the dictionary. When the user is done, there will be one, two or more variables with the highest value. For example, the code gives me this:

2017-06-08 15:05:43 g_dirt4 9 g_destiny2 8 g_southpark 5 g_codww2 8 g_bfront2 8 g_reddead2 7 g_fifa18 8 g_motogp17 9 g_elderscrolls 5 g_crashbandicoot 6
2017-06-08 15:05:43 ('g_dirt4', 9)
```

Now it tells me that g_dirt4 has the highest value of 9, but if you look at motogp17, it also had 9 but it doesn't get printed because it's at a higher position in the dictionary. So how do I print them both? And what if it has 3 variables with the same max value?

答:
Let me introduce you to a more complicated but more powerful answer.  If you sort your dictionary items, you can use itertools.groupby for some powerful results:

```<code>import itertools
foo = {"one": 1, "two": 2, "three": 3, "tres": 3, "dos": 2, "troi": 3}
sorted_kvp = sorted(foo.items(), key=lambda kvp: -kvp[1])
grouped = itertools.groupby(sorted_kvp, key=lambda kvp: kvp[1])
</code>```

The sorted line takes the key/value pairs of dictionary items and sorts them based on the value.  I put a - in front so that the values will end up being sorted descending.  The results of that line are:

>>> print(sorted_kvp)

[('tres', 3), ('troi', 3), ('three', 3), ('two', 2), ('dos', 2), ('one', 1)]

Note, as the comments said above, the order of the keys (in this case, 'tres', 'troi', and 'three', and then 'two' and 'dos', is arbitrary, since the order of the keys in the dictionary is arbitrary.

The itertools.groupby line makes groups out of the runs of data.  The lambda tells it to look at kvp[1] for each key-value pair, i.e. the value.

At the moment, you're only interested in the max, so you can then do this:

```<code>max, key_grouper = next(grouped)
print("{}: {}".format(max, list(key_grouper)))
</code>```

And get the following results:

3: [('tres', 3), ('troi', 3), ('three', 3)]

But if you wanted all the information sorted, instead, with this method, that's just as easy:

```<code>for value, grouper in grouped:
    print("{}: {}".format(value, list(grouper)))
</code>```

produces:

3: [('tres', 3), ('troi', 3), ('three', 3)]

2: [('two', 2), ('dos', 2)]

1: [('one', 1)]

One last note: you can use next or you can use the for loop, but using both will give you different results.  grouped is an iterator, and calling next on it moves it to its next result (and the for loop consumes the entire iterator, so a subsequent next(grouped) would cause a StopIteration exception).

Body:
How can I check if something in a dictionary is the same as the max in that dictionary. In other words, get all the max values instead of the max value with lowest position.
I have this code which returns the max variable name and value:

d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark, 'g_codww2': g_codww2, 'g_bfront2': g_bfront2, 'g_reddead2': g_reddead2, 'g_fifa18': g_fifa18, 'g_motogp17': g_motogp17, 'g_elderscrolls': g_elderscrolls, 'g_crashbandicoot': g_crashbandicoot}
print("g_dirt4", g_dirt4, "g_destiny2", g_destiny2, "g_southpark", g_southpark, "g_codww2", g_codww2, "g_bfront2", g_bfront2, "g_reddead2", g_reddead2, "g_fifa18", g_fifa18, "g_motogp17", g_motogp17, "g_elderscrolls", g_elderscrolls, "g_crashbandicoot", g_crashbandicoot)
print (max(d.items(), key=lambda x: x[1]))

Now it prints the variable with the highest value plus the value itself, but what if there are two or three variables with the same max value? I would like to print all of the max values.

Edit:

The user has to fill in a form, which adds values to the variables in the dictionary. When the user is done, there will be one, two or more variables with the highest value. For example, the code gives me this:

2017-06-08 15:05:43 g_dirt4 9 g_destiny2 8 g_southpark 5 g_codww2 8 g_bfront2 8 g_reddead2 7 g_fifa18 8 g_motogp17 9 g_elderscrolls 5 g_crashbandicoot 6
2017-06-08 15:05:43 ('g_dirt4', 9)

Now it tells me that g_dirt4 has the highest value of 9, but if you look at motogp17, it also had 9 but it doesn't get printed because it's at a higher position in the dictionary. So how do I print them both? And what if it has 3 variables with the same max value?

Body:
Let me introduce you to a more complicated but more powerful answer.  If you sort your dictionary items, you can use itertools.groupby for some powerful results:

import itertools
foo = {"one": 1, "two": 2, "three": 3, "tres": 3, "dos": 2, "troi": 3}
sorted_kvp = sorted(foo.items(), key=lambda kvp: -kvp[1])
grouped = itertools.groupby(sorted_kvp, key=lambda kvp: kvp[1])

The sorted line takes the key/value pairs of dictionary items and sorts them based on the value.  I put a - in front so that the values will end up being sorted descending.  The results of that line are:

>>> print(sorted_kvp)

[('tres', 3), ('troi', 3), ('three', 3), ('two', 2), ('dos', 2), ('one', 1)]

Note, as the comments said above, the order of the keys (in this case, 'tres', 'troi', and 'three', and then 'two' and 'dos', is arbitrary, since the order of the keys in the dictionary is arbitrary.

The itertools.groupby line makes groups out of the runs of data.  The lambda tells it to look at kvp[1] for each key-value pair, i.e. the value.

At the moment, you're only interested in the max, so you can then do this:

max, key_grouper = next(grouped)
print("{}: {}".format(max, list(key_grouper)))

And get the following results:

3: [('tres', 3), ('troi', 3), ('three', 3)]

But if you wanted all the information sorted, instead, with this method, that's just as easy:

for value, grouper in grouped:
    print("{}: {}".format(value, list(grouper)))

produces:

3: [('tres', 3), ('troi', 3), ('three', 3)]

2: [('two', 2), ('dos', 2)]

1: [('one', 1)]

One last note: you can use next or you can use the for loop, but using both will give you different results.  grouped is an iterator, and calling next on it moves it to its next result (and the for loop consumes the entire iterator, so a subsequent next(grouped) would cause a StopIteration exception).


来源: stackexchange

问:
How to detect ENTER keypress/ or the "GO" button in the Address Bar?
I want to detect the ENTER keypress of the Address Bar and also, the "Go(to the specified URL)" button using Javascript.
As per my previous efforts using "keycode==13" did not work as required.
say, in the following code:

```<code>window.onkeypress = testKeyEvent;

function testKeyEvent(e) {
    if (e.keyCode == 13) //We are using Enter key press event for test purpose.
    {
        alert('Enter key pressed');
    }
    else //If any other button pressed.
    {
        alert('Not Enter key pressed');
    }
}    </script>
</code>```

I want first the Alert box to be displayed,after I have typed any URL(valid or not) in the address box and Pressed ENTER/ Clicked GO button and then go to specified URL.

Is it Possible? I know I am missing out on a lot of things, Please mention about them.

答:
You can't detect the keystroke because it's outside your window, but you can detect navigation away from your page like</p>

```<code>window.onbeforeunload = function () {
    alert("Leaving page...");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to detect the ENTER keypress of the Address Bar and also, the "Go(to the specified URL)" button using Javascript.
As per my previous efforts using "keycode==13" did not work as required.
say, in the following code:

window.onkeypress = testKeyEvent;

function testKeyEvent(e) {
    if (e.keyCode == 13) //We are using Enter key press event for test purpose.
    {
        alert('Enter key pressed');
    }
    else //If any other button pressed.
    {
        alert('Not Enter key pressed');
    }
}    </script>

I want first the Alert box to be displayed,after I have typed any URL(valid or not) in the address box and Pressed ENTER/ Clicked GO button and then go to specified URL.

Is it Possible? I know I am missing out on a lot of things, Please mention about them.

Body:
You can't detect the keystroke because it's outside your window, but you can detect navigation away from your page like

window.onbeforeunload = function () {
    alert("Leaving page...");
}


问:
Joke generator with random jokes not working
I'm currently making myself a script on python that will pick jokes and display them to the user. I need to use a random picker to select one of the jokes on the list and display it. I have been trying this for a long time and can't seem to get it to work. Please help!

E.G:

```<code>import random

random.choice joke
print random joke
^^^^
</code>```

How can I do this?

答:
I'm assuming you have a list of jokes. Let's imagine this is called jokeList. Start with

```<code>from random import randint
</code>```

and then our program might look a little like this:

```<code>randChoice = randint(0, len(jokeList)-1)
joke = jokeList[randChoice]
print(joke)
</code>```

Body:
I'm currently making myself a script on python that will pick jokes and display them to the user. I need to use a random picker to select one of the jokes on the list and display it. I have been trying this for a long time and can't seem to get it to work. Please help!

E.G:

import random

random.choice joke
print random joke
^^^^

How can I do this?

Body:
I'm assuming you have a list of jokes. Let's imagine this is called jokeList. Start with

from random import randint

and then our program might look a little like this:

randChoice = randint(0, len(jokeList)-1)
joke = jokeList[randChoice]
print(joke)


问:
Solving sub-problems
When do I choose memoization over dynamic programming?

They both seem to possess identical time and space complexity.

What then would be the rules of thumb to prefer one over the other?

答:
Memoization is a technique used in dynamic programming, not a separate entity.  Time/space complexity depends on the algorithm and implementation.

Dynamic programming, in general, is a strategy of recognizing common sub-tasks in a job.  Instead of executing the sub-tasks multiple times, you use system resources other than execution cycles to capture the execution results for later use.

Typically, this is a simple matter of storing computation results to avoid duplication of computational effort.  In most cases, this involves storing functional results, indexed by the parameter values.  This is memoization.

In more detail ...

DP comes in two basic flavours: top-down and bottom-up.  The bottom-up method starts with the base case and works up to the requested result.  This is often implemented with a simple iteration loop and an array to store intermediate results.

The top-down method is memoization.  This breaks the original request into smaller problems, and recurs on each of those.  As it solves each sub-problem, it stores the result to be used by other branches needing the same result.

Title: Solving sub-problems


问:
DASK with local files on WORKER systems
I am working with mutiple systems as workers.
Each worker system has a part of the data locally stored. And I want the computation done by each worker on its respective file only.

I have tried using :

distributed.scheduler.decide_worker()

send_task_to_worker(worker, key)

but I could not automate assigning the task for each file.

Also, is there anyway I can access local files of the worker? Using tcp address, I only have access to a temp folder of the worker created for dask.

答:
You can target computations to run on certain workers using the workers= keyword to the various methods on the client.  See http://distributed.readthedocs.io/en/latest/locality.html#user-control for more information.

You might run a function on each of your workers that tells you which files are present:

```<code>>>> client.run(os.listdir, my_directory)
{'192.168.0.1:52523': ['myfile1.dat', 'myfile2.dat'],
 '192.168.0.2:4244': ['myfile3.dat'],
 '192.168.0.3:5515': ['myfile4.dat', 'myfile5.dat']}
</code>```

You might then submit computations to run on those workers specifically.

```<code>future = client.submit(load, 'myfile1.dat', workers='192.168.0.1:52523')
</code>```

If you are using dask.delayed you can also pass workers= to the `persist method.  See http://distributed.readthedocs.io/en/latest/locality.html#user-control for more information

Title: DASK with local files on WORKER systems

Body:
You can target computations to run on certain workers using the workers= keyword to the various methods on the client.  See http://distributed.readthedocs.io/en/latest/locality.html#user-control for more information.

You might run a function on each of your workers that tells you which files are present:

>>> client.run(os.listdir, my_directory)
{'192.168.0.1:52523': ['myfile1.dat', 'myfile2.dat'],
 '192.168.0.2:4244': ['myfile3.dat'],
 '192.168.0.3:5515': ['myfile4.dat', 'myfile5.dat']}

You might then submit computations to run on those workers specifically.

future = client.submit(load, 'myfile1.dat', workers='192.168.0.1:52523')

If you are using dask.delayed you can also pass workers= to the `persist method.  See http://distributed.readthedocs.io/en/latest/locality.html#user-control for more information


问:
Arithmetic overflow w/ bigints in SQL Server 2008
I'm having a problem with arithmetic overflow when converting to bigint in SQL Server 2008.  The following is confusing me.

This works:

```<code>select 58356453 * 228204732751
</code>```

Answer: 13317218761161292203

But, all other attempts that involve explicit conversion fail.

```<code>select convert(bigint, 58356453 * 228204732751)
</code>```

result: arithmetic overflow

```<code>begin
    declare @key bigint = 58356453,
        @workingVal bigint,
        @primeMultiplier1 bigint = 228204732751;
    set @workingVal = @key * @primeMultiplier1;
end;
</code>```

result: arithmetic overflow

What am I missing here?  I've also tried "cast(BigNumber as bigint)" (don't think it's any different from convert), and various combinations of conversion before/after arithmetic operations.

And, this is on Windows Server 2008 x64

答:
The maxiumum value for a bigint is

9223372036854775807

you're returning

13317218761161292203.

I suggest casting to a decimal that has enough precision.

ContentLicense: CC BY-SA 2.5

Body:
I'm having a problem with arithmetic overflow when converting to bigint in SQL Server 2008.  The following is confusing me.

This works:

select 58356453 * 228204732751

Answer: 13317218761161292203

But, all other attempts that involve explicit conversion fail.

select convert(bigint, 58356453 * 228204732751)

result: arithmetic overflow

begin
    declare @key bigint = 58356453,
        @workingVal bigint,
        @primeMultiplier1 bigint = 228204732751;
    set @workingVal = @key * @primeMultiplier1;
end;

result: arithmetic overflow

What am I missing here?  I've also tried "cast(BigNumber as bigint)" (don't think it's any different from convert), and various combinations of conversion before/after arithmetic operations.

And, this is on Windows Server 2008 x64


问:
jq - nested dictionary parser and extract key
I am trying to parse with jq the following structure:

```<code>{
    "a": {
        "sensitive": false,
        "type": "string",
        "value": "mykeypair"
    },
    "b": {
        "sensitive": false,
        "type": "string",
        "value": "123"
    }
}
</code>```

and get this as an output:

```<code>{
        "a": "mykeypair",
        "b": "123"
}
</code>```

I would like the key and as a value, the value of the field 'value'.
Any idea?
Cheers,

答:
If you're merely getting the value of every value in the root object, you could use map_values/1 to get those values.

```<code>map_values(.value)
</code>```

Body:
I am trying to parse with jq the following structure:

{
    "a": {
        "sensitive": false,
        "type": "string",
        "value": "mykeypair"
    },
    "b": {
        "sensitive": false,
        "type": "string",
        "value": "123"
    }
}

and get this as an output:

{
        "a": "mykeypair",
        "b": "123"
}

I would like the key and as a value, the value of the field 'value'.
Any idea?
Cheers,

Body:
If you're merely getting the value of every value in the root object, you could use map_values/1 to get those values.

map_values(.value)


问:
How to set a custom class UIButton with another object of the same class?
I have a UITableView with customs cells: ParagraphTableViewCell.

```<code>@IBDesignable
class ParagraphTableViewCell: UITableViewCell {

    weak var delegate: ParagraphProtocol?

    var paragraph:Paragraph!

    @IBInspectable @IBOutlet weak var dialogueLabel: UILabel!

    @IBInspectable @IBOutlet weak var choice1Button: ChoiceButton!
    @IBInspectable @IBOutlet weak var choice2Button: ChoiceButton!
    @IBInspectable @IBOutlet weak var choice3Button: ChoiceButton!
}
</code>```

ChoiceButton is a UIButton custom class:

```<code>class ChoiceButton: UIButton {

    var goToParagraphId: String!

    @IBInspectable var text: String? {
        didSet {
            self.setTitle(text, for: .normal)
            print("ChoiceButton didSet viewLabel, viewLabel = \(text!)")
        }
    }

    required init(text: String, goToParagraphId:String) {

        self.text = text
        self.goToParagraphId = goToParagraphId

        super.init(frame: .zero)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}
</code>```

For my project, I created an object Paragraph which define, amongst others,  the cell content.

```<code>class Paragraph: NSObject {

    var id:String!
    var dialogueLabel: UILabel!
    var choice1Button: ChoiceButton!
    var choice2Button: ChoiceButton!
    var choice3Button: ChoiceButton!

    init(dict: NSDictionary) {

        self.dialogueLabel = UILabel()
        self.dialogueLabel.text = dict["keyLabel"]! as! String

        if dict["button1"] != nil {
            self.choice1Button=ChoiceButton(text: dict["keyLabel"]! as! String, goToParagraphId: 1)
        }

        //do the same for the other ChoiceButton

}
</code>```

To populate my UITableView, I have a NSMutableArray of Paragraph objects.
In configureCell function, I need to set the ChoiceButton of the cell with the ChoiceButton of the Paragraph object.

```<code>  func configureCell(tableView: UITableView, cell: ParagraphTableViewCell, atIndexPath indexPath: IndexPath) {

        let paragraph = paragraphArray[indexPath.row] as! Paragraph
        cell.paragraph = paragraph

        //TO SET the ChoiceButton I tried :
        cell.choice1Button = paragraph.choice1Button // -> not worked

        //TO SET the ChoiceButton I tried also
        cell.choice1Button.goToParagraphId = paragraph.choice1Button.goToParagraphId
        cell.choice1Button.text = paragraph.choice1Button.text!
        // -> but the other properties of UIButton class are not set, as the state of the UIButton

        }
</code>```

I also to try to use NSCopying in the ChoiceButton class:

```<code>  func copy(with zone: NSZone? = nil) -> Any {

        let copy = ChoiceButton(text: text!, goToParagraphId: goToParagraphId)
        return copy
}
</code>```

I don't know how to link my ChoiceButton in my cell with the ChoiceButton in the paragraph object without losing UIButton properties.

答:
I updated my paragraph object, with an array dictionary, inside I store the data to set my buttons:

```<code>class Paragraph: NSObject {

   var id:String!
   var dialogueLabel: UILabel!
   var choiceButtonArray:[Dictionary<String, String>] = []

   init(dict: NSDictionary) {

       for i in 0...2 {
            self.choiceButtonArray.insert(["text":dict[String(i)]["keyLabel"], "goToParagraphId":dict[String(i)]["nextParagraphId"], at: i)
        }
    }
}
</code>```

I updated my UIButton subclass, with a new func:

```<code> func setInfos(text: String, goToParagraphId:String, tag:Int) {

    self.text = text
    self.goToParagraphId = goToParagraphId
}
</code>```

In my cell I use my array of dictionary to set the buttons' info:

```<code>choiceButton.setInfos(text: self.paragraph.choiceButtonArray[button]["text"]!, goToParagraphId: self.paragraph.choiceButtonArray[button]["goToParagraphId"]!)
</code>```

Body:
I have a UITableView with customs cells: ParagraphTableViewCell.

@IBDesignable
class ParagraphTableViewCell: UITableViewCell {

    weak var delegate: ParagraphProtocol?

    var paragraph:Paragraph!

    @IBInspectable @IBOutlet weak var dialogueLabel: UILabel!

    @IBInspectable @IBOutlet weak var choice1Button: ChoiceButton!
    @IBInspectable @IBOutlet weak var choice2Button: ChoiceButton!
    @IBInspectable @IBOutlet weak var choice3Button: ChoiceButton!
}

ChoiceButton is a UIButton custom class:

class ChoiceButton: UIButton {

    var goToParagraphId: String!

    @IBInspectable var text: String? {
        didSet {
            self.setTitle(text, for: .normal)
            print("ChoiceButton didSet viewLabel, viewLabel = \(text!)")
        }
    }

    required init(text: String, goToParagraphId:String) {

        self.text = text
        self.goToParagraphId = goToParagraphId

        super.init(frame: .zero)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

For my project, I created an object Paragraph which define, amongst others,  the cell content.

class Paragraph: NSObject {

    var id:String!
    var dialogueLabel: UILabel!
    var choice1Button: ChoiceButton!
    var choice2Button: ChoiceButton!
    var choice3Button: ChoiceButton!

    init(dict: NSDictionary) {

        self.dialogueLabel = UILabel()
        self.dialogueLabel.text = dict["keyLabel"]! as! String

        if dict["button1"] != nil {
            self.choice1Button=ChoiceButton(text: dict["keyLabel"]! as! String, goToParagraphId: 1)
        }

        //do the same for the other ChoiceButton

}

To populate my UITableView, I have a NSMutableArray of Paragraph objects.
In configureCell function, I need to set the ChoiceButton of the cell with the ChoiceButton of the Paragraph object.

  func configureCell(tableView: UITableView, cell: ParagraphTableViewCell, atIndexPath indexPath: IndexPath) {

        let paragraph = paragraphArray[indexPath.row] as! Paragraph
        cell.paragraph = paragraph

        //TO SET the ChoiceButton I tried :
        cell.choice1Button = paragraph.choice1Button // -> not worked

        //TO SET the ChoiceButton I tried also
        cell.choice1Button.goToParagraphId = paragraph.choice1Button.goToParagraphId
        cell.choice1Button.text = paragraph.choice1Button.text!
        // -> but the other properties of UIButton class are not set, as the state of the UIButton

        }

I also to try to use NSCopying in the ChoiceButton class:

  func copy(with zone: NSZone? = nil) -> Any {

        let copy = ChoiceButton(text: text!, goToParagraphId: goToParagraphId)
        return copy
}

I don't know how to link my ChoiceButton in my cell with the ChoiceButton in the paragraph object without losing UIButton properties.

Body:
I updated my paragraph object, with an array dictionary, inside I store the data to set my buttons:

class Paragraph: NSObject {

   var id:String!
   var dialogueLabel: UILabel!
   var choiceButtonArray:[Dictionary<String, String>] = []

   init(dict: NSDictionary) {

       for i in 0...2 {
            self.choiceButtonArray.insert(["text":dict[String(i)]["keyLabel"], "goToParagraphId":dict[String(i)]["nextParagraphId"], at: i)
        }
    }
}

I updated my UIButton subclass, with a new func:

 func setInfos(text: String, goToParagraphId:String, tag:Int) {

    self.text = text
    self.goToParagraphId = goToParagraphId
}

In my cell I use my array of dictionary to set the buttons' info:

choiceButton.setInfos(text: self.paragraph.choiceButtonArray[button]["text"]!, goToParagraphId: self.paragraph.choiceButtonArray[button]["goToParagraphId"]!)


问:
Random Number Generator is repetitive in simulink
How does one ensure that a model in the form of simulink generated executable "standalone executable" generate different random sequence every time the executable is executed.
I added rng('shuffle') in the initFcn Callbacks, but that didn't do the trick.

答:
I think I found your solution - the rand function always generates the same numbers every time MATLAB is loaded (it gets initialized with a 0 seed).  That's why you get different outputs (re)running from MATLAB than when the exe is built.  The workaround is to add this line to your code (which will instead generate a random seed based on the system clock) ONLY ONCE IN YOUR CODE before your calls to rand, randn, or randi:

```<code>%THIS IS THE SOLUTION GIVEN FOR AN EXE (UPDATED FOR NEWER MATLAB VERSIONS)
reset(RandStream.getGlobalStream,sum(100*clock))

%OR (THIS IS INSIDE MATLAB, HAVEN'T TRIED WITH AN EXE)
RandStream.setGlobalStream(RandStream('mt19937ar','seed',sum(100*clock))); %note you can use 6 other random number generators, type RandStream.list for more
</code>```

See here for more details: https://www.mathworks.com/matlabcentral/answers/104306-why-does-my-compiled-rand-function-give-the-same-values-every-time-i-run-my-matlab-generated-standal

https://www.mathworks.com/matlabcentral/answers/336-why-do-i-get-the-same-numbers-in-randn-function?s_tid=answers_rc1-1_p1_Topic

Now if you're using MATLAB coder you're supposed to do something like this (if clock isn't available):

```<code>coder.cinclude('"time.h"')
sd=0;
sd=coder.ceval('time',[]);
rng(sd);
</code>```

All of these solutions work on the rand, randn, randi functions.

Body:
I think I found your solution - the rand function always generates the same numbers every time MATLAB is loaded (it gets initialized with a 0 seed).  That's why you get different outputs (re)running from MATLAB than when the exe is built.  The workaround is to add this line to your code (which will instead generate a random seed based on the system clock) ONLY ONCE IN YOUR CODE before your calls to rand, randn, or randi:

%THIS IS THE SOLUTION GIVEN FOR AN EXE (UPDATED FOR NEWER MATLAB VERSIONS)
reset(RandStream.getGlobalStream,sum(100*clock))

%OR (THIS IS INSIDE MATLAB, HAVEN'T TRIED WITH AN EXE)
RandStream.setGlobalStream(RandStream('mt19937ar','seed',sum(100*clock))); %note you can use 6 other random number generators, type RandStream.list for more

See here for more details: https://www.mathworks.com/matlabcentral/answers/104306-why-does-my-compiled-rand-function-give-the-same-values-every-time-i-run-my-matlab-generated-standal

https://www.mathworks.com/matlabcentral/answers/336-why-do-i-get-the-same-numbers-in-randn-function?s_tid=answers_rc1-1_p1_Topic

Now if you're using MATLAB coder you're supposed to do something like this (if clock isn't available):

coder.cinclude('"time.h"')
sd=0;
sd=coder.ceval('time',[]);
rng(sd);

All of these solutions work on the rand, randn, randi functions.


问:
More than 5300 message to my website had a JS content
I create a website, and I receive more than 5300 message in 1 day, had a JavaScript content

I resolve the problem to stop the messages adding the CAPTCHA

But I want to know what's is this

The content of message is:

```<code>javascript:window.top._arachni_js_namespace_taint_tracer.log_execution_flow_sink()
</code>```

答: Someone was probably using Arachni to check your site for vulnerabilities.</p>

ContentLicense: CC BY-SA 4.0

Body:
I create a website, and I receive more than 5300 message in 1 day, had a JavaScript content

I resolve the problem to stop the messages adding the CAPTCHA

But I want to know what's is this

The content of message is:

javascript:window.top._arachni_js_namespace_taint_tracer.log_execution_flow_sink()


问:
WPF ListView: Custom Scrolling Behavior
Is there a way to keep a ListView scrolling vertically as data is updated via a binding to the ListView's ItemsSource property? I can't seem to find a property in either the ListView or its underlying GridView control to achieve the desired result. I would like it to scroll so that the newest information is always visible to the user. A scroll bar already appears as the rows add to the control but the most current row is not presented.

Should I consider using a different type of control that has auto-scroll capability? I only have two columns: one contains DateTimes and the other contains a simple string. I'm starting to think that my control choice may be too limited.

My XAML looks roughly like this:

```<code><ListView ItemsSource="{Binding Updates}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Timestamp" DisplayMemberBinding="{Binding TimeStamp}"/>
            <GridViewColumn DisplayMemberBinding="{Binding UpdateString}" />
        </GridView>
    </ListView.View>
</ListView>
</code>```

答:
A Listview has a method called ScrollIntoView(object item).

This will scroll the Listview to the position where the specified item is.

When you have a collection that is binded to the Listview, you can call this method when your collection has changed, something like:

```<code>private void myCollectionChanged()
{
    myListView.ScrollIntoView(myCollection.Last());
}
</code>```

Title: WPF ListView: Custom Scrolling Behavior

Body:
Is there a way to keep a ListView scrolling vertically as data is updated via a binding to the ListView's ItemsSource property? I can't seem to find a property in either the ListView or its underlying GridView control to achieve the desired result. I would like it to scroll so that the newest information is always visible to the user. A scroll bar already appears as the rows add to the control but the most current row is not presented.

Should I consider using a different type of control that has auto-scroll capability? I only have two columns: one contains DateTimes and the other contains a simple string. I'm starting to think that my control choice may be too limited.

My XAML looks roughly like this:

<ListView ItemsSource="{Binding Updates}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Timestamp" DisplayMemberBinding="{Binding TimeStamp}"/>
            <GridViewColumn DisplayMemberBinding="{Binding UpdateString}" />
        </GridView>
    </ListView.View>
</ListView>

Body:
A Listview has a method called ScrollIntoView(object item).

This will scroll the Listview to the position where the specified item is.

When you have a collection that is binded to the Listview, you can call this method when your collection has changed, something like:

private void myCollectionChanged()
{
    myListView.ScrollIntoView(myCollection.Last());
}


问:
django - Can't login after creating user
I can't login after create user. Here's my code:

```<code>class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        username = validated_data.pop('username')
        password = validated_data.pop('password')
        return User.objects.create_user(username, password, **validated_data)
</code>```

My api:

```<code>from django.contrib.auth.models import User
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
</code>```

any help is appreciated.
Updated: Here's my test case

```<code>class UserAPITestCase(APITestCase):

def setUp(self):
    self.client = APIClient()

    self.user = User.objects.create_user(
        username='anhnguyen',
        password=PASSWORD,
    )
    self.user.save()

def test_create_user(self):
    data = {
        'username': 'khoavo',
        'password': PASSWORD,
    }

    user = self.client.post(URL, data, format='json')
    self.assertEqual(user.status_code, status.HTTP_201_CREATED)

    url = reverse(URL1, args=[2])
    response = self.client.get(url)
    self.assertEqual(response.status_code, status.HTTP_200_OK)

    login = self.client.login(username='khoavo', password=PASSWORD)
    self.assertTrue(login)
</code>```

The test case failed at login statement after creating a user

答:
The create_user method takes email as its second argument. You could fix the problem by changing password to a keyword argument:

```<code>return User.objects.create_user(username, password=password, **validated_data)
</code>```

Body:
I can't login after create user. Here's my code:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        username = validated_data.pop('username')
        password = validated_data.pop('password')
        return User.objects.create_user(username, password, **validated_data)

My api:

from django.contrib.auth.models import User
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

any help is appreciated.
Updated: Here's my test case

class UserAPITestCase(APITestCase):

def setUp(self):
    self.client = APIClient()

    self.user = User.objects.create_user(
        username='anhnguyen',
        password=PASSWORD,
    )
    self.user.save()

def test_create_user(self):
    data = {
        'username': 'khoavo',
        'password': PASSWORD,
    }

    user = self.client.post(URL, data, format='json')
    self.assertEqual(user.status_code, status.HTTP_201_CREATED)

    url = reverse(URL1, args=[2])
    response = self.client.get(url)
    self.assertEqual(response.status_code, status.HTTP_200_OK)

    login = self.client.login(username='khoavo', password=PASSWORD)
    self.assertTrue(login)

The test case failed at login statement after creating a user

Body:
The create_user method takes email as its second argument. You could fix the problem by changing password to a keyword argument:

return User.objects.create_user(username, password=password, **validated_data)


问:
Server Error (500)
This is my JS code in my index.php:

```<code>$('#registerForm').on('click', function(){
  event.preventDefault();
  var regusername = $('#register_username').val();
  var regpassword = $('#register_password').val();
  var regemail = $('#register_email').val();
  $.ajax({
    url:"register.php",
    method:"POST",
    data:{regusername:regusername, regemail:regemail, regpassword: regpassword},
    success:function(data)
    {
      if(data == 'Yes'){
        $('#login').hide();
        location.replace("login.php");
      }
    }
  })
});
});
</code>```

And this is my register.php where I update the database :

```<code>session_start();
if(!empty($_POST["regusername"]))
{
  $connect = mysqli_connect("xxx.xxx.xx.xx", "", "", "" );
  $output = '';
  $username = mysqli_real_escape_string($connect, $_POST["regusername"]);
  $email    = mysqli_real_escape_string($connect, $_POST["regemail"]);
  $password = mysqli_real_escape_string($connect, $_POST["regpassword"]);

  $query = "INSERT INTO users(username, password, email) VALUES('$username',
  '$password', '$email')";
  if(mysqli_query($connect, $query))
  {
    echo 'Yes';
  }
  $_SESSION["regusername"]=$_POST["regusername"];
}
</code>```

I'm getting a server error in my register.php and I can't figure out where.

Also, is it better to use .serialize() to send data via AJAX instead of this?

Edit: Fixed register.php, thanks. Is it better to use serialize() than sending each variable individually?

答:
because you are referencing the input elements from the dom, not the values.</p>

```<code>data:{register_username:register_username, register_email:register_email, register_password: register_password}
</code>```

Title: Server Error (500)

Body:
This is my JS code in my index.php:

$('#registerForm').on('click', function(){
  event.preventDefault();
  var regusername = $('#register_username').val();
  var regpassword = $('#register_password').val();
  var regemail = $('#register_email').val();
  $.ajax({
    url:"register.php",
    method:"POST",
    data:{regusername:regusername, regemail:regemail, regpassword: regpassword},
    success:function(data)
    {
      if(data == 'Yes'){
        $('#login').hide();
        location.replace("login.php");
      }
    }
  })
});
});

And this is my register.php where I update the database :

session_start();
if(!empty($_POST["regusername"]))
{
  $connect = mysqli_connect("xxx.xxx.xx.xx", "", "", "" );
  $output = '';
  $username = mysqli_real_escape_string($connect, $_POST["regusername"]);
  $email    = mysqli_real_escape_string($connect, $_POST["regemail"]);
  $password = mysqli_real_escape_string($connect, $_POST["regpassword"]);

  $query = "INSERT INTO users(username, password, email) VALUES('$username',
  '$password', '$email')";
  if(mysqli_query($connect, $query))
  {
    echo 'Yes';
  }
  $_SESSION["regusername"]=$_POST["regusername"];
}

I'm getting a server error in my register.php and I can't figure out where.

Also, is it better to use .serialize() to send data via AJAX instead of this?

Edit: Fixed register.php, thanks. Is it better to use serialize() than sending each variable individually?

Body:
because you are referencing the input elements from the dom, not the values.

data:{register_username:register_username, register_email:register_email, register_password: register_password}


问:
Sending Mail via SMTP in C# using BCC without TO
I am trying to use the System.Net.Mail.MailMessage class in C# to create an email that is sent to a list of email addresses all via BCC. I do not want to include a TO address, but it seems that I must because I get an exception if I use an empty string for the TO address in the MailMessage constructor. The error states:

```<code>ArgumentException
The parameter 'addresses' cannot be an empty string.
Parameter name: addresses
</code>```

Surely it is possible to send an email using only BCC as this is not a limitation of SMTP.

Is there a way around this?

答:
You can use a temporary fake address then remove it just after:</p>

```<code>MailMessage msg = new MailMessage(from, "fake@example.com");
msg.To.Clear();
foreach (string email in bcc.Split(';').Select(x => x.Trim()).Where(x => x != ""))
{
     msg.Bcc.Add(email);
}
</code>```

OwnerDisplayName: Brad Barker

Body:
I am trying to use the System.Net.Mail.MailMessage class in C# to create an email that is sent to a list of email addresses all via BCC. I do not want to include a TO address, but it seems that I must because I get an exception if I use an empty string for the TO address in the MailMessage constructor. The error states:

ArgumentException
The parameter 'addresses' cannot be an empty string.
Parameter name: addresses

Surely it is possible to send an email using only BCC as this is not a limitation of SMTP.

Is there a way around this?

Body:
You can use a temporary fake address then remove it just after:

MailMessage msg = new MailMessage(from, "fake@example.com");
msg.To.Clear();
foreach (string email in bcc.Split(';').Select(x => x.Trim()).Where(x => x != ""))
{
     msg.Bcc.Add(email);
}


问:
filtering out specific keys in an object
I am writing out the key/value pair of an object.  I'm trying to filter out 2 of the keys in the object like this:

```<code>{Object.entries(params.char).filter('Attribute1').filter('Attribute2').map(([key,value], index) => <Text key={key}>{key}</Text>)}
</code>```

Here is one of the objects in "paramas":

```<code>{
    id: 1,
    Name: "Drax Bravesword",
    Rating: "*****",
    XP: 392
Age: 34
    Avatar: require('./images/profile1.png'),
    Map: require('./images/map_1.png'),
    Attribute1: "Power",
    Attribute2: "Knowledge",
    Attribute3: "Family"
}
</code>```

However when I run this, I get this error:

"Array.prototype.filter callback must be a function"

I'm not quite sure how to fix this, but is there a way to fix it or am I doing this all wrong?

Thanks!

答:
From what I'm understanding, you want to only make text elements for attributes 1 and 2, you won't have to chain the filters...you can do it in one go:</p>

```<code>{Object.entries(params.char).filter(touple =>
   (touple[0] === 'Attribute1' || touple[0] === 'Attribute2')).map(touple => <Text key={touple[0]}>{touple[0]}</Text>)}
</code>```

Body:
I am writing out the key/value pair of an object.  I'm trying to filter out 2 of the keys in the object like this:

{Object.entries(params.char).filter('Attribute1').filter('Attribute2').map(([key,value], index) => <Text key={key}>{key}</Text>)}

Here is one of the objects in "paramas":

{
    id: 1,
    Name: "Drax Bravesword",
    Rating: "*****",
    XP: 392
Age: 34
    Avatar: require('./images/profile1.png'),
    Map: require('./images/map_1.png'),
    Attribute1: "Power",
    Attribute2: "Knowledge",
    Attribute3: "Family"
}

However when I run this, I get this error:

"Array.prototype.filter callback must be a function"

I'm not quite sure how to fix this, but is there a way to fix it or am I doing this all wrong?

Thanks!

Body:
From what I'm understanding, you want to only make text elements for attributes 1 and 2, you won't have to chain the filters...you can do it in one go:

{Object.entries(params.char).filter(touple =>
   (touple[0] === 'Attribute1' || touple[0] === 'Attribute2')).map(touple => <Text key={touple[0]}>{touple[0]}</Text>)}


问:
\377\376 Appended to file (Windows -> Unix)
I have an SSIS package that performs the following.

Run a SQL script

Export the results to a flat file (UTF-8 encoded, ; delimited, and \n for new lines)

FTP results to a Solaris machine (binary format)

The problem is that when the file shows up on my Solaris box, it has the following at the start of the file.

\377\376

I have tried dos2unix, and it still has not corrected the issue. In fact, it changes the \377\376 to \227\226, not very helpful.

Is there a way to remove these characters from my file? When they are there, they mess with grep and other Unix tools, like head.

答:
As the previews answers stated, using dos2unix made the job. In my case I used:

```<code>dos2unix.exe -r -v -f -D utf8 <FileName>
</code>```

in which:

-r, --remove-bom      remove Byte Order Mark (default)

-v,  --verbose        verbose operation

-f, --force           force conversion of binary files

-D, --display-enc     set encoding of displayed text messages encoding            ansi, unicode, utf8, default to ansi

And the BOM character was removed.

Body:
As the previews answers stated, using dos2unix made the job. In my case I used:

dos2unix.exe -r -v -f -D utf8 <FileName>

in which:

-r, --remove-bom      remove Byte Order Mark (default)

-v,  --verbose        verbose operation

-f, --force           force conversion of binary files

-D, --display-enc     set encoding of displayed text messages encoding            ansi, unicode, utf8, default to ansi

And the BOM character was removed.


问:
Looking at Sorts - Quicksort Iterative?
I'm looking at all different sorts. Note that this is not homework (I'm in the midst of finals) I'm just looking to be prepared if that sort of thing would pop up.
I was unable to find a reliable method of doing a quicksort iteratively. Is it possible and, if so, how?</p>

答:
```<code>#include <stdio.h>
#include <conio.h>

#define MAXELT          100
#define INFINITY        32760         // numbers in list should not exceed
                                      // this. change the value to suit your
                                      // needs
#define SMALLSIZE       10            // not less than 3
#define STACKSIZE       100           // should be ceiling(lg(MAXSIZE)+1)

int list[MAXELT+1];                   // one extra, to hold INFINITY

struct {                              // stack element.
        int a,b;
} stack[STACKSIZE];

int top=-1;                           // initialise stack

int main()                           // overhead!
{
    int i=-1,j,n;
    char t[10];
    void quicksort(int);

    do {
        if (i!=-1)
            list[i++]=n;
        else
            i++;
        printf("Enter the numbers <End by #>: ");
        fflush(stdin);
        scanf("%[^\n]",t);
        if (sscanf(t,"%d",&n)<1)
        break;
    } while (1);

    quicksort(i-1);

    printf("\nThe list obtained is ");
    for (j=0;j<i;j++)
        printf("\n %d",list[j]);

    printf("\n\nProgram over.");
    getch();
    return 0;       // successful termination.
}

void interchange(int *x,int *y)        // swap
{
    int temp;

    temp=*x;
    *x=*y;
    *y=temp;
}

void split(int first,int last,int *splitpoint)
{
    int x,i,j,s,g;

    // here, atleast three elements are needed
    if (list[first]<list[(first+last)/2]) {  // find median
        s=first;
        g=(first+last)/2;
    }
    else {
        g=first;
        s=(first+last)/2;
    }
    if (list[last]<=list[s])
        x=s;
    else if (list[last]<=list[g])
        x=last;
    else
        x=g;
    interchange(&list[x],&list[first]);      // swap the split-point element
                                             // with the first
    x=list[first];
    i=first+1;                               // initialise
    j=last+1;
    while (i<j) {
        do {                                 // find j
            j--;
        } while (list[j]>x);
        do {
            i++;                             // find i
        } while (list[i]<x);
        interchange(&list[i],&list[j]);      // swap
    }
    interchange(&list[i],&list[j]);          // undo the extra swap
    interchange(&list[first],&list[j]);      // bring the split-point
                                             // element to the first
    *splitpoint=j;
}

void push(int a,int b)                        // push
{
    top++;
    stack[top].a=a;
    stack[top].b=b;
}

void pop(int *a,int *b)                       // pop
{
    *a=stack[top].a;
    *b=stack[top].b;
    top--;
}

void insertion_sort(int first,int last)
{
    int i,j,c;

    for (i=first;i<=last;i++) {
        j=list[i];
        c=i;
        while ((list[c-1]>j)&&(c>first)) {
            list[c]=list[c-1];
            c--;
        }
        list[c]=j;
    }
}

void quicksort(int n)
{
    int first,last,splitpoint;

    push(0,n);
    while (top!=-1) {
        pop(&first,&last);
        for (;;) {
            if (last-first>SMALLSIZE) {
                // find the larger sub-list
                split(first,last,&splitpoint);
                // push the smaller list
                if (last-splitpoint<splitpoint-first) {
                    push(first,splitpoint-1);
                    first=splitpoint+1;
                }
                else {
                    push(splitpoint+1,last);
                    last=splitpoint-1;
                }
            }
            else {  // sort the smaller sub-lists
                    // through insertion sort
                insertion_sort(first,last);
                break;
            }
        }
    }                        // iterate for larger list
}

// End of code.
</code>```

taken from here

Title: Looking at Sorts - Quicksort Iterative?

Body:
#include <stdio.h>
#include <conio.h>

#define MAXELT          100
#define INFINITY        32760         // numbers in list should not exceed
                                      // this. change the value to suit your
                                      // needs
#define SMALLSIZE       10            // not less than 3
#define STACKSIZE       100           // should be ceiling(lg(MAXSIZE)+1)

int list[MAXELT+1];                   // one extra, to hold INFINITY

struct {                              // stack element.
        int a,b;
} stack[STACKSIZE];

int top=-1;                           // initialise stack

int main()                           // overhead!
{
    int i=-1,j,n;
    char t[10];
    void quicksort(int);

    do {
        if (i!=-1)
            list[i++]=n;
        else
            i++;
        printf("Enter the numbers <End by #>: ");
        fflush(stdin);
        scanf("%[^\n]",t);
        if (sscanf(t,"%d",&n)<1)
        break;
    } while (1);

    quicksort(i-1);

    printf("\nThe list obtained is ");
    for (j=0;j<i;j++)
        printf("\n %d",list[j]);

    printf("\n\nProgram over.");
    getch();
    return 0;       // successful termination.
}

void interchange(int *x,int *y)        // swap
{
    int temp;

    temp=*x;
    *x=*y;
    *y=temp;
}

void split(int first,int last,int *splitpoint)
{
    int x,i,j,s,g;

    // here, atleast three elements are needed
    if (list[first]<list[(first+last)/2]) {  // find median
        s=first;
        g=(first+last)/2;
    }
    else {
        g=first;
        s=(first+last)/2;
    }
    if (list[last]<=list[s])
        x=s;
    else if (list[last]<=list[g])
        x=last;
    else
        x=g;
    interchange(&list[x],&list[first]);      // swap the split-point element
                                             // with the first
    x=list[first];
    i=first+1;                               // initialise
    j=last+1;
    while (i<j) {
        do {                                 // find j
            j--;
        } while (list[j]>x);
        do {
            i++;                             // find i
        } while (list[i]<x);
        interchange(&list[i],&list[j]);      // swap
    }
    interchange(&list[i],&list[j]);          // undo the extra swap
    interchange(&list[first],&list[j]);      // bring the split-point
                                             // element to the first
    *splitpoint=j;
}

void push(int a,int b)                        // push
{
    top++;
    stack[top].a=a;
    stack[top].b=b;
}

void pop(int *a,int *b)                       // pop
{
    *a=stack[top].a;
    *b=stack[top].b;
    top--;
}

void insertion_sort(int first,int last)
{
    int i,j,c;

    for (i=first;i<=last;i++) {
        j=list[i];
        c=i;
        while ((list[c-1]>j)&&(c>first)) {
            list[c]=list[c-1];
            c--;
        }
        list[c]=j;
    }
}

void quicksort(int n)
{
    int first,last,splitpoint;

    push(0,n);
    while (top!=-1) {
        pop(&first,&last);
        for (;;) {
            if (last-first>SMALLSIZE) {
                // find the larger sub-list
                split(first,last,&splitpoint);
                // push the smaller list
                if (last-splitpoint<splitpoint-first) {
                    push(first,splitpoint-1);
                    first=splitpoint+1;
                }
                else {
                    push(splitpoint+1,last);
                    last=splitpoint-1;
                }
            }
            else {  // sort the smaller sub-lists
                    // through insertion sort
                insertion_sort(first,last);
                break;
            }
        }
    }                        // iterate for larger list
}

// End of code.

taken from here


问:
Android make view height 50% of screen width
I wish to make a view with the width to be match_parent, but the height to be 50% of the width.

How do I do it?

Is the only way to do it through java code inside the activity? I'll have to read the screen width and set the height that way.

答:
try this way, hope this will help you.

```<code>Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int s_width = size.x;
</code>```

here s_width is your Device Screen width, now you can pass  match_parent as width of your view and (s_width/2) as height of View.

Body:
try this way, hope this will help you.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int s_width = size.x;

here s_width is your Device Screen width, now you can pass  match_parent as width of your view and (s_width/2) as height of View.


问:
Getting unit test coverage working with Angular 4, Webpack 2, Karma, and Jasmine
I have an app that uses Webpack, Angular 4 and ES6 modules. The app works as expected.

I also have unit tests setup using Karma and Jasmine. As part of the test setup I have a test-main.js which is as follows:

```<code>Error.stackTraceLimit = Infinity;

import 'core-js/es6';
import 'core-js/es7/reflect';
import 'reflect-metadata';
import 'zone.js';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/proxy';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';

import {TestBed} from '@angular/core/testing';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing';

let appContext = require.context('./', true, /\.spec\.js/);

appContext.keys().forEach(appContext);

TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
</code>```

The unit tests run as expected.

I am trying to setup a coverage report, but the best I have been able to achieve is a coverage report where the entire Webpack-generated bundle is instrumented and reported in the coverage report. This is not entirely useful, as you can imagine.

I've tried using the babel-plugin-istanbul and also the istanbul-instrumenter-loader and I either get my entire bundle file in the coverage report, or no report at all. I don't see any errors, and my tests continue to run as expected.

Here is my karma.conf.js file (with everything to do with coverage removed as it was not working):

```<code>// Karma configuration
// Generated on Thu May 04 2017 13:00:28 GMT+0100 (GMT Daylight Time)
'use strict';

const webpack = require('webpack');
const path = require('path');

let reporters = ['progress'],
    singleRunSwitch = true,
    browsers = ['ChromeHeadless'];

function isDebug(argument) {
    return argument === 'debug';
}

if (process.argv.some(isDebug)) {
    reporters = ['progress'];
    singleRunSwitch = false;
    browsers = ['Chrome'];
}

module.exports = function(config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine'],
        files: [
            { pattern: './test-main.js' }
        ],
        exclude: [],
        preprocessors: {
            './test-main.js': ['webpack', 'sourcemap']
        },
        reporters: reporters,
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: browsers,

        customLaunchers: {
            ChromeHeadless: {
                base: 'Chrome',
                flags: [
                  '--headless',
                  ' --remote-debugging-port=9222',
                  '--disable-gpu',
                  '--disable-plugins',
                  '--window-size=0,0',
                  '--window-position=-9999,0'
                ],
            },
        },
        singleRun: singleRunSwitch,
        concurrency: Infinity,

        webpack: {
            module: {
                rules: [{
                    test: /\.js$/,
                    exclude: path.join(__dirname, '../node_modules/'),
                    use: [{
                        loader: 'babel-loader',
                        options: {
                            presets: ['es2015']
                        }
                    }]
                }]
            },
            devtool: 'inline-source-map',
            plugins: [
                new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname))
            ]
        },

        webpackMiddleware: {
            stats: 'errors-only'
        },

        webpackServer: {
            noInfo: true
        }

    });
}
</code>```

Can anyone advise which plugins I need to use and how I should configure them please?

答:
I got it working, I used Istanbul and istanbul-instrumenter-loader - both installed via NPM. My karma.conf.js file now looks like this:

```<code>// Karma configuration
// Generated on Thu May 04 2017 13:00:28 GMT+0100 (GMT Daylight Time)
'use strict';

const webpack = require('webpack');
const path = require('path');

let reporters = ['progress', 'coverage'],
    singleRunSwitch = true,
    browsers = ['ChromeHeadless'];

function isDebug(argument) {
    return argument === 'debug';
}

if (process.argv.some(isDebug)) {
    reporters = ['progress'];
    singleRunSwitch = false;
    browsers = ['Chrome'];
}

module.exports = function(config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine'],
        files: [
            { pattern: './test-main.js' }
        ],
        exclude: [],
        preprocessors: {
            './test-main.js': ['webpack', 'sourcemap']
        },
        reporters: reporters,
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: browsers,
        customLaunchers: {
            ChromeHeadless: {
                base: 'Chrome',
                flags: [
                  '--headless',
                  '--remote-debugging-port=9222',
                  '--disable-gpu',
                  '--disable-plugins',
                  '--window-size=0,0',
                  '--window-position=-9999,0'
                ],
            },
        },
        singleRun: singleRunSwitch,
        concurrency: Infinity,
        webpack: {
            module: {
                rules: [{
                    test: /\.spec.js$/,
                    exclude: [path.join(__dirname, '../node_modules/'), /\.html$/],
                    use: [{
                        loader: 'babel-loader',
                        options: { presets: ['es2015'] }
                    }]
                }, {
                    test: /\.js$/,
                    exclude: [path.join(__dirname, '../node_modules/'), /\.spec.js$/, /\.html$/, /test-main.js/],
                    use: [{
                        loader: 'istanbul-instrumenter-loader',
                    }, {
                        loader: 'babel-loader',
                        options: { presets: ['es2015'] }
                    }]
                }]
            },
            devtool: 'inline-source-map',
            plugins: [
                new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname))
            ]
        },
        webpackMiddleware: {
            stats: 'errors-only'
        },
        webpackServer: {
            noInfo: true
        }
    });
}
</code>```

The configuration was actually quite straight-forward; I had to add a 'coverage' reporter (but not when debugging), and had to add a new module.rules Webpack configuration - there are actually two configs here; I had to run the spec files through Babel separately from the rest of the .js files, and then add the instanbul-intrumenter to the rules array for .js files except *.spec.js (plus exclude a bunch of things!)

Body:
I have an app that uses Webpack, Angular 4 and ES6 modules. The app works as expected.

I also have unit tests setup using Karma and Jasmine. As part of the test setup I have a test-main.js which is as follows:

Error.stackTraceLimit = Infinity;

import 'core-js/es6';
import 'core-js/es7/reflect';
import 'reflect-metadata';
import 'zone.js';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/proxy';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';

import {TestBed} from '@angular/core/testing';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing';

let appContext = require.context('./', true, /\.spec\.js/);

appContext.keys().forEach(appContext);

TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());

The unit tests run as expected.

I am trying to setup a coverage report, but the best I have been able to achieve is a coverage report where the entire Webpack-generated bundle is instrumented and reported in the coverage report. This is not entirely useful, as you can imagine.

I've tried using the babel-plugin-istanbul and also the istanbul-instrumenter-loader and I either get my entire bundle file in the coverage report, or no report at all. I don't see any errors, and my tests continue to run as expected.

Here is my karma.conf.js file (with everything to do with coverage removed as it was not working):

// Karma configuration
// Generated on Thu May 04 2017 13:00:28 GMT+0100 (GMT Daylight Time)
'use strict';

const webpack = require('webpack');
const path = require('path');

let reporters = ['progress'],
    singleRunSwitch = true,
    browsers = ['ChromeHeadless'];

function isDebug(argument) {
    return argument === 'debug';
}

if (process.argv.some(isDebug)) {
    reporters = ['progress'];
    singleRunSwitch = false;
    browsers = ['Chrome'];
}

module.exports = function(config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine'],
        files: [
            { pattern: './test-main.js' }
        ],
        exclude: [],
        preprocessors: {
            './test-main.js': ['webpack', 'sourcemap']
        },
        reporters: reporters,
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: browsers,

        customLaunchers: {
            ChromeHeadless: {
                base: 'Chrome',
                flags: [
                  '--headless',
                  ' --remote-debugging-port=9222',
                  '--disable-gpu',
                  '--disable-plugins',
                  '--window-size=0,0',
                  '--window-position=-9999,0'
                ],
            },
        },
        singleRun: singleRunSwitch,
        concurrency: Infinity,

        webpack: {
            module: {
                rules: [{
                    test: /\.js$/,
                    exclude: path.join(__dirname, '../node_modules/'),
                    use: [{
                        loader: 'babel-loader',
                        options: {
                            presets: ['es2015']
                        }
                    }]
                }]
            },
            devtool: 'inline-source-map',
            plugins: [
                new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname))
            ]
        },

        webpackMiddleware: {
            stats: 'errors-only'
        },

        webpackServer: {
            noInfo: true
        }

    });
}

Can anyone advise which plugins I need to use and how I should configure them please?

Body:
I got it working, I used Istanbul and istanbul-instrumenter-loader - both installed via NPM. My karma.conf.js file now looks like this:

// Karma configuration
// Generated on Thu May 04 2017 13:00:28 GMT+0100 (GMT Daylight Time)
'use strict';

const webpack = require('webpack');
const path = require('path');

let reporters = ['progress', 'coverage'],
    singleRunSwitch = true,
    browsers = ['ChromeHeadless'];

function isDebug(argument) {
    return argument === 'debug';
}

if (process.argv.some(isDebug)) {
    reporters = ['progress'];
    singleRunSwitch = false;
    browsers = ['Chrome'];
}

module.exports = function(config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine'],
        files: [
            { pattern: './test-main.js' }
        ],
        exclude: [],
        preprocessors: {
            './test-main.js': ['webpack', 'sourcemap']
        },
        reporters: reporters,
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: browsers,
        customLaunchers: {
            ChromeHeadless: {
                base: 'Chrome',
                flags: [
                  '--headless',
                  '--remote-debugging-port=9222',
                  '--disable-gpu',
                  '--disable-plugins',
                  '--window-size=0,0',
                  '--window-position=-9999,0'
                ],
            },
        },
        singleRun: singleRunSwitch,
        concurrency: Infinity,
        webpack: {
            module: {
                rules: [{
                    test: /\.spec.js$/,
                    exclude: [path.join(__dirname, '../node_modules/'), /\.html$/],
                    use: [{
                        loader: 'babel-loader',
                        options: { presets: ['es2015'] }
                    }]
                }, {
                    test: /\.js$/,
                    exclude: [path.join(__dirname, '../node_modules/'), /\.spec.js$/, /\.html$/, /test-main.js/],
                    use: [{
                        loader: 'istanbul-instrumenter-loader',
                    }, {
                        loader: 'babel-loader',
                        options: { presets: ['es2015'] }
                    }]
                }]
            },
            devtool: 'inline-source-map',
            plugins: [
                new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname))
            ]
        },
        webpackMiddleware: {
            stats: 'errors-only'
        },
        webpackServer: {
            noInfo: true
        }
    });
}

The configuration was actually quite straight-forward; I had to add a 'coverage' reporter (but not when debugging), and had to add a new module.rules Webpack configuration - there are actually two configs here; I had to run the spec files through Babel separately from the rest of the .js files, and then add the instanbul-intrumenter to the rules array for .js files except *.spec.js (plus exclude a bunch of things!)


问:
How to import Image in Python3.5 under windows from PIL/Pillow
I want to write a little app to convert some images.
I think to have to use Image.open(), so I have to import the Image module. Right?

If so, here my problem. I have read other questions like this but any of them worked for me. I tried:

import Image => ImportError: cannot import name 'VERSION'

from PIL import Image => ImportError: cannot import name 'VERSION'

from Pillow import Image => ImportError: No module named 'Pillow'

In documentation I read:

```<code>Pillow and PIL cannot co-exist in the same environment. Before installing Pillow, please uninstall PIL.

Pillow >= 1.0 no longer supports “import Image”. Please use “from PIL import Image” instead.
</code>```

In my virtual enviroment I had PIL and Pillow directory but pip list gave only Pillow (3.1.0) so, even reading other answers, I try to uninstall PIL using pip but it can't find PIL, so I just delete the directory PIL and installed Pillow-PIL (now it appears on pip list and there's the directory Pillow_PIL on my venv\Lib\site-packages\) now:

import Image => ImportError: No module named 'PIL'

from PIL import Image => ImportError: No module named 'PIL'

from Pillow import Image => ImportError: No module named 'Pillow'

from Pillow-PIL import Image => SyntaxError: invalid syntax (on the minus sign)

from Pillow_PIL import Image => ImportError: No module named 'Pillow_PIL'

apt-get install python-imaging => "apt-get" command unknow (my free translation)

So, what now?

Edit: full error is

```<code>Traceback (most recent call last):
  File "prova.py", line 1, in <module>
    import Image
  File "D:\Python\Envs\possedimenti\lib\site-packages\Image.py", line 1, in <mod
ule>
from PIL.Image import *
  File "D:\Python\Envs\possedimenti\lib\site-packages\PIL\Image.py", line 29, in
 <module>
    from PIL import VERSION, PILLOW_VERSION, _plugins
ImportError: cannot import name 'VERSION'
</code>```

答:
When you install Pillow, it installs a module that you import as PIL. Pillow-PIL is apparantly a "Pillow wrapper for PIL compatibility".

It is generally not a good idea to delete files from site-packages, but to use a package installer like pip to do it.

To remedy this, I would suggest uninstalling Pillow-PIL, PIL (if you have it) and Pillow, and then reinstalling just Pillow.

```<code>pip3 uninstall Pillow-PIL ; pip3 uninstall PIL ; pip3 uninstall Pillow ; pip3 install Pillow
</code>```

Body:
I want to write a little app to convert some images.
I think to have to use Image.open(), so I have to import the Image module. Right?

If so, here my problem. I have read other questions like this but any of them worked for me. I tried:

import Image => ImportError: cannot import name 'VERSION'

from PIL import Image => ImportError: cannot import name 'VERSION'

from Pillow import Image => ImportError: No module named 'Pillow'

In documentation I read:

Pillow and PIL cannot co-exist in the same environment. Before installing Pillow, please uninstall PIL.

Pillow >= 1.0 no longer supports “import Image”. Please use “from PIL import Image” instead.

In my virtual enviroment I had PIL and Pillow directory but pip list gave only Pillow (3.1.0) so, even reading other answers, I try to uninstall PIL using pip but it can't find PIL, so I just delete the directory PIL and installed Pillow-PIL (now it appears on pip list and there's the directory Pillow_PIL on my venv\Lib\site-packages\) now:

import Image => ImportError: No module named 'PIL'

from PIL import Image => ImportError: No module named 'PIL'

from Pillow import Image => ImportError: No module named 'Pillow'

from Pillow-PIL import Image => SyntaxError: invalid syntax (on the minus sign)

from Pillow_PIL import Image => ImportError: No module named 'Pillow_PIL'

apt-get install python-imaging => "apt-get" command unknow (my free translation)

So, what now?

Edit: full error is

Traceback (most recent call last):
  File "prova.py", line 1, in <module>
    import Image
  File "D:\Python\Envs\possedimenti\lib\site-packages\Image.py", line 1, in <mod
ule>
from PIL.Image import *
  File "D:\Python\Envs\possedimenti\lib\site-packages\PIL\Image.py", line 29, in
 <module>
    from PIL import VERSION, PILLOW_VERSION, _plugins
ImportError: cannot import name 'VERSION'

Body:
When you install Pillow, it installs a module that you import as PIL. Pillow-PIL is apparantly a "Pillow wrapper for PIL compatibility".

It is generally not a good idea to delete files from site-packages, but to use a package installer like pip to do it.

To remedy this, I would suggest uninstalling Pillow-PIL, PIL (if you have it) and Pillow, and then reinstalling just Pillow.

pip3 uninstall Pillow-PIL ; pip3 uninstall PIL ; pip3 uninstall Pillow ; pip3 install Pillow


问:
Blank iFrame in IE
I have an iframe:

```<code><iframe src="http://externaldomain.com/something.html">
</code>```

If something.html from externaldomain.com has the css:

```<code>html { position: relative; }
</code>```

In IE, it will render the iframe as blank. All other browser are fine.

Anyone know of a solution? Remember the same origin policy. I cannot alter anything within the iframe with javascript or change the css as the iframe src is external.

Thanks.

答: As a workaround, if all else fails, you can download the contents of something.html using server-side logic, like ASP.NET or PHP, and save it on your local web-server somewhere. Then you can avoid the same-origin policy, or you can even modify the HTML/CSS yourself on the server, for ex., remove the offending position:relative.</p>

Title: Blank iFrame in IE

Body:
I have an iframe:

If something.html from externaldomain.com has the css:

html { position: relative; }

In IE, it will render the iframe as blank. All other browser are fine.

Anyone know of a solution? Remember the same origin policy. I cannot alter anything within the iframe with javascript or change the css as the iframe src is external.

Thanks.


问:
Can text animation in css be applied to images ?
I am trying to get the shake animation to an image.
It works with texts but not with images. Need some help here. </p>

```<code>.shake:hover {
 animation-name: shake;
 }

  @keyframes shake {
   from, to {
   transform: translate3d(0, 0, 0);
   }

   10%, 30%, 50%, 70%, 90% {
   transform: translate3d(-50px, 0, 0);
   }

   20%, 40%, 60%, 80% {
   transform: translate3d(50px, 0, 0);
     }
    }
</code>```

答:
Try this instead.

.shake:hover {
  animation: shake 0.82s cubic-bezier(.36,.07,.19,.97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%, 90% {
    transform: translate3d(-1px, 0, 0);
  }

  20%, 80% {
    transform: translate3d(2px, 0, 0);
  }

  30%, 50%, 70% {
    transform: translate3d(-4px, 0, 0);
  }

  40%, 60% {
    transform: translate3d(4px, 0, 0);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="shake">
<img src="https://placeholdit.co//i/555x150">
</div></code>```

Body:
I am trying to get the shake animation to an image.
It works with texts but not with images. Need some help here.

.shake:hover {
 animation-name: shake;
 }

  @keyframes shake {
   from, to {
   transform: translate3d(0, 0, 0);
   }

   10%, 30%, 50%, 70%, 90% {
   transform: translate3d(-50px, 0, 0);
   }

   20%, 40%, 60%, 80% {
   transform: translate3d(50px, 0, 0);
     }
    }

Body:
Try this instead.

.shake:hover {
  animation: shake 0.82s cubic-bezier(.36,.07,.19,.97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%, 90% {
    transform: translate3d(-1px, 0, 0);
  }

  20%, 80% {
    transform: translate3d(2px, 0, 0);
  }

  30%, 50%, 70% {
    transform: translate3d(-4px, 0, 0);
  }

  40%, 60% {
    transform: translate3d(4px, 0, 0);
  }
}

<div class="shake">
<img src="https://placeholdit.co//i/555x150">
</div>


问:
TeamCity + Line endings, C# Multi-line verbatim strings
I have multi-line strings in the following format:

```<code>@"Text on Line 1
Text on Line 2."
</code>```

When I build my tests in Visual Studio and run using VS Developer cmd, it runs fine and compares expected string vs actual.

But when running on teamcity using either MSBuild or VS sln, it only likes my multi-line strings, when they are in the following format with "\r\n" and no @ sign. And treats above format as having no new line character.

```<code>"Text on Line 1\r\nText on Line 2."
</code>```

I decompliled the dll file with tests, that teamcity is producing and instead of "\r\n" all new line characters in verbatim multi-line string are replaced with "\n", so could be a teamcity issue with new line endings.

I could go ahead and change all my strings format, but looking for a solution to avoid it. thanks!

答: I had to check the "Convert line-endings to CRLF" checkbox in VCS root settings on teamcity</p>

Body:
I have multi-line strings in the following format:

@"Text on Line 1
Text on Line 2."

When I build my tests in Visual Studio and run using VS Developer cmd, it runs fine and compares expected string vs actual.

But when running on teamcity using either MSBuild or VS sln, it only likes my multi-line strings, when they are in the following format with "\r\n" and no @ sign. And treats above format as having no new line character.

"Text on Line 1\r\nText on Line 2."

I decompliled the dll file with tests, that teamcity is producing and instead of "\r\n" all new line characters in verbatim multi-line string are replaced with "\n", so could be a teamcity issue with new line endings.

I could go ahead and change all my strings format, but looking for a solution to avoid it. thanks!


问:
Can I use localStorage to create a permanent database?
I'm currently learning about hybrid app development on my own. I need to create a local database on the phone in order to save some information, however, I don't know much about storage.

I've seen HTML5 Local Storage (https://www.w3schools.com/html/html5_webstorage.asp), and it's easy and confortable to apply, but I don't know if this kind of storage will be permanent on a hybrid app when the phone turns off or when the app closes.

Can you, please, help me with this doubt?

Thank you!

答: Local storage isn't permanent, the user can clear the data whenever they wish. This means it stays until they choose to clear the data, a reboot won't affect it. If you really need to store data permanently, why not create your own server, or integrate with a cloud-based storage service (e.g. Google Drive) so you can store user data there?</p>


问:
Passing page checkBox value to other class
I've been reading other questions and pages and seen some ideas but could not understand them or get them to work properly.

My Example:

I have this checkBox1 on my mainpage.xaml

```<code> <CheckBox Content="Central WC / EC" Height="68" HorizontalAlignment="Left" Margin="106,206,0,0" Name="checkBox1" VerticalAlignment="Top" BorderThickness="0" />
</code>```

I have a anotherpage.xaml with its c# on anotherpage.xaml.cs:

```<code> public void Feed(object Sender, DownloadStringCompletedEventArgs e)
    {
        if (checkBox1.Checked("SE" == (_item.Sector))) ;
        {

        }
     }
</code>```

How do I pass the value of the checkBox1 on the mainpage.xaml to the anotherpage.xaml.cs

答:
You can declare a public property in the App class.

```<code>public partial class App : Application
{
    public int Shared { set; get; }
    //...
}
</code>```

Then you can access it from the pages via:

```<code>(Application.Current as App).Shared
</code>```

You could store a reference to the form or put an event or anything else you want to do.

On a side note, I highly recommend Petzold's WP7 book free for download.

Body:
I've been reading other questions and pages and seen some ideas but could not understand them or get them to work properly.

My Example:

I have this checkBox1 on my mainpage.xaml

 <CheckBox Content="Central WC / EC" Height="68" HorizontalAlignment="Left" Margin="106,206,0,0" Name="checkBox1" VerticalAlignment="Top" BorderThickness="0" />

I have a anotherpage.xaml with its c# on anotherpage.xaml.cs:

 public void Feed(object Sender, DownloadStringCompletedEventArgs e)
    {
        if (checkBox1.Checked("SE" == (_item.Sector))) ;
        {

        }
     }

How do I pass the value of the checkBox1 on the mainpage.xaml to the anotherpage.xaml.cs

Body:
You can declare a public property in the App class.

public partial class App : Application
{
    public int Shared { set; get; }
    //...
}

Then you can access it from the pages via:

(Application.Current as App).Shared

You could store a reference to the form or put an event or anything else you want to do.

On a side note, I highly recommend Petzold's WP7 book free for download.


问:
Can I overwrite a designtime component reference at runtime?
I'm using a TSQLConnection component (connDT) on a data module only to fetch the fields to a TSQLDataset, TDatasetProvider and TClientDataset trio at design time that connects to my test database.
At runtime I need to change object instance of the designtime TSQLConnection (connDT) with a runtime object instance (connRT) connected to the production database.
I did it this way in the data module's OnCreate event:

connDT := connRT;

But when I open my TClientDataset object (trio), it still uses the test database (the connDT connection object settings are used). How can I overwrite a desigtime component reference at runtime?

答:
Do not overwrite design time created object references this way. If you want to change connection of your database component(s) at runtime, do it either by modifying their SQLConnection property, or by modifying the connection object's parameters (which is what I would prefer). So either this:

```<code>SQLDataSet1.SQLConnection := ConnRunTime;
</code>```

Or something like this:

```<code>ConnDesignTime.Params.Values['Database'] := 'MyDatabase';
ConnDesignTime.Params.Values['User_Name'] := 'UserLogin';
ConnDesignTime.Params.Values['Password'] := 'Password';
ConnDesignTime.Open;
</code>```

There are other ways, but the above ones are pretty easy.

Body:
Do not overwrite design time created object references this way. If you want to change connection of your database component(s) at runtime, do it either by modifying their SQLConnection property, or by modifying the connection object's parameters (which is what I would prefer). So either this:

SQLDataSet1.SQLConnection := ConnRunTime;

Or something like this:

ConnDesignTime.Params.Values['Database'] := 'MyDatabase';
ConnDesignTime.Params.Values['User_Name'] := 'UserLogin';
ConnDesignTime.Params.Values['Password'] := 'Password';
ConnDesignTime.Open;

There are other ways, but the above ones are pretty easy.


答:
It works with images. Your problem is that you don't define animation's duration.

Try this:

```<code>.shake:hover {
  animation-name: shake;
  animation-duration: 2s;
}
</code>```

Or shorthand version:

```<code>.shake:hover {
  animation: shake 2s;
}
</code>```

Demo: jsfiddle

Title: Can text animation in css be applied to images ?

Body:
It works with images. Your problem is that you don't define animation's duration.

Try this:

.shake:hover {
  animation-name: shake;
  animation-duration: 2s;
}

Or shorthand version:

.shake:hover {
  animation: shake 2s;
}

Demo: jsfiddle


问:
React communicate with others components
i have these components "Portlet", "PortletTitle","PortletTool","PortletBody" . All work fine, but now i want add a simple interaction between components.

to use in my app:

```<code><Portlet>
  <PortletTitle>
    <PortletTool toolCollapse={true}>
  </PortletTitle>
  <PortletBody>bla vla bla </PortletBody>
</Portlet>
</code>```

PortletTool.js

```<code>class PortletTools extends React.Component {

    static propTypes = { toolCollapse: PropTypes.bool };
    state = { collaped: false };

    handler = () => {
        let newstate = !this.state.collaped;
        this.setState({ collaped: newstate });
    };

    render() {
        const classCollaped = !this.state.collaped ? "collapse" : "expand";
        let toolCollapse = this.props.toolCollapse
            ? <a href="javascript:;" className={classCollaped} title="" data-original-title="" onClick={this.handler}>{" "}</a>
            : "";

        return (
            <div className="tools">
                {toolCollapse}
            </div>
        );
    }
}
</code>```

PortletBody have a props "showbody" to hide/show the element, but i can now with this structure (already used in other page of application) click on my PortletTool e hide/show my PortletBody? Yes, how to?

I must (if possible) do this in "Portet" component.

答:
If you want to add some interaction between any children components, then you're in a position where it would be helpful to lift state up. In this case, you'd want to move the collapsed state up in to your Portlet component, register a handler that changes the state in your Portlet class, bind the context, and pass that handler down to your PortletTool. You would also want to pass the collapsed state in to your PortletBody via props.

For example:

```<code>class Portlet extends React.Component {
  state={collaped:false};
    handler=()=>{
    let newstate=!this.state.collaped;
    this.setState({collaped:newstate});
    }

   render() {
    return (
      <PortletTitle>
          <PortletTool handler={this.handler}>
        </PortletTitle>
        <PortletBody collapsed={this.state.collapsed}>bla vla bla </PortletBody>
      )
   }
}
</code>```

Then assign the handler to an onClick prop somewhere in your PortletTool.  If you get a cannot read property of undefined error then you need to bind the context to the handler.

Body:
i have these components "Portlet", "PortletTitle","PortletTool","PortletBody" . All work fine, but now i want add a simple interaction between components.

to use in my app:

<Portlet>
  <PortletTitle>
    <PortletTool toolCollapse={true}>
  </PortletTitle>
  <PortletBody>bla vla bla </PortletBody>
</Portlet>

PortletTool.js

class PortletTools extends React.Component {

    static propTypes = { toolCollapse: PropTypes.bool };
    state = { collaped: false };

    handler = () => {
        let newstate = !this.state.collaped;
        this.setState({ collaped: newstate });
    };

    render() {
        const classCollaped = !this.state.collaped ? "collapse" : "expand";
        let toolCollapse = this.props.toolCollapse
            ? {" "}
            : "";

        return (

                {toolCollapse}

        );
    }
}

PortletBody have a props "showbody" to hide/show the element, but i can now with this structure (already used in other page of application) click on my PortletTool e hide/show my PortletBody? Yes, how to?

I must (if possible) do this in "Portet" component.

Body:
If you want to add some interaction between any children components, then you're in a position where it would be helpful to lift state up. In this case, you'd want to move the collapsed state up in to your Portlet component, register a handler that changes the state in your Portlet class, bind the context, and pass that handler down to your PortletTool. You would also want to pass the collapsed state in to your PortletBody via props.

For example:

class Portlet extends React.Component {
  state={collaped:false};
    handler=()=>{
    let newstate=!this.state.collaped;
    this.setState({collaped:newstate});
    }

   render() {
    return (
      <PortletTitle>
          <PortletTool handler={this.handler}>
        </PortletTitle>
        <PortletBody collapsed={this.state.collapsed}>bla vla bla </PortletBody>
      )
   }
}

Then assign the handler to an onClick prop somewhere in your PortletTool.  If you get a cannot read property of undefined error then you need to bind the context to the handler.


问:
List files (recursively) which have no matching pair
I have a set of files in multiple directories. Most of them have a related pair with a different extension and the same base name. The related files are always within the same directory. I need to list only files (and path) without pairs within a directory including all sub directories. How can I do that in bash?

```<code>file1.xxx
file1.yyy

file2.xxx
file2.zzz

file3.xxx
file3.aaa

file4.xxx
</code>```

Any help is much appreciated!

答:
You can list all the files under your directory and then count how many matches you can find of their whole name in the same tree directory which has the same path name (excluding extension).

If your file matches with less or one names, that means it has not "companion" files:

```<code>for f in $(find -type f); do
    c=$(find -wholename "$(echo $f | rev | cut --complement -d . -f 1 | rev).*" | wc -l);
    if [ "$c" -le "1" ]; then echo $f; fi;
done
</code>```

Edit:

It might more readable if the pattern composition is performed in a different line:

```<code>for f in $(find -type f); do
    compPattern="$(echo $f | rev | cut --complement -d . -f 1 | rev).*"
    c=$(find -wholename "$compPattern" | wc -l);
    if [ "$c" -le "1" ]; then echo $f; fi;
done
</code>```

Edit (2)

To avoid parsing the output of the find you can use read:

```<code>find -type f | while read f; do
    if [ $(find -wholename "$(echo $f | rev | cut --complement -d . -f 1 | rev).*" | wc -l) -le "1" ]; then echo $f; fi;
done
</code>```

Edit(3)

To handle special chars, spaces etc. you can use the following.

```<code>while IFS= read -r -d '' f ; do
    c=$(find -wholename "$(echo $f | rev | cut --complement -d . -f 1 | rev).*" | wc -l);
    if [ "$c" -le "1" ]; then echo $f; fi;
done < <(find -type f -print0)
</code>```

Body:
I have a set of files in multiple directories. Most of them have a related pair with a different extension and the same base name. The related files are always within the same directory. I need to list only files (and path) without pairs within a directory including all sub directories. How can I do that in bash?

file1.xxx
file1.yyy

file2.xxx
file2.zzz

file3.xxx
file3.aaa

file4.xxx

Any help is much appreciated!

Body:
You can list all the files under your directory and then count how many matches you can find of their whole name in the same tree directory which has the same path name (excluding extension).

If your file matches with less or one names, that means it has not "companion" files:

for f in $(find -type f); do
    c=$(find -wholename "$(echo $f | rev | cut --complement -d . -f 1 | rev).*" | wc -l);
    if [ "$c" -le "1" ]; then echo $f; fi;
done

Edit:

It might more readable if the pattern composition is performed in a different line:

for f in $(find -type f); do
    compPattern="$(echo $f | rev | cut --complement -d . -f 1 | rev).*"
    c=$(find -wholename "$compPattern" | wc -l);
    if [ "$c" -le "1" ]; then echo $f; fi;
done

Edit (2)

To avoid parsing the output of the find you can use read:

find -type f | while read f; do
    if [ $(find -wholename "$(echo $f | rev | cut --complement -d . -f 1 | rev).*" | wc -l) -le "1" ]; then echo $f; fi;
done

Edit(3)

To handle special chars, spaces etc. you can use the following.

while IFS= read -r -d '' f ; do
    c=$(find -wholename "$(echo $f | rev | cut --complement -d . -f 1 | rev).*" | wc -l);
    if [ "$c" -le "1" ]; then echo $f; fi;
done < <(find -type f -print0)


问:
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

答:
Updated**

it does not work with array.concat but with this merge function, don't know why....

Here is a kind of solution,

```<code>Array.prototype.merge = function(/* variable number of arrays */){
    for(var i = 0; i < arguments.length; i++){
        var array = arguments[i];
        for(var j = 0; j < array.length; j++){
            if(this.indexOf(array[j]) === -1) {
                this.push(array[j]);
            }
        }
    }
    return this;
};

var $a = [10, 7, 12, 3, 5, 6];
var $b = [12, 8, 5, 9, 6, 10];

function reorganize($array){

  var $reorganize = [];

  $reorganize.push($array.shift());

  $array.sort(function(a, b) { return a - b; });

  $reorganize.merge($array);

  return $reorganize;
}

console.log(reorganize($a));
console.log(reorganize($b));
</code>```

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

Body:
Updated**

it does not work with array.concat but with this merge function, don't know why....

Here is a kind of solution,

Array.prototype.merge = function(/* variable number of arrays */){
    for(var i = 0; i < arguments.length; i++){
        var array = arguments[i];
        for(var j = 0; j < array.length; j++){
            if(this.indexOf(array[j]) === -1) {
                this.push(array[j]);
            }
        }
    }
    return this;
};

var $a = [10, 7, 12, 3, 5, 6];
var $b = [12, 8, 5, 9, 6, 10];

function reorganize($array){

  var $reorganize = [];

  $reorganize.push($array.shift());

  $array.sort(function(a, b) { return a - b; });

  $reorganize.merge($array);

  return $reorganize;
}

console.log(reorganize($a));
console.log(reorganize($b));


问:
sudo: npm: command not found
I'm trying to upgrade to the latest version of node. I'm following the instructions at http://davidwalsh.name/upgrade-nodejs

But when I do:

```<code>sudo npm install -g n
</code>```

I get the error:

```<code>sudo: npm: command not found
</code>```

npm works without sudo. When I do:

```<code>whereis node
</code>```

I see:

```<code>node: /usr/bin/node /usr/lib/node /usr/bin/X11/node /usr/local/node
</code>```

Running:

```<code>which npm
</code>```

Shows:

```<code>/usr/local/node/bin/npm
</code>```

I tried the solution at https://stackoverflow.com/a/5062718/1246159

But I'm still getting the same error. I also looked at the /etc/sudoers file and the relevant line is:

```<code>Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
</code>```

This looks fine to me. How can I possibly get NPM working with sudo command?

答:
Remove Node completely:

```<code>  brew uninstall --force node
</code>```

Install again:

```<code>brew install node;
which node # => /usr/local/bin/node
export NODE_PATH='/usr/local/lib/node_modules'
</code>```

Title: sudo: npm: command not found

Body:
I'm trying to upgrade to the latest version of node. I'm following the instructions at http://davidwalsh.name/upgrade-nodejs

But when I do:

sudo npm install -g n

I get the error:

sudo: npm: command not found

npm works without sudo. When I do:

whereis node

I see:

node: /usr/bin/node /usr/lib/node /usr/bin/X11/node /usr/local/node

Running:

which npm

Shows:

/usr/local/node/bin/npm

I tried the solution at https://stackoverflow.com/a/5062718/1246159

But I'm still getting the same error. I also looked at the /etc/sudoers file and the relevant line is:

Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

This looks fine to me. How can I possibly get NPM working with sudo command?

Body:
Remove Node completely:

  brew uninstall --force node

Install again:

brew install node;
which node # => /usr/local/bin/node
export NODE_PATH='/usr/local/lib/node_modules'


问:
Use an integer in a pandas dataframe column to extract a specific value from a list inside another column
I have a dataframe with a list inside a column, and another column with a specific integer value for that row. I want to use this integer value to extract a specific value from the list inside the other column:

df:

```<code>    list                                         val
1   ['mohamed', 'adam', 'paul', 'dave']           3
2   ['dave', 'fred']                              0
3   ['john', 'dave', 'jane']                      1
4   ['dave']                                      0
</code>```

this was created by:

```<code>df = df.loc[df['unsplit_list'].str.contains('dave')]
df['list'] = df['unsplit_list'].str.split('|')
df['val'] = df['list'].apply(lambda lst: [i for i, x in enumerate(lst) if 'dave' in x][0])
df['val'] = df['val'].astype(int)
</code>```

when i try to obtain the value for dave out of my list, it comes up with an error:

```<code>df['list'].str[df['val']]

>>
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

however if i did:

```<code>df['list'].str[df[1]]
</code>```

then i would be able to obtain the value in the list using this integer. How can I get this value i want out?

答:
You can do:</p>

```<code>df.apply(lambda x: x['list'][x['value']], axis=1)
</code>```

Body:
I have a dataframe with a list inside a column, and another column with a specific integer value for that row. I want to use this integer value to extract a specific value from the list inside the other column:

df:

    list                                         val
1   ['mohamed', 'adam', 'paul', 'dave']           3
2   ['dave', 'fred']                              0
3   ['john', 'dave', 'jane']                      1
4   ['dave']                                      0

this was created by:

df = df.loc[df['unsplit_list'].str.contains('dave')]
df['list'] = df['unsplit_list'].str.split('|')
df['val'] = df['list'].apply(lambda lst: [i for i, x in enumerate(lst) if 'dave' in x][0])
df['val'] = df['val'].astype(int)

when i try to obtain the value for dave out of my list, it comes up with an error:

df['list'].str[df['val']]

>>
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

however if i did:

df['list'].str[df[1]]

then i would be able to obtain the value in the list using this integer. How can I get this value i want out?

Body:
You can do:

df.apply(lambda x: x['list'][x['value']], axis=1)