问:
Worker cannot connect to docker swarm manager
I have setup the docker swarm manager in one machine with IP 192.168.XXX.XXX by using this command :

docker swarm init  --advertise-addr=192.168.XXX.XXX
and I got this message :

```<code>To add a worker to this swarm, run the following command:

docker swarm join --token SWMTKN-1-
0jpgak7bm7t4mzluz48gdub06f5036q8yaoo99awkjmlz48vtb-
1eutz0k1vp37ztmiuxdnglka2 192.168.XXX.XXX:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.
</code>```

In other machine I tried the following command :

```<code>docker swarm join --token SWMTKN-1-
0jpgak7bm7t4mzluz48gdub06f5036q8yaoo99awkjmlz48vtb-
1eutz0k1vp37ztmiuxdnglka2 192.168.XXX.XXX:2377
</code>```

and the result was :

```<code>error response from daemon : rpc error : code = Unavailable desc = all
SubConns are in TransientFailure, latest connection error: connection error
: desc = "transport: Error while dialing dial tcp 192.168.XXX.XXX:2377 :
connect: connection refused
</code>```

Docker version :

```<code>Client: Docker Engine - Community
 Version:           18.09.0
 API version:       1.39
 Go version:        go1.10.4
 Git commit:        4d60db4
 Built:             Wed Nov  7 00:47:51 2018
 OS/Arch:           windows/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.0
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.4
  Git commit:       4d60db4
  Built:            Wed Nov  7 00:55:00 2018
  OS/Arch:          linux/amd64
  Experimental:     false
</code>```

答:
This is a connection refused error you are running into. Most likely, the other machine cannot connect to the manager as it is not on the same network. Solution: To fix this, the two machines have to be able to talk to each other. If the machines are in a cloud like Azure or AWS create a virtual network and add the two machines to it.

Debugging connection refused error:

To confirm the machines cannot talk to each other, try pinging the manager from the other machine. It will most likely fail in your current setup.

```<code>$ ping 192.168.XXX.XXX
</code>```

If it succeeds then check if port 2377 is open and listening on the manager. Run below from the other machine:

```<code>$ nc -vz 192.168.XXX.XXX 2377
</code>```

Another tool that can help in debugging is to run netstat on the manager:

```<code>$ netstat -tuplen
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       User       Inode      PID/Program name
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      101        51772227   -
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      0          25361290   -
tcp6       0      0 :::2377                 :::*                    LISTEN      0          1423965    -
tcp6       0      0 :::7946                 :::*                    LISTEN      0          1423980    -
</code>```

Verify you see :::2377 and :::7946 and that their state is set to LISTEN as these ports are required by docker swarm [1]

Body:
I have setup the docker swarm manager in one machine with IP 192.168.XXX.XXX by using this command :

docker swarm init  --advertise-addr=192.168.XXX.XXX
and I got this message :

To add a worker to this swarm, run the following command:

docker swarm join --token SWMTKN-1-
0jpgak7bm7t4mzluz48gdub06f5036q8yaoo99awkjmlz48vtb-
1eutz0k1vp37ztmiuxdnglka2 192.168.XXX.XXX:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

In other machine I tried the following command :

docker swarm join --token SWMTKN-1-
0jpgak7bm7t4mzluz48gdub06f5036q8yaoo99awkjmlz48vtb-
1eutz0k1vp37ztmiuxdnglka2 192.168.XXX.XXX:2377

and the result was :

error response from daemon : rpc error : code = Unavailable desc = all
SubConns are in TransientFailure, latest connection error: connection error
: desc = "transport: Error while dialing dial tcp 192.168.XXX.XXX:2377 :
connect: connection refused

Docker version :

Client: Docker Engine - Community
 Version:           18.09.0
 API version:       1.39
 Go version:        go1.10.4
 Git commit:        4d60db4
 Built:             Wed Nov  7 00:47:51 2018
 OS/Arch:           windows/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.0
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.4
  Git commit:       4d60db4
  Built:            Wed Nov  7 00:55:00 2018
  OS/Arch:          linux/amd64
  Experimental:     false

Body:
This is a connection refused error you are running into. Most likely, the other machine cannot connect to the manager as it is not on the same network. Solution: To fix this, the two machines have to be able to talk to each other. If the machines are in a cloud like Azure or AWS create a virtual network and add the two machines to it.

Debugging connection refused error:

To confirm the machines cannot talk to each other, try pinging the manager from the other machine. It will most likely fail in your current setup.

$ ping 192.168.XXX.XXX

If it succeeds then check if port 2377 is open and listening on the manager. Run below from the other machine:

$ nc -vz 192.168.XXX.XXX 2377

Another tool that can help in debugging is to run netstat on the manager:

$ netstat -tuplen
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       User       Inode      PID/Program name
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      101        51772227   -
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      0          25361290   -
tcp6       0      0 :::2377                 :::*                    LISTEN      0          1423965    -
tcp6       0      0 :::7946                 :::*                    LISTEN      0          1423980    -

Verify you see :::2377 and :::7946 and that their state is set to LISTEN as these ports are required by docker swarm [1]


来源: stackexchange

问:
Matplotlib multiprocessing fonts corruption using savefig
I have troubles with multiprocessing in Matplotlib since version 1.5.  The fonts are randomly jumping around their original position. Example is here:

The simple example to reproduce this bug is here:

```<code>import multiprocessing
import matplotlib.pyplot as plt

fig = plt.figure()

def plot(i):
    fig = plt.gcf()
    plt.plot([],[])
    fig.savefig('%d.png' % i)

plot(0)
pool = multiprocessing.Pool(4)
pool.map(plot, range(10))
</code>```

if the order of multiprocessing and simple plotting is reversed

```<code>pool = multiprocessing.Pool(4)
plot(0)
pool.map(plot, range(10))
</code>```

then it works, but this workaround is useless for my purpose.

Thank you.

答: The solution to this is to place your matplotlib imports inside the function you're passing to multiprocessing.

ContentLicense: CC BY-SA 3.0

Body:
I have troubles with multiprocessing in Matplotlib since version 1.5.  The fonts are randomly jumping around their original position. Example is here:

The simple example to reproduce this bug is here:

import multiprocessing
import matplotlib.pyplot as plt

fig = plt.figure()

def plot(i):
    fig = plt.gcf()
    plt.plot([],[])
    fig.savefig('%d.png' % i)

plot(0)
pool = multiprocessing.Pool(4)
pool.map(plot, range(10))

if the order of multiprocessing and simple plotting is reversed

pool = multiprocessing.Pool(4)
plot(0)
pool.map(plot, range(10))

then it works, but this workaround is useless for my purpose.

Thank you.

ContentLicense: CC BY-SA 4.0


问:
JButton is drawing behind an image
I am making a starting screen, and it's working out pretty fine, got a background image when it starts, now I am trying to draw a JButton on the startmenu, which is a JFrame. But when I run my program, the button appears behind the background picture. If I hover above the area where the button is placed, it's flickering, and when I click it that happens too. Is there any way to draw the Button INFRONT of the background? I made the button as last in the code. My code to draw the background and button:

```<code>    public void drawStartScreen(){
    startScreenOn = true;
    Graphics2D b = buffer.createGraphics();
    b.setColor( Color.WHITE );
    b.fillRect(0, 0, 800, 600);
    b.drawImage(start,0,0,null);

    setLayout( null );
    button = new JButton("Start Game");
    button.setBounds(10,10,100,100);
    button.setVisible( true );
    add(button);
}
</code>```

It draws the image first, and then the Button, but the button still draws behind the image.

答:
Override the paint method on the JFrame:

```<code>@Override
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D b = (Graphics2D)g;
    b.setColor( Color.WHITE );
    b.fillRect(0, 0, 800, 600);
    b.drawImage(start.getImage(),0,0,null);
    b.dispose();
}
</code>```

Notice that this calls paint() on the parent and dispose() on the graphics context when done.  I just tried this code and it worked for me.

Title: JButton is drawing behind an image

Body:
I am making a starting screen, and it's working out pretty fine, got a background image when it starts, now I am trying to draw a JButton on the startmenu, which is a JFrame. But when I run my program, the button appears behind the background picture. If I hover above the area where the button is placed, it's flickering, and when I click it that happens too. Is there any way to draw the Button INFRONT of the background? I made the button as last in the code. My code to draw the background and button:

    public void drawStartScreen(){
    startScreenOn = true;
    Graphics2D b = buffer.createGraphics();
    b.setColor( Color.WHITE );
    b.fillRect(0, 0, 800, 600);
    b.drawImage(start,0,0,null);

    setLayout( null );
    button = new JButton("Start Game");
    button.setBounds(10,10,100,100);
    button.setVisible( true );
    add(button);
}

It draws the image first, and then the Button, but the button still draws behind the image.

Body:
Override the paint method on the JFrame:

@Override
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D b = (Graphics2D)g;
    b.setColor( Color.WHITE );
    b.fillRect(0, 0, 800, 600);
    b.drawImage(start.getImage(),0,0,null);
    b.dispose();
}

Notice that this calls paint() on the parent and dispose() on the graphics context when done.  I just tried this code and it worked for me.


问:
Best way to check for mongoose validation error
I've got two validation functions for my usermodel

```<code>User.schema.path('email').validate(function(value, respond) {
  User.findOne({email: value}, function(err, user) {
    if(err) throw err;
    if(user) return respond(false);
    respond(true);
  });
}, 'EMAIL_EXISTS');
</code>```

and the same for username

```<code>User.schema.path('username').validate(function(value, respond) {
  User.findOne({username: value}, function(err, user) {
    if(err) throw err;
    if(user) return respond(false);
    respond(true);
  });
}, 'USERNAME_TAKEN');
</code>```

They return errors in the following format

```<code>{ message: 'Validation failed',
  name: 'ValidationError',
  errors:
    { username:
      { message: 'Validator "USERNAME_TAKEN" failed for path username',
        name: 'ValidatorError',
        path: 'username',
        type: 'USERNAME_TAKEN' } } }
</code>```

The error for the email path is similar. Is there a smarter way to check for those errors than the following?

```<code>if (err && err.errors && err.errors.username) { ... }
</code>```

This is kind of ugly.

答:
Approach #1

My Best Guess for this approach is to use generalized validator with promise based returns,
hope it may help down the road

```<code>function validateDoc(model,fieldName) {
  return new Promise((resolve, reject) => {
    model.validate(err => {
      if (err) {
        return reject(err.errors[fieldName]);
      } else {
        return resolve(model);
      }
    });
  })
}

// Access error message in catch() or get the validated doc in then()

validateDoc(model,fieldName)
           .then((model) => console.log(model))
           .catch((message) => console.warn(message))
</code>```

Approach #2

```<code>const userSchema = new Schema({
  name: {
    type:String,
    required:[true,'Name is required.'],
    validate:{
      validator:(name) => { name.length <= 2 }
      message:'Name must be longer than two characters'
    }
  }
})
const User = mongoose.model('user',userSchema)
</code>```

Use the validate:Object inside schema with validator:function and message:String

Later when u will try to save the record it will thow the validation error object in the catch function

For Example

```<code>const newUser = new User({ name: undefined });

newUser.save().catch( ( { errors } ) => {

let errorBag = [];

Object.keys(errors).forEach((fieldName) => {

errorBag.push({ [fieldName]:errors[fieldName].message })

});

 // All the errors with the **fieldName** and  **errorMessages**

console.log(errorBag);

   })
</code>```

Body:
I've got two validation functions for my usermodel

User.schema.path('email').validate(function(value, respond) {
  User.findOne({email: value}, function(err, user) {
    if(err) throw err;
    if(user) return respond(false);
    respond(true);
  });
}, 'EMAIL_EXISTS');

and the same for username

User.schema.path('username').validate(function(value, respond) {
  User.findOne({username: value}, function(err, user) {
    if(err) throw err;
    if(user) return respond(false);
    respond(true);
  });
}, 'USERNAME_TAKEN');

They return errors in the following format

{ message: 'Validation failed',
  name: 'ValidationError',
  errors:
    { username:
      { message: 'Validator "USERNAME_TAKEN" failed for path username',
        name: 'ValidatorError',
        path: 'username',
        type: 'USERNAME_TAKEN' } } }

The error for the email path is similar. Is there a smarter way to check for those errors than the following?

if (err && err.errors && err.errors.username) { ... }

This is kind of ugly.

Body:
Approach #1

My Best Guess for this approach is to use generalized validator with promise based returns,
hope it may help down the road

function validateDoc(model,fieldName) {
  return new Promise((resolve, reject) => {
    model.validate(err => {
      if (err) {
        return reject(err.errors[fieldName]);
      } else {
        return resolve(model);
      }
    });
  })
}

// Access error message in catch() or get the validated doc in then()

validateDoc(model,fieldName)
           .then((model) => console.log(model))
           .catch((message) => console.warn(message))

Approach #2

const userSchema = new Schema({
  name: {
    type:String,
    required:[true,'Name is required.'],
    validate:{
      validator:(name) => { name.length <= 2 }
      message:'Name must be longer than two characters'
    }
  }
})
const User = mongoose.model('user',userSchema)

Use the validate:Object inside schema with validator:function and message:String

Later when u will try to save the record it will thow the validation error object in the catch function

For Example

const newUser = new User({ name: undefined });

newUser.save().catch( ( { errors } ) => {

let errorBag = [];

Object.keys(errors).forEach((fieldName) => {

errorBag.push({ [fieldName]:errors[fieldName].message })

});

 // All the errors with the **fieldName** and  **errorMessages**

console.log(errorBag);

   })


问:
MERN Stack: Using Redux to store whether user is logged in or not
I'm new to backend programming and building my first full stack project and using Express/Mongoose/Mongo and Passport.js for the first time.

I have built "sign in with Github" functionality and have everything with Passport set up. Now I want to use Redux to store whether or not a user is logged in. If the user is logged in I want to change my navigation bar i.e. if the user isn't logged in one link says "log in", but if the user is logged in the "log in" link changes to "profile".

I know I can use the ternary operator in my React component to toggle the link depending on whether the user is logged in.

How do I use Redux to store whether a user is logged in? Here's what I have so far:

Redux action:

```<code>export function loggedIn() {
    return {
      type: "LOGGED_IN",
      loggedIn: false
    }
};
</code>```

Redux reducer:

```<code>export default function reducer(state = {
  loggedIn: false
}, action) {
  switch(action.type) {
    case "LOGGED_IN": {
      return {
        ...state,
        loggedIn: true
      }
    }
    case "LOGGED_OUT": {
      return {
        ...state,
        loggedIn: false
      }
    }
    default: return state;
  }

}
</code>```

I'm my Express route I am using the following middleware:

```<code>// Checks if user is not logged in
const authCheck = (req, res, next) => {
    if(!req.user) {
      // If user is not logged in, redirect them to login page
      res.redirect('/auth/login');
    }
    else {
      // If user is logged in call next in router.get

      // Would this be the proper place to dispatch to the Redux store
      // whether a user is logged in?
      dispatch(loggedIn(true));
      // After updating the Redux store call next()
      next();
    }
};
</code>```

How can I properly store in state whether the user is logged in/out and then access this state in the React component so I can use the ternary operator to choose whether to display "logged in" or "profile" in my navigation bar?

答:
You should just handle your authentication state in your react frontend. Even if your are doing server side auth, its better to just have the authentication state saved in your React frontend with Redux. In your react app:

You will also need to use the react-redux library to connect react with redux

Actions

```<code>export const login_success = () => {
  return {
    type: ACTION_TYPES.LOGIN_SUCCESS
  }
}

export const login_failure = () => {
  return {
    type: ACTION_TYPES.LOGIN_FAILURE
  }
}
</code>```

reducer:

```<code>const initialState = {
  isAuthenticated: false,

}

const AuthReducer = (state= initialState, action) => {
  switch(action.type) {
    case ACTION_TYPES.LOGIN_SUCCESS:
      return {
        ...state,
        isAuthenticated: true
      }
    case ACTION_TYPES.LOGIN_FAILURE:
      return {
        ...state,
        isAuthenticated: false
      }
}
</code>```

Access the auth state with props

```<code> {this.props.isAuthenticated
         ? <h3> user is logged in </h3>
         : <h3> user is not logged in </h3>
       }

function mapStateToProps(state) {
  return {
     isAuthenticated: state.auth_reducer.isAuthenticated
  }
}
</code>```

Implement this in a callback component that is rendered after the user signs in.

```<code>function mapDispatchToProps(dispatch) {
  return {
    action1: () => dispatch(ACTIONS.LOGIN_SUCCESS),
  }
}
</code>```

If you want a fully functioning example of how to do this you can check out this project I built, it is a full stack react express app with authentication

https://github.com/iqbal125/react-redux-fullstack-blog

To give you some tough love, it seems to me you dont fully understand Redux, I would suggest mastering Redux before trying to build a complex full stack app, just a suggestion.

Edit:

Communication with server can be done with a proxy, so in your package.json in your react app you can do:

```<code>"proxy": http://localhost:5000"
</code>```

or wherever your node server is running. You can also just send back a server response to your React frontend, anything at all, then  update your React-Redux frontend based on that server response.

So in your express server

```<code>router.get('api/login', (req, res) => {
  if(res.login === true) {
    res.json(success_login: true)
  }
})
</code>```

then in your react frontend

```<code>axios.get('/api/login')
  .then(res => this.props.login_success(res.data) )

login_success(res) {
  if(res.success_login === true) {
    type: "SUCCESS_LOGIN"
}
</code>```

So essentially you will not handle any routing or redux authentication state in your express server. Your server will send a response to your react frontend and then the routing and redux authentication state will be handled by your frontend.

Body:
I'm new to backend programming and building my first full stack project and using Express/Mongoose/Mongo and Passport.js for the first time.

I have built "sign in with Github" functionality and have everything with Passport set up. Now I want to use Redux to store whether or not a user is logged in. If the user is logged in I want to change my navigation bar i.e. if the user isn't logged in one link says "log in", but if the user is logged in the "log in" link changes to "profile".

I know I can use the ternary operator in my React component to toggle the link depending on whether the user is logged in.

How do I use Redux to store whether a user is logged in? Here's what I have so far:

Redux action:

export function loggedIn() {
    return {
      type: "LOGGED_IN",
      loggedIn: false
    }
};

Redux reducer:

export default function reducer(state = {
  loggedIn: false
}, action) {
  switch(action.type) {
    case "LOGGED_IN": {
      return {
        ...state,
        loggedIn: true
      }
    }
    case "LOGGED_OUT": {
      return {
        ...state,
        loggedIn: false
      }
    }
    default: return state;
  }

}

I'm my Express route I am using the following middleware:

// Checks if user is not logged in
const authCheck = (req, res, next) => {
    if(!req.user) {
      // If user is not logged in, redirect them to login page
      res.redirect('/auth/login');
    }
    else {
      // If user is logged in call next in router.get

      // Would this be the proper place to dispatch to the Redux store
      // whether a user is logged in?
      dispatch(loggedIn(true));
      // After updating the Redux store call next()
      next();
    }
};

How can I properly store in state whether the user is logged in/out and then access this state in the React component so I can use the ternary operator to choose whether to display "logged in" or "profile" in my navigation bar?

Body:
You should just handle your authentication state in your react frontend. Even if your are doing server side auth, its better to just have the authentication state saved in your React frontend with Redux. In your react app:

You will also need to use the react-redux library to connect react with redux

Actions

export const login_success = () => {
  return {
    type: ACTION_TYPES.LOGIN_SUCCESS
  }
}

export const login_failure = () => {
  return {
    type: ACTION_TYPES.LOGIN_FAILURE
  }
}

reducer:

const initialState = {
  isAuthenticated: false,

}

const AuthReducer = (state= initialState, action) => {
  switch(action.type) {
    case ACTION_TYPES.LOGIN_SUCCESS:
      return {
        ...state,
        isAuthenticated: true
      }
    case ACTION_TYPES.LOGIN_FAILURE:
      return {
        ...state,
        isAuthenticated: false
      }
}

Access the auth state with props

 {this.props.isAuthenticated
         ? <h3> user is logged in </h3>
         : <h3> user is not logged in </h3>
       }

function mapStateToProps(state) {
  return {
     isAuthenticated: state.auth_reducer.isAuthenticated
  }
}

Implement this in a callback component that is rendered after the user signs in.

function mapDispatchToProps(dispatch) {
  return {
    action1: () => dispatch(ACTIONS.LOGIN_SUCCESS),
  }
}

If you want a fully functioning example of how to do this you can check out this project I built, it is a full stack react express app with authentication

https://github.com/iqbal125/react-redux-fullstack-blog

To give you some tough love, it seems to me you dont fully understand Redux, I would suggest mastering Redux before trying to build a complex full stack app, just a suggestion.

Edit:

Communication with server can be done with a proxy, so in your package.json in your react app you can do:

"proxy": http://localhost:5000"

or wherever your node server is running. You can also just send back a server response to your React frontend, anything at all, then  update your React-Redux frontend based on that server response.

So in your express server

router.get('api/login', (req, res) => {
  if(res.login === true) {
    res.json(success_login: true)
  }
})

then in your react frontend

axios.get('/api/login')
  .then(res => this.props.login_success(res.data) )

login_success(res) {
  if(res.success_login === true) {
    type: "SUCCESS_LOGIN"
}

So essentially you will not handle any routing or redux authentication state in your express server. Your server will send a response to your react frontend and then the routing and redux authentication state will be handled by your frontend.


问:
Points in a rectangle All
I am trying to get all list of points to populate a boolean true if the list of points fall within a rectangle.

I've tried to run the below code in Jupyterlab. but I keep getting the following error:

TypeError: '>=' not supported between instances of 'tuple' and 'int'

```<code>def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
   fc1,sc1=firstCorner[0],firstCorner[1]
   fc2,sc2=secondCorner[0],secondCorner[1]

   fc,sc=pointList[0],pointList[1]
   if (fc >= fc1 and fc <= fc2 and sc >= sc1 and sc <= sc2) :
       return True
   elif(fc >= fc2 and fc <= fc1 and sc >= sc2 and sc <= sc1):
       return True
   else:
       return False

print(allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]))
</code>```

I expect the output to be allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]) should return True but allIn((0,0), (5,5), [(1,1), (0,0), (5,6)]) should return False
and empty list of points allIn((0,0), (5,5), []) should return False

答:
Look at individual points inside your list of points.</p>

```<code>def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
   fc1,sc1=firstCorner[0],firstCorner[1]
   fc2,sc2=secondCorner[0],secondCorner[1]
   inside = False
   for point in pointList:
       fc,sc=point[0],point[1]
       if (fc >= fc1 and fc <= fc2 and sc >= sc1 and sc <= sc2) :
           inside = True
       elif(fc >= fc2 and fc <= fc1 and sc >= sc2 and sc <= sc1):
           inside = True
       else:
           return False
   return inside
</code>```

Title: Points in a rectangle All

Body:
I am trying to get all list of points to populate a boolean true if the list of points fall within a rectangle.

I've tried to run the below code in Jupyterlab. but I keep getting the following error:

TypeError: '>=' not supported between instances of 'tuple' and 'int'

def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
   fc1,sc1=firstCorner[0],firstCorner[1]
   fc2,sc2=secondCorner[0],secondCorner[1]

   fc,sc=pointList[0],pointList[1]
   if (fc >= fc1 and fc <= fc2 and sc >= sc1 and sc <= sc2) :
       return True
   elif(fc >= fc2 and fc <= fc1 and sc >= sc2 and sc <= sc1):
       return True
   else:
       return False

print(allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]))

I expect the output to be allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]) should return True but allIn((0,0), (5,5), [(1,1), (0,0), (5,6)]) should return False
and empty list of points allIn((0,0), (5,5), []) should return False

Body:
Look at individual points inside your list of points.

def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
   fc1,sc1=firstCorner[0],firstCorner[1]
   fc2,sc2=secondCorner[0],secondCorner[1]
   inside = False
   for point in pointList:
       fc,sc=point[0],point[1]
       if (fc >= fc1 and fc <= fc2 and sc >= sc1 and sc <= sc2) :
           inside = True
       elif(fc >= fc2 and fc <= fc1 and sc >= sc2 and sc <= sc1):
           inside = True
       else:
           return False
   return inside


问:
"object invoked has disconnected from its clients" error message is displayed while working with popup windows
I am trying to work with popup windows. I have gone through the site "http://wiki.openqa.org/display/WTR/JavaScript+Pop+Ups". I have modified the "ie-class.rb" by adding the code mentioned in the solution #7 of the site.

Also I have tried the example mentioned below :

```<code>require 'watir/ie'
require 'win32ole'

iewin = Watir::IE.new
iewin.goto("http://www.w3schools.com/js/tryit_view.asp?filename=tryjs_confirm")
iewin=Watir::IE.attach(:url, /w3schools/)
iewin.bring_to_front
iewin.maximize
iewin.button(:value, "Show a confirm box").click_no_wait
txt = iewin.clickprompt("OK") # waits for popup and click ok
puts txt #prints the popup text
txt1=iewin.clickprompt("OK")
puts txt1

iewin.close
</code>```

On executing the following code, popups are handled but produces the following error :

```<code>C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-1.7.1/lib/watir/ie-class.rb:319:in `method_missing': unknown property or method: `name' (NoMethodError)
    HRESULT error code:0x80010108
      The object invoked has disconnected from its clients.
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-1.7.1/lib/watir/ie-class.rb:319:in `exists?'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-1.7.1/lib/watir/ie-class.rb:406:in `close'
    from popup.rb:50:in `<main>'
Press a button!
You pressed OK!
</code>```

But when I remove the command "iewin.close", error message is not displayed.

"iewin.close" command closes the browser and then there is nothing for watir to perform then why is the error message displayed.

Please suggest.

答:
It appears that you are using ruby 1.9.2 with Watir. The watir installation page recommends using Ruby 1.8.7. That should fix the problem.

Good luck,

Dave

Body:
I am trying to work with popup windows. I have gone through the site "http://wiki.openqa.org/display/WTR/JavaScript+Pop+Ups". I have modified the "ie-class.rb" by adding the code mentioned in the solution #7 of the site.

Also I have tried the example mentioned below :

require 'watir/ie'
require 'win32ole'

iewin = Watir::IE.new
iewin.goto("http://www.w3schools.com/js/tryit_view.asp?filename=tryjs_confirm")
iewin=Watir::IE.attach(:url, /w3schools/)
iewin.bring_to_front
iewin.maximize
iewin.button(:value, "Show a confirm box").click_no_wait
txt = iewin.clickprompt("OK") # waits for popup and click ok
puts txt #prints the popup text
txt1=iewin.clickprompt("OK")
puts txt1

iewin.close

On executing the following code, popups are handled but produces the following error :

C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-1.7.1/lib/watir/ie-class.rb:319:in `method_missing': unknown property or method: `name' (NoMethodError)
    HRESULT error code:0x80010108
      The object invoked has disconnected from its clients.
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-1.7.1/lib/watir/ie-class.rb:319:in `exists?'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/watir-1.7.1/lib/watir/ie-class.rb:406:in `close'
    from popup.rb:50:in `'
Press a button!
You pressed OK!

But when I remove the command "iewin.close", error message is not displayed.

"iewin.close" command closes the browser and then there is nothing for watir to perform then why is the error message displayed.

Please suggest.


问:
Violation Long running JavaScript task took xx ms
Recently, I got this kind of warning, and this is my first time getting it:

[Violation] Long running JavaScript task took 234ms
[Violation] Forced reflow while executing JavaScript took 45ms
```
</blockquote>

<p>I'm working on a group project and I have no idea where this is coming from. This never happened before. Suddenly, it appeared when someone else got involved in the project. How do I find what file/function causes this warning? I've been looking for the answer, but mostly about the solution on how to solve it. I can't solve it if I can't even find the source of the problem.</p>

<p>In this case, the warning appears only on Chrome. I tried to use Edge, but I didn't get any similar warnings, and I haven't tested it on Firefox yet.</p>

<p>I even get the error from <code>jquery.min.js</code>:</p>

<blockquote>
  <pre class="lang-none prettyprint-override"><code>[Violation] Handler took 231ms of runtime (50ms allowed)            jquery.min.js:2
</code>```

答:
This is violation error from Google Chrome that shows when the Verbose logging level is enabled.

Example of error message:

Explanation:

Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document. Because reflow is a user-blocking operation in the browser, it is useful for developers to understand how to improve reflow time and also to understand the effects of various document properties (DOM depth, CSS rule efficiency, different types of style changes) on reflow time. Sometimes reflowing a single element in the document may require reflowing its parent elements and also any elements which follow it.

Original article: Minimizing browser reflow by Lindsey Simon, UX Developer, posted on developers.google.com.

And this is the link Google Chrome gives you in the Performance profiler, on the layout profiles (the mauve regions), for more info on the warning.

Body:
Recently, I got this kind of warning, and this is my first time getting it:

[Violation] Long running JavaScript task took 234ms
[Violation] Forced reflow while executing JavaScript took 45ms

I'm working on a group project and I have no idea where this is coming from. This never happened before. Suddenly, it appeared when someone else got involved in the project. How do I find what file/function causes this warning? I've been looking for the answer, but mostly about the solution on how to solve it. I can't solve it if I can't even find the source of the problem.

In this case, the warning appears only on Chrome. I tried to use Edge, but I didn't get any similar warnings, and I haven't tested it on Firefox yet.

I even get the error from jquery.min.js:

[Violation] Handler took 231ms of runtime (50ms allowed)            jquery.min.js:2


问:
Convert object attributes to dict
```<code>class foo:
    def __init__(self,name):
        self.name = name
        #other attributes
        self.children = [] #Child objects in self.children

    def convert(self):
        return vars(self)
</code>```

When using vars(foo) or foo.__dict__ the objects in self.children aren't converted into dictionaries too, returning a dictionary like this:

```<code>{'name': 'name', 'children': [object1,object2...]}
</code>```

These 'child' objects are also instances of the foo class.
At first I tried using dict['children'] = [vars(item) for item in dict['children']] to convert these objects but unfortunately this doesn't work for children of children.
Is there a recursive function I can create to convert all these objects and their children?

答:
Do it with a recursive function. Get the vars for the object, then replace the children list with a list of converted children.</p>

```<code>def convert(self):
    d = dict(vars(self)) # Copy the vars() dictionary
    d['children'] = [c.convert() for c in self.children]
    return d
</code>```

Title: Convert object attributes to dict

Body:
class foo:
    def __init__(self,name):
        self.name = name
        #other attributes
        self.children = [] #Child objects in self.children

    def convert(self):
        return vars(self)

When using vars(foo) or foo.__dict__ the objects in self.children aren't converted into dictionaries too, returning a dictionary like this:

{'name': 'name', 'children': [object1,object2...]}

These 'child' objects are also instances of the foo class.
At first I tried using dict['children'] = [vars(item) for item in dict['children']] to convert these objects but unfortunately this doesn't work for children of children.
Is there a recursive function I can create to convert all these objects and their children?

Body:
Do it with a recursive function. Get the vars for the object, then replace the children list with a list of converted children.

def convert(self):
    d = dict(vars(self)) # Copy the vars() dictionary
    d['children'] = [c.convert() for c in self.children]
    return d


问:
Query using only partition key in DynamoDB
I am trying to query on my table using only the partition key and ignoring the sort key but I get no items.

My global secondary index looks like this:

And my table looks like this:

And this is my query:

```<code>const params = {
  ExpressionAttributeValues: {
    ':app': 'app',
  },
  IndexName: 'glc-development-gsi1',
  KeyConditionExpression: 'sk = :app',
  TableName: this.tableName,
};
return new Promise((resolve, reject) => {
  this.client.query(params, (err, data) => {
    console.log(data);
    if (err) {
      reject(err);
    } else {
      resolve(data);
    }
  });
});
</code>```

According to all the documentation I've read and the other questions on here, this should work and I can't understand why it doesn't. The scan from my index is also empty.

答: Finally found my solution. DynamoDB stores data in indexes only when both the partition key and the sort key are defined, so my index was empty all the time. The query was fine.</p>

Body:
I am trying to query on my table using only the partition key and ignoring the sort key but I get no items.

My global secondary index looks like this:

And my table looks like this:

And this is my query:

const params = {
  ExpressionAttributeValues: {
    ':app': 'app',
  },
  IndexName: 'glc-development-gsi1',
  KeyConditionExpression: 'sk = :app',
  TableName: this.tableName,
};
return new Promise((resolve, reject) => {
  this.client.query(params, (err, data) => {
    console.log(data);
    if (err) {
      reject(err);
    } else {
      resolve(data);
    }
  });
});

According to all the documentation I've read and the other questions on here, this should work and I can't understand why it doesn't. The scan from my index is also empty.


问:
Laravel Error - Trying to get property game of non-object
I am trying to run a query that counts the number of times a user participate in an event, but I got this error:

Trying to get property 'game' of non-object

Also this was underlined:

<?php echo e($player->game); ?>
```

<p>I have written the query</p>

<p>Controller</p>

<pre class="lang-php prettyprint-override"><code>$players = DB::table("played_game")
    ->select("played_game.user_id","played_game.game","users.username", DB::raw("COUNT(played_game.game) as no_game"))
    ->join("users","users.id","=","played_game.user_id")
    ->groupBy("played_game.game","users.username","played_game.user_id")
    ->orderByRaw('COUNT(played_game.game) DESC')
    ->paginate(15);
</code>```

View

@foreach ($players as $key => $player_list)

        {{ $player_list->username }}

    @foreach ($player_list as $player)

            {{ $player->game }}
            {{ $player->no_game }}

    @endforeach
@endforeach
```

I want to display the player(username) involved in colspan and other details in the td.

答:
paginate() returns an instance of Illuminate\Pagination\LengthAwarePaginator which extends the AbstractPaginator that has functions like items(), check it out for further useful functions.

To get the paginated result, do ->paginate(15)->items(), you can also do all(), toArray(), toJson() and other stuff since it implements a number of interfaces.

Body:
I am trying to run a query that counts the number of times a user participate in an event, but I got this error:

Trying to get property 'game' of non-object

Also this was underlined:

<?php echo e($player->game); ?>

I have written the query

Controller

$players = DB::table("played_game")
    ->select("played_game.user_id","played_game.game","users.username", DB::raw("COUNT(played_game.game) as no_game"))
    ->join("users","users.id","=","played_game.user_id")
    ->groupBy("played_game.game","users.username","played_game.user_id")
    ->orderByRaw('COUNT(played_game.game) DESC')
    ->paginate(15);

View

@foreach ($players as $key => $player_list)

        {{ $player_list->username }}

    @foreach ($player_list as $player)

            {{ $player->game }}
            {{ $player->no_game }}

    @endforeach
@endforeach

I want to display the player(username) involved in colspan and other details in the td.


问:
Edit parameters in Settings file
I have DataClasses.dbml file in my C# winforms project. This automatically adds a setting of type ConnectionString to Settings file of the project. The connection string throughout the project is accessed using this setting.

Now when I work on my PC, it connects to the database and works fine. But how to set a new connection string depending on client's host and instance names in the settings file permanently and for once (during setup).

I tried doing:

```<code>Settings.Default.ConnectionString = "SqlConnectionString";
Settings.Default.Save();
</code>```

But it gives a compile-time error that its Read-Only.

My only aim is to set the connectionstrings according the clients setting. I dont want to make it hard coded.

答:
Add a partial class definition like the following

```<code>public partial class DataClasses
{
    partial void OnCreated()
    {
        Connection.ConnectionString = SQLHelpers.GetConnectionStr();
    }
}
</code>```

where SQLHelpers.GetConnectionStr should lookup the settings from the users App.Config file.

Remember to put this in a separate file to your auto-generated dbml file.

Title: Edit parameters in Settings file

Body:
I have DataClasses.dbml file in my C# winforms project. This automatically adds a setting of type ConnectionString to Settings file of the project. The connection string throughout the project is accessed using this setting.

Now when I work on my PC, it connects to the database and works fine. But how to set a new connection string depending on client's host and instance names in the settings file permanently and for once (during setup).

I tried doing:

Settings.Default.ConnectionString = "SqlConnectionString";
Settings.Default.Save();

But it gives a compile-time error that its Read-Only.

My only aim is to set the connectionstrings according the clients setting. I dont want to make it hard coded.

Body:
Add a partial class definition like the following

public partial class DataClasses
{
    partial void OnCreated()
    {
        Connection.ConnectionString = SQLHelpers.GetConnectionStr();
    }
}

where SQLHelpers.GetConnectionStr should lookup the settings from the users App.Config file.

Remember to put this in a separate file to your auto-generated dbml file.


问:
Terraform create a Cloudwatch rule with multiple targets
From the Terraform docs - https://www.terraform.io/docs/providers/aws/r/cloudwatch_event_target.html

I don't see an option to map multiple targets to the same Cloudwatch rule. It only takes an arn field which accepts one resource. I'm trying to map 5 Lambdas to the same Cloudwatch rule. Does Terraform support this?

EDIT: How can I attach only 5 lambdas? If I've created 15 lambdas, I want to attach 5 each to 3 cloudwatch rules.

答:
Assuming you created all your lambas using the same terraform resource with count, you can use count on this as well:</p>

```<code>resource "aws_cloudwatch_event_target" "cw_target" {
    count = length(aws_lambda_function.my_lambdas)
    rule = "${aws_cloudwatch_event_rule.my_rule.name}"
    arn = "${aws_lambda_function.my_lambdas.*.arn[count.index]}"
}
</code>```

Body:
Assuming you created all your lambas using the same terraform resource with count, you can use count on this as well:

resource "aws_cloudwatch_event_target" "cw_target" {
    count = length(aws_lambda_function.my_lambdas)
    rule = "${aws_cloudwatch_event_rule.my_rule.name}"
    arn = "${aws_lambda_function.my_lambdas.*.arn[count.index]}"
}


问:
How to extract a subString from android java String?
I tried to extract Sub-String from java string, but failed. i tried like this

```<code>String text = "audios/{any_number} any_audio_name.mp3";
text= text.substring(text.indexOf('/'), text.indexOf('3')-2);
</code>```

Updated

I need String contains only any_audio_name and removing audios/ , any number e.g. {123} and .mp3

For example audios/{211} new school poem.mp3 to new school poem

答:
This answer might helpful</p>

```<code>String text = "audios/any_audio_name.mp3";
text= text.substring(text.indexOf('/')+1, text.indexOf('.'));
</code>```

Body:
I tried to extract Sub-String from java string, but failed. i tried like this

String text = "audios/{any_number} any_audio_name.mp3";
text= text.substring(text.indexOf('/'), text.indexOf('3')-2);

Updated

I need String contains only any_audio_name and removing audios/ , any number e.g. {123} and .mp3

For example audios/{211} new school poem.mp3 to new school poem

Body:
This answer might helpful

String text = "audios/any_audio_name.mp3";
text= text.substring(text.indexOf('/')+1, text.indexOf('.'));


问:
How to fix 'custom post show by category' in WordPress
How can I fix this problem? I'm trying with passing a variable in WP_Query on 'category_name' => $category->slug, but not showing any posts in output.
When I remove 'category_name' => $category->slug, line from code then showing posts but need to display posts by category.

```<code><?php
function mytheme_schedule_shortcode($atts, $content = null){
    extract( shortcode_atts( array(
        'style'         => 1
    ), $atts) );
    $domain = 'mytheme-toolkit';
    $mytheme_schedule_categories = get_terms('schedule_cat');

    $mytheme_schedule_markup ='
        <section class="schedule-area bg-image ptb-120">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="tab">
                            <ul class="tabs">';
                            if (!empty($mytheme_schedule_categories) && ! is_wp_error($mytheme_schedule_categories)) {
                                foreach($mytheme_schedule_categories as $category){
                                $mytheme_schedule_markup .='
                                <li>
                                    <a href="#">'.esc_html__($category->name).'
                                        <span>'.esc_html__($category->slug).'</span>
                                    </a>
                                </li>';
                                }
                            }
                            $mytheme_schedule_markup .='
                            </ul>

                            <div class="tab_content">';
                                foreach($mytheme_schedule_categories as $category){
                                    $mytheme_schedule_markup .='
                                    <div class="tabs_item">
                                        <ul class="accordion">';
                                            $args = array(
                                                'post_type' => 'schedule',
                                                'posts_per_page' => -1,
                                                'category_name' => $category->slug,
                                            );
                                            $schedule_array = new WP_Query( $args );

                                            while($schedule_array->have_posts()): $schedule_array->the_post();
                                                $mytheme_schedule_markup .= '
                                                <li class=-item">
                                                        <h3>'.get_the_title().'</h3>
                                                </li>';

                                            endwhile;
                                            wp_reset_query();
                                            $mytheme_schedule_markup .= '
                                        </ul>
                                    </div>';
                                }
                                $mytheme_schedule_markup .='
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>';
    return $mytheme_schedule_markup;
}
add_shortcode('mytheme_schedule', 'mytheme_schedule_shortcode');
</code>```

答:
It appears that you are using a custom taxonomy for your post type in which case the code should be something like this:

```<code>$args = array(
  'post_type' => 'schedule',
  'posts_per_page' => -1,
  'tax_query' => array(
    array(
        'taxonomy' => 'schedule_cat',
        'field'    => 'slug',
        'terms'    => $category->slug,
    ),
  ),
);
$schedule_array = new WP_Query( $args );
</code>```

This should resolve the issue for you. Good Luck!!!

For future reference, check the WP Query arguments here

Body:
How can I fix this problem? I'm trying with passing a variable in WP_Query on 'category_name' => $category->slug, but not showing any posts in output.
When I remove 'category_name' => $category->slug, line from code then showing posts but need to display posts by category.

<?php
function mytheme_schedule_shortcode($atts, $content = null){
    extract( shortcode_atts( array(
        'style'         => 1
    ), $atts) );
    $domain = 'mytheme-toolkit';
    $mytheme_schedule_categories = get_terms('schedule_cat');

    $mytheme_schedule_markup ='

';
                            if (!empty($mytheme_schedule_categories) && ! is_wp_error($mytheme_schedule_categories)) {
                                foreach($mytheme_schedule_categories as $category){
                                $mytheme_schedule_markup .='

                                    '.esc_html__($category->name).'
                                        '.esc_html__($category->slug).'

';
                                }
                            }
                            $mytheme_schedule_markup .='

';
                                foreach($mytheme_schedule_categories as $category){
                                    $mytheme_schedule_markup .='

';
                                            $args = array(
                                                'post_type' => 'schedule',
                                                'posts_per_page' => -1,
                                                'category_name' => $category->slug,
                                            );
                                            $schedule_array = new WP_Query( $args );

                                            while($schedule_array->have_posts()): $schedule_array->the_post();
                                                $mytheme_schedule_markup .= '

'.get_the_title().'

';

                                            endwhile;
                                            wp_reset_query();
                                            $mytheme_schedule_markup .= '

';
                                }
                                $mytheme_schedule_markup .='

';
    return $mytheme_schedule_markup;
}
add_shortcode('mytheme_schedule', 'mytheme_schedule_shortcode');

Body:
It appears that you are using a custom taxonomy for your post type in which case the code should be something like this:

$args = array(
  'post_type' => 'schedule',
  'posts_per_page' => -1,
  'tax_query' => array(
    array(
        'taxonomy' => 'schedule_cat',
        'field'    => 'slug',
        'terms'    => $category->slug,
    ),
  ),
);
$schedule_array = new WP_Query( $args );

This should resolve the issue for you. Good Luck!!!

For future reference, check the WP Query arguments here


问:
React use route from Express instead of index.html
I have a React application running on port 3000,  I have an express backend running on port 5000.  I would like React to instead of using index.html as the base HTML for the application to instead call port 5000 and use that html (I have a route there, index.html that when I do localhost:5000/index.html responds correctly).  How can I tell React to not look in the public/index.html and instead pull it from the backend?</p>

答:
I think you could minimize this kind of problem by using everything in just one project.

The thing is that, you need a mount point for your React app. So, you could fetch for what it's in localhost:5000/index.html (you may need to enable CORS), and obviously you should use DOM Parser to parse the incoming response to text, and then to a manipulable DOM, after that find a mount point element for your application, and finally render everything as a string in your current html document.

So, you'd need to do something like this; and then using a querySelector to find the mount point in you application, and then use DOMParser to render.

However, you'd need to have an arquitecture in which every component you're using in your application is provided. You may need to use react-router so this is achieved.


问:
Assign nil value to double in Objective-C
In my iOS iPhone app I have this method:

```<code>-(id)initWithLocationName:(NSString *)locatNm latitude:(double)lati longitude:(double)longi xCoord:(double)xco yCoord:(double)yco;
</code>```

In this method I need to assign nil value to xCoord & yCoord.

How can I assign nil to double?

答: You can only assign nil to pointers. Instead of using nil, I would use a special value, usually -1. If you really need to use nil, you'll need to wrap the double in a NSNumber.</p>

Body:
In my iOS iPhone app I have this method:

-(id)initWithLocationName:(NSString *)locatNm latitude:(double)lati longitude:(double)longi xCoord:(double)xco yCoord:(double)yco;

In this method I need to assign nil value to xCoord & yCoord.

How can I assign nil to double?


问:
How to import a PowerShell module for administrators only?
When importing a PowerShell module that

#Requires -RunAsAdministrator
```

from my PowerShell profile, it throws an ScriptRequiresElevation,Microsoft.PowerShell.Commands.ImportModuleCommand error.

How can I either

a) add a condition/parameter that the module is only imported when running an elevated shell or

b) move the import to a profile that gets only loaded when running an elevated shell?

答:
The easiest is to add the condition check in your profile script, you can add the check to see if you are running as Administrator:</p>

```<code>$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
    Import-Module NeedsAdminModule
}
</code>```

Body:
When importing a PowerShell module that

#Requires -RunAsAdministrator

from my PowerShell profile, it throws an ScriptRequiresElevation,Microsoft.PowerShell.Commands.ImportModuleCommand error.

How can I either

a) add a condition/parameter that the module is only imported when running an elevated shell or

b) move the import to a profile that gets only loaded when running an elevated shell?

Body:
The easiest is to add the condition check in your profile script, you can add the check to see if you are running as Administrator:

$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
    Import-Module NeedsAdminModule
}


问:
PDOException “could not find driver”
I have just installed Debian Lenny with Apache, MySQL, and PHP and I am receiving a PDOException could not find driver.

This is the specific line of code it is referring to:

$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS)

DB_HOST, DB_NAME, DB_USER, and DB_PASS are constants that I have defined. It works fine on the production server (and on my previous Ubuntu Server setup).

Is this something to do with my PHP installation?

Searching the internet has not helped, all I get is experts-exchange and examples, but no solutions.

答: Check correct path in extension_dir in you phpinfo().</p>

ContentLicense: CC BY-SA 2.5

Title: PDOException “could not find driver”


问:
Retrieve audio data in JSON format and play it through Amazon Alexa
I am working on a custom lambda function in JavaScript for the Amazon Alexa. Amazon's docs have clear details on building custom skills, and I have successfully built several "stock" skills from their templates.

I am writing a unique skill now which must retrieve the JSON data located at this link:
https://api.ense.nyc/latest

and then 'play' that data (since the data is snippets of audio) through the Alexa. I am not sure what to write to bring about this functionality.

答: It seems that the audio files are short. In that case connect to the endpoint using an http fetch library (eg. httpm module, node-fetch or axios in node.js). Once you get the json file navigate to the properties that have the audio, get the url, surround them by audio tags <audio src="url"/> ands send them in a standard speech response of your skill. The audio tag has time and quality limitations so if you run into issues the audio is probably longer or a different quality than expected.


问:
Mocha/Chai test keeps producing error "cannot read property 'length' of undefined," but the function works in the app itself
Problem summary:

I wrote a function called getImagePathsFromCatalog that takes a string representing the location of a catalog (XML) file. It reads product info from the catalog file and produces an array "map"(*) consisting of productIds (key), each with an array of their associated images (value).

In my application, this runs fine and always returns the expected output, which should look something like this (formatted for readability):

```<code>[
'TEST-123': [ 'products/TEST-123.jpg' ],
'TEST-12345': [ 'products/Equipment/TEST-12345.jpg',
              'products/Equipment/TEST-12345_1.jpg' ]
]
</code>```

Background Info:

I have tried using various syntax to construct the it block (using async/await, using .then); using return and expect; using various Chai methods (be, should, assert, etc.); assigning the resolve value of the promise to a let for use in the assertion; using done; and some other things I'm sure I'm forgetting.

I have also tried different expectations, including to.be.array, to.be.ok, to.exist, and etc., but all end in the same error.

I have installed and am importing all of the required libraries and functions: chai, chai-as-promised, chai-arrays, chai-asserttype, chai.expect (etc.) and am also "using" them, as in chai.use(chaiAsPromised), etc.

(*) Note: Due to project specs, I have to use an array that behaves more or less like a map, rather than using an actual map object. I know this may cause issues with tests like to.be.array, but it shouldn't prevent me from expecting things like the result existing or coming back non-null (at least I wouldn't think it would?.)

Code:

```<code>describe('catalogImages.getImagePathsFromCatalog(catalogFile)', function () {
    it('function should return an array', function() {
        catalogImages.getImagePathsFromCatalog('../imports/catalog.xml')
        .then(catalogImagePathsMap => {
            return expect(catalogImagePathsMap).to.be.array();
        });
    });
});
</code>```

Expected and actual result summary:

Expected result: Some tests (even just basic assertions about the existence or non-null/non-undefined status of the result) should pass.

Actual result: All tests written for this function return the same error ("cannot read property 'length' of undefined").

I've been researching this error and haven't found a solution that works for me yet. Thank you in advance for any assistance.

答:
Very unexpected, but the issue was actually the file path I was passing-into the function as an argument. The path was referencing the file from the test's location in the file system, but when my coworker suggested doing a console.log(process.cwd()); in the test just to double-check (after trying A LOT of other things that seemed more obvious), we found that the file was behaving as if it was in the root instead of in its subfolder. After switching the path argument to start at the root level rather than the subfolder the test file resides in, the tests started working perfectly. I still don't understand why this is the case, but maybe this will help someone else in the future who is banging their head against a similar Mocha/Chai mystery!

Doesn't work:

```<code>describe('catalogImages.getImagePathsFromCatalog(catalogFile)', function () {
    it('function should return an array', function() {
        catalogImages.getImagePathsFromCatalog('../imports/catalog.xml')
        .then(catalogImagePathsMap => {
           return expect(catalogImagePathsMap).to.be.array();
        });
    });
});
</code>```

Does work:

```<code>describe('catalogImages.getImagePathsFromCatalog(catalogFile)', function () {
    it('function should return an array', function() {
        catalogImages.getImagePathsFromCatalog('./imports/catalog.xml')
        .then(catalogImagePathsMap => {
           return expect(catalogImagePathsMap).to.be.array();
        });
    });
});
</code>```

Body:
Problem summary:

I wrote a function called getImagePathsFromCatalog that takes a string representing the location of a catalog (XML) file. It reads product info from the catalog file and produces an array "map"(*) consisting of productIds (key), each with an array of their associated images (value).

In my application, this runs fine and always returns the expected output, which should look something like this (formatted for readability):

[
'TEST-123': [ 'products/TEST-123.jpg' ],
'TEST-12345': [ 'products/Equipment/TEST-12345.jpg',
              'products/Equipment/TEST-12345_1.jpg' ]
]

Background Info:

I have tried using various syntax to construct the it block (using async/await, using .then); using return and expect; using various Chai methods (be, should, assert, etc.); assigning the resolve value of the promise to a let for use in the assertion; using done; and some other things I'm sure I'm forgetting.

I have also tried different expectations, including to.be.array, to.be.ok, to.exist, and etc., but all end in the same error.

I have installed and am importing all of the required libraries and functions: chai, chai-as-promised, chai-arrays, chai-asserttype, chai.expect (etc.) and am also "using" them, as in chai.use(chaiAsPromised), etc.

(*) Note: Due to project specs, I have to use an array that behaves more or less like a map, rather than using an actual map object. I know this may cause issues with tests like to.be.array, but it shouldn't prevent me from expecting things like the result existing or coming back non-null (at least I wouldn't think it would?.)

Code:

describe('catalogImages.getImagePathsFromCatalog(catalogFile)', function () {
    it('function should return an array', function() {
        catalogImages.getImagePathsFromCatalog('../imports/catalog.xml')
        .then(catalogImagePathsMap => {
            return expect(catalogImagePathsMap).to.be.array();
        });
    });
});

Expected and actual result summary:

Expected result: Some tests (even just basic assertions about the existence or non-null/non-undefined status of the result) should pass.

Actual result: All tests written for this function return the same error ("cannot read property 'length' of undefined").

I've been researching this error and haven't found a solution that works for me yet. Thank you in advance for any assistance.

Body:
Very unexpected, but the issue was actually the file path I was passing-into the function as an argument. The path was referencing the file from the test's location in the file system, but when my coworker suggested doing a console.log(process.cwd()); in the test just to double-check (after trying A LOT of other things that seemed more obvious), we found that the file was behaving as if it was in the root instead of in its subfolder. After switching the path argument to start at the root level rather than the subfolder the test file resides in, the tests started working perfectly. I still don't understand why this is the case, but maybe this will help someone else in the future who is banging their head against a similar Mocha/Chai mystery!

Doesn't work:

describe('catalogImages.getImagePathsFromCatalog(catalogFile)', function () {
    it('function should return an array', function() {
        catalogImages.getImagePathsFromCatalog('../imports/catalog.xml')
        .then(catalogImagePathsMap => {
           return expect(catalogImagePathsMap).to.be.array();
        });
    });
});

Does work:

describe('catalogImages.getImagePathsFromCatalog(catalogFile)', function () {
    it('function should return an array', function() {
        catalogImages.getImagePathsFromCatalog('./imports/catalog.xml')
        .then(catalogImagePathsMap => {
           return expect(catalogImagePathsMap).to.be.array();
        });
    });
});


问:
Time format used in .ics file?
I am creating an .ics file in Java, and I need to know what date and time format to use.

Here is the current format of my ics file:

```<code>BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
DTSTART:20120901T180000
DTEND:20120901T183000
SUMMARY:my birthday
LOCATION:Bangalore
DESCRIPTION:Every one is welcome..!! time to party
PRIORITY:3
END:VEVENT
END:VCALENDAR
</code>```

I used ISO_DATETIME_TIME_ZONE_FORMAT to convert my date to the required format, but it returned 2012-09-01T18:00:00+00:00

What is the date format used in the DTSTART and DTEND values? Specifically, how can I format this properly in Java?

答:
Building off of Roger's answer, I wrote a quick block of code for anyone who wants a quick online "converter".

https://repl.it/repls/SomeNovelFields

The code to get something compiling and running is here:

```<code>import java.text.DateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");

        try {
        Date date = dateFormat.parse("20140110T000732");
                System.out.println(date);

        } catch(Exception e) {

        }
     }
}
</code>```

Title: Time format used in .ics file?

Body:
I am creating an .ics file in Java, and I need to know what date and time format to use.

Here is the current format of my ics file:

BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
DTSTART:20120901T180000
DTEND:20120901T183000
SUMMARY:my birthday
LOCATION:Bangalore
DESCRIPTION:Every one is welcome..!! time to party
PRIORITY:3
END:VEVENT
END:VCALENDAR

I used ISO_DATETIME_TIME_ZONE_FORMAT to convert my date to the required format, but it returned 2012-09-01T18:00:00+00:00

What is the date format used in the DTSTART and DTEND values? Specifically, how can I format this properly in Java?

Body:
Building off of Roger's answer, I wrote a quick block of code for anyone who wants a quick online "converter".

https://repl.it/repls/SomeNovelFields

The code to get something compiling and running is here:

import java.text.DateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");

        try {
        Date date = dateFormat.parse("20140110T000732");
                System.out.println(date);

        } catch(Exception e) {

        }
     }
}


问:
How to read multiple files from a directory, extract specific strings and ouput to an html file?
Greetings,

I have the following code and am stuck on how I would proceed to modify it so it will ask for the directory, read all files in the directory, then extract specific strings and ouput to an html file? Thanks in advance.

```<code>
#!/usr/local/bin/perl

use warnings;
use strict;
use Cwd;

print "Enter filename: "; # Should be Enter directory
my $perlfile =STDIN;

open INPUT_FILE, $perlfile || die "Could not open file: $!";
open OUTPUT, '>out.html' || die "Could not open file: $!";

# Evaluates the file and imports it into an array.
my @comment_array = ;
close(INPUT_FILE);
chomp @comment_array;
@comment_array = grep /^\s*#/g, @comment_array;

my $comment;

foreach $comment (@comment_array) {
        $comment =~ /####/; #Pattern match to grab only #s

# Prints comments to screen
Print results in html format

# Writes comments to output.html
Writes results to html file

}

close (OUTPUT);
</code>```

答:
a good starting point to learn about specific functions (from the cmd line)

```<code>perldoc -f opendir
</code>```

However, your particular problem is answered as follows, you can also use command line programs and pipe them into a string to simplify file handling ('cat') and pattern matching ('grep').

```<code>#!/usr/bin/perl -w
use strict;
my $dir = "/tmp";
my $dh;
my @patterns;
my $file;

opendir($dh,$dir);
while ($file = readdir($dh)){
    if (-f "$dir/$file"){
        my $string = `cat $dir/$file | grep pattern123`;
        push @patterns, $string;
    }
}
closedir($dh);

my $html = join("<br>",@patterns);
open F, ">out.html";
print F $html;
close F;
</code>```

Body:
Greetings,

I have the following code and am stuck on how I would proceed to modify it so it will ask for the directory, read all files in the directory, then extract specific strings and ouput to an html file? Thanks in advance.

#!/usr/local/bin/perl

use warnings;
use strict;
use Cwd;

print "Enter filename: "; # Should be Enter directory
my $perlfile =STDIN;

open INPUT_FILE, $perlfile || die "Could not open file: $!";
open OUTPUT, '>out.html' || die "Could not open file: $!";

# Evaluates the file and imports it into an array.
my @comment_array = ;
close(INPUT_FILE);
chomp @comment_array;
@comment_array = grep /^\s*#/g, @comment_array;

my $comment;

foreach $comment (@comment_array) {
        $comment =~ /####/; #Pattern match to grab only #s

# Prints comments to screen
Print results in html format

# Writes comments to output.html
Writes results to html file

}

close (OUTPUT);

Body:
a good starting point to learn about specific functions (from the cmd line)

perldoc -f opendir

However, your particular problem is answered as follows, you can also use command line programs and pipe them into a string to simplify file handling ('cat') and pattern matching ('grep').

#!/usr/bin/perl -w
use strict;
my $dir = "/tmp";
my $dh;
my @patterns;
my $file;

opendir($dh,$dir);
while ($file = readdir($dh)){
    if (-f "$dir/$file"){
        my $string = `cat $dir/$file | grep pattern123`;
        push @patterns, $string;
    }
}
closedir($dh);

my $html = join("<br>",@patterns);
open F, ">out.html";
print F $html;
close F;


问:
Failed to stop bean 'inputBindingLifecycle' with Spring Boot 2.1.5, Spring Cloud Stream Greenwich.SR1 and RocketMQ 0.9.0
I've seen a similar question here, but it's for an older version. Not sure what the conflicting version is for me, and what I need to use.

I used Spring Initializr to create my project, following the SCS Reference Quick Start. That set me up with my current versions (2.1.5, Greenwich.SR1).

The only dependency I added manually was for RocketMQ, since Spring Initializr couldn't find it. Here's my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
            <version>0.9.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-test-support</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

The error in question happens when I try to shut down the application, a process which takes nearly a minute each time. Here's the full stack trace when I shut down the app:

Failed to stop bean 'inputBindingLifecycle'

java.lang.IllegalStateException: Shutdown in progress     at
  java.lang.ApplicationShutdownHooks.remove(ApplicationShutdownHooks.java:82)
  ~[na:1.8.0_181]   at
  java.lang.Runtime.removeShutdownHook(Runtime.java:239) ~[na:1.8.0_181]
    at
  org.apache.rocketmq.client.trace.AsyncTraceDispatcher.removeShutdownHook(AsyncTraceDispatcher.java:210)
  ~[rocketmq-client-4.4.0.jar:4.4.0]    at
  org.apache.rocketmq.client.trace.AsyncTraceDispatcher.shutdown(AsyncTraceDispatcher.java:183)
  ~[rocketmq-client-4.4.0.jar:4.4.0]    at
  org.apache.rocketmq.client.consumer.DefaultMQPushConsumer.shutdown(DefaultMQPushConsumer.java:598)
  ~[rocketmq-client-4.4.0.jar:4.4.0]    at
  org.springframework.cloud.stream.binder.rocketmq.consuming.RocketMQListenerBindingContainer.stop(RocketMQListenerBindingContainer.java:175)
  ~[spring-cloud-stream-binder-rocketmq-0.9.0.RELEASE.jar:0.9.0.RELEASE]
    at
  org.springframework.cloud.stream.binder.rocketmq.integration.RocketMQInboundChannelAdapter.doStop(RocketMQInboundChannelAdapter.java:128)
  ~[spring-cloud-stream-binder-rocketmq-0.9.0.RELEASE.jar:0.9.0.RELEASE]
    at
  org.springframework.integration.endpoint.AbstractEndpoint.stop(AbstractEndpoint.java:173)
  ~[spring-integration-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]    at
  org.springframework.cloud.stream.binder.DefaultBinding.stop(DefaultBinding.java:127)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binder.DefaultBinding.unbind(DefaultBinding.java:159)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.BindingService.unbindConsumers(BindingService.java:303)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.BindableProxyFactory.unbindInputs(BindableProxyFactory.java:307)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.InputBindingLifecycle.doStopWithBindable(InputBindingLifecycle.java:66)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  java.util.LinkedHashMap$LinkedValues.forEach(LinkedHashMap.java:608)
  ~[na:1.8.0_181]   at
  org.springframework.cloud.stream.binding.AbstractBindingLifecycle.stop(AbstractBindingLifecycle.java:56)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.InputBindingLifecycle.stop(InputBindingLifecycle.java:34)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.AbstractBindingLifecycle.stop(AbstractBindingLifecycle.java:73)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.InputBindingLifecycle.stop(InputBindingLifecycle.java:34)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.context.support.DefaultLifecycleProcessor.doStop(DefaultLifecycleProcessor.java:238)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.DefaultLifecycleProcessor.access$300(DefaultLifecycleProcessor.java:53)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.stop(DefaultLifecycleProcessor.java:377)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.DefaultLifecycleProcessor.stopBeans(DefaultLifecycleProcessor.java:210)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.DefaultLifecycleProcessor.onClose(DefaultLifecycleProcessor.java:128)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1018)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:945)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE] ```

答:
Solution was to use version 0.2.1.RELEASE for the RocketMQ binder:</p>

```<code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
    <version>0.2.1.RELEASE</version>
</dependency>
</code>```

Body:
I've seen a similar question here, but it's for an older version. Not sure what the conflicting version is for me, and what I need to use.

I used Spring Initializr to create my project, following the SCS Reference Quick Start. That set me up with my current versions (2.1.5, Greenwich.SR1).

The only dependency I added manually was for RocketMQ, since Spring Initializr couldn't find it. Here's my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
            <version>0.9.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-test-support</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

The error in question happens when I try to shut down the application, a process which takes nearly a minute each time. Here's the full stack trace when I shut down the app:

Failed to stop bean 'inputBindingLifecycle'

java.lang.IllegalStateException: Shutdown in progress     at
  java.lang.ApplicationShutdownHooks.remove(ApplicationShutdownHooks.java:82)
  ~[na:1.8.0_181]   at
  java.lang.Runtime.removeShutdownHook(Runtime.java:239) ~[na:1.8.0_181]
    at
  org.apache.rocketmq.client.trace.AsyncTraceDispatcher.removeShutdownHook(AsyncTraceDispatcher.java:210)
  ~[rocketmq-client-4.4.0.jar:4.4.0]    at
  org.apache.rocketmq.client.trace.AsyncTraceDispatcher.shutdown(AsyncTraceDispatcher.java:183)
  ~[rocketmq-client-4.4.0.jar:4.4.0]    at
  org.apache.rocketmq.client.consumer.DefaultMQPushConsumer.shutdown(DefaultMQPushConsumer.java:598)
  ~[rocketmq-client-4.4.0.jar:4.4.0]    at
  org.springframework.cloud.stream.binder.rocketmq.consuming.RocketMQListenerBindingContainer.stop(RocketMQListenerBindingContainer.java:175)
  ~[spring-cloud-stream-binder-rocketmq-0.9.0.RELEASE.jar:0.9.0.RELEASE]
    at
  org.springframework.cloud.stream.binder.rocketmq.integration.RocketMQInboundChannelAdapter.doStop(RocketMQInboundChannelAdapter.java:128)
  ~[spring-cloud-stream-binder-rocketmq-0.9.0.RELEASE.jar:0.9.0.RELEASE]
    at
  org.springframework.integration.endpoint.AbstractEndpoint.stop(AbstractEndpoint.java:173)
  ~[spring-integration-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]    at
  org.springframework.cloud.stream.binder.DefaultBinding.stop(DefaultBinding.java:127)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binder.DefaultBinding.unbind(DefaultBinding.java:159)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.BindingService.unbindConsumers(BindingService.java:303)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.BindableProxyFactory.unbindInputs(BindableProxyFactory.java:307)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.InputBindingLifecycle.doStopWithBindable(InputBindingLifecycle.java:66)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  java.util.LinkedHashMap$LinkedValues.forEach(LinkedHashMap.java:608)
  ~[na:1.8.0_181]   at
  org.springframework.cloud.stream.binding.AbstractBindingLifecycle.stop(AbstractBindingLifecycle.java:56)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.InputBindingLifecycle.stop(InputBindingLifecycle.java:34)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.AbstractBindingLifecycle.stop(AbstractBindingLifecycle.java:73)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.cloud.stream.binding.InputBindingLifecycle.stop(InputBindingLifecycle.java:34)
  ~[spring-cloud-stream-2.1.2.RELEASE.jar:2.1.2.RELEASE]    at
  org.springframework.context.support.DefaultLifecycleProcessor.doStop(DefaultLifecycleProcessor.java:238)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.DefaultLifecycleProcessor.access$300(DefaultLifecycleProcessor.java:53)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.stop(DefaultLifecycleProcessor.java:377)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.DefaultLifecycleProcessor.stopBeans(DefaultLifecycleProcessor.java:210)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.DefaultLifecycleProcessor.onClose(DefaultLifecycleProcessor.java:128)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1018)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]  at
  org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:945)
  [spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE] ```

Body:
Solution was to use version 0.2.1.RELEASE for the RocketMQ binder:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
    <version>0.2.1.RELEASE</version>
</dependency>


问:
Waking up Stm32F4 from sleep mode on button press
I am putting my board using STM32F4 into sleep mode. I want to wake up when I press button. I am using following code for implementing this

```<code>void SleepMode(void)
{
  GPIO_InitTypeDef GPIO_InitStruct;
  MX_GPIO_Deinit();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  GPIO_InitStruct.Pin = B1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
  HAL_UART_DeInit(&huart4);
  HAL_SuspendTick();
  __HAL_RCC_PWR_CLK_ENABLE();
  HAL_PWR_EnterSLEEPMode(0, PWR_SLEEPENTRY_WFI);
}
</code>```

The board goes into sleep mode but doesn't wake up when I press button. Where I am making mistake in my code?

答: Have you configured the EXTI line in NVIC to start EXTI ISR on the button press? You may also need to resume SysTick when the device wakes up by calling HAL_ResumeTick()

Body:
I am putting my board using STM32F4 into sleep mode. I want to wake up when I press button. I am using following code for implementing this

void SleepMode(void)
{
  GPIO_InitTypeDef GPIO_InitStruct;
  MX_GPIO_Deinit();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  GPIO_InitStruct.Pin = B1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
  HAL_UART_DeInit(&huart4);
  HAL_SuspendTick();
  __HAL_RCC_PWR_CLK_ENABLE();
  HAL_PWR_EnterSLEEPMode(0, PWR_SLEEPENTRY_WFI);
}

The board goes into sleep mode but doesn't wake up when I press button. Where I am making mistake in my code?


问:
sending json web token using ajax to Node API
I'm trying to do an authorisation middleware using jsonwebtoken, cookie-parser to set cookies and jQuery in the client.

For that I'm using a middleware to check authorisations.

here is the middleware

```<code>const jwt = require('jsonwebtoken')

module.exports = (req,res,next)=> {
    try{
        const token = req.headers.authorization.split("=")[1];
        const decodedToken = jwt.verify(token, process.env.JWT_KEY)
        req.userData = decodedToken;
        next();

    } catch(error){
        return res.status(401).json({
            message: "Auth failed"
        })
    }
}
</code>```

In my API I'm creating and sending the token like this:

```<code>
                const token = jwt.sign({
                        email: user[0].email,
                        userId: user[0]._id
                    },

                    process.env.JWT_KEY, {
                        expiresIn: "1h"
                    }
                )

                res.cookie('userToken', token)
                res.render('index', {
                    movies: {}, token:token
                });

</code>```

In the client I'm sending back to the server like this:

```<code>var userToken = document.cookie;
        // console.log(userToken)

        $.ajax({
            url: "/movies/add",
            type: "GET",
            beforeSend: function (xhr, settings) {
                console.log(xhr)
                xhr.setRequestHeader('Authorization', 'Bearer ' + userToken);
            }
        });

</code>```

The movies/add route is receiving the request, because it's printing 'it entered', but it's not redirecting to movies/addMovies. What am I missing?

```<code>    router.get('/add', checkAuth, function (req, res, next) {

        console.log('it entered')

        res.render('movies/addMovies', {
            movies: {}
        })

    });
</code>```

答:
I've changed to this:

```<code>
$.ajax({
            url: "/movies/add",
            type: "GET",
            data:{
                'userToken':userToken
            },
            success: function(){
                console.log('sim')
                window.location.href = "/movies/add";
            }
        });
</code>```

and in the server

```<code>const token = req.cookies.userToken
const decodedToken = jwt.verify(token, process.env.JWT_KEY)
</code>```

and now it works

Body:
I'm trying to do an authorisation middleware using jsonwebtoken, cookie-parser to set cookies and jQuery in the client.

For that I'm using a middleware to check authorisations.

here is the middleware

const jwt = require('jsonwebtoken')

module.exports = (req,res,next)=> {
    try{
        const token = req.headers.authorization.split("=")[1];
        const decodedToken = jwt.verify(token, process.env.JWT_KEY)
        req.userData = decodedToken;
        next();

    } catch(error){
        return res.status(401).json({
            message: "Auth failed"
        })
    }
}

In my API I'm creating and sending the token like this:

                const token = jwt.sign({
                        email: user[0].email,
                        userId: user[0]._id
                    },

                    process.env.JWT_KEY, {
                        expiresIn: "1h"
                    }
                )

                res.cookie('userToken', token)
                res.render('index', {
                    movies: {}, token:token
                });

In the client I'm sending back to the server like this:

var userToken = document.cookie;
        // console.log(userToken)

        $.ajax({
            url: "/movies/add",
            type: "GET",
            beforeSend: function (xhr, settings) {
                console.log(xhr)
                xhr.setRequestHeader('Authorization', 'Bearer ' + userToken);
            }
        });

The movies/add route is receiving the request, because it's printing 'it entered', but it's not redirecting to movies/addMovies. What am I missing?

    router.get('/add', checkAuth, function (req, res, next) {

        console.log('it entered')

        res.render('movies/addMovies', {
            movies: {}
        })

    });

Body:
I've changed to this:

$.ajax({
            url: "/movies/add",
            type: "GET",
            data:{
                'userToken':userToken
            },
            success: function(){
                console.log('sim')
                window.location.href = "/movies/add";
            }
        });

and in the server

const token = req.cookies.userToken
const decodedToken = jwt.verify(token, process.env.JWT_KEY)

and now it works


问:
Run-time error 1004 - Autofilter Method of Range Class Failed
When I run my vba, I get the

Run-time error'1004; AutoFilter method of Range Class failed

I tried changing the worksheet as sheet 1 as it was recommended in a previous answer and it did not work

```<code>Sub Split_Data_in_workbooks()

Application.ScreenUpdating = False

Dim data_sh As Worksheet
Set data_sh = ThisWorkbook.Sheets("Working File")

Dim setting_Sh As Worksheet
Set setting_Sh = ThisWorkbook.Sheets("Setting")

Dim nwb As Workbook
Dim nsh As Worksheet

''''''Get unique districts

setting_Sh.Range("A:A").Clear
data_sh.AutoFilterMode = False
data_sh.Range("b:b").Copy setting_Sh.Range("A1")

setting_Sh.Range("A:A").RemoveDuplicates 1, xlYes

Dim I As Integer

For I = 2 To Application.CountA(setting_Sh.Range("A:A"))

   data_sh.UsedRange.AutoFilter 2, setting_Sh.Range("A" & I).Value

   Set nwb = Workbooks.Add
   Set nsh = nwb.Sheets(1)

   data_sh.UsedRange.SpecialCells(xlCellTypeVisible).Copy nsh.Range("A1")

   nwb.SaveAs setting_Sh.Range("H6").Value & "/" & setting_Sh.Range("A" &
I).Value & ".xlsx"
   nwb.Close False
   data_sh.AutoFilterMode = False
Next I

setting_Sh.Range("A:A").Clear

MsgBox "Done"

End Sub
</code>```

The code is supposed to take each district's information (which could be multiple lines), which from one workbook and save it into separate workbooks and save them in a designated file.  The code will not run pass this line

```<code>data_sh.UsedRange.AutoFilter 2, setting_Sh.Range("A" & I).Value
</code>```

答:
You are probably passing incorrect arguments to the data_sh.UsedRange.AutoFilter method. First argument must not be larger than the number of fields - try 1 instead of 2. Description of the second argument from the documentation:

The criteria (a string; for example, "101"). Use "=" to find blank
  fields, "<>" to find non-blank fields, and "><" to select (No Data)
  fields in data types. If this argument is omitted, the criteria is
  All. If Operator is xlTop10Items, Criteria1 specifies the number of
  items (for example, "10").

Try this line and then play with different arguments' values. Make sure you know what argument values are you passing to the function:

```<code>data_sh.UsedRange.AutoFilter 1
</code>```

Body:
When I run my vba, I get the

Run-time error'1004; AutoFilter method of Range Class failed

I tried changing the worksheet as sheet 1 as it was recommended in a previous answer and it did not work

Sub Split_Data_in_workbooks()

Application.ScreenUpdating = False

Dim data_sh As Worksheet
Set data_sh = ThisWorkbook.Sheets("Working File")

Dim setting_Sh As Worksheet
Set setting_Sh = ThisWorkbook.Sheets("Setting")

Dim nwb As Workbook
Dim nsh As Worksheet

''''''Get unique districts

setting_Sh.Range("A:A").Clear
data_sh.AutoFilterMode = False
data_sh.Range("b:b").Copy setting_Sh.Range("A1")

setting_Sh.Range("A:A").RemoveDuplicates 1, xlYes

Dim I As Integer

For I = 2 To Application.CountA(setting_Sh.Range("A:A"))

   data_sh.UsedRange.AutoFilter 2, setting_Sh.Range("A" & I).Value

   Set nwb = Workbooks.Add
   Set nsh = nwb.Sheets(1)

   data_sh.UsedRange.SpecialCells(xlCellTypeVisible).Copy nsh.Range("A1")

   nwb.SaveAs setting_Sh.Range("H6").Value & "/" & setting_Sh.Range("A" &
I).Value & ".xlsx"
   nwb.Close False
   data_sh.AutoFilterMode = False
Next I

setting_Sh.Range("A:A").Clear

MsgBox "Done"

End Sub

The code is supposed to take each district's information (which could be multiple lines), which from one workbook and save it into separate workbooks and save them in a designated file.  The code will not run pass this line

data_sh.UsedRange.AutoFilter 2, setting_Sh.Range("A" & I).Value

Body:
You are probably passing incorrect arguments to the data_sh.UsedRange.AutoFilter method. First argument must not be larger than the number of fields - try 1 instead of 2. Description of the second argument from the documentation:

The criteria (a string; for example, "101"). Use "=" to find blank
  fields, "<>" to find non-blank fields, and "><" to select (No Data)
  fields in data types. If this argument is omitted, the criteria is
  All. If Operator is xlTop10Items, Criteria1 specifies the number of
  items (for example, "10").

Try this line and then play with different arguments' values. Make sure you know what argument values are you passing to the function:

data_sh.UsedRange.AutoFilter 1


问:
select with index on DataTable?
After I get DataTable from sqlAdapter I'm closing connection.
If I preform SELECT from this DataTable, does the select use the index
I created in the DB?

what code do I need to write for using the index?

答: A DataTable is an in-memory dataset. If you (sub)select after it has been fetched from the DB you're query your data in memory and you're not using an index.

Title: select with index on DataTable?