问:
Navigate to root screen from nested stack navigator
i am new to react and trying to learn it by myself , i am facing problem in navigating user back to root screen from nested stck navigator screen .

Here is some of my classes :-

index.android.js :-

```<code>import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import {LoginStack} from './login/loginregisterrouter';
import {StackNavigator } from 'react-navigation';
class reactNavigationSample extends Component {
  render(){
    return (
   <LoginStack/>
    );
  }
}
AppRegistry.registerComponent('MssReactDemo', () => reactNavigationSample);
</code>```

loginregisterrouter :-

```<code>import React from 'react';
import {StackNavigator } from 'react-navigation';
import LoginScreen from './LoginScreen';
import RegisterScreen from './RegisterScreen';
import NavigationContainer from './navigationContainer';
export const LoginStack = StackNavigator({
  LoginScreen: {
    screen: LoginScreen,
    navigationOptions: {
      title: 'LoginScreen',
    }
  },
  RegisterScreen: {
    screen: RegisterScreen,
    navigationOptions: ({ navigation }) => ({
      title: 'RegisterScreen',
    }),
  },NavigationContainer: {
        screen: NavigationContainer,
        navigationOptions: ({ navigation }) => ({
          title: 'NavigationContainer', header: null,
        }),
      },
});
</code>```

Navigationcontainer.js :-

```<code>import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import {EasyRNRoute,} from '../parent';
import {StackNavigator } from 'react-navigation';
export default class NavigationContainer extends Component {
  render(){
    return (
   <EasyRNRoute/>
    );
  }
}
</code>```

parent.js :-

```<code>import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import App from './app';
import DrawerMenu from './Drawer/drawer-toolbar-android';
import BookmarkView from './Pages/bookmark';
import ClientView from './Pages/client';
import InfoView from './Pages/info';
import SettingsView from './Pages/setting';
import { DrawerNavigator, StackNavigator } from 'react-navigation';

export const stackNavigator = StackNavigator({
  Info: { screen: InfoView },
  Settings: {screen: SettingsView },
  Bookmark: {screen: BookmarkView },
  Connections: {screen: ClientView},
}, {
  headerMode: 'none'
});

export const EasyRNRoute = DrawerNavigator({
  Home: {
    screen: App,
  },
  Stack: {
    screen: stackNavigator
  }
}, {
  contentComponent: DrawerMenu,
  contentOptions: {
    activeTintColor: '#e91e63',
    style: {
      flex: 1,
      paddingTop: 15,
    }
  }
});
</code>```

Drawer-toolbar-android.js :-

```<code>import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    StatusBar,
    View
} from 'react-native';
import { NavigationActions } from 'react-navigation'
import { COLOR, ThemeProvider, Toolbar, Drawer, Avatar } from 'react-native-material-ui';
import Container from '../Container';
import LoginScreen from '../login/LoginScreen';

const uiTheme = {
    palette: {
        primaryColor: COLOR.green500,
        accentColor: COLOR.pink500,
      },
    toolbar: {
        container: {
            height: 70,
            paddingTop: 20,
          },
      },
      avatar: {
          container: {
              backgroundColor: '#333'
          }
      }
  };

export default class DrawerMenu extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
        active: 'people',
      };
  }
handleLogoutPress = () => {
//    AsyncStorage.setItem('SignedUpuser', '');
this.props
               .navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [
                      NavigationActions.navigate({ routeName: 'LoginScreen'})
                    ]
                  }));
//     this.props.navigation.dispatch(NavigationActions.back());
  };
  _setInfoActive() {
    this.setState({ active: 'info' });
  }

  render() {
    return (
        <ThemeProvider uiTheme={uiTheme}>
                <Container>
                    <StatusBar backgroundColor="rgba(0, 0, 0, 0.2)" translucent />
                    <Toolbar
                    leftElement="arrow-back"
                    onLeftElementPress={() => this.props.navigation.navigate('DrawerClose')}
                    centerElement="Menu"
                />
                    <View style={styles.container}>
                        <Drawer>
                            <Drawer.Header >
                                <Drawer.Header.Account
                                style={{
                                    container: { backgroundColor: '#fafafa' },
                                }}
                                avatar={<Avatar text={'S'} />}
//                                accounts={[
//                                    { avatar: <Avatar text="H" /> },
//                                    { avatar: <Avatar text="L" /> },
//                                ]}
                                footer={{
                                    dense: true,
                                    centerElement: {
                                        primaryText: 'Siddharth',
                                        secondaryText: 'I am DONE now',
                                    },

                                  }}
                            />
                            </Drawer.Header>
                            <Drawer.Section
                            style={{
                                label: {color: '#0000ff'}
                            }}
                            divider
                            items={[
                                {
                                    icon: 'bookmark-border', value: 'Bookmarks',
                                    active: this.state.active == 'bookmark',
                                    onPress: () => {
                                        this.setState({ active: 'bookmark' });
                                        this.props.navigation.navigate('Bookmark');
                                      },
                                  },
                                {
                                    icon: 'people', value: 'Connections',
                                    active: this.state.active == 'Connection',
                                    onPress: () => {
                                        this.setState({ active: 'Connection' });
                                        this.props.navigation.navigate('Connections');
                                      },
                                  },
                            ]}
                        />
                            <Drawer.Section
                            title="Personal"
                            items={[
                                {
                                    icon: 'info', value: 'Info',
                                    active: this.state.active == 'info',
                                    onPress: () => {
                                        this.setState({ active: 'info' });
                                        //this.props.navigation.navigate('DrawerClose');
                                        this.props.navigation.navigate('Info');
                                      },
                                  },
                                {
                                    icon: 'settings', value: 'Settings',
                                    active: this.state.active == 'settings',
                                    onPress: () => {
                                        this.setState({ active: 'settings' });
                                        this.props.navigation.navigate('Settings');
                                      },
                                  },
                                   {
                                    icon: 'logout', value: 'Logout',
                                    active: this.state.active == 'logout',
                                    onPress: () => {
                                    this.handleLogoutPress();
                                     },
                                      },
                            ]}
                        />
                        </Drawer>
                    </View>
                </Container>
            </ThemeProvider>
    );
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
      },
    header: {
        backgroundColor: '#455A64',
      },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
      },
  });
</code>```

The above is the stack architecture i am using inside my application and as you can see that my Main screen is LOGIN screen and i do have option for LOGOUT from application in my Drawer(side menu). What i eaxtly want is that when user click on logout he/she should get redirected to LOGIN screen . i have googled about this and got to know about two ways of doing it , but both the ways are not working for me , may be i am using them in wrong way. so i am here to seek your help .

The two methods are :-

1)

```<code>this.props
               .navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [
                      NavigationActions.navigate({ routeName: 'LoginScreen'})
                    ]
                  }));
</code>```

2) this.props.navigation.dispatch(NavigationActions.back());

this question may seems silly to you but i am really stuck at this point and just want to know how can i  figure this out.Any help would be greatly Appreciated!!!!
Thanks in advance.

答:
As per react navigation doc you can go to any stack by following ways:
check the following link for more details
React-navigation stack action link

```<code>1. import { StackActions, NavigationActions } from 'react-navigation';
         const resetAction = StackActions.reset({
          index: 0,
          actions: [NavigationActions.navigate({ routeName: 'Profile' })],
        });
        this.props.navigation.dispatch(resetAction);
</code>```

If you have a stack for profile then you can also go through like this check following link  nested react navigation

import { NavigationActions } from 'react-navigation';

const navigateAction = NavigationActions.navigate({
  routeName: 'Profile',

  params: {},

  action: NavigationActions.navigate({ routeName: 'SubProfileRoute' }),
});

this.props.navigation.dispatch(navigateAction);```

Body:
i am new to react and trying to learn it by myself , i am facing problem in navigating user back to root screen from nested stck navigator screen .

Here is some of my classes :-

index.android.js :-

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import {LoginStack} from './login/loginregisterrouter';
import {StackNavigator } from 'react-navigation';
class reactNavigationSample extends Component {
  render(){
    return (
   <LoginStack/>
    );
  }
}
AppRegistry.registerComponent('MssReactDemo', () => reactNavigationSample);

loginregisterrouter :-

import React from 'react';
import {StackNavigator } from 'react-navigation';
import LoginScreen from './LoginScreen';
import RegisterScreen from './RegisterScreen';
import NavigationContainer from './navigationContainer';
export const LoginStack = StackNavigator({
  LoginScreen: {
    screen: LoginScreen,
    navigationOptions: {
      title: 'LoginScreen',
    }
  },
  RegisterScreen: {
    screen: RegisterScreen,
    navigationOptions: ({ navigation }) => ({
      title: 'RegisterScreen',
    }),
  },NavigationContainer: {
        screen: NavigationContainer,
        navigationOptions: ({ navigation }) => ({
          title: 'NavigationContainer', header: null,
        }),
      },
});

Navigationcontainer.js :-

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import {EasyRNRoute,} from '../parent';
import {StackNavigator } from 'react-navigation';
export default class NavigationContainer extends Component {
  render(){
    return (
   <EasyRNRoute/>
    );
  }
}

parent.js :-

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import App from './app';
import DrawerMenu from './Drawer/drawer-toolbar-android';
import BookmarkView from './Pages/bookmark';
import ClientView from './Pages/client';
import InfoView from './Pages/info';
import SettingsView from './Pages/setting';
import { DrawerNavigator, StackNavigator } from 'react-navigation';

export const stackNavigator = StackNavigator({
  Info: { screen: InfoView },
  Settings: {screen: SettingsView },
  Bookmark: {screen: BookmarkView },
  Connections: {screen: ClientView},
}, {
  headerMode: 'none'
});

export const EasyRNRoute = DrawerNavigator({
  Home: {
    screen: App,
  },
  Stack: {
    screen: stackNavigator
  }
}, {
  contentComponent: DrawerMenu,
  contentOptions: {
    activeTintColor: '#e91e63',
    style: {
      flex: 1,
      paddingTop: 15,
    }
  }
});

Drawer-toolbar-android.js :-

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    StatusBar,
    View
} from 'react-native';
import { NavigationActions } from 'react-navigation'
import { COLOR, ThemeProvider, Toolbar, Drawer, Avatar } from 'react-native-material-ui';
import Container from '../Container';
import LoginScreen from '../login/LoginScreen';

const uiTheme = {
    palette: {
        primaryColor: COLOR.green500,
        accentColor: COLOR.pink500,
      },
    toolbar: {
        container: {
            height: 70,
            paddingTop: 20,
          },
      },
      avatar: {
          container: {
              backgroundColor: '#333'
          }
      }
  };

export default class DrawerMenu extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
        active: 'people',
      };
  }
handleLogoutPress = () => {
//    AsyncStorage.setItem('SignedUpuser', '');
this.props
               .navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [
                      NavigationActions.navigate({ routeName: 'LoginScreen'})
                    ]
                  }));
//     this.props.navigation.dispatch(NavigationActions.back());
  };
  _setInfoActive() {
    this.setState({ active: 'info' });
  }

  render() {
    return (
        <ThemeProvider uiTheme={uiTheme}>
                <Container>
                    <StatusBar backgroundColor="rgba(0, 0, 0, 0.2)" translucent />
                    <Toolbar
                    leftElement="arrow-back"
                    onLeftElementPress={() => this.props.navigation.navigate('DrawerClose')}
                    centerElement="Menu"
                />
                    <View style={styles.container}>
                        <Drawer>
                            <Drawer.Header >
                                <Drawer.Header.Account
                                style={{
                                    container: { backgroundColor: '#fafafa' },
                                }}
                                avatar={<Avatar text={'S'} />}
//                                accounts={[
//                                    { avatar: <Avatar text="H" /> },
//                                    { avatar: <Avatar text="L" /> },
//                                ]}
                                footer={{
                                    dense: true,
                                    centerElement: {
                                        primaryText: 'Siddharth',
                                        secondaryText: 'I am DONE now',
                                    },

                                  }}
                            />
                            </Drawer.Header>
                            <Drawer.Section
                            style={{
                                label: {color: '#0000ff'}
                            }}
                            divider
                            items={[
                                {
                                    icon: 'bookmark-border', value: 'Bookmarks',
                                    active: this.state.active == 'bookmark',
                                    onPress: () => {
                                        this.setState({ active: 'bookmark' });
                                        this.props.navigation.navigate('Bookmark');
                                      },
                                  },
                                {
                                    icon: 'people', value: 'Connections',
                                    active: this.state.active == 'Connection',
                                    onPress: () => {
                                        this.setState({ active: 'Connection' });
                                        this.props.navigation.navigate('Connections');
                                      },
                                  },
                            ]}
                        />
                            <Drawer.Section
                            title="Personal"
                            items={[
                                {
                                    icon: 'info', value: 'Info',
                                    active: this.state.active == 'info',
                                    onPress: () => {
                                        this.setState({ active: 'info' });
                                        //this.props.navigation.navigate('DrawerClose');
                                        this.props.navigation.navigate('Info');
                                      },
                                  },
                                {
                                    icon: 'settings', value: 'Settings',
                                    active: this.state.active == 'settings',
                                    onPress: () => {
                                        this.setState({ active: 'settings' });
                                        this.props.navigation.navigate('Settings');
                                      },
                                  },
                                   {
                                    icon: 'logout', value: 'Logout',
                                    active: this.state.active == 'logout',
                                    onPress: () => {
                                    this.handleLogoutPress();
                                     },
                                      },
                            ]}
                        />
                        </Drawer>
                    </View>
                </Container>
            </ThemeProvider>
    );
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
      },
    header: {
        backgroundColor: '#455A64',
      },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
      },
  });

The above is the stack architecture i am using inside my application and as you can see that my Main screen is LOGIN screen and i do have option for LOGOUT from application in my Drawer(side menu). What i eaxtly want is that when user click on logout he/she should get redirected to LOGIN screen . i have googled about this and got to know about two ways of doing it , but both the ways are not working for me , may be i am using them in wrong way. so i am here to seek your help .

The two methods are :-

1)

this.props
               .navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [
                      NavigationActions.navigate({ routeName: 'LoginScreen'})
                    ]
                  }));

2) this.props.navigation.dispatch(NavigationActions.back());

this question may seems silly to you but i am really stuck at this point and just want to know how can i  figure this out.Any help would be greatly Appreciated!!!!
Thanks in advance.

Body:
As per react navigation doc you can go to any stack by following ways:
check the following link for more details
React-navigation stack action link

1. import { StackActions, NavigationActions } from 'react-navigation';
         const resetAction = StackActions.reset({
          index: 0,
          actions: [NavigationActions.navigate({ routeName: 'Profile' })],
        });
        this.props.navigation.dispatch(resetAction);

If you have a stack for profile then you can also go through like this check following link  nested react navigation

import { NavigationActions } from 'react-navigation';

const navigateAction = NavigationActions.navigate({
  routeName: 'Profile',

  params: {},

  action: NavigationActions.navigate({ routeName: 'SubProfileRoute' }),
});

this.props.navigation.dispatch(navigateAction);


来源: stackexchange

问:
My class fileds are getting initialized may be because I have a @bean for the same class but in a different .java file
I am new to spring and annotations.
I started the application in debug mode and I found that by the time my code reaches init() method of Actuator below values got assigned to actVar1 and actVar2.

actVar1 has "abc" value

actVar2 has  "xyz" value

Note: My application is not yet started completely . I am just trying with debug point in init() method for a different purpose and I observed above thing.

My question is why those variables have assigned those values.

```<code>//Actuator.java
@Component
public class Actuator {
private String actVar1;
private String actVar2;
//.. some code here
@PostConstruct
public void init(){
//my debug point is here
//some code .....
}
//.. some code here

}
//Beancreator.java
@Component
public class BeanCreator {
//.. some code here
private String first="abc";
private field2 second ="xyz";
//.. some code here

@Bean
public Actuator actuator() {
Actuator actuator = new Actuator();
actuator.setActVar1(first);
actuator.setActVar2(second);
return actuatorPoller;
}
//.. some code here
}
</code>```

When I change the method name under @Bean to different one ,those values are not getting assigned .

答:
My question is why those variables have assigned those values ?

First, after Spring creates a bean, it will call that bean 's @PostConstruct method.

Second , Spring will create a bean for the following cases:

If a class is annotated by @Component or its stereotype annotation such as @Repository, @Service, and @Controller etc , and auto-scanning feature is enable for the package containing that class , it will create a bean for it.

If a method on @Configuration /@Component class is annotated with @Bean , Spring will call that method to create a bean.

So your example creates 2 beans in the type of Actuator. A is due to @Component on Actuator class while B is due to @Bean method on BeanCreator.actuator().That 's why you see init() executes two times as there are two Actuator beans. For A , its init() is executed with NULL. For B, its init() is executed with "abc" and "xyz" simply because you set it in the @Bean method that creates it.

ContentLicense: CC BY-SA 4.0

Body:
I am new to spring and annotations.
I started the application in debug mode and I found that by the time my code reaches init() method of Actuator below values got assigned to actVar1 and actVar2.

actVar1 has "abc" value

actVar2 has  "xyz" value

Note: My application is not yet started completely . I am just trying with debug point in init() method for a different purpose and I observed above thing.

My question is why those variables have assigned those values.

//Actuator.java
@Component
public class Actuator {
private String actVar1;
private String actVar2;
//.. some code here
@PostConstruct
public void init(){
//my debug point is here
//some code .....
}
//.. some code here

}
//Beancreator.java
@Component
public class BeanCreator {
//.. some code here
private String first="abc";
private field2 second ="xyz";
//.. some code here

@Bean
public Actuator actuator() {
Actuator actuator = new Actuator();
actuator.setActVar1(first);
actuator.setActVar2(second);
return actuatorPoller;
}
//.. some code here
}

When I change the method name under @Bean to different one ,those values are not getting assigned .


问:
Custom allocators as alternatives to vector of smart pointers?
This question is about owning pointers, consuming pointers, smart pointers, vectors, and allocators.

I am a little bit lost on my thoughts about code architecture. Furthermore, if this  question has already an answer somewhere, 1. sorry, but I haven't found a satisfying answer so far and 2. please point me to it.

My problem is the following:

I have several "things" stored in a vector and several "consumers" of those "things". So, my first try was like follows:

```<code>std::vector<thing> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return &i_am_the_owner_of_things[5]; // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};
</code>```

In my application, this would be safe because the "things" outlive the "consumers" in any case. However, more "things" can be added during runtime and that can become a problem because if the std::vector<thing> i_am_the_owner_of_things; gets reallocated, all the thing* m_thing pointers become invalid.

A fix to this scenario would be to store unique pointers to "things" instead of "things" directly, i.e. like follows:

```<code>std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return i_am_the_owner_of_things[5].get(); // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};
</code>```

The downside here is that memory coherency between "things" is lost. Can this memory coherency be re-established by using custom allocators somehow? I am thinking of something like an allocator which would always allocate memory for, e.g., 10 elements at a time and whenever required, adds more 10-elements-sized chunks of memory.

Example:

initially:

v = ☐☐☐☐☐☐☐☐☐☐

more elements:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

and again:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

Using such an allocator, I wouldn't even have to use std::unique_ptrs of "things" because at std::vector's reallocation time, the memory addresses of the already existing elements would not change.

As alternative, I can only think of referencing the "thing" in "consumer" via a std::shared_ptr<thing> m_thing, as opposed to the current thing* m_thing but that seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So, is the allocator-approach a good one? And if so, how can it be done? Do I have to implement the allocator by myself or is there an existing one?

答:
IMO best approach would be create new container which will behave is safe way.

Pros:

change will be done on separate level of abstraction

changes to old code will be minimal (just replace std::vector with new container).

it will be "clean code" way to do it

Cons:

it may look like there is a bit more work to do

Other answer proposes use of std::list which will do the job, but with larger number of allocation and slower random access. So IMO it is better to compose own container from couple of std::vectors.

So it may start look more or less like this (minimum example):

template<typename T>
class cluster_vector
{
public:
    static const constexpr cluster_size = 16;

    cluster_vector() {
       clusters.reserve(1024);
       add_cluster();
    }

    ...

    size_t size() const {
       if (clusters.empty()) return 0;
       return (clusters.size() - 1) * cluster_size + clusters.back().size();
    }

    T& operator[](size_t index) {
        thowIfIndexToBig(index);
        return clusters[index / cluster_size][index % cluster_size];
    }

    void push_back(T&& x) {
        if_last_is_full_add_cluster();
        clusters.back().push_back(std::forward<T>(x));
    }

private:
    void thowIfIndexToBig(size_t index) const {
        if (index >= size()) {
            throw std::out_of_range("cluster_vector out of range");
        }
    }

    void add_cluster() {
       clusters.push_back({});
       clusters.back().reserve(cluster_size);
    }

    void if_last_is_full_add_cluster() {
       if (clusters.back().size() == cluster_size) {
           add_cluster();
       }
    }

private:
    std::vector<std::vector<T>> clusters;
}
```

This way you will provide container which will not reallocate items. It doesn't meter what T does.

Body:
This question is about owning pointers, consuming pointers, smart pointers, vectors, and allocators.

I am a little bit lost on my thoughts about code architecture. Furthermore, if this  question has already an answer somewhere, 1. sorry, but I haven't found a satisfying answer so far and 2. please point me to it.

My problem is the following:

I have several "things" stored in a vector and several "consumers" of those "things". So, my first try was like follows:

std::vector<thing> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return &i_am_the_owner_of_things[5]; // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};

In my application, this would be safe because the "things" outlive the "consumers" in any case. However, more "things" can be added during runtime and that can become a problem because if the std::vector<thing> i_am_the_owner_of_things; gets reallocated, all the thing* m_thing pointers become invalid.

A fix to this scenario would be to store unique pointers to "things" instead of "things" directly, i.e. like follows:

std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return i_am_the_owner_of_things[5].get(); // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};

The downside here is that memory coherency between "things" is lost. Can this memory coherency be re-established by using custom allocators somehow? I am thinking of something like an allocator which would always allocate memory for, e.g., 10 elements at a time and whenever required, adds more 10-elements-sized chunks of memory.

Example:

initially:

v = ☐☐☐☐☐☐☐☐☐☐

more elements:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

and again:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

Using such an allocator, I wouldn't even have to use std::unique_ptrs of "things" because at std::vector's reallocation time, the memory addresses of the already existing elements would not change.

As alternative, I can only think of referencing the "thing" in "consumer" via a std::shared_ptr<thing> m_thing, as opposed to the current thing* m_thing but that seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So, is the allocator-approach a good one? And if so, how can it be done? Do I have to implement the allocator by myself or is there an existing one?

Body:
IMO best approach would be create new container which will behave is safe way.

Pros:

change will be done on separate level of abstraction

changes to old code will be minimal (just replace std::vector with new container).

it will be "clean code" way to do it

Cons:

it may look like there is a bit more work to do

Other answer proposes use of std::list which will do the job, but with larger number of allocation and slower random access. So IMO it is better to compose own container from couple of std::vectors.

So it may start look more or less like this (minimum example):

template<typename T>
class cluster_vector
{
public:
    static const constexpr cluster_size = 16;

    cluster_vector() {
       clusters.reserve(1024);
       add_cluster();
    }

    ...

    size_t size() const {
       if (clusters.empty()) return 0;
       return (clusters.size() - 1) * cluster_size + clusters.back().size();
    }

    T& operator[](size_t index) {
        thowIfIndexToBig(index);
        return clusters[index / cluster_size][index % cluster_size];
    }

    void push_back(T&& x) {
        if_last_is_full_add_cluster();
        clusters.back().push_back(std::forward<T>(x));
    }

private:
    void thowIfIndexToBig(size_t index) const {
        if (index >= size()) {
            throw std::out_of_range("cluster_vector out of range");
        }
    }

    void add_cluster() {
       clusters.push_back({});
       clusters.back().reserve(cluster_size);
    }

    void if_last_is_full_add_cluster() {
       if (clusters.back().size() == cluster_size) {
           add_cluster();
       }
    }

private:
    std::vector<std::vector<T>> clusters;
}

This way you will provide container which will not reallocate items. It doesn't meter what T does.


问:
How can I use the SHA's on installing Ruby ? What's the risk if I don't verify them?
I'm installing Ruby (in order to eventually be able to use Redmine) on my Win 10 laptop.

I realize how critical the whole install process is and I'm wondering if there are real threats not to check the various SHA given there : https://www.ruby-lang.org/en/news/2015/04/13/ruby-2-2-2-released/.

I guess it's needed if you don't trust the source you're downloading from, but I found it through my usual search engine (ie qwant).

If this verification is really a must-do, how can I do it ?

One of the SHA's given is :

```<code>SHA1:   7d26835cb7711dfe75f2c10fe38cb85f5ed56df5
</code>```

I'm on Win 10, so I picked one from the .zip list.

答:
To prevent tampering (but if the download is through https you are safe).

Theory is pretty well introduced here.

Hands on side, in short, you need to execute $>sha1sum my_file.exe in PowerShell, and check if the hash is the expected one.

https://imgur.com/q3yYVXO

Body:
I'm installing Ruby (in order to eventually be able to use Redmine) on my Win 10 laptop.

I realize how critical the whole install process is and I'm wondering if there are real threats not to check the various SHA given there : https://www.ruby-lang.org/en/news/2015/04/13/ruby-2-2-2-released/.

I guess it's needed if you don't trust the source you're downloading from, but I found it through my usual search engine (ie qwant).

If this verification is really a must-do, how can I do it ?

One of the SHA's given is :

SHA1:   7d26835cb7711dfe75f2c10fe38cb85f5ed56df5

I'm on Win 10, so I picked one from the .zip list.


问:
Python) How to convert string to dict? (Strange type of string)
The string is..

```<code>{
   "version":"20131101",
   "logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif",
   "title":"알라딘 베스트셀러 리스트 - 철학사",
   "link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&BranchType=1&CID=51441&Year=2019&Month=5&Week=4&partner=openAPI",
   "pubDate":"Mon, 27 May 2019 10:33:33 GMT",
   "totalResults":955,
   "startIndex":1,
   "itemsPerPage":10,
   "query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4",
   "searchCategoryId":51441,
   "searchCategoryName":"철학사",
   "item":[
      {
         "title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음",
         "link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api",
         "author":"안광복 (지은이)",

      }
   ]
}
</code>```

I wanna convert string to dict.

This is what I want

I want to make this whole string to dictionary, So I want to get the value of "item"

```<code>"item" : [{"title: ", " : ", ... }, {"title: ", " : ", ...  }, { "title: ", " : ", ... }]
</code>```

I want the dictionaries(looks like dictionary but string) in the list(looks like list but str) so i want to use like dictionary

```<code>print(decoding_bestseller.find("item",370))
b=decoding_bestseller.split('"item"')
want_str=b[1]
want_str1=want_str.strip(':[]{}')
want_list=want_str1.split(',')
book_dic = {}
for i in range(0,len(want_list)):
    in_colon = ":" in want_list[i]
    if in_colon:
        split_list = want_list[i].split(':')
        book_key = split_list[0].strip('""')
        book_value = split_list[1].strip('""')
        book_dic[book_key] = book_value
</code>```

I did like that but I failed.

The string is like this
    {" : ", " : ", "item : [ {"title : ", "link : ", } {"title : ", "link : ",  }, " : "}

i want to make {"title : ", "link : ", ...} to REAL dictionary!

答:
You can create a dictionary from a string using eval.

```<code>as_string = str({"version":"20131101","logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif","title":"알라딘 베스트셀러 리스트 - 철학사","link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&BranchType=1&CID=51441&Year=2019&Month=5&Week=4&partner=openAPI","pubDate":"Mon, 27 May 2019 10:33:33 GMT","totalResults":955,"startIndex":1,"itemsPerPage":10,"query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4","searchCategoryId":51441,"searchCategoryName":"철학사","item":[{"title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음","link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api","author":"안광복 (지은이)",}]})
as_dict = eval(as_string)
</code>```

Body:
The string is..

{
   "version":"20131101",
   "logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif",
   "title":"알라딘 베스트셀러 리스트 - 철학사",
   "link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&BranchType=1&CID=51441&Year=2019&Month=5&Week=4&partner=openAPI",
   "pubDate":"Mon, 27 May 2019 10:33:33 GMT",
   "totalResults":955,
   "startIndex":1,
   "itemsPerPage":10,
   "query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4",
   "searchCategoryId":51441,
   "searchCategoryName":"철학사",
   "item":[
      {
         "title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음",
         "link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api",
         "author":"안광복 (지은이)",

      }
   ]
}

I wanna convert string to dict.

This is what I want

I want to make this whole string to dictionary, So I want to get the value of "item"

"item" : [{"title: ", " : ", ... }, {"title: ", " : ", ...  }, { "title: ", " : ", ... }]

I want the dictionaries(looks like dictionary but string) in the list(looks like list but str) so i want to use like dictionary

print(decoding_bestseller.find("item",370))
b=decoding_bestseller.split('"item"')
want_str=b[1]
want_str1=want_str.strip(':[]{}')
want_list=want_str1.split(',')
book_dic = {}
for i in range(0,len(want_list)):
    in_colon = ":" in want_list[i]
    if in_colon:
        split_list = want_list[i].split(':')
        book_key = split_list[0].strip('""')
        book_value = split_list[1].strip('""')
        book_dic[book_key] = book_value

I did like that but I failed.

The string is like this
    {" : ", " : ", "item : [ {"title : ", "link : ", } {"title : ", "link : ",  }, " : "}

i want to make {"title : ", "link : ", ...} to REAL dictionary!

Body:
You can create a dictionary from a string using eval.

as_string = str({"version":"20131101","logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif","title":"알라딘 베스트셀러 리스트 - 철학사","link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&amp;BranchType=1&amp;CID=51441&amp;Year=2019&amp;Month=5&amp;Week=4&amp;partner=openAPI","pubDate":"Mon, 27 May 2019 10:33:33 GMT","totalResults":955,"startIndex":1,"itemsPerPage":10,"query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4","searchCategoryId":51441,"searchCategoryName":"철학사","item":[{"title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음","link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&amp;partner=openAPI&amp;start=api","author":"안광복 (지은이)",}]})
as_dict = eval(as_string)


问:
How to add a font-awesome icon into @Html.TextBoxFor?
I have a following problem: How can I add a fa-user icon into my textbox?

I have a following code:

```<code>@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="row">
     <div class="container col-md-12">
          @*@Html.LabelFor(m => m.UserName, new { @class = "control-label" })*@
          <i class="fa fa-user col-md-12" aria-hidden="true"></i>
          @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
          @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
     </div>
</div>
</code>```

The "i" element is not visible on my site view in browser.
If it is imposible there is any posibility to add this icon to my site?

答:
Most likely you can use the Font awesome unicode codes for display.  Example (value=....):

```<code> <input type=“submit” value="&#xf0f6 My blog" class=“fa fa-input”>
</code>```

Found at https://www.freecodecamp.org/forum/t/solved-adding-font-awesome-icons-to-an-input-button/74139/6

You can find the unicode related code at:

https://fontawesome.com/icons/arrow-right?style=solid

Should work with any similar items.

ContentLicense: CC BY-SA 3.0

Body:
I have a following problem: How can I add a fa-user icon into my textbox?

I have a following code:

@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })

          @*@Html.LabelFor(m => m.UserName, new { @class = "control-label" })*@

          @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
          @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })

The "i" element is not visible on my site view in browser.
If it is imposible there is any posibility to add this icon to my site?

Body:
Most likely you can use the Font awesome unicode codes for display.  Example (value=....):

 <input type=“submit” value="&#xf0f6 My blog" class=“fa fa-input”>

Found at https://www.freecodecamp.org/forum/t/solved-adding-font-awesome-icons-to-an-input-button/74139/6

You can find the unicode related code at:

https://fontawesome.com/icons/arrow-right?style=solid

Should work with any similar items.


问:
Detecting when an object gets added to a movieclip
Alright, so I'm trying to figure out when a child is added to a movieclip "x", and handling/detouring this operation from within this "x" movieclip.

I tried overriding addChild and addChildAt at with no prevail. The movieclips that are placed on the stage via flash still don't trigger addChild or addChildAt. However, tracing this.numChildren shows '2' correctly.

Any hints?

答:
You can add an event listener for the "added" event for the x movie clip.

```<code>x.addEventListener(Event.ADDED, addHandler);

function addHandler(e:Event){
 // your code here
}
</code>```

This link may explain it better:
AS3.0 – Event.ADDED and Event.ADDED_TO_STAGE

The documentation is also a good resource:
flash.events.Event

Body:
You can add an event listener for the "added" event for the x movie clip.

x.addEventListener(Event.ADDED, addHandler);

function addHandler(e:Event){
 // your code here
}

This link may explain it better:
AS3.0 – Event.ADDED and Event.ADDED_TO_STAGE

The documentation is also a good resource:
flash.events.Event


问:
Is there any way to avoid missing bytes on a Python socket data transmission?
I have two different python clients communicating with each other (Client A and Client B) through an external node server on the internet. Client A should send many identified messages in a short period of time to client B, where the node server is responsible to forward all received messages from A to B.

What is happening is that client A is overwriting some message.

I have detected the problem on client B, which is where I analyze the messages. However, the problem occurs in the transmission of messages between client A and Node server, because I am already able to see the broken message on node server logs.

I will show some pseudo-code along with some logs regarding the error (Client A and Server only) :

Client A

Code
    ...
    import socket

```<code>server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((HOST, PORT))

...

while not END:
    #Prepare message_to_clinet

    #If I uncomment this timer, the error will not appear (or appear later)
    #time.sleep(0.2)

    # I have tried either sendall and send. But it seems that is not effective
    server_socket.sendall(message_to_client)
    print '(Sent):' + message_to_client
</code>```

Logs when the error occurs
Imagine that I want to send 100 times the message: 'Where is the bug?'

```<code>...
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
...
</code>```

Node

Code

```<code>const net = require('net');
const tcpServer = net.createServer(connection.requestHandler);
tcpServer.listen(connection.port, (err) => {
    if (err) {
        return console.log('tcp socket error', err);
    }

    console.log(`tcp socket listening on ${connection.port}`);
});

...

const requestHandler = (sock) => {
    sock.on('data', (data) => {
        const protocol_message = new Buffer(data).toString('ascii');

        //Send this message to remote client
        currentConnection.sendMessagesToClient(protocol_message)
        console.log('Received: ' + protocol_message)
    }
}
</code>```

Logs when the error occurs.
I receive more messages for each socket.send maybe because socket.send it is called several times in a short time on client A (which is not a problem because on the real code I have a 4 byte-length prefix to prevent errors when reading on clinet B)

```<code>...
Received: Where is the bug? Where is the bug? Where is the bug?  Where is the bug?Where is the bug?
Received: Where is the bug? Where is the bug? Where is the bug?  Where is the bug?Where is the bug?
Received: Where is thWhere is the bug? Where is the bug?Where is the bug?
...
</code>```

Here I can see that one of the 100 messages I repeatedly sent is broken. However, on client A, everything is apparently well.

Does anyone know what is a possible cause of this error?

I know if put a time.sleep(0.1) between each message on client A, the error takes more time and transmitted bytes to happen. But when it works, it is just too slow.
I also know that if I use the developer local server, I cannot reproduce the error. My guess is that this is related to socket buffer and delay on transmission.

EDIT: I am using Python 2.7

答:
You could always try:

s.recv #insert increased buffer size here#
```

Might work.

Body:
I have two different python clients communicating with each other (Client A and Client B) through an external node server on the internet. Client A should send many identified messages in a short period of time to client B, where the node server is responsible to forward all received messages from A to B.

What is happening is that client A is overwriting some message.

I have detected the problem on client B, which is where I analyze the messages. However, the problem occurs in the transmission of messages between client A and Node server, because I am already able to see the broken message on node server logs.

I will show some pseudo-code along with some logs regarding the error (Client A and Server only) :

Client A

Code
    ...
    import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((HOST, PORT))

...

while not END:
    #Prepare message_to_clinet

    #If I uncomment this timer, the error will not appear (or appear later)
    #time.sleep(0.2)

    # I have tried either sendall and send. But it seems that is not effective
    server_socket.sendall(message_to_client)
    print '(Sent):' + message_to_client

Logs when the error occurs
Imagine that I want to send 100 times the message: 'Where is the bug?'

...
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
...

Node

Code

const net = require('net');
const tcpServer = net.createServer(connection.requestHandler);
tcpServer.listen(connection.port, (err) => {
    if (err) {
        return console.log('tcp socket error', err);
    }

    console.log(`tcp socket listening on ${connection.port}`);
});

...

const requestHandler = (sock) => {
    sock.on('data', (data) => {
        const protocol_message = new Buffer(data).toString('ascii');

        //Send this message to remote client
        currentConnection.sendMessagesToClient(protocol_message)
        console.log('Received: ' + protocol_message)
    }
}

Logs when the error occurs.
I receive more messages for each socket.send maybe because socket.send it is called several times in a short time on client A (which is not a problem because on the real code I have a 4 byte-length prefix to prevent errors when reading on clinet B)

...
Received: Where is the bug? Where is the bug? Where is the bug?  Where is the bug?Where is the bug?
Received: Where is the bug? Where is the bug? Where is the bug?  Where is the bug?Where is the bug?
Received: Where is thWhere is the bug? Where is the bug?Where is the bug?
...

Here I can see that one of the 100 messages I repeatedly sent is broken. However, on client A, everything is apparently well.

Does anyone know what is a possible cause of this error?

I know if put a time.sleep(0.1) between each message on client A, the error takes more time and transmitted bytes to happen. But when it works, it is just too slow.
I also know that if I use the developer local server, I cannot reproduce the error. My guess is that this is related to socket buffer and delay on transmission.

EDIT: I am using Python 2.7

Body:
You could always try:

s.recv #insert increased buffer size here#

Might work.


问:
Changing Button Color using Listbox
I need to change background color of Button using ListBox. I have 3 ListBoxItems for 3 colors ( green, yellow and red). I am not sure how to do this. Any help will be greatly appreciated.</p>

```<code><StackPanel Grid.Column="1" Grid.Row="3">
  <ToggleButton Height="50" Content="Change!" Name="button">
   </ToggleButton>
    <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
     <Border Background="LightYellow">
       <ListBox>
        <ListBoxItem>Green</ListBoxItem>
         <ListBoxItem>Yellow</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
      </ListBox>
    </Border>
  </Popup>
</StackPanel>
</code>```

答:
You can also do something like this with DataTrigger</p>

```<code><StackPanel Grid.Row="2">
            <Popup IsOpen="{Binding IsChecked, ElementName=button}"  StaysOpen="False">
                <Border Background="LightYellow">
                    <ListBox x:Name="ColorPicker" >
                        <ListBoxItem>Green</ListBoxItem>
                        <ListBoxItem>Yellow</ListBoxItem>
                        <ListBoxItem>Red</ListBoxItem>
                    </ListBox>
                </Border>
            </Popup>
            <ToggleButton Name="button"
                  Height="50">
                <TextBlock Text="Change!" >
                    <TextBlock.Style>
                        <Style TargetType="TextBlock">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding ElementName=ColorPicker,Path=SelectedIndex}"  Value="0">
                                    <Setter Property="Background" Value="Green"></Setter>
                                </DataTrigger>
                                <DataTrigger Binding="{Binding ElementName=ColorPicker,Path=SelectedItem}"  Value="1">
                                    <Setter Property="Background" Value="Yellow"></Setter>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBlock.Style>

                </TextBlock>

            </ToggleButton>
        </StackPanel>
</code>```

Title: Changing Button Color using Listbox

Body:
I need to change background color of Button using ListBox. I have 3 ListBoxItems for 3 colors ( green, yellow and red). I am not sure how to do this. Any help will be greatly appreciated.

<StackPanel Grid.Column="1" Grid.Row="3">
  <ToggleButton Height="50" Content="Change!" Name="button">
   </ToggleButton>
    <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
     <Border Background="LightYellow">
       <ListBox>
        <ListBoxItem>Green</ListBoxItem>
         <ListBoxItem>Yellow</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
      </ListBox>
    </Border>
  </Popup>
</StackPanel>

Body:
You can also do something like this with DataTrigger

<StackPanel Grid.Row="2">
            <Popup IsOpen="{Binding IsChecked, ElementName=button}"  StaysOpen="False">
                <Border Background="LightYellow">
                    <ListBox x:Name="ColorPicker" >
                        <ListBoxItem>Green</ListBoxItem>
                        <ListBoxItem>Yellow</ListBoxItem>
                        <ListBoxItem>Red</ListBoxItem>
                    </ListBox>
                </Border>
            </Popup>
            <ToggleButton Name="button"
                  Height="50">
                <TextBlock Text="Change!" >
                    <TextBlock.Style>
                        <Style TargetType="TextBlock">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding ElementName=ColorPicker,Path=SelectedIndex}"  Value="0">
                                    <Setter Property="Background" Value="Green"></Setter>
                                </DataTrigger>
                                <DataTrigger Binding="{Binding ElementName=ColorPicker,Path=SelectedItem}"  Value="1">
                                    <Setter Property="Background" Value="Yellow"></Setter>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBlock.Style>

                </TextBlock>

            </ToggleButton>
        </StackPanel>


问:
Remove blank attributes from an Object in Javascript
How do I remove all attributes which are undefined or null in a JavaScript object?

(Question is similar to this one for Arrays)

答:
Functional and immutable approach, without .filter and without creating more objects than needed

```<code>Object.keys(obj).reduce((acc, key) => (obj[key] === undefined ? acc : {...acc, [key]: obj[key]}), {})
</code>```

OwnerDisplayName: globetrotter

Body:
Functional and immutable approach, without .filter and without creating more objects than needed

Object.keys(obj).reduce((acc, key) => (obj[key] === undefined ? acc : {...acc, [key]: obj[key]}), {})


问:
KeyError when saving workbook
The file transactions.xlsx is not updated and this is precisely due to add_chart(). If I comment out add_chart all these errors does not arise but I want to draw chart and this is the only method I know. transanctions2.xlsx file is created but it is corrupted whereas bunch of errors do come up.</p>

```<code>from openpyxl.chart import BarChart, Reference

wb1 = xl.load_workbook('transactions.xlsx')
sheet = wb1['Sheet1']
cell = sheet.cell(1, 1)

for row in range(2, sheet.max_row + 1):
    cell = sheet.cell(row, 3)
    corrected_price = cell.value * 0.9
    corrected_price_cell = sheet.cell(row, 4)
    corrected_price_cell.value = corrected_price

values = Reference(sheet,
                   min_row=2,
                   max_row=sheet.max_row,
                   min_col=4,
                   max_col=4)
chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart, 'f2')

wb1.save('transactions2.xlsx')
</code>```

```<code>Traceback (most recent call last):
  File "C:/Users/Saman/PycharmProjects/Excel/excel_edit.py", line 23, in <module>
    wb1.save('transactions2.xlsx')
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\workbook\workbook.py", line 397, in save
    save_workbook(self, filename)
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 294, in save_workbook
    writer.save()
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 276, in save
    self.write_data()
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 76, in write_data
    self._write_worksheets()
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 219, in _write_worksheets
    self._write_drawing(ws._drawing)
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 142, in _write_drawing
    self._archive.writestr(drawing.path[1:], tostring(drawing._write()))
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\drawing\spreadsheet_drawing.py", line 283, in _write
    anchor = _check_anchor(obj)
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\drawing\spreadsheet_drawing.py", line 224, in _check_anchor
    row, col = coordinate_to_tuple(anchor)
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\utils\cell.py", line 201, in coordinate_to_tuple
    return int(row), _COL_STRING_CACHE[col]
KeyError: 'f'
</code>```

答:
The case matters when naming columns - specifically, they are uppercase:

```<code>sheet.add_chart(chart, 'F2')
</code>```

I changed f to F.

Title: KeyError when saving workbook

Body:
The file transactions.xlsx is not updated and this is precisely due to add_chart(). If I comment out add_chart all these errors does not arise but I want to draw chart and this is the only method I know. transanctions2.xlsx file is created but it is corrupted whereas bunch of errors do come up.

from openpyxl.chart import BarChart, Reference

wb1 = xl.load_workbook('transactions.xlsx')
sheet = wb1['Sheet1']
cell = sheet.cell(1, 1)

for row in range(2, sheet.max_row + 1):
    cell = sheet.cell(row, 3)
    corrected_price = cell.value * 0.9
    corrected_price_cell = sheet.cell(row, 4)
    corrected_price_cell.value = corrected_price

values = Reference(sheet,
                   min_row=2,
                   max_row=sheet.max_row,
                   min_col=4,
                   max_col=4)
chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart, 'f2')

wb1.save('transactions2.xlsx')

Traceback (most recent call last):
  File "C:/Users/Saman/PycharmProjects/Excel/excel_edit.py", line 23, in <module>
    wb1.save('transactions2.xlsx')
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\workbook\workbook.py", line 397, in save
    save_workbook(self, filename)
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 294, in save_workbook
    writer.save()
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 276, in save
    self.write_data()
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 76, in write_data
    self._write_worksheets()
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 219, in _write_worksheets
    self._write_drawing(ws._drawing)
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 142, in _write_drawing
    self._archive.writestr(drawing.path[1:], tostring(drawing._write()))
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\drawing\spreadsheet_drawing.py", line 283, in _write
    anchor = _check_anchor(obj)
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\drawing\spreadsheet_drawing.py", line 224, in _check_anchor
    row, col = coordinate_to_tuple(anchor)
  File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\utils\cell.py", line 201, in coordinate_to_tuple
    return int(row), _COL_STRING_CACHE[col]
KeyError: 'f'

Body:
The case matters when naming columns - specifically, they are uppercase:

sheet.add_chart(chart, 'F2')

I changed f to F.


问:
How to correctly render info to handlebars template
Rendering information from my controller only passes information through to the partials included on the template.

Here is how I go about it in my login controller. After I check password and username provided I send two objects to the dashboard template that I would like to render to the page

```<code>res.render(path.join(DIST_DIR, 'dashboard.hbs'), {
                                    user,
                                    company
                                });
</code>```

I can log this info and can see that it exists and it also renders out in the partials that included on dashboard.hsb, but it seems that dashboard itself is not getting the data.

My webpack setup

```<code>{
                // Loads the javacript into html template provided.
                // Entry point is set below in HtmlWebPackPlugin in Plugins
                test: /\.hbs$/,
                loader: 'handlebars-loader',
                query: {
                    partialDirs: [
                        path.join(__dirname, './src/views/partials')
                    ],
                    helperDirs: [
                        path.join(__dirname, './src/helpers')
                    ]
                }
            },
</code>```

```<code>new HtmlWebPackPlugin({
            filename: 'dashboard.hbs',
            title: 'Dashboard',
            chunks: ['dashboard', 'dashboard~login', 'vendors~dashboard', 'vendors~dashboard~login'],
            template: 'src/views/index/dashboard.hbs',
            excludeChunks: ['server']
        }),
</code>```

So the page renders fine and the user information that I try to pass does show up in the partials (used by dashboard layout), but the information for the user that I want to display in the body of dashboard.hbs is always blank. I seems that information is not passed to this template.

Where am I going wrong? I would really appreciate some help here.

答:
I was using the wrong loader. Instead of using handlebars-loader, I updated the code to use the html-loader

```<code>{
                // Loads the javacript into html template provided.
                // Entry point is set below in HtmlWebPackPlugin in Plugins
                test: /\.hbs$/,
                loader: 'html-loader',
                query: {
                    partialDirs: [
                        path.join(__dirname, './src/views/partials')
                    ],
                    helperDirs: [
                        path.join(__dirname, './src/helpers')
                    ]
                }
            },
</code>```

And now everything works as expected. Hope this helps someone else down the line

Body:
Rendering information from my controller only passes information through to the partials included on the template.

Here is how I go about it in my login controller. After I check password and username provided I send two objects to the dashboard template that I would like to render to the page

res.render(path.join(DIST_DIR, 'dashboard.hbs'), {
                                    user,
                                    company
                                });

I can log this info and can see that it exists and it also renders out in the partials that included on dashboard.hsb, but it seems that dashboard itself is not getting the data.

My webpack setup

{
                // Loads the javacript into html template provided.
                // Entry point is set below in HtmlWebPackPlugin in Plugins
                test: /\.hbs$/,
                loader: 'handlebars-loader',
                query: {
                    partialDirs: [
                        path.join(__dirname, './src/views/partials')
                    ],
                    helperDirs: [
                        path.join(__dirname, './src/helpers')
                    ]
                }
            },

new HtmlWebPackPlugin({
            filename: 'dashboard.hbs',
            title: 'Dashboard',
            chunks: ['dashboard', 'dashboard~login', 'vendors~dashboard', 'vendors~dashboard~login'],
            template: 'src/views/index/dashboard.hbs',
            excludeChunks: ['server']
        }),

So the page renders fine and the user information that I try to pass does show up in the partials (used by dashboard layout), but the information for the user that I want to display in the body of dashboard.hbs is always blank. I seems that information is not passed to this template.

Where am I going wrong? I would really appreciate some help here.

Body:
I was using the wrong loader. Instead of using handlebars-loader, I updated the code to use the html-loader

{
                // Loads the javacript into html template provided.
                // Entry point is set below in HtmlWebPackPlugin in Plugins
                test: /\.hbs$/,
                loader: 'html-loader',
                query: {
                    partialDirs: [
                        path.join(__dirname, './src/views/partials')
                    ],
                    helperDirs: [
                        path.join(__dirname, './src/helpers')
                    ]
                }
            },

And now everything works as expected. Hope this helps someone else down the line


问:
Redirect to ReactNative component from webview
I am using react native WebView to open some complex form steps. I want app user to redirect Android app Home page(react native component) after completing last step(http://example.com/completed/) in WebView.</p>

答:
I achieve the same to navigate to another component from webview by following the documentation of react-navigation using following link
https://reactnavigation.org/docs/en/stack-actions.html

for webview inside onNavigationStateChange call 1st one

1st way

```<code>import { StackActions, NavigationActions } from 'react-navigation';

const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({ routeName: 'Profile' })],
});
this.props.navigation.dispatch(resetAction);
</code>```

2nd way
If you have a stack for profile then you can also go through like this check following link nested react navigation

import { NavigationActions } from 'react-navigation';

const navigateAction = NavigationActions.navigate({
  routeName: 'Profile',

  params: {},

  action: NavigationActions.navigate({ routeName: 'SubProfileRoute' }),
});

this.props.navigation.dispatch(navigateAction);```

Body:
I achieve the same to navigate to another component from webview by following the documentation of react-navigation using following link
https://reactnavigation.org/docs/en/stack-actions.html

for webview inside onNavigationStateChange call 1st one

1st way

import { StackActions, NavigationActions } from 'react-navigation';

const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({ routeName: 'Profile' })],
});
this.props.navigation.dispatch(resetAction);

2nd way
If you have a stack for profile then you can also go through like this check following link nested react navigation

import { NavigationActions } from 'react-navigation';

const navigateAction = NavigationActions.navigate({
  routeName: 'Profile',

  params: {},

  action: NavigationActions.navigate({ routeName: 'SubProfileRoute' }),
});

this.props.navigation.dispatch(navigateAction);


问:
jqGrid search not working
Here is my code. My search is not working and Edit is showing but not saving in to the database! I tried what is in this URL, http://www.trirand.com/jqgridwiki/doku.php?id=wiki%3asinge_searching. But I couldn't correct it up. How can I fix this problem?

```<code><SCRIPT type="text/javascript">
    $(function(){
        jQuery("#list1").jqGrid({
            url:'school_manager_db.php?q=1',
            datatype: "xml",
            colNames:['ID','Name', 'City', 'Email','Tel NO','Type','Notes'],
            colModel:[
                {name:'id',index:'school_id', width:65,},
                {name:'name',index:'school_name', width:290,editable: true},
                {name:'city',index:'city', width:130,editable: true},
                {name:'email',index:'email', width:130,editable: true, align:"right"},
                {name:'tel',index:'contact', width:130,editable: true, align:"right"},
                {name:'type',index:'type', width:80,editable: true,edittype: 'select',
                align:"right"},
                {name:'note',index:'note', width:150,editable: true, sortable:false}
            ],
            height:480,
            rowNum:10,
            rowList:[40,80,120],
            imgpath: '/images',
            pager: jQuery('#pager1'),
            sortname: 'id',
            viewrecords: true,
            sortorder: "desc",
            caption:'',
            editurl:"someurl.php"
        }).navGrid('#pager1',{
            edit:true,
            add:true,
            del:true
        });
        jQuery("#list1").searchGrid( options );
    });
</SCRIPT>
</code>```

My PHP page,

```<code><?php
    include("db.php");
    $page = $_GET['page']; // Get the requested page.
    $limit = $_GET['rows']; // Get how many rows we want to have into the grid.
    $sidx = $_GET['sidx']; // Get index row - i.e. user click to sort.
    $sord = $_GET['sord']; // Get the direction.

    if (!$sidx)
        $sidx =1;

    $result = mysql_query("SELECT COUNT(*) AS count FROM school");
    $row = mysql_fetch_array($result,MYSQL_ASSOC);
    $count = $row['count'];

    if( $count >0 )
    {
        $total_pages = ceil($count/$limit);
    }
    else
    {
        $total_pages = 0;
    }

    if ($page > $total_pages)
        $page=$total_pages;
    $start = $limit*$page - $limit; // Do not put $limit*($page - 1).
    $SQL = "SELECT school_id, school_name,school_bedge,city,contact, email,typ from school ORDER BY $sidx $sord LIMIT $start , $limit";
    $result = mysql_query( $SQL ) or die("Couldn?t execute query.".mysql_error());

    if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") )
    {
        header("Content-type: application/xhtml+xml;charset=utf-8");
    }
    else
    {
        header("Content-type: text/xml;charset=utf-8");
    }
    $et = ">";
    echo "<?xml version='1.0' encoding='utf-8'?$et\n";
    echo "<rows>";
    echo "<page>".$page."</page>";
    echo "<total>".$total_pages."</total>";
    echo "<records>".$count."</records>";

    // Be sure to put text data in CDATA.
    while($row = mysql_fetch_array($result,MYSQL_ASSOC))
    {
        echo "<row id='". $row[id]."'>";
        echo "<cell>". $row['school_id']."</cell>";
        echo "<cell>". $row['school_name']."</cell>";
        echo "<cell>".  $row['city']."</cell>";
        echo "<cell>". $row['email']."</cell>";
        echo "<cell>". $row['contact']."</cell>";
        echo "<cell>". $row['typ']."</cell>";
        echo "<cell><![CDATA[". $row[note]."]]></cell>";
        echo "</row>";
    }
    echo "</rows>";
?>
</code>```

答:
May be the problem is in your "Type" column where you use edittype: select . Try with replacing the following code :

```<code>{name:'type',index:'type', width:80,editable: true, search: false, edittype: 'select',
                align:"right"},
</code>```

ContentLicense: CC BY-SA 2.5

Title: jqGrid search not working

Body:
Here is my code. My search is not working and Edit is showing but not saving in to the database! I tried what is in this URL, http://www.trirand.com/jqgridwiki/doku.php?id=wiki%3asinge_searching. But I couldn't correct it up. How can I fix this problem?

My PHP page,

<?php
    include("db.php");
    $page = $_GET['page']; // Get the requested page.
    $limit = $_GET['rows']; // Get how many rows we want to have into the grid.
    $sidx = $_GET['sidx']; // Get index row - i.e. user click to sort.
    $sord = $_GET['sord']; // Get the direction.

    if (!$sidx)
        $sidx =1;

    $result = mysql_query("SELECT COUNT(*) AS count FROM school");
    $row = mysql_fetch_array($result,MYSQL_ASSOC);
    $count = $row['count'];

    if( $count >0 )
    {
        $total_pages = ceil($count/$limit);
    }
    else
    {
        $total_pages = 0;
    }

    if ($page > $total_pages)
        $page=$total_pages;
    $start = $limit*$page - $limit; // Do not put $limit*($page - 1).
    $SQL = "SELECT school_id, school_name,school_bedge,city,contact, email,typ from school ORDER BY $sidx $sord LIMIT $start , $limit";
    $result = mysql_query( $SQL ) or die("Couldn?t execute query.".mysql_error());

    if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") )
    {
        header("Content-type: application/xhtml+xml;charset=utf-8");
    }
    else
    {
        header("Content-type: text/xml;charset=utf-8");
    }
    $et = ">";
    echo "<?xml version='1.0' encoding='utf-8'?$et\n";
    echo "<rows>";
    echo "<page>".$page."</page>";
    echo "<total>".$total_pages."</total>";
    echo "<records>".$count."</records>";

    // Be sure to put text data in CDATA.
    while($row = mysql_fetch_array($result,MYSQL_ASSOC))
    {
        echo "<row id='". $row[id]."'>";
        echo "<cell>". $row['school_id']."</cell>";
        echo "<cell>". $row['school_name']."</cell>";
        echo "<cell>".  $row['city']."</cell>";
        echo "<cell>". $row['email']."</cell>";
        echo "<cell>". $row['contact']."</cell>";
        echo "<cell>". $row['typ']."</cell>";
        echo "<cell><![CDATA[". $row[note]."]]></cell>";
        echo "</row>";
    }
    echo "</rows>";
?>

Body:
May be the problem is in your "Type" column where you use edittype: select . Try with replacing the following code :

{name:'type',index:'type', width:80,editable: true, search: false, edittype: 'select',
                align:"right"},


答:
```<code>CREATE DEFINER=`root`@`localhost` PROCEDURE `GET_ECERBER_STAT_BY_LIST`(datedebut DATETIME, datefin DATETIME,information VARCHAR(4000),IN  str_pays VARCHAR(4000),str_banque VARCHAR(4000))
BEGIN
     if information = 'NBReceived' then
      DROP TABLE IF EXISTS temp_tblist;
      truncate table stat_by_list;
      SET @row_number = 0;
      SET lc_time_names = 'fr_FR';
      CREATE   TABLE temp_tblist(
    id INT(100) NOT NULL, Pays varchar(255) NOT NULL, Mois varchar(255) NOT NULL,Remise INT(100) NOT NULL, PRIMARY KEY (id))
    ENGINE=MEMORY AS (select (@row_number:=@row_number + 1) as id,c.name_ as Pays,CONCAT(UCASE(MID(DATE_FORMAT(rr.date_,"%M %Y"),1,1)),LCASE(MID(DATE_FORMAT(rr.date_,"%M %Y"),2))) as Mois,count(*) as Remise from REGULATORYR rr INNER JOIN country c ON rr.COUNTRYPK_=c.pk_
    where rr.date_ in (select distinct rr.date_ as dater
    from REGULATORYR rr, country c
    where rr.date_>=datedebut and rr.date_<= datefin
    and c.pk_=rr.countrypk_
    group by substring(rr.date_,1,7))
    and c.pk_=rr.countrypk_  and c.CODE_ = str_pays
    group by COUNTRYPK_, substring(rr.date_,1,7)
    order by c.name_);
    set @name_pays  = (SELECT Pays FROM temp_tblist WHERE id=1);
    set @val1  = (SELECT Remise FROM temp_tblist WHERE id=1);set @val2 = (SELECT Remise FROM temp_tblist WHERE id=2);set @val3  = (SELECT Remise FROM temp_tblist WHERE id=3);set @val4  = (SELECT Remise FROM temp_tblist WHERE id=4);
    set @val5  = (SELECT Remise FROM temp_tblist WHERE id=5);set @val6  = (SELECT Remise FROM temp_tblist WHERE id=6);set @val7  = (SELECT Remise FROM temp_tblist WHERE id=7);set @val8  = (SELECT Remise FROM temp_tblist WHERE id=8);
    set @val9  = (SELECT Remise FROM temp_tblist WHERE id=9);set @val10 = (SELECT Remise FROM temp_tblist WHERE id=10);set @val11 = (SELECT Remise FROM temp_tblist WHERE id=11);set @val12 = (SELECT Remise FROM temp_tblist WHERE id=12);
    set @val13 = (SELECT Remise FROM temp_tblist WHERE id=13);set @val14 = (SELECT Remise FROM temp_tblist WHERE id=14);set @val15 = (SELECT Remise FROM temp_tblist WHERE id=15);set @val16 = (SELECT Remise FROM temp_tblist WHERE id=16);
    set @val17 = (SELECT Remise FROM temp_tblist WHERE id=17);set @val18 = (SELECT Remise FROM temp_tblist WHERE id=18);set @val19 = (SELECT Remise FROM temp_tblist WHERE id=19);set @val20 = (SELECT Remise FROM temp_tblist WHERE id=20);
    set @val21 = (SELECT Remise FROM temp_tblist WHERE id=21);set @val22 = (SELECT Remise FROM temp_tblist WHERE id=22);set @val23 = (SELECT Remise FROM temp_tblist WHERE id=23);set @val24 = (SELECT Remise FROM temp_tblist WHERE id=24);
    set @val25 = (SELECT Remise FROM temp_tblist WHERE id=25);set @val26  = (SELECT Remise FROM temp_tblist WHERE id=26);set @val27  =(SELECT Remise FROM temp_tblist WHERE id=27);set @val28  =(SELECT Remise FROM temp_tblist WHERE id=28);
    set @val29  = (SELECT Remise FROM temp_tblist WHERE id=29);set @val30  = (SELECT Remise FROM temp_tblist WHERE id=30);set @val31  = (SELECT Remise FROM temp_tblist WHERE id=31);set @val32  = (SELECT Remise FROM temp_tblist WHERE id=32);
    set @val33  = (SELECT Remise FROM temp_tblist WHERE id=33);set @val34  = (SELECT Remise FROM temp_tblist WHERE id=34);set @val35 = (SELECT Remise FROM temp_tblist WHERE id=35);set @val36 = (SELECT Remise FROM temp_tblist WHERE id=36);
    set @val37 = (SELECT Remise FROM temp_tblist WHERE id=37);set @val38 = (SELECT Remise FROM temp_tblist WHERE id=38);set @val39 = (SELECT Remise FROM temp_tblist WHERE id=39);set @val40 = (SELECT Remise FROM temp_tblist WHERE id=40);
    set @val41 = (SELECT Remise FROM temp_tblist WHERE id=41);set @val42 = (SELECT Remise FROM temp_tblist WHERE id=42);set @val43 = (SELECT Remise FROM temp_tblist WHERE id=43);set @val44 = (SELECT Remise FROM temp_tblist WHERE id=44);
    set @val45 = (SELECT Remise FROM temp_tblist WHERE id=45);set @val46 = (SELECT Remise FROM temp_tblist WHERE id=46);set @val47 = (SELECT Remise FROM temp_tblist WHERE id=47);set @val48 = (SELECT Remise FROM temp_tblist WHERE id=48);
    set @val49 = (SELECT Remise FROM temp_tblist WHERE id=49);set @val50 = (SELECT Remise FROM temp_tblist WHERE id=50);set @val51  = (SELECT Remise FROM temp_tblist WHERE id=51);
    insert into stat_by_list(TITRE_,VALEUR1_,VALEUR2_,VALEUR3_,VALEUR4_,VALEUR5_,VALEUR6_,VALEUR7_,VALEUR8_,VALEUR9_,VALEUR10_,VALEUR11_,VALEUR12_,VALEUR13_,VALEUR14_,VALEUR15_,VALEUR16_,VALEUR17_,VALEUR18_,VALEUR19_,VALEUR20_,VALEUR21_,VALEUR22_,VALEUR23_,VALEUR24_,VALEUR25_,VALEUR26_,VALEUR27_,VALEUR28_,VALEUR29_,VALEUR30_,VALEUR31_,VALEUR32_,VALEUR33_,VALEUR34_,VALEUR35_,VALEUR36_,VALEUR37_,VALEUR38_,VALEUR39_,VALEUR40_,VALEUR41_,VALEUR42_,VALEUR43_,VALEUR44_,VALEUR45_,VALEUR46_,VALEUR47_,VALEUR48_,VALEUR49_,
        VALEUR50_)
        values (@name_pays,@val1,@val2,@val3,@val4, @val5,@val6,@val7,@val8,@val9,@val10,
        @val11,@val12,@val13,@val14,@val15,@val16,@val17,@val18,@val19,@val20,
        @val21,@val22,@val23,@val24,@val25,@val26,@val27,@val28,@val29,@val30,
        @val31,@val32,@val33,@val34,@val35,@val36,@val37,@val38,@val39,@val40,
        @val41,@val42,@val43,@val44,@val45,@val46,@val47,@val48,@val49,@val50
    );
        select * from stat_by_list;
    end if;
    End
</code>```

Title: Stored Procedure That Insert Multi Row in a Table

Body:
I would like to insert more than one line into a table in a stored procedure,
It must be taken into concord that my values are recovered in a temporary array as follows:

mysql> select * from temp_tblist;

mysql> select * from temp_tblist ;

+------------------------------+---------------+--------------+-----------+
| id                           | NOm           | Mois         | Remise    |
+------------------------------+---------------+--------------+-----------+
| 1                            |Côte d'Ivoire  |Janvier 2019  | 2         |
| 2                            | Sénégal       | Janvier 2019 | 1         |
+------------------------------+---------------+-----------+--------------+
2 rows in set (0.30 sec)

The result of my procedure should be as follows:

mysql>  call GET_ECERBER_STAT_BY_LIST('2018-01-01','2019-12-29','NBReceived','CIV,SN',null);

+------------------------------+---------------+--------------+-----------+
| Titre                        | Valeur1       | Valeur2      | Valeur3   |
+------------------------------+---------------+--------------+-----------+
| Côte d'Ivoire                |10             |15            | 21        |
| Sénégal                      |2              |5             | 11        |
+------------------------------+---------------+-----------+--------------+
2 rows in set (0.30 sec)

Currently, I can insert in the table only one value as follows:

mysql>  call GET_ECERBER_STAT_BY_LIST('2018-01-01','2019-12-29','NBReceived','CIV',null);
+------------------------------+---------------+--------------+-----------+
| Titre                        | Valeur1       | Valeur2      | Valeur3   |
+------------------------------+---------------+--------------+-----------+
| Côte d'Ivoire                |10             |15            | 21        |
+------------------------------+---------------+-----------+--------------+
1 rows in set (0.30 sec)

Adding create syntax for the sp

CREATE DEFINER=`root`@`localhost` PROCEDURE `GET_ECERBER_STAT_BY_LIST`(datedebut DATETIME, datefin DATETIME,information VARCHAR(4000),IN  str_pays VARCHAR(4000),str_banque VARCHAR(4000))
BEGIN
     if information = 'NBReceived' then
      DROP TABLE IF EXISTS temp_tblist;
      truncate table stat_by_list;
      SET @row_number = 0;
      SET lc_time_names = 'fr_FR';
      CREATE   TABLE temp_tblist(
    id INT(100) NOT NULL, Pays varchar(255) NOT NULL, Mois varchar(255) NOT NULL,Remise INT(100) NOT NULL, PRIMARY KEY (id))
    ENGINE=MEMORY AS (select (@row_number:=@row_number + 1) as id,c.name_ as Pays,CONCAT(UCASE(MID(DATE_FORMAT(rr.date_,"%M %Y"),1,1)),LCASE(MID(DATE_FORMAT(rr.date_,"%M %Y"),2))) as Mois,count(*) as Remise from REGULATORYR rr INNER JOIN country c ON rr.COUNTRYPK_=c.pk_
    where rr.date_ in (select distinct rr.date_ as dater
    from REGULATORYR rr, country c
    where rr.date_>=datedebut and rr.date_<= datefin
    and c.pk_=rr.countrypk_
    group by substring(rr.date_,1,7))
    and c.pk_=rr.countrypk_  and c.CODE_ = str_pays
    group by COUNTRYPK_, substring(rr.date_,1,7)
    order by c.name_);
    set @name_pays  = (SELECT Pays FROM temp_tblist WHERE id=1);
    set @val1  = (SELECT Remise FROM temp_tblist WHERE id=1);set @val2 = (SELECT Remise FROM temp_tblist WHERE id=2);set @val3  = (SELECT Remise FROM temp_tblist WHERE id=3);set @val4  = (SELECT Remise FROM temp_tblist WHERE id=4);
    set @val5  = (SELECT Remise FROM temp_tblist WHERE id=5);set @val6  = (SELECT Remise FROM temp_tblist WHERE id=6);set @val7  = (SELECT Remise FROM temp_tblist WHERE id=7);set @val8  = (SELECT Remise FROM temp_tblist WHERE id=8);
    set @val9  = (SELECT Remise FROM temp_tblist WHERE id=9);set @val10 = (SELECT Remise FROM temp_tblist WHERE id=10);set @val11 = (SELECT Remise FROM temp_tblist WHERE id=11);set @val12 = (SELECT Remise FROM temp_tblist WHERE id=12);
    set @val13 = (SELECT Remise FROM temp_tblist WHERE id=13);set @val14 = (SELECT Remise FROM temp_tblist WHERE id=14);set @val15 = (SELECT Remise FROM temp_tblist WHERE id=15);set @val16 = (SELECT Remise FROM temp_tblist WHERE id=16);
    set @val17 = (SELECT Remise FROM temp_tblist WHERE id=17);set @val18 = (SELECT Remise FROM temp_tblist WHERE id=18);set @val19 = (SELECT Remise FROM temp_tblist WHERE id=19);set @val20 = (SELECT Remise FROM temp_tblist WHERE id=20);
    set @val21 = (SELECT Remise FROM temp_tblist WHERE id=21);set @val22 = (SELECT Remise FROM temp_tblist WHERE id=22);set @val23 = (SELECT Remise FROM temp_tblist WHERE id=23);set @val24 = (SELECT Remise FROM temp_tblist WHERE id=24);
    set @val25 = (SELECT Remise FROM temp_tblist WHERE id=25);set @val26  = (SELECT Remise FROM temp_tblist WHERE id=26);set @val27  =(SELECT Remise FROM temp_tblist WHERE id=27);set @val28  =(SELECT Remise FROM temp_tblist WHERE id=28);
    set @val29  = (SELECT Remise FROM temp_tblist WHERE id=29);set @val30  = (SELECT Remise FROM temp_tblist WHERE id=30);set @val31  = (SELECT Remise FROM temp_tblist WHERE id=31);set @val32  = (SELECT Remise FROM temp_tblist WHERE id=32);
    set @val33  = (SELECT Remise FROM temp_tblist WHERE id=33);set @val34  = (SELECT Remise FROM temp_tblist WHERE id=34);set @val35 = (SELECT Remise FROM temp_tblist WHERE id=35);set @val36 = (SELECT Remise FROM temp_tblist WHERE id=36);
    set @val37 = (SELECT Remise FROM temp_tblist WHERE id=37);set @val38 = (SELECT Remise FROM temp_tblist WHERE id=38);set @val39 = (SELECT Remise FROM temp_tblist WHERE id=39);set @val40 = (SELECT Remise FROM temp_tblist WHERE id=40);
    set @val41 = (SELECT Remise FROM temp_tblist WHERE id=41);set @val42 = (SELECT Remise FROM temp_tblist WHERE id=42);set @val43 = (SELECT Remise FROM temp_tblist WHERE id=43);set @val44 = (SELECT Remise FROM temp_tblist WHERE id=44);
    set @val45 = (SELECT Remise FROM temp_tblist WHERE id=45);set @val46 = (SELECT Remise FROM temp_tblist WHERE id=46);set @val47 = (SELECT Remise FROM temp_tblist WHERE id=47);set @val48 = (SELECT Remise FROM temp_tblist WHERE id=48);
    set @val49 = (SELECT Remise FROM temp_tblist WHERE id=49);set @val50 = (SELECT Remise FROM temp_tblist WHERE id=50);set @val51  = (SELECT Remise FROM temp_tblist WHERE id=51);
    insert into stat_by_list(TITRE_,VALEUR1_,VALEUR2_,VALEUR3_,VALEUR4_,VALEUR5_,VALEUR6_,VALEUR7_,VALEUR8_,VALEUR9_,VALEUR10_,VALEUR11_,VALEUR12_,VALEUR13_,VALEUR14_,VALEUR15_,VALEUR16_,VALEUR17_,VALEUR18_,VALEUR19_,VALEUR20_,VALEUR21_,VALEUR22_,VALEUR23_,VALEUR24_,VALEUR25_,VALEUR26_,VALEUR27_,VALEUR28_,VALEUR29_,VALEUR30_,VALEUR31_,VALEUR32_,VALEUR33_,VALEUR34_,VALEUR35_,VALEUR36_,VALEUR37_,VALEUR38_,VALEUR39_,VALEUR40_,VALEUR41_,VALEUR42_,VALEUR43_,VALEUR44_,VALEUR45_,VALEUR46_,VALEUR47_,VALEUR48_,VALEUR49_,
        VALEUR50_)
        values (@name_pays,@val1,@val2,@val3,@val4, @val5,@val6,@val7,@val8,@val9,@val10,
        @val11,@val12,@val13,@val14,@val15,@val16,@val17,@val18,@val19,@val20,
        @val21,@val22,@val23,@val24,@val25,@val26,@val27,@val28,@val29,@val30,
        @val31,@val32,@val33,@val34,@val35,@val36,@val37,@val38,@val39,@val40,
        @val41,@val42,@val43,@val44,@val45,@val46,@val47,@val48,@val49,@val50
    );
        select * from stat_by_list;
    end if;
    End

and create table

CREATE TABLE IF NOT EXISTS stat_by_list(TITRE_ VARCHAR(255),VALEUR1_ INT(11),
    VALEUR2_ INT(11),VALEUR3_ INT(11),VALEUR4_ INT(11),VALEUR5_ INT(11),
VALEUR6_ INT(11),VALEUR7_ INT(11),VALEUR8_ INT(11),VALEUR9_ INT(11),
VALEUR10_ INT(11),VALEUR11_ INT(11),VALEUR12_ INT(11),
VALEUR13_ ......,VALEUR50_ );


问:
Conditionally concatenate string values of a tuple in a list in python based on the elements
Here is the list which includes tags to the word type

```<code>t = [('The','OTHER'),('name','OTHER'),('is','OTHER'),('Wall','ORGANIZATION'),('Mart','ORGANIZATION'),('and','OTHER'),('Thomas','ORGANIZATION'),('Cook','ORGANIZATION')]
</code>```

The expectation is to conditionally check if the subsequent tuple is tagged as organization if so concatenate them with a space and continue with the same over the entire list.

Expected output:

```<code>Wall Mart, Thomas Cook

for x in t:
    if(x[1] == 'ORGANIZATION'):
         org_list = org_list + ' | ' + x[0]
</code>```

I was just able to extract the names but not really getting a way where I could concatenate the words tagged as organization.

Refereed to other Question asked: [Link]Concatenate elements of a tuple in a list in python

Expected output: Wall Mart, Thomas Cook

答:
You can use the following solution:</p>

```<code>t = [('The','OTHER'),('name','OTHER'),('is','OTHER'),('Wall','ORGANIZATION'),('Mart','ORGANIZATION'),('and','OTHER'),('Thomas','ORGANIZATION'),('Cook','ORGANIZATION')]

result = [[]]
for i, j in t:
    if j == 'ORGANIZATION':
        result[-1].append(i)
    elif result[-1]:
        result.append([])

result = [' '.join(i) for i in result if i]
# ['Wall Mart', 'Thomas Cook']
</code>```

Body:
Here is the list which includes tags to the word type

t = [('The','OTHER'),('name','OTHER'),('is','OTHER'),('Wall','ORGANIZATION'),('Mart','ORGANIZATION'),('and','OTHER'),('Thomas','ORGANIZATION'),('Cook','ORGANIZATION')]

The expectation is to conditionally check if the subsequent tuple is tagged as organization if so concatenate them with a space and continue with the same over the entire list.

Expected output:

Wall Mart, Thomas Cook

for x in t:
    if(x[1] == 'ORGANIZATION'):
         org_list = org_list + ' | ' + x[0]

I was just able to extract the names but not really getting a way where I could concatenate the words tagged as organization.

Refereed to other Question asked: [Link]Concatenate elements of a tuple in a list in python

Expected output: Wall Mart, Thomas Cook

Body:
You can use the following solution:

t = [('The','OTHER'),('name','OTHER'),('is','OTHER'),('Wall','ORGANIZATION'),('Mart','ORGANIZATION'),('and','OTHER'),('Thomas','ORGANIZATION'),('Cook','ORGANIZATION')]

result = [[]]
for i, j in t:
    if j == 'ORGANIZATION':
        result[-1].append(i)
    elif result[-1]:
        result.append([])

result = [' '.join(i) for i in result if i]
# ['Wall Mart', 'Thomas Cook']