问:
React.JS: Sequence of timed state changes
I have a simple web app with one parent component and three child components. The children are just div boxes that can change their background color from white to red based on their property active. The animateChild() function can be used to turn a specific child red and then white again after 1s.

My goal is to "play" an arbitrary sequence of child animations with a break of 1s between each animation. This should happen in the animateSequence() function.

My initial idea to accomplish that, was to use a for loop and call animateChild(childNum) in a window.setTimeout() at each iteration. However, this didn't work. I guess because setState() is asynchronous and several state changes get merged together.

What is the best way to accomplish a sequence (e.g. Child 1, Child 2, Child 3) of animations with a break time of 1s between each animation? Thank you very much

Javascript Code:

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

  render() {
    var childStyle = "basic";
    if (this.props.active){
      childStyle += " active";
    }
    return (
        <div className={childStyle}></div>
    );
  }
}

class Parent extends React.Component {
  constructor(){
    super();
    this.state = {
      firstChildActive:false,
      secondChildActive:false,
      thirdChildActive:false,
    };
    this.animateChild = this.animateChild.bind(this);

  }

  animateChild(childNum){
    var childDict = ["firstChildActive","secondChildActive","thirdChildActive"];
    this.setState({[childDict[childNum]]: true}, function() {

        window.setTimeout(() => {
        this.setState({[childDict[childNum]]: false});

        },1000);
    });
  }

  animateSequence(){
    // animate child 2, then child 1, then child 3, then child 1, etc.
  }

  render() {
    return (
      <div className ="container">
      <Child active={this.state.firstChildActive}/>
      <Child active={this.state.secondChildActive}/>
      <Child active={this.state.thirdChildActive}/>
      </div>
    );
  }
}

ReactDOM.render(<Parent />,document.getElementById('app'));
</code>```

CSS Code:

```<code>.container{
  display:flex;
  width:100%;
  justify-content: space-between;

}

.basic{
  margin: 10px;
  width: 100px;
  height:100px;
  border: 2px solid black;
}

.active{
  background: red;
}
</code>```

Codepen: https://codepen.io/miga89/full/owgZea/

答:
Your this context is invalid in the callback of first setState.

```<code>var childDict = ["firstChildActive","secondChildActive","thirdChildActive"];
this.setState({[childDict[childNum]]: true}, function() {
</code>```

Should be

```<code>var childDict = ["firstChildActive","secondChildActive","thirdChildActive"];
this.setState({[childDict[childNum]]: true}, () => {
</code>```

Body:
I have a simple web app with one parent component and three child components. The children are just div boxes that can change their background color from white to red based on their property active. The animateChild() function can be used to turn a specific child red and then white again after 1s.

My goal is to "play" an arbitrary sequence of child animations with a break of 1s between each animation. This should happen in the animateSequence() function.

My initial idea to accomplish that, was to use a for loop and call animateChild(childNum) in a window.setTimeout() at each iteration. However, this didn't work. I guess because setState() is asynchronous and several state changes get merged together.

What is the best way to accomplish a sequence (e.g. Child 1, Child 2, Child 3) of animations with a break time of 1s between each animation? Thank you very much

Javascript Code:

class Child extends React.Component {

  render() {
    var childStyle = "basic";
    if (this.props.active){
      childStyle += " active";
    }
    return (

    );
  }
}

class Parent extends React.Component {
  constructor(){
    super();
    this.state = {
      firstChildActive:false,
      secondChildActive:false,
      thirdChildActive:false,
    };
    this.animateChild = this.animateChild.bind(this);

  }

  animateChild(childNum){
    var childDict = ["firstChildActive","secondChildActive","thirdChildActive"];
    this.setState({[childDict[childNum]]: true}, function() {

        window.setTimeout(() => {
        this.setState({[childDict[childNum]]: false});

        },1000);
    });
  }

  animateSequence(){
    // animate child 2, then child 1, then child 3, then child 1, etc.
  }

  render() {
    return (

      <Child active={this.state.firstChildActive}/>
      <Child active={this.state.secondChildActive}/>
      <Child active={this.state.thirdChildActive}/>

    );
  }
}

ReactDOM.render(<Parent />,document.getElementById('app'));

CSS Code:

.container{
  display:flex;
  width:100%;
  justify-content: space-between;

}

.basic{
  margin: 10px;
  width: 100px;
  height:100px;
  border: 2px solid black;
}

.active{
  background: red;
}

Codepen: https://codepen.io/miga89/full/owgZea/

Body:
Your this context is invalid in the callback of first setState.

var childDict = ["firstChildActive","secondChildActive","thirdChildActive"];
this.setState({[childDict[childNum]]: true}, function() {

Should be

var childDict = ["firstChildActive","secondChildActive","thirdChildActive"];
this.setState({[childDict[childNum]]: true}, () => {


来源: stackexchange

问:
Rendering tiles that are seen on screen
everybody, I'm making an android game using java and libgdx. I'm also using Tiled to render my tiles on the screen. I hava the camera set up already, all I need is to figure out how to not render tiles that are not shown on the screen. Here is the code </p>

```<code>testRenderer.setView(main.getOrthographicCamera());
testRenderer.render();
main.getOrthographicCamera().position.set(main.getPlayer().getX() + (Main.PLAYER_WIDTH / 2), main.getPlayer().getY() + (Main.PLAYER_HEIGHT / 2), 0);
main.getSpriteBatch().setProjectionMatrix(main.getOrthographicCamera().combined);
setBoundsToCamera();
main.getOrthographicCamera().update();
</code>```

答:
You don't have to do it.
OrthographicCamera.update() is taking care of it by itself. All you have to do is define viewport size.</p>

ContentLicense: CC BY-SA 3.0

Title: Rendering tiles that are seen on screen

Body:
everybody, I'm making an android game using java and libgdx. I'm also using Tiled to render my tiles on the screen. I hava the camera set up already, all I need is to figure out how to not render tiles that are not shown on the screen. Here is the code

testRenderer.setView(main.getOrthographicCamera());
testRenderer.render();
main.getOrthographicCamera().position.set(main.getPlayer().getX() + (Main.PLAYER_WIDTH / 2), main.getPlayer().getY() + (Main.PLAYER_HEIGHT / 2), 0);
main.getSpriteBatch().setProjectionMatrix(main.getOrthographicCamera().combined);
setBoundsToCamera();
main.getOrthographicCamera().update();


问:
IBOutlet UITableView visible in simulator but not on device
I have developed a split view based universal application which runs as a navigation based application on iPhone. after login table view appears which is the root view in split based application.

The code works fine on iPhone simulator but when i try running it on device, ,the table view does not appear.

I tried debugging it and the problem is that table view is not being allocated memory when i am running on device whereas on simulator the same code allocates memory to IBOutlet table view.

I dont understand why the same object is not being allocated memory when i try running it on device.

答: I figured it out. It was a relatively silly mistake. I had not made xib for iPhone, and so table view was not conected to any interface builder object. But why the same code runs on simulator is still a mystery.</p>

ContentLicense: CC BY-SA 2.5


问:
make a text file into a list
This is what my text file consists of:
"file1
file2"

So far this is my code:

```<code>def create_filenames_list(filename):
    filenames_list = []
    file = open('input.txt', "r").readlines()
    for line in file:
            filenames_list = line

    return filenames_list.split()
def main():
    filenames_list = create_filenames_list('input.txt')
    print(filenames_list)
</code>```

The Output I got:
"file2"
What I expected is:
['file1', 'file2']

答:
```<code>def create_filenames_list(filename):
filenames_list = []
file = open('input.txt', "r").readlines()
for line in file:
        filenames_list.append(line)

return filenames_list
def main():
    filenames_list = create_filenames_list('input.txt')
    print(filenames_list)
</code>```

Title: make a text file into a list

Body:
This is what my text file consists of:
"file1
file2"

So far this is my code:

def create_filenames_list(filename):
    filenames_list = []
    file = open('input.txt', "r").readlines()
    for line in file:
            filenames_list = line

    return filenames_list.split()
def main():
    filenames_list = create_filenames_list('input.txt')
    print(filenames_list)

The Output I got:
"file2"
What I expected is:
['file1', 'file2']


问:
Extract am or pm in jquery
I have date in following manner -

```<code>06:04:51 am
</code>```

I want to extract am/pm from this date time.
Based upon the am or pm will select particular class in time-holder.

Is there any way to extract the value?

答:
you can also use this to extract the am or pm after space

```<code>var str="06:04:51 am";
alert(str.substr(str.indexOf(" ") + 1));
</code>```

Title: Extract am or pm in jquery

Body:
I have date in following manner -

06:04:51 am

I want to extract am/pm from this date time.
Based upon the am or pm will select particular class in time-holder.

Is there any way to extract the value?

Body:
you can also use this to extract the am or pm after space

var str="06:04:51 am";
alert(str.substr(str.indexOf(" ") + 1));


问:
How can activity tell its fragments that location is available so they update contents
This is more of a design question.

So I have a bottom navigation Activity (which has multiple fragments). One of the fragments (the one that loads by default) has textview which will display the location information of the user.

When the activity starts, it does the googleApiClient connect and request the location permission from the user. By the time the user accepts and all this is done, the fragment is loaded and the textview is showing "unknown location". Which is all expected.

Now when the location is acquired( after the user has accepted), what would be the right way to pass this information down to the fragment and tell the textview to update?

I can do polling (meaning keep checking the location if it is not null in a handler timer) but I feel this is not the right approach.

Any hint on how something like that is done would be appreciated

Thanks.

答:
Just define appropriate method in your fragment, for instance

```<code>public class FragmentA extends Fragment{

    public void changeLocationField(Location location){

    }
}
</code>```

Then in the activity, call your method from fragment

```<code>private LocationListener mListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        FragmentA fragmentA = (FragmentA)
                getSupportFragmentManager().findFragmentById(R.id.a_fragment);

        if (fragmentA != null) {
            fragmentA.changeLocationField(location);
        }
    }
};
</code>```

Body:
Just define appropriate method in your fragment, for instance

public class FragmentA extends Fragment{

    public void changeLocationField(Location location){

    }
}

Then in the activity, call your method from fragment

private LocationListener mListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        FragmentA fragmentA = (FragmentA)
                getSupportFragmentManager().findFragmentById(R.id.a_fragment);

        if (fragmentA != null) {
            fragmentA.changeLocationField(location);
        }
    }
};


答:
If it's a string cut last 2 characters.

var date = '06:04:51 am';
var ampm = date.slice(-2);
console.log(ampm);```
</div>
</div>
</p>

<p>if It's a date object</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var date = new Date();

console.log(getAMPM(date));

function getAMPM(dateObj) {
  return dateObj.getHours < 12 ? 'am' : 'pm';
}</code>```

Title: Extract am or pm in jquery

Body:
If it's a string cut last 2 characters.

var date = '06:04:51 am';
var ampm = date.slice(-2);
console.log(ampm);

if It's a date object

var date = new Date();

console.log(getAMPM(date));

function getAMPM(dateObj) {
  return dateObj.getHours < 12 ? 'am' : 'pm';
}


问:
Creating class with variables vs passing variables as parameters into a method

Which is a better way to do this, in terms of performance or other factors?

Say I am creating a class with jut one method in it that takes 2 values and adds them together.

Is it better to have 2 instance variables to store the 2 values then have a method which uses these, or is it better to just pass the variables in as parameters when calling the method?

Note: this class is only ever created just to use this method.

public class MyClass {
    int value1;
    int value2;

public MyClass(int value1, int value2){
    this.value1 = value1;
    this.value2 = value2;
}

public int MyMethod(){
    return value1 + value2;
}
```

<p>or this way:</p>

<pre class="lang-java prettyprint-override"><code>public class MyClass {

public MyClass(){

}

public int MyMethod(int value1, int value2){
    return value1 + value2;
}
</code>```

Or would it be better to just use a static method, so I don't need to create an object every time I use the method?

答:
In Java, variables that are in class called member or instance variables not global.

```<code>public class MyClass {
    int value1;
    int value2;
</code>```

These two variables need to use base upon your reqiurements. First of all implement make and structure, think about what do you want to achieve. Then decide what classes and what members are needed for these classes(methods/ variables).

As a example, these two int value1; int value2; variable may be needed when you want to perform another tasks using same values. Such as divide(), multiply(), etc.

```<code>public class MyClass {
    int value1;
    int value2;

    public MyClass(int value1, int value2){
        this.value1 = value1;
        this.value2 = value2;
    }

    public int add(){
        return value1 + value2;
    }

    public int sub(){
        return value1 - value2;
    }

    public int divide(){
        return value1 / value2;
    }

    public int multiply(){
        return value1 * value2;
    }
}
</code>```

Using like public int MyMethod(int value1, int value2){ method you only can perform task. You won't be able to save variables values to perform another task. Like that methods helpful to divide tasks.

```<code>public class MyClass {
    public int add(int value1, int value2){
        return value1 + value2;
    }

    public int sub(int value1, int value2){
        return value1 - value2;
    }

    public int divide(int value1, int value2){
        return value1 / value2;
    }

    public int multiply(int value1, int value2){
        return value1 * value2;
    }
}
</code>```

But you can take two arguments each for methods perform task return value, that's all(all are different, donot have anything related).

Summary:

Both have unique functionality and roll to play according to your requirements.

Clean code is good book to read. And read these javanote, q1 and q2

Body:
Which is a better way to do this, in terms of performance or other factors?

Say I am creating a class with jut one method in it that takes 2 values and adds them together.

Is it better to have 2 instance variables to store the 2 values then have a method which uses these, or is it better to just pass the variables in as parameters when calling the method?

Note: this class is only ever created just to use this method.

public class MyClass {
    int value1;
    int value2;

public MyClass(int value1, int value2){
    this.value1 = value1;
    this.value2 = value2;
}

public int MyMethod(){
    return value1 + value2;
}

or this way:

public class MyClass {

public MyClass(){

}

public int MyMethod(int value1, int value2){
    return value1 + value2;
}

Or would it be better to just use a static method, so I don't need to create an object every time I use the method?

Body:
In Java, variables that are in class called member or instance variables not global.

public class MyClass {
    int value1;
    int value2;

These two variables need to use base upon your reqiurements. First of all implement make and structure, think about what do you want to achieve. Then decide what classes and what members are needed for these classes(methods/ variables).

As a example, these two int value1; int value2; variable may be needed when you want to perform another tasks using same values. Such as divide(), multiply(), etc.

public class MyClass {
    int value1;
    int value2;

    public MyClass(int value1, int value2){
        this.value1 = value1;
        this.value2 = value2;
    }

    public int add(){
        return value1 + value2;
    }

    public int sub(){
        return value1 - value2;
    }

    public int divide(){
        return value1 / value2;
    }

    public int multiply(){
        return value1 * value2;
    }
}

Using like public int MyMethod(int value1, int value2){ method you only can perform task. You won't be able to save variables values to perform another task. Like that methods helpful to divide tasks.

public class MyClass {
    public int add(int value1, int value2){
        return value1 + value2;
    }

    public int sub(int value1, int value2){
        return value1 - value2;
    }

    public int divide(int value1, int value2){
        return value1 / value2;
    }

    public int multiply(int value1, int value2){
        return value1 * value2;
    }
}

But you can take two arguments each for methods perform task return value, that's all(all are different, donot have anything related).

Summary:

Both have unique functionality and roll to play according to your requirements.

Clean code is good book to read. And read these javanote, q1 and q2


问:
Expecting member declaration in Kotlin
I want to assign my class variable in constructor, but I get an error 'expecting member declaration'

class YLAService {

    var context:Context?=null

    class YLAService constructor(context: Context) {
        this.context=context;// do something
    }
}
```

答:
In Kotlin you can use constructors like so:

```<code>class YLAService constructor(val context: Context) {

}
</code>```

Even shorter:

```<code>class YLAService(val context: Context) {

}
</code>```

If you want to do some processing first:

```<code>class YLAService(context: Context) {

  val locationService: LocationManager

  init {
    locationService = context.getService(LocationManager::class.java)
  }
}
</code>```

If you really want to use a secondary constructor:

```<code>class YLAService {

  val context: Context

  constructor(context: Context) {
    this.context = context
  }

}
</code>```

This looks more like the Java variant, but is more verbose.

See the Kotlin reference on constructors.

ContentLicense: CC BY-SA 4.0

Title: Expecting member declaration in Kotlin

Body:
In Kotlin you can use constructors like so:

class YLAService constructor(val context: Context) {

}

Even shorter:

class YLAService(val context: Context) {

}

If you want to do some processing first:

class YLAService(context: Context) {

  val locationService: LocationManager

  init {
    locationService = context.getService(LocationManager::class.java)
  }
}

If you really want to use a secondary constructor:

class YLAService {

  val context: Context

  constructor(context: Context) {
    this.context = context
  }

}

This looks more like the Java variant, but is more verbose.

See the Kotlin reference on constructors.


问:
Checking if a file exists from stdin <
I'm trying to create validation on a Python script that should take a file from the commandline. Much like:

./script.py < somefilename

As you can see the filename could come without any sort of extension on it. This should also work on multiple platforms, preferably.

In terms of validation it should be able to hold lines of strings separated by a newline character \n.

This poses two problems that I can't really solve:

I want to ensure that the file is of a correct filetype (ie. can hold text)

Check so the file actually exists.

In my current form I use argparse to parse flags, but since the requirements have changed I need to use a more dynamic (they say), solution where I implement the < "piper". This is quite simple by using stdin.

But using stdin poses a problem as I can't verify that the file exists; a user might input textfile without a correct extension, which would display

'No such file or directory'

What I'd like to do is create a list of possible extensions that could hold text (like '.txt') and check if a file with that extension exists in case the inputted file doesn't exist in the current folder. Just to make it more robust...

This seems to be very difficult (if not impossible) when using stdin, as you can't properly interface with the filename on multiple platforms.

I've also tried using fileinput, but I can't use a fileinput.filename() until I'm already reading the file:

```<code>for line in fileinput.input():
    print fileinput.filename()
</code>```

Does anyone have any suggestions on how I can add some robust file validation on the above mentioned example (./script.py < somefilename)?

Is it even possible on multiple platforms?

答:
There's no way for your program to determine how it was called by the shell, so these two commands are indistinguishable from your program's perspective:

```<code>$ ./script.py < somefilename
</code>```

and

```<code>$ cat somefilename | script.py
</code>```

If file somefilename doesn't exist, the caller will get a shell error like No such file or directory, and ./script.py won't be even called by the shell, so there's no chance for it to validate anything in principle.

If the goal you're trying to achieve is to validate your program's arguments, you can always provide an additional way for that by passing input file to it using -i switch: ./script.py -i somefilename, and validate file somefilename for existence. In order to achieve the desired level of versatility, the program also may provide an option to be called without -i switch, assuming that the file should be read from the stdin.

Title: Checking if a file exists from stdin <

Body:
I'm trying to create validation on a Python script that should take a file from the commandline. Much like:

./script.py < somefilename

As you can see the filename could come without any sort of extension on it. This should also work on multiple platforms, preferably.

In terms of validation it should be able to hold lines of strings separated by a newline character \n.

This poses two problems that I can't really solve:

I want to ensure that the file is of a correct filetype (ie. can hold text)

Check so the file actually exists.

In my current form I use argparse to parse flags, but since the requirements have changed I need to use a more dynamic (they say), solution where I implement the < "piper". This is quite simple by using stdin.

But using stdin poses a problem as I can't verify that the file exists; a user might input textfile without a correct extension, which would display

'No such file or directory'

What I'd like to do is create a list of possible extensions that could hold text (like '.txt') and check if a file with that extension exists in case the inputted file doesn't exist in the current folder. Just to make it more robust...

This seems to be very difficult (if not impossible) when using stdin, as you can't properly interface with the filename on multiple platforms.

I've also tried using fileinput, but I can't use a fileinput.filename() until I'm already reading the file:

for line in fileinput.input():
    print fileinput.filename()

Does anyone have any suggestions on how I can add some robust file validation on the above mentioned example (./script.py < somefilename)?

Is it even possible on multiple platforms?

Body:
There's no way for your program to determine how it was called by the shell, so these two commands are indistinguishable from your program's perspective:

$ ./script.py < somefilename

and

$ cat somefilename | script.py

If file somefilename doesn't exist, the caller will get a shell error like No such file or directory, and ./script.py won't be even called by the shell, so there's no chance for it to validate anything in principle.

If the goal you're trying to achieve is to validate your program's arguments, you can always provide an additional way for that by passing input file to it using -i switch: ./script.py -i somefilename, and validate file somefilename for existence. In order to achieve the desired level of versatility, the program also may provide an option to be called without -i switch, assuming that the file should be read from the stdin.


问:
How to create stacked bar chart using react-chartjs-2?
I have to create stacked bar chart using react-chartjs-2.

```<code>options : {
    maintainAspectRatio: false,
    tooltips: {
      mode: 'x-axis'
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        stacked: true
      }]
    }
  }
</code>```

The stacked in Bar doesn't seem to work.

I am using chartjs@2.4.0

答:
 const options = {
       scales: {
            xAxes: [{
                stacked: true
            }],
            yAxes: [{
                stacked: true
            }]
        }
    }

    let data ={
      datasets:[{
        label: 'test1',
          data :[1]
        },
        {
          label: 'test2',
          data:  [2]
        }],
      labels:['label']
    }

    render(){
      return  <Bar  data={data} options={options} />
    }```

Body:
I have to create stacked bar chart using react-chartjs-2.

options : {
    maintainAspectRatio: false,
    tooltips: {
      mode: 'x-axis'
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        stacked: true
      }]
    }
  }

The stacked in Bar doesn't seem to work.

I am using chartjs@2.4.0


答:
You can also use regex to get the am or pm
from the string

```<code>"06:04:51 am".match(/(am|pm)/gi)
["am"]

"06:04:51 pm".match(/(am|pm)/gi)
["pm"]
</code>```

Using case insensitive flag ensures that it matches AM,PM also

Title: Extract am or pm in jquery

Body:
You can also use regex to get the am or pm
from the string

"06:04:51 am".match(/(am|pm)/gi)
["am"]

"06:04:51 pm".match(/(am|pm)/gi)
["pm"]

Using case insensitive flag ensures that it matches AM,PM also


问:
Twilio client: Outbound call isn't showing agent/caller name in 'From' field on call logs
I'm making an outbound call from my Twilio client to make outbound web browser calls. The calls are successfuly made and are fine, but...

Unfortunately I'm unable to see the agent/client name in your logs. I am currently using the agent/client name of 'Andy' but in Twilio's call logs it's showing the 'From' field as anonymous.

I have made a few changes to the JavaScript SDK and have added the following ''//CLIENT NAME clientName: 'Andy'' in the 'params' variable but this hasn't made a difference and the from field is still showing up as Anonymous in Twilio's call logs when I make an outbound call using the browser client.

How do I make this work? :(

Here is my code:

```<code>// Bind button to make call
  document.getElementById('button-call').onclick = function () {
    // get the phone number to connect the call to
    var params = {

      //CLIENT NAME
      clientName: 'Andy',

      //PARAMETERS THAT WILL BE SENT THROUGH TO TWILIO
      To: document.getElementById('customer-number').value,

      //THIS IS CUSTOMER CALLER ID WE'RE PASSING TO THE OUTGOING TWIML AS THE CALLER ID TO USE FOR OUTGOING CALL
      CallerID: document.getElementById('source-number').value
    };

    console.log('Calling ' + params.To + '...');
    Twilio.Device.connect(params);
  };
</code>```

答:
Twilio developer evangelist here.

The parameters you pass into Twilio.Device.connect are not recorded by Twilio, but they are sent on as parameters to the URL you set as your application URL.

Client names are actually only required for incoming calls that are routed to a client. If you were to setup a client for outgoing calls only you need not setup a name. As such, client names are not captured by Twilio in the call logs.

If you need to track which clients are making calls you can do so within your own application by reading the clientName that you set in Twilio.Device.connect from the webhook parameters and associating it with the CallSid (also available in the webhook parameters).

Body:
I'm making an outbound call from my Twilio client to make outbound web browser calls. The calls are successfuly made and are fine, but...

Unfortunately I'm unable to see the agent/client name in your logs. I am currently using the agent/client name of 'Andy' but in Twilio's call logs it's showing the 'From' field as anonymous.

I have made a few changes to the JavaScript SDK and have added the following ''//CLIENT NAME clientName: 'Andy'' in the 'params' variable but this hasn't made a difference and the from field is still showing up as Anonymous in Twilio's call logs when I make an outbound call using the browser client.

How do I make this work? :(

Here is my code:

// Bind button to make call
  document.getElementById('button-call').onclick = function () {
    // get the phone number to connect the call to
    var params = {

      //CLIENT NAME
      clientName: 'Andy',

      //PARAMETERS THAT WILL BE SENT THROUGH TO TWILIO
      To: document.getElementById('customer-number').value,

      //THIS IS CUSTOMER CALLER ID WE'RE PASSING TO THE OUTGOING TWIML AS THE CALLER ID TO USE FOR OUTGOING CALL
      CallerID: document.getElementById('source-number').value
    };

    console.log('Calling ' + params.To + '...');
    Twilio.Device.connect(params);
  };


问:
Lucene: exception - Query parser encountered <EOF> after "some word"
I am working on a classification problem to classify product reviews as positive, negative or neutral as per the training data using Lucene API.

I am using an ArrayList of Review objects - "reviewList" that stores the attributes for each review while crawling the web pages.

The review attributes which include "polarity" & "review content" are then indexed using the indexer. Thereafter, based on the indexes objects, I need to classify the remaining review objects. But while doing so, there is a review object for which the Query parser is encountering an EOF character in the "review content", and hence terminating.

The line causing error has been commented accordingly -

```<code>    IndexReader reader = IndexReader.open(FSDirectory.open(new File("index")));
    IndexSearcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
    QueryParser parser = new QueryParser(Version.LUCENE_31, "Review", analyzer);

    int length = Crawler.reviewList.size();
    for (int i = 200; i < length; i++) {
        String true_class;
        double r_stars = Crawler.reviewList.get(i).getStars();

        if (r_stars < 2.0) {
            true_class = "-1";
        } else if (r_stars > 3.0) {
            true_class = "1";
        } else {
            true_class = "0";
        }

        String[] reviewTokens = Crawler.reviewList.get(i).getReview().split(" ");
        String parsedReview = "";

        int j;

        for (j = 0; j < reviewTokens.length; j++) {
            if (reviewTokens[j] != null) {
                if (!((reviewTokens[j].contains("-")) || (reviewTokens[j].contains("!")))) {
                    parsedReview += reviewTokens[j] + " ";
                }
            } else {
                break;
            }
        }

        Query query = parser.parse(parsedReview); // CAUSING ERROR!!

        TopScoreDocCollector results = TopScoreDocCollector.create(5, true);
        searcher.search(query, results);
        ScoreDoc[] hits = results.topDocs().scoreDocs;
</code>```

I've parsed the text manually to remove the characters that are causing the error, apart from checking if the next string is null...but the error persists.

This is the error stack trace -

```<code>Exception in thread "main" org.apache.lucene.queryParser.ParseException: Cannot parse 'I made the choice ... be all "thumbs ': Lexical error at line 1, column 938.  Encountered: <EOF> after : "\"thumbs "
at org.apache.lucene.queryParser.QueryParser.parse(QueryParser.java:216)
at Sentiment_Analysis.Classification.classify(Classification.java:58)
at Sentiment_Analysis.Main.main(Main.java:17)
Caused by: org.apache.lucene.queryParser.TokenMgrError: Lexical error at line 1, column 938.  Encountered: <EOF> after : "\"thumbs "
at org.apache.lucene.queryParser.QueryParserTokenManager.getNextToken(QueryParserTokenManager.java:1229)
at org.apache.lucene.queryParser.QueryParser.jj_scan_token(QueryParser.java:1709)
at org.apache.lucene.queryParser.QueryParser.jj_3R_2(QueryParser.java:1598)
at org.apache.lucene.queryParser.QueryParser.jj_3_1(QueryParser.java:1605)
at org.apache.lucene.queryParser.QueryParser.jj_2_1(QueryParser.java:1585)
at org.apache.lucene.queryParser.QueryParser.Clause(QueryParser.java:1280)
at org.apache.lucene.queryParser.QueryParser.Query(QueryParser.java:1266)
at org.apache.lucene.queryParser.QueryParser.Clause(QueryParser.java:1313)
at org.apache.lucene.queryParser.QueryParser.Query(QueryParser.java:1266)
at org.apache.lucene.queryParser.QueryParser.TopLevelQuery(QueryParser.java:1226)
at org.apache.lucene.queryParser.QueryParser.parse(QueryParser.java:206)
... 2 more
Java Result: 1
</code>```

Please help me solve this problem...have been banging my head with this for hours now!

答:
I recognise this problem.

Declaring the GROUP BY before the WHERE declaration works fine in Teradata, but throws an error while parsing.

To fix, move the GROUP BY declaration after the WHERE declaration.

Body:
I am working on a classification problem to classify product reviews as positive, negative or neutral as per the training data using Lucene API.

I am using an ArrayList of Review objects - "reviewList" that stores the attributes for each review while crawling the web pages.

The review attributes which include "polarity" & "review content" are then indexed using the indexer. Thereafter, based on the indexes objects, I need to classify the remaining review objects. But while doing so, there is a review object for which the Query parser is encountering an EOF character in the "review content", and hence terminating.

The line causing error has been commented accordingly -

    IndexReader reader = IndexReader.open(FSDirectory.open(new File("index")));
    IndexSearcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
    QueryParser parser = new QueryParser(Version.LUCENE_31, "Review", analyzer);

    int length = Crawler.reviewList.size();
    for (int i = 200; i < length; i++) {
        String true_class;
        double r_stars = Crawler.reviewList.get(i).getStars();

        if (r_stars < 2.0) {
            true_class = "-1";
        } else if (r_stars > 3.0) {
            true_class = "1";
        } else {
            true_class = "0";
        }

        String[] reviewTokens = Crawler.reviewList.get(i).getReview().split(" ");
        String parsedReview = "";

        int j;

        for (j = 0; j < reviewTokens.length; j++) {
            if (reviewTokens[j] != null) {
                if (!((reviewTokens[j].contains("-")) || (reviewTokens[j].contains("!")))) {
                    parsedReview += reviewTokens[j] + " ";
                }
            } else {
                break;
            }
        }

        Query query = parser.parse(parsedReview); // CAUSING ERROR!!

        TopScoreDocCollector results = TopScoreDocCollector.create(5, true);
        searcher.search(query, results);
        ScoreDoc[] hits = results.topDocs().scoreDocs;

I've parsed the text manually to remove the characters that are causing the error, apart from checking if the next string is null...but the error persists.

This is the error stack trace -

Exception in thread "main" org.apache.lucene.queryParser.ParseException: Cannot parse 'I made the choice ... be all "thumbs ': Lexical error at line 1, column 938.  Encountered: <EOF> after : "\"thumbs "
at org.apache.lucene.queryParser.QueryParser.parse(QueryParser.java:216)
at Sentiment_Analysis.Classification.classify(Classification.java:58)
at Sentiment_Analysis.Main.main(Main.java:17)
Caused by: org.apache.lucene.queryParser.TokenMgrError: Lexical error at line 1, column 938.  Encountered: <EOF> after : "\"thumbs "
at org.apache.lucene.queryParser.QueryParserTokenManager.getNextToken(QueryParserTokenManager.java:1229)
at org.apache.lucene.queryParser.QueryParser.jj_scan_token(QueryParser.java:1709)
at org.apache.lucene.queryParser.QueryParser.jj_3R_2(QueryParser.java:1598)
at org.apache.lucene.queryParser.QueryParser.jj_3_1(QueryParser.java:1605)
at org.apache.lucene.queryParser.QueryParser.jj_2_1(QueryParser.java:1585)
at org.apache.lucene.queryParser.QueryParser.Clause(QueryParser.java:1280)
at org.apache.lucene.queryParser.QueryParser.Query(QueryParser.java:1266)
at org.apache.lucene.queryParser.QueryParser.Clause(QueryParser.java:1313)
at org.apache.lucene.queryParser.QueryParser.Query(QueryParser.java:1266)
at org.apache.lucene.queryParser.QueryParser.TopLevelQuery(QueryParser.java:1226)
at org.apache.lucene.queryParser.QueryParser.parse(QueryParser.java:206)
... 2 more
Java Result: 1

Please help me solve this problem...have been banging my head with this for hours now!


问:
How do you launch a youtube video from within an iPad app?
How do you launch a youtube video from within an iPad app?</p>

答:
```<code>NSString *stringURL = @"/*your youtube video URL/*";
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];
</code>```


问:
get authorization header token with node js
I would like to get token in backend node js.

First, I get the token from jwt and I stored in localstorage,but when i would like to send a request with this token, I can't get it in server side.

Client side:

```<code>        function list_users(){
            url= "http://localhost:8181/users";
            var tok = window.localStorage.getItem('token');
            if (tok) {
        /*
        $.ajaxSetup({
                    headers: {
                        'x-access-token': tok
                    }
                });
        */

                $.ajax({
                headers: {'Authorization': tok},
                dataType: "application/json; charset=utf-8",
                url,
                type: 'GET',
                dataType: 'json',
                success: function (json) {
    alert("done");
    }
})
}
}
</code>```

Server side:

```<code>router.use(function(req, res, next) {

res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Authorization");

console.log(req.headers['authorization']);
...

}
</code>```

But

req.headers['authorization']

print

"undefined"

Any solution please.

答:
Try something like this:</p>

```<code>.....
.....

$.ajax({
         headers: {'Authorization': 'Bearer '+tok},
......
......
</code>```

Body:
I would like to get token in backend node js.

First, I get the token from jwt and I stored in localstorage,but when i would like to send a request with this token, I can't get it in server side.

Client side:

        function list_users(){
            url= "http://localhost:8181/users";
            var tok = window.localStorage.getItem('token');
            if (tok) {
        /*
        $.ajaxSetup({
                    headers: {
                        'x-access-token': tok
                    }
                });
        */

                $.ajax({
                headers: {'Authorization': tok},
                dataType: "application/json; charset=utf-8",
                url,
                type: 'GET',
                dataType: 'json',
                success: function (json) {
    alert("done");
    }
})
}
}

Server side:

router.use(function(req, res, next) {

res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Authorization");

console.log(req.headers['authorization']);
...

}

But

req.headers['authorization']

print

"undefined"

Any solution please.

Body:
Try something like this:

.....
.....

$.ajax({
         headers: {'Authorization': 'Bearer '+tok},
......
......


问:
Python ValueError: No JSON object could be decoded
I'm trying to read a json and get its values.
I have a folder with the JSON's archives, and I need to open all archives and get the values from them.

This is the code:

```<code># -*- encoding: utf-8 -*-
from pprint import pprint
import json
import os
def start():
    for dirname, dirnames, filenames in os.walk('test'):
        for filename in filenames:
            json_file = open(os.path.join(dirname, filename)).read()
            # json_file = unicode(json_file, 'utf-8')
            json_data = json.loads(json_file)
           pprint(json_data)
            for key, value in json_data.items():
                print "KEY : ", key
                print "VALUE: ", value
                start()
</code>```

This is one of the JSON's

```<code>{ "test" : "Search User 1",
   "url"  : "http://127.0.0.1:8000/api/v1/user/1/?format=json",
   "status_code" : 200,
   "method" : "get"
}
</code>```

But when I run it, i get this:

```<code>ValueError: No JSON object could be decoded
</code>```

What the hell is wrong? Yesterday it was working exactly as it is now, or am I crazy

I tried this way:

```<code>from pprint import pprint
import json
import os
for dirname, dirnames, filenames in os.walk('test'):
    for filename in filenames:
        json_file_contents = open(os.path.join(dirname, filename)).read()
        try:
            json_data = json.loads(json_file_contents)
        except ValueError, e:
            print e
            print "ERROR"
</code>```

I cant see any error '-'

```<code>for filename in filenames:
        with open(os.path.join(dirname,filename)) as fd:
            json_data = fd.read()
            print json_data
</code>```

This way I can see what the json files contain, but I can't use for example access by the key, like json_data['url']

答:
I resolved this error by Converting the json file to UTF-8 with no BOM.
Below is a python snippet and url for conversion</p>

```<code>myFile=open(cases2.json, 'r')
myObject=myFile.read()
u = myObject.decode('utf-8-sig')
myObject = u.encode('utf-8')
myFile.encoding
myFile.close()
myData=json.loads(myObject,'utf-8')
</code>```

Body:
I'm trying to read a json and get its values.
I have a folder with the JSON's archives, and I need to open all archives and get the values from them.

This is the code:

# -*- encoding: utf-8 -*-
from pprint import pprint
import json
import os
def start():
    for dirname, dirnames, filenames in os.walk('test'):
        for filename in filenames:
            json_file = open(os.path.join(dirname, filename)).read()
            # json_file = unicode(json_file, 'utf-8')
            json_data = json.loads(json_file)
           pprint(json_data)
            for key, value in json_data.items():
                print "KEY : ", key
                print "VALUE: ", value
                start()

This is one of the JSON's

{ "test" : "Search User 1",
   "url"  : "http://127.0.0.1:8000/api/v1/user/1/?format=json",
   "status_code" : 200,
   "method" : "get"
}

But when I run it, i get this:

ValueError: No JSON object could be decoded

What the hell is wrong? Yesterday it was working exactly as it is now, or am I crazy

I tried this way:

from pprint import pprint
import json
import os
for dirname, dirnames, filenames in os.walk('test'):
    for filename in filenames:
        json_file_contents = open(os.path.join(dirname, filename)).read()
        try:
            json_data = json.loads(json_file_contents)
        except ValueError, e:
            print e
            print "ERROR"

I cant see any error '-'

for filename in filenames:
        with open(os.path.join(dirname,filename)) as fd:
            json_data = fd.read()
            print json_data

This way I can see what the json files contain, but I can't use for example access by the key, like json_data['url']

Body:
I resolved this error by Converting the json file to UTF-8 with no BOM.
Below is a python snippet and url for conversion

myFile=open(cases2.json, 'r')
myObject=myFile.read()
u = myObject.decode('utf-8-sig')
myObject = u.encode('utf-8')
myFile.encoding
myFile.close()
myData=json.loads(myObject,'utf-8')


问:
How is to run applications on Android?
First I'm sorry because my English language is poor.
But is my question.
How is to compile and run application written in c/c++ and under NDK on Android OS??
Does it application compiling and running in Dalvik or ART?
Or independent is that VM??
In the case of programs written in other languages, how is it?
For example (C# in Xamarin) or (Delphi in Firemonkey) or (Basic) or (Python)? Thanks a lot for my question answers.</p>

答:
Please, do a research.

Basically yes, almost all non native solutions use some kind of VMs. For example Xamarin use MonoVM for Android platform. The C# code is compiled into CIL, which is executed by the Mono execution environment. This execution environment is run side by side with the Java Virtual Machine, which means the applications are not executed the same as native application, however they are executed in a equivalent way. This means that the performance is tied to MonoVMs implementation.

MonoVM is packaged with the application, which means that Xamarin Platform applications can be installed in the same way as a native application, without any additional installs.

Title: How is to run applications on Android?


问:
Downsizing header, removing footer entirely
I am working/designing the front-end (working on the layout html+css, later will use php, mvc pattern) of a website. The website has a header, body, side menu and a footer The layout is ready.

There are a few forms which are unusually long/huge since all fields are necessary and I could not make them any shorter. The form opens in a new page.

Not to scare the user away I am planning to downsize the header on the form template (the design change will only apply to the form templates) and get rid of the footer completely.

I tried looking a few places but did not find how to go it done. In short, I want the site to have all block i.e. header, body, footer but when it comes to the form I would want to downsize the header and remove the footer to make the form look sleeker.

Is there a way to do this?

Note: I post no code because I have no problem with the code but the concept.

答:
Make sure the body of the page has a class, for example .no-footer .small-header or .form-page. and then in your CSS stylesheet, use something like this :

```<code>body.no-footer #footer{
    display:none;
}
body.small-header #header{
    height:50px;
    /* or whatever you want to apply to make the header smaller */
}
</code>```

Body:
Make sure the body of the page has a class, for example .no-footer .small-header or .form-page. and then in your CSS stylesheet, use something like this :

body.no-footer #footer{
    display:none;
}
body.small-header #header{
    height:50px;
    /* or whatever you want to apply to make the header smaller */
}


问:
AWS Redshift ETL Process
I'm investigating redshift for our Data Warehouse, and I'm trying to think of how to architect a solution.

I have an instance of Amazon Kinesis Firehose as a delivery stream which writes to my Redshift database, and all that works fine.

Now my issue is how do I automate the creation of dimensions and fact tables.

Can I use a Lambda function in the delivery stream to write to the fact table and update the dimensions?

答:
The Data Transformation capability of AWS Lambda on an Amazon Kinesis Firehose is purely to modify or exclude streaming data. It cannot be used to create other tables.

If you wish to create dimension and fact tables, or otherwise perform ETL, you'll need to trigger it externally, such as having a scheduled task run SQL commands on your Amazon Redshift instance. This task would connect via JDBC/ODBC to run the commands.

Title: AWS Redshift ETL Process


问:
Assign new value to var in loop
Don´t have access to var in loop. Why? thanks.

```<code>   var grupo = "A"
   for (a <- dataframe) {
        grupo = "B"
    }
    println(grupo) //Print A
</code>```

Edit!

dataframe filterP show like this:

```<code>|   CODIGO|LISTA|NUMERO|OPCION|NUMERO|OP|VALOR|
+---------+-----+------+------+------+--+-----+
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     A|  0000| 1|    2|
|110111001|    P|  0000|     A|  0000| 1|    3|
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     B|  0000| 1|    2|
</code>```

Code:

```<code>var grupo = List(filterP.first()(3).toString())
   var grupo_tmp = grupo(0)
   println("first group:" + grupo(0))
   for (a <- filterP) {
       if(grupo_tmp != a(3).toString()){
         println(grupo_tmp + "|" + a(3).toString())
         grupo = a(3).toString() :: grupo
         grupo_tmp = a(3).toString()
       }
    }
    println(grupo_tmp)
    println("Grupos de lista "+grupo.length)
    for(i <- 0 to grupo.length-1){
      println("grupo: "+ grupo(i))
    }
</code>```

This print:

```<code>   first group:A
   A|B
   A
   Grupos de lista 1
   grupo: A
</code>```

I don`t see where is the problem..

答:
I am wondering how your for loop is working without you collecting the filterP dataframe. for loop is just transformation and println should not have executed without an action on the dataframe.

Dataframes are partitioned by dafault and I am guessing is that your dataframe is partitioned and you are getting only partial output.

collecting dataframe to the driver should solve the issue

```<code>var grupo = List(filterP.first()(3).toString())
var grupo_tmp = grupo(0)
println("first group:" + grupo(0))
for (a <- filterP.collect) { //collect the dataframe to the driver
  if(grupo_tmp != a(3).toString()){
    println(grupo_tmp + "|" + a(3).toString())
    grupo = a(3).toString() :: grupo
    grupo_tmp = a(3).toString()
  }
}
println(grupo_tmp)
println("Grupos de lista "+grupo.length)
for(i <- 0 to grupo.length-1){
  println("grupo: "+ grupo(i))
}
</code>```

I get the output as

```<code>first group:A
A|B
B
Grupos de lista 2
grupo: B
grupo: A
</code>```

Title: Assign new value to var in loop

Body:
Don´t have access to var in loop. Why? thanks.

   var grupo = "A"
   for (a <- dataframe) {
        grupo = "B"
    }
    println(grupo) //Print A

Edit!

dataframe filterP show like this:

|   CODIGO|LISTA|NUMERO|OPCION|NUMERO|OP|VALOR|
+---------+-----+------+------+------+--+-----+
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     A|  0000| 1|    2|
|110111001|    P|  0000|     A|  0000| 1|    3|
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     B|  0000| 1|    2|

Code:

var grupo = List(filterP.first()(3).toString())
   var grupo_tmp = grupo(0)
   println("first group:" + grupo(0))
   for (a <- filterP) {
       if(grupo_tmp != a(3).toString()){
         println(grupo_tmp + "|" + a(3).toString())
         grupo = a(3).toString() :: grupo
         grupo_tmp = a(3).toString()
       }
    }
    println(grupo_tmp)
    println("Grupos de lista "+grupo.length)
    for(i <- 0 to grupo.length-1){
      println("grupo: "+ grupo(i))
    }

This print:

   first group:A
   A|B
   A
   Grupos de lista 1
   grupo: A

I don`t see where is the problem..

Body:
I am wondering how your for loop is working without you collecting the filterP dataframe. for loop is just transformation and println should not have executed without an action on the dataframe.

Dataframes are partitioned by dafault and I am guessing is that your dataframe is partitioned and you are getting only partial output.

collecting dataframe to the driver should solve the issue

var grupo = List(filterP.first()(3).toString())
var grupo_tmp = grupo(0)
println("first group:" + grupo(0))
for (a <- filterP.collect) { //collect the dataframe to the driver
  if(grupo_tmp != a(3).toString()){
    println(grupo_tmp + "|" + a(3).toString())
    grupo = a(3).toString() :: grupo
    grupo_tmp = a(3).toString()
  }
}
println(grupo_tmp)
println("Grupos de lista "+grupo.length)
for(i <- 0 to grupo.length-1){
  println("grupo: "+ grupo(i))
}

I get the output as

first group:A
A|B
B
Grupos de lista 2
grupo: B
grupo: A


问:
C# Fastest search object which has nearest value given
I try to find an object in list which has nearest value that given
I wrote this :

```<code>float target = 100.0f;
int index = int.MaxValue;
float nearest = float.MaxValue;
for(int i = 0; i < objectList.Count; i++)
{
   if(Math.Abs(objectList[i].value - target) < nearest)
   {
       nearest = Math.Abs(objectList[i].value - target);
       index = i;
   }
}

//do something with objectList[index]
</code>```

This actually works, but when the list is too large, It consumes quite much time to search.

I know there are probably way to do it, but I don't know what is it.

答:
You can slightly speed up things by caching some values and inverting loop:

```<code>float target = 100.0f;
int index = -1;
float nearest = float.MaxValue;
int count = objectList.Count;
for(int i = count-1; i >= 0; i--)
{
   var diff = Math.Abs(objectList[i].value - target);
   if(diff < nearest)
   {
       nearest = diff;
       index = i;
   }
   if(nearest == 0)
       break;
}
</code>```

Also, if your object list not changing too much you can Sort it and apply binary nearest search which will run in O(log(n)). There is plenty of optimisations can be done.

For example, you can put everything into sorted binary tree (RB-tree for example) and run your search on it. It will run considerably faster than plain look. Of course this will work only if you have a bunch of searches on this list.

Other way would be to split array into batches and process them simulteniously through Parallel.For. Then just process result of batches.

Body:
I try to find an object in list which has nearest value that given
I wrote this :

float target = 100.0f;
int index = int.MaxValue;
float nearest = float.MaxValue;
for(int i = 0; i < objectList.Count; i++)
{
   if(Math.Abs(objectList[i].value - target) < nearest)
   {
       nearest = Math.Abs(objectList[i].value - target);
       index = i;
   }
}

//do something with objectList[index]

This actually works, but when the list is too large, It consumes quite much time to search.

I know there are probably way to do it, but I don't know what is it.

Body:
You can slightly speed up things by caching some values and inverting loop:

float target = 100.0f;
int index = -1;
float nearest = float.MaxValue;
int count = objectList.Count;
for(int i = count-1; i >= 0; i--)
{
   var diff = Math.Abs(objectList[i].value - target);
   if(diff < nearest)
   {
       nearest = diff;
       index = i;
   }
   if(nearest == 0)
       break;
}

Also, if your object list not changing too much you can Sort it and apply binary nearest search which will run in O(log(n)). There is plenty of optimisations can be done.

For example, you can put everything into sorted binary tree (RB-tree for example) and run your search on it. It will run considerably faster than plain look. Of course this will work only if you have a bunch of searches on this list.

Other way would be to split array into batches and process them simulteniously through Parallel.For. Then just process result of batches.


问:
Is it possible to create Ionic 2 project in Ionic 3 CLI
When I do this, I get the message below:

Command :

```<code>ionic start blank myapp --v2
</code>```

Error :

[ERROR] Sorry! The --v1 and --v2 flags have been removed.
          Use the --type option. (ionic start --help)
          For Ionic Angular projects, try ionic start blank myapp --type=ionic-angular

My Ionic CLI version is :

```<code>ionic -v
3.3.0
</code>```

答:
Update 2 : You can no longer create Ionic 2 project in Ionic 3 CLI.

As Ionic 2 was not updated & is rewritten using Ionic 3, which uses Angular 4.

So if you create new Ionic project it will use Ionic 3 by default.

Update 1 : More Info Available Here

With the updates few changes are done in syntax as well :

To create a new project : (You have 3 templates available with Ionic i.e. blank, tabs, sidemenu)

ionic start {{AppName}} {{TemplateName}} ==> Latest Ionic codebase project

ionic start {{AppName}} {{TemplateName}} --type ionic1 ==> Ionic v1 project

Yes, You can check this link out

ionic start [app-name] [template] --type=ionic1

ionic start [app-name] [template] --type=ionic2

ionic start [app-name] [template] --type=ionic-angular

I have Ionic -v 2.2.2 right now so couldn't test it, so please try and let me know ;)

Body:
When I do this, I get the message below:

Command :

ionic start blank myapp --v2

Error :

[ERROR] Sorry! The --v1 and --v2 flags have been removed.
          Use the --type option. (ionic start --help)
          For Ionic Angular projects, try ionic start blank myapp --type=ionic-angular

My Ionic CLI version is :

ionic -v
3.3.0


问:
Hide a dynamic element function on.('hide')
I have a problem with the following function. I am dynamically creating a bootstrap modal (regular div), and I want to attach a function I pass trough a variable (witch works fine) and run it on on.("hide"), but instead it fires as soon as the modal is opened ( $(modal).on('hide', windowclose_function ); ). Is there something I`m missing?

Thanks

```<code>function openModalFromUrl(modal_url, close_function = function(){}) {

    var token = $("meta[name='csrf-token']").attr("content");

    $.ajax({
        data: {
            '_token': token,
        },
        url: modal_url,
        type: 'POST',
        success: function(html) {

            // create a new modal div
            var modal = document.createElement("div");
            $(modal).addClass('modal fade');
            $(modal).attr( "role", "dialog" );

            $('body').append(modal);

            // place response in the modal
            $(modal).html(html)

            // open the modal
            $(modal).modal('show');

            // THIS FIRES IMMEDIATELY
            $(modal).on('hide', window[close_function]() );

        },

        error: function() {
            bootbox.alert('Error');
        }

    });

}
</code>```

答:
The issue is in this line :-

$(modal).on('hide', window[close_function]() );
```

<p><strong>Change it to :-</strong></p>

<pre class="lang-js prettyprint-override"><code>$(modal).on('hide', window[close_function] );
</code>```

Explanation :-

In JavaScript when we provide a function as a reference, we use it's name without any parenthesis

i.e. 'my_func' not 'my_func()'

As 'my_func()' give the result of the function as reference not the function itself.

So just remove the parenthesis and your problem is solved.

Body:
I have a problem with the following function. I am dynamically creating a bootstrap modal (regular div), and I want to attach a function I pass trough a variable (witch works fine) and run it on on.("hide"), but instead it fires as soon as the modal is opened ( $(modal).on('hide', windowclose_function ); ). Is there something I`m missing?

Thanks

function openModalFromUrl(modal_url, close_function = function(){}) {

    var token = $("meta[name='csrf-token']").attr("content");

    $.ajax({
        data: {
            '_token': token,
        },
        url: modal_url,
        type: 'POST',
        success: function(html) {

            // create a new modal div
            var modal = document.createElement("div");
            $(modal).addClass('modal fade');
            $(modal).attr( "role", "dialog" );

            $('body').append(modal);

            // place response in the modal
            $(modal).html(html)

            // open the modal
            $(modal).modal('show');

            // THIS FIRES IMMEDIATELY
            $(modal).on('hide', window[close_function]() );

        },

        error: function() {
            bootbox.alert('Error');
        }

    });

}

Body:
The issue is in this line :-

$(modal).on('hide', window[close_function]() );

Change it to :-

$(modal).on('hide', window[close_function] );

Explanation :-

In JavaScript when we provide a function as a reference, we use it's name without any parenthesis

i.e. 'my_func' not 'my_func()'

As 'my_func()' give the result of the function as reference not the function itself.

So just remove the parenthesis and your problem is solved.


问:
string split based on char \
Got a bit of a mind freeze at the moment.
I have the following syntax:-

```<code>        string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split('\');
</code>```

and I get an error on the split character. Can anyone advise on how I can do the split using the \ character as the delimiter?

Cheers

答:
Split takes a char[] as a parameter, not a char. Try;</p>

```<code>string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split(new char[] {'\\'});
</code>```

Title: string split based on char \

Body:
Got a bit of a mind freeze at the moment.
I have the following syntax:-

        string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split('\');

and I get an error on the split character. Can anyone advise on how I can do the split using the \ character as the delimiter?

Cheers

Body:
Split takes a char[] as a parameter, not a char. Try;

string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split(new char[] {'\\'});

OwnerDisplayName: Stu Mackellar


问:
converting date format
I got date as '14-Dec-2010' i want to get the month in number format for the given date.
that is., i want to convert the date to '14-12-2010'.

答:
```<code>DateFormat inFm = new SimpleDateFormat("d-MMM-y");
DateFormat outFm = new SimpleDateFormat("d-M-yyyy");
Date date = inFm.parse("14-Dec-2010");
String output = outFm.format(date);
</code>```

Generally, you should use a datetime type like Date internally, then transform to String at output time.

Title: converting date format

Body:
DateFormat inFm = new SimpleDateFormat("d-MMM-y");
DateFormat outFm = new SimpleDateFormat("d-M-yyyy");
Date date = inFm.parse("14-Dec-2010");
String output = outFm.format(date);

Generally, you should use a datetime type like Date internally, then transform to String at output time.


问:
What's the difference between a mock & stub?
I've read various articles about mocking vs stubbing in testing, including Martin Fowler's Mocks Aren't Stubs, but still don't understand the difference.</p>

答:
This slide explain the main differences very good.

*From CSE 403 Lecture 16 , University of Washington (slide created by "Marty Stepp")


问:
Python Error: Unexpected end of data while reading a .tar file
I'm trying to run TensorFlow's translate.py file, but after a few seconds already I keep getting this error:

```<code>tarfile.ReadError: unexpected end of data
</code>```

I have no idea why this happens and I've tried several things, including downloading the needed data myself and comment the line in the code that do the downloading, but nothing worked.

Here is the site that I follow:
https://www.tensorflow.org/tutorials/seq2seq

And just in case you need everything, here are the lines from the command to the error:

```<code>C:\Users\Mueller>python translate.py
Preparing WMT data in /tmp
Extracting tar file /tmp\training-giga-fren.tar
Traceback (most recent call last):
  File "translate.py", line 322, in <module>
    tf.app.run()
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\site-package
s\tensorflow\python\platform\app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "translate.py", line 319, in main
    train()
  File "translate.py", line 173, in train
    FLAGS.data_dir, FLAGS.from_vocab_size, FLAGS.to_vocab_size)
  File "C:\Users\Mueller\data_utils.py", line 267, in prepare_wmt_data
    train_path = get_wmt_enfr_train_set(data_dir)
  File "C:\Users\Mueller\data_utils.py", line 83, in get_wmt_enfr_train_set
    corpus_tar.extractall(directory)
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\tarfile.py",
 line 1996, in extractall
    numeric_owner=numeric_owner)
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\tarfile.py",
 line 2038, in extract
    numeric_owner=numeric_owner)
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\tarfile.py",
 line 2108, in _extract_member
    self.makefile(tarinfo, targetpath)
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\tarfile.py",
 line 2156, in makefile
    copyfileobj(source, target, tarinfo.size, ReadError)
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\tarfile.py",
 line 243, in copyfileobj
    raise exception("unexpected end of data")
tarfile.ReadError: unexpected end of data
</code>```

Does anybody know what is happening here?

答: If your machine is running behind a proxy server, its possible that the downloaded tar file maybe getting stripped/blocked by proxy server, resulting in corrupted downloaded file.</p>

Body:
I'm trying to run TensorFlow's translate.py file, but after a few seconds already I keep getting this error:

tarfile.ReadError: unexpected end of data

I have no idea why this happens and I've tried several things, including downloading the needed data myself and comment the line in the code that do the downloading, but nothing worked.

Here is the site that I follow:
https://www.tensorflow.org/tutorials/seq2seq

And just in case you need everything, here are the lines from the command to the error:

C:\Users\Mueller>python translate.py
Preparing WMT data in /tmp
Extracting tar file /tmp\training-giga-fren.tar
Traceback (most recent call last):
  File "translate.py", line 322, in <module>
    tf.app.run()
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\site-package
s\tensorflow\python\platform\app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "translate.py", line 319, in main
    train()
  File "translate.py", line 173, in train
    FLAGS.data_dir, FLAGS.from_vocab_size, FLAGS.to_vocab_size)
  File "C:\Users\Mueller\data_utils.py", line 267, in prepare_wmt_data
    train_path = get_wmt_enfr_train_set(data_dir)
  File "C:\Users\Mueller\data_utils.py", line 83, in get_wmt_enfr_train_set
    corpus_tar.extractall(directory)
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\tarfile.py",
 line 1996, in extractall
    numeric_owner=numeric_owner)
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\tarfile.py",
 line 2038, in extract
    numeric_owner=numeric_owner)
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\tarfile.py",
 line 2108, in _extract_member
    self.makefile(tarinfo, targetpath)
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\tarfile.py",
 line 2156, in makefile
    copyfileobj(source, target, tarinfo.size, ReadError)
  File "C:\Users\Mueller\AppData\Local\Programs\Python\Python35\lib\tarfile.py",
 line 243, in copyfileobj
    raise exception("unexpected end of data")
tarfile.ReadError: unexpected end of data

Does anybody know what is happening here?


问:
Trouble with installing python 2.7.12 on CentOS 6.8- adding path
Edited
I tried to install Python 2.7 on my OS.
I used the commenand :

```<code>yum install -y python27
</code>```

here is the output :

```<code>Loaded plugins: fastestmirror, refresh-packagekit, security
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: ftp.hosteurope.de
 * epel: repo.fedoralinux.ir
 * extras: ftp.hosteurope.de
 * updates: ftp.hosteurope.de
Package python27-1.1-25.el6.x86_64 already installed and latest version
Nothing to do
</code>```

So it seems that it's done.But I still see previous version 2.6. Which address I should add to path in .bashrc file
it is at :

```<code>/opt/rh/python27/root/lib/modules
/opt/rh/python27/root/usr/include/python2.7/moduleobject.h
/opt/rh/python27/root/usr/include/python2.7/sysmodule.h
/opt/rh/python27/root/usr/lib/python2.7/site-packages/nose/plugins/allmodules.py
/opt/rh/python27/root/usr/lib/python2.7/site-packages/nose/plugins/allmodules.pyc
/opt/rh/python27/root/usr/lib/python2.7/site-packages/nose/plugins/allmodules.pyo
/opt/rh/python27/root/usr/lib/python2.7/site-packages/sphinx/ext/autosummary/templates/autosummary/module.rst
/opt/rh/python27/root/usr/lib64/pm-utils/module.d
/opt/rh/python27/root/usr/lib64/python2.7/modulefinder.py
/opt/rh/python27/root/usr/lib64/python2.7/modulefinder.pyc
/opt/rh/python27/root/usr/lib64/python2.7/modulefinder.pyo
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_bisectmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_collectionsmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_cryptmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_functoolsmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_localemodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_multibytecodecmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_randommodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_socketmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/arraymodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/cmathmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/dlmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/fcntlmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/gdbmmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/grpmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/itertoolsmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/mmapmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/nismodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/parsermodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/selectmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/spwdmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/stropmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/timemodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/timingmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/zlibmodule.so
</code>```

Thanks for any comment or guide.

答:
Try this command:

```<code>. /opt/rh/python27/enable
</code>```

Then ask for python version:

```<code>python -V
</code>```

it outputs:

Python 2.7.8

Now be careful, this is going to work as long as you keep your session. I.E. : as soon as you exit your shell, your environment variables are gone.

Body:
Edited
I tried to install Python 2.7 on my OS.
I used the commenand :

yum install -y python27

here is the output :

Loaded plugins: fastestmirror, refresh-packagekit, security
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: ftp.hosteurope.de
 * epel: repo.fedoralinux.ir
 * extras: ftp.hosteurope.de
 * updates: ftp.hosteurope.de
Package python27-1.1-25.el6.x86_64 already installed and latest version
Nothing to do

So it seems that it's done.But I still see previous version 2.6. Which address I should add to path in .bashrc file
it is at :

/opt/rh/python27/root/lib/modules
/opt/rh/python27/root/usr/include/python2.7/moduleobject.h
/opt/rh/python27/root/usr/include/python2.7/sysmodule.h
/opt/rh/python27/root/usr/lib/python2.7/site-packages/nose/plugins/allmodules.py
/opt/rh/python27/root/usr/lib/python2.7/site-packages/nose/plugins/allmodules.pyc
/opt/rh/python27/root/usr/lib/python2.7/site-packages/nose/plugins/allmodules.pyo
/opt/rh/python27/root/usr/lib/python2.7/site-packages/sphinx/ext/autosummary/templates/autosummary/module.rst
/opt/rh/python27/root/usr/lib64/pm-utils/module.d
/opt/rh/python27/root/usr/lib64/python2.7/modulefinder.py
/opt/rh/python27/root/usr/lib64/python2.7/modulefinder.pyc
/opt/rh/python27/root/usr/lib64/python2.7/modulefinder.pyo
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_bisectmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_collectionsmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_cryptmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_functoolsmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_localemodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_multibytecodecmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_randommodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/_socketmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/arraymodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/cmathmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/dlmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/fcntlmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/gdbmmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/grpmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/itertoolsmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/mmapmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/nismodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/parsermodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/selectmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/spwdmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/stropmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/timemodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/timingmodule.so
/opt/rh/python27/root/usr/lib64/python2.7/lib-dynload/zlibmodule.so

Thanks for any comment or guide.

Body:
Try this command:

. /opt/rh/python27/enable

Then ask for python version:

python -V

it outputs:

Python 2.7.8

Now be careful, this is going to work as long as you keep your session. I.E. : as soon as you exit your shell, your environment variables are gone.


问:
Prolog - count occurrence of number
I want to write predicate which can count all encountered number:

```<code>count(1, [1,0,0,1,0], X).
X = 2.
</code>```

I tried to write it like:

```<code>count(_, [], 0).
count(Num, [H|T], X) :- count(Num, T, X1), Num = H, X is X1 + 1.
</code>```

Why doesn't work it?

答:
The problem is that as stated by @lurker if condition (or better unification) fails then the predicate will fail. You could make another clause for this purpose, using dif/2 which is pure and defined in the iso:

```<code>count(_, [], 0).
count(Num, [H|T], X) :- dif(Num,H), count(Num, T, X).
count(Num, [H|T], X) :- Num = H, count(Num, T, X1), X is X1 + 1.
</code>```

The above is not the most efficient solution since it leaves many choice points but it is a quick and correct solution.

Title: Prolog - count occurrence of number

Body:
I want to write predicate which can count all encountered number:

count(1, [1,0,0,1,0], X).
X = 2.

I tried to write it like:

count(_, [], 0).
count(Num, [H|T], X) :- count(Num, T, X1), Num = H, X is X1 + 1.

Why doesn't work it?

Body:
The problem is that as stated by @lurker if condition (or better unification) fails then the predicate will fail. You could make another clause for this purpose, using dif/2 which is pure and defined in the iso:

count(_, [], 0).
count(Num, [H|T], X) :- dif(Num,H), count(Num, T, X).
count(Num, [H|T], X) :- Num = H, count(Num, T, X1), X is X1 + 1.

The above is not the most efficient solution since it leaves many choice points but it is a quick and correct solution.


问:
Is ExpectedException used for testing more than one cases in one test method?
I am writing unit tests on each of several methods MyMethod1, MyMethod2, ...
For each method, I would like to test a case when it raises a particular exception and a case when it doesn't.

What I do now is to group the two cases for each method into a test method:

```<code>[TestMethod]
[TestCategory("Unit")]
public void MyTest()
{
    SetupExceptionCase();
    try
    {
        MyMethod1();
        Assert.Fail();
    }
    catch (InvalidDataException) { }

    SetupNonExceptionCase();
    try
    {
        MyMethod1();
    }
    catch (InvalidDataException)
    {
        Assert.Fail();
    }
}
</code>```

If I would like to use ExpectedException attribute to replace the more lengthy try...catch... control, as suggested in https://stackoverflow.com/a/933627/156458,

do I need to split my test method into two test methods, each for a case?

If yes, how can I use the attribute for the case where I don't expect my method to raise an exception?

Is there any way that I don't have to split it, because grouping two cases for the same method to be tested in a test method separates nicely the tests for different methods to be tested?

Thanks.

答:
Your unit test is actually testing two different cases, so logically it should be split out anyway. But in regards to using the out of the box attribute, it is applied to the method so yes, you would need to split them out (I'd recommend that anyway).

If yes, how can I use the attribute for the case where I don't expect my method to raise an exception?

If you are not expecting your method to raise an exception then do not use the attribute.

Is there any way that I don't have to split it, because grouping two cases for the same method to be tested in a test method separates nicely the tests for different methods to be tested?

It's best practice to split your tests out into units anyway, I'm not sure how you think grouping them is nice but it's not something I would recommend.

Body:
I am writing unit tests on each of several methods MyMethod1, MyMethod2, ...
For each method, I would like to test a case when it raises a particular exception and a case when it doesn't.

What I do now is to group the two cases for each method into a test method:

[TestMethod]
[TestCategory("Unit")]
public void MyTest()
{
    SetupExceptionCase();
    try
    {
        MyMethod1();
        Assert.Fail();
    }
    catch (InvalidDataException) { }

    SetupNonExceptionCase();
    try
    {
        MyMethod1();
    }
    catch (InvalidDataException)
    {
        Assert.Fail();
    }
}

If I would like to use ExpectedException attribute to replace the more lengthy try...catch... control, as suggested in https://stackoverflow.com/a/933627/156458,

do I need to split my test method into two test methods, each for a case?

If yes, how can I use the attribute for the case where I don't expect my method to raise an exception?

Is there any way that I don't have to split it, because grouping two cases for the same method to be tested in a test method separates nicely the tests for different methods to be tested?

Thanks.


问:
Running a command with os.system(A) produces different output then running A in shell
I have a hex to binary converter that I am using in a Python script...

```<code>os.system("./HexToBinary " + str(sys.argv[1]) + "_hex " + str(sys.argv[1]) + "_binary")
</code>```

If I run my python script on file A_hex, it produces file A_binary.

But if I run this command directly in the command-line, on file AA_hex it produces AA_binary. But A_binary and AA_binary differ!

```<code>diff example_python example_shell
Binary files example_python and example_shell differ
</code>```

The version produced by the python os.system call is missing a chunk of data from the end. It seems that it just gets cut off.

I'm kinda stumped. Any thoughts?

答:
I dont know if it is needed, but try wait, http://docs.python.org/library/os.html#os.wait

also, check the output of system, it may help tell you if something is wrong

Body:
I have a hex to binary converter that I am using in a Python script...

os.system("./HexToBinary " + str(sys.argv[1]) + "_hex " + str(sys.argv[1]) + "_binary")

If I run my python script on file A_hex, it produces file A_binary.

But if I run this command directly in the command-line, on file AA_hex it produces AA_binary. But A_binary and AA_binary differ!

diff example_python example_shell
Binary files example_python and example_shell differ

The version produced by the python os.system call is missing a chunk of data from the end. It seems that it just gets cut off.

I'm kinda stumped. Any thoughts?


问:
Laravel Three State Login Attempt
As default Laravel Login attempt method returns bool but I want to modify it and getting another result if user exists but user's status is passive.
I do not want to change any code in laravel vendor directory. I can write my own login method in LoginController like AuthenticatesUsers::login() easily but the problem is SessionGuard::attempt() has own lifecycle, it is not a trait that LoginController uses it.

Following is original version of SessionGuard::attempt() method.

```<code>public function attempt(array $credentials = [], $remember = false, $login = false)
{
    $this->fireAttemptEvent($credentials, $remember, $login);

    $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);

    // If an implementation of UserInterface was returned, we'll ask the provider
    // to validate the user against the given credentials, and if they are in
    // fact valid we'll log the users into the application and return true.
    if ($this->hasValidCredentials($user, $credentials)) {

        if ($login) {
            $this->login($user, $remember);
        }

        return true;
    }

    // If the authentication attempt fails we will fire an event so that the user
    // may be notified of any suspicious attempts to access their account from
    // an unrecognized user. A developer may listen to this event as needed.
    if ($login) {
        $this->fireFailedEvent($user, $credentials);
    }

    return false;
}
</code>```

Note:

```<code>$credentials = [
            'email' => $request->input('email'),
            'password' => $request->input('password'),
            'status_id' => 1
           ];
</code>```

But I want to remove status_id field and I want to show message to users if user's status_id is not 1.

Basically I just want to override SessionGuard::attempt() method, something like this.

```<code>public function attempt(array $credentials = [], $remember = false, $login = false)
{
    $this->fireAttemptEvent($credentials, $remember, $login);

    $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);

    // If an implementation of UserInterface was returned, we'll ask the provider
    // to validate the user against the given credentials, and if they are in
    // fact valid we'll log the users into the application and return true.
    if ($this->hasValidCredentials($user, $credentials)) {
        //User exists but user's status_id is not 1
        if($user->status_id != 1)
            return 2; // 2 for passive accounts
        if ($login) {
            $this->login($user, $remember);
        }

        return 1; //for active accounts
    }

    // If the authentication attempt fails we will fire an event so that the user
    // may be notified of any suspicious attempts to access their account from
    // an unrecognized user. A developer may listen to this event as needed.
    if ($login) {
        $this->fireFailedEvent($user, $credentials);
    }

    return 0; // for non exists acounts
}
</code>```

How can I achive this?

答:
You can do it inside your login function of your controller (normally the LoginController)

You first get the user with a unique email. Then you check if the account has the variable. If yes you can try to login the user, if not you can throw an error.

```<code>class LoginController extends Controller
{

    use AuthenticatesUsers;

        public function login(Request $request) {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }
        $user = App\User::where('email', $request->get('email'))->first();

        if ($user && $user->status_id == 1 && $this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
}
</code>```

Title: Laravel Three State Login Attempt

Body:
As default Laravel Login attempt method returns bool but I want to modify it and getting another result if user exists but user's status is passive.
I do not want to change any code in laravel vendor directory. I can write my own login method in LoginController like AuthenticatesUsers::login() easily but the problem is SessionGuard::attempt() has own lifecycle, it is not a trait that LoginController uses it.

Following is original version of SessionGuard::attempt() method.

public function attempt(array $credentials = [], $remember = false, $login = false)
{
    $this->fireAttemptEvent($credentials, $remember, $login);

    $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);

    // If an implementation of UserInterface was returned, we'll ask the provider
    // to validate the user against the given credentials, and if they are in
    // fact valid we'll log the users into the application and return true.
    if ($this->hasValidCredentials($user, $credentials)) {

        if ($login) {
            $this->login($user, $remember);
        }

        return true;
    }

    // If the authentication attempt fails we will fire an event so that the user
    // may be notified of any suspicious attempts to access their account from
    // an unrecognized user. A developer may listen to this event as needed.
    if ($login) {
        $this->fireFailedEvent($user, $credentials);
    }

    return false;
}

Note:

$credentials = [
            'email' => $request->input('email'),
            'password' => $request->input('password'),
            'status_id' => 1
           ];

But I want to remove status_id field and I want to show message to users if user's status_id is not 1.

Basically I just want to override SessionGuard::attempt() method, something like this.

public function attempt(array $credentials = [], $remember = false, $login = false)
{
    $this->fireAttemptEvent($credentials, $remember, $login);

    $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);

    // If an implementation of UserInterface was returned, we'll ask the provider
    // to validate the user against the given credentials, and if they are in
    // fact valid we'll log the users into the application and return true.
    if ($this->hasValidCredentials($user, $credentials)) {
        //User exists but user's status_id is not 1
        if($user->status_id != 1)
            return 2; // 2 for passive accounts
        if ($login) {
            $this->login($user, $remember);
        }

        return 1; //for active accounts
    }

    // If the authentication attempt fails we will fire an event so that the user
    // may be notified of any suspicious attempts to access their account from
    // an unrecognized user. A developer may listen to this event as needed.
    if ($login) {
        $this->fireFailedEvent($user, $credentials);
    }

    return 0; // for non exists acounts
}

How can I achive this?

Body:
You can do it inside your login function of your controller (normally the LoginController)

You first get the user with a unique email. Then you check if the account has the variable. If yes you can try to login the user, if not you can throw an error.

class LoginController extends Controller
{

    use AuthenticatesUsers;

        public function login(Request $request) {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }
        $user = App\User::where('email', $request->get('email'))->first();

        if ($user && $user->status_id == 1 && $this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
}


问:
I want to create a window manager dialog when incoming call is detected but click event is not working
I want to create a window manager dialog when incoming call is detected but click event is not working

I want click event in the dialog and outside the dialog as I would want to receive calls

```<code>windowManager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.CENTER;
</code>```

答:
use code.

LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    2003,
                    262184,
                    PixelFormat.TRANSPARENT);

work properly..

Body:
I want to create a window manager dialog when incoming call is detected but click event is not working

I want click event in the dialog and outside the dialog as I would want to receive calls

windowManager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.CENTER;


问:
Receiving data from Myo stops after a while
I am using this (https://github.com/dzhu/myo-raw) project to connect Myo Armband to my PC (running on Windows) and receive raw EMG data. I have two problems related to this:

1) Data receiving is extremely slow, but the author had warned about this. It seems, that switching off everything except for EMG speeds up receiving the data, but is there a way to speed it up more? BTW, everything is fine on Linux;

2) Data receiving crashes after a while. I've noticed, that it usually crashes when I try to do "strong" gestures like making fist and moving my right hand to the right. I don`t have an explanation to this since everything works fine under Linux.

I am asking my question here because GitHub page seems to be dead.

答:
So, problem was so trivial than I have been blaming myself for hours. When adding n = self.ser.inWaiting() and print(n) to BT.recv_packet() I noticed that n grows exponentially until reaching 12 kilobytes and then the connection stops. Adding this:

```<code>        ret = self.proc_byte(ord(c))
        if ret:
            if n >= 100:
                self.ser.flushInput()
</code>```

Solved the problem.

Body:
So, problem was so trivial than I have been blaming myself for hours. When adding n = self.ser.inWaiting() and print(n) to BT.recv_packet() I noticed that n grows exponentially until reaching 12 kilobytes and then the connection stops. Adding this:

        ret = self.proc_byte(ord(c))
        if ret:
            if n >= 100:
                self.ser.flushInput()

Solved the problem.


问:
make a text file into a list
This is what my text file consists of:
"file1
file2"

So far this is my code:

```<code>def create_filenames_list(filename):
    filenames_list = []
    file = open('input.txt', "r").readlines()
    for line in file:
            filenames_list = line

    return filenames_list.split()
def main():
    filenames_list = create_filenames_list('input.txt')
    print(filenames_list)
</code>```

The Output I got:
"file2"
What I expected is:
['file1', 'file2']

答:
Instead of

```<code>    filenames_list = line
</code>```

(which overwrites the list filenames_list two times with a string, so it will in the end contain only the latest one - "file2")

use

```<code>    filenames_list.append(line)
</code>```

to append to the list.

Title: make a text file into a list

Body:
This is what my text file consists of:
"file1
file2"

So far this is my code:

def create_filenames_list(filename):
    filenames_list = []
    file = open('input.txt', "r").readlines()
    for line in file:
            filenames_list = line

    return filenames_list.split()
def main():
    filenames_list = create_filenames_list('input.txt')
    print(filenames_list)

The Output I got:
"file2"
What I expected is:
['file1', 'file2']

Body:
Instead of

    filenames_list = line

(which overwrites the list filenames_list two times with a string, so it will in the end contain only the latest one - "file2")

use

    filenames_list.append(line)

to append to the list.


问:
How could I use HTML snippets in VS Community 2017?
How could I easly generate next code in Visual Studio Community 2017 in an ASP.NET MVC project?

```

<p>using next snippet</p>

```h1#welcome+div.row>(section.col-md-4>(h2+p))*3
```

Like on this image

This must work inside a .cshtml (HTML with razor code) and .html file

答:
```<code>h1#welcome+div.row>(section.col-md-4>(h2+p))*3
</code>```

Looks like you are doing Zen Coding of HTML. VS needs an extension for that to work.

https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ZenCoding

Body:
How could I easly generate next code in Visual Studio Community 2017 in an ASP.NET MVC project?

using next snippet

h1#welcome+div.row>(section.col-md-4>(h2+p))*3

Like on this image

This must work inside a .cshtml (HTML with razor code) and .html file

Body:
h1#welcome+div.row>(section.col-md-4>(h2+p))*3

Looks like you are doing Zen Coding of HTML. VS needs an extension for that to work.

https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ZenCoding


问:
opening sublime text from windows git bash
How do I open Sublime text from Git Bash in Windows? I tried adding the alias at the ~/.bashrc file but nothing worked. I was looking for something very easy but I could not find in the internet.</p>

答:
Create .bash_profile file under C:\Users\YourUserName\ and add the following line in the file:

```<code>alias 'subl="/c/Program Files/Sublime Text 3/subl.exe"'
</code>```

Body:
Create .bash_profile file under C:\Users\YourUserName\ and add the following line in the file:

alias 'subl="/c/Program Files/Sublime Text 3/subl.exe"'


答:
do I need to split my test method into two test methods, each for a
  case?

Yes.

If yes, how can I use the attribute for the case where I don't expect
  my method to raise an exception?

Just don't add the attribute to the method!?

Is there any way that I don't have to split it, because grouping two
  cases for the same method to be tested in a test method separates
  nicely the tests for different methods to be tested?

I dont think so, because the attributes needs the exception to be thrown. Therefore the test ends with the first exception. However, it is good to split test in single test cases anyway (as atomic as possible) so that you don't have to waste time with debugging / analyzing what went wrong if a test fails.

Title: Is ExpectedException used for testing more than one cases in one test method?