问:
size of struct field from ncinfo
I want to get the size of a certain field inside a structure.

For example the size of the field Name inside the field Dimensions of the struct obtained from ncinfo:

```<code>finfo = ncinfo('example.nc');
finfo.Dimensions.Name

>>ans =

x

ans =

y

ans =

z
</code>```

Just using size causes an obvious error:

size(finfo.Dimensions.Name)

Error using size
  Too many input arguments.

How can I do it in an alternative way?

Also, I would like to save the content of finfo.Dimensions.Name in a separate array or struct. But I get a similar error. For example:

```<code>a.b=finfo.Dimensions.Name
</code>```

returns the error:

Illegal right hand side in assignment. Too many elements.

答:
Your problem is that the Dimensions field in the structure returned by ncinfo is itself an array of structures, and when you access a field of a structure array it returns a comma-separated list of values, one for each array element. You need to collect these values, for example in a cell array:

```<code>nameCell = {finfo.Dimensions.Name};  % Now a 1-by-3 cell array of names
</code>```

If you just want to know the number of dimensions, you can check the size of the Dimensions field like so:

```<code>N = size(finfo.Dimensions);
</code>```

Title: size of struct field from ncinfo

Body:
I want to get the size of a certain field inside a structure.

For example the size of the field Name inside the field Dimensions of the struct obtained from ncinfo:

finfo = ncinfo('example.nc');
finfo.Dimensions.Name

>>ans =

x

ans =

y

ans =

z

Just using size causes an obvious error:

size(finfo.Dimensions.Name)

Error using size
  Too many input arguments.

How can I do it in an alternative way?

Also, I would like to save the content of finfo.Dimensions.Name in a separate array or struct. But I get a similar error. For example:

a.b=finfo.Dimensions.Name

returns the error:

Illegal right hand side in assignment. Too many elements.

Body:
Your problem is that the Dimensions field in the structure returned by ncinfo is itself an array of structures, and when you access a field of a structure array it returns a comma-separated list of values, one for each array element. You need to collect these values, for example in a cell array:

nameCell = {finfo.Dimensions.Name};  % Now a 1-by-3 cell array of names

If you just want to know the number of dimensions, you can check the size of the Dimensions field like so:

N = size(finfo.Dimensions);


来源: stackexchange

问:
How do I produce only an object file (*.o) from a CMake build target?
I'm trying to build an object file using CMake, but I can't seem to get CMake to build something other than a complete executable. I'm basically looking for the result of the following compilation (the result will be loaded on a VxWorks target and linked then):

```<code>$(CC) $(CFLAGS) $(INC_DIRS) -c src/object.c
</code>```

I've tried changing the OUTPUT_NAME property of the target, but that doesn't seem to help, either.

I think I could work around this by using a custom command, but that seems like I'm also working around the nice things that CMake provides.

Thanks for your help!

答: I would go the custom command path. Remember you can still use those object files for compilation with CMake latter if you set the GENERATED and EXTERNAL_OBJECT source file properties.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to build an object file using CMake, but I can't seem to get CMake to build something other than a complete executable. I'm basically looking for the result of the following compilation (the result will be loaded on a VxWorks target and linked then):

$(CC) $(CFLAGS) $(INC_DIRS) -c src/object.c

I've tried changing the OUTPUT_NAME property of the target, but that doesn't seem to help, either.

I think I could work around this by using a custom command, but that seems like I'm also working around the nice things that CMake provides.

Thanks for your help!

ContentLicense: CC BY-SA 2.5


问:
Adding Values to a List Separately
I am a beginner to Python and just programming in general so this will probably have a very obvious answer to everyone here.

So - I am currently trying to make hangman however I have run into an issue with the display. I am trying to add underscores to a list, with each underscore being in it's own string. I am doing this with

```<code>targetWord = ["_ " * len(answer)]
</code>```

answer is the word being searched for

targetWord is what the user sees (e.g. app_e)

However instead of adding say, 5 strings with each string containing 1 underscore, 1 string is being added with 5 underscores.

The output is ["_ _ _ _ _ "]

The output should be ["_ ","_ ","_ ","_ ","_ "]

All help is appreciated :)

答:
You're making the string first and then putting it as a list.

Try

```<code>targetWord = ['_'] * len(answer)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Adding Values to a List Separately

Body:
I am a beginner to Python and just programming in general so this will probably have a very obvious answer to everyone here.

So - I am currently trying to make hangman however I have run into an issue with the display. I am trying to add underscores to a list, with each underscore being in it's own string. I am doing this with

targetWord = ["_ " * len(answer)]

answer is the word being searched for

targetWord is what the user sees (e.g. app_e)

However instead of adding say, 5 strings with each string containing 1 underscore, 1 string is being added with 5 underscores.

The output is ["_ _ _ _ _ "]

The output should be ["_ ","_ ","_ ","_ ","_ "]

All help is appreciated :)

Body:
You're making the string first and then putting it as a list.

Try

targetWord = ['_'] * len(answer)


答:
Per the documentation for ncinfo, Dimensions is an array of structures, so you need to be more explicit with what you want to do.

If you want the size of the 'Dimensions' field then that is your query:

```<code>S.Dimensions(1).Name = 'x';
S.Dimensions(2).Name = 'y';
S.Dimensions(3).Name = 'z';

size(S.Dimensions)
</code>```

Which returns:

```<code>ans =

     1     3
</code>```

Title: size of struct field from ncinfo

Body:
Per the documentation for ncinfo, Dimensions is an array of structures, so you need to be more explicit with what you want to do.

If you want the size of the 'Dimensions' field then that is your query:

S.Dimensions(1).Name = 'x';
S.Dimensions(2).Name = 'y';
S.Dimensions(3).Name = 'z';

size(S.Dimensions)

Which returns:

ans =

     1     3


问:
Query to identify duplicates based on time of day
SQL newbie here. I have a table with trainer schedules. Each record within the table, Schedule, contains the following relevant fields:
course_code,
training_date,
start_time,
end_time,
trainer,
room

I would like a query to identify whenever a trainer or a room is double-booked. The query wizard gets me pretty far, but obviously my need is a bit more complex than the wizard's capability. I was able to generate this query:

```<code>SELECT Schedule.[training_date], Schedule.[trainer], Schedule.[course_code]
FROM Schedule
WHERE (((Schedule.[training_date]) In (SELECT [training_date] FROM [Schedule] As Tmp GROUP BY [training_date],[trainer] HAVING Count(*)>1  And [trainer] = [Schedule].[trainer])) AND (Not (Schedule.[course_code])="OP00487"))
ORDER BY Schedule.[training_date], Schedule.[trainer];
</code>```

It returns the course codes where trainers are booked multiple times in any given day, but I would like to exclude those records where the trainer is training two different times. For example, OP1 might be taught 9:00 to 12:30, and OP2 is taught 12:30 to 16:00. In this case, this is not a duplicate within the date that I care about. I do want to see the record if a trainer is teaching 8:00 to 12:00 and also 10:30 to 14:00.

My query does exclude one course_code because duplicates for that code are irrelevant. I will also have the same thing with the room query (doesn't matter how many off site rooms overlap).

I should be able to engineer the room query based on the trainer query, but if both could be integrated into one query, that would be wonderful.

答:
One method uses a correlated subquery.  The following should find any overlap in time on the same date for a training or room:

```<code>select s.*
from schedule as s
where exists (select 1
              from schedule as s2
              where (s2.trainer = s.trainer or s2.room = s.room) and
                    s2.training_date = s.training_date and
                    s2.start_time < s.end_time and
                    s2.end_time > s.start_time and
                    s2.schedule_id <> s.schedule_id
              );
</code>```

Note that this postulates the existence of a column called schedule_id to prevent the query from finding that any given record overlaps with itself.

Body:
SQL newbie here. I have a table with trainer schedules. Each record within the table, Schedule, contains the following relevant fields:
course_code,
training_date,
start_time,
end_time,
trainer,
room

I would like a query to identify whenever a trainer or a room is double-booked. The query wizard gets me pretty far, but obviously my need is a bit more complex than the wizard's capability. I was able to generate this query:

SELECT Schedule.[training_date], Schedule.[trainer], Schedule.[course_code]
FROM Schedule
WHERE (((Schedule.[training_date]) In (SELECT [training_date] FROM [Schedule] As Tmp GROUP BY [training_date],[trainer] HAVING Count(*)>1  And [trainer] = [Schedule].[trainer])) AND (Not (Schedule.[course_code])="OP00487"))
ORDER BY Schedule.[training_date], Schedule.[trainer];

It returns the course codes where trainers are booked multiple times in any given day, but I would like to exclude those records where the trainer is training two different times. For example, OP1 might be taught 9:00 to 12:30, and OP2 is taught 12:30 to 16:00. In this case, this is not a duplicate within the date that I care about. I do want to see the record if a trainer is teaching 8:00 to 12:00 and also 10:30 to 14:00.

My query does exclude one course_code because duplicates for that code are irrelevant. I will also have the same thing with the room query (doesn't matter how many off site rooms overlap).

I should be able to engineer the room query based on the trainer query, but if both could be integrated into one query, that would be wonderful.

Body:
One method uses a correlated subquery.  The following should find any overlap in time on the same date for a training or room:

select s.*
from schedule as s
where exists (select 1
              from schedule as s2
              where (s2.trainer = s.trainer or s2.room = s.room) and
                    s2.training_date = s.training_date and
                    s2.start_time < s.end_time and
                    s2.end_time > s.start_time and
                    s2.schedule_id <> s.schedule_id
              );

Note that this postulates the existence of a column called schedule_id to prevent the query from finding that any given record overlaps with itself.


问:
IPHONE - Use multiple views
I have to make an application with six views, which can be accessed to by bar button items on a toolbar.

I'm really new at this.
I have a view controller and a XIB file for each view, with six functions (goToView1, goToView2, ..., goToView6).

Here is an example :

```<code>SecondViewController *secondview;

-(IBAction)goToView2 {
    secondview = [[SecondViewController alloc]
                 initWithNibName:@"SecondViewController" bundle:nil];
    [self.view addSubview:secondview.view];
}
</code>```

But as you can see, if I want to go from view3 to view2, I'm not deleting the view3 from the stack : I'm just adding the view2 over it.
So here's my problem, how do I "delete" my view before using addSubView ?
I tried with removeFromSuperView, but I think I'm not using it right.

Thanks for helping, as I said I'm really new and I am aware it can be a stupid question :/

答:
Take a look at UITabBar. I think using a tab bar might be better suited for what you want to do, than a toolbar.

UITabBar Class Reference

Title: IPHONE - Use multiple views

Body:
I have to make an application with six views, which can be accessed to by bar button items on a toolbar.

I'm really new at this.
I have a view controller and a XIB file for each view, with six functions (goToView1, goToView2, ..., goToView6).

Here is an example :

SecondViewController *secondview;

-(IBAction)goToView2 {
    secondview = [[SecondViewController alloc]
                 initWithNibName:@"SecondViewController" bundle:nil];
    [self.view addSubview:secondview.view];
}

But as you can see, if I want to go from view3 to view2, I'm not deleting the view3 from the stack : I'm just adding the view2 over it.
So here's my problem, how do I "delete" my view before using addSubView ?
I tried with removeFromSuperView, but I think I'm not using it right.

Thanks for helping, as I said I'm really new and I am aware it can be a stupid question :/


问:
Java 8, Lambda: Sorting within grouped Lists and merging all groups to a list
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

```<code>Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
</code>```

I need the Grouping based on the order of the Elements in the origin List.

```<code>First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"
</code>```

The result would then look like the following:

```<code>List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"
</code>```

I have tried the following:

```<code>studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
</code>```

But this doesn't work.

答:
try sort first and then groupinBy it works well. The below code sorts the Students within the location.

students.stream().sorted().collect(Collectors.groupingBy(Student::getLocation))

The output in this case is

```<code>{New York=[1726  John  New York, 3442  Mark  New York, 5223  Michael  New York], Los Angeles=[2234  Andrew  Los Angeles], California=[4321  Max  California, 7765  Sam  California]}
</code>```

If you would like to have locations also to be sorted, use a code snippet like below

```<code>students.stream().sorted().collect(Collectors.groupingBy(Student::getLocation, TreeMap::new, Collectors.toList()))
</code>```

The output in this case is
 {California=[4321  Max  California, 7765  Sam  California], Los Angeles=[2234  Andrew  Los Angeles], New York=[1726  John  New York, 3442  Mark  New York, 5223  Michael  New York]}

Student class implements Comparable and the compareTo method is  is based on the id.

Body:
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

I need the Grouping based on the order of the Elements in the origin List.

First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"

The result would then look like the following:

List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"

I have tried the following:

studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))

But this doesn't work.

Body:
try sort first and then groupinBy it works well. The below code sorts the Students within the location.

students.stream().sorted().collect(Collectors.groupingBy(Student::getLocation))

The output in this case is

{New York=[1726  John  New York, 3442  Mark  New York, 5223  Michael  New York], Los Angeles=[2234  Andrew  Los Angeles], California=[4321  Max  California, 7765  Sam  California]}

If you would like to have locations also to be sorted, use a code snippet like below

students.stream().sorted().collect(Collectors.groupingBy(Student::getLocation, TreeMap::new, Collectors.toList()))

The output in this case is
 {California=[4321  Max  California, 7765  Sam  California], Los Angeles=[2234  Andrew  Los Angeles], New York=[1726  John  New York, 3442  Mark  New York, 5223  Michael  New York]}

Student class implements Comparable and the compareTo method is  is based on the id.


问:
How to add a WHERE clause to BigQuery Query to find rows where a column value is not in a list of values
I have a table in BigQuery named events that has a column named 'entitlement'.  That column can have values such as 'lapb', 'lacf', 'lasg', 'laxy', 'laza' etc.  It can also have 'null' or '' or other values that I don't know.  It will only have 1 given value per row so it isn't a list of values.  So for example, here is some sample data:

```<code>name    entitlement date
alice   laxy        01072017
bob     null        01082018
charlie lapb        01092017
daniel  lacf        01092017
</code>```

etc

How can I write a query so that I can check if the entitlement value is not in a list of values?

This is how I am currently doing it.  I am adding an additional "and entitlement != clause for each one.

```<code>SELECT *
FROM events
WHERE entitlement != 'lapb' and entitlement != 'lacf'
and entitlement != 'lasg' and entitlement != 'laxy'
and entitlement != 'laza' and entitlement is not null
order by logtime desc
LIMIT 1000
</code>```

I tried doing the following:

```<code>SELECT *
FROM events
WHERE entitlement is not in ['labp', 'lpaf']
order by logtime desc
LIMIT 1000
</code>```

but I get the following error:

Query Failed
Error: Encountered "" at line 3, column 33.

Is there a way in BigQuery to check for only rows that do not contain values in a list or must I add an individual "and entitlement != ..." clause for each additional value?  Basically the query is really becoming large and complicated very quickly and I was trying to find a way to simplify it for manageability and readability purposes.  I tried square brackets, parentheses, nothing, etc but all give me the same error.

答:
```<code>#standardSQL
WITH events AS (
  SELECT 'alice' AS name, 'laxy' AS entitlement, '01072017' AS date UNION ALL
  SELECT 'bob', NULL, '01082018' UNION ALL
  SELECT 'charlie', 'lapb', '01092017' UNION ALL
  SELECT 'daniel', 'lacf', '01092017'
)
SELECT *
FROM events
WHERE entitlement NOT IN ('labp', 'lpaf');
+---------+-------------+----------+
| name    | entitlement | date     |
+---------+-------------+----------+
| alice   | laxy        | 01072017 |
| charlie | lapb        | 01092017 |
| daniel  | lacf        | 01092017 |
+---------+-------------+----------+
</code>```

Body:
I have a table in BigQuery named events that has a column named 'entitlement'.  That column can have values such as 'lapb', 'lacf', 'lasg', 'laxy', 'laza' etc.  It can also have 'null' or '' or other values that I don't know.  It will only have 1 given value per row so it isn't a list of values.  So for example, here is some sample data:

name    entitlement date
alice   laxy        01072017
bob     null        01082018
charlie lapb        01092017
daniel  lacf        01092017

etc

How can I write a query so that I can check if the entitlement value is not in a list of values?

This is how I am currently doing it.  I am adding an additional "and entitlement != clause for each one.

SELECT *
FROM events
WHERE entitlement != 'lapb' and entitlement != 'lacf'
and entitlement != 'lasg' and entitlement != 'laxy'
and entitlement != 'laza' and entitlement is not null
order by logtime desc
LIMIT 1000

I tried doing the following:

SELECT *
FROM events
WHERE entitlement is not in ['labp', 'lpaf']
order by logtime desc
LIMIT 1000

but I get the following error:

Query Failed
Error: Encountered "" at line 3, column 33.

Is there a way in BigQuery to check for only rows that do not contain values in a list or must I add an individual "and entitlement != ..." clause for each additional value?  Basically the query is really becoming large and complicated very quickly and I was trying to find a way to simplify it for manageability and readability purposes.  I tried square brackets, parentheses, nothing, etc but all give me the same error.


问:
Update local JSON file using AngularJS
The file performs.json contains an JSON array with objects of user info.

I want to programmatically update this array and save again. But I don't know how.

```<code>$http.get('db/performs.json')
    .then(function (res) {
        res.data.push(newSubmit);
        // Save this new res.data to db/performs.json
    });
</code>```

答:
When you call $http.get the server sends the file to you, it is then placed in memory, which you then modify. At this point you need to send the modified file back to the server for storage.

This needs to be supported by the server that served the file initially.

Here's an example of how to do in a NodeJS server

Title: Update local JSON file using AngularJS

Body:
The file performs.json contains an JSON array with objects of user info.

I want to programmatically update this array and save again. But I don't know how.

$http.get('db/performs.json')
    .then(function (res) {
        res.data.push(newSubmit);
        // Save this new res.data to db/performs.json
    });


问:
How to change the textColor of TextInput in react native dynamically?
hi guys i want to change textcolor of input dynamically. for example initially in CSS placed as color:'#fff',then i want to change the text color whenever need as '#ddd'.</p>

答:
Similar to Khushboo Shah's answer, this is how I adjusted the color for my Component. The code must be placed in the render() function, and render() must be triggered using normal methods.

```<code>render() {

    var overrideStyle = {};
    if ( condition ) {
         overrideStyle = { color: '#ddd' };
    }
    return (
              <Text style={[ this.props.style, overrideStyle ]}>
                //...
              </Text>
    );

}
</code>```

Body:
Similar to Khushboo Shah's answer, this is how I adjusted the color for my Component. The code must be placed in the render() function, and render() must be triggered using normal methods.

render() {

    var overrideStyle = {};
    if ( condition ) {
         overrideStyle = { color: '#ddd' };
    }
    return (
              <Text style={[ this.props.style, overrideStyle ]}>
                //...
              </Text>
    );

}


问:
C++ - class issue
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

```<code>#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}
</code>```

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.

答:
Add

```<code>#include <string.h>
</code>```

And change wage to m_wage on line 19.

Title: C++ - class issue

Body:
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.

Body:
Add

#include <string.h>

And change wage to m_wage on line 19.


问:
React + Redux: why the global state is not fed to the component
Consider the following code. It's supposed to work like this; keystrokes are supposed to update the local state and once the button is clicked, the global state should be updated. And the component itself is responsible to show the global state as well.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: this.props.appState.name, localName: "" };
    this.nameChanged = this.nameChanged.bind(this);
    this.sendAction = this.sendAction.bind(this);
  }

  nameChanged(event) {
    this.setState(Object.assign({}, this.state, { localName: event.target.value }));
  }

  sendAction(event) {
    this.props.saveName(this.state.localName);
  }

  render() {
    return (

Hello, {this.state.name}!

        <input type="text" value={this.state.localName} onChange={this.nameChanged} />
        <input type="button" value="Click me!" onClick={this.sendAction} />

    );
  }
}

const AppContainer = ReactRedux.connect(
  state => ({ appState: state.appReducer.appState }),
  dispatch => Redux.bindActionCreators({
    saveName: (name) => ({ type: "SAVE_NAME", name })
  }, dispatch)
)(App);

const appReducer = (state = { appState: { name: "World!" } }, action) => {
  switch (action.type) {
    case "SAVE_NAME":
      return Object.assign({}, state, { name: action.name });

    default:
      return state;
  }
};

const combinedReducers = Redux.combineReducers({
  appReducer
});

const store = Redux.createStore(combinedReducers);

ReactDOM.render(
  <ReactRedux.Provider store={store}>
    <AppContainer />
  </ReactRedux.Provider>,
  document.getElementsByTagName('main')[0]
);
```

Right now, the local state is updated correctly. But when I click the button, even though the action is created and sent, but I don't see the global state with the new value in the UI. I'm not sure if the global state is not updated or the component is not properly informed.

答:
Change
Hello, {this.state.name}!
 to this:

```<code><h1>Hello, {this.props.appState.name}!</h1>
</code>```

You don't have to set the state locally, Redux is updating the props for you through connect when the store state changes. The other change you'll need to make is in your reducer. Your current state is pretty deeply nested and it's not being returned how you're expecting it to when you dispatch your action. Here's the updated version:

case "SAVE_NAME":
      return {
        ...state,
        appState: {
          ...state.appState,
          name: action.name
        }
      }

Here's a working version in CodePen Link

Body:
Consider the following code. It's supposed to work like this; keystrokes are supposed to update the local state and once the button is clicked, the global state should be updated. And the component itself is responsible to show the global state as well.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: this.props.appState.name, localName: "" };
    this.nameChanged = this.nameChanged.bind(this);
    this.sendAction = this.sendAction.bind(this);
  }

  nameChanged(event) {
    this.setState(Object.assign({}, this.state, { localName: event.target.value }));
  }

  sendAction(event) {
    this.props.saveName(this.state.localName);
  }

  render() {
    return (

Hello, {this.state.name}!

        <input type="text" value={this.state.localName} onChange={this.nameChanged} />
        <input type="button" value="Click me!" onClick={this.sendAction} />

    );
  }
}

const AppContainer = ReactRedux.connect(
  state => ({ appState: state.appReducer.appState }),
  dispatch => Redux.bindActionCreators({
    saveName: (name) => ({ type: "SAVE_NAME", name })
  }, dispatch)
)(App);

const appReducer = (state = { appState: { name: "World!" } }, action) => {
  switch (action.type) {
    case "SAVE_NAME":
      return Object.assign({}, state, { name: action.name });

    default:
      return state;
  }
};

const combinedReducers = Redux.combineReducers({
  appReducer
});

const store = Redux.createStore(combinedReducers);

ReactDOM.render(
  <ReactRedux.Provider store={store}>
    <AppContainer />
  </ReactRedux.Provider>,
  document.getElementsByTagName('main')[0]
);

Right now, the local state is updated correctly. But when I click the button, even though the action is created and sent, but I don't see the global state with the new value in the UI. I'm not sure if the global state is not updated or the component is not properly informed.

Body:
Change <h1>Hello, {this.state.name}!</h1> to this:

<h1>Hello, {this.props.appState.name}!</h1>

You don't have to set the state locally, Redux is updating the props for you through connect when the store state changes. The other change you'll need to make is in your reducer. Your current state is pretty deeply nested and it's not being returned how you're expecting it to when you dispatch your action. Here's the updated version:

case "SAVE_NAME":
      return {
        ...state,
        appState: {
          ...state.appState,
          name: action.name
        }
      }

Here's a working version in CodePen Link


问:
Mocha testing javascript with inheritance
I am new to Mocha and Node but trying to write some Mocha tests on some JavaScript classes.

I have the following class:

```<code>function FormField() {
}

FormField.prototype.sanitizeFieldValue = function(value) {
    if (value == null || value.replace == null) {
        return null;
    }
    return value
        .replace(/ /g, " ")
        .replace(/&/g, '&')
        .replace(/\\/g, '\\\\')
        .replace(/'/g, "\\'")
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/"/g, '"')
        .replace(/[\n\r]+/g, " ");
};

module.exports = FormField;
</code>```

When I run my mocha tests on this file, everything works fine and the tests pass.

```<code>var expect = require("chai").expect;
var formfield = require("FormField");

describe("new Form Field Tests", function() {
   var ff = new formfield();
   describe("sanitizeFieldValue", function() {
        it("escapes apostrophe", function() {
            expect(ff.sanitizeFieldValue("'")).to.equal("\\\'");
        });
    });
});
</code>```

However, I have another file which references the first:

```<code>TargetDateField.prototype = new FormField();
function TargetDateField() {
// some functions

}
module.exports = TargetDateField;
</code>```

But I am not sure how to test this
I have tried the following but I keep getting FormField is not defined.

```<code>var expect = require("chai").expect;
var FormField = require("FormField").FormField;
var targetdatefield = require("TargetDateField");
</code>```

Any ideas on how to resolve this?

答:
Everywhere where you want to use FormField you require the module that defines it.... except in your TargetDateField.js file, where you don't require it. That's why you are getting an error. You need to require it there too:

```<code>var FormField = require("FormField");

TargetDateField.prototype = new FormField();
// etc...
</code>```

By the way, I strongly suggest writing your code to use relative paths when you want to load other modules that are part of the same package. At first glance, I'd expect require("FormField") to load something from node_modules. (Like when you do require("chai").)

Body:
I am new to Mocha and Node but trying to write some Mocha tests on some JavaScript classes.

I have the following class:

function FormField() {
}

FormField.prototype.sanitizeFieldValue = function(value) {
    if (value == null || value.replace == null) {
        return null;
    }
    return value
        .replace(/ /g, " ")
        .replace(/&/g, '&')
        .replace(/\\/g, '\\\\')
        .replace(/'/g, "\\'")
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/"/g, '"')
        .replace(/[\n\r]+/g, " ");
};

module.exports = FormField;

When I run my mocha tests on this file, everything works fine and the tests pass.

var expect = require("chai").expect;
var formfield = require("FormField");

describe("new Form Field Tests", function() {
   var ff = new formfield();
   describe("sanitizeFieldValue", function() {
        it("escapes apostrophe", function() {
            expect(ff.sanitizeFieldValue("'")).to.equal("\\\'");
        });
    });
});

However, I have another file which references the first:

TargetDateField.prototype = new FormField();
function TargetDateField() {
// some functions

}
module.exports = TargetDateField;

But I am not sure how to test this
I have tried the following but I keep getting FormField is not defined.

var expect = require("chai").expect;
var FormField = require("FormField").FormField;
var targetdatefield = require("TargetDateField");

Any ideas on how to resolve this?

Body:
Everywhere where you want to use FormField you require the module that defines it.... except in your TargetDateField.js file, where you don't require it. That's why you are getting an error. You need to require it there too:

var FormField = require("FormField");

TargetDateField.prototype = new FormField();
// etc...

By the way, I strongly suggest writing your code to use relative paths when you want to load other modules that are part of the same package. At first glance, I'd expect require("FormField") to load something from node_modules. (Like when you do require("chai").)


问:
Replace a cell value if criteria is fulfilled
Hope this question finds you well. I am trying to do some testing in excel using VBA however i ran into a problem.
Below is the code i wrote but it is not working as per my expectations.

Details:

```<code>Me.txt_EN.Value is Employee Name

Me.cmb_S.Value is Shift

Me.cmb_M.Value is Month

Worksheet Name = Test

Userform Name is Userform1
</code>```

Above Values would be added via userform in excel.

Here is what below code is supposed to do: Once i click on submit button in my userform1, it should first paste the value specified in Shift (Me.cmb_S.Value) in a range (It does fine until here) then if i enter "WO" as a entry (Look at the first screen shot1), the code should change the cell value with "WO".
Example: If i select "WO" for Tuesday (Tue) and Wednesday (Wed) and my shift as Evening (E), it should first fill all cells (range E32:AI32)with E and then replaces "E" with "WO" for all Tuesdays and Wednesdays.Screenshot1
Screenshot2

Below code is a bit slow and it gives me results as shown in screen shot 2, it always excludes last Tuesdays and Wednesdays (Look at 1/30/18 and 1/3/18, they should be changed as "WO")

Any help to fix this would be appreciated and also is there a way i could add a rule so the same user cannot fill this form more than once?

```<code>Private Sub cmd_Submit_Click()
'select worksheet
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("RawData")
Dim i As Integer
Dim m As Integer
Dim n As Integer

'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows,
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

'copy the data to the database

For i = 5 To 36
ws.Cells(iRow, 1).Value = Me.txt_EN.Value
ws.Cells(iRow, i).Value = Me.cmb_S.Value
ws.Cells(iRow, 37).Value = Me.cmb_M.Value
Next i

For m = 5 To 29
If Me.cmb_mon.Value = "WO" Then ws.Cells(iRow, m).Value = "WO"
If Me.cmb_Tue.Value = "WO" Then ws.Cells(iRow, m + 1).Value = "WO"
If Me.cmb_Wed.Value = "WO" Then ws.Cells(iRow, m + 2).Value = "WO"
If Me.cmb_thu.Value = "WO" Then ws.Cells(iRow, m + 3).Value = "WO"
If Me.cmb_Fri.Value = "WO" Then ws.Cells(iRow, m + 4).Value = "WO"
If Me.cmb_Sat.Value = "WO" Then ws.Cells(iRow, m + 5).Value = "WO"
If Me.cmb_Sun.Value = "WO" Then ws.Cells(iRow, m + 6).Value = "WO"

m = m + 6
If m > 35 Then Exit For Else
Next

MsgBox "Data added", vbOKOnly + vbInformation, "Data Added"
Unload Me
UserForm1.Show

End Sub
</code>```

答:
You use

```<code>For m = 5 To 29
   ...
   m = m + 6 'here you increase counter by 6
Next 'here you increase counter by 1
</code>```

So before your last expected loop the counter (m) is already = 32 so its > then 29 so the loop ends. Thats why last days are excluded.

You must change your loop a little.

If row with day name is always 30 you could use something like this

```<code>Private Sub cmd_Submit_Click()
   'select worksheet
   Dim iRow As Long
   Dim ws As Worksheet
   Set ws = Worksheets("RawData")
   Dim i As Integer
   Dim m As Integer
   Dim n As Integer

   Dim Mon As Boolean, Tue As Boolean, Wed As Boolean, Thu As Boolean
   DIM Fri As Boolean, Sat As Boolean, Sun As Boolean
   DIM aCell as Range

   'find first empty row in database
   iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows,
   SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

   Application.ScreenUpdating = False
   Application.Calculation = xlCalculationManual

   'copy the data to the database

   For i = 5 To 36
      ws.Cells(iRow, 1).Value = Me.txt_EN.Value
      ws.Cells(iRow, i).Value = Me.cmb_S.Value
      ws.Cells(iRow, 37).Value = Me.cmb_M.Value
   Next i

   If Me.cmb_mon.Value = "WO" Then Mon = True
   If Me.cmb_Tue.Value = "WO" Then Tue = True
   If Me.cmb_Wed.Value = "WO" Then Wed = True
   If Me.cmb_thu.Value = "WO" Then Thu = True
   If Me.cmb_Fri.Value = "WO" Then Fri = True
   If Me.cmb_Sat.Value = "WO" Then Sat = True
   If Me.cmb_Sun.Value = "WO" Then Sun = True

   For Each aCell In ws.Range("E30:AI30")
      If aCell = "Mon" And Mon Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Tue" And Tue Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Wed" And Wed Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Thu" And Thu Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Fri" And Fri Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Sat" And Sat Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Sun" And Sun Then ws.Cells(iRow, aCell.Column).Value = "WO"
   Next

   MsgBox "Data added", vbOKOnly + vbInformation, "Data Added"
   Unload Me
   UserForm1.Show

   application.screenupdating = true
   application.Calculation = xlCalculationAutomatic
End Sub
</code>```

Didn't tested it so it might need some adjustments

Body:
Hope this question finds you well. I am trying to do some testing in excel using VBA however i ran into a problem.
Below is the code i wrote but it is not working as per my expectations.

Details:

Me.txt_EN.Value is Employee Name

Me.cmb_S.Value is Shift

Me.cmb_M.Value is Month

Worksheet Name = Test

Userform Name is Userform1

Above Values would be added via userform in excel.

Here is what below code is supposed to do: Once i click on submit button in my userform1, it should first paste the value specified in Shift (Me.cmb_S.Value) in a range (It does fine until here) then if i enter "WO" as a entry (Look at the first screen shot1), the code should change the cell value with "WO".
Example: If i select "WO" for Tuesday (Tue) and Wednesday (Wed) and my shift as Evening (E), it should first fill all cells (range E32:AI32)with E and then replaces "E" with "WO" for all Tuesdays and Wednesdays.Screenshot1
Screenshot2

Below code is a bit slow and it gives me results as shown in screen shot 2, it always excludes last Tuesdays and Wednesdays (Look at 1/30/18 and 1/3/18, they should be changed as "WO")

Any help to fix this would be appreciated and also is there a way i could add a rule so the same user cannot fill this form more than once?

Private Sub cmd_Submit_Click()
'select worksheet
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("RawData")
Dim i As Integer
Dim m As Integer
Dim n As Integer

'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows,
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

'copy the data to the database

For i = 5 To 36
ws.Cells(iRow, 1).Value = Me.txt_EN.Value
ws.Cells(iRow, i).Value = Me.cmb_S.Value
ws.Cells(iRow, 37).Value = Me.cmb_M.Value
Next i

For m = 5 To 29
If Me.cmb_mon.Value = "WO" Then ws.Cells(iRow, m).Value = "WO"
If Me.cmb_Tue.Value = "WO" Then ws.Cells(iRow, m + 1).Value = "WO"
If Me.cmb_Wed.Value = "WO" Then ws.Cells(iRow, m + 2).Value = "WO"
If Me.cmb_thu.Value = "WO" Then ws.Cells(iRow, m + 3).Value = "WO"
If Me.cmb_Fri.Value = "WO" Then ws.Cells(iRow, m + 4).Value = "WO"
If Me.cmb_Sat.Value = "WO" Then ws.Cells(iRow, m + 5).Value = "WO"
If Me.cmb_Sun.Value = "WO" Then ws.Cells(iRow, m + 6).Value = "WO"

m = m + 6
If m > 35 Then Exit For Else
Next

MsgBox "Data added", vbOKOnly + vbInformation, "Data Added"
Unload Me
UserForm1.Show

End Sub

Body:
You use

For m = 5 To 29
   ...
   m = m + 6 'here you increase counter by 6
Next 'here you increase counter by 1

So before your last expected loop the counter (m) is already = 32 so its > then 29 so the loop ends. Thats why last days are excluded.

You must change your loop a little.

If row with day name is always 30 you could use something like this

Private Sub cmd_Submit_Click()
   'select worksheet
   Dim iRow As Long
   Dim ws As Worksheet
   Set ws = Worksheets("RawData")
   Dim i As Integer
   Dim m As Integer
   Dim n As Integer

   Dim Mon As Boolean, Tue As Boolean, Wed As Boolean, Thu As Boolean
   DIM Fri As Boolean, Sat As Boolean, Sun As Boolean
   DIM aCell as Range

   'find first empty row in database
   iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows,
   SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

   Application.ScreenUpdating = False
   Application.Calculation = xlCalculationManual

   'copy the data to the database

   For i = 5 To 36
      ws.Cells(iRow, 1).Value = Me.txt_EN.Value
      ws.Cells(iRow, i).Value = Me.cmb_S.Value
      ws.Cells(iRow, 37).Value = Me.cmb_M.Value
   Next i

   If Me.cmb_mon.Value = "WO" Then Mon = True
   If Me.cmb_Tue.Value = "WO" Then Tue = True
   If Me.cmb_Wed.Value = "WO" Then Wed = True
   If Me.cmb_thu.Value = "WO" Then Thu = True
   If Me.cmb_Fri.Value = "WO" Then Fri = True
   If Me.cmb_Sat.Value = "WO" Then Sat = True
   If Me.cmb_Sun.Value = "WO" Then Sun = True

   For Each aCell In ws.Range("E30:AI30")
      If aCell = "Mon" And Mon Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Tue" And Tue Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Wed" And Wed Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Thu" And Thu Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Fri" And Fri Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Sat" And Sat Then ws.Cells(iRow, aCell.Column).Value = "WO"
      If aCell = "Sun" And Sun Then ws.Cells(iRow, aCell.Column).Value = "WO"
   Next

   MsgBox "Data added", vbOKOnly + vbInformation, "Data Added"
   Unload Me
   UserForm1.Show

   application.screenupdating = true
   application.Calculation = xlCalculationAutomatic
End Sub

Didn't tested it so it might need some adjustments


问:
Determine points inside each cell of a grid and add a new column to a dataset
I have a dataframe df with a point each 0.1 unit:

```<code>df <- expand.grid(x = seq(0, 20, by = .1),
                  y = seq(0, 20, by = .1))
</code>```

I defined a new dataframe grid which has a point each 4 units:

```<code>grid <- expand.grid(xg = seq(0, 20, by = 4),
                    yg = seq(0, 20, by = 4))
</code>```

I would like to use the points of grid as nodes of a grid and determine the points in df which fall inside its cells.
The information about the grid cell should be added to a new column in df providing a string such as i.j for each point, where i and j are the row and column index of the grid cell, respectively. The new column should report NA for df points on the grid lines.

For example, all df points with 0 < x < 4 and 0 < y < 4 should be labeled as 1.1, whereas points with 8 < x < 12 and 16 < y < 20 should be labeled as 3.5 and so on.

The ideal solution should be fine also for grids with different size, i.e. expand.grid(xg = seq(0, 20, by = 2), yg = seq(0, 20, by = 2).

Thanks for your help.

答:
This is a bit hacky, but you could create the i.j index in grid then join this to df and pad the NAs for each grid chunk:

df <- expand.grid(x = seq(0, 20, by = .1),
                  y = seq(0, 20, by = .1))
head(df)
#>     x y
#> 1 0.0 0
#> 2 0.1 0
#> 3 0.2 0
#> 4 0.3 0
#> 5 0.4 0
#> 6 0.5 0

grid <- expand.grid(xg = seq(0, 20, by = 4),
                    yg = seq(0, 20, by = 4))
head(grid)
#>   xg yg
#> 1  0  0
#> 2  4  0
#> 3  8  0
#> 4 12  0
#> 5 16  0
#> 6 20  0

# Make row/col indices
grid$i <- as.integer(factor(grid$xg))
grid$j <- as.integer(factor(grid$yg))
grid$i.j <- paste(grid$i, grid$j, sep = '.')
grid$i <- NULL
grid$j <- NULL

# Merge indices to df
indexed <- merge(df, grid, by.x = c('x', 'y'), by.y = c('xg', 'yg'), all = TRUE)
head(indexed)
#>   x   y i.j
#> 1 0 0.0 1.1
#> 2 0 0.1  NA
#> 3 0 0.2  NA
#> 4 0 0.3  NA
#> 5 0 0.4  NA
#> 6 0 0.5  NA

# Fill in betweens
for (i in 2:nrow(indexed)) {
  if (is.na(indexed$i.j[i])) {
    indexed$i.j[i] <- indexed$i.j[i - 1]
  }
}
head(indexed)
#>   x   y i.j
#> 1 0 0.0 1.1
#> 2 0 0.1 1.1
#> 3 0 0.2 1.1
#> 4 0 0.3 1.1
#> 5 0 0.4 1.1
#> 6 0 0.5 1.1
```

This would only work if the df sequences intersect the grid sequences, i.e. df[8081, ] = {4.0, 4.0} is in grid and df[1, ] is also in grid.

Also, the for loop is pretty slow. You could try converting it to an Rcpp loop, or maybe there's a more efficient way of non-equi joining with {data.table} or {sqldf}

Body:
I have a dataframe df with a point each 0.1 unit:

df <- expand.grid(x = seq(0, 20, by = .1),
                  y = seq(0, 20, by = .1))

I defined a new dataframe grid which has a point each 4 units:

grid <- expand.grid(xg = seq(0, 20, by = 4),
                    yg = seq(0, 20, by = 4))

I would like to use the points of grid as nodes of a grid and determine the points in df which fall inside its cells.
The information about the grid cell should be added to a new column in df providing a string such as i.j for each point, where i and j are the row and column index of the grid cell, respectively. The new column should report NA for df points on the grid lines.

For example, all df points with 0 < x < 4 and 0 < y < 4 should be labeled as 1.1, whereas points with 8 < x < 12 and 16 < y < 20 should be labeled as 3.5 and so on.

The ideal solution should be fine also for grids with different size, i.e. expand.grid(xg = seq(0, 20, by = 2), yg = seq(0, 20, by = 2).

Thanks for your help.

Body:
This is a bit hacky, but you could create the i.j index in grid then join this to df and pad the NAs for each grid chunk:

df <- expand.grid(x = seq(0, 20, by = .1),
                  y = seq(0, 20, by = .1))
head(df)
#>     x y
#> 1 0.0 0
#> 2 0.1 0
#> 3 0.2 0
#> 4 0.3 0
#> 5 0.4 0
#> 6 0.5 0

grid <- expand.grid(xg = seq(0, 20, by = 4),
                    yg = seq(0, 20, by = 4))
head(grid)
#>   xg yg
#> 1  0  0
#> 2  4  0
#> 3  8  0
#> 4 12  0
#> 5 16  0
#> 6 20  0

# Make row/col indices
grid$i <- as.integer(factor(grid$xg))
grid$j <- as.integer(factor(grid$yg))
grid$i.j <- paste(grid$i, grid$j, sep = '.')
grid$i <- NULL
grid$j <- NULL

# Merge indices to df
indexed <- merge(df, grid, by.x = c('x', 'y'), by.y = c('xg', 'yg'), all = TRUE)
head(indexed)
#>   x   y i.j
#> 1 0 0.0 1.1
#> 2 0 0.1  NA
#> 3 0 0.2  NA
#> 4 0 0.3  NA
#> 5 0 0.4  NA
#> 6 0 0.5  NA

# Fill in betweens
for (i in 2:nrow(indexed)) {
  if (is.na(indexed$i.j[i])) {
    indexed$i.j[i] <- indexed$i.j[i - 1]
  }
}
head(indexed)
#>   x   y i.j
#> 1 0 0.0 1.1
#> 2 0 0.1 1.1
#> 3 0 0.2 1.1
#> 4 0 0.3 1.1
#> 5 0 0.4 1.1
#> 6 0 0.5 1.1

This would only work if the df sequences intersect the grid sequences, i.e. df[8081, ] = {4.0, 4.0} is in grid and df[1, ] is also in grid.

Also, the for loop is pretty slow. You could try converting it to an Rcpp loop, or maybe there's a more efficient way of non-equi joining with {data.table} or {sqldf}


问:
Why React setState is not triggering re-render?
I am trying to use react and update properties with setState, however, it doesnt seem to re-render.

In the following code, you will see that the onStart and onComplete use setState to update the style property.

The property gets updated, but the style does not get changed in the dom, despite my render function appearing to be set up in the correct way?

```<code>export default class FirstScene extends React.Component {
    constructor() {
        super();
        let self=this;
        this.state = {
            style:{display:'hidden'}
        };
        this.mainTimeline= new TimelineMax({repeat:0,paused:true,
            onStart:function(){
                self.setState({style:{display:'block'}})
            }.bind(self),
            onComplete:function(){
                self.setState({style:{display:'hidden'}})
                console.log(this.state);
            }.bind(self)
        });
    }

    render() {
        return (
            <div style={this.state.style} >test hey</div>
        )
    }

};
</code>```

答:
Generally, initialization like this is better handled in the componentDidMount() method, so it's guaranteed that the component exists before the state is modified.

export default class FirstScene extends React.Component {

  state = {
    style: {
      display: 'hidden'
    },
    mainTimeline: null
  }

  componentDidMount() {
    const mainTimeline = new TimelineMax({
      repeat: 0,
      paused: true,
      onStart: () => {
        this.setState({
          style: {
            display: 'block'
          }
        })
      }.bind(self),
      onComplete: () => {
        this.setState({
          style: {
            display: 'hidden'
          }
        })
        console.log(this.state);
      }
    });

    this.setState({
      mainTimeline
    });
  }

  render() {
    return
test hey
;
  }

};```

Also, side note, using es6 arrow functions in your onStart and onComplete callbacks, you can avoid having to bind and trap a reference to this.

Body:
I am trying to use react and update properties with setState, however, it doesnt seem to re-render.

In the following code, you will see that the onStart and onComplete use setState to update the style property.

The property gets updated, but the style does not get changed in the dom, despite my render function appearing to be set up in the correct way?

export default class FirstScene extends React.Component {
    constructor() {
        super();
        let self=this;
        this.state = {
            style:{display:'hidden'}
        };
        this.mainTimeline= new TimelineMax({repeat:0,paused:true,
            onStart:function(){
                self.setState({style:{display:'block'}})
            }.bind(self),
            onComplete:function(){
                self.setState({style:{display:'hidden'}})
                console.log(this.state);
            }.bind(self)
        });
    }

    render() {
        return (

test hey

        )
    }

};

Body:
Generally, initialization like this is better handled in the componentDidMount() method, so it's guaranteed that the component exists before the state is modified.

export default class FirstScene extends React.Component {

  state = {
    style: {
      display: 'hidden'
    },
    mainTimeline: null
  }

  componentDidMount() {
    const mainTimeline = new TimelineMax({
      repeat: 0,
      paused: true,
      onStart: () => {
        this.setState({
          style: {
            display: 'block'
          }
        })
      }.bind(self),
      onComplete: () => {
        this.setState({
          style: {
            display: 'hidden'
          }
        })
        console.log(this.state);
      }
    });

    this.setState({
      mainTimeline
    });
  }

  render() {
    return <div style={this.state.style}>test hey</div>;
  }

};

Also, side note, using es6 arrow functions in your onStart and onComplete callbacks, you can avoid having to bind and trap a reference to this.


问:
Schedule AutoHotKey Script
I have an AutoHotKey script that is functioning properly to log me in to my WordPress dashboard.

I want to add a schedule to run this script:

Run this script at 9am every day

Excluding Saturday and Sunday

Excluding specific dates (Example: Christmas day this year 12/25/17)

Here is the current code

```<code>; Start script, open website login URL
Run http://www.digitango.com/wp-login.php

; Wait for page to fully load
Sleep, 2000

; Click Username Field
Click, 850, 430

; Selected all items in input field
Send, ^{a}

; Remove all from input field
Send, {Del}

; Enter User Name
Send, username

; Click Password Field
Click, 850, 510

; Selected all items in input field
Send, ^{a}

; Remove all from input field
Send, {Del}

; Enter Password
Send, password

; Click Login Button
Click, 1075, 560

; Wait f
Sleep, 2000

; Notify script has started
MsgBox, You successully logged in automatically!

; Enable exit script by hitting escape key
Esc::ExitApp

; End Script
Return
</code>```

答:
This does not address your question of doing it all in AutoHotKey, I'm sorry. What I am providing, is the basic JavaScript to do it in TamperMonkey FF or TamperMonkey Chrome.

If you were to go with this solution, you would simply have to make Bat file that gets triggered by a Scheduled Task. Your bat file would launch your preferred browser, at your desired URL, and from there, TamperMonkey would take care of evaluating today's date to decide if you should get logged in or not. Please note this uses Javascript, and months are represented from 0 to 11(not 1 to 12 as you would normally expect), hence why new Date(2017, 11, 25) is actually December 25 2017 and not November 25 2017.

```<code>//
//TamperMonkey script
//
var workDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];//set your working days
var holidays = [new Date(2017, 11, 25).setHours(0, 0, 0, 0), new Date("2017", "11", "6").setHours(0, 0, 0, 0)];//set your holidays
var today = new Date();//get today's date

/*
This function will return the name of the day
*/
function getDayName(dateStr, locale) {
    var date = new Date(dateStr);
    return date.toLocaleDateString(locale, { weekday: 'long' });
}

/*
If today's day is in the workDays array, and today is not in the hollidays array
Then login
Else Don't log in
*/
if (workDays.indexOf(getDayName(today, "en-US")) > -1 && holidays.indexOf(new Date(today).setHours(0, 0, 0, 0)) == -1) {
    console.log("working today");
    document.getElementById("user_login").value = "your username";//enter your username
    document.getElementById("user_pass").value = "your pwd";//enter your password
    document.getElementById("wp-submit").click();//click the login button
}
else {
    console.log("not working today");
}
</code>```

Following up. The only missing portion here is TaskScheduler. So what I have is a bat file that launches FireFox @ www.google.com. Once the page loads, TamperMonkey takes over and evaluates today's date. If today's date is a good day, it automatically inserts text in the text field, and the button gets clicked.

I created a bat file "GetMeThere.bat"
In that file, I wrote:

"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" "www.google.com"

In TamperMonkey, I created a new script and this is everything that's in it.

```<code>// ==UserScript==
// @name         SearchOnGoogleOnWorkDays
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.google.ca*
// @grant        none
// ==/UserScript==

//
//TamperMonkey script
//
var workDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];//set your working days
var holidays = [new Date(2017, 11, 25).setHours(0, 0, 0, 0), new Date("2017", "11", "6").setHours(0, 0, 0, 0)];//set your holidays
var today = new Date();//get today's date

/*
This function will return the name of the day
*/
function getDayName(dateStr, locale) {
    var date = new Date(dateStr);
    return date.toLocaleDateString(locale, { weekday: 'long' });
}

/*
If today's day is in the workDays array, and today is not in the hollidays array
Then login
Else Don't log in
*/
if (workDays.indexOf(getDayName(today, "en-US")) > -1 && holidays.indexOf(new Date(today).setHours(0, 0, 0, 0)) == -1) {
    console.log("working today");
    //document.getElementById("user_login").value = "your username";//enter your username
    //document.getElementById("user_pass").value = "your pwd";//enter your password
    //document.getElementById("wp-submit").click();//click the login button
    document.getElementById("lst-ib").value = "search for this";
    var els = document.getElementsByName("btnK");
    console.log(els);
    if(els != null){els[0].click();}
}
else {
    console.log("not working today");
}
</code>```

Please note I put this together very quickly to prove the concept. My posted TamperMonkey script, as-is, goes into an infinite search loop because this // @match        https://www.google.ca* is much too broad for production code. But it proves the concept does work. If I double click my bat file, Firefox launches at www.google.com then TamperMonkey automatically does my search.

Title: Schedule AutoHotKey Script

Body:
I have an AutoHotKey script that is functioning properly to log me in to my WordPress dashboard.

I want to add a schedule to run this script:

Run this script at 9am every day

Excluding Saturday and Sunday

Excluding specific dates (Example: Christmas day this year 12/25/17)

Here is the current code

; Start script, open website login URL
Run http://www.digitango.com/wp-login.php

; Wait for page to fully load
Sleep, 2000

; Click Username Field
Click, 850, 430

; Selected all items in input field
Send, ^{a}

; Remove all from input field
Send, {Del}

; Enter User Name
Send, username

; Click Password Field
Click, 850, 510

; Selected all items in input field
Send, ^{a}

; Remove all from input field
Send, {Del}

; Enter Password
Send, password

; Click Login Button
Click, 1075, 560

; Wait f
Sleep, 2000

; Notify script has started
MsgBox, You successully logged in automatically!

; Enable exit script by hitting escape key
Esc::ExitApp

; End Script
Return

Body:
This does not address your question of doing it all in AutoHotKey, I'm sorry. What I am providing, is the basic JavaScript to do it in TamperMonkey FF or TamperMonkey Chrome.

If you were to go with this solution, you would simply have to make Bat file that gets triggered by a Scheduled Task. Your bat file would launch your preferred browser, at your desired URL, and from there, TamperMonkey would take care of evaluating today's date to decide if you should get logged in or not. Please note this uses Javascript, and months are represented from 0 to 11(not 1 to 12 as you would normally expect), hence why new Date(2017, 11, 25) is actually December 25 2017 and not November 25 2017.

//
//TamperMonkey script
//
var workDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];//set your working days
var holidays = [new Date(2017, 11, 25).setHours(0, 0, 0, 0), new Date("2017", "11", "6").setHours(0, 0, 0, 0)];//set your holidays
var today = new Date();//get today's date

/*
This function will return the name of the day
*/
function getDayName(dateStr, locale) {
    var date = new Date(dateStr);
    return date.toLocaleDateString(locale, { weekday: 'long' });
}

/*
If today's day is in the workDays array, and today is not in the hollidays array
Then login
Else Don't log in
*/
if (workDays.indexOf(getDayName(today, "en-US")) > -1 && holidays.indexOf(new Date(today).setHours(0, 0, 0, 0)) == -1) {
    console.log("working today");
    document.getElementById("user_login").value = "your username";//enter your username
    document.getElementById("user_pass").value = "your pwd";//enter your password
    document.getElementById("wp-submit").click();//click the login button
}
else {
    console.log("not working today");
}

Following up. The only missing portion here is TaskScheduler. So what I have is a bat file that launches FireFox @ www.google.com. Once the page loads, TamperMonkey takes over and evaluates today's date. If today's date is a good day, it automatically inserts text in the text field, and the button gets clicked.

I created a bat file "GetMeThere.bat"
In that file, I wrote:

"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" "www.google.com"

In TamperMonkey, I created a new script and this is everything that's in it.

// ==UserScript==
// @name         SearchOnGoogleOnWorkDays
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.google.ca*
// @grant        none
// ==/UserScript==

//
//TamperMonkey script
//
var workDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];//set your working days
var holidays = [new Date(2017, 11, 25).setHours(0, 0, 0, 0), new Date("2017", "11", "6").setHours(0, 0, 0, 0)];//set your holidays
var today = new Date();//get today's date

/*
This function will return the name of the day
*/
function getDayName(dateStr, locale) {
    var date = new Date(dateStr);
    return date.toLocaleDateString(locale, { weekday: 'long' });
}

/*
If today's day is in the workDays array, and today is not in the hollidays array
Then login
Else Don't log in
*/
if (workDays.indexOf(getDayName(today, "en-US")) > -1 && holidays.indexOf(new Date(today).setHours(0, 0, 0, 0)) == -1) {
    console.log("working today");
    //document.getElementById("user_login").value = "your username";//enter your username
    //document.getElementById("user_pass").value = "your pwd";//enter your password
    //document.getElementById("wp-submit").click();//click the login button
    document.getElementById("lst-ib").value = "search for this";
    var els = document.getElementsByName("btnK");
    console.log(els);
    if(els != null){els[0].click();}
}
else {
    console.log("not working today");
}

Please note I put this together very quickly to prove the concept. My posted TamperMonkey script, as-is, goes into an infinite search loop because this // @match        https://www.google.ca* is much too broad for production code. But it proves the concept does work. If I double click my bat file, Firefox launches at www.google.com then TamperMonkey automatically does my search.


问:
checking,if a string of an array of strings is available in a string
all string functions(preg_match,strpos...) in php I know allow me to find a string in a string. My intention is to find a string of an array of strings in a string like this:

```<code>         $pattern = array("jpg", "bmp");
         $subject = $bild->dateiname;
</code>```

Any ideas,how to implemnet my intention using php-function(s)?

答:
If you only want to see if any one of the array strings is in the subject string, then attempt to replace them and check if there was a replacement:

```<code>if(str_replace($pattern, '', $subject) != $subject) {
    echo 'something was found';
}
</code>```

Or:

```<code>if(str_replace($pattern, '', $subject, $count) && $count) {
    echo 'something was found';
}
</code>```

To capture the match use preg_match or to capture all matches:

```<code>preg_match_all('/(' . implode('|', $pattern) . ')/', $subject, $matches);
</code>```

Then inspect $matches.

Body:
all string functions(preg_match,strpos...) in php I know allow me to find a string in a string. My intention is to find a string of an array of strings in a string like this:

         $pattern = array("jpg", "bmp");
         $subject = $bild->dateiname;

Any ideas,how to implemnet my intention using php-function(s)?

Body:
If you only want to see if any one of the array strings is in the subject string, then attempt to replace them and check if there was a replacement:

if(str_replace($pattern, '', $subject) != $subject) {
    echo 'something was found';
}

Or:

if(str_replace($pattern, '', $subject, $count) && $count) {
    echo 'something was found';
}

To capture the match use preg_match or to capture all matches:

preg_match_all('/(' . implode('|', $pattern) . ')/', $subject, $matches);

Then inspect $matches.


问:
Use exec to execute a file inside a function with globals()
I need to execute a file inside a python shell.

I can

```<code>exec(open('Test.py').read())
</code>```

But I need to call it from inside a function.

"Test.py" will set variable C=10

So,

```<code>#x.py
def load(file):
    exec(open(file).read(),globals())

>>> import x
>>> x.load('Test.py')
>>> C
>>> NameError: name 'C' is not defined
</code>```

I have passed in the globals, but I still cant access the varibales from exec.
References:

In Python, why doesn't an import in an exec in a function work?

How to execute a file within the python interpreter?

答:
So here is one way to do it

```<code>#x.py
def load(file):
    exec(open(file).read())
    return locals()

>>> import x
>>> var = x.load('Test.py')
>>> locals().update(var)
>>> C
>>> 10
</code>```

Hope it helps

Body:
I need to execute a file inside a python shell.

I can

exec(open('Test.py').read())

But I need to call it from inside a function.

"Test.py" will set variable C=10

So,

#x.py
def load(file):
    exec(open(file).read(),globals())

>>> import x
>>> x.load('Test.py')
>>> C
>>> NameError: name 'C' is not defined

I have passed in the globals, but I still cant access the varibales from exec.
References:

In Python, why doesn't an import in an exec in a function work?

How to execute a file within the python interpreter?

Body:
So here is one way to do it

#x.py
def load(file):
    exec(open(file).read())
    return locals()

>>> import x
>>> var = x.load('Test.py')
>>> locals().update(var)
>>> C
>>> 10

Hope it helps


问:
Find employees without training records
I have an Access training database that logs training by session and topic.  The reason for the split is one session might cover multiple topics.  I'm trying to make a query that will pull which employees are missing a given topic.  I have no problem getting a query that lists what training each employee attended, however the reverse is not working.  Data model shown below:

答:
You can use joins to correlate employee ids to topics and then use the not exists operator to find employees that are missing a topic:

```<code>SELECT *
FROM   tblEmployees e
WHERE  NOT EXISTS (SELECT *
                   FROM   tblTrainingTopics tt
                   JOIN   tblTrainingSessions ts ON tt.sessionid = ts.id
                   JOIN   tblTrainingLog tl ON tl.session = ts.id
                   WHERE  tl.eenumber = e.eeid AND tt.topic = 'some_topic')
</code>```

Title: Find employees without training records

Body:
You can use joins to correlate employee ids to topics and then use the not exists operator to find employees that are missing a topic:

SELECT *
FROM   tblEmployees e
WHERE  NOT EXISTS (SELECT *
                   FROM   tblTrainingTopics tt
                   JOIN   tblTrainingSessions ts ON tt.sessionid = ts.id
                   JOIN   tblTrainingLog tl ON tl.session = ts.id
                   WHERE  tl.eenumber = e.eeid AND tt.topic = 'some_topic')


问:
How to plot a histogram from existing counts with uneven bin widths using ggplot
I want to create an histogram from already existing classes. I have this dataset:

```<code>interval        counts
0 - 8.50        2577
8.51 - 10.00    1199
10.01 - 12.00   1878
12.01 - 14.00   637
14.01 - 16.00   369
16.01 - 18.00   98
18.00 - 20.00   308

library(ggplot2)

plot_tab5_lohn <- ggplot(DS18, aes(x=interval)) + geom_histogram(stat="count")
return(plot_tab5_lohn)})
</code>```

does result in this graph:

I want the counts to be on the y axis and the intervals have to be a different width. How can I do this?

EDIT:
I've made it this far:

using this code

```<code>DS18$interval <- factor(DS18$interval, levels = DS18$interval)
output$DS32 <- renderPlot({
plot_tab5_lohn <- ggplot(DS18, aes(x=interval, y = counts)) +
geom_col() +
geom_point(color = "red") +
geom_line(aes(group = 1), color = "red")
return(plot_tab5_lohn)
})
</code>```

I'd like the bars to be as wide as the interval itself. And the density should be on the Y-Axis. The sum of the areas should be 1 (100%) then.
Something like this link

答:
You can extract the boundaries, then plot using geom_rect:

```<code># Using dt from @www
library(tidyr)
dt2 <- separate(dt, interval, c('left', 'right'), sep = ' - ', convert = TRUE)
ggplot(dt2) +
  geom_rect(aes(xmin = left, xmax = right, ymin = 0, ymax = counts),
            col = 1) +
  geom_line(aes(x = right + (left - right) / 2, y = counts),
            col = 'red')
</code>```

Alternatively, you can first expand your data into single observations, this also easily allows you to plot the densities instead:

```<code>library(dplyr)
library(tidyr)
dt3 <- dt %>%
  group_by(interval) %>%
  do(data.frame(interval = rep.int(.$interval, .$counts), stringsAsFactors = FALSE)) %>%
  separate(interval, c('left', 'right'), sep = ' - ', convert = TRUE) %>%
  mutate(value = right + (left - right) / 2)
breaks <- c(0, unique(dt3$right))

ggplot(dt3, aes(value)) +
  geom_histogram(aes(y = ..density..), breaks = breaks, col = 1) +
  geom_freqpoly(aes(y = ..density..), breaks = breaks, col = 'red')
</code>```

Body:
I want to create an histogram from already existing classes. I have this dataset:

interval        counts
0 - 8.50        2577
8.51 - 10.00    1199
10.01 - 12.00   1878
12.01 - 14.00   637
14.01 - 16.00   369
16.01 - 18.00   98
18.00 - 20.00   308

library(ggplot2)

plot_tab5_lohn <- ggplot(DS18, aes(x=interval)) + geom_histogram(stat="count")
return(plot_tab5_lohn)})

does result in this graph:

I want the counts to be on the y axis and the intervals have to be a different width. How can I do this?

EDIT:
I've made it this far:

using this code

DS18$interval <- factor(DS18$interval, levels = DS18$interval)
output$DS32 <- renderPlot({
plot_tab5_lohn <- ggplot(DS18, aes(x=interval, y = counts)) +
geom_col() +
geom_point(color = "red") +
geom_line(aes(group = 1), color = "red")
return(plot_tab5_lohn)
})

I'd like the bars to be as wide as the interval itself. And the density should be on the Y-Axis. The sum of the areas should be 1 (100%) then.
Something like this link

Body:
You can extract the boundaries, then plot using geom_rect:

# Using dt from @www
library(tidyr)
dt2 <- separate(dt, interval, c('left', 'right'), sep = ' - ', convert = TRUE)
ggplot(dt2) +
  geom_rect(aes(xmin = left, xmax = right, ymin = 0, ymax = counts),
            col = 1) +
  geom_line(aes(x = right + (left - right) / 2, y = counts),
            col = 'red')

Alternatively, you can first expand your data into single observations, this also easily allows you to plot the densities instead:

library(dplyr)
library(tidyr)
dt3 <- dt %>%
  group_by(interval) %>%
  do(data.frame(interval = rep.int(.$interval, .$counts), stringsAsFactors = FALSE)) %>%
  separate(interval, c('left', 'right'), sep = ' - ', convert = TRUE) %>%
  mutate(value = right + (left - right) / 2)
breaks <- c(0, unique(dt3$right))

ggplot(dt3, aes(value)) +
  geom_histogram(aes(y = ..density..), breaks = breaks, col = 1) +
  geom_freqpoly(aes(y = ..density..), breaks = breaks, col = 'red')


问:
how can I turn off screen in android programmatically
I want to turn off the screen. So I tried to do it with PowerManager class but it didn't turn off screen.</p>

```<code>PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
</code>```

答:
You can turn off screen by overriding system screen turn off time.

First get system turn off time

```<code>int defaultTurnOffTime =  Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 60000);
</code>```

then put your turn off time

```<code>Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 1000);
</code>```

and when the screen turned off, set default turn off time

```<code>Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, defaultTurnOffTime);
</code>```

add below permission

```<code><uses-permission android:name="android.permission.WRITE_SETTINGS"/>
</code>```

Body:
I want to turn off the screen. So I tried to do it with PowerManager class but it didn't turn off screen.

PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();

Body:
You can turn off screen by overriding system screen turn off time.

First get system turn off time

int defaultTurnOffTime =  Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 60000);

then put your turn off time

Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 1000);

and when the screen turned off, set default turn off time

Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, defaultTurnOffTime);

add below permission

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>


问:
Join in pandas based on column interpolation
I'm trying to join 2 data frames based on the 2 columns. The problem is that I'd like to interpolate one of the column values.

```<code>df1 = pd.DataFrame(data=[['ABC', 'USD', 2.31], ['DEF', 'MXN', 4.72], ['XYZ', 'EUR', 5.83]], columns=['A', 'B', 'C'])
>>df1
    A    B     C
0  ABC  USD  2.31
1  DEF  MXN  4.72
2  XYZ  EUR  5.83

df2 = pd.DataFrame(data=[['USD', 1, 0.5], ['USD', 2, 0.8], ['USD', 3, 1.5], ['MXN', 2, 0.6], ['MXN', 3, 0.71], ['MXN', 4, 0.88], ['EUR', 6, 0.12], ['EUR', 7, 0.5], ['EUR', 8, 0.7]], columns=['B', 'C', 'V'])
>>df2
     B  C     V
0  USD  1  0.50
1  USD  2  0.80
2  USD  3  1.50
3  MXN  2  0.60
4  MXN  3  0.71
5  MXN  4  0.88
6  EUR  6  0.12
7  EUR  7  0.50
8  EUR  8  0.70
</code>```

I'd like to join the two data frames based on columns B and C such that I get the following result

```<code>     A    B     C      V
0  ABC  USD  2.31  1.017
1  DEF  MXN  4.72  0.880
2  XYZ  EUR  5.83  0.120
</code>```

The interpolation is linear and uses the closest points when out of range.

The first value

```<code>1.017=0.8+(2.31-2)*(1.5-0.8)
</code>```

The second value is there because the maximum value MXN has in df2 is 0.6

The third value is similarly the maximum value for EUR, which is 0.12

The goal is to do this as efficiently as possible since the dataframes are quite big.

As of now, I'm grouping by the B and using scipy interpolate function.

答:
Here's the solution I came up with though I think you could probably improve this by using an apply with scipy.interpolate for the interpolation step. First create floor, ceiling and delta columns for df1.

```<code>enter df1['C_floor'] = df1.C.apply(np.floor)
df1['C_ceil'] = df1.C.apply(np.ceil)
df1['C_delta'] = df1.C - df1.C_floor
</code>```

Do a double left join to obtain the V corresponding to the floor and ceiling of C from df2.

```<code>df1 = df1.merge(df2, how ='left', left_on = ['B',  'C_floor'], right_on = ['B', 'C'])
df1 = df1.merge(df2, how ='left', left_on = ['B',  'C_ceil'], right_on = ['B', 'C'])
</code>```

Here's where I think you could make the code faster, but I wrote a brief function to find the weighted mean and account for cases where C falls outside the range available in df2.

```<code>def weighted_mean(x):
    if np.isnan(x.V_x):
        return x.V_y
    elif np.isnan(x.V_y):
        return x.V_x
    else:
        return x.V_y + (x.V_x - x.V_y) * x.C_delta

df1['V'] = df1[['V_x', 'V_y', 'C_delta']].apply(weighted_mean, axis = 1)
</code>```

Finally some cleanup.

```<code>df1 = df1[['A', 'B', 'C_x', 'V']]
df1.columns = ['A', 'B', 'C', 'V']
</code>```

Which gives.

```<code>     A    B     C      V
0  ABC  USD  2.31  1.283
1  DEF  MXN  4.72  0.880
2  XYZ  EUR  5.83  0.120
</code>```

Body:
I'm trying to join 2 data frames based on the 2 columns. The problem is that I'd like to interpolate one of the column values.

df1 = pd.DataFrame(data=[['ABC', 'USD', 2.31], ['DEF', 'MXN', 4.72], ['XYZ', 'EUR', 5.83]], columns=['A', 'B', 'C'])
>>df1
    A    B     C
0  ABC  USD  2.31
1  DEF  MXN  4.72
2  XYZ  EUR  5.83

df2 = pd.DataFrame(data=[['USD', 1, 0.5], ['USD', 2, 0.8], ['USD', 3, 1.5], ['MXN', 2, 0.6], ['MXN', 3, 0.71], ['MXN', 4, 0.88], ['EUR', 6, 0.12], ['EUR', 7, 0.5], ['EUR', 8, 0.7]], columns=['B', 'C', 'V'])
>>df2
     B  C     V
0  USD  1  0.50
1  USD  2  0.80
2  USD  3  1.50
3  MXN  2  0.60
4  MXN  3  0.71
5  MXN  4  0.88
6  EUR  6  0.12
7  EUR  7  0.50
8  EUR  8  0.70

I'd like to join the two data frames based on columns B and C such that I get the following result

     A    B     C      V
0  ABC  USD  2.31  1.017
1  DEF  MXN  4.72  0.880
2  XYZ  EUR  5.83  0.120

The interpolation is linear and uses the closest points when out of range.

The first value

1.017=0.8+(2.31-2)*(1.5-0.8)

The second value is there because the maximum value MXN has in df2 is 0.6

The third value is similarly the maximum value for EUR, which is 0.12

The goal is to do this as efficiently as possible since the dataframes are quite big.

As of now, I'm grouping by the B and using scipy interpolate function.

Body:
Here's the solution I came up with though I think you could probably improve this by using an apply with scipy.interpolate for the interpolation step. First create floor, ceiling and delta columns for df1.

enter df1['C_floor'] = df1.C.apply(np.floor)
df1['C_ceil'] = df1.C.apply(np.ceil)
df1['C_delta'] = df1.C - df1.C_floor

Do a double left join to obtain the V corresponding to the floor and ceiling of C from df2.

df1 = df1.merge(df2, how ='left', left_on = ['B',  'C_floor'], right_on = ['B', 'C'])
df1 = df1.merge(df2, how ='left', left_on = ['B',  'C_ceil'], right_on = ['B', 'C'])

Here's where I think you could make the code faster, but I wrote a brief function to find the weighted mean and account for cases where C falls outside the range available in df2.

def weighted_mean(x):
    if np.isnan(x.V_x):
        return x.V_y
    elif np.isnan(x.V_y):
        return x.V_x
    else:
        return x.V_y + (x.V_x - x.V_y) * x.C_delta

df1['V'] = df1[['V_x', 'V_y', 'C_delta']].apply(weighted_mean, axis = 1)

Finally some cleanup.

df1 = df1[['A', 'B', 'C_x', 'V']]
df1.columns = ['A', 'B', 'C', 'V']

Which gives.

     A    B     C      V
0  ABC  USD  2.31  1.283
1  DEF  MXN  4.72  0.880
2  XYZ  EUR  5.83  0.120


答:
You'll have to include the header that declares the strncpy function. So add

```<code>#include <cstring>
</code>```

at the beginning.

And the member name is m_wage but you've used it as wage in your print member function.

Change

```<code>std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
</code>```

to

```<code>std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<m_wage<<std::endl;
                                                         ^^^^^^
</code>```

Title: C++ - class issue

Body:
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.

Body:
You'll have to include the header that declares the strncpy function. So add

#include <cstring>

at the beginning.

And the member name is m_wage but you've used it as wage in your print member function.

Change

std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;

to

std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<m_wage<<std::endl;
                                                         ^^^^^^


问:
JSON Feed Won't Display in Tableview
I'm having trouble displaying data in a tableview. I know I'm reaching the data, because of the print function I have set up, displaying the data is a different story. For reference, this is a JSON feed coming from and API, listed here at https://api.opendota.com/api/rankings. If anyone has any advice, I would appreciate it. Thanks. </p>

```<code>import UIKit

struct PlayerStatsParent:Decodable{
    let rankings: [PlayerStats]
}

//Optional objects are defined using ?
struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var rankTable: UITableView!

    var rank = [PlayerStats]()

    override func viewDidLoad() {
        super.viewDidLoad()

        //this is an optional URL, so need to define objects in contains
        let jsonUrlString = "https://api.opendota.com/api/rankings"
        guard let url = URL(string: jsonUrlString) else {return}
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else {return}
            //let dataAsString = String(data: data, encoding: .utf8)
            //print(dataAsString)

            do{
                let downloadedRank = try JSONDecoder().decode(PlayerStatsParent.self, from: data)
                self.rank = downloadedRank.rankings
                DispatchQueue.main.async {
                    self.rankTable.reloadData()
                }
                print(downloadedRank.rankings)
            } catch let jsonErr {
                print("Error jsonErr", jsonErr)
            }
        }.resume()
    }

    let jsonUrlString = "https://api.opendota.com/api/rankings"

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "rankCell") as? RankTableViewCell else { return UITableViewCell() }
        cell.nameLabel.text = rank[indexPath.row].personaname

        return cell
    }
</code>```

答:
Unless you've set your UITableView delegate and dataSource in your storyboard you need to do so in viewDidLoad, like this:

```<code>self.rankTable.delegate = self
self.rankTable.dataSource = self
</code>```

Otherwise your tableview has no way of getting data.

Title: JSON Feed Won't Display in Tableview

Body:
I'm having trouble displaying data in a tableview. I know I'm reaching the data, because of the print function I have set up, displaying the data is a different story. For reference, this is a JSON feed coming from and API, listed here at https://api.opendota.com/api/rankings. If anyone has any advice, I would appreciate it. Thanks.

import UIKit

struct PlayerStatsParent:Decodable{
    let rankings: [PlayerStats]
}

//Optional objects are defined using ?
struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var rankTable: UITableView!

    var rank = [PlayerStats]()

    override func viewDidLoad() {
        super.viewDidLoad()

        //this is an optional URL, so need to define objects in contains
        let jsonUrlString = "https://api.opendota.com/api/rankings"
        guard let url = URL(string: jsonUrlString) else {return}
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else {return}
            //let dataAsString = String(data: data, encoding: .utf8)
            //print(dataAsString)

            do{
                let downloadedRank = try JSONDecoder().decode(PlayerStatsParent.self, from: data)
                self.rank = downloadedRank.rankings
                DispatchQueue.main.async {
                    self.rankTable.reloadData()
                }
                print(downloadedRank.rankings)
            } catch let jsonErr {
                print("Error jsonErr", jsonErr)
            }
        }.resume()
    }

    let jsonUrlString = "https://api.opendota.com/api/rankings"

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "rankCell") as? RankTableViewCell else { return UITableViewCell() }
        cell.nameLabel.text = rank[indexPath.row].personaname

        return cell
    }

Body:
Unless you've set your UITableView delegate and dataSource in your storyboard you need to do so in viewDidLoad, like this:

self.rankTable.delegate = self
self.rankTable.dataSource = self

Otherwise your tableview has no way of getting data.


问:
Using for loop and if statement side by side C++
Can someone explain this syntax of using for and if side by side?    </p>

```<code>int min_dist = huge;
int v = -1;

for (int i = 0; i < N; ++i) if (!done[i]) {
    if (d[i] >= min_dist) continue;
    min_dist = d[i];
    v = i;
}
</code>```

答:
This is a case of poorly indented and organized code. It is equivalent to:

```<code>for (int i = 0; i < N; ++i)
{
  if (!done[i])
  {
    if (d[i] >= min_dist) continue;
    min_dist = d[i];
    v = i;
  }
}
</code>```

Adding the block {} right after the for line makes it easier to read.

You can add another block for the second if statement to make it still easier.

```<code>for (int i = 0; i < N; ++i)
{
  if (!done[i])
  {
    if (d[i] >= min_dist)
    {
      continue;
    }

    min_dist = d[i];
    v = i;
  }
}
</code>```

You can simplify it to:

```<code>for (int i = 0; i < N; ++i)
{
  if (!done[i])
  {
    if (d[i] < min_dist)
    {
      min_dist = d[i];
      v = i;
    }
  }
}
</code>```

The two ifs can be combined to make it simpler still.

```<code>for (int i = 0; i < N; ++i)
{
  if (!done[i] && d[i] < min_dist)
  {
    min_dist = d[i];
    v = i;
  }
}
</code>```

Body:
Can someone explain this syntax of using for and if side by side?

int min_dist = huge;
int v = -1;

for (int i = 0; i < N; ++i) if (!done[i]) {
    if (d[i] >= min_dist) continue;
    min_dist = d[i];
    v = i;
}

Body:
This is a case of poorly indented and organized code. It is equivalent to:

for (int i = 0; i < N; ++i)
{
  if (!done[i])
  {
    if (d[i] >= min_dist) continue;
    min_dist = d[i];
    v = i;
  }
}

Adding the block {} right after the for line makes it easier to read.

You can add another block for the second if statement to make it still easier.

for (int i = 0; i < N; ++i)
{
  if (!done[i])
  {
    if (d[i] >= min_dist)
    {
      continue;
    }

    min_dist = d[i];
    v = i;
  }
}

You can simplify it to:

for (int i = 0; i < N; ++i)
{
  if (!done[i])
  {
    if (d[i] < min_dist)
    {
      min_dist = d[i];
      v = i;
    }
  }
}

The two ifs can be combined to make it simpler still.

for (int i = 0; i < N; ++i)
{
  if (!done[i] && d[i] < min_dist)
  {
    min_dist = d[i];
    v = i;
  }
}


Title: Returning a pandas DataFrame with the indexes of first next cases of >= value

Body:
Initial DataFrame

index        is_case        value_a         value_b
03/01/2005      True    0.598081665     0.189099313
04/01/2005     False    0.480809369     0.142255603
05/01/2005     False    0.963128886     0.422756089
06/01/2005     False    0.687675456     0.739599384
07/01/2005      True    0.513017431     0.397303797
08/01/2005      True    0.691884131     0.922642361
09/01/2005     False    0.659555415     0.222993436
10/01/2005     False    0.920539474     0.553573214
11/01/2005     False    0.360990121     0.535021421
12/01/2005     False    0.512528553     0.343931584
13/01/2005     False    0.083391071     0.277004714
14/01/2005     False    0.382696661     0.204780359
15/01/2005     False    0.838666246     0.337101306
16/01/2005      True    0.363920089     0.355211134
17/01/2005     False    0.354853214     0.691884131
18/01/2005     False    0.089324832     0.910276245
19/01/2005     False    0.611991454     0.513667459
20/01/2005      True    0.210785609     0.839849547

Desired Output:

The important thing about the output is to contain the column output and the index. Other columns may or may not be in the output.

index        is_case        value_a         value_b          output
03/01/2005      True    0.598081665     0.189099313      06/01/2005
07/01/2005      True    0.513017431     0.397303797      08/01/2005
08/01/2005      True    0.691884131     0.922642361      17/01/2005
16/01/2005      True    0.363920089     0.355211134      17/01/2005
20/01/2005      True    0.210785609     0.839849547             NaN

Transformation Logic

Get the value_a of all rows where is_case is True and search from the next row onwards for a value_b which is greater or equal than value_a, it returns the first index that meets this criteria in column output.

Body:
Using numpy with idxmax

mm=np.triu(-df['value_a'].values[:,None]+df['value_b'].values,1)
mm[np.tril_indices(mm.shape[0], 0)] = np.nan
temp=pd.DataFrame(mm)

df1=df.loc[df['is_case']]
df1['New']=np.nan
df1['New'].iloc[:4]=df['index'].iloc[(temp>=0).replace(False,np.nan).idxmax(1)[df['is_case']].dropna().astype(int).values].values

df1
Out[1098]:
         index  is_case   value_a   value_b         New
0   03/01/2005     True  0.598082  0.189099  06/01/2005
4   07/01/2005     True  0.513017  0.397304  08/01/2005
5   08/01/2005     True  0.691884  0.922642  17/01/2005
13  16/01/2005     True  0.363920  0.355211  17/01/2005
17  20/01/2005     True  0.210786  0.839850         NaN


问:
JSON object from Stringified value
Here is my very simple C# class object that I am trying to turn into a JSON string and stringifying:

```<code>public class rTestObject
{
    public rTestObject()
    {
        Name = "Hello";
        State = 7;
    }

    public string Name { get; set; }
    public int State { get; set; }
}
</code>```

I call the following static method:

```<code>    // Json.net
    // from Newtonsoft.Json.dll
    // version 8.0.2.19309
    //

    using Newtonsoft.Json;
    public static string ConvertToJSON<T>(T obj)
    {
        return JsonConvert.SerializeObject(obj);
    }
</code>```

Which produces the following (expected) output:

```<code>    {"Name":"Hello","State":7}
</code>```

I call the following static method to stringify my JSON string

```<code>    public static string Stringify(string json)
    {
        return JsonConvert.ToString(json);
    }
</code>```

Which produces the following (I think this is expected ??) output:

```<code>    "{\"Name\":\"Hello\",\"State\":7}"
</code>```

My question how do I get from:

```<code>    "{\"Name\":\"Hello\",\"State\":7}"
</code>```

back to rTestObject?

Here is what I have tried:

TRY 1

```<code>    public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
    {
        Newtonsoft.Json.Linq.JObject j = Newtonsoft.Json.Linq.JObject.Parse(stringifiedJSON);
        return ConvertFromJSON<T>(j.ToString());
    }
</code>```

Here is the exception:

```<code>    {"Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 34."}
</code>```

TRY 2

```<code>    public static T ConvertFromJSON<T>(string jsonNotation)
    {
        return JsonConvert.DeserializeObject<T>(jsonNotation, NoNullStrings);
    }
</code>```

Here is the exception:

```<code>    {"Error converting value \"{\"Name\":\"Hello\",\"State\":7}\" to type 'RestApi.Objects.rTestObject'. Path '', line 1, position 34."}
</code>```

Solution:

Thank you Alexander I. !

```<code>    public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
    {
        var json = JsonConvert.DeserializeObject<string>(stringifiedJSON);
        return ConvertFromJSON<T>(json);
    }
</code>```

答:
Please review next example:

```<code>class Program
    {
        static void Main(string[] args)
        {
            var test = new TestObject
            {
                Name = "Hello",
                State = 7
            };

            var json = ConvertToJson(test);
            var stringify = Stringify(json);

            var result = StringifyToObject<TestObject>(stringify);
        }

        public static string ConvertToJson<T>(T obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public static string Stringify(string json)
        {
            return JsonConvert.ToString(json);
        }

        public static T StringifyToObject<T>(string stringify)
        {
            var json = JsonConvert.DeserializeObject<string>(stringify);
            var result = JsonConvert.DeserializeObject<T>(json);
            return result;
        }
    }

    public class TestObject
    {
        public TestObject()
        {
            Name = "Hi";
            State = 0;
        }

        public string Name { get; set; }
        public int State { get; set; }
    }
</code>```

Look at StringifyToObject method.

Convert stringified string to JSON string

Desirialize JSON string to object

Title: JSON object from Stringified value

Body:
Here is my very simple C# class object that I am trying to turn into a JSON string and stringifying:

public class rTestObject
{
    public rTestObject()
    {
        Name = "Hello";
        State = 7;
    }

    public string Name { get; set; }
    public int State { get; set; }
}

I call the following static method:

    // Json.net
    // from Newtonsoft.Json.dll
    // version 8.0.2.19309
    //

    using Newtonsoft.Json;
    public static string ConvertToJSON<T>(T obj)
    {
        return JsonConvert.SerializeObject(obj);
    }

Which produces the following (expected) output:

    {"Name":"Hello","State":7}

I call the following static method to stringify my JSON string

    public static string Stringify(string json)
    {
        return JsonConvert.ToString(json);
    }

Which produces the following (I think this is expected ??) output:

    "{\"Name\":\"Hello\",\"State\":7}"

My question how do I get from:

    "{\"Name\":\"Hello\",\"State\":7}"

back to rTestObject?

Here is what I have tried:

TRY 1

    public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
    {
        Newtonsoft.Json.Linq.JObject j = Newtonsoft.Json.Linq.JObject.Parse(stringifiedJSON);
        return ConvertFromJSON<T>(j.ToString());
    }

Here is the exception:

    {"Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 34."}

TRY 2

    public static T ConvertFromJSON<T>(string jsonNotation)
    {
        return JsonConvert.DeserializeObject<T>(jsonNotation, NoNullStrings);
    }

Here is the exception:

    {"Error converting value \"{\"Name\":\"Hello\",\"State\":7}\" to type 'RestApi.Objects.rTestObject'. Path '', line 1, position 34."}

Solution:

Thank you Alexander I. !

    public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
    {
        var json = JsonConvert.DeserializeObject<string>(stringifiedJSON);
        return ConvertFromJSON<T>(json);
    }

Body:
Please review next example:

class Program
    {
        static void Main(string[] args)
        {
            var test = new TestObject
            {
                Name = "Hello",
                State = 7
            };

            var json = ConvertToJson(test);
            var stringify = Stringify(json);

            var result = StringifyToObject<TestObject>(stringify);
        }

        public static string ConvertToJson<T>(T obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public static string Stringify(string json)
        {
            return JsonConvert.ToString(json);
        }

        public static T StringifyToObject<T>(string stringify)
        {
            var json = JsonConvert.DeserializeObject<string>(stringify);
            var result = JsonConvert.DeserializeObject<T>(json);
            return result;
        }
    }

    public class TestObject
    {
        public TestObject()
        {
            Name = "Hi";
            State = 0;
        }

        public string Name { get; set; }
        public int State { get; set; }
    }

Look at StringifyToObject method.

Convert stringified string to JSON string

Desirialize JSON string to object