问:
How to write a platform independent wrapper function in C++
I am using snprintf to send the output to the buffer. Using C++ 11 and for desktop application.

As of now I am doing it only for windows. But from now onwards it has to support for different platforms (Windows, Linux and Mac)

To support for multiple platforms, I am planning to write a wrapper function with #if tags.

but here the challenge I am facing is, when invoking WrapperSprintf from different places of the project the number of parameters are different.

How to write a common wrapper that can be used from different places with different no of parameters passed to WrapperSprintf function?

I tried the wrapper function like as shown below. Please help me how to proceed with this:

```<code>void WrapperSprintf( char buffer, const char *format, ... )
{
#if defined(_WIN32)
    _snprintf_s(buffer, sizeof(buffer), format,...);
#else
    snprintf(buffer, sizeof(buffer), format, ...);
#endif
}
</code>```

Calling WrapperSprintf function1:

```<code>char m_systemTime[20];

char* CUPSManager ::getSystemTime()
{
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    WrapperSprintf(m_systemTime,"%d-%d-%d :%d:%d:%d" , timeinfo ->tm_year +1900,
             timeinfo ->tm_mon +1,
             timeinfo->tm_mday,
             timeinfo->tm_hour,
             timeinfo->tm_min,
             timeinfo->tm_sec);
    return m_systemTime;
}
</code>```

Calling WrapperSprintf function2:

```<code>void getDevicePath()
{
    wstring strDevPath;
    strDevPath = (LPCWSTR)cDevicePath;
    char cDevPath[2048];
    WrapperSprintf(cDevPath,"%ls", strDevPath.c_str());
    int nPathLength = strlen(cDevPath);
...
}
</code>```

答:
How to write a platform independent wrapper function in C++?

One way is to read the C++ standard (e.g. n3337 for C++11), or choose a more recent standard such as C++17, and stick to functions mentioned there.

Another way is to write your C++ code above libraries (such as Qt or POCO or Boost or GTKmm) providing an abstraction above all platforms you want to target.

For freestanding C++ code cross-compiled then running on embedded platforms (e.g. some port of FreeNOS to RaspBerry Pi 4, or some recent Android, or to AutoSar) this could be a technical challenge.

read carefully the documentation of your C++ compiler

Choose a good enough build automation tool (e.g. GNU make or Ninja or others) to run your C++ compiler (and other programs, possibly your metaprograms).

Consider also a web interface to your C++ program.

Toolkits like Wt or Libonion come to mind (or just cpp-httplib). Most desktop operating systems today have some web browser (like Firefox, itself coded in C++).

Consider also some meta-programming approach :

Write your small programs generating C++ code helping in portability.

The SWIG generator might be useful  or inspirational (see also as examples the ANTLR parser generator, The Qt moc, the RefPerSys project, the FLTK toolkit for inspiration or search for Quine programs coded in C++). The GPP or GNU m4 preprocessors could be useful too. Your metaprogram generating C++ code might be coded in Python, Lua, Guile, or just C++, etc...

So enable warnings related to portability, if available from your C++ compiler. For GCC, read this. Consider using some static analyzer (e.g. the Clang static analyzer, or Frama-C++, or Coverity, or BugSeng or perhaps Bismon at end of 2020; see this draft report) to help you.

Remember the old adage

there is no such thing as portable code, there are just some ported software....

attribution forgotten, but I read something like that in the previous century

Body:
I am using snprintf to send the output to the buffer. Using C++ 11 and for desktop application.

As of now I am doing it only for windows. But from now onwards it has to support for different platforms (Windows, Linux and Mac)

To support for multiple platforms, I am planning to write a wrapper function with #if tags.

but here the challenge I am facing is, when invoking WrapperSprintf from different places of the project the number of parameters are different.

How to write a common wrapper that can be used from different places with different no of parameters passed to WrapperSprintf function?

I tried the wrapper function like as shown below. Please help me how to proceed with this:

void WrapperSprintf( char buffer, const char *format, ... )
{
#if defined(_WIN32)
    _snprintf_s(buffer, sizeof(buffer), format,...);
#else
    snprintf(buffer, sizeof(buffer), format, ...);
#endif
}

Calling WrapperSprintf function1:

char m_systemTime[20];

char* CUPSManager ::getSystemTime()
{
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    WrapperSprintf(m_systemTime,"%d-%d-%d :%d:%d:%d" , timeinfo ->tm_year +1900,
             timeinfo ->tm_mon +1,
             timeinfo->tm_mday,
             timeinfo->tm_hour,
             timeinfo->tm_min,
             timeinfo->tm_sec);
    return m_systemTime;
}

Calling WrapperSprintf function2:

void getDevicePath()
{
    wstring strDevPath;
    strDevPath = (LPCWSTR)cDevicePath;
    char cDevPath[2048];
    WrapperSprintf(cDevPath,"%ls", strDevPath.c_str());
    int nPathLength = strlen(cDevPath);
...
}


来源: stackexchange

问:
defining a variable in a class
I am trying to place a method in a class that will replace null values with running average of non null values. Please refer to the code below:

```<code>class ElNinoData(object):
    # Your implementation here
    add = 0
    counter = 0
    average = 0

    # methods
    def __init__(self , object):
        self.object = object

    def get_humidity(self):
        if not math.isnan(self.object['humidity']):
            global add
            global counter
            global average

            add += self.object['humidity']
            counter += 1
            average = add/counter
        else:
            self.object['humidity'] = average
        return self.object['humidity']
</code>```

While executing this class in a method, I am getting the following error:

```<code><ipython-input-40-c52c3ac6484b> in get_humidity(self)
     19             global average
     20
---> 21             add += self.object['humidity']
     22             counter += 1
     23             average = add/counter

NameError: name 'add' is not defined
</code>```

Could anyone please explain the error,I am relatively new to python?

答:
What you are missing here is that you have initialized the variables but not given them any values and then you are adding the values using +=, due to which python is throwing you this error.
Refer to the below code:-</p>

```<code>class ElNinoData(object):
# Your implementation here
    add = 0
    counter = 0
    average = 0

    # methods
    def __init__(self , object):
        self.object = object

    def get_humidity(self):
        if not math.isnan(self.object['humidity']):
            global add
            global counter
            global average
            add = 0
            counter = 1
            add += self.object['humidity']
            counter += 1
            average = add/counter
        else:
            self.object['humidity'] = average
        return self.object['humidity']
t = {'humidity' : 10}
a =ElNinoData(t)
a.get_humidity()
</code>```

ContentLicense: CC BY-SA 4.0

Title: defining a variable in a class

Body:
I am trying to place a method in a class that will replace null values with running average of non null values. Please refer to the code below:

class ElNinoData(object):
    # Your implementation here
    add = 0
    counter = 0
    average = 0

    # methods
    def __init__(self , object):
        self.object = object

    def get_humidity(self):
        if not math.isnan(self.object['humidity']):
            global add
            global counter
            global average

            add += self.object['humidity']
            counter += 1
            average = add/counter
        else:
            self.object['humidity'] = average
        return self.object['humidity']

While executing this class in a method, I am getting the following error:

<ipython-input-40-c52c3ac6484b> in get_humidity(self)
     19             global average
     20
---> 21             add += self.object['humidity']
     22             counter += 1
     23             average = add/counter

NameError: name 'add' is not defined

Could anyone please explain the error,I am relatively new to python?

Body:
What you are missing here is that you have initialized the variables but not given them any values and then you are adding the values using +=, due to which python is throwing you this error.
Refer to the below code:-

class ElNinoData(object):
# Your implementation here
    add = 0
    counter = 0
    average = 0

    # methods
    def __init__(self , object):
        self.object = object

    def get_humidity(self):
        if not math.isnan(self.object['humidity']):
            global add
            global counter
            global average
            add = 0
            counter = 1
            add += self.object['humidity']
            counter += 1
            average = add/counter
        else:
            self.object['humidity'] = average
        return self.object['humidity']
t = {'humidity' : 10}
a =ElNinoData(t)
a.get_humidity()


问:
overiding class attributes but not methods in the child class
I have this problem, for example I define a Vehicle class as such.

```<code>class Vehicle():
    speed = 0
    def __init__(self):
        pass
    def get_speed(self):
        return Vehicle.speed
</code>```

I have a class attribute speed which I will override in the Bike child class

```<code>class Bike(Vehicle):
   speed = 20
</code>```

if I instantiate a new object of type Bike I get this

```<code>>>> a = Bike()
>>> a.get_speed()
0
</code>```

How do I make it to get without having to override parent class methods.

```<code>>>> a.get_speed()
20
</code>```

I do have a solution but I don't know if it is a good programming practice or not, because instance variables should be unique to that instance, so now I am very much confused.

```<code>class Vehicle():
   def __init__(self):
      self.speed = 0

   def get_speed(self):
      return self.speed

class Bike(Vehicle):
   def __init__(self):
      self.speed = 20
</code>```

should I re-declare it as an instance variable so that if I override self.speed = 20 in the constructor then I get

```<code>>>> a = Bike()
>>> a.get_speed()
20
</code>```

Any help would be much appreciated, thanks a lot in advance.

答:
If you need get_speed to be a class-wide property (not an instance-wide), you could use @classmethod decorator:

```<code>class Vehicle():
    speed = 0
    def __init__(self):
        pass

    @classmethod
    def get_speed(cls):
        return cls.speed
</code>```

It would still be possible to override speed attribute inside a class instance though.

Body:
I have this problem, for example I define a Vehicle class as such.

class Vehicle():
    speed = 0
    def __init__(self):
        pass
    def get_speed(self):
        return Vehicle.speed

I have a class attribute speed which I will override in the Bike child class

class Bike(Vehicle):
   speed = 20

if I instantiate a new object of type Bike I get this

>>> a = Bike()
>>> a.get_speed()
0

How do I make it to get without having to override parent class methods.

>>> a.get_speed()
20

I do have a solution but I don't know if it is a good programming practice or not, because instance variables should be unique to that instance, so now I am very much confused.

class Vehicle():
   def __init__(self):
      self.speed = 0

   def get_speed(self):
      return self.speed

class Bike(Vehicle):
   def __init__(self):
      self.speed = 20

should I re-declare it as an instance variable so that if I override self.speed = 20 in the constructor then I get

>>> a = Bike()
>>> a.get_speed()
20

Any help would be much appreciated, thanks a lot in advance.

Body:
If you need get_speed to be a class-wide property (not an instance-wide), you could use @classmethod decorator:

class Vehicle():
    speed = 0
    def __init__(self):
        pass

    @classmethod
    def get_speed(cls):
        return cls.speed

It would still be possible to override speed attribute inside a class instance though.


问:
Wordpress Page always Reload Old Cache (LiteSpeed)
My Wordpress run on Google Cloud Platform using LiteSpeed WebServer, below are the specifications:

WordPress 5.4.1

PHP 7.3

OpenLiteSpeed 1.6.13

phpMyAdmin 5.0.2

MariaDB 10.4

Redis 5.0.7

Memcached 1.5.22

CertBot 0.40.0

However, after updating my page, it always reloads old page cache.

I have tried below steps:

Purge Cache, by disable / enable cache on LiteSpeed Cache Plugin. I can see notification said Purged all caches successfully.

Disable All Plugins

Reboot VPS

But still cant solve it, the old page still show.

Any Idea to solve this issue?

==Update: .htaccess

```<code>BEGIN LSCACHE
## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ##
<IfModule LiteSpeed>
RewriteEngine on
CacheLookup on
RewriteRule .* - [E=Cache-Control:no-autoflush]
### marker LOGIN COOKIE start ###
RewriteRule .? - [E="Cache-Vary:wp-postpass_07cx34bxfgxrbttrt56"]
### marker LOGIN COOKIE end ###
### marker DROPQS start ###
CacheKeyModify -qs:fbclid
CacheKeyModify -qs:gclid
CacheKeyModify -qs:utm*
CacheKeyModify -qs:_ga
### marker DROPQS end ###
</IfModule>
## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ##
# END LSCACHE
# BEGIN NON_LSCACHE
## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ##
## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ##
# END NON_LSCACHE
# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

答:
I was in a similar situation ones but at the time I was using elementor to make page changes. After making changes, saving and closing, initial results before changes would show instead of the new changes, Later realized at the time, the LiteSpeed Cache Plugin was not working well elementor. To test this,

I had to disable the cache cleaner plugin and see if the new page changes would take effect. If so,

Went forward to look for compatible cache cleaner that best works with elementor.

The issue is most commonly a certain plugin interfering with the theme, you didn't have to even edit the .htaccess file, but that's my share. Hope it somehow helps.

Body:
My Wordpress run on Google Cloud Platform using LiteSpeed WebServer, below are the specifications:

WordPress 5.4.1

PHP 7.3

OpenLiteSpeed 1.6.13

phpMyAdmin 5.0.2

MariaDB 10.4

Redis 5.0.7

Memcached 1.5.22

CertBot 0.40.0

However, after updating my page, it always reloads old page cache.

I have tried below steps:

Purge Cache, by disable / enable cache on LiteSpeed Cache Plugin. I can see notification said Purged all caches successfully.

Disable All Plugins

Reboot VPS

But still cant solve it, the old page still show.

Any Idea to solve this issue?

==Update: .htaccess

BEGIN LSCACHE
## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ##
<IfModule LiteSpeed>
RewriteEngine on
CacheLookup on
RewriteRule .* - [E=Cache-Control:no-autoflush]
### marker LOGIN COOKIE start ###
RewriteRule .? - [E="Cache-Vary:wp-postpass_07cx34bxfgxrbttrt56"]
### marker LOGIN COOKIE end ###
### marker DROPQS start ###
CacheKeyModify -qs:fbclid
CacheKeyModify -qs:gclid
CacheKeyModify -qs:utm*
CacheKeyModify -qs:_ga
### marker DROPQS end ###
</IfModule>
## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ##
# END LSCACHE
# BEGIN NON_LSCACHE
## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ##
## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ##
# END NON_LSCACHE
# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


问:
Android: Filter out an application
I am struggling with a weird problem. I have an application manifest that defines intent filters for office files, .doc, .ppt, etc. So, the user can go to an office file in a file explorer, choose open, and select my application. My application is not really a document viewer; it allows a user to extract images from a file.

Now, inside my application, I want to allow the user to view the selected office file in a document viewer. For this, I am providing an open button, which fires an ACTION_VIEW intent. When the activity chooser comes up, it displays my application also as an option because I have declared the intent filters in my manifest. In a nut shell, I do not want my application to be one of the options when my application sends the ACTION_VIEW intent.

Is there a way I can filter out my application from this chooser dialog?

Thanks,

Akshay

P.S: I cannot register for the SEND filter instead of the VIEW filter in my manifest due to my requirements.

答:
I asked this question on Android Developers and found that no easy solution exists. Fore more details, see http://groups.google.com/group/android-developers/browse_thread/thread/9e9b1007ec7ad935.

-Akshay

ContentLicense: CC BY-SA 3.0

Title: Android: Filter out an application


问:
React Native Error - TypeError: undefined is not an object (evaluating 'item.key')
I am trying to use APIs from this website for my React Native App: https://api.spacexdata.com/v2/launches

I tried to follow the APIs from the JSON formatter closely, but receive the following error and do not know how to resolve it:

```<code>TypeError: undefined is not an object (evaluating 'item.key')

This error is located at:
    in VirtualizedList (at FlatList.js:676)
    in FlatList (at App.js:42)
    in App
    in ExpoRoot (at renderApplication.js:40)
    in RCTView (at AppContainer.js:101)
    in DevAppContainer (at AppContainer.js:115)
    in RCTView (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:39)

defaultProps.keyExtractor
    VirtualizedList.js:467:15
_pushCells
    VirtualizedList.js:761:31
_pushCells
    VirtualizedList.js:759:13
render
    VirtualizedList.js:871:8
renderRoot
    [native code]:0
runRootCallback
    [native code]:0
Component.prototype.setState
    react.development.js:325:31
tryCallOne
    core.js:37:14
setImmediate$argument_0
    core.js:123:25
callImmediates
    [native code]:0
flushedQueue
    [native code]:0
invokeCallbackAndReturnFlushedQueue
    [native code]:0
</code>```

my code in App.js is as below..

```<code> import React from 'react'; import { ActivityIndicator, FlatList,
 Image, StyleSheet, Text, View } from 'react-native'; import { Card,
 CardItem, Item } from 'native-base'

 export default class App extends React.Component {

   constructor(propos) {
     super(propos);
     this.state = {
       isLoading: true,
       dataSource: []
     };   }

   getUserFromAPI = () => {
     return fetch('https://api.spacexdata.com/v2/launches')
       .then(response => response.json())
       .then(responseJson => {
         this.setState({
           isLoading: false,
           dataSource: this.state.dataSource.concat(responseJson.array)
         });
       })
       .catch(error => console.log(error));   };   _keyExtractor = (datasource, index) => datasource.id;   componentDidMount() {
     this.getUserFromAPI();   }

   render() {
     if (this.state.isLoading) {
       return (
         <View style={styles.progress}>
           <ActivityIndicator size="large" color="#01CBC6" />
         </View>

       );
     }

     return (
       <FlatList
         data={this.state.dataSource}
         _keyExtractor={this._keyExtractor}
         renderItem={({ item }) => (
           <Card>
             <CardItem>
               <View style={styles.container}>
                 <Image style={styles.profilepic}
                   source={{
                     uri: item.links.mission_patch
                     // from API docs
                   }}
                 />
               </View>
               <View style={styles.userinfo}>
                 <Text>
                   Flight Number: {item.flight_number} {", Mission Name: "} {item.mission_name}
                 </Text>
                 <Text>
                   Launch date (UTC): {item.mission_id.launch_date_utc}
                 </Text>
                 <Text>
                   {item.rocket.rocket_name}
                 </Text>
                 <Text>
                   Launch Site: {item.launch_site.site_name_long}
                 </Text>
                 <Text>
                   Details: {item.details}
                   Crew: {item.crew}
                 </Text>
               </View>
             </CardItem>
           </Card>
         )}
       />
     );   } }
</code>```

My code for styling is as below:

```<code> const styles = StyleSheet.create({   container: {
     flex: 1,
     backgroundColor: '#fff',
     alignItems: 'center',
     justifyContent: 'center'   },   profilepic: {
     flex: 2,
     height: 100,
     width: 100   },   userinfo: {
     flex: 5,
     flexDirection: 'column',
     marginStart: 50   },   progress: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center'   }

 });
</code>```

Thanks very much.

答: I think you need to change the prop on the Flatlist component from _keyExtractor={this._keyExtractor} to keyExtractor={this._keyExtractor}

Body:
I am trying to use APIs from this website for my React Native App: https://api.spacexdata.com/v2/launches

I tried to follow the APIs from the JSON formatter closely, but receive the following error and do not know how to resolve it:

TypeError: undefined is not an object (evaluating 'item.key')

This error is located at:
    in VirtualizedList (at FlatList.js:676)
    in FlatList (at App.js:42)
    in App
    in ExpoRoot (at renderApplication.js:40)
    in RCTView (at AppContainer.js:101)
    in DevAppContainer (at AppContainer.js:115)
    in RCTView (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:39)

defaultProps.keyExtractor
    VirtualizedList.js:467:15
_pushCells
    VirtualizedList.js:761:31
_pushCells
    VirtualizedList.js:759:13
render
    VirtualizedList.js:871:8
renderRoot
    [native code]:0
runRootCallback
    [native code]:0
Component.prototype.setState
    react.development.js:325:31
tryCallOne
    core.js:37:14
setImmediate$argument_0
    core.js:123:25
callImmediates
    [native code]:0
flushedQueue
    [native code]:0
invokeCallbackAndReturnFlushedQueue
    [native code]:0

my code in App.js is as below..

 import React from 'react'; import { ActivityIndicator, FlatList,
 Image, StyleSheet, Text, View } from 'react-native'; import { Card,
 CardItem, Item } from 'native-base'

 export default class App extends React.Component {

   constructor(propos) {
     super(propos);
     this.state = {
       isLoading: true,
       dataSource: []
     };   }

   getUserFromAPI = () => {
     return fetch('https://api.spacexdata.com/v2/launches')
       .then(response => response.json())
       .then(responseJson => {
         this.setState({
           isLoading: false,
           dataSource: this.state.dataSource.concat(responseJson.array)
         });
       })
       .catch(error => console.log(error));   };   _keyExtractor = (datasource, index) => datasource.id;   componentDidMount() {
     this.getUserFromAPI();   }

   render() {
     if (this.state.isLoading) {
       return (
         <View style={styles.progress}>
           <ActivityIndicator size="large" color="#01CBC6" />
         </View>

       );
     }

     return (
       <FlatList
         data={this.state.dataSource}
         _keyExtractor={this._keyExtractor}
         renderItem={({ item }) => (
           <Card>
             <CardItem>
               <View style={styles.container}>
                 <Image style={styles.profilepic}
                   source={{
                     uri: item.links.mission_patch
                     // from API docs
                   }}
                 />
               </View>
               <View style={styles.userinfo}>
                 <Text>
                   Flight Number: {item.flight_number} {", Mission Name: "} {item.mission_name}
                 </Text>
                 <Text>
                   Launch date (UTC): {item.mission_id.launch_date_utc}
                 </Text>
                 <Text>
                   {item.rocket.rocket_name}
                 </Text>
                 <Text>
                   Launch Site: {item.launch_site.site_name_long}
                 </Text>
                 <Text>
                   Details: {item.details}
                   Crew: {item.crew}
                 </Text>
               </View>
             </CardItem>
           </Card>
         )}
       />
     );   } }

My code for styling is as below:

 const styles = StyleSheet.create({   container: {
     flex: 1,
     backgroundColor: '#fff',
     alignItems: 'center',
     justifyContent: 'center'   },   profilepic: {
     flex: 2,
     height: 100,
     width: 100   },   userinfo: {
     flex: 5,
     flexDirection: 'column',
     marginStart: 50   },   progress: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center'   }

 });

Thanks very much.


问:
'DataFrame' object has no attribute 'map'
I have the following command below:

```<code>datamax['Date'] = pd.to_datetime(datamax['Date'])
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax2015["day_of_year"] = datamax["Date"].dt.dayofyear
datamaxappend = datamax2015.join(datamax,on="day_of_year",rsuffix="_new")
upper = datamaxappend.loc[datamaxappend["Data_Value_new"]<datamaxappend["Data_Value"]]

upper = upper.rename(columns={"Date_new":"Date","Data_Value_new":"Data_Value"})
lower = lower.rename(columns={"Date_new":"Date","Data_Value_new":"Data_Value"})
upper['Date'] = upper['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))
lower['Date'] = lower['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))
</code>```

However, I keep getting the error:

'DataFrame' object has no attribute 'map'

I am confused as to why this is. Could anybody help me out here?

The dataframe lower looks like this:

upper:

```<code>     Date           ID Element  Data_Value  day_of_year       Date  \
3  2015-01-04  USW00094889    TMAX          44            4 2005-01-05
4  2015-01-05  USW00094889    TMAX          28            5 2005-01-06
5  2015-01-06  USW00094889    TMAX          33            6 2005-01-07
14 2015-01-15  USW00094889    TMAX          -5           15 2005-01-16
15 2015-01-16  USW00094889    TMAX           6           16 2005-01-17

         ID_new Element_new  Data_Value  day_of_year_new
3   USW00094889        TMAX          33                5
4   USW00094889        TMAX           0                6
5   USW00094889        TMAX           6                7
14  USW00094889        TMAX         -33               16
15  USW00094889        TMAX         -50               17
</code>```

lower:

```<code>   Date           ID Element  Data_Value  day_of_year       Date  \
0 2015-01-01  USC00200032    TMIN        -133            1 2005-01-02
1 2015-01-02  USC00200032    TMIN        -122            2 2005-01-03
2 2015-01-03  USC00200032    TMIN         -67            3 2005-01-04
4 2015-01-05  USC00200032    TMIN        -155            5 2005-01-06
5 2015-01-06  USC00200032    TMIN        -182            6 2005-01-07

        ID_new Element_new  Data_Value  day_of_year_new
0  USC00200032        TMIN         -56                2
1  USC00200032        TMIN           0                3
2  USC00200032        TMIN         -39                4
4  USC00200032        TMIN        -106                6
5  USC00200032        TMIN        -111                7
</code>```

datamax:

```<code>     Date           ID Element  Data_Value  day_of_year
    0 2005-01-01  USW00094889    TMAX         156            1
    1 2005-01-02  USW00094889    TMAX         139            2
    2 2005-01-03  USW00094889    TMAX         133            3
    3 2005-01-04  USW00094889    TMAX          39            4
    4 2005-01-05  USW00094889    TMAX          33            5
</code>```

datamin:

```<code> Date           ID Element  Data_Value  day_of_year
0 2005-01-01  USC00200032    TMIN         -56            1
1 2005-01-02  USC00200032    TMIN         -56            2
2 2005-01-03  USC00200032    TMIN           0            3
3 2005-01-04  USC00200032    TMIN         -39            4
4 2005-01-05  USC00200032    TMIN         -94            5
</code>```

The dataframe data:

```<code>                 ID        Date Element  Data_Value
0       USW00094889  2014-11-12    TMAX          22
1       USC00208972  2009-04-29    TMIN          56
2       USC00200032  2008-05-26    TMAX         278
3       USC00205563  2005-11-11    TMAX         139
4       USC00200230  2014-02-27    TMAX        -106
5       USW00014833  2010-10-01    TMAX         194
6       USC00207308  2010-06-29    TMIN         144
7       USC00203712  2005-10-04    TMAX         289
8       USW00004848  2007-12-14    TMIN         -16
9       USC00200220  2011-04-21    TMAX          72
10      USC00205822  2013-01-16    TMAX          11
11      USC00205822  2008-05-29    TMIN          28
12      USC00203712  2008-10-17    TMIN          17
13      USC00205563  2006-05-14    TMAX         183
</code>```

答:
Python code which returns a line graph of the record high and record low temperatures by day of the year over the period 2005-2014. The area between the record high and record low temperatures for each day should be shaded.

Then, overlay a scatter of the 2015 data for any points (highs and lows) for which the ten year record (2005-2014) record high or record low was broken in 2015.

Remove leap year dates (i.e. 29th February).

```<code>from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt

pd.set_option("display.max_rows",None,"display.max_columns",None)
data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax = datamax.groupby('day_of_year').max()
datamin["day_of_year"] = datamin["Date"].dt.dayofyear
datamin = datamin.groupby('day_of_year').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d')
datamax['Date'] = datamax['Date'].dt.strftime('%Y-%m-%d')
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

breakoutdata = data[(data['Date']  > '2014-12-31')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamin2015['Date'] = pd.to_datetime(datamin2015['Date'])
datamax2015["day_of_year"] = datamax2015["Date"].dt.dayofyear
datamax2015 = datamax2015.groupby('day_of_year').max()
datamin2015["day_of_year"] = datamin2015["Date"].dt.dayofyear
datamin2015 = datamin2015.groupby('day_of_year').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamin2015['Date'] = datamin2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015['Date'] = datamax2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

dataminappend = datamin2015.join(datamin,on="day_of_year",rsuffix="_new")
lower = dataminappend.loc[dataminappend["Data_Value_new"]>dataminappend["Data_Value"]]
datamaxappend = datamax2015.join(datamax,on="day_of_year",rsuffix="_new")
upper = datamaxappend.loc[datamaxappend["Data_Value_new"]<datamaxappend["Data_Value"]]

upper['Date'] = pd.to_datetime(upper['Date'])
lower['Date'] = pd.to_datetime(lower['Date'])
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])

ax = plt.gca()
plt.plot(datamax['day_of_year'],datamax['Data_Value'],color='red')
plt.plot(datamin['day_of_year'],datamin['Data_Value'], color='blue')
plt.scatter(upper['day_of_year'],upper['Data_Value'],color='purple')
plt.scatter(lower['day_of_year'],lower['Data_Value'], color='cyan')

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Day of the year",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day between 2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()
</code>```

I have converted the 'Date' column to a string using Datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d').

I have then converted this back to 'datetime' format using upper['Date'] = pd.to_datetime(upper['Date'])

I then used 'date of year' as the x-value.

Body:
I have the following command below:

datamax['Date'] = pd.to_datetime(datamax['Date'])
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax2015["day_of_year"] = datamax["Date"].dt.dayofyear
datamaxappend = datamax2015.join(datamax,on="day_of_year",rsuffix="_new")
upper = datamaxappend.loc[datamaxappend["Data_Value_new"]<datamaxappend["Data_Value"]]

upper = upper.rename(columns={"Date_new":"Date","Data_Value_new":"Data_Value"})
lower = lower.rename(columns={"Date_new":"Date","Data_Value_new":"Data_Value"})
upper['Date'] = upper['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))
lower['Date'] = lower['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))

However, I keep getting the error:

'DataFrame' object has no attribute 'map'

I am confused as to why this is. Could anybody help me out here?

The dataframe lower looks like this:

upper:

     Date           ID Element  Data_Value  day_of_year       Date  \
3  2015-01-04  USW00094889    TMAX          44            4 2005-01-05
4  2015-01-05  USW00094889    TMAX          28            5 2005-01-06
5  2015-01-06  USW00094889    TMAX          33            6 2005-01-07
14 2015-01-15  USW00094889    TMAX          -5           15 2005-01-16
15 2015-01-16  USW00094889    TMAX           6           16 2005-01-17

         ID_new Element_new  Data_Value  day_of_year_new
3   USW00094889        TMAX          33                5
4   USW00094889        TMAX           0                6
5   USW00094889        TMAX           6                7
14  USW00094889        TMAX         -33               16
15  USW00094889        TMAX         -50               17

lower:

   Date           ID Element  Data_Value  day_of_year       Date  \
0 2015-01-01  USC00200032    TMIN        -133            1 2005-01-02
1 2015-01-02  USC00200032    TMIN        -122            2 2005-01-03
2 2015-01-03  USC00200032    TMIN         -67            3 2005-01-04
4 2015-01-05  USC00200032    TMIN        -155            5 2005-01-06
5 2015-01-06  USC00200032    TMIN        -182            6 2005-01-07

        ID_new Element_new  Data_Value  day_of_year_new
0  USC00200032        TMIN         -56                2
1  USC00200032        TMIN           0                3
2  USC00200032        TMIN         -39                4
4  USC00200032        TMIN        -106                6
5  USC00200032        TMIN        -111                7

datamax:

     Date           ID Element  Data_Value  day_of_year
    0 2005-01-01  USW00094889    TMAX         156            1
    1 2005-01-02  USW00094889    TMAX         139            2
    2 2005-01-03  USW00094889    TMAX         133            3
    3 2005-01-04  USW00094889    TMAX          39            4
    4 2005-01-05  USW00094889    TMAX          33            5

datamin:

 Date           ID Element  Data_Value  day_of_year
0 2005-01-01  USC00200032    TMIN         -56            1
1 2005-01-02  USC00200032    TMIN         -56            2
2 2005-01-03  USC00200032    TMIN           0            3
3 2005-01-04  USC00200032    TMIN         -39            4
4 2005-01-05  USC00200032    TMIN         -94            5

The dataframe data:

                 ID        Date Element  Data_Value
0       USW00094889  2014-11-12    TMAX          22
1       USC00208972  2009-04-29    TMIN          56
2       USC00200032  2008-05-26    TMAX         278
3       USC00205563  2005-11-11    TMAX         139
4       USC00200230  2014-02-27    TMAX        -106
5       USW00014833  2010-10-01    TMAX         194
6       USC00207308  2010-06-29    TMIN         144
7       USC00203712  2005-10-04    TMAX         289
8       USW00004848  2007-12-14    TMIN         -16
9       USC00200220  2011-04-21    TMAX          72
10      USC00205822  2013-01-16    TMAX          11
11      USC00205822  2008-05-29    TMIN          28
12      USC00203712  2008-10-17    TMIN          17
13      USC00205563  2006-05-14    TMAX         183

Body:
Python code which returns a line graph of the record high and record low temperatures by day of the year over the period 2005-2014. The area between the record high and record low temperatures for each day should be shaded.

Then, overlay a scatter of the 2015 data for any points (highs and lows) for which the ten year record (2005-2014) record high or record low was broken in 2015.

Remove leap year dates (i.e. 29th February).

from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt

pd.set_option("display.max_rows",None,"display.max_columns",None)
data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax = datamax.groupby('day_of_year').max()
datamin["day_of_year"] = datamin["Date"].dt.dayofyear
datamin = datamin.groupby('day_of_year').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d')
datamax['Date'] = datamax['Date'].dt.strftime('%Y-%m-%d')
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

breakoutdata = data[(data['Date']  > '2014-12-31')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamin2015['Date'] = pd.to_datetime(datamin2015['Date'])
datamax2015["day_of_year"] = datamax2015["Date"].dt.dayofyear
datamax2015 = datamax2015.groupby('day_of_year').max()
datamin2015["day_of_year"] = datamin2015["Date"].dt.dayofyear
datamin2015 = datamin2015.groupby('day_of_year').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamin2015['Date'] = datamin2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015['Date'] = datamax2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

dataminappend = datamin2015.join(datamin,on="day_of_year",rsuffix="_new")
lower = dataminappend.loc[dataminappend["Data_Value_new"]>dataminappend["Data_Value"]]
datamaxappend = datamax2015.join(datamax,on="day_of_year",rsuffix="_new")
upper = datamaxappend.loc[datamaxappend["Data_Value_new"]<datamaxappend["Data_Value"]]

upper['Date'] = pd.to_datetime(upper['Date'])
lower['Date'] = pd.to_datetime(lower['Date'])
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])

ax = plt.gca()
plt.plot(datamax['day_of_year'],datamax['Data_Value'],color='red')
plt.plot(datamin['day_of_year'],datamin['Data_Value'], color='blue')
plt.scatter(upper['day_of_year'],upper['Data_Value'],color='purple')
plt.scatter(lower['day_of_year'],lower['Data_Value'], color='cyan')

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Day of the year",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day between 2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()

I have converted the 'Date' column to a string using Datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d').

I have then converted this back to 'datetime' format using upper['Date'] = pd.to_datetime(upper['Date'])

I then used 'date of year' as the x-value.


问:
Object property lose null after descruction
Why is that y became string type only after object descruction?

```<code>const obj: { x: string; y: string | null } = {} as any

const { x, y } = obj // y is string now
</code>```

答: Set strictNullChecks as true in your tsconfig.json, see https://www.typescriptlang.org/tsconfig#strictNullChecks.

Body:
Why is that y became string type only after object descruction?

const obj: { x: string; y: string | null } = {} as any

const { x, y } = obj // y is string now


问:
BeautifulSoup.select Method
This script is suppose to take command line string and run it through the google search engine and then if results are found it will open up the first 5 in different tabs. I am having some issues trying to get it to work. I think the problem is happening towards the bottom where it says link = soup.select(".r a"), I have been altering the values here and then it will show the next line with an actual length. But running it like this shows the length to still be 0. I am trying to scrape the .r class and a tag because that seems to be where the searched results start on the google result source code.

```<code>import requests
import bs4
import sys
import webbrowser

print("Googling...")
response = requests.get("https://www.google.com/#q=" + " ".join(sys.argv[1:]))
response.raise_for_status()

'''Function to return the top search result links'''
soup = bs4.BeautifulSoup(response.text, "html.parser")

'''Open a browser tab for each result'''
links = soup.select(".r a")
print(len(links))
numOpen = min(5, len(links))

for i in range(numOpen):
    webbrowser.open("https://google.com/#q=" + links[i].get("href"))
</code>```

答:
You are right! The problem should be resulted from select(".r a")
I suggest you try find_all('a',{"data-uch":1}), which will find all a tags with attribute data-uch = 1

Explanation:

"If you look up a little from the  element, though, there is an element like this: . Looking through the rest of the HTML source,
it looks like the r class is used only for search result links."

The sentence above is from the book. However, in real, if you print this soup variable, soup = bs4.BeautifulSoup(response.text, "html.parser"), you will not find any
`` in the HTML source code. That is whyprint(len(links))``` always show 0.

Title: BeautifulSoup.select Method

Body:
This script is suppose to take command line string and run it through the google search engine and then if results are found it will open up the first 5 in different tabs. I am having some issues trying to get it to work. I think the problem is happening towards the bottom where it says link = soup.select(".r a"), I have been altering the values here and then it will show the next line with an actual length. But running it like this shows the length to still be 0. I am trying to scrape the .r class and a tag because that seems to be where the searched results start on the google result source code.

import requests
import bs4
import sys
import webbrowser

print("Googling...")
response = requests.get("https://www.google.com/#q=" + " ".join(sys.argv[1:]))
response.raise_for_status()

'''Function to return the top search result links'''
soup = bs4.BeautifulSoup(response.text, "html.parser")

'''Open a browser tab for each result'''
links = soup.select(".r a")
print(len(links))
numOpen = min(5, len(links))

for i in range(numOpen):
    webbrowser.open("https://google.com/#q=" + links[i].get("href"))

Body:
You are right! The problem should be resulted from select(".r a")
I suggest you try find_all('a',{"data-uch":1}), which will find all a tags with attribute data-uch = 1

Explanation:

"If you look up a little from the  element, though, there is an element like this: . Looking through the rest of the HTML source,
it looks like the r class is used only for search result links."

The sentence above is from the book. However, in real, if you print this soup variable, soup = bs4.BeautifulSoup(response.text, "html.parser"), you will not find any <h3 class="r">`` in the HTML source code. That is whyprint(len(links))``` always show 0.


问:
Python set comparison is operator
I am trying to compare two sets

```<code>#logical operators

set1 = {1,2,3,4,5,6}

set2 = {1,2,3,4,5,6,7}

# is operator
is_set1_set2_same = set1 is set2

print(is_set1_set2_same)
</code>```

This result is as expected "False"

```<code>set2.remove(7)
is_set1_set2_same = set1 is set2

print(is_set1_set2_same)
</code>```

Question : I was expecting the output of this one should be "True", but i see its "False" , When I print two sets i see exactly same. Please let me know if i am missing something here on sets.

```<code>set3 = set1

is_set1_set3_same =  set1 is set3

print(is_set1_set3_same)
</code>```

This results as expected "True"

答:
is is not a set operator - it is an operator for object references.

set3 = set1 will be making the set3 object reference the same as object set1, therefore is will be True always, regardless of the type of object.

To compare set equality, you must check if they are proper subsets of one another

```<code>sets_same = (set1 <= set2) and (set2 <= set1)
</code>```

Title: Python set comparison is operator

Body:
I am trying to compare two sets

#logical operators

set1 = {1,2,3,4,5,6}

set2 = {1,2,3,4,5,6,7}

# is operator
is_set1_set2_same = set1 is set2

print(is_set1_set2_same)

This result is as expected "False"

set2.remove(7)
is_set1_set2_same = set1 is set2

print(is_set1_set2_same)

Question : I was expecting the output of this one should be "True", but i see its "False" , When I print two sets i see exactly same. Please let me know if i am missing something here on sets.

set3 = set1

is_set1_set3_same =  set1 is set3

print(is_set1_set3_same)

This results as expected "True"

Body:
is is not a set operator - it is an operator for object references.

set3 = set1 will be making the set3 object reference the same as object set1, therefore is will be True always, regardless of the type of object.

To compare set equality, you must check if they are proper subsets of one another

sets_same = (set1 <= set2) and (set2 <= set1)


问:
Python - Plot a graph with times on x-axis
I have the following dataframe in pandas:

```<code>dfClicks = pd.DataFrame({'clicks': [700,800,550],'date_of_click': ['10/25/1995
03:30','10/25/1995 04:30','10/25/1995 05:30']})

dfClicks['date_of_click'] = pd.to_datetime(dfClicks['date_of_click'])

dfClicks.set_index('date_of_click')

dfClicks.clicks = pd.to_numeric(dfClicks.clicks)
</code>```

Could you please advise how I can plot the above such that the x-axis shows the date/time and the y axis the number of clicks? I will also need to plot another data frame which includes predicted clicks on the same graph, just to compare. The test could be a replica of above, with minor changes:

```<code>dfClicks2 = pd.DataFrame({'clicks': [750,850,500],'date_of_click': ['10/25/1995
    03:30','10/25/1995 04:30','10/25/1995 05:30']})

dfClicks2['date_of_click'] = pd.to_datetime(dfClicks2['date_of_click'])

dfClicks2.set_index('date_of_click')

dfClicks2.clicks = pd.to_numeric(dfClicks2.clicks)
</code>```

答:
Change to numeric the column clicks and then:

```<code>ax = dfClicks.plot()
dfClicks2.plot(ax=ax)
ax.legend(["Clicks","Clicks2"])
</code>```

Output:

UPDATE:
There is an error in how you set the index, change

```<code>dfClicks.set_index('date_of_click')
</code>```

with:

```<code>dfClicks = dfClicks.set_index('date_of_click')
</code>```

Body:
I have the following dataframe in pandas:

dfClicks = pd.DataFrame({'clicks': [700,800,550],'date_of_click': ['10/25/1995
03:30','10/25/1995 04:30','10/25/1995 05:30']})

dfClicks['date_of_click'] = pd.to_datetime(dfClicks['date_of_click'])

dfClicks.set_index('date_of_click')

dfClicks.clicks = pd.to_numeric(dfClicks.clicks)

Could you please advise how I can plot the above such that the x-axis shows the date/time and the y axis the number of clicks? I will also need to plot another data frame which includes predicted clicks on the same graph, just to compare. The test could be a replica of above, with minor changes:

dfClicks2 = pd.DataFrame({'clicks': [750,850,500],'date_of_click': ['10/25/1995
    03:30','10/25/1995 04:30','10/25/1995 05:30']})

dfClicks2['date_of_click'] = pd.to_datetime(dfClicks2['date_of_click'])

dfClicks2.set_index('date_of_click')

dfClicks2.clicks = pd.to_numeric(dfClicks2.clicks)

Body:
Change to numeric the column clicks and then:

ax = dfClicks.plot()
dfClicks2.plot(ax=ax)
ax.legend(["Clicks","Clicks2"])

Output:

UPDATE:
There is an error in how you set the index, change

dfClicks.set_index('date_of_click')

with:

dfClicks = dfClicks.set_index('date_of_click')


问:
CSS delay when Laravel mail function is used
I am using Laravel 6. I have a button which gets triggered when it has been clicked. The click event does two things. It adds a css class to the button which shows an animated svg spinner to indicate that something is loading and it sends information to my controller which sends an e-mail.
The spinner class is set as soon as the button is clicked, but the problem is that the spinner is only shown when the mail has been sent. But I want the spinner to be shown while the gets sent so the user knows that he has to wait.

This is my .spinner class

```<code>.spinner {
background-image: url(storage/app/public/img/spinner.svg);
background-size: 100% 100%;
height: 40px;
width: 40px;
}
</code>```

This is the button from my child component which can be clicked:

```<code><button class="btn btn-success teamplayerButton" @click="addSpinner($event.target); $emit('del-match', match.id);">Add
</button>
</code>```

The addSpinner method on the child component:

```<code>addSpinner(match) {
match.classList.toggle('spinner');
match.innerText = "";
}
</code>```

The parent component gets the emitted match.id and makes a get request to a route which sends a mail like this:

```<code>Mail::to($email)->send(new ReceivedInvitation(Auth::user()->name, $receiverName));
</code>```

Here is a short video to show you what I mean.
click here

Why does the css depends on what php(laravel) on the backend does?
The css gets set instant but the animation is shown after a few seconds.
When I remove the call of the mail function in my controller, and try it again, the spinner is shown instantly.

答:
It would appear that the CSS changes instantly, but the actual image isn't  being loaded until after the AJAX call finishes.

I would check your network tab to understand how the spinner file is being loaded, and see if its being blocked for some reason by the AJAX call. If it isn't just a static file, something else might be going on.

Body:
I am using Laravel 6. I have a button which gets triggered when it has been clicked. The click event does two things. It adds a css class to the button which shows an animated svg spinner to indicate that something is loading and it sends information to my controller which sends an e-mail.
The spinner class is set as soon as the button is clicked, but the problem is that the spinner is only shown when the mail has been sent. But I want the spinner to be shown while the gets sent so the user knows that he has to wait.

This is my .spinner class

.spinner {
background-image: url(storage/app/public/img/spinner.svg);
background-size: 100% 100%;
height: 40px;
width: 40px;
}

This is the button from my child component which can be clicked:

<button class="btn btn-success teamplayerButton" @click="addSpinner($event.target); $emit('del-match', match.id);">Add
</button>

The addSpinner method on the child component:

addSpinner(match) {
match.classList.toggle('spinner');
match.innerText = "";
}

The parent component gets the emitted match.id and makes a get request to a route which sends a mail like this:

Mail::to($email)->send(new ReceivedInvitation(Auth::user()->name, $receiverName));

Here is a short video to show you what I mean.
click here

Why does the css depends on what php(laravel) on the backend does?
The css gets set instant but the animation is shown after a few seconds.
When I remove the call of the mail function in my controller, and try it again, the spinner is shown instantly.


问:
get array values in python
I have the values arr1  as 25,26 and arr2 values as A,B

Its always that the number of values in arr1 and arr2 are equal

My question is that

```<code>          for i in arr1.split(","):
                print i //prints 25 and 26
</code>```

is it not possible to get the values of arr2 in the same loop or should  another loop be written only for this purpose.Basically the idea is that map the values of arr1 and arr2

答:
You should be able to do this with python's enumerate function.  This lets you loop through a list and get both its numerical index and its value:

```<code>array1 = arr1.split(',')
array2 = arr2.split(',')
for i,value in enumerate(array1):
   print value, array2[i]
</code>```

This produces:

```<code>25 A
26 B
</code>```

Title: get array values in python

Body:
I have the values arr1  as 25,26 and arr2 values as A,B

Its always that the number of values in arr1 and arr2 are equal

My question is that

          for i in arr1.split(","):
                print i //prints 25 and 26

is it not possible to get the values of arr2 in the same loop or should  another loop be written only for this purpose.Basically the idea is that map the values of arr1 and arr2

Body:
You should be able to do this with python's enumerate function.  This lets you loop through a list and get both its numerical index and its value:

array1 = arr1.split(',')
array2 = arr2.split(',')
for i,value in enumerate(array1):
   print value, array2[i]

This produces:

25 A
26 B


问:
Flutter old app upgrading to use it today
I've found this code for flutter home automation application.
but it was wrote in an older version of flutter, which i tried many times to start it but i couldn't make it,
last best thing that i have ever came to was that i could could mergrated the application to Android X and the application was starting but when i try to sign up a new mail inside it it says,
Error fetching data.
It dosen't use Firebase to store email it just uses a SQL package.
if any one can help to git the code and upgrade it for me to use it i will be very thankful :D.
Here is the link,
https://github.com/mlinarevicMateo/home-automation-flutter</p>

答:
As the project was created in an older version of flutter you might be missing some latest flutter modules you can add those to your existing project by running this command within your project directory.

flutter create .


问:
How to use Java property files?
I have a list of key/value pairs of configuration values I want to store as Java property files, and later load and iterate through.

Questions:

Do I need to store the file in the same package as the class which will load them, or is there any specific location where it should be placed?

Does the file need to end in any specific extension or is .txt OK?

How can I load the file in the code

And how can I iterate through the values inside?

答:
in my opinion other ways are deprecated when we can do it very simple as below:

```<code>@PropertySource("classpath:application.properties")
public class SomeClass{

    @Autowired
    private Environment env;

    public void readProperty() {
        env.getProperty("language");
    }

}
</code>```

it is so simple but i think that's the best way!!
Enjoy

Title: How to use Java property files?

Body:
in my opinion other ways are deprecated when we can do it very simple as below:

@PropertySource("classpath:application.properties")
public class SomeClass{

    @Autowired
    private Environment env;

    public void readProperty() {
        env.getProperty("language");
    }

}

it is so simple but i think that's the best way!!
Enjoy


问:
LearnYouNode: Juggling Async without BL/Async/After
I was following this tutorial when a wild step 9 appears.

This problem is the same as the previous problem (HTTP COLLECT) in that you need to use http.get(). However, this time you will be provided with three URLs as the first three command-line arguments.

You must collect the complete content provided to you by each of the URLs and print it to the console (stdout). You don't need to print out the length, just the data as a String; one line per URL. The catch is that you must print them out in the same order as the URLs are provided to you as command-line arguments.

My code was (It doesn't work fine just when he pleases):

```<code>http = require("http");
var url = [process.argv[2], process.argv[3], process.argv[4]];
var responses = [];
var completed_responses = 0;

for(var i in url){
    http.get(url[i], function(response){
        var content = "";
        //if(completed_responses == url.length){
                response.setEncoding("utf-8");
                response.on("data", function(data){
                    content += data;
                })
                response.on("error", console.error);
                response.on("end", function(end){
                    console.log(content);
                });

    })
}
</code>```

And the answer was:

```<code>var http = require("http");
var bl = require("bl");
var results = [];
var count = 0;

function printResults(){
    for(var i = 0; i < 3; i++)
        console.log(results[i]);
}

function httpGet(index){
    http.get(process.argv[2 + index], function(response){
        response.pipe(bl(function(err, data){
            if (err)
                return console.error(err);

            results[index] = data.toString();
            count++;

            if(count == 3)
                printResults()
        }))
    })
}

for(var i = 0; i < 3; i++)
    httpGet(i);
</code>```

What is the right answer WITHOUT BL/AFTER/ETC?

Thanks to all!

答:
This is how you can do it without any external modules(except http ;P).

const http = require('http'); //http module

let results = ["", "", ""]; //this will store the data from http.get()
let counter = 0; //to keep a counter for no of httpget's done

//it will iterate when counter is 3 i.e. the 'end' for all
function print() {
  for (let i = 0; i < 3; i++) {
    console.log(results[i]);
  }
}

//accept index(for process.argv) as parameter
function httpGetter(i) {
  //http.get method on the url first encountered, 2+i because 2 values are reserved
  http.get(process.argv[2 + i], (res) => {
    //for converting (res)ponse to string/alternatively toString() method can be used
    res.setEncoding('utf8');
    //event data on the url, callback with recived chunk as parameter
    res.on('data', function(chunk) {
      //appending the recived chunk to that element of results corresponding to 'i' of httpGetter function
      results[i] += chunk;
    });
    //event end, when no more data is read
    //runs every time for each value of 'i' that is for each url
    res.on('end', function() {
      //to keep count
      counter++;
      //when 3 that is when data from all inputs receved
      if (counter === 3) {
        //print function simply iterating over results array
        print();
      }
    });
  })
}

//inputs are recieved from here
for (let i = 0; i < 3; i++) {
  //i can be index for results
  httpGetter(i);
}```

Body:
I was following this tutorial when a wild step 9 appears.

This problem is the same as the previous problem (HTTP COLLECT) in that you need to use http.get(). However, this time you will be provided with three URLs as the first three command-line arguments.

You must collect the complete content provided to you by each of the URLs and print it to the console (stdout). You don't need to print out the length, just the data as a String; one line per URL. The catch is that you must print them out in the same order as the URLs are provided to you as command-line arguments.

My code was (It doesn't work fine just when he pleases):

http = require("http");
var url = [process.argv[2], process.argv[3], process.argv[4]];
var responses = [];
var completed_responses = 0;

for(var i in url){
    http.get(url[i], function(response){
        var content = "";
        //if(completed_responses == url.length){
                response.setEncoding("utf-8");
                response.on("data", function(data){
                    content += data;
                })
                response.on("error", console.error);
                response.on("end", function(end){
                    console.log(content);
                });

    })
}

And the answer was:

var http = require("http");
var bl = require("bl");
var results = [];
var count = 0;

function printResults(){
    for(var i = 0; i < 3; i++)
        console.log(results[i]);
}

function httpGet(index){
    http.get(process.argv[2 + index], function(response){
        response.pipe(bl(function(err, data){
            if (err)
                return console.error(err);

            results[index] = data.toString();
            count++;

            if(count == 3)
                printResults()
        }))
    })
}

for(var i = 0; i < 3; i++)
    httpGet(i);

What is the right answer WITHOUT BL/AFTER/ETC?

Thanks to all!


问:
How to add multiple key and value for search object array
I have function code for search data in array, it goes well but in one key and one value. what I want is an array search with multiple key and value, that work like query and in sql.

My question: How to add multiple key and value in my function code?

Array Data:

```<code>[{
    "id": 1,
    "name": "John",
    "addres": {
      "code": 1,
      "status": 1
    }
  },
  {
    "id": 2,
    "name": "Jery",
    "addres": {
      "code": 2,
      "status": 1
    }
  }
]
</code>```

My Function code:

```<code>function where(prop, value) {
  var filtered = [], checkStatus = 0;
  for (var i = 0; i < data.length; i++) {
    var obj = data[i];
    for (var key in obj) {
      var item = obj[key];
      if (typeof(obj[key] == "object")) {
        if (item[prop] == value) {
          checkStatus = 1;
          filtered.push(obj);
        }
        if (typeof(value) == "string") {
          if (item[prop] != undefined
            && item[prop].toLowerCase().includes(value.toLowerCase())) {
            checkStatus = 1;
            filtered.push(obj);
          }
        }
      }
    }
    if (checkStatus == 0 && obj[prop] != undefined) {
      if (obj[prop] == value) {
        filtered.push(obj);
      }
      if (typeof(obj[prop]) == 'string') {
        if (obj[prop] != undefined
          && obj[prop].toLowerCase().includes(value.toLowerCase())) {
          filtered.push(obj);
        }
      }
    }
  }
  return filtered;
}
</code>```

Its work when where('status',1) but what i want where(['id','status'],[2,1])

答:
Sorry everyone, I tried and was successful

function where(value) {
  var result = data.filter(function(o) {
    return Object.keys(value).every(function(p) {
      if (typeof(o[p]) == 'object') {
        return Object.keys(value[p]).some(function(opo) {
          if (typeof(value[p][opo]) == 'string') {
            return o[p][opo].toLowerCase().includes(value[p][opo].toLowerCase());
          } else {
            return o[p][opo] == value[p][opo];
          }
        });
      } else if (typeof(o[p]) == 'string') {
        return o[p].toLowerCase().includes(value[p].toLowerCase());
      } else {
        return o[p] == value[p];
      }
    });
  });
  return result;
}
```

Thank you for giving me advice on using object, for calling where({id:2,addres:{status:1}})

Body:
I have function code for search data in array, it goes well but in one key and one value. what I want is an array search with multiple key and value, that work like query and in sql.

My question: How to add multiple key and value in my function code?

Array Data:

[{
    "id": 1,
    "name": "John",
    "addres": {
      "code": 1,
      "status": 1
    }
  },
  {
    "id": 2,
    "name": "Jery",
    "addres": {
      "code": 2,
      "status": 1
    }
  }
]

My Function code:

function where(prop, value) {
  var filtered = [], checkStatus = 0;
  for (var i = 0; i < data.length; i++) {
    var obj = data[i];
    for (var key in obj) {
      var item = obj[key];
      if (typeof(obj[key] == "object")) {
        if (item[prop] == value) {
          checkStatus = 1;
          filtered.push(obj);
        }
        if (typeof(value) == "string") {
          if (item[prop] != undefined
            && item[prop].toLowerCase().includes(value.toLowerCase())) {
            checkStatus = 1;
            filtered.push(obj);
          }
        }
      }
    }
    if (checkStatus == 0 && obj[prop] != undefined) {
      if (obj[prop] == value) {
        filtered.push(obj);
      }
      if (typeof(obj[prop]) == 'string') {
        if (obj[prop] != undefined
          && obj[prop].toLowerCase().includes(value.toLowerCase())) {
          filtered.push(obj);
        }
      }
    }
  }
  return filtered;
}

Its work when where('status',1) but what i want where(['id','status'],[2,1])

Body:
Sorry everyone, I tried and was successful

function where(value) {
  var result = data.filter(function(o) {
    return Object.keys(value).every(function(p) {
      if (typeof(o[p]) == 'object') {
        return Object.keys(value[p]).some(function(opo) {
          if (typeof(value[p][opo]) == 'string') {
            return o[p][opo].toLowerCase().includes(value[p][opo].toLowerCase());
          } else {
            return o[p][opo] == value[p][opo];
          }
        });
      } else if (typeof(o[p]) == 'string') {
        return o[p].toLowerCase().includes(value[p].toLowerCase());
      } else {
        return o[p] == value[p];
      }
    });
  });
  return result;
}

Thank you for giving me advice on using object, for calling where({id:2,addres:{status:1}})


问:
Using Docker with Python shows an error loading libpython3.8.so.1.0
I was working on a Flask project of mine and when I booted my PC the next day it wouldn't run anymore. I tried reinstalling Docker and even reinstalling my OS (Ubuntu) and this error still shows up even with a basic example Hello World Python project. Here is the output from trying to build a simple Hello World project:

```<code># docker build -t hello-world .
Sending build context to Docker daemon  4.608kB
Step 1/6 : FROM python:3.8
 ---> 659f826fabf4
Step 2/6 : WORKDIR /usr/src/app
 ---> Using cache
 ---> 5e381e0b49f2
Step 3/6 : COPY requirements.txt ./
 ---> Using cache
 ---> 4d46722cff64
Step 4/6 : RUN pip install --no-cache-dir -r requirements.txt
 ---> Running in 305e14db0fa2
/usr/local/bin/python: error while loading shared libraries: libpython3.8.so.1.0: cannot open shared object file: No such file or directory
The command '/bin/sh -c pip install --no-cache-dir -r requirements.txt' returned a non-zero code: 127
</code>```

The Dockerfile:

```<code>FROM python:3.8

WORKDIR /usr/src/app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD [ "python", "./run.py" ]
</code>```

run.py

```<code>print("Hello World")
</code>```

And the requirements.txt is empty. It was working yesterday and I've been really struggling to figure out why it's not working now.

答: Using apt instead of snap for installing Docker fixed it for me.</p>

Body:
I was working on a Flask project of mine and when I booted my PC the next day it wouldn't run anymore. I tried reinstalling Docker and even reinstalling my OS (Ubuntu) and this error still shows up even with a basic example Hello World Python project. Here is the output from trying to build a simple Hello World project:

# docker build -t hello-world .
Sending build context to Docker daemon  4.608kB
Step 1/6 : FROM python:3.8
 ---> 659f826fabf4
Step 2/6 : WORKDIR /usr/src/app
 ---> Using cache
 ---> 5e381e0b49f2
Step 3/6 : COPY requirements.txt ./
 ---> Using cache
 ---> 4d46722cff64
Step 4/6 : RUN pip install --no-cache-dir -r requirements.txt
 ---> Running in 305e14db0fa2
/usr/local/bin/python: error while loading shared libraries: libpython3.8.so.1.0: cannot open shared object file: No such file or directory
The command '/bin/sh -c pip install --no-cache-dir -r requirements.txt' returned a non-zero code: 127

The Dockerfile:

FROM python:3.8

WORKDIR /usr/src/app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD [ "python", "./run.py" ]

run.py

print("Hello World")

And the requirements.txt is empty. It was working yesterday and I've been really struggling to figure out why it's not working now.


问:
Spring Integration @MessagingGateway multiple replies for a single request
I am trying to create an application able to subscribe to external legacy/non-spring server, with the use of Spring Integration. I am using both AbstractServerConnectionFactory and AbstractClientConnectionFactory. The problem is that after I send the message which enables subscription I receive more than one reply (one ack for subscription, then a message every x minutes containing subscription data), for a single request. It seems like @Gateway is not suitable for such case, so I tried to somehow redirect the replies to @MessageEndpoint by setting the request channel on TcpInboudGateway and reply channel TcpOutboundGateway to be the same. This did not help and I can not get rid of TcpOutboundGateway Cannot corelate response - no pending reply for .... I tried to remove CachingClientConnectionFactory and use pure AbstractClientConnectionFactory, but it also did not help. Every single request and single response calls are working fine. Also, I am able to send any packets to my app and they are handled just fine.

Tried to solve this for many days, but I am still stuck with it. After all this time I assume it must be the problem with @MessagingGateway and @Gateway methods within it not being able to handle more than one reply, nor delegating it to @MessageEndpoint. Is there any way to get rid of @MessagingGateway and using something capable of doing mentioned operation? Maybe there is a way of using @Header to free the @Gateway methods for handling any replies? Searched in Spring Integration samples on github and in the documnetation, but did not find answers for those questions.

答:
Gateways are specifically designed for 1 request/1 reply messaging.

To achieve arbitrary bi-directional messaging between client and server, you can use a pair of Collaborating Channel Adapters.

... You can also use collaborating adapters (server-side or client-side) for totally asynchronous communication (rather than with request-reply semantics). On the server side, message correlation is automatically handled by the adapters, because the inbound adapter adds a header that allows the outbound adapter to determine which connection to use when sending the reply message. ...


问:
ERROR 2013 (HY000) trying to import mariadb database
I am migrating a nextcloud server from a raspberry pi 3 running raspian stretch to an rpi 4 running raspian buster. One step is to dump a mariadb database and import in on the new server. I created a dump of the mariadb database (the database dump file is 120MB) and am tyring to restore it with the following commands:

```<code>mysql -h localhost -u nextcloud -p<password> -e "CREATE DATABASE nextcloud"

mysql -h localhost -uroot -p<password> -e "GRANT ALL PRIVILEGES on nextcloud.* to nextcloud@localhost"

mysql -h localhost -u nextcloud -p<password> nextcloud < <backup_db_file>
</code>```

However, I get the following error:

```<code>ERROR 2013 (HY000) at line 746: Lost connection to MySQL server during query
</code>```

Bsed on google searching, I tried modifying my mariadb configuration file in /etc/mysql/my.cnf so it is like this:

```<code># The MariaDB configuration file
#
# The MariaDB/MySQL tools read configuration files in the following order:
# 1. "/etc/mysql/mariadb.cnf" (this file) to set global defaults,
# 2. "/etc/mysql/conf.d/*.cnf" to set global options.
# 3. "/etc/mysql/mariadb.conf.d/*.cnf" to set MariaDB-only options.
# 4. "~/.my.cnf" to set user-specific options.
#
# If the same option is defined multiple times, the last one will apply.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.

#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]

# Import all .cnf files from configuration directory
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mariadb.conf.d/

[mysqld]
max_allowed_packet = 160M
net_read_timeout = 300
net_write_timeout = 600
innodb_buffer_pool_size = 2G

[mysqldump]
max_allowed_packet = 160M
</code>```

But I get the same error. Can anyone suggest what I might be doing wrong, or how I can work around this?

The raspberry pi 4 has 4 GB of ram in case it's relevant

答: So, actually, I rebooted the server, and after that the database could be imported. I thought the new settings would be picked up when I restarted the mysql service, which I certainly attempted to do before rebooting. </p>

Body:
I am migrating a nextcloud server from a raspberry pi 3 running raspian stretch to an rpi 4 running raspian buster. One step is to dump a mariadb database and import in on the new server. I created a dump of the mariadb database (the database dump file is 120MB) and am tyring to restore it with the following commands:

mysql -h localhost -u nextcloud -p<password> -e "CREATE DATABASE nextcloud"

mysql -h localhost -uroot -p<password> -e "GRANT ALL PRIVILEGES on nextcloud.* to nextcloud@localhost"

mysql -h localhost -u nextcloud -p<password> nextcloud < <backup_db_file>

However, I get the following error:

ERROR 2013 (HY000) at line 746: Lost connection to MySQL server during query

Bsed on google searching, I tried modifying my mariadb configuration file in /etc/mysql/my.cnf so it is like this:

# The MariaDB configuration file
#
# The MariaDB/MySQL tools read configuration files in the following order:
# 1. "/etc/mysql/mariadb.cnf" (this file) to set global defaults,
# 2. "/etc/mysql/conf.d/*.cnf" to set global options.
# 3. "/etc/mysql/mariadb.conf.d/*.cnf" to set MariaDB-only options.
# 4. "~/.my.cnf" to set user-specific options.
#
# If the same option is defined multiple times, the last one will apply.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.

#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]

# Import all .cnf files from configuration directory
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mariadb.conf.d/

[mysqld]
max_allowed_packet = 160M
net_read_timeout = 300
net_write_timeout = 600
innodb_buffer_pool_size = 2G

[mysqldump]
max_allowed_packet = 160M

But I get the same error. Can anyone suggest what I might be doing wrong, or how I can work around this?

The raspberry pi 4 has 4 GB of ram in case it's relevant


问:
Avoid checkbox on top of clickable div
I have a clickable div with a checkbox inside it.

```<code><div class="card" onclick="location.href = 'www.google.com'">
 <input type="checkbox" class="selectable-item" />
</div
</code>```

How do I avoid onclick on the checkbox. Maybe with javascript

https://jsfiddle.net/m64tqfdj/

答:
Here you're dealing with event bubling, which means that the event will propagate to the containing DOM elements of what you click.

The solution is to use .stopPropagation like this

```<code><script>
 function clickHereOnly(event) {
    event.stopPropagation()
 }
</script>

<div class="card" onclick="location.href = 'www.google.com'">
  <div >
    <input type="checkbox" onclick="clickHereOnly(event)" class="selectable-item" id="media_1"/>
    <label for="media_1"></label>
  </div>
  <h3>John</h3>
</div>
</code>```

Title: Avoid checkbox on top of clickable div

Body:
I have a clickable div with a checkbox inside it.

 <input type="checkbox" class="selectable-item" />
</div

How do I avoid onclick on the checkbox. Maybe with javascript

https://jsfiddle.net/m64tqfdj/

Body:
Here you're dealing with event bubling, which means that the event will propagate to the containing DOM elements of what you click.

The solution is to use .stopPropagation like this

<script>
 function clickHereOnly(event) {
    event.stopPropagation()
 }
</script>

<div class="card" onclick="location.href = 'www.google.com'">
  <div >
    <input type="checkbox" onclick="clickHereOnly(event)" class="selectable-item" id="media_1"/>
    <label for="media_1"></label>
  </div>
  <h3>John</h3>
</div>


问:
Getting two buttons next to each other
I am having a problem with my design.

I have two buttons on my product page. However because one is in a form, they are on top of each other(see image ).

I want to get the two buttons next to each other. Can someone help me out, please ? Below I added my HTML and CSS code.

Thanks in advance!

HTML:

```<code><!DOCTYPE HTML>
<div class="container text-center">
            <div class="sale">
                <h1>On Sale</h1>
                <p class="text-secondary">
                    We have new sales promotions online for a short period of time every day. We offer products from
                    popular labels and luxury brands in the lifestyle segment up to 75% cheaper than the
                    recommended retail price.
                </p>
            </div>
</div>

        <section class="on-sale">
            <div class="container">
                <div class="row">

                <?php
                    for($i = 0; $i < $countProductItems && $i < 4; $i++){
                        ?>
                        <div class="col-md-3">
                        <div class="product-top">
                        <a href="products/product-page.php?product=<?php echo ($saleProducts[$i]['strProductNaam']); ?>" onclick="POST"><img src="<?php echo ($saleProducts[$i]['imgProduct1']);?>" class="img-fluid" alt="Product1"/></a>
                            <div class="overlay-right text-center">
                                <button type="button" class="btn btn-secondary" title="Quick Shop">
                                <a href="products/product-page.php?product=<?php echo ($saleProducts[$i]['strProductNaam']); ?>" onclick="POST"><i class="fa fa-eye text-white"></i></a>
                                </button>
                                <form action="includes/shopping-cart.inc.php?action=add&id=<?php echo ($saleProducts[$i]['ID'])?>" method="post">
                                    <input class="text-center" type="hidden" name="quantity" value="1"/>
                                    <input type="hidden" name="index-page" value="index">
                                    <input type="hidden" name="product-name" value="<?php echo ($saleProducts[$i]['strProductNaam']); ?>">
                                    <input type="hidden" name="product-price" value="<?php echo ($saleProducts[$i]['strSalePrijs']); ?>">
                                    <button type="submit" class="btn btn-secondary " title="Add to cart" name="add_to_cart"><i class="fa fa-shopping-cart"></i></button>
                                </form>
                            </div>
                        </div>
                        <div class="product-bottom text-center">
                        <p>
                                <?php rating_star(($saleProducts[$i]['RatingStar'])) ?>
                            </p>
                            <p><h3><?php echo ($saleProducts[$i]['strProductNaam']); ?></h3></p>
                            <?php sale_product(($saleProducts[$i]['intPrijs']), ($saleProducts[$i]['strSalePrijs']))?>
                        </div>
                    </div>
                    <?php
                    }
                ?>

                </div>
            </div>
        </section>
</html>
</code>```

CSS:

```<code>.container .sale{
    padding: 3rem 0;
    }

    .container .sale{
        font-family: var(--gugi);
    }

    .container .sale{
        padding: 0.5% 25%;
        font-size: 0.9em;
    }

.on-sale{
    margin: 50px 0;
}

.on-sale img{
    width: 100%;
    padding: 20px;
    transition: 1s;
    cursor: pointer;
}

.on-sale img:hover{
    transform: scale(1.1);
}

.product-top{
    width:100%;
    display: inline-block;

}

.product-bottom .fa{
    color: orange;
    font-size: 10px;
}

.product-bottom h3{
    font-size: 20px;
    font-weight: bold;
}

.product-bottom h5{
    font-size: 15px;
    padding-bottom: 10px;
}

.make_red {
        color: red;
}
</code>```

// codefilling text[error] - nfnjsnfjsfnbjkdsnfdsfndjsfbjabsdjhbgdgabadsg

答:
You can try this as well--</p>

```<code>button {
  display: inline;
  margin: auto;
  padding: 5px;
}
</code>```

Title: Getting two buttons next to each other

Body:
I am having a problem with my design.

I have two buttons on my product page. However because one is in a form, they are on top of each other(see image ).

I want to get the two buttons next to each other. Can someone help me out, please ? Below I added my HTML and CSS code.

Thanks in advance!

HTML:

<!DOCTYPE HTML>

On Sale

                    We have new sales promotions online for a short period of time every day. We offer products from
                    popular labels and luxury brands in the lifestyle segment up to 75% cheaper than the
                    recommended retail price.

                <?php
                    for($i = 0; $i < $countProductItems && $i < 4; $i++){
                        ?>

                        <a href="products/product-page.php?product=<?php echo ($saleProducts[$i]['strProductNaam']); ?>" onclick="POST"><img src="<?php echo ($saleProducts[$i]['imgProduct1']);?>" class="img-fluid" alt="Product1"/>

                                <button type="button" class="btn btn-secondary" title="Quick Shop">
                                <a href="products/product-page.php?product=<?php echo ($saleProducts[$i]['strProductNaam']); ?>" onclick="POST">
                                </button>
                                <form action="includes/shopping-cart.inc.php?action=add&id=<?php echo ($saleProducts[$i]['ID'])?>" method="post">
                                    <input class="text-center" type="hidden" name="quantity" value="1"/>
                                    <input type="hidden" name="index-page" value="index">
                                    <input type="hidden" name="product-name" value="<?php echo ($saleProducts[$i]['strProductNaam']); ?>">
                                    <input type="hidden" name="product-price" value="<?php echo ($saleProducts[$i]['strSalePrijs']); ?>">
                                    <button type="submit" class="btn btn-secondary " title="Add to cart" name="add_to_cart"></button>
                                </form>

                                <?php rating_star(($saleProducts[$i]['RatingStar'])) ?>

<?php echo ($saleProducts[$i]['strProductNaam']); ?>

                            <?php sale_product(($saleProducts[$i]['intPrijs']), ($saleProducts[$i]['strSalePrijs']))?>

                    <?php
                    }
                ?>

CSS:

.container .sale{
    padding: 3rem 0;
    }

    .container .sale{
        font-family: var(--gugi);
    }

    .container .sale{
        padding: 0.5% 25%;
        font-size: 0.9em;
    }

.on-sale{
    margin: 50px 0;
}

.on-sale img{
    width: 100%;
    padding: 20px;
    transition: 1s;
    cursor: pointer;
}

.on-sale img:hover{
    transform: scale(1.1);
}

.product-top{
    width:100%;
    display: inline-block;

}

.product-bottom .fa{
    color: orange;
    font-size: 10px;
}

.product-bottom h3{
    font-size: 20px;
    font-weight: bold;
}

.product-bottom h5{
    font-size: 15px;
    padding-bottom: 10px;
}

.make_red {
        color: red;
}

// codefilling text[error] - nfnjsnfjsfnbjkdsnfdsfndjsfbjabsdjhbgdgabadsg

Body:
You can try this as well--

button {
  display: inline;
  margin: auto;
  padding: 5px;
}


问:
whats the logic behind the following loop?
please anyone explain me the logic behind this piece of looping.</p>

```<code>public static void main(String[] args) {
    int number = 0;

    while (true) {
        number = number + 1;

        if (number >= 5) {
            break;
        }

        if (number < 5) {
            continue;
        }

        System.out.print(number + " ");
    }

    System.out.print(number + " ");
}
</code>```

答:
while(true) means an infinite loop and it will only break; the loop if(number >= 5) is true.

continue; means to ignore the succeeding commands and proceed to the next loop, therefore print function at the bottom of the loop will only execute if(number<5) is false (but will never happen because of the break; command above)

when the loop exits, the number's last value will be printed.

Body:
please anyone explain me the logic behind this piece of looping.

public static void main(String[] args) {
    int number = 0;

    while (true) {
        number = number + 1;

        if (number >= 5) {
            break;
        }

        if (number < 5) {
            continue;
        }

        System.out.print(number + " ");
    }

    System.out.print(number + " ");
}


问:
FCM throws 401 after some time for data message notification
I am sending data message notification from Java app server to the FCM rest endpoint. Everything works fine, data messages are received by the app without any issues,  however after some time (without any noticeable trend) ,  FCM stars returning 401. I am using Apache common's HTTPClient library to make the http callss. This is the relevant code snippet

```<code>final HttpPost httpPost = new HttpPost("https://fcm.googleapis.com/v1/projects/proj1/messages:send");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer "+ accessToken);
responseBody = httpclient.execute(httpPost, responseHandler);
</code>```

And this snippet is for getting the access token for API authorization

```<code> static{
             FileInputStream refreshToken = null;
             refreshToken = new FileInputStream("C:/prj/proserviceaccoutkey.json");
             googleCredentials=GoogleCredentials.fromStream(refreshToken).createScoped("https://www.googleapis.com/auth/firebase.messaging");
             options = new FirebaseOptions.Builder() .setCredentials(googleCredentials).build();
    }

// Gets called each time a data message needs to be sent
  public static synchronized String getAccessToken()
    {
        if(googleCredentials.getAccessToken()==null)
            try {
                googleCredentials.refresh();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return googleCredentials.getAccessToken().getTokenValue();
    }
</code>```

答:
looks like googleCredentials.getAccessToken() will always return non-null, even when the cahce token in no longer valid, and this is why token was not getting refreshed in the code. Applied the following fix, and it's working now.

```<code>public static synchronized String getAccessToken()
    {
        if(googleCredentials!=null)
            try {
                googleCredentials.refresh();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return googleCredentials.getAccessToken().getTokenValue();
    }
</code>```

Though, it's not really utilizing the cached token, as every time it will be refreshing the token, but my issue has been rsolved for now.

Body:
I am sending data message notification from Java app server to the FCM rest endpoint. Everything works fine, data messages are received by the app without any issues,  however after some time (without any noticeable trend) ,  FCM stars returning 401. I am using Apache common's HTTPClient library to make the http callss. This is the relevant code snippet

final HttpPost httpPost = new HttpPost("https://fcm.googleapis.com/v1/projects/proj1/messages:send");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer "+ accessToken);
responseBody = httpclient.execute(httpPost, responseHandler);

And this snippet is for getting the access token for API authorization

 static{
             FileInputStream refreshToken = null;
             refreshToken = new FileInputStream("C:/prj/proserviceaccoutkey.json");
             googleCredentials=GoogleCredentials.fromStream(refreshToken).createScoped("https://www.googleapis.com/auth/firebase.messaging");
             options = new FirebaseOptions.Builder() .setCredentials(googleCredentials).build();
    }

// Gets called each time a data message needs to be sent
  public static synchronized String getAccessToken()
    {
        if(googleCredentials.getAccessToken()==null)
            try {
                googleCredentials.refresh();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return googleCredentials.getAccessToken().getTokenValue();
    }

Body:
looks like googleCredentials.getAccessToken() will always return non-null, even when the cahce token in no longer valid, and this is why token was not getting refreshed in the code. Applied the following fix, and it's working now.

public static synchronized String getAccessToken()
    {
        if(googleCredentials!=null)
            try {
                googleCredentials.refresh();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return googleCredentials.getAccessToken().getTokenValue();
    }

Though, it's not really utilizing the cached token, as every time it will be refreshing the token, but my issue has been rsolved for now.


问:
plt.plot categorical axis overcrowded
I'm currently plotting a data frame which consists of 119 observations that represent recycling rates (float) by country (categorical). I've tried to make a scatter plot and a bar plot, but both times encountered overcrowding of the categorical y-axis.

I thought it was possible to make the axis bigger or increase space between categories, but didn't manage to find anything helpful. Could you explain to me how to improve code so that all countries on the y-axis are observable?

Attached is MWE (though it is ultimately simple), the plt.plot() output, and dataset.info().

MWE:

```<code>plt.plot(
    rr_data['r_rate'],
    rr_data['country'],
    '.',
    color='red')
plt.title('Recycling rates by country')
plt.ylabel('Countrycode')
plt.xlabel('Waste recycled, %')
</code>```

Info:

```<code><class 'pandas.core.frame.DataFrame'>
Int64Index: 119 entries, 0 to 120
Data columns (total 2 columns):
country    119 non-null object
r_rate     119 non-null float64
dtypes: float64(1), object(1)
memory usage: 2.8+ KB
</code>```

Plot:
rr_by_country

答:
There are several ways you can define the size of the figure. For example:

```<code>fig, ax = plt.subplot(figsize=(10, 10))
ax.plot(rr_data['r_rate'], rr_data['country'], figsize(10,10),'.',color='red')
</code>```

OR

```<code>plt.plot(rr_data['r_rate'], rr_data['country'], figsize(10,10),'.',color='red')
</code>```

OR

```<code>fig, ax = plt.subplots()
ax.plot(...)

fig.set_size_inches(width,height)
</code>```

Title: plt.plot categorical axis overcrowded

Body:
I'm currently plotting a data frame which consists of 119 observations that represent recycling rates (float) by country (categorical). I've tried to make a scatter plot and a bar plot, but both times encountered overcrowding of the categorical y-axis.

I thought it was possible to make the axis bigger or increase space between categories, but didn't manage to find anything helpful. Could you explain to me how to improve code so that all countries on the y-axis are observable?

Attached is MWE (though it is ultimately simple), the plt.plot() output, and dataset.info().

MWE:

plt.plot(
    rr_data['r_rate'],
    rr_data['country'],
    '.',
    color='red')
plt.title('Recycling rates by country')
plt.ylabel('Countrycode')
plt.xlabel('Waste recycled, %')

Info:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 119 entries, 0 to 120
Data columns (total 2 columns):
country    119 non-null object
r_rate     119 non-null float64
dtypes: float64(1), object(1)
memory usage: 2.8+ KB

Plot:
rr_by_country

Body:
There are several ways you can define the size of the figure. For example:

fig, ax = plt.subplot(figsize=(10, 10))
ax.plot(rr_data['r_rate'], rr_data['country'], figsize(10,10),'.',color='red')

OR

plt.plot(rr_data['r_rate'], rr_data['country'], figsize(10,10),'.',color='red')

OR

fig, ax = plt.subplots()
ax.plot(...)

fig.set_size_inches(width,height)


问:
angular event bind can I create own attribute in HTML and send it to the class file
```<code> <div>
        <input type="text" value="myInputText"  (click)=onAddCart($event)>
        <button (click)=onAddCart($event) value="car" myvalue="bike">Car</button>
    </div>

     onAddCart(event:any){
        console.log(event.target.myvalue);
        }
</code>```

Questions

I am getting undefined

Can I create the own attribute in HTML and send it class file

is it a good practice of angular

答: from your code nothing is clear and can you please be more specific about the requirment ,it seems you are trying to achieve event emit using output() but code and question is not complete</p>

Body:
        <input type="text" value="myInputText"  (click)=onAddCart($event)>
        <button (click)=onAddCart($event) value="car" myvalue="bike">Car</button>

     onAddCart(event:any){
        console.log(event.target.myvalue);
        }

Questions

I am getting undefined

Can I create the own attribute in HTML and send it class file

is it a good practice of angular


问:
python boto3 text to speech 'polly'
i'm using python 3 and when i try to run my code, i get an error: </p>

```<code>    raise NoRegionError()
botocore.exceptions.NoRegionError: You must specify a region.
</code>```

<p>my code: </p>

```<code>import boto3

client = boto3.client('polly')

output = client.synthesize_speech (
  Text = "Some random text I want to convert", OutputFormat = "mp3", VoiceId = 'Aditi'
)

print(output['AudioStream'])

file = open('speech.mp3', 'wb')
file.write(output['AudioStream'].read())
file.close()
</code>```

答:
You need to try and add the region name somewhere in the client class.

I.E

```<code>polly_client = boto3.Session(
                aws_access_key_id=,
    aws_secret_access_key=,
    region_name='us-west-2').client('polly')
</code>```

This doesn't necessarily what you intended, but you get the point. the region must be included somewhere

Title: python boto3 text to speech 'polly'

Body:
i'm using python 3 and when i try to run my code, i get an error:

    raise NoRegionError()
botocore.exceptions.NoRegionError: You must specify a region.

my code:

import boto3

client = boto3.client('polly')

output = client.synthesize_speech (
  Text = "Some random text I want to convert", OutputFormat = "mp3", VoiceId = 'Aditi'
)

print(output['AudioStream'])

file = open('speech.mp3', 'wb')
file.write(output['AudioStream'].read())
file.close()

Body:
You need to try and add the region name somewhere in the client class.

I.E

polly_client = boto3.Session(
                aws_access_key_id=,
    aws_secret_access_key=,
    region_name='us-west-2').client('polly')

This doesn't necessarily what you intended, but you get the point. the region must be included somewhere


问:
Nested if or switch case statement
From the point of view of optimizing the code run time, is there a thumb rule for where to use "nested if" statement and when to use "switch case" statements ?</p>

答:
If you have more than 2-3 comparisons
then "switch"
else "if"

try to apply some patterns before you go to switch like strategy...

Title: Nested if or switch case statement