答:
The simplest solution would be to make transformer an async function, and await it inside calculate (which would also need to be an async function).

async function transformer(instring) {
  var outstring = instring + instring;
  return outstring;
}

async function calculate() {
  var srcStr = document.mainform.src.value;
  var transformed = await transformer(srcStr);
  document.mainform.dst.value = transformed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="mainform">
  Input data <input type="text" name="src" value="abc" /><br>
  <button type="button" onclick="javascript:calculate();">Calculate</button><br>
  Output data <input type="text" name="dst" />
</form></code>```

Of course, this will only work on browsers that support this syntax (which is any major browser released in 2017 or later). If you need to support the older Promise-based syntax, the above code is effectively identical to this:

function transformer(instring) {
  var outstring = instring + instring;
  return Promise.resolve(outstring);
}

function calculate() {
  var srcStr = document.mainform.src.value;
  transformer(srcStr).then(function(transformed) {
    document.mainform.dst.value = transformed;
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="mainform">
  Input data <input type="text" name="src" value="abc" /><br>
  <button type="button" onclick="javascript:calculate();">Calculate</button><br>
  Output data <input type="text" name="dst" />
</form></code>```

And of course, this will only work in browsers that support promises (which is any major browser released in 2015 or later), but you can use a library like Bluebird to patch it in to most browsers that do not.

Title: How can I implement a promise in my calculator function?

Body:
I've written a calculator-like application in JavaScript, mainly so that it will run in any browser. It has a number of input fields. When I press the calculate button, it gathers data from these fields, calls various functions on it, and displays the result. There's no asynchronous stuff to do, no web or disc fetches that could delay or fail, the user triggers an event and then has to wait until the answer has been produced.

The fragment below is more or less a Hello World for this sort of process.

<form name="mainform">
Input data <input type="text" name="src" value="abc"/>

<button type="button" onclick="javascript:calculate();">Calculate</button>

Output data <input type="text" name="dst"  />
</form>

I would like to replace the transformer() function with a function from a library that returns a promise. What's the minimum change in code I need to make to accomplish this. I've searched a lot for promises, async functions, thens etc, but not found a simple 'here is how to use a promise in a simple event driven program', and I have not yet managed to write a working equivalent of the program above. Once I have a working hello world, I can build from there.

Assume that the promise will always resolve, reject never needs to be handled. By 'minimum change', I don't necessarily mean fewest characters, but easiest to understand, or with fewest new concepts.

Body:
The simplest solution would be to make transformer an async function, and await it inside calculate (which would also need to be an async function).

async function transformer(instring) {
  var outstring = instring + instring;
  return outstring;
}

async function calculate() {
  var srcStr = document.mainform.src.value;
  var transformed = await transformer(srcStr);
  document.mainform.dst.value = transformed;
}

<form name="mainform">
  Input data <input type="text" name="src" value="abc" /><br>
  <button type="button" onclick="javascript:calculate();">Calculate</button><br>
  Output data <input type="text" name="dst" />
</form>

Of course, this will only work on browsers that support this syntax (which is any major browser released in 2017 or later). If you need to support the older Promise-based syntax, the above code is effectively identical to this:

function transformer(instring) {
  var outstring = instring + instring;
  return Promise.resolve(outstring);
}

function calculate() {
  var srcStr = document.mainform.src.value;
  transformer(srcStr).then(function(transformed) {
    document.mainform.dst.value = transformed;
  });
}

<form name="mainform">
  Input data <input type="text" name="src" value="abc" /><br>
  <button type="button" onclick="javascript:calculate();">Calculate</button><br>
  Output data <input type="text" name="dst" />
</form>

And of course, this will only work in browsers that support promises (which is any major browser released in 2015 or later), but you can use a library like Bluebird to patch it in to most browsers that do not.


来源: stackexchange

问:
Extra select when persisting an entity
When i try to save a entity

```<code>@Autowired
private GenericDao<ProfileRoles, Integer> gProfileRolesDao;
...
gProfileRolesDao.create(new ProfileRoles(new Profile(idProfile), new Role(role)));
</code>```

With create

```<code>@Repository
public class GenericDao<T, PK extends Serializable>  {

    @PersistenceContext
    private EntityManager entityManager;
    ...
    public T create(T t) {
        this.entityManager.persist(t);
        return t;
    }
</code>```

And ProfileRoles entity

```<code>@Entity
@Table(name="profile_roles")
public class ProfileRoles {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "profile")
    private Profile profile;

    @ManyToOne
    @JoinColumn(name = "role")
    private Role role;
</code>```

Everything is fine but i get an extra select

```<code>Hibernate: select role_.id, role_.label as label2_22_ from role role_ where role_.id=?
Hibernate: insert into profile_roles (profile, role) values (?, ?)
</code>```

How can I optimize this ?

答:
This is more of a discussion than an answer at this stage, but need more than a comment for the code sample...

A quick test, assigning a new Role(existingRoleId) to the ProfileRole worked fine, with no extra select against the role table.

The extra select could point to something saving or merging the role.  After the select Hibernate then finds no changes that need to be updated back to the database.

A straightforward way to trace what is selecting for the role would be a @PostLoad method on Role.  For example, it could dump the current stack trace:

```<code>@PostLoad
public void postLoad() {
    new Exception("Post-load trace stack").printStackTrace();
}
</code>```

With luck this will provide a lead.

ContentLicense: CC BY-SA 4.0

Title: Extra select when persisting an entity

Body:
When i try to save a entity

@Autowired
private GenericDao<ProfileRoles, Integer> gProfileRolesDao;
...
gProfileRolesDao.create(new ProfileRoles(new Profile(idProfile), new Role(role)));

With create

@Repository
public class GenericDao<T, PK extends Serializable>  {

    @PersistenceContext
    private EntityManager entityManager;
    ...
    public T create(T t) {
        this.entityManager.persist(t);
        return t;
    }

And ProfileRoles entity

@Entity
@Table(name="profile_roles")
public class ProfileRoles {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "profile")
    private Profile profile;

    @ManyToOne
    @JoinColumn(name = "role")
    private Role role;

Everything is fine but i get an extra select

Hibernate: select role_.id, role_.label as label2_22_ from role role_ where role_.id=?
Hibernate: insert into profile_roles (profile, role) values (?, ?)

How can I optimize this ?

Body:
This is more of a discussion than an answer at this stage, but need more than a comment for the code sample...

A quick test, assigning a new Role(existingRoleId) to the ProfileRole worked fine, with no extra select against the role table.

The extra select could point to something saving or merging the role.  After the select Hibernate then finds no changes that need to be updated back to the database.

A straightforward way to trace what is selecting for the role would be a @PostLoad method on Role.  For example, it could dump the current stack trace:

@PostLoad
public void postLoad() {
    new Exception("Post-load trace stack").printStackTrace();
}

With luck this will provide a lead.


问:
JsonQueryElasticSearch Processor in Nifi
I am working with JsonQueryElasticSearch Processor in Nifi (v1.9.2).

The query string is as below:

```<code>{
     "query": {
         "bool": {
            "must": [
                { "match":       { "event": "New" }},
                { "match":       { "uniqueId":  "${unique_id}"}},
                { "match":       { "header.schemaVersion": "1.3" }}
            ]
        }
    },
    "sort" : {
        "header.sourceSystemCreationTimestamp" : {"order" : "desc"}
    }
}
</code>```

It's not giving me any result as value of ${unique_id} flow attribute within query is blank. If I hard code the value in query it works as expected. At processor level, I do see the value for ${unique_id} flow attribute.

Thanks much for  your time and help.

答:
(I'm the developer who wrote this processor)

I tried to duplicate the issue by doing the following:

Creating an index with several test documents.

Using GenerateFlowFile -> JsonQueryElasticsearch.

Putting this simple query in the query parameter of JsonQueryElasticsearch:

```<code>{
  "query": {
    "match": {
      "from": "${sender}"
    }
  },
  "aggs": {
    "senders": {
      "terms": {
        "field": "from",
        "size": 10
      }
    }
  }
}
</code>```

All of the expected results were returned. If you are attempting to pass the query in via the flowfile content, you cannot use Expression Language (${unique_id}). That's expected behavior because Expression Language is not evaluated on the contents of flowfiles, only on configuration properties.

Body:
I am working with JsonQueryElasticSearch Processor in Nifi (v1.9.2).

The query string is as below:

{
     "query": {
         "bool": {
            "must": [
                { "match":       { "event": "New" }},
                { "match":       { "uniqueId":  "${unique_id}"}},
                { "match":       { "header.schemaVersion": "1.3" }}
            ]
        }
    },
    "sort" : {
        "header.sourceSystemCreationTimestamp" : {"order" : "desc"}
    }
}

It's not giving me any result as value of ${unique_id} flow attribute within query is blank. If I hard code the value in query it works as expected. At processor level, I do see the value for ${unique_id} flow attribute.

Thanks much for  your time and help.

Body:
(I'm the developer who wrote this processor)

I tried to duplicate the issue by doing the following:

Creating an index with several test documents.

Using GenerateFlowFile -> JsonQueryElasticsearch.

Putting this simple query in the query parameter of JsonQueryElasticsearch:

{
  "query": {
    "match": {
      "from": "${sender}"
    }
  },
  "aggs": {
    "senders": {
      "terms": {
        "field": "from",
        "size": 10
      }
    }
  }
}

All of the expected results were returned. If you are attempting to pass the query in via the flowfile content, you cannot use Expression Language (${unique_id}). That's expected behavior because Expression Language is not evaluated on the contents of flowfiles, only on configuration properties.


问:
How can I display dotted line in react native
I need to display a dotted line in a view

I have tried borderTopWidth: 1, borderStyle: 'dashed' for a view.

答:
TL;DR: If you need any kind of control, and not a hacky solution, use a third-party solution like react-native-dash.

There is no easy way to make a dotted line in React Native (at least as of version 0.59, May 2019). The problem with using something like a dotted or dashed borderStyle on a <View /> component is that it will apply to all 4 sides of that view box. That means you will get super tight groupings of dots and dashes, with no out-of-the-box solution for controlling the dash or dot spacing or size. It's fine for doing a simple dotted or dashed box, but not a line.


问:
Could anyone verify the correctness of getting a md5 hash using this method?
```<code>        MessageDigest m=MessageDigest.getInstance("MD5");
        StringBuffer sb = new StringBuffer();
        if(nodeName!=null) sb.append(nodeName);
        if(nodeParentName!=null) sb.append(nodeParentName);
        if(nodeParentFieldName!=null) sb.append(nodeParentFieldName);
        if(nodeRelationName!=null) sb.append(nodeRelationName);
        if(nodeViewName!=null) sb.append(nodeViewName);
        if(treeName!=null) sb.append(treeName);
        if(nodeValue!=null && nodeValue.trim().length()>0) sb.append(nodeValue);
        if(considerParentHash) sb.append(parentHash);
        m.update(sb.toString().getBytes("UTF-8"),0,sb.toString().length());
        BigInteger i = new BigInteger(1,m.digest());
        hash = String.format("%1$032X", i);
</code>```

The idea behind these lines of code is that we append all the values of a class/model into a StringBuilder and then return the padded hash of that (the Java implementation returns md5 hashes that are lenght 30 or 31, so the last line formats the hash to be padded with 0s).

I can verify that this works, but I have a feeling it fails at one point (our application fails and I believe this to be the probable cause).

Can anyone see a reason why this wouldn't work? Are there any workarounds to make this code less prone to errors (e.g. removing the need for the strings to be UTF-8).

答:
There are a few weird things in your code.

UTF-8 encoding of a character may use more than one byte. So you should not use the string length as final parameter to the update() call, but the length of the array of bytes that getBytes() actually returned. As suggested by Paŭlo, use the update() method which takes a single byte[] as parameter.

The output of MD5 is a sequence of 16 bytes with quite arbitrary values. If you interpret it as an integer (that's what you do with your call to BigInteger()), then you will get a numerical value which will be smaller than 2160, possibly much smaller. When converted back to hexadecimal digits, you may get 32, 31, 30... or less than 30 characters. Your usage of the the "%032X" format string left-pads with enough zeros, so your code works, but it is kind of indirect (the output of MD5 has never been an integer to begin with).

You assemble the hash input elements with raw concatenation. This may induce issues. For instance, if modeName is "foo" and modeParentName is "barqux", then the MD5 input will begin with (the UTF-8 encoding of) "foobarqux". If modeName is "foobar" and modeParentName is "qux", then the MD5 input will also begin with "foobarqux". You do not tell why you want to use a hash function, but usually, when one uses a hash function, it is to have a unique trace of some piece of data; two distinct data elements should yield distinct hash inputs.

When handling nodeValue, you call trim(), which means that this string could begin and/or end with whitespace, and you do not want to include that whitespace into the hash input -- but you do include it, since you append nodeValue and not nodeValue.trim().

If what you are trying to do has any relation to security then you should not use MD5, which is cryptographically broken. Use SHA-256 instead.

Hashing an XML element is normally done through canonicalization (which handles whitespace, attribute order, text representation, and so on). See this question on the topic of canonicalizing XML data with Java.

ContentLicense: CC BY-SA 3.0

Body:
        MessageDigest m=MessageDigest.getInstance("MD5");
        StringBuffer sb = new StringBuffer();
        if(nodeName!=null) sb.append(nodeName);
        if(nodeParentName!=null) sb.append(nodeParentName);
        if(nodeParentFieldName!=null) sb.append(nodeParentFieldName);
        if(nodeRelationName!=null) sb.append(nodeRelationName);
        if(nodeViewName!=null) sb.append(nodeViewName);
        if(treeName!=null) sb.append(treeName);
        if(nodeValue!=null && nodeValue.trim().length()>0) sb.append(nodeValue);
        if(considerParentHash) sb.append(parentHash);
        m.update(sb.toString().getBytes("UTF-8"),0,sb.toString().length());
        BigInteger i = new BigInteger(1,m.digest());
        hash = String.format("%1$032X", i);

The idea behind these lines of code is that we append all the values of a class/model into a StringBuilder and then return the padded hash of that (the Java implementation returns md5 hashes that are lenght 30 or 31, so the last line formats the hash to be padded with 0s).

I can verify that this works, but I have a feeling it fails at one point (our application fails and I believe this to be the probable cause).

Can anyone see a reason why this wouldn't work? Are there any workarounds to make this code less prone to errors (e.g. removing the need for the strings to be UTF-8).


问:
Create interlaced Select box
Lets assume a hierarchical structure:

```<code>{
  birds: [ chicken, ostrich, sparrow],
  mammals: [mouse, horse, lion],
  reptiles: [ crocodile, tortoise, lizard]
}
</code>```

I want to create a select box, having the categories (in this case: birds, mammals, reptiles) as visible options, which appear, when I open the select box. When I hover one of these options, a menu appears on the right side of the option pane, displaying the items that belong to the respective category. When I hover 'birds', I want a side menu that displays the options chicken, ostrich, sparrow. Hovering the side menu, it allows me to select one of these options on click, so that, in the end, the value of the original select box.

Logically, this select box should correspond to a grouped select box (<optgroup>), but technically it offers more than a mere grouping of options.

Is something like this already available somewhere? And how could I overcome the main obstacles, i.e. option elements not triggering hoverevents?

答:
How about using checkbox as toggle ?

Fiddle

```<code><div class="listitem">
   <label for="type1">
     Birds
   </label>
   <input id="type1" type="checkbox" />
   <div class="listitem-group">
       <button>Chicken</button>
       <button>Ostrich</button>
       <button>Sparrow</button>
   </div>
</div>
</code>```

Title: Create interlaced Select box

Body:
Lets assume a hierarchical structure:

{
  birds: [ chicken, ostrich, sparrow],
  mammals: [mouse, horse, lion],
  reptiles: [ crocodile, tortoise, lizard]
}

I want to create a select box, having the categories (in this case: birds, mammals, reptiles) as visible options, which appear, when I open the select box. When I hover one of these options, a menu appears on the right side of the option pane, displaying the items that belong to the respective category. When I hover 'birds', I want a side menu that displays the options chicken, ostrich, sparrow. Hovering the side menu, it allows me to select one of these options on click, so that, in the end, the value of the original select box.

Logically, this select box should correspond to a grouped select box (<optgroup>), but technically it offers more than a mere grouping of options.

Is something like this already available somewhere? And how could I overcome the main obstacles, i.e. option elements not triggering hoverevents?

Body:
How about using checkbox as toggle ?

Fiddle

<div class="listitem">
   <label for="type1">
     Birds
   </label>
   <input id="type1" type="checkbox" />
   <div class="listitem-group">
       <button>Chicken</button>
       <button>Ostrich</button>
       <button>Sparrow</button>
   </div>
</div>


问:
passport bookshelf is not inserting user into database
I'm using passport with bookshelf, and im having issues inserting a user in the database.

I'm using postman, and it shows that a user has been added to the db, but its not.

There doesn't seem to be much information about bookshelf, passport, and postgres used together. So it makes finding solutions like this hard.

routes/users

```<code>router.post('/register', (req, res, next) => {
    passport.authenticate('register', (err, user, info) => {
        if(err){
            console.log(err)
        }
        if(info !== undefined){
            console.log(info.message)
            res.status(403).send(info.message)
        }else{
            req.logIn(user, err  => {
                const data = {
                    username: req.body.username.trim(),
                    password: req.body.password.trim(),
                    email: req.body.email.trim()
                }
                console.log(data);
                User.forge({
                    username: data.username
                }).fetch().then( (user) => {

                    console.log('user creatd in db');
                    res.status(200).send({
                        message:'user created'
                    })
                })
            })
        }
    })(req, res, next);
});
</code>```

passport.js

```<code>import passport from 'passport';
import LocalStrategy from 'passport-local';
import User from '../models/User';
import bcrypt from 'bcrypt';
import JWTstrag from 'passport-jwt';
import ExtracJWT from 'passport-jwt';

const JWTstrategy  = JWTstrag.Strategy
const ExtractJWT = ExtracJWT.ExtractJwt
const Local = LocalStrategy.Strategy

const opts = {
    jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme('JWT'),
    secretOrKey: process.env.JWT_SECRET,
};

passport.use('jwt', new JWTstrategy(opts, (jwt_payload, done) => {
    try{
        User.forge({username: jwt_payload._id})
        .fetch()
        .then( (user) => {
            if(user){
                console.log('user found in db in passport');
                done(null, user)
            }else{
                console.log('user not found in db');
                done(null, false)
            }
        })
    } catch(err){
        done(err)
    }

}))

passport.use(
    'register',
    new Local(
      {
        usernameField: 'username',
        passwordField: 'password',
        // passReqToCallback: true,
        session: false,
      },
      (req, username, password, done) => {
        try {
            User.forge({username: username}, {email: req.body.email}).fetch().then(user => {
            if (user != null) {
              console.log('username or email already taken');
              return done(null, false, {
                message: 'username or email already taken',
              });
            } else {
              bcrypt.hash(password, 12).then(hashedPassword => {
                const user = new User({
                    username: req.body.username,
                    password: hashedPassword,
                    email: req.body.email
                })
                user.save().then( () => {
                    res.status(200).send('user created')
                    return done(null, user);
                })
              });
            }
          });
        } catch (err) {
            return done(err);
        }
      },
    ),
);

// passport.use(new Local ( (username, password, done) => {
//     User.findOne({username: username} , (err, user) =>{
//         if(err){
//             return done(err)
//         }
//         if(!user){
//             return done(null, false, {message: "Incorrect username."})
//         }

//         if(!user.validPassword(password)){
//             return done(null, false, {message: 'Incorrect password'})
//         }

//         return done (null, user)
//     })
// }))

passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

passport.deserializeUser(function(user, done) {
    User
      .forge({id: user})
      .fetch()
      .then((usr) => {
        done(null, usr);
      })
      .catch((err) => {
        done(err);
      });
});
</code>```

main.js

```<code>import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRoute from './routes/users';
import passport from 'passport';
import session from 'express-session';
import './config/passport';

const app = express();

app.use(cors());
app.use(logger('dev'));
// For React Stuff if need be
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
app.use(bodyParser.json());
// you need body parser urlencoded so passport will not give a Missing Credentials error
app.use(bodyParser.urlencoded({ extended:false}));

app.use(session({
  saveUninitialized: false,
  resave:false,
  cookie: {   maxAge: 30 * 24 * 60 * 60 * 1000 },  // 30 days
  secret : process.env.JWT_SECRET,

}));

app.use(passport.initialize());
app.use(passport.session());

app.get('/', (req, res) => {
  res.send('Hello World!');
});
app.use('/users', userRoute);

app.use(() => (req, res, next)  =>{
  res.locals.user = req.user; // This is the important line
  // req.session.user = user
  console.log(res.locals.user);
  next();
});

//build mode
// app.get('*', (req, res) => {
//   res.sendFile(path.join(__dirname+'/client/public/index.html'));
// })

// module.parent prevents the
// Node / Express: EADDRINUSE, Address already in use error when unit testing
if(!module.parent){
  app.listen(process.env.PORT, () =>
    console.log(`Example app listening on port ${process.env.PORT}!`),
  );
 }

export default app;
</code>```

答:
Fixed it, there were a number of errors.

One being the

done is not a function

Which will be fixed by uncommenting

```<code>passReqToCallback: true,
</code>```

two being res thats not supposed to be in the passport.js file but route file.

so remove

res.status(200).send('user created')

Now everything should be working.

passport.js

```<code>passport.use(
    'register',
    new Local(
      {
        usernameField: 'username',
        passwordField: 'password',
        passReqToCallback: true,
        session: false,
      },
      (req, username, password, done) => {
        try {
            User.forge({username: username}, {email: req.body.email}).fetch().then(user => {
            if (user != null) {
              console.log('username or email already taken');
              return done(null, false, {
                message: 'username or email already taken',
              });
            } else {
              bcrypt.hash(password, 12).then(hashedPassword => {
                const user = new User({
                    username: req.body.username,
                    password: hashedPassword,
                    email: req.body.email
                })
                user.save().then( () => {
                    return done(null, user);
                })
              });
            }
          });
        } catch (err) {
            return done(err);
        }
      },
    ),
);
</code>```

routes/users

```<code>router.post('/register', (req, res, next) => {
    passport.authenticate('register', (err, user, info) => {
        if(err){
            console.log(err)
        }
        if(info !== undefined){
            console.log(info.message)
            res.status(403).send(info.message)
        }else{
            req.logIn(user, err  => {
                const data = {
                    username: req.body.username.trim(),
                    password: req.body.password.trim(),
                    email: req.body.email.trim()
                }
                console.log(data);
                User.forge({
                    username: data.username
                }).fetch().then( (user) => {
                    console.log('user creatd in db');
                    res.status(200).send({
                        message:'user created'
                    })
                })
            })
        }
    })(req, res, next);
});
</code>```

Body:
I'm using passport with bookshelf, and im having issues inserting a user in the database.

I'm using postman, and it shows that a user has been added to the db, but its not.

There doesn't seem to be much information about bookshelf, passport, and postgres used together. So it makes finding solutions like this hard.

routes/users

router.post('/register', (req, res, next) => {
    passport.authenticate('register', (err, user, info) => {
        if(err){
            console.log(err)
        }
        if(info !== undefined){
            console.log(info.message)
            res.status(403).send(info.message)
        }else{
            req.logIn(user, err  => {
                const data = {
                    username: req.body.username.trim(),
                    password: req.body.password.trim(),
                    email: req.body.email.trim()
                }
                console.log(data);
                User.forge({
                    username: data.username
                }).fetch().then( (user) => {

                    console.log('user creatd in db');
                    res.status(200).send({
                        message:'user created'
                    })
                })
            })
        }
    })(req, res, next);
});

passport.js

import passport from 'passport';
import LocalStrategy from 'passport-local';
import User from '../models/User';
import bcrypt from 'bcrypt';
import JWTstrag from 'passport-jwt';
import ExtracJWT from 'passport-jwt';

const JWTstrategy  = JWTstrag.Strategy
const ExtractJWT = ExtracJWT.ExtractJwt
const Local = LocalStrategy.Strategy

const opts = {
    jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme('JWT'),
    secretOrKey: process.env.JWT_SECRET,
};

passport.use('jwt', new JWTstrategy(opts, (jwt_payload, done) => {
    try{
        User.forge({username: jwt_payload._id})
        .fetch()
        .then( (user) => {
            if(user){
                console.log('user found in db in passport');
                done(null, user)
            }else{
                console.log('user not found in db');
                done(null, false)
            }
        })
    } catch(err){
        done(err)
    }

}))

passport.use(
    'register',
    new Local(
      {
        usernameField: 'username',
        passwordField: 'password',
        // passReqToCallback: true,
        session: false,
      },
      (req, username, password, done) => {
        try {
            User.forge({username: username}, {email: req.body.email}).fetch().then(user => {
            if (user != null) {
              console.log('username or email already taken');
              return done(null, false, {
                message: 'username or email already taken',
              });
            } else {
              bcrypt.hash(password, 12).then(hashedPassword => {
                const user = new User({
                    username: req.body.username,
                    password: hashedPassword,
                    email: req.body.email
                })
                user.save().then( () => {
                    res.status(200).send('user created')
                    return done(null, user);
                })
              });
            }
          });
        } catch (err) {
            return done(err);
        }
      },
    ),
);

// passport.use(new Local ( (username, password, done) => {
//     User.findOne({username: username} , (err, user) =>{
//         if(err){
//             return done(err)
//         }
//         if(!user){
//             return done(null, false, {message: "Incorrect username."})
//         }

//         if(!user.validPassword(password)){
//             return done(null, false, {message: 'Incorrect password'})
//         }

//         return done (null, user)
//     })
// }))

passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

passport.deserializeUser(function(user, done) {
    User
      .forge({id: user})
      .fetch()
      .then((usr) => {
        done(null, usr);
      })
      .catch((err) => {
        done(err);
      });
});

main.js

import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRoute from './routes/users';
import passport from 'passport';
import session from 'express-session';
import './config/passport';

const app = express();

app.use(cors());
app.use(logger('dev'));
// For React Stuff if need be
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
app.use(bodyParser.json());
// you need body parser urlencoded so passport will not give a Missing Credentials error
app.use(bodyParser.urlencoded({ extended:false}));

app.use(session({
  saveUninitialized: false,
  resave:false,
  cookie: {   maxAge: 30 * 24 * 60 * 60 * 1000 },  // 30 days
  secret : process.env.JWT_SECRET,

}));

app.use(passport.initialize());
app.use(passport.session());

app.get('/', (req, res) => {
  res.send('Hello World!');
});
app.use('/users', userRoute);

app.use(() => (req, res, next)  =>{
  res.locals.user = req.user; // This is the important line
  // req.session.user = user
  console.log(res.locals.user);
  next();
});

//build mode
// app.get('*', (req, res) => {
//   res.sendFile(path.join(__dirname+'/client/public/index.html'));
// })

// module.parent prevents the
// Node / Express: EADDRINUSE, Address already in use error when unit testing
if(!module.parent){
  app.listen(process.env.PORT, () =>
    console.log(`Example app listening on port ${process.env.PORT}!`),
  );
 }

export default app;

Body:
Fixed it, there were a number of errors.

One being the

done is not a function

Which will be fixed by uncommenting

passReqToCallback: true,

two being res thats not supposed to be in the passport.js file but route file.

so remove

res.status(200).send('user created')

Now everything should be working.

passport.js

passport.use(
    'register',
    new Local(
      {
        usernameField: 'username',
        passwordField: 'password',
        passReqToCallback: true,
        session: false,
      },
      (req, username, password, done) => {
        try {
            User.forge({username: username}, {email: req.body.email}).fetch().then(user => {
            if (user != null) {
              console.log('username or email already taken');
              return done(null, false, {
                message: 'username or email already taken',
              });
            } else {
              bcrypt.hash(password, 12).then(hashedPassword => {
                const user = new User({
                    username: req.body.username,
                    password: hashedPassword,
                    email: req.body.email
                })
                user.save().then( () => {
                    return done(null, user);
                })
              });
            }
          });
        } catch (err) {
            return done(err);
        }
      },
    ),
);

routes/users

router.post('/register', (req, res, next) => {
    passport.authenticate('register', (err, user, info) => {
        if(err){
            console.log(err)
        }
        if(info !== undefined){
            console.log(info.message)
            res.status(403).send(info.message)
        }else{
            req.logIn(user, err  => {
                const data = {
                    username: req.body.username.trim(),
                    password: req.body.password.trim(),
                    email: req.body.email.trim()
                }
                console.log(data);
                User.forge({
                    username: data.username
                }).fetch().then( (user) => {
                    console.log('user creatd in db');
                    res.status(200).send({
                        message:'user created'
                    })
                })
            })
        }
    })(req, res, next);
});


问:
Trying to print multiple variable under loop
Here is what I tried

```<code>f = open('names.txt')
for people in f:
    print('{0} and {1}'.format(people, people))
</code>```

Output:

```<code>john
and john

vlad
and vlad
</code>```

But my expected output is

```<code>john and john
vlad and vlad
</code>```

What is wrong here and how to fix it?

答:
You can try removing the newline characters:

```<code>f = open('names.txt')
for people in f:
    people = people.replace("\n", "")
    print('{0} and {1}'.format(people, people))
</code>```

This way there should only be a new line on the next person in the file f.

Body:
Here is what I tried

f = open('names.txt')
for people in f:
    print('{0} and {1}'.format(people, people))

Output:

john
and john

vlad
and vlad

But my expected output is

john and john
vlad and vlad

What is wrong here and how to fix it?

Body:
You can try removing the newline characters:

f = open('names.txt')
for people in f:
    people = people.replace("\n", "")
    print('{0} and {1}'.format(people, people))

This way there should only be a new line on the next person in the file f.


问:
UWSGI for https configuration is not working
UWSGI Version- 2.0.18

Openssl- 1.0.2k-fips

Python 2.7

Getting Error:

```<code>uwsgi: error while loading shared libraries: libssl.so.1.0.0: cannot open shared object file: No such file or directory
</code>```

答:
When ever we do pip install uWSGI, It automatically binds to openssl libs.

But make sure you have installed openssl and openssl-devel package.

I tried with following versions:

Python- 3.6

UWSGI- 2.0.18

Commands:

Create Virtual Env and install flask and uWSGI:

```<code>virtualenv -p /usr/bin/python3.6 testing
source testing/bin/activate
pip install flask
pip install uWSGI
</code>```

Create Certs:

```<code>openssl genrsa -out foobar.key 2048
openssl req -new -key foobar.key -out foobar.csr
openssl x509 -req -days 365 -in foobar.csr -signkey foobar.key -out foobar.crt
</code>```

Create Sample Python file: foobar.py

```<code>def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"]
</code>```

Run uWSGI:

```<code>uwsgi --shared-socket 0.0.0.0:443 --uid roberto --gid roberto --https =0,foobar.crt,foobar.key --wsgi-file foobar.py
</code>```

Make sure do not get confused with the uWSGI installed in a virtual environment and with root user.

Follow the documentation:

https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html

Body:
UWSGI Version- 2.0.18

Openssl- 1.0.2k-fips

Python 2.7

Getting Error:

uwsgi: error while loading shared libraries: libssl.so.1.0.0: cannot open shared object file: No such file or directory

Body:
When ever we do pip install uWSGI, It automatically binds to openssl libs.

But make sure you have installed openssl and openssl-devel package.

I tried with following versions:

Python- 3.6

UWSGI- 2.0.18

Commands:

Create Virtual Env and install flask and uWSGI:

virtualenv -p /usr/bin/python3.6 testing
source testing/bin/activate
pip install flask
pip install uWSGI

Create Certs:

openssl genrsa -out foobar.key 2048
openssl req -new -key foobar.key -out foobar.csr
openssl x509 -req -days 365 -in foobar.csr -signkey foobar.key -out foobar.crt

Create Sample Python file: foobar.py

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"]

Run uWSGI:

uwsgi --shared-socket 0.0.0.0:443 --uid roberto --gid roberto --https =0,foobar.crt,foobar.key --wsgi-file foobar.py

Make sure do not get confused with the uWSGI installed in a virtual environment and with root user.

Follow the documentation:

https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html


问:
CLAMP can not run the Ruta Rules for predicting the relationships
I am trying to implement relationship ruta rules same as in this video (https://www.youtube.com/watch?time_continue=1105&v=8PYvzswOXog).
However, I can not get the results of any relationships.
I did perfectly follow everything in his demo.

Any help is appreciated.

```<code>BLOCK (ForEach) Sentence{}{
   ClampNameEntityUIMA { FEATURE ( "semanticTag", "test")}
   BaseToken??{REGEXP("grade")}
   ClampNameEntityUIMA { FEATURE ( "semanticTag", "Date" ) -> CREATE( ClampRelationUIMA, "entFrom"=3, "entTo"=1), SETFEATURE("semanticTag", "testdate")};
}

BLOCK (ForEach) Sentence{}{
    ClampNameEntityUIMA { FEATURE ( "semanticTag", "test")}
    BaseToken??{REGEXP("[grade\\s]*")}
    ClampNameEntityUIMA { FEATURE ( "semanticTag", "value" ) -> CREATE( ClampRelationUIMA, "entFrom"=3, "entTo"=1), SETFEATURE("semanticTag", "testvalue")};
}
</code>```

答:
It looks like that you actually want to use the GATHER action instead of the CREATE action. The GATHER action is able to assign the values of a feature using the index of the rule element whereas the matched annotation of the matching condition is assigned to the feature. The CREATE action tries to assign the given argument to the feature. In your example, that is an integer for a feature with an annotation range, which will result in no assignment.

Your block could look like:

```<code>BLOCK (ForEach) Sentence{}{
   ClampNameEntityUIMA { FEATURE ( "semanticTag", "test")}
   BaseToken??{REGEXP("grade")}
   ClampNameEntityUIMA { FEATURE ( "semanticTag", "Date" ) -> GATHER( ClampRelationUIMA, "entFrom"=3, "entTo"=1), SETFEATURE("semanticTag", "testdate")};
}
</code>```

DISCLAIMER: I ama developer of UIMA Ruta

Body:
I am trying to implement relationship ruta rules same as in this video (https://www.youtube.com/watch?time_continue=1105&v=8PYvzswOXog).
However, I can not get the results of any relationships.
I did perfectly follow everything in his demo.

Any help is appreciated.

BLOCK (ForEach) Sentence{}{
   ClampNameEntityUIMA { FEATURE ( "semanticTag", "test")}
   BaseToken??{REGEXP("grade")}
   ClampNameEntityUIMA { FEATURE ( "semanticTag", "Date" ) -> CREATE( ClampRelationUIMA, "entFrom"=3, "entTo"=1), SETFEATURE("semanticTag", "testdate")};
}

BLOCK (ForEach) Sentence{}{
    ClampNameEntityUIMA { FEATURE ( "semanticTag", "test")}
    BaseToken??{REGEXP("[grade\\s]*")}
    ClampNameEntityUIMA { FEATURE ( "semanticTag", "value" ) -> CREATE( ClampRelationUIMA, "entFrom"=3, "entTo"=1), SETFEATURE("semanticTag", "testvalue")};
}

Body:
It looks like that you actually want to use the GATHER action instead of the CREATE action. The GATHER action is able to assign the values of a feature using the index of the rule element whereas the matched annotation of the matching condition is assigned to the feature. The CREATE action tries to assign the given argument to the feature. In your example, that is an integer for a feature with an annotation range, which will result in no assignment.

Your block could look like:

BLOCK (ForEach) Sentence{}{
   ClampNameEntityUIMA { FEATURE ( "semanticTag", "test")}
   BaseToken??{REGEXP("grade")}
   ClampNameEntityUIMA { FEATURE ( "semanticTag", "Date" ) -> GATHER( ClampRelationUIMA, "entFrom"=3, "entTo"=1), SETFEATURE("semanticTag", "testdate")};
}

DISCLAIMER: I ama developer of UIMA Ruta


问:
Aligning right to left on UICollectionView with contents
I tried with the following question:

Aligning right to left on UICollectionView but it's not achieved my goal.

What I was tried:

In viewDidLoad():

```<code>collectionView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
</code>```

In cellForItemAtIndexPath():

```<code>cell.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
</code>```

My current CollectionView is on the left, but I want it to look like the CollecitonView on the right.

```<code>dataSource = ["item1","item2","item3","item4","item5","item6"]
</code>```

Update:

Change semanticContentAttribute of the collectionView to .forceRightToLeft

```<code>collectionView.semanticContentAttribute = .forceRightToLeft
</code>```

by  @RajeshKumar answered

I notice. items has spacing too much between two element for example item1 and item2 How can i reduce  that the space and rest of things? ok for me. on the other hand I tried with layout.minimumInteritemSpacing = 0 but it is not worked for me and item3 not alinement right too.

答:
Change semanticContentAttribute of the collectionView to .forceRightToLeft

```<code>collectionView.semanticContentAttribute = .forceRightToLeft
</code>```

It works

Body:
I tried with the following question:

Aligning right to left on UICollectionView but it's not achieved my goal.

What I was tried:

In viewDidLoad():

collectionView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)

In cellForItemAtIndexPath():

cell.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)

My current CollectionView is on the left, but I want it to look like the CollecitonView on the right.

dataSource = ["item1","item2","item3","item4","item5","item6"]

Update:

Change semanticContentAttribute of the collectionView to .forceRightToLeft

collectionView.semanticContentAttribute = .forceRightToLeft

by  @RajeshKumar answered

I notice. items has spacing too much between two element for example item1 and item2 How can i reduce  that the space and rest of things? ok for me. on the other hand I tried with layout.minimumInteritemSpacing = 0 but it is not worked for me and item3 not alinement right too.

Body:
Change semanticContentAttribute of the collectionView to .forceRightToLeft

collectionView.semanticContentAttribute = .forceRightToLeft

It works


问:
How to create different dashboards for different users of a Shiny app? (on the same app code)
I need to create a Shiny App that will generate 6 different versions of the same dashboard layout, to 6 different users. Each user will see its own historical data during production, and it's all in the same database (I'm guessing I just need to filter the whole database for each specific user).

Specifically:

1 - How do I detect which user is which? I'm gonna use Authentication so I'm guessing I can probably retrieve the information from the user by how he logged. But how do I retrieve this information in code terms?

2 - Knowing which user is which, how do I create the 6 different versions on the same app code? They'll be the same layout, the only difference is the filtering of the dataset based on the user.

(optional) 3 - How does Shiny servers conciliate different users' displays? Thinking about a dashboard that has user interaction, different inputs don't interfere each others' displays? Do they have to replicate the code for each access so they're independent results?

I haven't made it yet, and even if I did I think it would be too complex to resolve here, so I'm posting the Hello World of Shiny. This way, imagine that the dataset used for plotting the Histogram has a column called 'user'. What would be the code used for discriminating the users?

```<code>library(shiny)

  output$distPlot <- renderPlot({

    dist <- dataset[1:obs,1] %>% filter(???)
    hist(dist)
  })

})

shinyUI(fluidPage(

  titlePanel("Hello Shiny!"),

  # Sidebar with a slider input for number of observations
  sidebarLayout(
    sidebarPanel(
      sliderInput("obs",
                  "Number of observations:",
                  min = 1,
                  max = 1000,
                  value = 500)
    ),

    mainPanel(
      plotOutput("distPlot")
    )
  )
))
</code>```

Thanks!

答:
If you are using the authentication provided in shinyapps.io here is a simple solution to showing different UI elements to different users.

```<code>library(shiny)
library(dplyr)
ui <- fluidPage(
  titlePanel("Hello Shiny!"),

  # Sidebar with a slider input for number of observations
  sidebarLayout(
    sidebarPanel(
      uiOutput("slider")
    ),

    mainPanel(
      plotOutput("distPlot")
    )
  )
)

server <- function(input, output, session) {

  # If using shinyapps.io the users email is stored in session$user

  #session$user = "testuser1"
  # session$user = "testuser2"
  session$user = "testuser3"

  slider_max_limit <- switch(session$user,
                       "testuser1" = 100,
                       "testuser2" = 200,
                       "testuser3" = 500)

  output$slider <- renderUI(sliderInput("hp",
                                       "Filter Horsepower:",
                                       min = min(mtcars$hp),
                                       max = slider_max_limit,
                                       value = 70))

  output$distPlot <- renderPlot({
    req(input$hp)

    mtcars %>%
      filter(hp < input$hp) %>%
      .$mpg %>%
      hist(.)

  })
}

shinyApp(ui, server)
</code>```

By uncommenting the different users in the server function you can see how the slider changes.

Body:
I need to create a Shiny App that will generate 6 different versions of the same dashboard layout, to 6 different users. Each user will see its own historical data during production, and it's all in the same database (I'm guessing I just need to filter the whole database for each specific user).

Specifically:

1 - How do I detect which user is which? I'm gonna use Authentication so I'm guessing I can probably retrieve the information from the user by how he logged. But how do I retrieve this information in code terms?

2 - Knowing which user is which, how do I create the 6 different versions on the same app code? They'll be the same layout, the only difference is the filtering of the dataset based on the user.

(optional) 3 - How does Shiny servers conciliate different users' displays? Thinking about a dashboard that has user interaction, different inputs don't interfere each others' displays? Do they have to replicate the code for each access so they're independent results?

I haven't made it yet, and even if I did I think it would be too complex to resolve here, so I'm posting the Hello World of Shiny. This way, imagine that the dataset used for plotting the Histogram has a column called 'user'. What would be the code used for discriminating the users?

library(shiny)

  output$distPlot <- renderPlot({

    dist <- dataset[1:obs,1] %>% filter(???)
    hist(dist)
  })

})

shinyUI(fluidPage(

  titlePanel("Hello Shiny!"),

  # Sidebar with a slider input for number of observations
  sidebarLayout(
    sidebarPanel(
      sliderInput("obs",
                  "Number of observations:",
                  min = 1,
                  max = 1000,
                  value = 500)
    ),

    mainPanel(
      plotOutput("distPlot")
    )
  )
))

Thanks!

Body:
If you are using the authentication provided in shinyapps.io here is a simple solution to showing different UI elements to different users.

library(shiny)
library(dplyr)
ui <- fluidPage(
  titlePanel("Hello Shiny!"),

  # Sidebar with a slider input for number of observations
  sidebarLayout(
    sidebarPanel(
      uiOutput("slider")
    ),

    mainPanel(
      plotOutput("distPlot")
    )
  )
)

server <- function(input, output, session) {

  # If using shinyapps.io the users email is stored in session$user

  #session$user = "testuser1"
  # session$user = "testuser2"
  session$user = "testuser3"

  slider_max_limit <- switch(session$user,
                       "testuser1" = 100,
                       "testuser2" = 200,
                       "testuser3" = 500)

  output$slider <- renderUI(sliderInput("hp",
                                       "Filter Horsepower:",
                                       min = min(mtcars$hp),
                                       max = slider_max_limit,
                                       value = 70))

  output$distPlot <- renderPlot({
    req(input$hp)

    mtcars %>%
      filter(hp < input$hp) %>%
      .$mpg %>%
      hist(.)

  })
}

shinyApp(ui, server)

By uncommenting the different users in the server function you can see how the slider changes.


问:
How to pass a Private Map and input data
I'm trying to pass a private map that takes a long and a string type, one being a student id and a student name. I've declared my map as so:

```<code>typedef map<long, string> Student;
</code>```

I'm having trouble passing this into a setter function as I cannot access the maps methods once I try to declare Student in this function.

Ideally, I was trying to make this set method to take in some other variables I've declared from the same class and have getter and setter methods provided.

```<code>void SetMap(long studentId, string studentname);
{
    Student.insert(pair<long, string>(studentId, studentname);
}
</code>```

This method would be called to take in values from a file.

I understand that I might have to pass Student into the parameters but I have no idea how to declare this.

I was also trying to do the same for a get method but the same problem arises.

Some advice would help a lot, thanks in advance.

答:
Your Student is a type (an alias to map), not an instantiation that you can call insert on. You should modify your class to include a full declaration of this Student type like so:

```<code>typedef map<long, string> Student;
Student studentMap;
</code>```

Now, you should be able to call insert on the instantiation of the map, studentMap:

```<code>void SetMap(long studentId, string studentname);
{
    studentMap.insert(pair<long, string>(studentId, studentname);
}
</code>```

Body:
I'm trying to pass a private map that takes a long and a string type, one being a student id and a student name. I've declared my map as so:

typedef map<long, string> Student;

I'm having trouble passing this into a setter function as I cannot access the maps methods once I try to declare Student in this function.

Ideally, I was trying to make this set method to take in some other variables I've declared from the same class and have getter and setter methods provided.

void SetMap(long studentId, string studentname);
{
    Student.insert(pair<long, string>(studentId, studentname);
}

This method would be called to take in values from a file.

I understand that I might have to pass Student into the parameters but I have no idea how to declare this.

I was also trying to do the same for a get method but the same problem arises.

Some advice would help a lot, thanks in advance.

Body:
Your Student is a type (an alias to map), not an instantiation that you can call insert on. You should modify your class to include a full declaration of this Student type like so:

typedef map<long, string> Student;
Student studentMap;

Now, you should be able to call insert on the instantiation of the map, studentMap:

void SetMap(long studentId, string studentname);
{
    studentMap.insert(pair<long, string>(studentId, studentname);
}


问:
Unable to return function parameter due to conflicting types for 'function' in C
I'm new to C and I'm trying to understand how there are conflicting types for my function "using_name".

I also don't understand why I have to include a '*' to name the 'using_name()' function. It is because I'm storing a value in the function address?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int using_name(), call_func(char name[20]);
char name[20];

int main ()
{
    using_name();
    call_func(name);

    return 0;
}

char* using_name()
{
        printf("What is your name: ");
        scanf("%s", name);
        printf("\n Your name is %s", name);

        return name;
}

int call_func(char name[20])
{
    printf("Hello %s", using_name(name));

}
</code>```

Error: conflicting types for 'using_name'

答:
The return and argument types in the funnction prototype at the beginning of the program has to match the actual types when the function is defined later.

Since using_name() is defined as:

```<code>char *using_name()
</code>```

You need to change the earlier prototype to:

```<code>char *using_name();
int call_func(char name[20]);
</code>```

Another solution is to just put the function definitions at the beginning of the program. You only need prototypes for functions that are used before they're defined, or functions that are defined in another compilation unit (although these prototypes are usually put in a header file).

Body:
I'm new to C and I'm trying to understand how there are conflicting types for my function "using_name".

I also don't understand why I have to include a '*' to name the 'using_name()' function. It is because I'm storing a value in the function address?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int using_name(), call_func(char name[20]);
char name[20];

int main ()
{
    using_name();
    call_func(name);

    return 0;
}

char* using_name()
{
        printf("What is your name: ");
        scanf("%s", name);
        printf("\n Your name is %s", name);

        return name;
}

int call_func(char name[20])
{
    printf("Hello %s", using_name(name));

}

Error: conflicting types for 'using_name'

Body:
The return and argument types in the funnction prototype at the beginning of the program has to match the actual types when the function is defined later.

Since using_name() is defined as:

char *using_name()

You need to change the earlier prototype to:

char *using_name();
int call_func(char name[20]);

Another solution is to just put the function definitions at the beginning of the program. You only need prototypes for functions that are used before they're defined, or functions that are defined in another compilation unit (although these prototypes are usually put in a header file).


问:
Java - Status 401 - PAC Proxy authentication for JSoup
I'm trying to use Jsoup to gather elements from a webpage, however I am behind a PAC Proxy.  When I try to access a website using Jsoup I get a code status 401 Authentication error. It seems issue is with proxy. I have installed a library called Proxy-Vole that should authenticate me but I believe I am not using it right. What I wish is to ultimately authenticate against the proxy and continue however way possible.</p>

```<code>ProxySearch proxySearch = new ProxySearch();
if (PlatformUtil.getCurrentPlattform() == Platform.WIN) {
    proxySearch.addStrategy(Strategy.IE);
    proxySearch.addStrategy(Strategy.FIREFOX);
    proxySearch.addStrategy(Strategy.JAVA);
} else if (PlatformUtil.getCurrentPlattform() == Platform.LINUX) {
    proxySearch.addStrategy(Strategy.GNOME);
    proxySearch.addStrategy(Strategy.KDE);
    proxySearch.addStrategy(Strategy.FIREFOX);
} else {
    proxySearch.addStrategy(Strategy.OS_DEFAULT);
}

ProxySelector proxySelector = proxySearch.getProxySelector();
ProxySelector.setDefault(proxySelector);

Document doc = Jsoup.connect("https://www.whatever.com").get();
</code>```

答:
As the guide explains you should select the right proxy for your request. I updated the changed the example code for this a bit with Java Streams:

```<code>URI uri = new URI("https://www.whatever.com");

Proxy proxy = Optional.ofNullable(ProxySelector.getDefault())
        .map(ps -> ps.select(uri))
        .stream().flatMap(List::stream)
        .max(Comparator.comparing(Proxy::type))
        .orElse(Proxy.NO_PROXY);
</code>```

This example uses the proxies by the following priority: SOCKS, HTTP, DIRECT. You can easily change that by wrapping it in a separate method:

```<code>private static int getPriority(Proxy.Type type) {
    switch (type) {
        case HTTP:
            return 2;
        case SOCKS:
            return 1;
    }
    return 0;
}
</code>```

Use this with Comparator.comparingInt(p -> getPriority(p.type())) in .max(). Alternatively you can use the official example code which I linked above.

You now can use that proxy in your Jsoup connection:

```<code>Document doc = Jsoup.connect(uri.toString())
        .proxy(proxy)
        .get();
</code>```

Beside that you should make sure that your connection is working through the proxy. If your proxy requires authentication follow this part of the guide. For troubleshooting you can use the Proxy Vole Tester.

Body:
I'm trying to use Jsoup to gather elements from a webpage, however I am behind a PAC Proxy.  When I try to access a website using Jsoup I get a code status 401 Authentication error. It seems issue is with proxy. I have installed a library called Proxy-Vole that should authenticate me but I believe I am not using it right. What I wish is to ultimately authenticate against the proxy and continue however way possible.

ProxySearch proxySearch = new ProxySearch();
if (PlatformUtil.getCurrentPlattform() == Platform.WIN) {
    proxySearch.addStrategy(Strategy.IE);
    proxySearch.addStrategy(Strategy.FIREFOX);
    proxySearch.addStrategy(Strategy.JAVA);
} else if (PlatformUtil.getCurrentPlattform() == Platform.LINUX) {
    proxySearch.addStrategy(Strategy.GNOME);
    proxySearch.addStrategy(Strategy.KDE);
    proxySearch.addStrategy(Strategy.FIREFOX);
} else {
    proxySearch.addStrategy(Strategy.OS_DEFAULT);
}

ProxySelector proxySelector = proxySearch.getProxySelector();
ProxySelector.setDefault(proxySelector);

Document doc = Jsoup.connect("https://www.whatever.com").get();

Body:
As the guide explains you should select the right proxy for your request. I updated the changed the example code for this a bit with Java Streams:

URI uri = new URI("https://www.whatever.com");

Proxy proxy = Optional.ofNullable(ProxySelector.getDefault())
        .map(ps -> ps.select(uri))
        .stream().flatMap(List::stream)
        .max(Comparator.comparing(Proxy::type))
        .orElse(Proxy.NO_PROXY);

This example uses the proxies by the following priority: SOCKS, HTTP, DIRECT. You can easily change that by wrapping it in a separate method:

private static int getPriority(Proxy.Type type) {
    switch (type) {
        case HTTP:
            return 2;
        case SOCKS:
            return 1;
    }
    return 0;
}

Use this with Comparator.comparingInt(p -> getPriority(p.type())) in .max(). Alternatively you can use the official example code which I linked above.

You now can use that proxy in your Jsoup connection:

Document doc = Jsoup.connect(uri.toString())
        .proxy(proxy)
        .get();

Beside that you should make sure that your connection is working through the proxy. If your proxy requires authentication follow this part of the guide. For troubleshooting you can use the Proxy Vole Tester.


问:
How to prevent the user from repetitively inputting same number
I am creating a program in java where the user has to guess a random number generated by the computer, The user gets 20 tries in total to guess the number,if the user enters the same number repeatedly it should show an error message and no count as one of their guesses but am unsure how to do this. For example if the users first guess is 5 and they guess 5 again an error message should appear saying "You have already entered this number </p>

```<code>package guessinggame2;
import java.util.Scanner;

public class GuessingGame2 {

  static Scanner kboard = new Scanner(System.in);

  public static void main(String args[]) // start of main
  {
    System.out.println("Welcome to the guessing game, the computer will
    generate a random number that you have to guess, good luck!");

    int secret_number = 0;
    int number_of_guesses = 0;
    Scanner input = new Scanner(System.in);
    int user_guess;
    int used_number = 0;

    secret_number = (int)(Math.random()*100) + 1;
    System.out.println("The computer has generated it's number");

    for(int i=0; i<20;i++) {

      System.out.println("Please make your guess");
      user_guess = kboard.nextInt();
      number_of_guesses++;

      if (user_guess == secret_number)
      {
        System.out.println("Your guess is correct it took you " +
        number_of_guesses + " guesses");
      }

      else if  (user_guess < secret_number)
      {
        System.out.println("Your guess is too low try again");
      }

      else if (user_guess > secret_number)
      {
        System.out.println("Your guess is too high try again");
      }

      System.out.println (20 - number_of_guesses + " Guesses remaining");
    }
  }
}
</code>```

答:
You can use a set to keep track of numbers submitted by user e.g. </p>

```<code>public class GuessingGame2 {

   static Scanner kboard = new Scanner(System.in);

   public static void main(String args[]) // start of main
   {

      System.out.println("Welcome to the guessing game, the computer will generate a random number that you have to guess, good luck!");

      int secret_number = 0;
      int number_of_guesses = 0;
      Scanner input = new Scanner(System.in);
      int user_guess;
      int used_number = 0;
      HashSet<Integer> user_inputs = new HashSet<>();

      secret_number = (int) (Math.random() * 100) + 1;
      System.out.println("The computer has generated it's number");

      for (int i = 0; i < 20; i++) {

         System.out.println("Please make your guess");
         user_guess = kboard.nextInt();
         if (!user_inputs.add(user_guess)) {
            System.out.println("Please provide another input");
            continue;
         }
         number_of_guesses++;

         if (user_guess == secret_number) {
            System.out.println("Your guess is correct it took you " +
                  number_of_guesses + " guesses");
         } else if (user_guess < secret_number) {
            System.out.println("Your guess is too low try again");
         } else if (user_guess > secret_number) {
            System.out.println("Your guess is too high try again");
         }

         System.out.println(20 - number_of_guesses + " Guesses remaining");

      }

   }

}
</code>```

Body:
I am creating a program in java where the user has to guess a random number generated by the computer, The user gets 20 tries in total to guess the number,if the user enters the same number repeatedly it should show an error message and no count as one of their guesses but am unsure how to do this. For example if the users first guess is 5 and they guess 5 again an error message should appear saying "You have already entered this number

package guessinggame2;
import java.util.Scanner;

public class GuessingGame2 {

  static Scanner kboard = new Scanner(System.in);

  public static void main(String args[]) // start of main
  {
    System.out.println("Welcome to the guessing game, the computer will
    generate a random number that you have to guess, good luck!");

    int secret_number = 0;
    int number_of_guesses = 0;
    Scanner input = new Scanner(System.in);
    int user_guess;
    int used_number = 0;

    secret_number = (int)(Math.random()*100) + 1;
    System.out.println("The computer has generated it's number");

    for(int i=0; i<20;i++) {

      System.out.println("Please make your guess");
      user_guess = kboard.nextInt();
      number_of_guesses++;

      if (user_guess == secret_number)
      {
        System.out.println("Your guess is correct it took you " +
        number_of_guesses + " guesses");
      }

      else if  (user_guess < secret_number)
      {
        System.out.println("Your guess is too low try again");
      }

      else if (user_guess > secret_number)
      {
        System.out.println("Your guess is too high try again");
      }

      System.out.println (20 - number_of_guesses + " Guesses remaining");
    }
  }
}

Body:
You can use a set to keep track of numbers submitted by user e.g.

public class GuessingGame2 {

   static Scanner kboard = new Scanner(System.in);

   public static void main(String args[]) // start of main
   {

      System.out.println("Welcome to the guessing game, the computer will generate a random number that you have to guess, good luck!");

      int secret_number = 0;
      int number_of_guesses = 0;
      Scanner input = new Scanner(System.in);
      int user_guess;
      int used_number = 0;
      HashSet<Integer> user_inputs = new HashSet<>();

      secret_number = (int) (Math.random() * 100) + 1;
      System.out.println("The computer has generated it's number");

      for (int i = 0; i < 20; i++) {

         System.out.println("Please make your guess");
         user_guess = kboard.nextInt();
         if (!user_inputs.add(user_guess)) {
            System.out.println("Please provide another input");
            continue;
         }
         number_of_guesses++;

         if (user_guess == secret_number) {
            System.out.println("Your guess is correct it took you " +
                  number_of_guesses + " guesses");
         } else if (user_guess < secret_number) {
            System.out.println("Your guess is too low try again");
         } else if (user_guess > secret_number) {
            System.out.println("Your guess is too high try again");
         }

         System.out.println(20 - number_of_guesses + " Guesses remaining");

      }

   }

}


问:
Php output array in Twig
I'm trying to output an array in twig, but I don't have enough experience in Twig.

I just don’t know how to output a non-associative array if the keys are index
Array
$c_comments of such

```<code>Array
(
    [0] => Array
        (
            [0] => 20:28 28:05:2019
            [1] => dokl
            [2] => 45645
        )

    [1] => Array
        (
            [0] => 20:27 28:05:2019
            [1] => Alex
            [2] => 546
        )

)
</code>```

```<code>    {% for vars.item.c_page in vars.item.comment %}
       <li>{{ vars.item.comment. }}</li>
    {% endfor %}
</code>```

This is how I display an array in php, also needed in twig

'.$c_comments[$i][0].' '.$c_comments[$i][1].' Wrote:
'.$c_comments[$i][2].'
';
```

<p>Because of this, the template simply doesn't work.
So transfer the data to the template</p>

<pre class="lang-php prettyprint-override"><code>$item = ['first' => $number_f, 'two' => $number_t, 'comment' => $c_comments, 'c_page' => $c_page,'pagination' => $varPagination];
$this->registry['template']->set('item', $item);
</code>```

Where is my mistake?

答:
If your variable is c_comments, you can use this for loop :

// PHP
$data = [
    [
        '20:28 28:05:2019',
        'dokl',
        45645,
    ],

    [
        '20:27 28:05:2019',
        'Alex',
        546,
    ]
];

echo $twig->render('index.html', ['c_comments' => $data]);
```

<pre class="lang-html prettyprint-override"><code><!-- index.html -->
{% for key, comment in c_comments %}
    <i>{{ comment[0] }} {{ comment[1] }} Wrote: {{ comment[2] }}</i><br>
{% endfor %}
</code>```

Title: Php output array in Twig

Body:
I'm trying to output an array in twig, but I don't have enough experience in Twig.

I just don’t know how to output a non-associative array if the keys are index
Array
$c_comments of such

Array
(
    [0] => Array
        (
            [0] => 20:28 28:05:2019
            [1] => dokl
            [2] => 45645
        )

    [1] => Array
        (
            [0] => 20:27 28:05:2019
            [1] => Alex
            [2] => 546
        )

)

    {% for vars.item.c_page in vars.item.comment %}

{{ vars.item.comment. }}

    {% endfor %}

This is how I display an array in php, also needed in twig

'.$c_comments[$i][0].' '.$c_comments[$i][1].' Wrote:
'.$c_comments[$i][2].'
';

Because of this, the template simply doesn't work.
So transfer the data to the template

$item = ['first' => $number_f, 'two' => $number_t, 'comment' => $c_comments, 'c_page' => $c_page,'pagination' => $varPagination];
$this->registry['template']->set('item', $item);

Where is my mistake?

Body:
If your variable is c_comments, you can use this for loop :

// PHP
$data = [
    [
        '20:28 28:05:2019',
        'dokl',
        45645,
    ],

    [
        '20:27 28:05:2019',
        'Alex',
        546,
    ]
];

echo $twig->render('index.html', ['c_comments' => $data]);

<!-- index.html -->
{% for key, comment in c_comments %}
    <i>{{ comment[0] }} {{ comment[1] }} Wrote: {{ comment[2] }}</i><br>
{% endfor %}


问:
How can i prevent this negative white space in my website from appearing?
I have been working on fixing this problem for a while, my website at some pages that has less or few content, or if it's shown in a big screen, it shows white space right under the footer.

"as shown here (https://imgur.com/ATR59Ts)"

i tried using height:100% but it doesn't work if the screen is small, because if i put the height:100% in body{} it will cause elements inside the body to overlap over the body and cause white space.

"as shown here (https://imgur.com/3fWTNZE)"

i have no idea what else to tinker with to prevent this white space.

i tried to add height:100% in body,html (doesn't work on small screens when i add more element in my divs.

```<code>body, html{
    margin: 0;
    padding: 0;
    width: 100%;
    /* height: 100%; */
    /* overflow: scroll; */
}
</code>```

i expected the result to make the body always at 100% on all possible screens, but the element would overflow over the body and cause white spaces.

答: Can you link us to your site so we can see the issue?</p>

Body:
I have been working on fixing this problem for a while, my website at some pages that has less or few content, or if it's shown in a big screen, it shows white space right under the footer.

"as shown here (https://imgur.com/ATR59Ts)"

i tried using height:100% but it doesn't work if the screen is small, because if i put the height:100% in body{} it will cause elements inside the body to overlap over the body and cause white space.

"as shown here (https://imgur.com/3fWTNZE)"

i have no idea what else to tinker with to prevent this white space.

i tried to add height:100% in body,html (doesn't work on small screens when i add more element in my divs.

body, html{
    margin: 0;
    padding: 0;
    width: 100%;
    /* height: 100%; */
    /* overflow: scroll; */
}

i expected the result to make the body always at 100% on all possible screens, but the element would overflow over the body and cause white spaces.


问:
Python get least significant digits from a float (without using string operations)
Assuming I have the float 12345.6789 and I want to get the six least significant digits (i.e. 45.6789) as an int (i.e. 456789) using bit operations in python (v. 2.6).

How do I do that?

Thanks

PS I do not want to use string operations even if it would be rather easy to: for any float f:

```<code>int(str(int(f * 1000))[-10:])
</code>```

EDIT:  This original question is pointless, as shown by comments within.  Many apologies... instead methods on getting the least significant digits without using strings are shown below (using ints and modulus)

答:
Relevant for your string solution is that the float display algorithm changed in python 2.7:

```<code>Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
>>> 12345.6789
12345.678900000001

Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55)
>>> 12345.6789
12345.6789
</code>```

Whether you use one or the other, there's a problem knowing what, exactly, is the precision of a floating point number. Say your algorithm is given the float 1.23. What's the precision? Maybe it was stored as 1.230, but it just happened to end with a zero digit. So you must know how many digits after the period you wish to preserve.

Also, bit operations do not work on floats:

```<code>>>> 12345.6789 << 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'float' and 'int'
</code>```

So you must multiply the float by your known precision and use modulo (%), as suggested by other posters.

Body:
Assuming I have the float 12345.6789 and I want to get the six least significant digits (i.e. 45.6789) as an int (i.e. 456789) using bit operations in python (v. 2.6).

How do I do that?

Thanks

PS I do not want to use string operations even if it would be rather easy to: for any float f:

int(str(int(f * 1000))[-10:])

EDIT:  This original question is pointless, as shown by comments within.  Many apologies... instead methods on getting the least significant digits without using strings are shown below (using ints and modulus)

Body:
Relevant for your string solution is that the float display algorithm changed in python 2.7:

Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
>>> 12345.6789
12345.678900000001

Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55)
>>> 12345.6789
12345.6789

Whether you use one or the other, there's a problem knowing what, exactly, is the precision of a floating point number. Say your algorithm is given the float 1.23. What's the precision? Maybe it was stored as 1.230, but it just happened to end with a zero digit. So you must know how many digits after the period you wish to preserve.

Also, bit operations do not work on floats:

>>> 12345.6789 << 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'float' and 'int'

So you must multiply the float by your known precision and use modulo (%), as suggested by other posters.


问:
Robocopy /RH Run End Time Parameter
I am trying to understand parameters for Robocopy parameter /rh:hhmm-hhmm .

"Specifies run times when new copies may be started."

https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy

```<code>robocopy C:\Source   C:\Destination   /MIR  /rh:1500-1800 .
</code>```

Does that mean job starts at certain time, and if does not complete by end time, it will stop? So if it has a 100 files to copy, and only 50 are copied by 3:00 pm (1800), it will stop?

答:
Yes. According to this article, Robocopy will only do its copying within the specified time frame. It will pause copying on reaching the end time.

using the /RH:hhmm-hhmm switch. This tells Robocopy that it can only copy files between the hours/minutes of the first "hhmm" and the second "hhmm". There are, of course, three scenarios here.

1)
  If the timeframe specified with /RH has already passed, Robocopy will remain paused until the time occurs the next day.

2)
  If the current system time is within the boundaries established with /RH then the copy occurs immediately.

3)
  Finally, if the timeframe specified with /RH is in the future, Robocopy remains paused until the time occurs, and then the copy is performed.

Title: Robocopy /RH Run End Time Parameter

Body:
I am trying to understand parameters for Robocopy parameter /rh:hhmm-hhmm .

"Specifies run times when new copies may be started."

https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy

robocopy C:\Source   C:\Destination   /MIR  /rh:1500-1800 .

Does that mean job starts at certain time, and if does not complete by end time, it will stop? So if it has a 100 files to copy, and only 50 are copied by 3:00 pm (1800), it will stop?


问:
Bootstrap 4 "hidden" class doesn't work
I'm using Bootstrap v4 with it's default CSS and JS. I'm trying to apply the classes hidden, hidden-XX-down and hidden-XX-up to various divs, buttons, etc. But it doesn't seem to affect anything. All other classes work, except this one.

Here's an example:

Lorem ipsum dolor sit amet.

```

I want the paragraph to be invisible when I resize the window to a smaller width (sm-down), yet it remains visible and nothing happens.

答:
If you already have code with the hidden class I recommend creating one:

```<code>.hidden{
    display: none;
}
</code>```

Cheers

Title: Bootstrap 4 "hidden" class doesn't work

Body:
I'm using Bootstrap v4 with it's default CSS and JS. I'm trying to apply the classes hidden, hidden-XX-down and hidden-XX-up to various divs, buttons, etc. But it doesn't seem to affect anything. All other classes work, except this one.

Here's an example:

Lorem ipsum dolor sit amet.

I want the paragraph to be invisible when I resize the window to a smaller width (sm-down), yet it remains visible and nothing happens.

Body:
If you already have code with the hidden class I recommend creating one:

.hidden{
    display: none;
}

Cheers


问:
running a .py file from another Python script using os
Can someone give me a tip on how I can use os to run a different .py file from my python script? This code below works, but only because I specify the complete file path.

How can I modify the code to incorporate running plots.py from the same directory as my main script app.py? Im using Windows at the moment but hoping it can work on any operating system. Thanks

```<code>import os

os.system('py C:/Users/benb/Desktop/flaskEconServer/plots.py')
</code>```

答:
Python has built-in support for executing other scripts, without the need for the os module.

Try:

from . import plots
```

If you want to execute it in an independent python process, look into the multiprocessing or subprocess modules.

Body:
Can someone give me a tip on how I can use os to run a different .py file from my python script? This code below works, but only because I specify the complete file path.

How can I modify the code to incorporate running plots.py from the same directory as my main script app.py? Im using Windows at the moment but hoping it can work on any operating system. Thanks

import os

os.system('py C:/Users/benb/Desktop/flaskEconServer/plots.py')

Body:
Python has built-in support for executing other scripts, without the need for the os module.

Try:

from . import plots

If you want to execute it in an independent python process, look into the multiprocessing or subprocess modules.


问:
Upload multiple files with additional information (Spring RestController)
I know that there are plenty of questions covering the topic, but I cannot figure out how to achieve the following requirement.

I would like to upload a list of files, each one containing some extra information.
In the java world this would mean the following:

```<code>@NoArgsConstructor
@Getter
public class SkillsVerificationData {

   String type; // this information is related to the file
   MultipartFile file;
}
</code>```

Question 1:
Is this possible for a RestController to achieve such a mapping using a wrapper object? (See first answer of the referenced question- @ModelAttribute)

Question 2:
Using the following controller method answered in the question referenced above

```<code>@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = { "multipart/form-data" })
public void upload(@RequestPart("type") @Valid String type,
        @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
}
</code>```

I assume that it applies for a single file. How should the request parts be defined/described to achieve uploading a List<SkillsVerificationData> or SkillsVerificationData[] ?

Note that the client sends the information using FormData.

Thanks in advance!

答:
If i understand your question correctly, you want to upload a list of files along with certain information specific to each file. I can correlate with an example to bring more clarity. A user wants to upload a list of candidates' technical profiles or resumes along with candidate information. If that is the case, you can create an array of MultiPart file and a json structure which contains information about each unique fileName, with unique id and candidate information in a json structure. If that is the requirement, you can refer below the code.

```<code>@PostMapping(
      value = "/multiUpload",
      consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
      produces = MediaType.TEXT_PLAIN_VALUE)
  public ResponseEntity<?> uploadingMultipleFiles(
      @RequestParam("files") MultipartFile[] uploadingFiles, @RequestPart(value = "emps", required = true) String empJsonTxt) {
      System.out.println("EMP as Json String = " + empJsonTxt);
      //Process the empJsonTxt
    ObjectMapper objectMapper = new ObjectMapper();
    try {
      Employee emp = objectMapper.readValue(empJsonTxt, Employee.class);
      System.out.println("Now emp = " + emp);
    } catch (IOException e) {
      e.printStackTrace();
    }
    for (MultipartFile uploadedFile : uploadingFiles) {
      System.out.println("Uploaded File Name = " + uploadedFile.getOriginalFilename());
      File file = new File("E:/sure-delete/" + uploadedFile.getOriginalFilename());

    //Upload functionality
      try {
        uploadedFile.transferTo(file);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return ResponseEntity.ok("All Files uploaded successfully ...");
  }
</code>```

In this case empJsonTxt is a string of json contents which contains all the required information about the employees and their resume/profile. Multipart files will be used only for uploading. However, you can extrapolate this part to make suitable to your requirement. This is doable, there may be many more good approaches also.

Body:
I know that there are plenty of questions covering the topic, but I cannot figure out how to achieve the following requirement.

I would like to upload a list of files, each one containing some extra information.
In the java world this would mean the following:

@NoArgsConstructor
@Getter
public class SkillsVerificationData {

   String type; // this information is related to the file
   MultipartFile file;
}

Question 1:
Is this possible for a RestController to achieve such a mapping using a wrapper object? (See first answer of the referenced question- @ModelAttribute)

Question 2:
Using the following controller method answered in the question referenced above

@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = { "multipart/form-data" })
public void upload(@RequestPart("type") @Valid String type,
        @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
}

I assume that it applies for a single file. How should the request parts be defined/described to achieve uploading a List<SkillsVerificationData> or SkillsVerificationData[] ?

Note that the client sends the information using FormData.

Thanks in advance!

Body:
If i understand your question correctly, you want to upload a list of files along with certain information specific to each file. I can correlate with an example to bring more clarity. A user wants to upload a list of candidates' technical profiles or resumes along with candidate information. If that is the case, you can create an array of MultiPart file and a json structure which contains information about each unique fileName, with unique id and candidate information in a json structure. If that is the requirement, you can refer below the code.

@PostMapping(
      value = "/multiUpload",
      consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
      produces = MediaType.TEXT_PLAIN_VALUE)
  public ResponseEntity<?> uploadingMultipleFiles(
      @RequestParam("files") MultipartFile[] uploadingFiles, @RequestPart(value = "emps", required = true) String empJsonTxt) {
      System.out.println("EMP as Json String = " + empJsonTxt);
      //Process the empJsonTxt
    ObjectMapper objectMapper = new ObjectMapper();
    try {
      Employee emp = objectMapper.readValue(empJsonTxt, Employee.class);
      System.out.println("Now emp = " + emp);
    } catch (IOException e) {
      e.printStackTrace();
    }
    for (MultipartFile uploadedFile : uploadingFiles) {
      System.out.println("Uploaded File Name = " + uploadedFile.getOriginalFilename());
      File file = new File("E:/sure-delete/" + uploadedFile.getOriginalFilename());

    //Upload functionality
      try {
        uploadedFile.transferTo(file);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return ResponseEntity.ok("All Files uploaded successfully ...");
  }

In this case empJsonTxt is a string of json contents which contains all the required information about the employees and their resume/profile. Multipart files will be used only for uploading. However, you can extrapolate this part to make suitable to your requirement. This is doable, there may be many more good approaches also.


问:
How to use GTMetrix Api using Javascript?
I am new to API usage. I have properly managed to utilize Google Page Insights V.5 API through javascript code, but I cannot for the life of me succeed in doing so for GTMetrix. It seems the only information relating to GTMetrix API & Javascript is a link to the RapidApi website. I simply wish to achieve the same simple retrieval of data from GTMetrix as I have from Google. Is this possible?

Am I simply structuring my request incorrectly when I set it as:

```<code>https://gtmetrix.com/api/0.1/?login-user=myemail@email.com&login-pass=MyRanDomApIKeY&location=2&url=https://sitetotest.com
</code>```

Because when I set my Google Page Insights Request URL as the following it works.

```<code>https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://websitetotest.com&category=performance&strategy=desktop&key=MyRanDomApIKeY
</code>```

The below code works for Google Page Insights and I am even able to retrieve JSON data in a browser window with a URL such as:

```<code><div id="firstmetric"></div>
<br>
<div id="domSize"></div>

<button>Click Me</button>

<script>
$('button').click(function(){

var baseUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=";

var fieldUrl = "https://websitetotest.com";
var trailing = "&category=performance&strategy=desktop&key=MyRanDomApIKeY";

$.getJSON(baseUrl + fieldUrl + trailing, function(data){

console.log(data);

var item = data.lighthouseResult.categories.performance.auditRefs[0].weight;
var domSize = data.lighthouseResult.audits['dom-size'].displayValue;

$("#firstmetric").html( item );

$("#domSize").html( domSize );

});

});
</code>```

I truly need it spelled out for me because anything less is going to lead me to ask follow up questions and put us in a tail spin. :/

As a newbie, JSFiddle has been a life saving resource for testing and trying, breaking, and building in my learning process. If it wouldn't be too much to ask for, a fiddle would help me get my brain around things.

答:
The parameters that you are using: login-user and login-pass refer to HTTP authentication on the page you are analyzing (as in, GTmetrix will pass these parameters on your analysis) not your GTmetrix API credentials.

The authentication used for the GTmetrix API is your e-mail for the username and your API key as the password, as pointed out by the API docs.

Another thing to keep in mind is that GTmetrix will not allow you to do API calls through your web application frontend, since they disallow CORS requests. If you do it through your Web application on a normal website, you would be exposing your GTmetrix API key, which is probably not a good idea.

So, you would then do it through your backend code. For example if done through Node JavaScript:

```<code>fetch("https://gtmetrix.com/api/0.1/locations", {
    headers: new Headers({
        "Authorization": 'Basic ' + btoa("[YOUR E-MAIL]" + ":" +"[YOUR API KEY]"),
    }),
}).then(res => res.json())
.then(response => console.log(response));
</code>```

would print me the array of locations.

Note that whichever backend code you choose, you need to add the basic authorization header request for you API call and encode it properly (that is what the btoa function call does).

Body:
I am new to API usage. I have properly managed to utilize Google Page Insights V.5 API through javascript code, but I cannot for the life of me succeed in doing so for GTMetrix. It seems the only information relating to GTMetrix API & Javascript is a link to the RapidApi website. I simply wish to achieve the same simple retrieval of data from GTMetrix as I have from Google. Is this possible?

Am I simply structuring my request incorrectly when I set it as:

https://gtmetrix.com/api/0.1/?login-user=myemail@email.com&login-pass=MyRanDomApIKeY&location=2&url=https://sitetotest.com

Because when I set my Google Page Insights Request URL as the following it works.

https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://websitetotest.com&category=performance&strategy=desktop&key=MyRanDomApIKeY

The below code works for Google Page Insights and I am even able to retrieve JSON data in a browser window with a URL such as:

<button>Click Me</button>

Body:
The parameters that you are using: login-user and login-pass refer to HTTP authentication on the page you are analyzing (as in, GTmetrix will pass these parameters on your analysis) not your GTmetrix API credentials.

The authentication used for the GTmetrix API is your e-mail for the username and your API key as the password, as pointed out by the API docs.

Another thing to keep in mind is that GTmetrix will not allow you to do API calls through your web application frontend, since they disallow CORS requests. If you do it through your Web application on a normal website, you would be exposing your GTmetrix API key, which is probably not a good idea.

So, you would then do it through your backend code. For example if done through Node JavaScript:

fetch("https://gtmetrix.com/api/0.1/locations", {
    headers: new Headers({
        "Authorization": 'Basic ' + btoa("[YOUR E-MAIL]" + ":" +"[YOUR API KEY]"),
    }),
}).then(res => res.json())
.then(response => console.log(response));

would print me the array of locations.

Note that whichever backend code you choose, you need to add the basic authorization header request for you API call and encode it properly (that is what the btoa function call does).


问:
My SpringBoot project won't load into Eclipse
https://grokonez.com/spring-framework/spring-boot/angular-6-upload-get-multipartfile-spring-boot-example#I_Technologies

From the above site I have downloaded the source code for the server. It's supposed to be a SpringBoot application. However, when I try importing the files in Eclipse, it doesn't seem to recognize them.

After downloading the source code as a zip file and extracting all files in it, I have noticed that the .project and .classpath files are missing. However, when I add the two files, I just get a java application and not a SpringBoot application.

Does anyone know how to fix this problem?

答:
Since it is a Maven project , you have to import it as a Maven project:

File -> Import -> Maven -> Existing Maven Project

If the project is imported successfully , .project and .classpath will be generated.


问:
How do I install the yaml package for Python?
I have a Python program that uses YAML.  I attempted to install it on a new server using pip install yaml and it returns the following:

```<code>$ sudo pip install yaml
Downloading/unpacking yaml
  Could not find any downloads that satisfy the requirement yaml
No distributions at all found for yaml
Storing complete log in /home/pa/.pip/pip.log
</code>```

How do I install the yaml package for Python?  I'm running Python 2.7.  (OS: Debian Wheezy)

答:
Consider using strictyaml instead

If you have the luxury of creating the yaml file yourself, or if you don't require any of these features of regular yaml, I recommend using strictyaml instead of the standard pyyaml package.

In short, default yaml has some serious flaws in terms of security, interface, and predictability. strictyaml is a subset of the yaml spec that does not have those issues (and is better documented).

You can read more about the problems with regular yaml here

OPINION: strictyaml should be the default implementation of yaml and the old yaml spec should be obsoleted.

Body:
I have a Python program that uses YAML.  I attempted to install it on a new server using pip install yaml and it returns the following:

$ sudo pip install yaml
Downloading/unpacking yaml
  Could not find any downloads that satisfy the requirement yaml
No distributions at all found for yaml
Storing complete log in /home/pa/.pip/pip.log

How do I install the yaml package for Python?  I'm running Python 2.7.  (OS: Debian Wheezy)


问:
How to access network drive folder using credentials in php?
I am working on a php code as shown below in which I want to access network drive folder (music) using credentials in php. The credentials
is being set because I want to give the full access only to a particular user.

$src_dir = '\\\INVEST-OP-001\test\music';   // Line#A

The full permission/access of music folder is given to the following credentials:

```<code>username : 'mickeymouse'
password : 'helloworld'
</code>```

Problem Statement:

I am wondering what changes I should make in the php code at Line#A so that I can access the music folder using credentials in php.

答:
This works for me:

```<code><?php

$user = 'mickeymouse';
$password = 'helloworld';

exec('net use "\\\INVEST-OP-001\test\music" /user:"'.$user.'" "'.$password.'" /persistent:no');
$files = scandir('\\\INVEST-OP-001\test\music');
echo '```';
print_r($files);

exec('net use "\\\INVEST-OP-001\test\music" /delete /yes');
```

Body:
I am working on a php code as shown below in which I want to access network drive folder (music) using credentials in php. The credentials
is being set because I want to give the full access only to a particular user.

$src_dir = '\\\INVEST-OP-001\test\music';   // Line#A

The full permission/access of music folder is given to the following credentials:

username : 'mickeymouse'
password : 'helloworld'

Problem Statement:

I am wondering what changes I should make in the php code at Line#A so that I can access the music folder using credentials in php.

Body:
This works for me:

<?php

$user = 'mickeymouse';
$password = 'helloworld';

exec('net use "\\\INVEST-OP-001\test\music" /user:"'.$user.'" "'.$password.'" /persistent:no');
$files = scandir('\\\INVEST-OP-001\test\music');
echo '<pre>';
print_r($files);

exec('net use "\\\INVEST-OP-001\test\music" /delete /yes');