问:
antd 4: setting a default value for Select with defaultValue, can't use initialValue
In our rather complex form we have a dynamic form field (similar to the example in the antd documentation, except using a Select field). We use initialValue to feed our Form data from the database, now we want to have our Select fields, which are added dynamically, to have a default value.

The problem exists in the fact that it isn't possible to add an initialValue to fields that haven't rendered yet + form doesn't know how many dynamic Select fields will be added.

So instinctively I resorted to the defaultValue prop on the Select box, which in my eyes should just work, but it doesn't. (in antd 4 there is no fieldDescriptor with a defaultValue)

Maybe this example will explain better what I'm trying to say:
https://codesandbox.io/s/thirsty-hamilton-m7bmc

If you add a field in the example and hit submit, it will complain the field is required. However it certainly does have a value in there, but apparently not for the Form state.

I hope someone else has encountered a similar issue

答:
Your Select components need VALUE to be defined. I see you have defaultValue, but they also need such properties as VALUE, and ONCHANGE. When you add them the select will start to work properly.

1). It is better to define default value inside VALUE property, so that if nothing is selected by user (selected value is undefined), the value will default to whatever you mention in the following condition with ternary operator:

value={selectedValue ? selectedValue : defaultValue}.

2). In onChange property you need to pass value and update the state with that value:

onChange={(value) => this.updateSelectedValue(value)}

```<code>import React, { PureComponent } from "react";
import { Form, Select } from "antd";

const { Option } = Select;
export default class DynamicFieldSet extends PureComponent {
    state = {
        selectedValue: undefined,
    }

    updateSelectedValue = value => this.setState({ selectedValue: value })

    render() {
        const { selectedValue } = this.state;
        return (
            <Form>
                    <Form.Item>
                        <Select
                            value={selectedValue ? selectedValue : "TAG"}
                            onChange={(value) => this.updateSelectedValue(value)}
                        >
                            <Option value="MARKER">Marker</Option>
                            <Option value="TAG">Tag</Option>
                            <Option value="FIELD">Field</Option>
                        </Select>
                    </Form.Item>
            </Form>
          );
    }
}
</code>```

Body:
Your Select components need VALUE to be defined. I see you have defaultValue, but they also need such properties as VALUE, and ONCHANGE. When you add them the select will start to work properly.

1). It is better to define default value inside VALUE property, so that if nothing is selected by user (selected value is undefined), the value will default to whatever you mention in the following condition with ternary operator:

value={selectedValue ? selectedValue : defaultValue}.

2). In onChange property you need to pass value and update the state with that value:

onChange={(value) => this.updateSelectedValue(value)}

import React, { PureComponent } from "react";
import { Form, Select } from "antd";

const { Option } = Select;
export default class DynamicFieldSet extends PureComponent {
    state = {
        selectedValue: undefined,
    }

    updateSelectedValue = value => this.setState({ selectedValue: value })

    render() {
        const { selectedValue } = this.state;
        return (
            <Form>
                    <Form.Item>
                        <Select
                            value={selectedValue ? selectedValue : "TAG"}
                            onChange={(value) => this.updateSelectedValue(value)}
                        >
                            <Option value="MARKER">Marker</Option>
                            <Option value="TAG">Tag</Option>
                            <Option value="FIELD">Field</Option>
                        </Select>
                    </Form.Item>
            </Form>
          );
    }
}


来源: stackexchange

问:
SQL sub-queries not returning expected result
```<code>Select name
from instructor
where dept_name = 'Comp. Sci.' and ID in
    (select ID
     from course
     where title != 'Intro. to Computer Science')
</code>```

With this input I want the output to be the instructors who never taught "Intro. to Computer Science but the output is all instructors from CS rather than just the 1 Professor Brant who has not taught Intro to Computer Science. What am I doing wrong?

答:
this should work for you</p>

```<code>select i.name
from instructor as i, teaches as t
where i.dept_name = 'Comp. Sci.' and i.ID=t.ID
and not exists (
  select 1
  from course
  where t.ID = course.course_id and title = 'Intro. to Computer Science'
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Select name
from instructor
where dept_name = 'Comp. Sci.' and ID in
    (select ID
     from course
     where title != 'Intro. to Computer Science')

With this input I want the output to be the instructors who never taught "Intro. to Computer Science but the output is all instructors from CS rather than just the 1 Professor Brant who has not taught Intro to Computer Science. What am I doing wrong?

Body:
this should work for you

select i.name
from instructor as i, teaches as t
where i.dept_name = 'Comp. Sci.' and i.ID=t.ID
and not exists (
  select 1
  from course
  where t.ID = course.course_id and title = 'Intro. to Computer Science'
)


问:
ArrayList<String[]> won't add more than one item
I'm trying to create an ArrayList of String[], but can't get it to add more than one item. Ultimately I want to extract the items from the ArrayList and send them to a JTable. The program is 5 separate classes, but here's the applicable code for this issue:

```<code>    static JComboBox<String> foodChoice;
    DefaultTableModel foodList;
    static String[] newFood;
    static List<String[]> foodData;
    JTextField newFoodText, portionText, carbsText;

public Main() {
        void createFood() {

            String[] foodProperties = new String[3];
            foodProperties[0] = newFoodText.getText();
            foodProperties[1] = portionText.getText();
            foodProperties[2] = carbsText.getText();
            Main.createFood(foodProperties);
            }

    static void createFood(String[] foodArray) {
            foodData = new ArrayList<String[]>();
            foodData.add(foodArray);
            foodChoice.addItem(foodArray[0]);
        }

        void addFoodToTable() {

            String[] s = new String[3];
            s = (String[]) foodData.get(foodChoice.getSelectedIndex());
            System.out.println(foodData.get(0));
            System.out.println(foodData.get(1));
        }
</code>```

addFoodToTable gets called with a button click. So the issue I'm having is that (based on the sysouts) I will get a pointer address to the first entry in the ArrayList, but then a Null Pointer Exception stating that it is out of bounds for Length 0 when it tries to print the second one to console. This is obviously after calling createFood() 3 or four times in order to populate foodData. I can provide additional code if required, it's just too much to place in whole into this post. Thanks!

答:
you clear out foodData every time you call createFood  remove this line:

foodData = new ArrayList();

and move the initialization to a static level , like this:

```<code>static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]>  foodData = new ArrayList<String[]>();
JTextField newFoodText, portionText, carbsText;

public Main() {
  void createFood() {

    String[] foodProperties = new String[3];
    foodProperties[0] = newFoodText.getText();
    foodProperties[1] = portionText.getText();
    foodProperties[2] = carbsText.getText();
    Main.createFood(foodProperties);
  }

  static void createFood(String[] foodArray) {
    foodData.add(foodArray);
    foodChoice.addItem(foodArray[0]);
  }

  void addFoodToTable() {

    String[] s = new String[3];
    s = (String[]) foodData.get(foodChoice.getSelectedIndex());
    System.out.println(foodData.get(0));
    System.out.println(foodData.get(1));
  }
</code>```

Body:
I'm trying to create an ArrayList of String[], but can't get it to add more than one item. Ultimately I want to extract the items from the ArrayList and send them to a JTable. The program is 5 separate classes, but here's the applicable code for this issue:

    static JComboBox<String> foodChoice;
    DefaultTableModel foodList;
    static String[] newFood;
    static List<String[]> foodData;
    JTextField newFoodText, portionText, carbsText;

public Main() {
        void createFood() {

            String[] foodProperties = new String[3];
            foodProperties[0] = newFoodText.getText();
            foodProperties[1] = portionText.getText();
            foodProperties[2] = carbsText.getText();
            Main.createFood(foodProperties);
            }

    static void createFood(String[] foodArray) {
            foodData = new ArrayList<String[]>();
            foodData.add(foodArray);
            foodChoice.addItem(foodArray[0]);
        }

        void addFoodToTable() {

            String[] s = new String[3];
            s = (String[]) foodData.get(foodChoice.getSelectedIndex());
            System.out.println(foodData.get(0));
            System.out.println(foodData.get(1));
        }

addFoodToTable gets called with a button click. So the issue I'm having is that (based on the sysouts) I will get a pointer address to the first entry in the ArrayList, but then a Null Pointer Exception stating that it is out of bounds for Length 0 when it tries to print the second one to console. This is obviously after calling createFood() 3 or four times in order to populate foodData. I can provide additional code if required, it's just too much to place in whole into this post. Thanks!

Body:
you clear out foodData every time you call createFood  remove this line:

foodData = new ArrayList();

and move the initialization to a static level , like this:

static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]>  foodData = new ArrayList<String[]>();
JTextField newFoodText, portionText, carbsText;

public Main() {
  void createFood() {

    String[] foodProperties = new String[3];
    foodProperties[0] = newFoodText.getText();
    foodProperties[1] = portionText.getText();
    foodProperties[2] = carbsText.getText();
    Main.createFood(foodProperties);
  }

  static void createFood(String[] foodArray) {
    foodData.add(foodArray);
    foodChoice.addItem(foodArray[0]);
  }

  void addFoodToTable() {

    String[] s = new String[3];
    s = (String[]) foodData.get(foodChoice.getSelectedIndex());
    System.out.println(foodData.get(0));
    System.out.println(foodData.get(1));
  }


问:
How to print every third character of a string? java
I am trying to print every 3rd character of a string so an example would be:
  123456 returns 36

But my code below returns 14

public String getEveryThird() {
    String newString = "";

    for (int i = 0; i < string.length(); i++) {

        if (i % 3 == 0) {
            newString += (string.charAt(i));
        }
    }

    return newString;
}
```

答:
It is returning 14 because your loop starts in 0 and 0 % 0 is equal to 0.
Then, when it gets to number 4, the index i is equal to 3, and again 3 % 3 = 0.

Try something like:

```<code>if((i+1) % 3 == 0){
    newString += (string.charAt(i));
}
</code>```

Body:
It is returning 14 because your loop starts in 0 and 0 % 0 is equal to 0.
Then, when it gets to number 4, the index i is equal to 3, and again 3 % 3 = 0.

Try something like:

if((i+1) % 3 == 0){
    newString += (string.charAt(i));
}


问:
Accessing and showing modal located in another component
I have a PersonList component, wherever user clicks on List.Item I want to pass some details like personId to PersonModal and display it. I'm using Ant Design component for modal.

Below is what I tried, but unfortunately I'm getting an error like:

Warning: Can't call setState on a component that is not yet mounted.
  This is a no-op, but it might indicate a bug in your application.
  Instead, assign to this.state directly or define a state = {};
  class property with the desired state in the PersonModal component.

PersonModal.js

```<code>import React from "react";
import {Modal} from "antd";

class PersonModal extends React.Component {
    constructor(props) {
        super(props);
        console.log(this.props.personId)
    }

    state = { visible: false };

    showModal = () => {
        this.setState({
            visible: true,
        });
    };

    // handleOk (...)
    // handleCancel (...)

    render() {
        return <Modal
            title="Basic Modal"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
        >
            Modal body
        </Modal>
    }
}
export default PersonModal;
</code>```

PersonList.js

```<code>import React from "react";
import {Icon, Input, List, Avatar} from "antd";
import PersonModal from "PersonModal/PersonModal"

class PersonList extends React.Component {

    showModal(personId) {
        const modal = new PersonModal({personId: 123})
        modal.showModal()
    }

    render() {
        const persons = this.props.list;
        return (
            <div>
            <List
                itemLayout="horizontal"
                dataSource={persons}
                renderItem={item => (
                    <>
                    <List.Item onClick={this.showModal(123)} style={{cursor: 'pointer'}}>
                        <List.Item.Meta
                            avatar={<Avatar src="avatar.png"/>}
                            title={<span>{item.firstName} {item.lastName}</span>}
                            description={<span>{item.city}, {item.country}</span>}
                        />
                    </List.Item>
                    </>
                )}
            />
            </div>
        );
    }
}
</code>```

What would be correct way of approaching this problem? Since I am new to React i suppose this is not a correct approach.

Reproduced issue on stackblitz here

答:
Your onClick handlers are being called continuously. Change them to functions that return the function you wish to call and this should fix your issue.

So,

Instead of: <List.Item onClick={{this.showModal(123)} style={{cursor: 'pointer'}}>

We do: <List.Item onClick={() => {this.showModal(123)} } style={{cursor: 'pointer'}}>

updated stackblitz here

Body:
I have a PersonList component, wherever user clicks on List.Item I want to pass some details like personId to PersonModal and display it. I'm using Ant Design component for modal.

Below is what I tried, but unfortunately I'm getting an error like:

Warning: Can't call setState on a component that is not yet mounted.
  This is a no-op, but it might indicate a bug in your application.
  Instead, assign to this.state directly or define a state = {};
  class property with the desired state in the PersonModal component.

PersonModal.js

import React from "react";
import {Modal} from "antd";

class PersonModal extends React.Component {
    constructor(props) {
        super(props);
        console.log(this.props.personId)
    }

    state = { visible: false };

    showModal = () => {
        this.setState({
            visible: true,
        });
    };

    // handleOk (...)
    // handleCancel (...)

    render() {
        return <Modal
            title="Basic Modal"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
        >
            Modal body
        </Modal>
    }
}
export default PersonModal;

PersonList.js

import React from "react";
import {Icon, Input, List, Avatar} from "antd";
import PersonModal from "PersonModal/PersonModal"

class PersonList extends React.Component {

    showModal(personId) {
        const modal = new PersonModal({personId: 123})
        modal.showModal()
    }

    render() {
        const persons = this.props.list;
        return (

            <List
                itemLayout="horizontal"
                dataSource={persons}
                renderItem={item => (
                    <>
                    <List.Item onClick={this.showModal(123)} style={{cursor: 'pointer'}}>
                        <List.Item.Meta
                            avatar={<Avatar src="avatar.png"/>}
                            title={{item.firstName} {item.lastName}}
                            description={{item.city}, {item.country}}
                        />
                    </List.Item>
                    </>
                )}
            />

        );
    }
}

What would be correct way of approaching this problem? Since I am new to React i suppose this is not a correct approach.

Reproduced issue on stackblitz here


问:
Not initialised and memory errors (strings and pointers)
Here is what I need to do: delete all occurrences of a number that appears most frequently in a given string

Here is what I've done: wrote two functions; the second one extracts all integers from a string into an array, finds the most frequently repeated one, calls the first function to find that number in a string, deletes all its occurrences in a given string

The problem is it works alright when I compile it, but doesn't pass the series of auto-generated tests and displays "access to an uninitialised value" and "memory error" in lines I marked with <------.

I know this is not exactly the "minimum reproducible code" but I'm hoping someone could point out what the problem is, as I run into a lot of similar errors when working with pointers.

```<code>char* find_number(char* string,int search)
{
    int sign=1;
    int number=0,temp=0;
    char* p = string;
while(*string != '\0') {<----------
        p=string;
        if(*string=='-') sign=-1;
        else if(*string==' ') {
            string++;
            continue;
        } else if(*string>='0' && *string<='9') {
            temp=0;

            while(*string != '\0' && *string>='0' && *string<='9') {
                temp=temp*10+*string-'0';
                string++;
            }

            number=temp*sign;
            if(number==search) {
                return p;
            }
        } else {
            sign=1,number=0;
        }
        string++;
    }
    return NULL;
}

char* delete_most_frequent(char* string)
{
    //writing all integers in a string to an array
    char* pointer=string;
    char* s = string;
    int temp=0, sign = 1,i=0,array[1000],number=0,counters[1001]= {0},n=0;
    while (*s != '\0') {<------------
        if (*s == '-') sign = -1;<----------
        else if (*s >= '0' && *s <='9') {<----------
            temp = 0;
            while (*s != '\0' && *s >= '0' && *s <= '9') {
                temp = temp * 10 + *s - '0';
                s++;
            }
            number=sign*temp;
            if(number>=0 && number<=1000) {
                array[i]=number;
                i++;
            }
        }
        number=0;
        sign=1;
        s++;
    }
    n=i;//size of the array
    //finding the number that occurs most frequently
    int max=0;
    for (i=0; i<n; i++) {
        counters[array[i]]++;
        if(counters[array[i]]>counters[max]) {
            max=array[i];
        }
    }

    char* p=find_number(string,max);//pointer to the first digit of wanted number
//deleting the integer
    while (*string != '\0') {
        if (p != NULL) {
            char *beginning = p, *end = p;
            while(*end>='0' && *end<='9')
                end++;
            //while (*beginning++ = *end++);
            while(*end != '\0'){
                *beginning = *end;
                beginning++;
                end++;
            }
            *beginning = '\0';
        } else string++;
        p=find_number(string,max);
    }
    return pointer;//pointer to the first character of a string
}

int main()
{
    char s[] = "abc 14 0, 389aaa 14! 15 1, 153";
    printf("'%s'", delete_most_frequent(s));
    return 0;
}
</code>```

答:
chopping your code down to just what is likely causing the problem, you have pattern that looks like

```<code>    while(*string != '\0') {
            :
        while(*string != '\0' ...) {
                :
            string++;
        }
            :
        string++;
    }
</code>```

so you have two nested while loops, both of which are advancing the pointer looking for a NUL terminator to end the loop.  The problem is that if the inner loop gets all the way to the NUL (it might stop earlier, but it might not), then the increment in the outer loop will increment the pointer past the NUL.  It will then happily run through (probably invalid) memory looking for another NUL that might not exist.  This is a hard one to catch as in most test cases you write, there are likely multiple NULs (soon) after the string, so it will appear to work fine -- you almost have to specifically write a test case to trigger this failure mode to catch this.

One fix would be to check you're not yet at the null before incrementing -- if (*string) string++; instead of just string++;

Body:
Here is what I need to do: delete all occurrences of a number that appears most frequently in a given string

Here is what I've done: wrote two functions; the second one extracts all integers from a string into an array, finds the most frequently repeated one, calls the first function to find that number in a string, deletes all its occurrences in a given string

The problem is it works alright when I compile it, but doesn't pass the series of auto-generated tests and displays "access to an uninitialised value" and "memory error" in lines I marked with <------.

I know this is not exactly the "minimum reproducible code" but I'm hoping someone could point out what the problem is, as I run into a lot of similar errors when working with pointers.

char* find_number(char* string,int search)
{
    int sign=1;
    int number=0,temp=0;
    char* p = string;
while(*string != '\0') {<----------
        p=string;
        if(*string=='-') sign=-1;
        else if(*string==' ') {
            string++;
            continue;
        } else if(*string>='0' && *string<='9') {
            temp=0;

            while(*string != '\0' && *string>='0' && *string<='9') {
                temp=temp*10+*string-'0';
                string++;
            }

            number=temp*sign;
            if(number==search) {
                return p;
            }
        } else {
            sign=1,number=0;
        }
        string++;
    }
    return NULL;
}

char* delete_most_frequent(char* string)
{
    //writing all integers in a string to an array
    char* pointer=string;
    char* s = string;
    int temp=0, sign = 1,i=0,array[1000],number=0,counters[1001]= {0},n=0;
    while (*s != '\0') {<------------
        if (*s == '-') sign = -1;<----------
        else if (*s >= '0' && *s <='9') {<----------
            temp = 0;
            while (*s != '\0' && *s >= '0' && *s <= '9') {
                temp = temp * 10 + *s - '0';
                s++;
            }
            number=sign*temp;
            if(number>=0 && number<=1000) {
                array[i]=number;
                i++;
            }
        }
        number=0;
        sign=1;
        s++;
    }
    n=i;//size of the array
    //finding the number that occurs most frequently
    int max=0;
    for (i=0; i<n; i++) {
        counters[array[i]]++;
        if(counters[array[i]]>counters[max]) {
            max=array[i];
        }
    }

    char* p=find_number(string,max);//pointer to the first digit of wanted number
//deleting the integer
    while (*string != '\0') {
        if (p != NULL) {
            char *beginning = p, *end = p;
            while(*end>='0' && *end<='9')
                end++;
            //while (*beginning++ = *end++);
            while(*end != '\0'){
                *beginning = *end;
                beginning++;
                end++;
            }
            *beginning = '\0';
        } else string++;
        p=find_number(string,max);
    }
    return pointer;//pointer to the first character of a string
}

int main()
{
    char s[] = "abc 14 0, 389aaa 14! 15 1, 153";
    printf("'%s'", delete_most_frequent(s));
    return 0;
}

Body:
chopping your code down to just what is likely causing the problem, you have pattern that looks like

    while(*string != '\0') {
            :
        while(*string != '\0' ...) {
                :
            string++;
        }
            :
        string++;
    }

so you have two nested while loops, both of which are advancing the pointer looking for a NUL terminator to end the loop.  The problem is that if the inner loop gets all the way to the NUL (it might stop earlier, but it might not), then the increment in the outer loop will increment the pointer past the NUL.  It will then happily run through (probably invalid) memory looking for another NUL that might not exist.  This is a hard one to catch as in most test cases you write, there are likely multiple NULs (soon) after the string, so it will appear to work fine -- you almost have to specifically write a test case to trigger this failure mode to catch this.

One fix would be to check you're not yet at the null before incrementing -- if (*string) string++; instead of just string++;


问:
Creating a column with the difference between 02 datetimes - Pandas
I have a dataset with 02 datetime columns and I want to calculate what is the difference between both and create a new column with that difference:

```<code>Column 1               Column 2
2020-02-14 01:16:32     2020-02-14 08:38:59
2019-12-24 00:09:29     2019-12-24 02:51:38
2020-02-17 00:39:02     2020-02-17 02:17:25
</code>```

The idea is to have Column 2 - Column 1 and the difference set in hours.
I didnt find a way to do that they way I need and I tried to to just a basic calculation, one minus the other, but it didn`t work so I was hoping someone could help with this task

thanks

答:
Difference the two columns (after converting to datetime), then use the dt accessor method to get the total seconds difference of the timedelta.  Convert to hours by dividing by 3600 (60 seconds per minute, 60 minutes per hour). Assign the result back to the dataframe.

```<code>df = pd.DataFrame({
    "Column 1": ["2020-02-14 01:16:32", "2019-12-24 00:09:29", "2020-02-17 00:39:02"],
    "Column 2": ["2020-02-14 08:38:59", "2019-12-24 02:51:38", "2020-02-17 02:17:25"]}
)

time_delta = pd.to_datetime(df['Column 2']) - pd.to_datetime(df['Column 1'])
>>> df.assign(hours_difference=time_delta.dt.total_seconds().div(3600))
              Column 1             Column 2  hours_difference
0  2020-02-14 01:16:32  2020-02-14 08:38:59          7.374167
1  2019-12-24 00:09:29  2019-12-24 02:51:38          2.702500
2  2020-02-17 00:39:02  2020-02-17 02:17:25          1.639722
</code>```

Body:
I have a dataset with 02 datetime columns and I want to calculate what is the difference between both and create a new column with that difference:

Column 1               Column 2
2020-02-14 01:16:32     2020-02-14 08:38:59
2019-12-24 00:09:29     2019-12-24 02:51:38
2020-02-17 00:39:02     2020-02-17 02:17:25

The idea is to have Column 2 - Column 1 and the difference set in hours.
I didnt find a way to do that they way I need and I tried to to just a basic calculation, one minus the other, but it didn`t work so I was hoping someone could help with this task

thanks

Body:
Difference the two columns (after converting to datetime), then use the dt accessor method to get the total seconds difference of the timedelta.  Convert to hours by dividing by 3600 (60 seconds per minute, 60 minutes per hour). Assign the result back to the dataframe.

df = pd.DataFrame({
    "Column 1": ["2020-02-14 01:16:32", "2019-12-24 00:09:29", "2020-02-17 00:39:02"],
    "Column 2": ["2020-02-14 08:38:59", "2019-12-24 02:51:38", "2020-02-17 02:17:25"]}
)

time_delta = pd.to_datetime(df['Column 2']) - pd.to_datetime(df['Column 1'])
>>> df.assign(hours_difference=time_delta.dt.total_seconds().div(3600))
              Column 1             Column 2  hours_difference
0  2020-02-14 01:16:32  2020-02-14 08:38:59          7.374167
1  2019-12-24 00:09:29  2019-12-24 02:51:38          2.702500
2  2020-02-17 00:39:02  2020-02-17 02:17:25          1.639722


问:
react-virtualized table x-scrolling
Is it possible to set a x-scrolling in react-virtualized? I have a table with a fixed width, and more columns to display than I got space in my table, so I need a x-scrollinig. In my tests if i did it, the table just shrinked up and did just display '...''s for content if the table runs out of space. </p>

答:
Building on bvaughn's accepted answer, the hack for a horizontally scrollable table could look something like this, however, beware of the following caveats that come with this hack:

Your overflowing Table columns will not be virtualized

The scrolling focus gets captured by the wrapper's x-axis scrolling and you will need to click within the internal Table component to refocus and regain y-axis scrolling. This is incredibly frustrating to use especially on mobile devices.

ContentLicense: CC BY-SA 3.0

Title: react-virtualized table x-scrolling


问:
Reduce array of objects within ES6 function
I am a little confused about a reduce function I am working on. I intend to reduce an array of objects, which works just fine, if I declare a variable and set it equal to a reduce iteration:

movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

const averageRating = movies.reduce((sum, current) => {
    return (sum + parseFloat(current.rate)) / 3;
  }, 0);

 console.log(averageRating)```
</div>
</div>
</p>

<p>However, if I try to write this as ES6 function, it tells me that sum is not defined:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

ratesAverage = (array) => {
    array.reduce((sum, movies) => {
        return sum + parseFloat(movies.rate);
      }, 0)
}

console.log(ratesAverage(movies))</code>```

What am I missing here?

Thanks a lot in advance

答:
If you wrap your arrow function in curly brackets, a return statement is required.

Only if you omit the curly brackets, the value of the expression is returned implicitly.

movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
]

ratesAverage = (array) => {
    return array.reduce((sum, movies) => {
        return sum + parseFloat(movies.rate);
      }, 0)
}

console.log(ratesAverage(movies))```

Body:
I am a little confused about a reduce function I am working on. I intend to reduce an array of objects, which works just fine, if I declare a variable and set it equal to a reduce iteration:

movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

const averageRating = movies.reduce((sum, current) => {
    return (sum + parseFloat(current.rate)) / 3;
  }, 0);

 console.log(averageRating)

However, if I try to write this as ES6 function, it tells me that sum is not defined:

movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

ratesAverage = (array) => {
    array.reduce((sum, movies) => {
        return sum + parseFloat(movies.rate);
      }, 0)
}

console.log(ratesAverage(movies))

What am I missing here?

Thanks a lot in advance


问:
Renaming Sub Column names and then creating a data frame using renamed column in R
I am having a tricky dataset3922327258060dat.txt for which I have to create a function to read three columns. This dataset is having multiple columns, out of those columns I need to change name of 3 columns (Date, HrMn, Slp) to (Date, Time, AtmosPressure) and then make a data frame of these 3 columns. BUT the tricky thing is the columns has sub heading as those names(Date, HrMn, Slp) as when I am trying to write
colnames(noaaFilename)
 it is giving me this result
"Identification" "SLP"            "X3"
I am trying to do this, but unable to get result with sub column names and values.

Please help me to create a data frame with three main columns with name "Date", "Time", "AtmosPressure"

```<code>noaaFilename <- read_table2("3922327258060dat.txt")

readNOAAData <- function(filename=noaaFilename) {

  colnames(noaaFilename)
  noaaFilename <- read_table2("3922327258060dat.txt")

  names(noaaFilename)[names(noaaFilename) == "Date"] <- "Date"
  names(noaaFilename)[names(noaaFilename) == "HrMn"] <- "Time"
  names(noaaFilename)[names(noaaFilename) == "Slp"] <- "AtmosPressure"

  noaaFiledf <- data.frame(Date, Time, AtmosPressure)

  noaaData <- subset(noaaFilename, Name == "ATLANTIC CITY", select = c("Date", "Time", "AtmosPressure"))

  ## Stop editing here
  return(noaaData)
}
</code>```

Sorry as this comes too long

```<code>dput(head(noaaFilename, 20))
</code>```

```<code>structure(list(Identification = c("Name", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC"),
    SLP = c("USAF", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY",
    "CITY", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY",
    "CITY", "CITY", "CITY", "CITY", "CITY"), X3 = c("NCDC", ",997270,99999,20121029,0000,4,FM-18,",
    ",997270,99999,20121029,0100,4,FM-18,", ",997270,99999,20121029,0200,4,FM-18,",
    ",997270,99999,20121029,0300,4,FM-18,", ",997270,99999,20121029,0400,4,FM-18,",
    ",997270,99999,20121029,0500,4,FM-18,", ",997270,99999,20121029,0600,4,FM-18,",
    ",997270,99999,20121029,0700,4,FM-18,", ",997270,99999,20121029,0800,4,FM-18,",
    ",997270,99999,20121029,0900,4,FM-18,", ",997270,99999,20121029,1000,4,FM-18,",
    ",997270,99999,20121029,1100,4,FM-18,", ",997270,99999,20121029,1200,4,FM-18,",
    ",997270,99999,20121029,1300,4,FM-18,", ",997270,99999,20121029,1400,4,FM-18,",
    ",997270,99999,20121029,1500,4,FM-18,", ",997270,99999,20121029,1600,4,FM-18,",
    ",997270,99999,20121029,1700,4,FM-18,", ",997270,99999,20121029,1800,4,FM-18,"
    )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-20L), problems = structure(list(row = 1:94, col = c(NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_), expected = c("3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns"), actual = c("11 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "4 columns",
"4 columns", "4 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns"), file = c("'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'"
)), row.names = c(NA, -94L), class = c("tbl_df", "tbl", "data.frame"
)))
</code>```

答:
Here we have a single line that should be skipped followed by a header that has no commas and then a body of data that is comma separated. Here is an alternate approach that uses the scan function to pull in the column names that are separated by whitespace. (It did require adding an additional value to the 'col.names' to account for the trailing commas in each of the data lines.):

```<code>input <- read.table( "~/CSV3.txt", sep=",", skip=2,
                      col.names=scan("~/CSV3.txt", what="", sep="", skip=1,n=11))
Read 11 items
#-------------------
input
                        Name   USAF  NCDC     Date HrMn I  Type QCP   sip Q ATLANTIC
1 ATLANTIC CITY              997270 99999 20121029    0 4 FM-18  NA 999.9 1       NA
2 ATLANTIC CITY              997270 99999 20121029  200 4 FM-18  NA 999.2 1       NA
3 ATLANTIC CITY              997270 99999 20121029  300 4 FM-18  NA 998.3 1       NA
</code>```

The default header argument for read.table is FALSE. The scan function requires a "what" argument to specify the column type. It can be given either as one of the defined types or as in this case by example, since "" is a character value.

To allow the subsetting to proceed correctly the trailing spaces from the inluyt process of column 1 needs to be corrected. First notice the failure of the process at this point:

```<code>names(input)[c(5,9)] <- c("Time","AtmosPressure") # no need to fix "Date"

noaaData <- subset(input, Name == "ATLANTIC CITY", select = c("Date", "Time", "AtmosPressure"))
noaaData
#----------
[1] Date          Time          AtmosPressure
<0 rows> (or 0-length row.names)
</code>```

The problem needs to be addressed by removing the trailing spaces from the first column using the trimws function (which takes care of both leading and trailing spaces or tabs):

```<code>input[[1]] <- trimws(input[[1]])
noaaData <- subset(input, Name == "ATLANTIC CITY", select = c("Date", "Time", "AtmosPressure"))
noaaData
#-----------------
      Date Time AtmosPressure
1 20121029    0         999.9
2 20121029  200         999.2
3 20121029  300         998.3
</code>```

Success at last.

```<code>Sample text file
------------------
Identification                                                       SLP
Name                       USAF    NCDC Date     HrMn I Type QCP   sip Q
ATLANTIC CITY             ,997270,99999,20121029,0000,4,FM-18, , 999.9,1,
ATLANTIC CITY             ,997270,99999,20121029,0200,4,FM-18, , 999.2,1,
ATLANTIC CITY             ,997270,99999,20121029,0300,4,FM-18, , 998.3,1,
</code>```

Body:
I am having a tricky dataset3922327258060dat.txt for which I have to create a function to read three columns. This dataset is having multiple columns, out of those columns I need to change name of 3 columns (Date, HrMn, Slp) to (Date, Time, AtmosPressure) and then make a data frame of these 3 columns. BUT the tricky thing is the columns has sub heading as those names(Date, HrMn, Slp) as when I am trying to write
colnames(noaaFilename)
 it is giving me this result
"Identification" "SLP"            "X3"
I am trying to do this, but unable to get result with sub column names and values.

Please help me to create a data frame with three main columns with name "Date", "Time", "AtmosPressure"

noaaFilename <- read_table2("3922327258060dat.txt")

readNOAAData <- function(filename=noaaFilename) {

  colnames(noaaFilename)
  noaaFilename <- read_table2("3922327258060dat.txt")

  names(noaaFilename)[names(noaaFilename) == "Date"] <- "Date"
  names(noaaFilename)[names(noaaFilename) == "HrMn"] <- "Time"
  names(noaaFilename)[names(noaaFilename) == "Slp"] <- "AtmosPressure"

  noaaFiledf <- data.frame(Date, Time, AtmosPressure)

  noaaData <- subset(noaaFilename, Name == "ATLANTIC CITY", select = c("Date", "Time", "AtmosPressure"))

  ## Stop editing here
  return(noaaData)
}

Sorry as this comes too long

dput(head(noaaFilename, 20))

structure(list(Identification = c("Name", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC",
"ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC", "ATLANTIC"),
    SLP = c("USAF", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY",
    "CITY", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY", "CITY",
    "CITY", "CITY", "CITY", "CITY", "CITY"), X3 = c("NCDC", ",997270,99999,20121029,0000,4,FM-18,",
    ",997270,99999,20121029,0100,4,FM-18,", ",997270,99999,20121029,0200,4,FM-18,",
    ",997270,99999,20121029,0300,4,FM-18,", ",997270,99999,20121029,0400,4,FM-18,",
    ",997270,99999,20121029,0500,4,FM-18,", ",997270,99999,20121029,0600,4,FM-18,",
    ",997270,99999,20121029,0700,4,FM-18,", ",997270,99999,20121029,0800,4,FM-18,",
    ",997270,99999,20121029,0900,4,FM-18,", ",997270,99999,20121029,1000,4,FM-18,",
    ",997270,99999,20121029,1100,4,FM-18,", ",997270,99999,20121029,1200,4,FM-18,",
    ",997270,99999,20121029,1300,4,FM-18,", ",997270,99999,20121029,1400,4,FM-18,",
    ",997270,99999,20121029,1500,4,FM-18,", ",997270,99999,20121029,1600,4,FM-18,",
    ",997270,99999,20121029,1700,4,FM-18,", ",997270,99999,20121029,1800,4,FM-18,"
    )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-20L), problems = structure(list(row = 1:94, col = c(NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_, NA_character_), expected = c("3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns", "3 columns", "3 columns",
"3 columns", "3 columns", "3 columns"), actual = c("11 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "5 columns", "5 columns", "5 columns", "4 columns",
"4 columns", "4 columns", "5 columns", "5 columns", "5 columns",
"5 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns", "4 columns", "4 columns",
"4 columns", "4 columns", "4 columns"), file = c("'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'",
"'3922327258060dat.txt'", "'3922327258060dat.txt'", "'3922327258060dat.txt'"
)), row.names = c(NA, -94L), class = c("tbl_df", "tbl", "data.frame"
)))

Body:
Here we have a single line that should be skipped followed by a header that has no commas and then a body of data that is comma separated. Here is an alternate approach that uses the scan function to pull in the column names that are separated by whitespace. (It did require adding an additional value to the 'col.names' to account for the trailing commas in each of the data lines.):

input <- read.table( "~/CSV3.txt", sep=",", skip=2,
                      col.names=scan("~/CSV3.txt", what="", sep="", skip=1,n=11))
Read 11 items
#-------------------
input
                        Name   USAF  NCDC     Date HrMn I  Type QCP   sip Q ATLANTIC
1 ATLANTIC CITY              997270 99999 20121029    0 4 FM-18  NA 999.9 1       NA
2 ATLANTIC CITY              997270 99999 20121029  200 4 FM-18  NA 999.2 1       NA
3 ATLANTIC CITY              997270 99999 20121029  300 4 FM-18  NA 998.3 1       NA

The default header argument for read.table is FALSE. The scan function requires a "what" argument to specify the column type. It can be given either as one of the defined types or as in this case by example, since "" is a character value.

To allow the subsetting to proceed correctly the trailing spaces from the inluyt process of column 1 needs to be corrected. First notice the failure of the process at this point:

names(input)[c(5,9)] <- c("Time","AtmosPressure") # no need to fix "Date"

noaaData <- subset(input, Name == "ATLANTIC CITY", select = c("Date", "Time", "AtmosPressure"))
noaaData
#----------
[1] Date          Time          AtmosPressure
<0 rows> (or 0-length row.names)

The problem needs to be addressed by removing the trailing spaces from the first column using the trimws function (which takes care of both leading and trailing spaces or tabs):

input[[1]] <- trimws(input[[1]])
noaaData <- subset(input, Name == "ATLANTIC CITY", select = c("Date", "Time", "AtmosPressure"))
noaaData
#-----------------
      Date Time AtmosPressure
1 20121029    0         999.9
2 20121029  200         999.2
3 20121029  300         998.3

Success at last.

Sample text file
------------------
Identification                                                       SLP
Name                       USAF    NCDC Date     HrMn I Type QCP   sip Q
ATLANTIC CITY             ,997270,99999,20121029,0000,4,FM-18, , 999.9,1,
ATLANTIC CITY             ,997270,99999,20121029,0200,4,FM-18, , 999.2,1,
ATLANTIC CITY             ,997270,99999,20121029,0300,4,FM-18, , 998.3,1,


问:
How to add reactions to messages sent by a webhook?
I want to add reactions to a messages sent by a webhook but idk how can I make this, here is my code:</p>

```<code>    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url', adapter=AsyncWebhookAdapter(session))
        embed = discord.Embed(color=color)
        caractère = ["(", "'", ")", ","]
        for caractère in caractère:
            args = str(args).replace(caractère, "")
        embed.add_field(name="Nouvelle suggestion !", value=str(args).strip(""))
        embed.set_footer(text=f"""{ctx.message.author} • {datetime.now().strftime("%d %b %Y %H:%M:%S")}""",
                         icon_url=str(ctx.message.author.avatar_url))
        message = await webhook.send(embed=embed, username=ctx.author.name, avatar_url=ctx.author.avatar_url)```
</code>```

答:
This is how i do it, After sending the Embed i do </p>

```<code>reactions = "\U0001f44d"
reactions2 = "\U0001f44e"
await application.add_reaction(reactions)
await application.add_reaction(reactions2)
</code>```

<p>application is the name of my embed, you will need to change it to whatever you name yours.
You could also import emoji and just do :thumbup: or whatever reactions you're after. </p>

Body:
I want to add reactions to a messages sent by a webhook but idk how can I make this, here is my code:

    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url', adapter=AsyncWebhookAdapter(session))
        embed = discord.Embed(color=color)
        caractère = ["(", "'", ")", ","]
        for caractère in caractère:
            args = str(args).replace(caractère, "")
        embed.add_field(name="Nouvelle suggestion !", value=str(args).strip(""))
        embed.set_footer(text=f"""{ctx.message.author} • {datetime.now().strftime("%d %b %Y %H:%M:%S")}""",
                         icon_url=str(ctx.message.author.avatar_url))
        message = await webhook.send(embed=embed, username=ctx.author.name, avatar_url=ctx.author.avatar_url)```

Body:
This is how i do it, After sending the Embed i do

reactions = "\U0001f44d"
reactions2 = "\U0001f44e"
await application.add_reaction(reactions)
await application.add_reaction(reactions2)

application is the name of my embed, you will need to change it to whatever you name yours.
You could also import emoji and just do :thumbup: or whatever reactions you're after.


问:
ajaxtoolkit modal popup Child window should return row value of gridview to the parent page
i'm new to ajax, i'm using ajaxtoolkit modalpopup here's the case

using an image button in a girdview on the parentpage modalpopup(child) is opened which has a girdview, i want to return the vale of the row of gridview from the childpage to the parent page textbox, modalpopup panel is on the same parent page .

Help me out...how to overcome this problem,

Thanks in Adv.

答:
why dont you use javascript

ScriptManager.RegisterStartupScript(Me, Me.GetType(), "Key", "window.open('popupnew.aspx?QueryString "', 'newwindow','toolbar=no,location=no,menubar=no,width=500,height=300,resizable=no,scrollbars=no,top=200,left=250')", False)

create a globel variable that you want to use in parent page in popup
after using variable clear it


问:
How to detect method overloading in subclasses in python?
I have a class that is a super-class to many other classes. I would like to know (in the __init__() of my super-class) if the subclass has overridden a specific method.

I tried to accomplish this with a class method, but the results were wrong:

```<code>class Super:
   def __init__(self):
      if self.method == Super.method:
         print 'same'
      else:
         print 'different'

   @classmethod
   def method(cls):
      pass

class Sub1(Super):
   def method(self):
      print 'hi'

class Sub2(Super):
   pass

Super() # should be same
Sub1() # should be different
Sub2() # should be same

>>> same
>>> different
>>> different
</code>```

Is there any way for a super-class to know if a sub-class has overridden a method?

答:
You can check to see if the function has been overridden by seeing if the function handle points to the Super class function or not. The function handler in the subclass object points either to the Super class function or to an overridden function in the Subclass.  For example:

```<code>class Test:
    def myfunc1(self):
        pass
    def myfunc2(self):
        pass

class TestSub(Test):
    def myfunc1(self):
        print('Hello World')

>>> test = TestSub()
>>> test.myfunc1.__func__ is Test.myfunc1
False
>>> test.myfunc2.__func__ is Test.myfunc2
True
</code>```

If the function handle does not point to the function in the Super class, then it has been overridden.

Body:
I have a class that is a super-class to many other classes. I would like to know (in the __init__() of my super-class) if the subclass has overridden a specific method.

I tried to accomplish this with a class method, but the results were wrong:

class Super:
   def __init__(self):
      if self.method == Super.method:
         print 'same'
      else:
         print 'different'

   @classmethod
   def method(cls):
      pass

class Sub1(Super):
   def method(self):
      print 'hi'

class Sub2(Super):
   pass

Super() # should be same
Sub1() # should be different
Sub2() # should be same

>>> same
>>> different
>>> different

Is there any way for a super-class to know if a sub-class has overridden a method?

Body:
You can check to see if the function has been overridden by seeing if the function handle points to the Super class function or not. The function handler in the subclass object points either to the Super class function or to an overridden function in the Subclass.  For example:

class Test:
    def myfunc1(self):
        pass
    def myfunc2(self):
        pass

class TestSub(Test):
    def myfunc1(self):
        print('Hello World')

>>> test = TestSub()
>>> test.myfunc1.__func__ is Test.myfunc1
False
>>> test.myfunc2.__func__ is Test.myfunc2
True

If the function handle does not point to the function in the Super class, then it has been overridden.


问:
ASM Get cart is making two HTTP request without passing authentication header
I created a Spartacus project with authentication configure using 'asm'. I used asmAuth.authorizeCustomerSupportAgent() to log in, and used OCC API:

```<code>GET /{baseSiteId}/users/{userId}/carts/{cartId}
</code>```

to get a cart with a given a user and a cart id.

However, when I make the GET request, I found out in my Network that I am actually making 2 requests. One is with the URL that I gave, the other is

```<code>/{baseSiteId}/users/{userId}/carts/{cartId}?fields=DEFAULT,potentialProductPromotions,appliedProductPromotions,potentialOrderPromotions,appliedOrderPromotions,entries(totalPrice(formattedValue),product(images(FULL),stock(FULL)),basePrice(formattedValue),updateable),totalPrice(formattedValue),totalItems,totalPriceWithTax(formattedValue),totalDiscounts(value,formattedValue),subTotal(formattedValue),deliveryItemsQuantity,deliveryCost(formattedValue),totalTax(formattedValue),pickupItemsQuantity,net,appliedVouchers,productDiscounts(formattedValue),user'
</code>```

The first request returned the cart successfully. The second request returns 401 Full Authentication is required error. Apparently, the authentication header was not passed into this second request.

I am wondering why is there 2 request, and if this is cause of the defaultOccCartConfig that came with Spartacus. If it is, how can I either disable it or pass in the authentication header?

Thank you!

答:
I’m not sure I fully understand your use case since it seems like you are not using the out of the box ASM implementation and perhaps also involves some custom code you are developing.

I doubt this behaviour is related to defaultOccCartConfig: this const contains the configuration for the urls of the endpoints, but no configuration that influences the number of calls.

I can give you an overview of some ASM logic that may be relevant to your case and may help you troubleshoot.

Yes, to begin, the customer support agent needs to sign in with AsmAuthService.authorizeCustomerSupportAgent()

In order to perform occ requests on the behalf of a customer, you need to start a customer emulation session via AsmAuthService.startCustomerEmulationSession(). You need to provide the agent’s token and customer id for that.  See:

```<code>AsmAuthService.startCustomerEmulationSession()
</code>```

https://github.com/SAP/cloud-commerce-spartacus-storefront/blob/release/1.4.x/projects/core/src/asm/facade/asm-auth.service.ts#L42

Once the customer emulation session is started, the UserTokenInterceptor should assign an authentication header to all outgoing occ requests, just like it does for regular customer sessions:

```<code>UserTokenInterceptor
</code>```

https://github.com/SAP/cloud-commerce-spartacus-storefront/blob/release/1.4.x/projects/core/src/auth/http-interceptors/user-token.interceptor.ts#L20-L42

Body:
I created a Spartacus project with authentication configure using 'asm'. I used asmAuth.authorizeCustomerSupportAgent() to log in, and used OCC API:

GET /{baseSiteId}/users/{userId}/carts/{cartId}

to get a cart with a given a user and a cart id.

However, when I make the GET request, I found out in my Network that I am actually making 2 requests. One is with the URL that I gave, the other is

/{baseSiteId}/users/{userId}/carts/{cartId}?fields=DEFAULT,potentialProductPromotions,appliedProductPromotions,potentialOrderPromotions,appliedOrderPromotions,entries(totalPrice(formattedValue),product(images(FULL),stock(FULL)),basePrice(formattedValue),updateable),totalPrice(formattedValue),totalItems,totalPriceWithTax(formattedValue),totalDiscounts(value,formattedValue),subTotal(formattedValue),deliveryItemsQuantity,deliveryCost(formattedValue),totalTax(formattedValue),pickupItemsQuantity,net,appliedVouchers,productDiscounts(formattedValue),user'

The first request returned the cart successfully. The second request returns 401 Full Authentication is required error. Apparently, the authentication header was not passed into this second request.

I am wondering why is there 2 request, and if this is cause of the defaultOccCartConfig that came with Spartacus. If it is, how can I either disable it or pass in the authentication header?

Thank you!

Body:
I’m not sure I fully understand your use case since it seems like you are not using the out of the box ASM implementation and perhaps also involves some custom code you are developing.

I doubt this behaviour is related to defaultOccCartConfig: this const contains the configuration for the urls of the endpoints, but no configuration that influences the number of calls.

I can give you an overview of some ASM logic that may be relevant to your case and may help you troubleshoot.

Yes, to begin, the customer support agent needs to sign in with AsmAuthService.authorizeCustomerSupportAgent()

In order to perform occ requests on the behalf of a customer, you need to start a customer emulation session via AsmAuthService.startCustomerEmulationSession(). You need to provide the agent’s token and customer id for that.  See:

AsmAuthService.startCustomerEmulationSession()

https://github.com/SAP/cloud-commerce-spartacus-storefront/blob/release/1.4.x/projects/core/src/asm/facade/asm-auth.service.ts#L42

Once the customer emulation session is started, the UserTokenInterceptor should assign an authentication header to all outgoing occ requests, just like it does for regular customer sessions:

UserTokenInterceptor

https://github.com/SAP/cloud-commerce-spartacus-storefront/blob/release/1.4.x/projects/core/src/auth/http-interceptors/user-token.interceptor.ts#L20-L42


问:
why @UniqueConstraint doesn't work in hibernate?
I added unique constraint annotation but still I can insert duplicate entry.</p>

```<code>@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"firstName", "LastName"})})
public class Student {
    @Id
    @GeneratedValue(strategy =  GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String LastName;
    //getter and setter and no-arg constructor
</code>```

```<code> Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Student student1 = new Student("alireza", "rayani");
        Student student2 = new Student("alireza", "rayani");
        session.save(student1);
        session.save(student2);
        session.getTransaction().commit();
</code>```

答: The schema for your database is generated by Hibernate? @UniqueConstraint is only used to generate the schema. If the database already exists, you should execute the alter table on it to add the constraint.

Body:
I added unique constraint annotation but still I can insert duplicate entry.

@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"firstName", "LastName"})})
public class Student {
    @Id
    @GeneratedValue(strategy =  GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String LastName;
    //getter and setter and no-arg constructor

 Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Student student1 = new Student("alireza", "rayani");
        Student student2 = new Student("alireza", "rayani");
        session.save(student1);
        session.save(student2);
        session.getTransaction().commit();


问:
How to angular route for sub modules?
I have a dashboard module in my angular application. And my app.module.ts is like following.

```<code>@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    DashboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

And app-routing.module.ts is

```<code>const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

And dashboard.route.ts is

```<code>const dashboardRoutes: Routes = [
    { path: 'dashboard', component: DashboardComponent }
]

@NgModule({
    imports: [RouterModule.forChild(dashboardRoutes)],
    exports: [RouterModule]
})
export class DashboardRouteModuel {}
</code>```

But the applciaiton is routing to PageNotFoundComponent always.

答:
You need to import the module routing on lazy loading. You can change:

```<code>{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
</code>```

by

```<code>{
    path: '',
    loadChildren:
        '../../dashboard.module#DashboardModule'
}
</code>```

Docs:
Lazy loading

Title: How to angular route for sub modules?

Body:
I have a dashboard module in my angular application. And my app.module.ts is like following.

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    DashboardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And app-routing.module.ts is

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

And dashboard.route.ts is

const dashboardRoutes: Routes = [
    { path: 'dashboard', component: DashboardComponent }
]

@NgModule({
    imports: [RouterModule.forChild(dashboardRoutes)],
    exports: [RouterModule]
})
export class DashboardRouteModuel {}

But the applciaiton is routing to PageNotFoundComponent always.

Body:
You need to import the module routing on lazy loading. You can change:

{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }

by

{
    path: '',
    loadChildren:
        '../../dashboard.module#DashboardModule'
}

Docs:
Lazy loading


问:
fix The ConnectionString property has not been initialized
When I start my application, I get this error:

The ConnectionString property has not been initialized.

I am getting this exception while trying to connect to my SQL Server database.

Register.aspx.cs

```<code>protected void btnRegister_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = string.Format("insert into member
values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
            txtFullName.Text, rblGender.SelectedValue, ddlCountry.SelectedValue,
            txtPhone.Text, txtEmail.Text, txtUsername.Text, txtPassword.Text);

    try
    {
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();

        tblRegister.Visible = false;
        Response.Write("Your account is created.");
    }
    catch(SqlException ex)
    {
        if (ex.Number == 2627)
            lblMsg.Text = "Please Change The Username.";
        else
            lblMsg.Text = "An Error : " + ex.Message;
    }
}
</code>```

```<code><configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.6.1"/>
        <httpRuntime targetFramework="4.6.1"/>
    </system.web>
    <system.codedom>
        <compilers>
            <compiler language="c#;cs;csharp" extension=".cs"
                      type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider,
Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                      warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
            <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
                      type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider,
Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                      warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
        </compilers>
    </system.codedom>
    <appSettings>
        <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>
    <connectionStrings>
        <add name="MyDB"
             connectionString="Data Source=.\sqlexpress;Initial Catalog=Company;Integrated Security=True"
             providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>
</code>```

答:
You need to do it like this:

```<code>SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=MSSQL1;Initial Catalog=AdventureWorks;Integrated Security=true;"";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
</code>```

With ConnectionString you specify which server to connect to and with what credentials, if not it won't know where you want to connect to and with what.
The example I gave is for SQL server and integrated security, depending on you database, server and your credentials you need to find the connection string you need

Body:
When I start my application, I get this error:

The ConnectionString property has not been initialized.

I am getting this exception while trying to connect to my SQL Server database.

Register.aspx.cs

protected void btnRegister_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = string.Format("insert into member
values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
            txtFullName.Text, rblGender.SelectedValue, ddlCountry.SelectedValue,
            txtPhone.Text, txtEmail.Text, txtUsername.Text, txtPassword.Text);

    try
    {
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();

        tblRegister.Visible = false;
        Response.Write("Your account is created.");
    }
    catch(SqlException ex)
    {
        if (ex.Number == 2627)
            lblMsg.Text = "Please Change The Username.";
        else
            lblMsg.Text = "An Error : " + ex.Message;
    }
}

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.6.1"/>
        <httpRuntime targetFramework="4.6.1"/>
    </system.web>
    <system.codedom>
        <compilers>
            <compiler language="c#;cs;csharp" extension=".cs"
                      type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider,
Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                      warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
            <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
                      type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider,
Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                      warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
        </compilers>
    </system.codedom>
    <appSettings>
        <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>
    <connectionStrings>
        <add name="MyDB"
             connectionString="Data Source=.\sqlexpress;Initial Catalog=Company;Integrated Security=True"
             providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

Body:
You need to do it like this:

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=MSSQL1;Initial Catalog=AdventureWorks;Integrated Security=true;"";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;

With ConnectionString you specify which server to connect to and with what credentials, if not it won't know where you want to connect to and with what.
The example I gave is for SQL server and integrated security, depending on you database, server and your credentials you need to find the connection string you need


问:
Order Boxplots by their Means
How do you go about changing the order or boxplots so that they are ordered greatest to least by their means.

This is my attempt of reordering the boxplots by their means:

```<code>url <- "http://www.cse.lehigh.edu/~brian/course/2020/datascience/student-teacher-ratios.csv"
df_ratios <- read.csv(url, header=T)
s2 <- with(df_ratios, reorder(region, -student_ratio, mean))
with(df_ratios, boxplot(student_ratio~s2))
</code>```

答:
Your problem is that your data has missing values. So the mean for all columns is NA. In order to ignore the missing values when calculating mean, you can doo

```<code>df_ratios <- read.csv(url, header=T)
s2 <- with(df_ratios, reorder(region, -student_ratio, mean, na.rm=TRUE))
with(df_ratios, boxplot(student_ratio~s2))
</code>```

Title: Order Boxplots by their Means

Body:
How do you go about changing the order or boxplots so that they are ordered greatest to least by their means.

This is my attempt of reordering the boxplots by their means:

url <- "http://www.cse.lehigh.edu/~brian/course/2020/datascience/student-teacher-ratios.csv"
df_ratios <- read.csv(url, header=T)
s2 <- with(df_ratios, reorder(region, -student_ratio, mean))
with(df_ratios, boxplot(student_ratio~s2))

Body:
Your problem is that your data has missing values. So the mean for all columns is NA. In order to ignore the missing values when calculating mean, you can doo

df_ratios <- read.csv(url, header=T)
s2 <- with(df_ratios, reorder(region, -student_ratio, mean, na.rm=TRUE))
with(df_ratios, boxplot(student_ratio~s2))


问:
Passing props along from styled component using Emotion.sh
I have the following styled button declared using @emotion\styled:

const Button = styled.button`
 background: blue;
 ${size({
  width: props => props.width
 )}
`
```

<p>In my code, <code>size</code> is a function that returns size css serialized style based on the prop that is passed:</p>

<pre class="lang-js prettyprint-override"><code>
const size = ({ width: "m"} = {}) => {
 switch(width) {
  case "s":
   return css`width: 100px`;
  break;
  case "m":
   return css`width: 150px`;
  break;
 }
}
</code>```

```<code><Button width="s">Some text</Button>
</code>```

However, the width value that I receive in the size function is not the resolved value from the passed prop i.e. s, but rather it is a string props => props.width.

Is there any way to pass the props along into a function from a styled component similar to what I am trying to achieve?

答:
It doesn't work since you're passing an anonymous function to width, in a place where you're not expecting a function.

I'm pretty sure this is what you're trying to do:

```<code>const Button = styled.button`
 background: blue;
 ${props => size({ width: props.width })}
`
</code>```

This way, you're passing an anonymous function in the scope of the styled declaration, getting the props from Emotion and free to use it however you like.

Body:
I have the following styled button declared using @emotion\styled:

const Button = styled.button`
 background: blue;
 ${size({
  width: props => props.width
 )}
`

In my code, size is a function that returns size css serialized style based on the prop that is passed:

const size = ({ width: "m"} = {}) => {
 switch(width) {
  case "s":
   return css`width: 100px`;
  break;
  case "m":
   return css`width: 150px`;
  break;
 }
}

<Button width="s">Some text</Button>

However, the width value that I receive in the size function is not the resolved value from the passed prop i.e. s, but rather it is a string props => props.width.

Is there any way to pass the props along into a function from a styled component similar to what I am trying to achieve?

Body:
It doesn't work since you're passing an anonymous function to width, in a place where you're not expecting a function.

I'm pretty sure this is what you're trying to do:

const Button = styled.button`
 background: blue;
 ${props => size({ width: props.width })}
`

This way, you're passing an anonymous function in the scope of the styled declaration, getting the props from Emotion and free to use it however you like.


问:
Regex-based string replacement operation not working
I have a file exp.txt with below content

```<code> hi. what are you doing. are you fine?
</code>```

This is my code:

```<code>$a = "are you fine?"

for($i=0;$i -lt $ar.Length; $i++)
{
    (Get-Content "exp.txt") -replace $ar[$i], "$&~" | Set-Content "exp.txt"
}
</code>```

I want to append ~ at the end of whatever text i put in $ar variable. But the above code does not work if i type "are you fine?" in $ar variable. Symbols like "*" "$" "+" also dont work. i need help

答:
In order to treat a search expression passed to the regex-based -replace operator as a literal string, you must escape regex metacharacters such as ?, which you can do programmatically by calling [regex]::Escape() (in a literal regex string, you could manually escape indiv. chars. with \):

```<code>(Get-Content exp.txt) -replace [regex]::Escape($ar[$i]), '$&~'
</code>```

Note how I've used '...' (single-quoting) for the replacement operand, which is preferable so as to avoid confusion with the string expansion that PowerShell itself performs up front in "..." (double-quoted) strings. Similarly, '...' is preferable for a literal search regex.

Sticking with the regex-based -replace operator in your case makes sense for two reasons:

You want to (directly and succinctly) refer to whatever was matched by the regex in the replacement expression, via placeholder $&.

You want to perform replacements on an array of input strings in a single operation (like many PowerShell operators, -replace supports an array of strings as its LHS, and then operates on each element).

By contrast, in cases where literal string substitutions with a single input string is needed, use of the [string] type's  .Replace() method is the simpler and faster option, but note that it is case-sensitive by default (unlike -replace).

See this answer for details.

Body:
I have a file exp.txt with below content

 hi. what are you doing. are you fine?

This is my code:

$a = "are you fine?"

for($i=0;$i -lt $ar.Length; $i++)
{
    (Get-Content "exp.txt") -replace $ar[$i], "$&~" | Set-Content "exp.txt"
}

I want to append ~ at the end of whatever text i put in $ar variable. But the above code does not work if i type "are you fine?" in $ar variable. Symbols like "*" "$" "+" also dont work. i need help

Body:
In order to treat a search expression passed to the regex-based -replace operator as a literal string, you must escape regex metacharacters such as ?, which you can do programmatically by calling [regex]::Escape() (in a literal regex string, you could manually escape indiv. chars. with \):

(Get-Content exp.txt) -replace [regex]::Escape($ar[$i]), '$&~'

Note how I've used '...' (single-quoting) for the replacement operand, which is preferable so as to avoid confusion with the string expansion that PowerShell itself performs up front in "..." (double-quoted) strings. Similarly, '...' is preferable for a literal search regex.

Sticking with the regex-based -replace operator in your case makes sense for two reasons:

You want to (directly and succinctly) refer to whatever was matched by the regex in the replacement expression, via placeholder $&.

You want to perform replacements on an array of input strings in a single operation (like many PowerShell operators, -replace supports an array of strings as its LHS, and then operates on each element).

By contrast, in cases where literal string substitutions with a single input string is needed, use of the [string] type's  .Replace() method is the simpler and faster option, but note that it is case-sensitive by default (unlike -replace).

See this answer for details.


Title: Creating a column with the difference between 02 datetimes - Pandas

Body:
I have a dataset with 02 datetime columns and I want to calculate what is the difference between both and create a new column with that difference:

Column 1               Column 2
2020-02-14 01:16:32     2020-02-14 08:38:59
2019-12-24 00:09:29     2019-12-24 02:51:38
2020-02-17 00:39:02     2020-02-17 02:17:25

The idea is to have Column 2 - Column 1 and the difference set in hours.
I didnt find a way to do that they way I need and I tried to to just a basic calculation, one minus the other, but it didn`t work so I was hoping someone could help with this task

thanks

Body:
using numpy and and timedelta64

# import numpy as np
df['diff'] = (df['Column 2'] - df['Column 1']) / np.timedelta64(1,'h') # h = hour.

print(df)

             Column 1            Column 2      diff
0 2020-02-14 01:16:32 2020-02-14 08:38:59  7.374167
1 2019-12-24 00:09:29 2019-12-24 02:51:38  2.702500
2 2020-02-17 00:39:02 2020-02-17 02:17:25  1.639722


问:
Australian Bureau of Statistics SDMX timeout issue
I'm trying to download Australian Bureau of Statistics data using pandasdmx.
I can download the ERP_COB using SDMX no problem but for ERP by SA2, age and sex I am getting a timeout error.
I have limited the time period to 2018 only but am still timing out.The weird thing is that it works sometimes but mostly not.
I would like to try limiting the parameters such as age or sex but not sure how to do this.
Any help would be much appreciated.

Thanks in advance.

```<code>from pandasdmx import Request

Agency_Code = 'ABS'
Dataset_Id = 'ABS_ERP_ASGS2016'
ABS = Request(Agency_Code)
data_response = ABS.data(resource_id='ABS_ERP_ASGS2016', params={'startTime': '2018','endTime': '2018'})
def timeout(self, value):
    self.client.config['timeout'] = 10000
ERP2018=data_response.write().unstack().reset_index()

ERP2018 = ERP2018[(ERP2018.REGIONTYPE =='AUS') | (ERP2018.REGIONTYPE =='STE')]

ERP2018.to_csv('c:\\Temp\\erp2018.csv')
</code>```

答:
If you turns on logging,

```<code> import logging

 from pandasdmx import Request
 Agency_Code = 'ABS'
 Dataset_Id = 'ABS_ERP_ASGS2016'
 ABS = Request(Agency_Code, log_level=logging.INFO)
</code>```

you can see the Request module is trying to download from http://stat.data.abs.gov.au/sdmx-json/data/ABS_ERP_ASGS2016. If you try this url in your browser, you will see you are not getting anything from ABS server.

I don't see any problem with your python code.

The odd thing is there is no data set for prior year (2015) or following years (2017, 2018). So this data set seems to be an odd one out.

It is likely a data issue. You can either contact the maintainers of pandasdmx or talk to ABS directly.

Body:
I'm trying to download Australian Bureau of Statistics data using pandasdmx.
I can download the ERP_COB using SDMX no problem but for ERP by SA2, age and sex I am getting a timeout error.
I have limited the time period to 2018 only but am still timing out.The weird thing is that it works sometimes but mostly not.
I would like to try limiting the parameters such as age or sex but not sure how to do this.
Any help would be much appreciated.

Thanks in advance.

from pandasdmx import Request

Agency_Code = 'ABS'
Dataset_Id = 'ABS_ERP_ASGS2016'
ABS = Request(Agency_Code)
data_response = ABS.data(resource_id='ABS_ERP_ASGS2016', params={'startTime': '2018','endTime': '2018'})
def timeout(self, value):
    self.client.config['timeout'] = 10000
ERP2018=data_response.write().unstack().reset_index()

ERP2018 = ERP2018[(ERP2018.REGIONTYPE =='AUS') | (ERP2018.REGIONTYPE =='STE')]

ERP2018.to_csv('c:\\Temp\\erp2018.csv')

Body:
If you turns on logging,

 import logging

 from pandasdmx import Request
 Agency_Code = 'ABS'
 Dataset_Id = 'ABS_ERP_ASGS2016'
 ABS = Request(Agency_Code, log_level=logging.INFO)

you can see the Request module is trying to download from http://stat.data.abs.gov.au/sdmx-json/data/ABS_ERP_ASGS2016. If you try this url in your browser, you will see you are not getting anything from ABS server.

I don't see any problem with your python code.

The odd thing is there is no data set for prior year (2015) or following years (2017, 2018). So this data set seems to be an odd one out.

It is likely a data issue. You can either contact the maintainers of pandasdmx or talk to ABS directly.


问:
How to avoid string repetition
I have two different string String A="example"; String B="example";
if concat both the string i am getting examplexample. Is there any possibility to avoid repetition of string with same name..??

答:
You can. Try something like this

```<code>private String concatStringExample1(String firstString, String secondString) {
            if(firstString.equalsIgnoreCase(secondString)) { // String matched
                 return firstString;  // or return secondString
            } else { // Not matched
                return firstString.concat(secondString);
            }
        }
</code>```

or

```<code>private String concatStringExample2(String firstString, String secondString) {
            if(firstString != null && firstString != null ) {
                if(firstString.toLowerCase().indexOf(secondString.toLowerCase()) >= 0)
                    return firstString;
                else if(secondString.toLowerCase().indexOf(firstString.toLowerCase()) >= 0)
                    return secondString;
                else
                    return firstString.concat(secondString);
            } else {
                return "";
            }
        }
</code>```

Title: How to avoid string repetition

Body:
You can. Try something like this

private String concatStringExample1(String firstString, String secondString) {
            if(firstString.equalsIgnoreCase(secondString)) { // String matched
                 return firstString;  // or return secondString
            } else { // Not matched
                return firstString.concat(secondString);
            }
        }

or

private String concatStringExample2(String firstString, String secondString) {
            if(firstString != null && firstString != null ) {
                if(firstString.toLowerCase().indexOf(secondString.toLowerCase()) >= 0)
                    return firstString;
                else if(secondString.toLowerCase().indexOf(firstString.toLowerCase()) >= 0)
                    return secondString;
                else
                    return firstString.concat(secondString);
            } else {
                return "";
            }
        }