问:
UnhandledPromiseRejectionWarning: Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
I have an app with a node/express server, a React client, and firebase firestore as database. When I do an operation on the firebase database, my code seems to work, but the data does not show up in the firestore console and I get the error below.

I implemented the solution below but it does not work:
https://stackoverflow.com/a/40321130/1438277

I am running npm 6.9.0 and node v11.8.0

Thank you

```<code>Unhandled Rejection at: Promise Promise {
[0]   <rejected> Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]       at Sign.sign (internal/crypto/sig.js:84:29)
[0]       at Object.sign (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jwa/index.js:152:45)
[0]       at Object.jwsSign [as sign] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jws/lib/sign-stream.js:32:24)
[0]       at GoogleToken.requestToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:180:31)
[0]       at GoogleToken.getTokenAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:119:21)
[0]       at GoogleToken.getToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:61:21)
[0]       at JWT.refreshTokenNoCache (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:129:36)
[0]       at JWT.refreshToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:148:24)
[0]       at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:265:28)
[0]       at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:26)
[0]       at JWT.getRequestHeaders (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:244:32)
[0]       at SingleCallCredentials.call_credentials_1.CallCredentials.createFromMetadataGenerator [as metadataGenerator] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/index.js:74:39)
[0]       at Promise (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:64:18)
[0]       at new Promise (<anonymous>)
[0]       at SingleCallCredentials.generateMetadata (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:63:16)
[0]       at Promise.all.creds.map (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:47:75) } reason: Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]     at Sign.sign (internal/crypto/sig.js:84:29)
[0]     at Object.sign (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jwa/index.js:152:45)
[0]     at Object.jwsSign [as sign] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jws/lib/sign-stream.js:32:24)
[0]     at GoogleToken.requestToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:180:31)
[0]     at GoogleToken.getTokenAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:119:21)
[0]     at GoogleToken.getToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:61:21)
[0]     at JWT.refreshTokenNoCache (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:129:36)
[0]     at JWT.refreshToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:148:24)
[0]     at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:265:28)
[0]     at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:26)
[0]     at JWT.getRequestHeaders (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:244:32)
[0]     at SingleCallCredentials.call_credentials_1.CallCredentials.createFromMetadataGenerator [as metadataGenerator] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/index.js:74:39)
[0]     at Promise (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:64:18)
[0]     at new Promise (<anonymous>)
[0]     at SingleCallCredentials.generateMetadata (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:63:16)
[0]     at Promise.all.creds.map (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:47:75)
[0] (node:3612) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 2)
[0] Unhandled Rejection at: Promise Promise {
[0]   <rejected> { Error: Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]       at Http2CallStream.call.on (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/client.js:102:45)
[0]       at Http2CallStream.emit (events.js:202:15)
[0]       at Http2CallStream.EventEmitter.emit (domain.js:439:20)
[0]       at Http2CallStream.endCall (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)
[0]       at /Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:355:18
[0]       at processTicksAndRejections (internal/process/next_tick.js:81:5)
[0]     code: 2,
[0]     details:
[0]      'Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line',
[0]     metadata: Metadata { internalRepr: Map {} } } } reason: { Error: Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]     at Http2CallStream.call.on (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/client.js:102:45)
[0]     at Http2CallStream.emit (events.js:202:15)
[0]     at Http2CallStream.EventEmitter.emit (domain.js:439:20)
[0]     at Http2CallStream.endCall (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)
[0]     at /Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:355:18
[0]     at processTicksAndRejections (internal/process/next_tick.js:81:5)
[0]   code: 2,
[0]   details:
[0]    'Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line',
[0]   metadata: Metadata { internalRepr: Map {} } }
</code>```

This is the database call I am making from my express server:

```<code>const admin = require('firebase-admin')
const config = require('./config.js')

exports.createAsin = p => {
  try {
    let addDoc = config.db.collection('asins').add({
      uid: p.uid,
      asin: p.asin,
      mapPrice: p.mapPrice,
      data: []
    })
    console.log('db: ASIN created')
    return p
  } catch (e) {
    console.log('db: error creating ASIN /', e)
    return null
  }
}
</code>```

答: I finally figured it out: my json certification file for Firebase was placed in a .env file and that’s what created the error. I moved it out into a separate json file (and added it to .gitignore) and it works. phew!</p>

Body:
I have an app with a node/express server, a React client, and firebase firestore as database. When I do an operation on the firebase database, my code seems to work, but the data does not show up in the firestore console and I get the error below.

I implemented the solution below but it does not work:
https://stackoverflow.com/a/40321130/1438277

I am running npm 6.9.0 and node v11.8.0

Thank you

Unhandled Rejection at: Promise Promise {
[0]   <rejected> Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]       at Sign.sign (internal/crypto/sig.js:84:29)
[0]       at Object.sign (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jwa/index.js:152:45)
[0]       at Object.jwsSign [as sign] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jws/lib/sign-stream.js:32:24)
[0]       at GoogleToken.requestToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:180:31)
[0]       at GoogleToken.getTokenAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:119:21)
[0]       at GoogleToken.getToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:61:21)
[0]       at JWT.refreshTokenNoCache (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:129:36)
[0]       at JWT.refreshToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:148:24)
[0]       at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:265:28)
[0]       at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:26)
[0]       at JWT.getRequestHeaders (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:244:32)
[0]       at SingleCallCredentials.call_credentials_1.CallCredentials.createFromMetadataGenerator [as metadataGenerator] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/index.js:74:39)
[0]       at Promise (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:64:18)
[0]       at new Promise (<anonymous>)
[0]       at SingleCallCredentials.generateMetadata (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:63:16)
[0]       at Promise.all.creds.map (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:47:75) } reason: Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]     at Sign.sign (internal/crypto/sig.js:84:29)
[0]     at Object.sign (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jwa/index.js:152:45)
[0]     at Object.jwsSign [as sign] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/jws/lib/sign-stream.js:32:24)
[0]     at GoogleToken.requestToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:180:31)
[0]     at GoogleToken.getTokenAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:119:21)
[0]     at GoogleToken.getToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/gtoken/build/src/index.js:61:21)
[0]     at JWT.refreshTokenNoCache (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:129:36)
[0]     at JWT.refreshToken (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:148:24)
[0]     at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:265:28)
[0]     at JWT.getRequestMetadataAsync (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:26)
[0]     at JWT.getRequestHeaders (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/google-auth-library/build/src/auth/oauth2client.js:244:32)
[0]     at SingleCallCredentials.call_credentials_1.CallCredentials.createFromMetadataGenerator [as metadataGenerator] (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/index.js:74:39)
[0]     at Promise (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:64:18)
[0]     at new Promise (<anonymous>)
[0]     at SingleCallCredentials.generateMetadata (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:63:16)
[0]     at Promise.all.creds.map (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-credentials.js:47:75)
[0] (node:3612) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 2)
[0] Unhandled Rejection at: Promise Promise {
[0]   <rejected> { Error: Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]       at Http2CallStream.call.on (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/client.js:102:45)
[0]       at Http2CallStream.emit (events.js:202:15)
[0]       at Http2CallStream.EventEmitter.emit (domain.js:439:20)
[0]       at Http2CallStream.endCall (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)
[0]       at /Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:355:18
[0]       at processTicksAndRejections (internal/process/next_tick.js:81:5)
[0]     code: 2,
[0]     details:
[0]      'Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line',
[0]     metadata: Metadata { internalRepr: Map {} } } } reason: { Error: Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line
[0]     at Http2CallStream.call.on (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/client.js:102:45)
[0]     at Http2CallStream.emit (events.js:202:15)
[0]     at Http2CallStream.EventEmitter.emit (domain.js:439:20)
[0]     at Http2CallStream.endCall (/Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)
[0]     at /Users/antoine/Desktop/jf_express_with_react/server/node_modules/@grpc/grpc-js/build/src/call-stream.js:355:18
[0]     at processTicksAndRejections (internal/process/next_tick.js:81:5)
[0]   code: 2,
[0]   details:
[0]    'Getting metadata from plugin failed with error: error:0906D06C:PEM routines:PEM_read_bio:no start line',
[0]   metadata: Metadata { internalRepr: Map {} } }

This is the database call I am making from my express server:

const admin = require('firebase-admin')
const config = require('./config.js')

exports.createAsin = p => {
  try {
    let addDoc = config.db.collection('asins').add({
      uid: p.uid,
      asin: p.asin,
      mapPrice: p.mapPrice,
      data: []
    })
    console.log('db: ASIN created')
    return p
  } catch (e) {
    console.log('db: error creating ASIN /', e)
    return null
  }
}


来源: stackexchange

问:
Cannot overwrite model once compiled Mongoose
Not Sure what I'm doing wrong, here is my check.js

```<code>var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));

var a1= db.once('open',function(){
var user = mongoose.model('users',{
       name:String,
       email:String,
       password:String,
       phone:Number,
      _enabled:Boolean
     });

user.find({},{},function (err, users) {
    mongoose.connection.close();
    console.log("Username supplied"+username);
    //doSomethingHere })
    });
</code>```

and here is my insert.js

```<code>var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/event-db')

var user = mongoose.model('users',{
     name:String,
     email:String,
     password: String,
     phone:Number,
     _enabled:Boolean
   });

var new_user = new user({
     name:req.body.name,
     email: req.body.email,
     password: req.body.password,
     phone: req.body.phone,
     _enabled:false
   });

new_user.save(function(err){
    if(err) console.log(err);
   });
</code>```

Whenever I'm trying to run check.js, I'm getting this error

Cannot overwrite 'users' model once compiled.

I understand that this error comes due to mismatching of Schema, but I cannot see where this is happening ? I'm pretty new to mongoose and nodeJS.

Here is what I'm getting from the client interface of my MongoDB:

```<code>MongoDB shell version: 2.4.6 connecting to: test
> use event-db
  switched to db event-db
> db.users.find()
  { "_id" : ObjectId("52457d8718f83293205aaa95"),
    "name" : "MyName",
    "email" : "myemail@me.com",
    "password" : "myPassword",
    "phone" : 900001123,
    "_enable" : true
  }
>
</code>```

答:
```<code>The reason of this issue is:

you given the model name "users" in the line
<<<var user = mongoose.model('users' {>>> in check.js file

and again the same model name you are giving in the insert file
<<< var user = mongoose.model('users',{ >>> in insert.js

This "users" name shouldn't be same when you declare a model that should be different
in a same project.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Not Sure what I'm doing wrong, here is my check.js

var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));

var a1= db.once('open',function(){
var user = mongoose.model('users',{
       name:String,
       email:String,
       password:String,
       phone:Number,
      _enabled:Boolean
     });

user.find({},{},function (err, users) {
    mongoose.connection.close();
    console.log("Username supplied"+username);
    //doSomethingHere })
    });

and here is my insert.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/event-db')

var user = mongoose.model('users',{
     name:String,
     email:String,
     password: String,
     phone:Number,
     _enabled:Boolean
   });

var new_user = new user({
     name:req.body.name,
     email: req.body.email,
     password: req.body.password,
     phone: req.body.phone,
     _enabled:false
   });

new_user.save(function(err){
    if(err) console.log(err);
   });

Whenever I'm trying to run check.js, I'm getting this error

Cannot overwrite 'users' model once compiled.

I understand that this error comes due to mismatching of Schema, but I cannot see where this is happening ? I'm pretty new to mongoose and nodeJS.

Here is what I'm getting from the client interface of my MongoDB:

MongoDB shell version: 2.4.6 connecting to: test
> use event-db
  switched to db event-db
> db.users.find()
  { "_id" : ObjectId("52457d8718f83293205aaa95"),
    "name" : "MyName",
    "email" : "myemail@me.com",
    "password" : "myPassword",
    "phone" : 900001123,
    "_enable" : true
  }
>

ContentLicense: CC BY-SA 4.0


问:
Draw ontop of all views
Is there a way to draw ontop of every view (like a watermark that shows everywhere for example)? sort of how the Dock4Droid app draws a a dockbar ontop of every screen.</p>

答: As an alternative, you can do your own drawing (onDraw) and set the opacity value such that it gives the presentation of being translucent.  Works for me with several of my requirements.</p>

Title: Draw ontop of all views


问:
Control.Exception.evaluate treats thunks generated by equivalent functions differently
Here are two equivalent partial functions:

\True -> \() -> ()

\True () -> ()

Applying either to False should raise a PatternMatchFail exception.

When I use Control.Exception.evaluate to force a thunk made from the former to WHNF, it forces the PatternMatchFail exception:

```<code>ghci> _ <- evaluate $ (\True -> \() -> ()) False
*** Exception: <interactive>:10:18-35: Non-exhaustive patterns in lambda
</code>```

When I use the latter form, it doesn't:

```<code>ghci> _ <- evaluate $ (\True () -> ()) False
</code>```

Why not?

(on GHC-8.0.1)

答:
From the Haskell 2010 report:

The following identity holds:

```<code>\ p1 … pn -> e    =   \ x1 … xn -> case (x1, …, xn) of (p1, …, pn) -> e
</code>```

https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-260003.3

So \True () -> e desugars to \x y -> case (x, y) of (True, ()) -> e, which after partial application to False is \y -> case (False, y) of ... i.e., a function abstraction, so that's not bottom.

In contrast, \True -> f (where f = \() -> e) desugars to \x -> case x of True -> ..., and there's the exception.

Body:
Here are two equivalent partial functions:

\True -> \() -> ()

\True () -> ()

Applying either to False should raise a PatternMatchFail exception.

When I use Control.Exception.evaluate to force a thunk made from the former to WHNF, it forces the PatternMatchFail exception:

ghci> _ <- evaluate $ (\True -> \() -> ()) False
*** Exception: <interactive>:10:18-35: Non-exhaustive patterns in lambda

When I use the latter form, it doesn't:

ghci> _ <- evaluate $ (\True () -> ()) False

Why not?

(on GHC-8.0.1)

Body:
From the Haskell 2010 report:

The following identity holds:

\ p1 … pn -> e    =   \ x1 … xn -> case (x1, …, xn) of (p1, …, pn) -> e

https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-260003.3

So \True () -> e desugars to \x y -> case (x, y) of (True, ()) -> e, which after partial application to False is \y -> case (False, y) of ... i.e., a function abstraction, so that's not bottom.

In contrast, \True -> f (where f = \() -> e) desugars to \x -> case x of True -> ..., and there's the exception.


问:
Trying to get a tooltip shown in eventRender from the fullcalendar documentation
Im working on a fullCalendar overview interface Using: Flask-python on server and html jinja2 js on client side.

Right now i am trying to create a tooltip on hover or click using tooltip.js.

I have a bug that drives me to the popper.js index.

here is my basic js:

```<code> document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');

    var calendar = new FullCalendar.Calendar(calendarEl, {
            plugins: ['dayGrid'],
            defaultView: 'dayGridMonth',

            eventRender: function(info) {
             var tooltip = new Tooltip(info.el, {
                    title: "info.event.extendedProps.description",
                    placement: 'top',
                    trigger: 'hover',
                    container: 'body'
                  });
        },
        events: {{hour}}

    });

    calendar.render();

  });
</code>```

From what i saw, le eventRender is called, if i mouseover the tooltip div is created BUT i got this error:

```<code>Uncaught TypeError: a is not a constructor
at g.value (index.js:246)
at index.js:381
</code>```

which is referencing this:

```<code>this.popperInstance = new Popper(
  reference,
  tooltipNode,
  this._popperOptions
);
</code>```

答:
In case someone else runs into this -- if you're not using Bootstrap, it's likely due to the order in which you're loading Popper and Tooltip.

Popper.js is a dependency of Tooltip.js, so it has to be loaded before Tooltip.js. a is not a constructor because a is undefined, and if you look at the source code, a represents Popper.

Body:
Im working on a fullCalendar overview interface Using: Flask-python on server and html jinja2 js on client side.

Right now i am trying to create a tooltip on hover or click using tooltip.js.

I have a bug that drives me to the popper.js index.

here is my basic js:

 document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');

    var calendar = new FullCalendar.Calendar(calendarEl, {
            plugins: ['dayGrid'],
            defaultView: 'dayGridMonth',

            eventRender: function(info) {
             var tooltip = new Tooltip(info.el, {
                    title: "info.event.extendedProps.description",
                    placement: 'top',
                    trigger: 'hover',
                    container: 'body'
                  });
        },
        events: {{hour}}

    });

    calendar.render();

  });

From what i saw, le eventRender is called, if i mouseover the tooltip div is created BUT i got this error:

Uncaught TypeError: a is not a constructor
at g.value (index.js:246)
at index.js:381

which is referencing this:

this.popperInstance = new Popper(
  reference,
  tooltipNode,
  this._popperOptions
);


问:
Identify different sequences with equal elements
I would like to get a sequence vector that is not influenced by equal values.

```<code>group = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3 )

x = c("B","B",NA,"A","B","C","D", "A","A",NA,"A","A","A", "D","A","A","D","C","D")

dad = data.frame(group, x)
</code>```

Expected vector

```<code>out = c(1,1,NA,2,3,4,5, 1,1,NA,1,1,1, 1,2,2,3,4,5)

dad = cbind(dad, out)
</code>```

That is, for example, in group 1 the element "B" appears again, but it must continue the sequence when there is a change in the sequence. In the cases NA will be NA.

答:
An option with data.table.  Convert the 'data.frame' to 'data.table' (setDT(dad)), grouped by 'group', specify the i with a logical index to select only rows where 'x' is non-NA, and get the run-length-id (rleid) of 'x' to be assigned as new column 'ind'

```<code>library(data.table)
setDT(dad)[!is.na(x),  ind := rleid(x), group]
dad
#    group    x ind
#1:     1    B   1
#2:     1    B   1
#3:     1 <NA>  NA
#4:     1    A   2
#5:     1    B   3
#6:     1    C   4
#7:     1    D   5
#8:     2    A   1
#9:     2    A   1
#10     2 <NA>  NA
#11:    2    A   1
#12:    2    A   1
#13:    2    A   1
#14:    3    D   1
#15:    3    A   2
#16:    3    A   2
#17:    3    D   3
#18:    3    C   4
#19:    3    D   5
</code>```

Body:
I would like to get a sequence vector that is not influenced by equal values.

group = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3 )

x = c("B","B",NA,"A","B","C","D", "A","A",NA,"A","A","A", "D","A","A","D","C","D")

dad = data.frame(group, x)

Expected vector

out = c(1,1,NA,2,3,4,5, 1,1,NA,1,1,1, 1,2,2,3,4,5)

dad = cbind(dad, out)

That is, for example, in group 1 the element "B" appears again, but it must continue the sequence when there is a change in the sequence. In the cases NA will be NA.

Body:
An option with data.table.  Convert the 'data.frame' to 'data.table' (setDT(dad)), grouped by 'group', specify the i with a logical index to select only rows where 'x' is non-NA, and get the run-length-id (rleid) of 'x' to be assigned as new column 'ind'

library(data.table)
setDT(dad)[!is.na(x),  ind := rleid(x), group]
dad
#    group    x ind
#1:     1    B   1
#2:     1    B   1
#3:     1 <NA>  NA
#4:     1    A   2
#5:     1    B   3
#6:     1    C   4
#7:     1    D   5
#8:     2    A   1
#9:     2    A   1
#10     2 <NA>  NA
#11:    2    A   1
#12:    2    A   1
#13:    2    A   1
#14:    3    D   1
#15:    3    A   2
#16:    3    A   2
#17:    3    D   3
#18:    3    C   4
#19:    3    D   5


问:
Select rows by comparing with next row
I have the following table,

```<code>value   caseid    version
-----   ------    -------
2.6     1         A
2.7     1         B
4.8     2         A
5.4     2         B
2.9     3         A
3.0     3         B
</code>```

and I want to compare the value in rows with version A with those in version B with the same caseid, and only display rows that have a difference of greater than 0.1.

So, in the above example, the result should be:

```<code>value   caseid    version
-----   ------    -------
4.8     2         A
5.4     2         B
</code>```

I've tried with a join, but then both rows get displayed in the same row.
Is there a way to do this where values get displayed on different rows?

Thank you.

答:
you can do it by using  union all

```<code>
with tab as(
select 2.6 as value,     1  as caseid,       'A' as version from dual union all
select 2.7,     1,         'B' from dual union all
select 4.8,     2,         'A' from dual union all
select 5.4,     2,         'B' from dual union all
select 2.9,     3,         'A' from dual union all
select 3.0,     3,         'B' from dual
)

select t1.value, t1.caseid, t1.version
  from tab t1
  join tab t2 on t1.caseid = t2.caseid
  where (t1.value- t2.value) > 0.1
union all
select t2.value, t2.caseid, t2.version
  from tab t1
  join tab t2 on t1.caseid = t2.caseid
  where (t1.value- t2.value) > 0.1
</code>```

db<>fiddle here

Title: Select rows by comparing with next row

Body:
I have the following table,

value   caseid    version
-----   ------    -------
2.6     1         A
2.7     1         B
4.8     2         A
5.4     2         B
2.9     3         A
3.0     3         B

and I want to compare the value in rows with version A with those in version B with the same caseid, and only display rows that have a difference of greater than 0.1.

So, in the above example, the result should be:

value   caseid    version
-----   ------    -------
4.8     2         A
5.4     2         B

I've tried with a join, but then both rows get displayed in the same row.
Is there a way to do this where values get displayed on different rows?

Thank you.

Body:
you can do it by using  union all

with tab as(
select 2.6 as value,     1  as caseid,       'A' as version from dual union all
select 2.7,     1,         'B' from dual union all
select 4.8,     2,         'A' from dual union all
select 5.4,     2,         'B' from dual union all
select 2.9,     3,         'A' from dual union all
select 3.0,     3,         'B' from dual
)

select t1.value, t1.caseid, t1.version
  from tab t1
  join tab t2 on t1.caseid = t2.caseid
  where (t1.value- t2.value) > 0.1
union all
select t2.value, t2.caseid, t2.version
  from tab t1
  join tab t2 on t1.caseid = t2.caseid
  where (t1.value- t2.value) > 0.1

db<>fiddle here


问:
Object reference null- URL rewriting asp.net
I have developed my asp.net website in .NET 2.0 in other system where it is working fine. Now when I copied the asp.net website in my system and run it than I am getting the run time error:

Object reference not set to an
  instance of an object.

```<code> public class FixURLs : IHttpModule
{
    public FixURLs()
    {

    }

    #region IHttpModule Members

    public void Dispose()
    {
        // do nothing
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
        context.CompleteRequest();

    }

 ..... some other logic
</code>```

I am getting object reference error at the line:

```<code>context.CompleteRequest();
</code>```

My web.Config file has

```<code><compilation debug="true">
  <assemblies>
    <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  </assemblies>
</compilation>
</code>```

How can I fix this issue?

EDIT
Edit Note New code added

```<code> void context_BeginRequest(object sender, EventArgs e)
{

    HttpApplication app = (HttpApplication)sender;

    if (app.Request.RawUrl.ToLower().Contains("/bikes/default.aspx"))
    {
        app.Context.RewritePath("BikeInfo.aspx", "", "");
    }
    else if (app.Request.RawUrl.ToLower().Contains("/bikes/mountainbike.aspx"))
    {
        app.Context.RewritePath("BikeInfo.aspx", "", "ItemID=1");
    }
 }
</code>```

答:
I think you should just leave out your call to context.CompleteRequest();

This is normally meant to stop the execution of a request, but you're calling it when your application is initializing and no requests are being processed. My guess was that in .NET 2.0 it would tolerate this call and not do anything bad, but in a later version it blows up.

It doesn't look to me like you want to stop the request immediately after you've rewritten the URLs... otherwise, why even rewrite them? So just try getting rid of that method call.

ContentLicense: CC BY-SA 2.5

Body:
I have developed my asp.net website in .NET 2.0 in other system where it is working fine. Now when I copied the asp.net website in my system and run it than I am getting the run time error:

Object reference not set to an
  instance of an object.

 public class FixURLs : IHttpModule
{
    public FixURLs()
    {

    }

    #region IHttpModule Members

    public void Dispose()
    {
        // do nothing
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
        context.CompleteRequest();

    }

 ..... some other logic

I am getting object reference error at the line:

context.CompleteRequest();

My web.Config file has

<compilation debug="true">
  <assemblies>
    <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  </assemblies>
</compilation>

How can I fix this issue?

EDIT
Edit Note New code added

 void context_BeginRequest(object sender, EventArgs e)
{

    HttpApplication app = (HttpApplication)sender;

    if (app.Request.RawUrl.ToLower().Contains("/bikes/default.aspx"))
    {
        app.Context.RewritePath("BikeInfo.aspx", "", "");
    }
    else if (app.Request.RawUrl.ToLower().Contains("/bikes/mountainbike.aspx"))
    {
        app.Context.RewritePath("BikeInfo.aspx", "", "ItemID=1");
    }
 }


问:
can't connect on mongodb in docker on windows 10
This is my docker-compose.yml setting for MongoDB

```<code> image: mongo:latest
 container_name: 'mongodb'
 ports:+
   - 27018:27017
 restart: always
</code>```

It works great on mac but keeps failing to connect on win10 on port 0.0.0.0:27018

答:
It's recommended to present the port configuration in quotes to avoid erroneous after effects.

Reference -> https://docs.docker.com/compose/compose-file/compose-file-v2/

This can work

```<code>image: mongo:latest
 container_name: 'mongodb'
 ports:+
   - "27018:27017"
 restart: always
</code>```

Body:
This is my docker-compose.yml setting for MongoDB

 image: mongo:latest
 container_name: 'mongodb'
 ports:+
   - 27018:27017
 restart: always

It works great on mac but keeps failing to connect on win10 on port 0.0.0.0:27018

Body:
It's recommended to present the port configuration in quotes to avoid erroneous after effects.

Reference -> https://docs.docker.com/compose/compose-file/compose-file-v2/

This can work

image: mongo:latest
 container_name: 'mongodb'
 ports:+
   - "27018:27017"
 restart: always


问:
Send HTTP request to server hosted on AWS EC2 instance
I'm trying to send an HTTP POST request from the client to a server hosted on my AWS EC2 instance. I get this error when I try to set up the server on AWS.

```<code>Traceback (most recent call last):
  File "testReceive_AWS.py", line 197, in <module>
    httpd = server_class((server_address), MyHandler)
  File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
    self.server_bind()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
    SocketServer.TCPServer.server_bind(self)
  File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
    self.socket.bind(self.server_address)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address
</code>```

Here's my code:

```<code>if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    handler_class=BaseHTTPServer.BaseHTTPRequestHandler

    server_address = ('EC2 instance public ip address', 9000)

    httpd = server_class((server_address), MyHandler)

    print time.asctime(), "Server Starts - %s:%s" % (server_address)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (server_address)
</code>```

I've confirmed that the IP address is correct. What am I doing wrong?

答:
For some reason changing to server_address = ('0.0.0.0', 9000) threw a similar error.

But changing to server_address = (' ', 9000) worked.

Body:
I'm trying to send an HTTP POST request from the client to a server hosted on my AWS EC2 instance. I get this error when I try to set up the server on AWS.

Traceback (most recent call last):
  File "testReceive_AWS.py", line 197, in <module>
    httpd = server_class((server_address), MyHandler)
  File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
    self.server_bind()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
    SocketServer.TCPServer.server_bind(self)
  File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
    self.socket.bind(self.server_address)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address

Here's my code:

if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    handler_class=BaseHTTPServer.BaseHTTPRequestHandler

    server_address = ('EC2 instance public ip address', 9000)

    httpd = server_class((server_address), MyHandler)

    print time.asctime(), "Server Starts - %s:%s" % (server_address)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (server_address)

I've confirmed that the IP address is correct. What am I doing wrong?


问:
How to get the value of a key in a JSON?
I have a JSON body. I would like to obtain the value of "access_token". I would like to use grep in bash. The grep I used doesn't not work.

I tried the following but it provides me a blank result.

```<code>HTTP_BODY=$(echo $HTTP_RESPONSE | grep ^"access_token":" ","experies_in$ )
</code>```

I want only to obtain the access_token value, i.e.:

```<code>eyJhbGciOiJSUzI1NiIsImtpZCI6IkE4M0UwQTFEQTY1MzE0NkZENUQxOTFDMzRDNTQ0RDJDODYyMzMzMzkiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJxRDRLSGFaVEZHX1YwWkhEVEZSTkxJWWpNemsifQ.eyJuYmYiOjE1NTkzMTYzNTYsImV4cCI6MTU1OTMxOTk1NiwiaXNzIjoiaHR0cHM6Ly9jaW5jaHktbnByLmNsb3VkLnJlcy5ibmdmLmxvY2FsL2NpbmNoeXNzbyIsImF1ZCI6WyJodHRwczovL2NpbmNoeS1ucHIuY2xvdWQucmVzLmJuZ2YubG9jYWwvY2luY2h5c3NvL3Jlc291cmNlcyIsImpzX2FwaSJdLCJjbGllbnRfaWQiOiJhcGkiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTU5MzE2MzU2LCJpZHAiOiJsb2NhbCIsInByb2ZpbGUiOiJBZG1pbmlzdHJhdG9yIiwiZW1haWwiOiJhZG1pbkBjaW5jaHkuY28iLCJyb2xlIjoiQ2luY2h5IFVzZXIgQWNjb3VudCIsImlkIjoiYWRtaW4iLCJzY29wZSI6WyJqc19hcGkiXSwiYW1yIjpbImN1c3RvbSJdfQ.O0--cahxPKlwHp-7fP0CMgSJTaXleupH32x7vVoxe8THVdeRIgyuZoKWPAK9p10PMO9a5Mi3N0t1Nqut5-dUS7lmeUfNKe25K1got9de7ghQ56QQXnL2SWd6g4I8Zi1R9fZsln7bZCIJvnG3_wIWHKGHBco9jEvKtO3AdYF4T9LAbdpT51SDzKPhX16BPc0Do6KfNImQpPQdK4fP3-JqxD4sOBldUg-g3aau2F_DmapEd0p5hTI4qeKgORnXJ3NadwWscQREGWVXhIRu_BF_cmEoIfPNyJI7D_L7EWn8XcFa2Gu-8khQ-WDpVUcpyidF_VHYRkMtYwpJ2dcYUaLILQ
</code>```

Input:

```<code>HTTP_RESPONSE="{"access_token":"eyJhbGciOiJSUzI1NiIsImtpZCI6IkE4M0UwQTFEQTY1MzE0NkZENUQxOTFDMzRDNTQ0RDJDODYyMzMzMzkiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJxRDRLSGFaVEZHX1YwWkhEVEZSTkxJWWpNemsifQ.eyJuYmYiOjE1NTkzMTYzNTYsImV4cCI6MTU1OTMxOTk1NiwiaXNzIjoiaHR0cHM6Ly9jaW5jaHktbnByLmNsb3VkLnJlcy5ibmdmLmxvY2FsL2NpbmNoeXNzbyIsImF1ZCI6WyJodHRwczovL2NpbmNoeS1ucHIuY2xvdWQucmVzLmJuZ2YubG9jYWwvY2luY2h5c3NvL3Jlc291cmNlcyIsImpzX2FwaSJdLCJjbGllbnRfaWQiOiJhcGkiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTU5MzE2MzU2LCJpZHAiOiJsb2NhbCIsInByb2ZpbGUiOiJBZG1pbmlzdHJhdG9yIiwiZW1haWwiOiJhZG1pbkBjaW5jaHkuY28iLCJyb2xlIjoiQ2luY2h5IFVzZXIgQWNjb3VudCIsImlkIjoiYWRtaW4iLCJzY29wZSI6WyJqc19hcGkiXSwiYW1yIjpbImN1c3RvbSJdfQ.O0--cahxPKlwHp-7fP0CMgSJTaXleupH32x7vVoxe8THVdeRIgyuZoKWPAK9p10PMO9a5Mi3N0t1Nqut5-dUS7lmeUfNKe25K1got9de7ghQ56QQXnL2SWd6g4I8Zi1R9fZsln7bZCIJvnG3_wIWHKGHBco9jEvKtO3AdYF4T9LAbdpT51SDzKPhX16BPc0Do6KfNImQpPQdK4fP3-JqxD4sOBldUg-g3aau2F_DmapEd0p5hTI4qeKgORnXJ3NadwWscQREGWVXhIRu_BF_cmEoIfPNyJI7D_L7EWn8XcFa2Gu-8khQ-WDpVUcpyidF_VHYRkMtYwpJ2dcYUaLILQ","expires_in":360,"token_type":"Bearer"}"
</code>```

Expected Output:

```<code>eyJhbGciOiJSUzI1NiIsImtpZCI6IkE4M0UwQTFEQTY1MzE0NkZENUQxOTFDMzRDNTQ0RDJDODYyMzMzMzkiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJxRDRLSGFaVEZHX1YwWkhEVEZSTkxJWWpNemsifQ.eyJuYmYiOjE1NTkzMTYzNTYsImV4cCI6MTU1OTMxOTk1NiwiaXNzIjoiaHR0cHM6Ly9jaW5jaHktbnByLmNsb3VkLnJlcy5ibmdmLmxvY2FsL2NpbmNoeXNzbyIsImF1ZCI6WyJodHRwczovL2NpbmNoeS1ucHIuY2xvdWQucmVzLmJuZ2YubG9jYWwvY2luY2h5c3NvL3Jlc291cmNlcyIsImpzX2FwaSJdLCJjbGllbnRfaWQiOiJhcGkiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTU5MzE2MzU2LCJpZHAiOiJsb2NhbCIsInByb2ZpbGUiOiJBZG1pbmlzdHJhdG9yIiwiZW1haWwiOiJhZG1pbkBjaW5jaHkuY28iLCJyb2xlIjoiQ2luY2h5IFVzZXIgQWNjb3VudCIsImlkIjoiYWRtaW4iLCJzY29wZSI6WyJqc19hcGkiXSwiYW1yIjpbImN1c3RvbSJdfQ.O0--cahxPKlwHp-7fP0CMgSJTaXleupH32x7vVoxe8THVdeRIgyuZoKWPAK9p10PMO9a5Mi3N0t1Nqut5-dUS7lmeUfNKe25K1got9de7ghQ56QQXnL2SWd6g4I8Zi1R9fZsln7bZCIJvnG3_wIWHKGHBco9jEvKtO3AdYF4T9LAbdpT51SDzKPhX16BPc0Do6KfNImQpPQdK4fP3-JqxD4sOBldUg-g3aau2F_DmapEd0p5hTI4qeKgORnXJ3NadwWscQREGWVXhIRu_BF_cmEoIfPNyJI7D_L7EWn8XcFa2Gu-8khQ-WDpVUcpyidF_VHYRkMtYwpJ2dcYUaLILQ
</code>```

Body:
I have a JSON body. I would like to obtain the value of "access_token". I would like to use grep in bash. The grep I used doesn't not work.

I tried the following but it provides me a blank result.

HTTP_BODY=$(echo $HTTP_RESPONSE | grep ^"access_token":" ","experies_in$ )

I want only to obtain the access_token value, i.e.:

eyJhbGciOiJSUzI1NiIsImtpZCI6IkE4M0UwQTFEQTY1MzE0NkZENUQxOTFDMzRDNTQ0RDJDODYyMzMzMzkiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJxRDRLSGFaVEZHX1YwWkhEVEZSTkxJWWpNemsifQ.eyJuYmYiOjE1NTkzMTYzNTYsImV4cCI6MTU1OTMxOTk1NiwiaXNzIjoiaHR0cHM6Ly9jaW5jaHktbnByLmNsb3VkLnJlcy5ibmdmLmxvY2FsL2NpbmNoeXNzbyIsImF1ZCI6WyJodHRwczovL2NpbmNoeS1ucHIuY2xvdWQucmVzLmJuZ2YubG9jYWwvY2luY2h5c3NvL3Jlc291cmNlcyIsImpzX2FwaSJdLCJjbGllbnRfaWQiOiJhcGkiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTU5MzE2MzU2LCJpZHAiOiJsb2NhbCIsInByb2ZpbGUiOiJBZG1pbmlzdHJhdG9yIiwiZW1haWwiOiJhZG1pbkBjaW5jaHkuY28iLCJyb2xlIjoiQ2luY2h5IFVzZXIgQWNjb3VudCIsImlkIjoiYWRtaW4iLCJzY29wZSI6WyJqc19hcGkiXSwiYW1yIjpbImN1c3RvbSJdfQ.O0--cahxPKlwHp-7fP0CMgSJTaXleupH32x7vVoxe8THVdeRIgyuZoKWPAK9p10PMO9a5Mi3N0t1Nqut5-dUS7lmeUfNKe25K1got9de7ghQ56QQXnL2SWd6g4I8Zi1R9fZsln7bZCIJvnG3_wIWHKGHBco9jEvKtO3AdYF4T9LAbdpT51SDzKPhX16BPc0Do6KfNImQpPQdK4fP3-JqxD4sOBldUg-g3aau2F_DmapEd0p5hTI4qeKgORnXJ3NadwWscQREGWVXhIRu_BF_cmEoIfPNyJI7D_L7EWn8XcFa2Gu-8khQ-WDpVUcpyidF_VHYRkMtYwpJ2dcYUaLILQ

Input:

HTTP_RESPONSE="{"access_token":"eyJhbGciOiJSUzI1NiIsImtpZCI6IkE4M0UwQTFEQTY1MzE0NkZENUQxOTFDMzRDNTQ0RDJDODYyMzMzMzkiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJxRDRLSGFaVEZHX1YwWkhEVEZSTkxJWWpNemsifQ.eyJuYmYiOjE1NTkzMTYzNTYsImV4cCI6MTU1OTMxOTk1NiwiaXNzIjoiaHR0cHM6Ly9jaW5jaHktbnByLmNsb3VkLnJlcy5ibmdmLmxvY2FsL2NpbmNoeXNzbyIsImF1ZCI6WyJodHRwczovL2NpbmNoeS1ucHIuY2xvdWQucmVzLmJuZ2YubG9jYWwvY2luY2h5c3NvL3Jlc291cmNlcyIsImpzX2FwaSJdLCJjbGllbnRfaWQiOiJhcGkiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTU5MzE2MzU2LCJpZHAiOiJsb2NhbCIsInByb2ZpbGUiOiJBZG1pbmlzdHJhdG9yIiwiZW1haWwiOiJhZG1pbkBjaW5jaHkuY28iLCJyb2xlIjoiQ2luY2h5IFVzZXIgQWNjb3VudCIsImlkIjoiYWRtaW4iLCJzY29wZSI6WyJqc19hcGkiXSwiYW1yIjpbImN1c3RvbSJdfQ.O0--cahxPKlwHp-7fP0CMgSJTaXleupH32x7vVoxe8THVdeRIgyuZoKWPAK9p10PMO9a5Mi3N0t1Nqut5-dUS7lmeUfNKe25K1got9de7ghQ56QQXnL2SWd6g4I8Zi1R9fZsln7bZCIJvnG3_wIWHKGHBco9jEvKtO3AdYF4T9LAbdpT51SDzKPhX16BPc0Do6KfNImQpPQdK4fP3-JqxD4sOBldUg-g3aau2F_DmapEd0p5hTI4qeKgORnXJ3NadwWscQREGWVXhIRu_BF_cmEoIfPNyJI7D_L7EWn8XcFa2Gu-8khQ-WDpVUcpyidF_VHYRkMtYwpJ2dcYUaLILQ","expires_in":360,"token_type":"Bearer"}"

Expected Output:

eyJhbGciOiJSUzI1NiIsImtpZCI6IkE4M0UwQTFEQTY1MzE0NkZENUQxOTFDMzRDNTQ0RDJDODYyMzMzMzkiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJxRDRLSGFaVEZHX1YwWkhEVEZSTkxJWWpNemsifQ.eyJuYmYiOjE1NTkzMTYzNTYsImV4cCI6MTU1OTMxOTk1NiwiaXNzIjoiaHR0cHM6Ly9jaW5jaHktbnByLmNsb3VkLnJlcy5ibmdmLmxvY2FsL2NpbmNoeXNzbyIsImF1ZCI6WyJodHRwczovL2NpbmNoeS1ucHIuY2xvdWQucmVzLmJuZ2YubG9jYWwvY2luY2h5c3NvL3Jlc291cmNlcyIsImpzX2FwaSJdLCJjbGllbnRfaWQiOiJhcGkiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTU5MzE2MzU2LCJpZHAiOiJsb2NhbCIsInByb2ZpbGUiOiJBZG1pbmlzdHJhdG9yIiwiZW1haWwiOiJhZG1pbkBjaW5jaHkuY28iLCJyb2xlIjoiQ2luY2h5IFVzZXIgQWNjb3VudCIsImlkIjoiYWRtaW4iLCJzY29wZSI6WyJqc19hcGkiXSwiYW1yIjpbImN1c3RvbSJdfQ.O0--cahxPKlwHp-7fP0CMgSJTaXleupH32x7vVoxe8THVdeRIgyuZoKWPAK9p10PMO9a5Mi3N0t1Nqut5-dUS7lmeUfNKe25K1got9de7ghQ56QQXnL2SWd6g4I8Zi1R9fZsln7bZCIJvnG3_wIWHKGHBco9jEvKtO3AdYF4T9LAbdpT51SDzKPhX16BPc0Do6KfNImQpPQdK4fP3-JqxD4sOBldUg-g3aau2F_DmapEd0p5hTI4qeKgORnXJ3NadwWscQREGWVXhIRu_BF_cmEoIfPNyJI7D_L7EWn8XcFa2Gu-8khQ-WDpVUcpyidF_VHYRkMtYwpJ2dcYUaLILQ


问:
p5js - Animating lines with 3 different positions
In my project i have 2 lines.
Each line changes position when you click on the screen.
The position of each line always falls randomly in thirds of the screen width.
I accomplished the clicks and the random position in thirds.

Now i would like the lines to animate to the new position on mousePress but i don’t know how to go about it. i’m wondering if a have to rebuild in another way.

can someone guide me? :slight_smile:

https://editor.p5js.org/antoniofrom1984/sketches/8n9le2Wvh

```<code>function setup(){
  createCanvas(windowWidth, windowHeight);
}

function draw(){
  noLoop();
  background(backcolor);
}

function mousePressed(){
  loop();
  var h = height;
  var w = width;
  var thirdsH = [h/3, h/2, h/1.5 ];
  var thirdsV = [w/3, w/2, w/1.5];

  var randomthirdsH = random(thirdsH);
  var randomthirdsV = random(thirdsV);
  strokeWeight(2);
  stroke(linecolor);
  line(0, randomthirdsH, w, randomthirdsH);
  line(randomthirdsV, 0 ,randomthirdsV, h);

  print(randomthirdsH);
}
</code>```

答:
To do what you want you, you've to remove tha noLoop() instruction and to implement the animation in draw().

Define a current_pos variable for the current position of the line, a target_pos variable for the target position of the line and a speed for the animation. Let current_pos and  target_pos undefined:

let current_pos, target_pos;
let speed = 2;
```

<p>Set the target position <code>target_pos</code>, when the mouse is pressed:</p>

<pre class="lang-js prettyprint-override"><code>function mousePressed(){
    var h = height;
    var w = width;
    var thirdsH = [h/3, h/2, h/1.5 ];
    var thirdsV = [w/3, w/2, w/1.5];
    target_pos = [random(thirdsV), random(thirdsH)];
}
</code>```

As soon as target_pos is define, start to draw the line in draw. If current_pos is not defined, then initialize current_pos by target_pos. This happens when the line is drawn the first time:

if (target_pos) {
    if (!current_pos) {
        current_pos = [target_pos[0], target_pos[1]];
    } else {
        // [...]
    }

    // [...]
}
```

<p>When the <code>target_pos</code> is changed the change the <code>current_pos</code> by <code>speed</code> and slightly move it in the direction of <code>target_pos</code>:</p>

<pre class="lang-js prettyprint-override"><code>for (let i = 0; i < 2; ++i) {
  if (current_pos[i] < target_pos[i])
      current_pos[i] = Math.min(target_pos[i], current_pos[i]+speed)
  else if (current_pos[i] > target_pos[i])
      current_pos[i] = Math.max(target_pos[i], current_pos[i]-speed)
}
</code>```

Always draw the line at current_pos:

line(0, current_pos[1], width, current_pos[1]);
line(current_pos[0], 0, current_pos[0], height);
```

<p>See the example, where I applied the suggestions to your original code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let backcolor = (0, 0, 0);
let linecolor = (255, 255, 255);
let current_pos, target_pos;
let speed = 2;

function setup(){
    createCanvas(windowWidth, windowHeight);

    // this is just to see somthing at start
    target_pos = [10, 10]
}

function draw(){
    background(backcolor);

    if (target_pos) {
        if (!current_pos) {
            current_pos = [target_pos[0], target_pos[1]];
        } else {
            for (let i = 0; i < 2; ++i) {
               if (current_pos[i] < target_pos[i])
                   current_pos[i] = Math.min(target_pos[i], current_pos[i]+speed)
               else if (current_pos[i] > target_pos[i])
                   current_pos[i] = Math.max(target_pos[i], current_pos[i]-speed)
           }
        }

        // draw lines
        strokeWeight(2);
        stroke(linecolor);
        line(0, current_pos[1], width, current_pos[1]);
        line(current_pos[0], 0, current_pos[0], height);

        // draw target marker
        strokeWeight(3);
        stroke(255, 0, 0);
        line(target_pos[0]-10, target_pos[1], target_pos[0]+10, target_pos[1]);
        line(target_pos[0], target_pos[1]-10, target_pos[0], target_pos[1]+10);
    }
}

function mousePressed(){
    var h = height;
    var w = width;
    var thirdsH = [h/3, h/2, h/1.5 ];
    var thirdsV = [w/3, w/2, w/1.5];
    target_pos = [random(thirdsV), random(thirdsH)];
}</code>```

```

Body:
In my project i have 2 lines.
Each line changes position when you click on the screen.
The position of each line always falls randomly in thirds of the screen width.
I accomplished the clicks and the random position in thirds.

Now i would like the lines to animate to the new position on mousePress but i don’t know how to go about it. i’m wondering if a have to rebuild in another way.

can someone guide me? :slight_smile:

https://editor.p5js.org/antoniofrom1984/sketches/8n9le2Wvh

function setup(){
  createCanvas(windowWidth, windowHeight);
}

function draw(){
  noLoop();
  background(backcolor);
}

function mousePressed(){
  loop();
  var h = height;
  var w = width;
  var thirdsH = [h/3, h/2, h/1.5 ];
  var thirdsV = [w/3, w/2, w/1.5];

  var randomthirdsH = random(thirdsH);
  var randomthirdsV = random(thirdsV);
  strokeWeight(2);
  stroke(linecolor);
  line(0, randomthirdsH, w, randomthirdsH);
  line(randomthirdsV, 0 ,randomthirdsV, h);

  print(randomthirdsH);
}

Body:
To do what you want you, you've to remove tha noLoop() instruction and to implement the animation in draw().

Define a current_pos variable for the current position of the line, a target_pos variable for the target position of the line and a speed for the animation. Let current_pos and  target_pos undefined:

let current_pos, target_pos;
let speed = 2;

Set the target position target_pos, when the mouse is pressed:

function mousePressed(){
    var h = height;
    var w = width;
    var thirdsH = [h/3, h/2, h/1.5 ];
    var thirdsV = [w/3, w/2, w/1.5];
    target_pos = [random(thirdsV), random(thirdsH)];
}

As soon as target_pos is define, start to draw the line in draw. If current_pos is not defined, then initialize current_pos by target_pos. This happens when the line is drawn the first time:

if (target_pos) {
    if (!current_pos) {
        current_pos = [target_pos[0], target_pos[1]];
    } else {
        // [...]
    }

    // [...]
}

When the target_pos is changed the change the current_pos by speed and slightly move it in the direction of target_pos:

for (let i = 0; i < 2; ++i) {
  if (current_pos[i] < target_pos[i])
      current_pos[i] = Math.min(target_pos[i], current_pos[i]+speed)
  else if (current_pos[i] > target_pos[i])
      current_pos[i] = Math.max(target_pos[i], current_pos[i]-speed)
}

Always draw the line at current_pos:

line(0, current_pos[1], width, current_pos[1]);
line(current_pos[0], 0, current_pos[0], height);

See the example, where I applied the suggestions to your original code:

let backcolor = (0, 0, 0);
let linecolor = (255, 255, 255);
let current_pos, target_pos;
let speed = 2;

function setup(){
    createCanvas(windowWidth, windowHeight);

    // this is just to see somthing at start
    target_pos = [10, 10]
}

function draw(){
    background(backcolor);

    if (target_pos) {
        if (!current_pos) {
            current_pos = [target_pos[0], target_pos[1]];
        } else {
            for (let i = 0; i < 2; ++i) {
               if (current_pos[i] < target_pos[i])
                   current_pos[i] = Math.min(target_pos[i], current_pos[i]+speed)
               else if (current_pos[i] > target_pos[i])
                   current_pos[i] = Math.max(target_pos[i], current_pos[i]-speed)
           }
        }

        // draw lines
        strokeWeight(2);
        stroke(linecolor);
        line(0, current_pos[1], width, current_pos[1]);
        line(current_pos[0], 0, current_pos[0], height);

        // draw target marker
        strokeWeight(3);
        stroke(255, 0, 0);
        line(target_pos[0]-10, target_pos[1], target_pos[0]+10, target_pos[1]);
        line(target_pos[0], target_pos[1]-10, target_pos[0], target_pos[1]+10);
    }
}

function mousePressed(){
    var h = height;
    var w = width;
    var thirdsH = [h/3, h/2, h/1.5 ];
    var thirdsV = [w/3, w/2, w/1.5];
    target_pos = [random(thirdsV), random(thirdsH)];
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>


问:
How to remove properties of objects from a array in javascript?
How to remove a key from an object

This function takes an array of user objects and deletes the moto key-value pair on each user object.

I have tried this code:

```<code>function deleteAllMoto(users) {

   for(var i=0; i<=users.length; i++) {

    delete users[i].password;
    return users[i];

}

</code>```

答:
Something like this:

```<code>function deleteAllMoto (arr) {
  arr.forEach(function(item) {
    delete item.moto
  })
  return arr
}
</code>```

From your code you are deleting password not moto, then trying to return each user instead of the whole array after the mutations.

Body:
How to remove a key from an object

This function takes an array of user objects and deletes the moto key-value pair on each user object.

I have tried this code:

function deleteAllMoto(users) {

   for(var i=0; i<=users.length; i++) {

    delete users[i].password;
    return users[i];

}

Body:
Something like this:

function deleteAllMoto (arr) {
  arr.forEach(function(item) {
    delete item.moto
  })
  return arr
}

From your code you are deleting password not moto, then trying to return each user instead of the whole array after the mutations.


问:
HttpClient not supporting PostAsJsonAsync method C#
I am trying to call a web API from my web application. I am using .Net 4.5 and while writing the code I am getting the error HttpClient does not contain a definition PostAsJsonAsync method.

Below is the code:

```<code>HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:51093/");
client.DefaultRequestHeaders.Accept.Add(
   new MediaTypeWithQualityHeaderValue("application/json"));
var user = new Users();
user.AgentCode = 100;
user.Remarks = "Test";
user.CollectionDate = System.DateTime.Today;
user.RemittanceDate = System.DateTime.Today;
user.TotalAmount = 1000;
user.OrgBranchID = 101;

var response = client.PostAsJsonAsync("api/AgentCollection", user).Result;
</code>```

and I am getting the error message:

Error:  'System.Net.Http.HttpClient' does not contain a definition for
  'PostAsJsonAsync' and No extension method 'PostAsJsonAsync' accepting a first argument of
  type     'System.Net.Http.HttpClient' could be found (are you missing
  a using directive or an assembly reference?)

Please have a look  and advice me.

答:
Try to install in your project the NuGet Package:  Microsoft.AspNet.WebApi.Client:</p>

```<code>Install-Package Microsoft.AspNet.WebApi.Client
</code>```

Body:
I am trying to call a web API from my web application. I am using .Net 4.5 and while writing the code I am getting the error HttpClient does not contain a definition PostAsJsonAsync method.

Below is the code:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:51093/");
client.DefaultRequestHeaders.Accept.Add(
   new MediaTypeWithQualityHeaderValue("application/json"));
var user = new Users();
user.AgentCode = 100;
user.Remarks = "Test";
user.CollectionDate = System.DateTime.Today;
user.RemittanceDate = System.DateTime.Today;
user.TotalAmount = 1000;
user.OrgBranchID = 101;

var response = client.PostAsJsonAsync("api/AgentCollection", user).Result;

and I am getting the error message:

Error:  'System.Net.Http.HttpClient' does not contain a definition for
  'PostAsJsonAsync' and No extension method 'PostAsJsonAsync' accepting a first argument of
  type     'System.Net.Http.HttpClient' could be found (are you missing
  a using directive or an assembly reference?)

Please have a look  and advice me.

Body:
Try to install in your project the NuGet Package:  Microsoft.AspNet.WebApi.Client:

Install-Package Microsoft.AspNet.WebApi.Client


问:
How to display and filter this array for angular/typescript app?
I'm wanting to group and display the data by BreakdownPalletID in the array below. I'm using typescript/angular and wanting to show this data grouped by Breakdown Pallet ID and then for each show the list of LPs and Skus for each one but i'm not sure how to do that with the JSON object the way it is below. The number of breakdownPalletIDs is also dynamic</p>

```<code> {
        "palletCount": 4,
        "lpCount": 6,
        "Sku": [
            {
                "sku": 394211,
                "lp": "00006844763464291206",
                "breakdownPalletID": 4,
                "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]

            },
            {
                "sku": 395299,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464289555",
                "breakdownPalletID": 4,
                    "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464291039",
                "breakdownPalletID": 2,
                "customerMessages": ["MESSAGE 1","MESSAGE 2","MESSAGE 3"]
            },
            {
                "sku": 461716,
                "lp": "00006844763464291336",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 506733,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
            "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 519795,
                "lp": "00006844763464291206",
                "breakdownPalletID": 3,
                "customerMessages": ["MESSAGE 5","MESSAGE 6","MESSAGE 7"]

            }
            ]
    }
</code>```

Body:
I'm wanting to group and display the data by BreakdownPalletID in the array below. I'm using typescript/angular and wanting to show this data grouped by Breakdown Pallet ID and then for each show the list of LPs and Skus for each one but i'm not sure how to do that with the JSON object the way it is below. The number of breakdownPalletIDs is also dynamic

 {
        "palletCount": 4,
        "lpCount": 6,
        "Sku": [
            {
                "sku": 394211,
                "lp": "00006844763464291206",
                "breakdownPalletID": 4,
                "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]

            },
            {
                "sku": 395299,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464289555",
                "breakdownPalletID": 4,
                    "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464291039",
                "breakdownPalletID": 2,
                "customerMessages": ["MESSAGE 1","MESSAGE 2","MESSAGE 3"]
            },
            {
                "sku": 461716,
                "lp": "00006844763464291336",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 506733,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
            "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 519795,
                "lp": "00006844763464291206",
                "breakdownPalletID": 3,
                "customerMessages": ["MESSAGE 5","MESSAGE 6","MESSAGE 7"]

            }
            ]
    }

Body:
If you want to simplify life with libraries like lodash or underscore!

example with underscore:

_.groupBy(this.data.Sku, (item: any) => item.breakdownPalletID);

will give you result like this:

    {
  "1": [
    {
      "sku": 395299,
      "lp": "00006844763464289555",
      "breakdownPalletID": 1
    },
    {
      "sku": 461716,
      "lp": "00006844763464291336",
      "breakdownPalletID": 1
    },
    {
      "sku": 506733,
      "lp": "00006844763464289555",
      "breakdownPalletID": 1
    }
  ],
  "2": [
    {
      "sku": 460957,
      "lp": "00006844763464291039",
      "breakdownPalletID": 2
    }
  ],
  "3": [
    {
      "sku": 519795,
      "lp": "00006844763464291206",
      "breakdownPalletID": 3
    }
  ],
  "4": [
    {
      "sku": 394211,
      "lp": "00006844763464291206",
      "breakdownPalletID": 4
    },
    {
      "sku": 460957,
      "lp": "00006844763464289555",
      "breakdownPalletID": 4
    }
  ]
}


问:
Raspberrry Pi 3 + Windows IOT Core crashes after some time
Im developing an uwp app on Raspberry Pi 3 with Windows IOT Core. But after I deploy my app and use it for couple days the os crashes. It says something went wrong. It says "Your pc ran into a problem and needs to restart". It restarts couple times but still same error on every boot.

I tried to remove the sd card(Class 10,64 GB) format it and reinstall everything. At first it was okay but after some time same error appears.
I tried to use different os builds and it didnt work.
I tried to use industrial power supply (5V3A) and  also it didnt work.

My SD Card is not one of the recommended ones but do I really have to get the recommended sd cards to use the windows iot core properly?

答:
"Your PC ran into a problem and needs to restart" is a typical blue screen message seen on Windows systems from the last few years - laptops and desktops with far larger hard drives and no SD card. The error is not associated with a RAM or disk space shortage (operating systems running in graphical mode usually monitor and actively warn about either). In your case, it is showing at startup, when not much is running (taking up RAM), and you can check the amount of space used on the card with the PC.

The key stats for SD cards are size (you have plenty) and speed (clearly enough or you would have trouble installing/running anything after starting the Pi). The cause is something else, and finding out what will require getting a more detailed error message from Windows - "a problem" could mean anything. In my experience, blue screen errors have mostly involved having a wrong driver installed, sometimes a bad Windows update - but IoT Core has its own alternatives, like "bad system configuration". Look for the underscored string (e.g., BAD_SYSTEM_CONFIG_INFO) at the end of your blue screen message, as that is the first hint.

Unfortunately, most Windows BSoD documentation is for traditional PCs, so I cannot recommend specific troubleshooting tools and be sure that they will run on the Pi.


问:
How to deploy SpringBoot Maven application with Jenkins ?
I have a Spring Boot application which runs on embedded Tomcat servlet container mvn spring-boot:run . And I don’t want to deploy the project as separate war to standalone Tomcat.

Whenever I push code to BitBucket/Github, a hook runs and triggers Jenkins job (runs on Amazon EC2) to deploy the application.

The Jenkins job has a post build action: mvn spring-boot:run, the problem is that the job hangs when post build action finished.

There should be another way to do this. Any help would be appreciated.

答:
This worked for me on jenkins on a linux machine

```<code>kill -9 $(lsof -t -i:8080) || echo "Process was not running."
mvn clean compile
echo "mvn spring-boot:run" | at now + 1 minutes
</code>```

In case no process on 8080 it will print the message and will continue.

Make sure that at is installed on your linux machine. You can use

```<code>sudo apt-get install at
</code>```

to install at

Body:
This worked for me on jenkins on a linux machine

kill -9 $(lsof -t -i:8080) || echo "Process was not running."
mvn clean compile
echo "mvn spring-boot:run" | at now + 1 minutes

In case no process on 8080 it will print the message and will continue.

Make sure that at is installed on your linux machine. You can use

sudo apt-get install at

to install at


问:
Springboot failed to map properties file to variable
i want to map values between a yaml file with a Map<String, List<String>> in springboot

country.yml file:

```<code>entries:
  map:
     MY:
      - en
      - zh
</code>```

SampleConfig file:

```<code>@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("entries")
public class SampleConfig {

    private Map<String, List<String>> map = new HashMap<>();

    @Bean
    public void bean1(){
        System.err.println("map has size: "+map.size());
    }
}
</code>```

But the map.size() is always 0, not sure what i do wrong.

答:
this will work and print out CountryData : {MY=[en, zh]}

but surely read the answer from Deadpool.

the hack is here to override the default configuration name 'application' by 'country'

in the example, I have done it by setting it via a System property, but starting your application via
java -jar mycountryapp.jar --spring.config.name=country should work perfectly

```<code>@SpringBootApplication
public class Application {

    static {
      System.setProperty("spring.config.name", "country");
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

@Service
class CountryService {
  private final CountryData countryData;
    public CountryService(CountryData countryData) {
        this.countryData = countryData;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void showCountryDataOnStartup() {
      System.err.println("CountryData : " + countryData.getMap());
    }

}

@Configuration
@ConfigurationProperties(prefix = "entries")
class CountryData {

    Map<String, List<String>> map;

    public Map<String, List<String>> getMap() {
        return map;
    }

    public void setMap(Map<String, List<String>> map) {
        this.map = map;
    }

}
</code>```

Body:
i want to map values between a yaml file with a Map<String, List<String>> in springboot

country.yml file:

entries:
  map:
     MY:
      - en
      - zh

SampleConfig file:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("entries")
public class SampleConfig {

    private Map<String, List<String>> map = new HashMap<>();

    @Bean
    public void bean1(){
        System.err.println("map has size: "+map.size());
    }
}

But the map.size() is always 0, not sure what i do wrong.

Body:
this will work and print out CountryData : {MY=[en, zh]}

but surely read the answer from Deadpool.

the hack is here to override the default configuration name 'application' by 'country'

in the example, I have done it by setting it via a System property, but starting your application via
java -jar mycountryapp.jar --spring.config.name=country should work perfectly

@SpringBootApplication
public class Application {

    static {
      System.setProperty("spring.config.name", "country");
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

@Service
class CountryService {
  private final CountryData countryData;
    public CountryService(CountryData countryData) {
        this.countryData = countryData;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void showCountryDataOnStartup() {
      System.err.println("CountryData : " + countryData.getMap());
    }

}

@Configuration
@ConfigurationProperties(prefix = "entries")
class CountryData {

    Map<String, List<String>> map;

    public Map<String, List<String>> getMap() {
        return map;
    }

    public void setMap(Map<String, List<String>> map) {
        this.map = map;
    }

}


问:
How can I change a bool to a 0 or a 1, can I cast it?
I have this method:

```<code>public void UpdatePhrase(PHRASE phraseColumn, bool value, string phraseId)
{
   sql = string.Format("UPDATE Phrase SET " + phraseColumn.Text() + " = {0} WHERE PhraseId = '{1}'", value, phraseId);
        App.DB.RunExecute(sql);
}
</code>```

It's not working correctly as it seems like I need the value of {0} needs to be a 0 or a 1.

Is there a simple way that I can take value and change it to be a 0 or a 1?

答:
you can do (GetHashCode on booleans returns a constant 1/0, no calculation):</p>

```<code>true.GetHashCode() // 1
false.GetHashCode() // 0
</code>```

Body:
I have this method:

public void UpdatePhrase(PHRASE phraseColumn, bool value, string phraseId)
{
   sql = string.Format("UPDATE Phrase SET " + phraseColumn.Text() + " = {0} WHERE PhraseId = '{1}'", value, phraseId);
        App.DB.RunExecute(sql);
}

It's not working correctly as it seems like I need the value of {0} needs to be a 0 or a 1.

Is there a simple way that I can take value and change it to be a 0 or a 1?

Body:
you can do (GetHashCode on booleans returns a constant 1/0, no calculation):

true.GetHashCode() // 1
false.GetHashCode() // 0


问:
Creating a GLUT popup menu in Python-OpenGL
I'm trying to create a right-click-popup-menu in a Python(v2.7) program using GLUT. I haven't found Python-specific documentation for doing this, so I used C++ documentation, which is usually almost similar.

Here's what I have:

```<code>if __name__=="__main__":
    glutInit(sys.argv)
    #...more initialization code...
    createMenu()
    init()
    glutMainLoop()
</code>```

And here are the functions that create the menu:

```<code>def createMenu():
    menu = glutCreateMenu(processMenuEvents)
    glutAddMenuEntry("One", 1)
    glutAddMenuEntry("Two", 2)
    glutAttachMenu(GLUT_RIGHT_BUTTON)

def processMenuEvents(option):
    logging.debug("Menu pressed")
    # not using 'option' right now
</code>```

The menu gets displayed correctly, but when I click on an item, I get this error:

```<code>DEBUG:root:Menu pressed:
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 338, in 'converting callback result'
TypeError: an integer is required
Exception  in <function processMenuEvents at 0x1760b90> ignored
</code>```

Does python-opengl have a different way of doing this? What am I doing wrong here?

Thanks.

答:
This example helped me identify the requirement for specifying function parameter ctypes to solve the same problem. Found following the pyopengl glut docs on glutAddMenuEntry(). Ctype data types for your function args are specified here.

This snippet shows an example of an f(int)->int function, referenced via an object instance:

```<code>class Menu:
 def select_menu(self, choice):
    def _exit():
        import sys
        sys.exit(0)
    {
        1: _exit
    }[choice]()
    glutPostRedisplay()
    return 0

 def create_menu(self):
    # --- Right-click Menu --------
    from ctypes import c_int
    import platform
    #platform specific imports:
    if (platform.system() == 'Windows'):
        #Windows
        from ctypes import WINFUNCTYPE
        CMPFUNCRAW = WINFUNCTYPE(c_int, c_int)
        # first is return type, then arg types.
    else:
        #Linux
        from ctypes import CFUNCTYPE
        CMPFUNCRAW = CFUNCTYPE(c_int, c_int)
        # first is return type, then arg types.

    myfunc = CMPFUNCRAW(self.select_menu)

    selection_menu = glutCreateMenu( myfunc )
    glutAddMenuEntry("Quit", 1);
    glutAttachMenu(GLUT_RIGHT_BUTTON);
    # ---------------------------------
</code>```

Body:
I'm trying to create a right-click-popup-menu in a Python(v2.7) program using GLUT. I haven't found Python-specific documentation for doing this, so I used C++ documentation, which is usually almost similar.

Here's what I have:

if __name__=="__main__":
    glutInit(sys.argv)
    #...more initialization code...
    createMenu()
    init()
    glutMainLoop()

And here are the functions that create the menu:

def createMenu():
    menu = glutCreateMenu(processMenuEvents)
    glutAddMenuEntry("One", 1)
    glutAddMenuEntry("Two", 2)
    glutAttachMenu(GLUT_RIGHT_BUTTON)

def processMenuEvents(option):
    logging.debug("Menu pressed")
    # not using 'option' right now

The menu gets displayed correctly, but when I click on an item, I get this error:

DEBUG:root:Menu pressed:
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 338, in 'converting callback result'
TypeError: an integer is required
Exception  in <function processMenuEvents at 0x1760b90> ignored

Does python-opengl have a different way of doing this? What am I doing wrong here?

Thanks.

Body:
This example helped me identify the requirement for specifying function parameter ctypes to solve the same problem. Found following the pyopengl glut docs on glutAddMenuEntry(). Ctype data types for your function args are specified here.

This snippet shows an example of an f(int)->int function, referenced via an object instance:

class Menu:
 def select_menu(self, choice):
    def _exit():
        import sys
        sys.exit(0)
    {
        1: _exit
    }[choice]()
    glutPostRedisplay()
    return 0

 def create_menu(self):
    # --- Right-click Menu --------
    from ctypes import c_int
    import platform
    #platform specific imports:
    if (platform.system() == 'Windows'):
        #Windows
        from ctypes import WINFUNCTYPE
        CMPFUNCRAW = WINFUNCTYPE(c_int, c_int)
        # first is return type, then arg types.
    else:
        #Linux
        from ctypes import CFUNCTYPE
        CMPFUNCRAW = CFUNCTYPE(c_int, c_int)
        # first is return type, then arg types.

    myfunc = CMPFUNCRAW(self.select_menu)

    selection_menu = glutCreateMenu( myfunc )
    glutAddMenuEntry("Quit", 1);
    glutAttachMenu(GLUT_RIGHT_BUTTON);
    # ---------------------------------


问:
AWS S3 CLI - Could not connect to the endpoint URL
```<code>$ aws s3 ls

Could not connect to the endpoint URL: "https://s3.us-east-1a.amazonaws.com/"
</code>```

What could be the problem?

答: Assuming that your profile in ~/aws/config is using the region (instead of AZ as per your original question); the other cause is your client's inability to connect to s3.us-east-1.amazonaws.com. In my case, I was unable to resolve that DNS name due to an error in my network configuration. Fixing the DNS issue solved my problem.

Body:
$ aws s3 ls

Could not connect to the endpoint URL: "https://s3.us-east-1a.amazonaws.com/"

What could be the problem?


问:
local variable 'form' referenced before assignment error
i am new to django 2.x .. trying to create blog project as a training  to me
i have a problem error
UnboundLocalError at /create_post/
local variable 'form' referenced before assignment

this error will made me mad

this is my views.py file

```<code># views.py
def add_post (request):
    if request.method=='POST':
        form = postform(request.POST)
        if form.is_valid():
            form.save()
        else:
            form=postform()
    context = {
        'form': form
    }
    return render(request, 'create_post.html', {})
</code>```

and this my models.py file

```<code># models.py
from django.db import models
from django.utils.timezone import now

# Create your models here.

class post (models.Model):
    Post_Title = models.CharField (max_length=200)
    Post_Image = models.ImageField(upload_to='post/statics/img/')
    Post_Text = models.TextField()
    Post_Date = models.DateTimeField(default=now, editable=False)

    def __str__(self):
        return self.Post_Title
</code>```

this is my create_post.html file

```<code># create_post.html
<form method="post">
{% csrf_token %}
    {{ form }}
    <button type="submit"}>save new post</button>
</form>
</code>```

this is my forms.py file

```<code># forms.py
from django import forms
from .models import *

class postform (forms.ModelForm):
    class Meta:
        model = post
        fields = ['Post_Title', 'Post_Image', 'Post_Text']
</code>```

this is the error what i got

```<code>UnboundLocalError at /create_post/
local variable 'form' referenced before assignment
Request Method: GET
Request URL:    http://127.0.0.1:8000/create_post/
Django Version: 2.2.1
Exception Type: UnboundLocalError
Exception Value:
local variable 'form' referenced before assignment
Exception Location: D:\PEPSI\PycharmProjects\bloggersystem\post\views.py in add_post, line 29
Python Executable:  C:\Users\Mohamed Abaas\AppData\Local\Programs\Python\Python37-32\python.exe
Python Version: 3.7.3
Python Path:
['D:\\PEPSI\\PycharmProjects\\bloggersystem',
 'C:\\Users\\Mohamed '
 'Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\Mohamed '
 'Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\Mohamed Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\Mohamed Abaas\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\Mohamed '
 'Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages']
Server time:    Fri, 31 May 2019 18:28:50 +0000
</code>```

i want to understand not only fix the code

can any body help ???!!!

答:
You did not define a form variable in case of a GET request. This is because you indented the else one too much:

```<code>def add_post (request):
    if request.method=='POST':
        form = postform(request.POST)
        if form.is_valid():
            form.save()
    <b>else:
        form=postform()</b>
    context = {
        'form': form
    }
    return render(request, 'create_post.html', {})</code>```

Body:
i am new to django 2.x .. trying to create blog project as a training  to me
i have a problem error
UnboundLocalError at /create_post/
local variable 'form' referenced before assignment

this error will made me mad

this is my views.py file

# views.py
def add_post (request):
    if request.method=='POST':
        form = postform(request.POST)
        if form.is_valid():
            form.save()
        else:
            form=postform()
    context = {
        'form': form
    }
    return render(request, 'create_post.html', {})

and this my models.py file

# models.py
from django.db import models
from django.utils.timezone import now

# Create your models here.

class post (models.Model):
    Post_Title = models.CharField (max_length=200)
    Post_Image = models.ImageField(upload_to='post/statics/img/')
    Post_Text = models.TextField()
    Post_Date = models.DateTimeField(default=now, editable=False)

    def __str__(self):
        return self.Post_Title

this is my create_post.html file

# create_post.html
<form method="post">
{% csrf_token %}
    {{ form }}
    <button type="submit"}>save new post</button>
</form>

this is my forms.py file

# forms.py
from django import forms
from .models import *

class postform (forms.ModelForm):
    class Meta:
        model = post
        fields = ['Post_Title', 'Post_Image', 'Post_Text']

this is the error what i got

UnboundLocalError at /create_post/
local variable 'form' referenced before assignment
Request Method: GET
Request URL:    http://127.0.0.1:8000/create_post/
Django Version: 2.2.1
Exception Type: UnboundLocalError
Exception Value:
local variable 'form' referenced before assignment
Exception Location: D:\PEPSI\PycharmProjects\bloggersystem\post\views.py in add_post, line 29
Python Executable:  C:\Users\Mohamed Abaas\AppData\Local\Programs\Python\Python37-32\python.exe
Python Version: 3.7.3
Python Path:
['D:\\PEPSI\\PycharmProjects\\bloggersystem',
 'C:\\Users\\Mohamed '
 'Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\Mohamed '
 'Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\Mohamed Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\Mohamed Abaas\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\Mohamed '
 'Abaas\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages']
Server time:    Fri, 31 May 2019 18:28:50 +0000

i want to understand not only fix the code

can any body help ???!!!

Body:
You did not define a form variable in case of a GET request. This is because you indented the else one too much:

def add_post (request):
    if request.method=='POST':
        form = postform(request.POST)
        if form.is_valid():
            form.save()
    else:
        form=postform()
    context = {
        'form': form
    }
    return render(request, 'create_post.html', {})


问:
Matplotlib imshow() collapsing for axes values of different orders of magnitude
I am trying to plot a heatmap using imshow(). When my x and y data values are all of similar order of magnitude, it works fine. However, if x and y are different orders of magnitude (for example, all 0 < x < 1.0 and all y > 1.0), it collapses the plot along the axis with small numbers, as below. How do I avoid this?

<img src="https://lh3.googleusercontent.com/_93QjB5-MR3qjzx6BhsVroZEvJZc89MxYsXWxNkEi0kv2oFYUoTW2CPpIEkt0UjyE8ui4ja5jmWxDvTjYoZ11E_5HcHec2D-QJcQ1B3qCl44h4giVrQPRZ6oPi1R0ON1gokJ8ya-4zCOUj23M5thaBmuwzNq1-n8TxQ-_dzJ-MSalk58hle7VmMvd7Gr2pJfKwaW413XlvB3Cr-1A5Vp6rtXEcFJFmpLOGmSUWoBKtczUxYvDiWXV9_b_McANJe5TjIfPuehj4-znGX6hI-vhQx0KoIFmDOhoCOuwHXvWvrW81GcrY-HpnM94iPyw2YaK-cMZhj7Zv--8DZz9lz6VvG-kpGHe_iQTd4r5zw-z0zeHLvjFByg3t3mdB0WFzj0MEhLeX5MLWLcxAbK34-HvRXxDn56S5qKlvbYs00jZs2eud81LR9kjUV3WKSWjx3OxXvKSYsvHH5fhle9ZLEOTkmWXQZaRnPKyoZfCOxUlMEWteqhE3VuYOYr9aaC8xofgjZEpjCeOBLdWwVaT4hNF4TiO5o6Cm06CD8LrjzzbR4u7gSkRzQubQZNYWbANYHPK--Cb5psz2ags2z7WRt1DDrcjKxjwqmPb7lgC5r9M6Zf9jp9ordN6Cxp6k6PpNZtlb61a7lWx7F6D9Vu40bcyALQgssbbguPuThMBzQKsxP2Y4zIjWeC4KF8h0V9NOCbgdq-c76_37xAdHpwQXdrh4p3jA=w107-h469-no" alt="plot">

答:
You'll want to specify the size of the figure, using figsize.

Figsize accepts a tuple with two floats: (width, height)

To use it with imshow():

```<code>fig, ax = subplots(figsize=(18, 2))
ax.imshow(random.rand(8, 90), interpolation='nearest')
tight_layout()
</code>```

Or if you just want to use pyplot.plot() you could try something like:

```<code>plt.figure(figsize=(15,5))
</code>```

https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.figure.html

Body:
You'll want to specify the size of the figure, using figsize.

Figsize accepts a tuple with two floats: (width, height)

To use it with imshow():

fig, ax = subplots(figsize=(18, 2))
ax.imshow(random.rand(8, 90), interpolation='nearest')
tight_layout()

Or if you just want to use pyplot.plot() you could try something like:

plt.figure(figsize=(15,5))

https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.figure.html


问:
VSCode Setting to push JavaScript objects inside arrays to new line
Is there a VS Code extension setting that, when using formatOnSave, will force object-literal curly-brackets for the first object in an array to start on the next line?

Trying to achieve this:

```<code>const arrOfObjs = [
  {
    name: 'Obj1'
  },
  {
    name: 'Obj2'
  }
];
</code>```

But instead, the formatter brings the first obj curly up on the same line as the array bracket:

```<code>const arrOfObjs = [{
    name: 'Obj1'
  },
  {
    name: 'Obj2'
  }
];
</code>```

That makes ESLint yell about indents (expecting 2 but found 4). Right now I am ignoring the error for the one time in my code this happens, but I'll continue to feel dirty until I can get these two things to work together. :)

答: Probably is a conflict between VSCode and ESLin, both are formatting at the same time, let ESLint manage the formatting put: "editor.formatOnSave": false and "eslint.autoFixOnSave": true

Body:
Is there a VS Code extension setting that, when using formatOnSave, will force object-literal curly-brackets for the first object in an array to start on the next line?

Trying to achieve this:

const arrOfObjs = [
  {
    name: 'Obj1'
  },
  {
    name: 'Obj2'
  }
];

But instead, the formatter brings the first obj curly up on the same line as the array bracket:

const arrOfObjs = [{
    name: 'Obj1'
  },
  {
    name: 'Obj2'
  }
];

That makes ESLint yell about indents (expecting 2 but found 4). Right now I am ignoring the error for the one time in my code this happens, but I'll continue to feel dirty until I can get these two things to work together. :)


问:
Wait until all Ajax requests in a for loop are done before moving on?
I have to make a call to the Agile Central API to get a list of defect suites and then iterate through the list and make a nested call to get the list of defects in each suite, the nested call depends on the outer call. I then have to append the rows of data to a table and then call doneCallback() to signal the end of data collection. The problem I'm having is that doneCallback() is being called before the requests have completed so none of the data is actually passed on

I've tried the approaches in this post: Wait until all jQuery Ajax requests are done? and this post: how to wait until Array is filled (asynchronous). In the console I can see that all the data I want is there but nothing gets appended. My question is: how can I make sure I don't call doneCallback() until all the requests that are made in the loop have finished and pushed the data? Here's my code right now:

```<code>function getSuites() {
        return $.ajax({
            url: suitesURL("71101309592") + "&fetch=Name,FormattedID,Defects",
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "zsessionid": apiKey
            }
        });
    }

    function getDefects(_ref) {
        return $.ajax({
            url: _ref,
            type:"GET",
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "zsessionid": apiKey
            }
        });
    }

    // Download the data
    myConnector.getData = function (table, doneCallback) {

        console.log("Getting Data...");

        var ajaxCalls = [], tableData = [];

        var suitesJSON = getSuites();

        suitesJSON.done(function(data) {

            var suites = data.QueryResult.Results;

            for(var i = 0; i < suites.length; i++) {

               (function(i) {
                    var defectsJSON = getDefects(suites[i].Defects._ref + "?fetch=Name,FormattedID,State,Priority,CreationDate,c_RootCause,c_RootCauseCRM");
                    ajaxCalls.push(defectsJSON);

                    defectsJSON.done(function(data) {
                        var defects = data.QueryResult.Results;

                        for(var j = 0; j < defects.length; j++) {
                            tableData.push({
                                "suiteName": suites[i].Name, // This is the name of the suite collected in the outer call
                                "defectName": defects[j].Name,
                                "FormattedID": defects[j].FormattedID,
                                "State": defects[j].State,
                                "Priority": defects[j].Priority,
                                "CreationDate": defects[j].CreationDate,
                                "RootCause": defects[j].c_RootCause,
                                "RootCauseCRM": defects[j].c_RootCauseCRM
                            });
                        }

                    });
               })(i);

            }

        });

        $.when.apply($, ajaxCalls).then(function() {
            console.log(tableData);
            table.appendRows(tableData);
            doneCallback();
        });
};
</code>```

答:
You should use a better model to get multiple items. Using a for loop to query for multiple gets is the problem, and the solution should be to refactor so that you make one request that returns everything you need.

If this doesn't seem possible to you, I've researched a way to do what you want in jQuery.

```<code>$.when(
    $.get(path, callback), $.get(path, callback), $.get(path, callback)
.then({
    //This is called after all requests are done
});
</code>```

You could create an array of all your requests like [$.get(path, callback), request2, request 3, etc...] and then use the spread method to put them as arguments like

```<code>var args = [$.get(path, callback), request2, request 3, etc...];
$.when(...args).then(() => {/*call here*/});
</code>```

This link has the rest of the information
https://css-tricks.com/multiple-simultaneous-ajax-requests-one-callback-jquery/

Body:
I have to make a call to the Agile Central API to get a list of defect suites and then iterate through the list and make a nested call to get the list of defects in each suite, the nested call depends on the outer call. I then have to append the rows of data to a table and then call doneCallback() to signal the end of data collection. The problem I'm having is that doneCallback() is being called before the requests have completed so none of the data is actually passed on

I've tried the approaches in this post: Wait until all jQuery Ajax requests are done? and this post: how to wait until Array is filled (asynchronous). In the console I can see that all the data I want is there but nothing gets appended. My question is: how can I make sure I don't call doneCallback() until all the requests that are made in the loop have finished and pushed the data? Here's my code right now:

function getSuites() {
        return $.ajax({
            url: suitesURL("71101309592") + "&fetch=Name,FormattedID,Defects",
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "zsessionid": apiKey
            }
        });
    }

    function getDefects(_ref) {
        return $.ajax({
            url: _ref,
            type:"GET",
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "zsessionid": apiKey
            }
        });
    }

    // Download the data
    myConnector.getData = function (table, doneCallback) {

        console.log("Getting Data...");

        var ajaxCalls = [], tableData = [];

        var suitesJSON = getSuites();

        suitesJSON.done(function(data) {

            var suites = data.QueryResult.Results;

            for(var i = 0; i < suites.length; i++) {

               (function(i) {
                    var defectsJSON = getDefects(suites[i].Defects._ref + "?fetch=Name,FormattedID,State,Priority,CreationDate,c_RootCause,c_RootCauseCRM");
                    ajaxCalls.push(defectsJSON);

                    defectsJSON.done(function(data) {
                        var defects = data.QueryResult.Results;

                        for(var j = 0; j < defects.length; j++) {
                            tableData.push({
                                "suiteName": suites[i].Name, // This is the name of the suite collected in the outer call
                                "defectName": defects[j].Name,
                                "FormattedID": defects[j].FormattedID,
                                "State": defects[j].State,
                                "Priority": defects[j].Priority,
                                "CreationDate": defects[j].CreationDate,
                                "RootCause": defects[j].c_RootCause,
                                "RootCauseCRM": defects[j].c_RootCauseCRM
                            });
                        }

                    });
               })(i);

            }

        });

        $.when.apply($, ajaxCalls).then(function() {
            console.log(tableData);
            table.appendRows(tableData);
            doneCallback();
        });
};

Body:
You should use a better model to get multiple items. Using a for loop to query for multiple gets is the problem, and the solution should be to refactor so that you make one request that returns everything you need.

If this doesn't seem possible to you, I've researched a way to do what you want in jQuery.

$.when(
    $.get(path, callback), $.get(path, callback), $.get(path, callback)
.then({
    //This is called after all requests are done
});

You could create an array of all your requests like [$.get(path, callback), request2, request 3, etc...] and then use the spread method to put them as arguments like

var args = [$.get(path, callback), request2, request 3, etc...];
$.when(...args).then(() => {/*call here*/});

This link has the rest of the information
https://css-tricks.com/multiple-simultaneous-ajax-requests-one-callback-jquery/


问:
Dynamically show enum values based on the class that implements them
I'm building a JavaFx application.
I want to dynamically show enum values in different comboboxes.

For example, in controller A I only want to show enum value "high" and in controller B I want to show all enum values.

Can anyone help?

Thanks!

```<code>public enum EnumPrio {

    High("high"),
    Medium("medium"),
    Low("low");

    private String prio;

    EnumPrio(String prio) {
        this.prio = prio;
    }

}
</code>```

答:
```<code>public enum EnumPrio {

    High("high"),
    Medium("medium"),
    Low("low");

    private String prio;

    EnumPrio(String prio) {
        this.prio = prio;
    }

    public static List<EnumPrio> getEnumPrioListByController(String controller) {
        Stream<EnumPrio> enumPrioStream=Stream.of(EnumPrio.values());

        return controller.equals("A")?enumPrioStream
                .filter(enumPrio->enumPrio.prio.equals("high")).collect(Collectors.toList()):enumPrioStream
                .filter(enumPrio->!enumPrio.prio.equals("high")).collect(Collectors.toList());
    }
    public static void main(String[] args) {

        System.out.println("enumPrioListForControllerA="+EnumPrio.getEnumPrioListByController("A"));
        // enumPrioListForControllerA=[High]
        System.out.println("enumPrioListForControllerB="+EnumPrio.getEnumPrioListByController("B"));
        // enumPrioListForControllerB=[Medium, Low]
    }
}
</code>```

Body:
I'm building a JavaFx application.
I want to dynamically show enum values in different comboboxes.

For example, in controller A I only want to show enum value "high" and in controller B I want to show all enum values.

Can anyone help?

Thanks!

public enum EnumPrio {

    High("high"),
    Medium("medium"),
    Low("low");

    private String prio;

    EnumPrio(String prio) {
        this.prio = prio;
    }

}


问:
configuring Content-Security-Policy in tomcat
I read about configuring/implementing Content-Security-Policy header and I came accross 2 ways of doing it:

using custom filter that implements Filter as given in this link

using meta tag

Please note that this question is not duplicate of this, Iam looking for a solution better than given in this link

I see the drawbacks in (1) is its driven through code, not through a configuration file , drawbacks in option (2) is if I have say 100 html files, I need to put this tag in every HTML? (correct me if I'm wrong)
The solution I'm looking for is something I can configure in web.xml and becomes applicable for all the html files. Something the way we do in case of configuring X-Frame-Options in web.xml like given here, don't we have similar way of configuring Content-Security-Policy in web.xml ?

答:
Configure content-security-policy in web.xml

You can use the recommendation provided by OWASP here. It is a web filter that you can implement in your backend.

The below filter has to be then defined in your web.xml file. This gets called on every request in your application. In java you may do that by creating an appropriate class.

    <filter>
        <filter-name>ContentSecurityPolicy</filter-name>
        <filter-class>YourPackagePath.ContentSecurityPolicyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ContentSecurityPolicy</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
```

The above will implement the below values for content-security-policy in your HTTP Header

default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self'; frame-src 'self'; connect-src 'self'; form-action 'self'; reflected-xss block

Body:
Configure content-security-policy in web.xml

You can use the recommendation provided by OWASP here. It is a web filter that you can implement in your backend.

The below filter has to be then defined in your web.xml file. This gets called on every request in your application. In java you may do that by creating an appropriate class.

    <filter>
        <filter-name>ContentSecurityPolicy</filter-name>
        <filter-class>YourPackagePath.ContentSecurityPolicyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ContentSecurityPolicy</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

The above will implement the below values for content-security-policy in your HTTP Header

default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self'; frame-src 'self'; connect-src 'self'; form-action 'self'; reflected-xss block