问:
Hook all Fetch Api AJAX requests
How would you hook all AJAX requests that use the Fetch Api?  Previously we could do something like this to hook all XMLHttpRequest:

```<code>(function() {
    var origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function() {
      console.log('request started!');
      this.addEventListener('load', function() {
          console.log('request completed!');
          console.log(this.readyState); //will always be 4 (ajax is completed successfully)
          console.log(this.responseText); //whatever the response was
      });
      origOpen.apply(this, arguments);
    };
  })();
</code>```

Or better yet, if you wanted to add to the function above, how would you hook all Fetch Api and all XMLHttpRequest AJAX requests?

答:
In fact, Fetch Api is supported by native browser and only has one interface: fetch.
The constructor return one Promise, and you can't get the Request、Response when you want to return your Promise to rewrite the fetch's constructor.

The following code doesn't work well.

```<code>(function() {
    var oldFectch = fetch;
    fetch.consotructor = function() {
        return new Promise(resolve, reject) {
            // your hook code
        };
    };
})();
</code>```

So,Does it mean we can't hook all Fetch Api ? NO!

Firstly, thanks the window.fetch polyfill.

Then, let's do something(edit fetch.js) and rock.

```<code>(function(self) {
    'use strict';

    // comment or delete the following code block
    // if (self.fetch) {
    //    return
    // }

    var support = {
        searchParams: 'URLSearchParams' in self,
        iterable: 'Symbol' in self && 'iterator' in Symbol,
        // ...
</code>```

Last, hook every thing as your better!

```<code>self.fetch = function(input, init) {
  return new Promise(function(resolve, reject) {
    var request = new Request(input, init)
    var xhr = new XMLHttpRequest()

    // Here we go!
    // Now we get the XMLHttpRequest Object
    // Do what you want!

    xhr.onload = function() {
      var options = {
        status: xhr.status,
        statusText: xhr.statusText,
        headers: parseHeaders(xhr.getAllResponseHeaders() || '')
      }
      options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
      var body = 'response' in xhr ? xhr.response : xhr.responseText
      resolve(new Response(body, options))
    }
    // ...
</code>```

Title: Hook all Fetch Api AJAX requests

Body:
How would you hook all AJAX requests that use the Fetch Api?  Previously we could do something like this to hook all XMLHttpRequest:

(function() {
    var origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function() {
      console.log('request started!');
      this.addEventListener('load', function() {
          console.log('request completed!');
          console.log(this.readyState); //will always be 4 (ajax is completed successfully)
          console.log(this.responseText); //whatever the response was
      });
      origOpen.apply(this, arguments);
    };
  })();

Or better yet, if you wanted to add to the function above, how would you hook all Fetch Api and all XMLHttpRequest AJAX requests?

Body:
In fact, Fetch Api is supported by native browser and only has one interface: fetch.
The constructor return one Promise, and you can't get the Request、Response when you want to return your Promise to rewrite the fetch's constructor.

The following code doesn't work well.

(function() {
    var oldFectch = fetch;
    fetch.consotructor = function() {
        return new Promise(resolve, reject) {
            // your hook code
        };
    };
})();

So,Does it mean we can't hook all Fetch Api ? NO!

Firstly, thanks the window.fetch polyfill.

Then, let's do something(edit fetch.js) and rock.

(function(self) {
    'use strict';

    // comment or delete the following code block
    // if (self.fetch) {
    //    return
    // }

    var support = {
        searchParams: 'URLSearchParams' in self,
        iterable: 'Symbol' in self && 'iterator' in Symbol,
        // ...

Last, hook every thing as your better!

self.fetch = function(input, init) {
  return new Promise(function(resolve, reject) {
    var request = new Request(input, init)
    var xhr = new XMLHttpRequest()

    // Here we go!
    // Now we get the XMLHttpRequest Object
    // Do what you want!

    xhr.onload = function() {
      var options = {
        status: xhr.status,
        statusText: xhr.statusText,
        headers: parseHeaders(xhr.getAllResponseHeaders() || '')
      }
      options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
      var body = 'response' in xhr ? xhr.response : xhr.responseText
      resolve(new Response(body, options))
    }
    // ...


来源: stackexchange

问:
passport authentication not working in nodejs using JWT
I wanna implement passport authorization with jwt, but after running i've got token but the get function is not working. when i remove passport.authenticate it works fine. Even the console.logs are not working if the passport.authenticate is added to get function.

my passport.js file code

```<code>const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('./../server/models/user');

module.exports = function(passport){
console.log('passport');
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken('jwt')
opts.secretOrKey = "secretkey";
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
    console.log(jwt_payload);
    User.getUserById(jwt_payload._doc._id, (err, user) => {
        if(err){
            return done(err, false);
        }
        if(user){
            return done(null, user);
        }else{
            return done(null, false);

        }
    });
}));
}
</code>```

api.js (get function)

```<code>router.get('/profile', passport.authenticate('jwt', {session: false}),
function(req, res){
console.log("prof");
res.json({user: req.user});
});
</code>```

user.js(models)

```<code> const mongoose = require('mongoose');
 const Schema = mongoose.Schema;
 var bcrypt = require('bcrypt-nodejs');

const userSchema = new Schema({
username: { type:String, lowercase:true, required:true, unique:true},
password: { type:String, required:true},
email: { type:String, lowercase:true, required:true, unique:true},

});

 userSchema.pre('save', function(next){
 var user = this;
 bcrypt.hash(user.password, null, null, function(err, hash) {
    // Store hash in your password DB.
    if(err) return next(err);
    user.password = hash;
    next();
 });
})

const User = module.exports = mongoose.model('User', userSchema);

module.exports.getUserById = function(id, callback){
   User.findById(id, callback);
}

module.exports.getUserByUsername = function(username, callback){
const query = {username: username};
User.findOne(query, callback);
}

module.exports.comparePassword = function(candidatePassword, hash, callback)

 {
    bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
        if(err){
            throw err;
        }
        callback(null, isMatch);
    });

 }
</code>```

答:
when you copy token from postman, make sure that you have the space after 'JWT' in the beginning of the token.  Also copy this to '/authenticate' api</p>

```<code>         res.json({
                    success: true,
                    token: 'JWT '+token,
                    user: {
                        id: resUser._id,
                        name: resUser.username,
                        email: resUser.email
                    }
                })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wanna implement passport authorization with jwt, but after running i've got token but the get function is not working. when i remove passport.authenticate it works fine. Even the console.logs are not working if the passport.authenticate is added to get function.

my passport.js file code

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('./../server/models/user');

module.exports = function(passport){
console.log('passport');
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken('jwt')
opts.secretOrKey = "secretkey";
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
    console.log(jwt_payload);
    User.getUserById(jwt_payload._doc._id, (err, user) => {
        if(err){
            return done(err, false);
        }
        if(user){
            return done(null, user);
        }else{
            return done(null, false);

        }
    });
}));
}

api.js (get function)

router.get('/profile', passport.authenticate('jwt', {session: false}),
function(req, res){
console.log("prof");
res.json({user: req.user});
});

user.js(models)

 const mongoose = require('mongoose');
 const Schema = mongoose.Schema;
 var bcrypt = require('bcrypt-nodejs');

const userSchema = new Schema({
username: { type:String, lowercase:true, required:true, unique:true},
password: { type:String, required:true},
email: { type:String, lowercase:true, required:true, unique:true},

});

 userSchema.pre('save', function(next){
 var user = this;
 bcrypt.hash(user.password, null, null, function(err, hash) {
    // Store hash in your password DB.
    if(err) return next(err);
    user.password = hash;
    next();
 });
})

const User = module.exports = mongoose.model('User', userSchema);

module.exports.getUserById = function(id, callback){
   User.findById(id, callback);
}

module.exports.getUserByUsername = function(username, callback){
const query = {username: username};
User.findOne(query, callback);
}

module.exports.comparePassword = function(candidatePassword, hash, callback)

 {
    bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
        if(err){
            throw err;
        }
        callback(null, isMatch);
    });

 }

Body:
when you copy token from postman, make sure that you have the space after 'JWT' in the beginning of the token.  Also copy this to '/authenticate' api

         res.json({
                    success: true,
                    token: 'JWT '+token,
                    user: {
                        id: resUser._id,
                        name: resUser.username,
                        email: resUser.email
                    }
                })


问:
Alternative to for and ifelse loops - determining whether elements lie within generated confidence intervals
I am trying to rewrite my code to not contain any for loops or ifelse loops. The purpose is to extract a matrix containing 0s and 1s depending on variable mu and variable cinterval - to generate a 1 if y0 falls within its 95th CI, and 0 y0 falls within its 95th CI, and likewise for y1. This would be repeated with both y0 and y1 for a number of modules.

mu contains values for y0 and y1; cinterval contains four rows:

lower 95th CI limit for y0

upper 95th CI limit for y0

lower 95th CI limit for y1

upper 95th CI limit for y1

cinterval can be programmed to have any number of modules:

```<code>cinterval.fn <- function(y0y1modules) {
  matrix(c(y0results, y1results) nrow=4, ncol=no.of.modules, byrow=T) #simplified from true code
  rownames(cinterval) <- c("y0 95LCI", "y0 95UCI", "y1 95LCI", "y1 95UCI")
  colnames(cinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(cinterval)
}

> cinterval
         module.1 module.2  module.3
y0 95LCI 2.434602 1.784056  1.751713
y0 95UCI 5.988160 6.519465  6.833455
y1 95LCI 3.778811 2.681708  2.805293
y1 95UCI 9.228941 9.716476 10.258412
</code>```

mu looks like this:

```<code>mu <- c(4, 8)
mu
y0 y1
 4  8
</code>```

The code I have is:

```<code>incinterval.fn <- function(cov.xy, mu, n1, dr) {
  cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after modules
  y0 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y0 <- cbind(y0, ifelse (cinterval[1, module.no] <= mu["y0"] || mu["y0"] <= cinterval[2, module.no], 1, 0))
  }            # If y0 inside CI, 1, else 0
  y1 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y1 <- cbind(y1, ifelse (cinterval[3, module.no] <= mu["y1"] || mu["y1"] <= cinterval[4, module.no], 1, 0))
  }            # If y1 inside CI, 1, else 0
  incinterval <- rbind(y0, y1) # Combines vectors
  colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(incinterval)
}
</code>```

The result, incinterval, looks like this:

```<code>     module.1 module.2 module.3
[y0]        1        1        1
[y1]        1        1        1
</code>```

Any assistance with more efficient coding to replace for and ifelse would be greatly appreciated! I currently use 2 for and ifeelse loops.

答:
I'm not sure how much you depend on your data structure, but I'm proposing a different approach.

If you'd structure your dataset in another format, you could easily write the outcome of incinterval in an additional variable.

New data:

```<code>cinterval <-  data.frame(year = c(0, 0, 0, 1, 1, 1),
               LCI = c(2.434602, 1.784056, 1.751713, 3.778811, 2.681708, 2.805293),
               UCI = c(5.988160, 6.519465, 6.833455, 9.228941, 9.716476, 10.258412),
               module = c(1, 2, 3, 1, 2, 3)
               )

> cinterval
  year      LCI       UCI module
1    0 2.434602  5.988160      1
2    0 1.784056  6.519465      2
3    0 1.751713  6.833455      3
4    1 3.778811  9.228941      1
5    1 2.681708  9.716476      2
6    1 2.805293 10.258412      3
</code>```

Now you define mu

```<code>mu <- c("y0" = 4, "y1" = 8)
</code>```

and apply a short ifelse condition over your rows using findInterval to get a new column with your results:

```<code>cinterval$inCI <- apply(cinterval, 1,
                        function(x) ifelse(x[1] == 0, findInterval(mu["y0"], x[2:3]),
                                                      findInterval(mu["y1"], x[2:3]))
                        )
</code>```

Your output:

```<code>  year      LCI       UCI module inCI
1    0 2.434602  5.988160      1    1
2    0 1.784056  6.519465      2    1
3    0 1.751713  6.833455      3    1
4    1 3.778811  9.228941      1    1
5    1 2.681708  9.716476      2    1
6    1 2.805293 10.258412      3    1
</code>```

Note that findInterval will return either a 0 if the mu value was below the CI, a 1 if it was within, or a 2 if it was above the CI.

This may become cumbersome when dealing with many years, but is quite robust to include as many modules as you wish.

Body:
I am trying to rewrite my code to not contain any for loops or ifelse loops. The purpose is to extract a matrix containing 0s and 1s depending on variable mu and variable cinterval - to generate a 1 if y0 falls within its 95th CI, and 0 y0 falls within its 95th CI, and likewise for y1. This would be repeated with both y0 and y1 for a number of modules.

mu contains values for y0 and y1; cinterval contains four rows:

lower 95th CI limit for y0

upper 95th CI limit for y0

lower 95th CI limit for y1

upper 95th CI limit for y1

cinterval can be programmed to have any number of modules:

cinterval.fn <- function(y0y1modules) {
  matrix(c(y0results, y1results) nrow=4, ncol=no.of.modules, byrow=T) #simplified from true code
  rownames(cinterval) <- c("y0 95LCI", "y0 95UCI", "y1 95LCI", "y1 95UCI")
  colnames(cinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(cinterval)
}

> cinterval
         module.1 module.2  module.3
y0 95LCI 2.434602 1.784056  1.751713
y0 95UCI 5.988160 6.519465  6.833455
y1 95LCI 3.778811 2.681708  2.805293
y1 95UCI 9.228941 9.716476 10.258412

mu looks like this:

mu <- c(4, 8)
mu
y0 y1
 4  8

The code I have is:

incinterval.fn <- function(cov.xy, mu, n1, dr) {
  cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after modules
  y0 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y0 <- cbind(y0, ifelse (cinterval[1, module.no] <= mu["y0"] || mu["y0"] <= cinterval[2, module.no], 1, 0))
  }            # If y0 inside CI, 1, else 0
  y1 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y1 <- cbind(y1, ifelse (cinterval[3, module.no] <= mu["y1"] || mu["y1"] <= cinterval[4, module.no], 1, 0))
  }            # If y1 inside CI, 1, else 0
  incinterval <- rbind(y0, y1) # Combines vectors
  colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(incinterval)
}

The result, incinterval, looks like this:

     module.1 module.2 module.3
[y0]        1        1        1
[y1]        1        1        1

Any assistance with more efficient coding to replace for and ifelse would be greatly appreciated! I currently use 2 for and ifeelse loops.

Body:
I'm not sure how much you depend on your data structure, but I'm proposing a different approach.

If you'd structure your dataset in another format, you could easily write the outcome of incinterval in an additional variable.

New data:

cinterval <-  data.frame(year = c(0, 0, 0, 1, 1, 1),
               LCI = c(2.434602, 1.784056, 1.751713, 3.778811, 2.681708, 2.805293),
               UCI = c(5.988160, 6.519465, 6.833455, 9.228941, 9.716476, 10.258412),
               module = c(1, 2, 3, 1, 2, 3)
               )

> cinterval
  year      LCI       UCI module
1    0 2.434602  5.988160      1
2    0 1.784056  6.519465      2
3    0 1.751713  6.833455      3
4    1 3.778811  9.228941      1
5    1 2.681708  9.716476      2
6    1 2.805293 10.258412      3

Now you define mu

mu <- c("y0" = 4, "y1" = 8)

and apply a short ifelse condition over your rows using findInterval to get a new column with your results:

cinterval$inCI <- apply(cinterval, 1,
                        function(x) ifelse(x[1] == 0, findInterval(mu["y0"], x[2:3]),
                                                      findInterval(mu["y1"], x[2:3]))
                        )

Your output:

  year      LCI       UCI module inCI
1    0 2.434602  5.988160      1    1
2    0 1.784056  6.519465      2    1
3    0 1.751713  6.833455      3    1
4    1 3.778811  9.228941      1    1
5    1 2.681708  9.716476      2    1
6    1 2.805293 10.258412      3    1

Note that findInterval will return either a 0 if the mu value was below the CI, a 1 if it was within, or a 2 if it was above the CI.

This may become cumbersome when dealing with many years, but is quite robust to include as many modules as you wish.


问:
Can't manage nil with Codable concept swift 4 while json parsing
I want to parse some data with some null field.And if the value of string is null than it should be replace with ""(blank) likewise for all data types. If the value is getting nil than I want to set default value of variable. here in JSON I am getting value of brewery null.

JSON For example

```<code>{
    "name": "Endeavor",
    "abv": 8.9,
    "brewery": null,
    "style": "ipa"
}
</code>```

I have created model class like this.

```<code>struct Beer: Codable {
    var name: String?
    var brewery: String?
    var style: String?
}
</code>```

I want to decode given json to Beer class, So how can I Manage Nil with Default value??

答:
The optional value inside model is perfectly fine.

At the time of parsing JSON you could:

Use Swift coalescing operator ??

Brewery = someOptionalValue ?? ""

Create your own category around optional:

extension Optional {
    func getOrElse<T>(defaultValue: T) -> T {
        if let value = self? {
            return value as T
        } else {
            return defaultValue
        }
    }
}

and use it as Brewery = someOptionalValue.getOrElse("")

or you could simply use a ternary operator

EDIT 1: As per the comment

Modify the model as below and access breweryComputed instead of brewery

```<code>struct Beer: Codable {
var name: String?
var brewery: String?
var style: String?

var breweryComputed : String {
    get{
        return (self.brewery ?? "")
    }
  }
}
</code>```

Body:
I want to parse some data with some null field.And if the value of string is null than it should be replace with ""(blank) likewise for all data types. If the value is getting nil than I want to set default value of variable. here in JSON I am getting value of brewery null.

JSON For example

{
    "name": "Endeavor",
    "abv": 8.9,
    "brewery": null,
    "style": "ipa"
}

I have created model class like this.

struct Beer: Codable {
    var name: String?
    var brewery: String?
    var style: String?
}

I want to decode given json to Beer class, So how can I Manage Nil with Default value??

Body:
The optional value inside model is perfectly fine.

At the time of parsing JSON you could:

Use Swift coalescing operator ??

Brewery = someOptionalValue ?? ""

Create your own category around optional:

extension Optional {
    func getOrElse<T>(defaultValue: T) -> T {
        if let value = self? {
            return value as T
        } else {
            return defaultValue
        }
    }
}

and use it as Brewery = someOptionalValue.getOrElse("")

or you could simply use a ternary operator

EDIT 1: As per the comment

Modify the model as below and access breweryComputed instead of brewery

struct Beer: Codable {
var name: String?
var brewery: String?
var style: String?

var breweryComputed : String {
    get{
        return (self.brewery ?? "")
    }
  }
}


问:
How Map two entities that share the same primary key in hibernate with annotations?
I'm new to hibernate and I do not know how to map this simple Model
using JPA or Hibernate annotations. I try to model is that a provider has a global rating and the identifier of the global rating entity is the same identifier of the provider entity (unidirectional OneToOne), in other words I want to have the foreign key in the entity global rating be primary and foreign at the same time, but that the provider entity also has a foreign key of the entity global rating. This is possible?

答:
You can achieve what you want with @MapsId annotation.

Example:

```<code>@Entity
public class Provider{

    @Id
    @GeneratedValue
    private long idProvider;

    @OneToOne(cascade=CascadeType.ALL, mappedBy="provider")
    private GlobalRating rating;

    // Getter & Setter
}

@Entity
public class GlobalRating{

    @Id
    private long idProvider;

    @OneToOne(cascade=CascadeType.ALL)
    @MapsId
    @JoinColumn(name="idProvider")
    private Provider provider;

    // Getter & Setter
}
</code>```

Body:
You can achieve what you want with @MapsId annotation.

Example:

@Entity
public class Provider{

    @Id
    @GeneratedValue
    private long idProvider;

    @OneToOne(cascade=CascadeType.ALL, mappedBy="provider")
    private GlobalRating rating;

    // Getter & Setter
}

@Entity
public class GlobalRating{

    @Id
    private long idProvider;

    @OneToOne(cascade=CascadeType.ALL)
    @MapsId
    @JoinColumn(name="idProvider")
    private Provider provider;

    // Getter & Setter
}

ContentLicense: CC BY-SA 4.0


问:
Who can explain the name "pull request' in git?
Who can explain the name "pull request' in git?

Because it is a workflow method for submitting contributions.

My question is just about the name 'pull'.

I understand the 'request' part.

What or which pulling do they mean?

Why is push request, submit request not better?

Note that I belong to the class of non-native "english" speakers.

答:
You need to refer to the documentation

Pull requests let you tell others about changes you've pushed to a repository on GitHub. Once a pull request is opened, you can discuss and review the potential changes with collaborators and add follow-up commits before the changes are merged into the repository.

Since its the request made to the target to pull your artifacts it's called a pull request


问:
Nested Template Class
I am trying to obtain a nested template class.

The compiler gives me the following error:

error: type/value mismatch at argument 1 in template parameter list for ‘template class MyClass’
  note:   expected a class template, got ‘SpecificType {aka TemplateClass< Type1, Typ2, Type3 >}

This is my code

```<code>/* ...class definition... */
template < template < typename T1,typename T2,typename T3 > typename T>
class MyClass{
    // is there a way to have these types available here
    // passing one single specialized type in the main?
    T1 member1;
    T2 member2;
    T3 member3;
    T<T1, T2, T3> member4;
};

/*  ...in my main... */
using SpecificType =  TemplateClass< Type1, Type2, Type3 >;
SpecificType test_object; //until here compiles
MyClass< SpecificType > myclass;
</code>```

I have already tried to define a SpecificType object, and until that point my code compiles and works.

答:
You define MyClass to accept a template as parameter and not a type. As this you simply should pass the template e.g. TemplateClass itself.

So your definition says: I want to have a template which itself has three template parameters. So you must pass a template and not a instance of a template.

```<code>/* ...class definition... */
template < template < typename T1,typename T2,typename T3 > typename T>
class MyClass{ /*...*/};

template <typename T1, typename T2, typename T3>
class TemplateClass {};

/*  ...in my main... */
int main()
{
    MyClass< TemplateClass > myclass;
}
</code>```

After passing the template to your class, inside the class you can use the template to instantiate it like:

```<code>template < template < typename T1,typename T2,typename T3 > typename T>
class MyClass
{
    T<int, float, char> obj;
};
</code>```

After getting your comment, you want a different thing! You want to pass a type, here you want the instance of a template. So simply do the following:

```<code>/* ...class definition... */
template < typename T>
class MyClass
{
    T obj;
};

template <typename T1, typename T2, typename T3>
class TemplateClass {};

int main()
{
    MyClass< TemplateClass< int, float, char> > myclass;
}
</code>```

And now to get the second request from OP :-)

It is possible to pass a type ( e.g. here we see the instantiated template ) and get out the types from the template parameters. Look here:

```<code>template < typename T>
class MyClass;

template < template < typename ,typename ,typename  > typename T, typename T1, typename T2, typename T3>
class MyClass< T<T1,T2,T3> >
{
    T1 var1; // here you can use the types...
    T2 var2;

    T<T1,T2,T3> obj;
};

template <typename T1, typename T2, typename T3>
class TemplateClass {};

int main()
{
    MyClass< TemplateClass< int, float, char> > myclass;
}
</code>```

Title: Nested Template Class

Body:
I am trying to obtain a nested template class.

The compiler gives me the following error:

error: type/value mismatch at argument 1 in template parameter list for ‘template class MyClass’
  note:   expected a class template, got ‘SpecificType {aka TemplateClass< Type1, Typ2, Type3 >}

This is my code

/* ...class definition... */
template < template < typename T1,typename T2,typename T3 > typename T>
class MyClass{
    // is there a way to have these types available here
    // passing one single specialized type in the main?
    T1 member1;
    T2 member2;
    T3 member3;
    T<T1, T2, T3> member4;
};

/*  ...in my main... */
using SpecificType =  TemplateClass< Type1, Type2, Type3 >;
SpecificType test_object; //until here compiles
MyClass< SpecificType > myclass;

I have already tried to define a SpecificType object, and until that point my code compiles and works.

Body:
You define MyClass to accept a template as parameter and not a type. As this you simply should pass the template e.g. TemplateClass itself.

So your definition says: I want to have a template which itself has three template parameters. So you must pass a template and not a instance of a template.

/* ...class definition... */
template < template < typename T1,typename T2,typename T3 > typename T>
class MyClass{ /*...*/};

template <typename T1, typename T2, typename T3>
class TemplateClass {};

/*  ...in my main... */
int main()
{
    MyClass< TemplateClass > myclass;
}

After passing the template to your class, inside the class you can use the template to instantiate it like:

template < template < typename T1,typename T2,typename T3 > typename T>
class MyClass
{
    T<int, float, char> obj;
};

After getting your comment, you want a different thing! You want to pass a type, here you want the instance of a template. So simply do the following:

/* ...class definition... */
template < typename T>
class MyClass
{
    T obj;
};

template <typename T1, typename T2, typename T3>
class TemplateClass {};

int main()
{
    MyClass< TemplateClass< int, float, char> > myclass;
}

And now to get the second request from OP :-)

It is possible to pass a type ( e.g. here we see the instantiated template ) and get out the types from the template parameters. Look here:

template < typename T>
class MyClass;

template < template < typename ,typename ,typename  > typename T, typename T1, typename T2, typename T3>
class MyClass< T<T1,T2,T3> >
{
    T1 var1; // here you can use the types...
    T2 var2;

    T<T1,T2,T3> obj;
};

template <typename T1, typename T2, typename T3>
class TemplateClass {};

int main()
{
    MyClass< TemplateClass< int, float, char> > myclass;
}


问:
How to set a configuration parameter at DB level in PostgreSQL permanently?
I am aware of the below command:

```<code>ALTER DATABASE name SET configuration_parameter { TO | = } { value | DEFAULT }
</code>```

On server restart, will these be overwritten by the parameter set in postgresql.conf

答:
https://www.postgresql.org/docs/current/static/sql-alterdatabase.html

Set this database's session default for the specified configuration
  parameter to the given value.

so If configuration_parameter is set for database it overrides the postgres.conf. It should persist after db restart, yes

Body:
I am aware of the below command:

ALTER DATABASE name SET configuration_parameter { TO | = } { value | DEFAULT }

On server restart, will these be overwritten by the parameter set in postgresql.conf


问:
Layout best practices with fragments
I work on a radio/video player (for android tv). I need 3 (fullscreen: all my app is fullscreen) pages (let's call them Main pages) :

Radio page (audio stream)

Tv page (video stream)

Video page (same as tv page but with local server videos)

On this 3 pages I need to show a menu to navigate between the 3 main pages or to close the application. This menu is called by pressing the dpad down key (back to hide).

Each page need a main menu who will come above the main page (to select another webradio or another video). The Tv main page doesn't have any menu page.

For now, I use multiple activities, one for each main page but I have to copy the main menu code...

So I thought about this kind of layout but I'm not sure it's the best way:

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/content_container"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/main_menu_container"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/menu_container"/>
</RelativeLayout>
</code>```

Question:

Is it nice to have only one Activity for the entire application ?

If it's OK, how can I do multiple level of menu (for example: my video menu would show first a page with 2 choices and then the filtered list of video). Is it best practice to put a fragment on another fragment ?

Thanks in advance !

答:
Answers,

It depends on your application design and requirement. But in your case, only one Activity you should use.

It can be worst practice to put Fragment on another. There should be only one Fragment at a same time/place on a Activity (all other should be cleared out).

Title: Layout best practices with fragments

Body:
I work on a radio/video player (for android tv). I need 3 (fullscreen: all my app is fullscreen) pages (let's call them Main pages) :

Radio page (audio stream)

Tv page (video stream)

Video page (same as tv page but with local server videos)

On this 3 pages I need to show a menu to navigate between the 3 main pages or to close the application. This menu is called by pressing the dpad down key (back to hide).

Each page need a main menu who will come above the main page (to select another webradio or another video). The Tv main page doesn't have any menu page.

For now, I use multiple activities, one for each main page but I have to copy the main menu code...

So I thought about this kind of layout but I'm not sure it's the best way:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/content_container"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/main_menu_container"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/menu_container"/>
</RelativeLayout>

Question:

Is it nice to have only one Activity for the entire application ?

If it's OK, how can I do multiple level of menu (for example: my video menu would show first a page with 2 choices and then the filtered list of video). Is it best practice to put a fragment on another fragment ?

Thanks in advance !


问:
Getting the key with max value in a portion of a python dictionary
I have a python dictionary, its keys are datetime.datetime objects, such as:

```<code>a = {datetime(2018,1,1):1, datetime(2018,1,2):2, datetime(2018,1,3):3, ...}
</code>```

I would like to get the key (date) with max value in a portion of this dictionary, such as between dates 2018-03-27 and 2018-04-17.

What is the mosy pythonic way of achieving this?

答:
First select those items in the dictionary having a key between the required values, then find the one with the largest value:

```<code>from datetime import datetime

min_date = datetime(2018, 3, 27)
max_date = datetime(2018, 4, 17)

date = max((d[k], k) for k in d if min_date <= k <= max_date)[1]
</code>```

This code creates a sequence of tuples containing the value and datetime (N.B. in that order) between min_date and max_date. Then it chooses the item from that sequence with the largest value. The required data is the second element in the resulting tuple.

Body:
I have a python dictionary, its keys are datetime.datetime objects, such as:

a = {datetime(2018,1,1):1, datetime(2018,1,2):2, datetime(2018,1,3):3, ...}

I would like to get the key (date) with max value in a portion of this dictionary, such as between dates 2018-03-27 and 2018-04-17.

What is the mosy pythonic way of achieving this?

Body:
First select those items in the dictionary having a key between the required values, then find the one with the largest value:

from datetime import datetime

min_date = datetime(2018, 3, 27)
max_date = datetime(2018, 4, 17)

date = max((d[k], k) for k in d if min_date <= k <= max_date)[1]

This code creates a sequence of tuples containing the value and datetime (N.B. in that order) between min_date and max_date. Then it chooses the item from that sequence with the largest value. The required data is the second element in the resulting tuple.


问:
How I avoid brute force searching in hash search
I have a program in java which takes an input string and generate a hash value using MD5 algorithm. The program searches a particular pattern (e.g 118855) in the generated hash string in each iteration by varying the last part of the input string by appending it with an integer which is incremented by one in each pass.

For example, if the input string is xyz then I will first find the hash for xyz0 and then for xyz1 and then for xyz2 and so no using MD5. In each pass it will search for a pattern eg 12345 in each hash value. Until this pattern is found the program will not stop.

Now my question is that how to avoid the brute force approach in searching this pattern in these generated hash strings. In other words, how can I jump the integer by a dynamic value instead of one each time?

Note: All the above hashes are generated using MD5. I am not requesting for replacement for MD5. Also, I not finding a collision in two hash value. My concern is to find a given substring pattern in these generated hash value.

答:
If it were possible to tell in advance what to append to your "xyz" string (instead of brute-force search) so the MD5 hash contains a given pattern, then the algorithm were useless.

Message digest algorithms are meant to make cheating near-impossible, so constructing a manipulated document that still gives the same hash value as the original one, should be computationally very hard.

MD5 isn't the cryptographically strongest available hashing algorithm, but surely you can't just somehow "construct" a plain text to give some specified MD5 hash (or hash pattern). If that were possible, people had thrown away MD5 long ago.

Unless you are a cryptography guru, I'd recommend to stay with the brute-force approach.

[EDIT]

The number of tries to find a N-digit pattern should roughly be 16^N / (33-N) (not corrected for double matches), e.g. 2500 tries for a 4-digit pattern or 40000 tries for a 5-digit pattern. So, depending on the pattern length, that looks doable to me.

[EDIT]

To explain the "calculation":

MD5 is written as 32 hex digits.

So if you want to find a specific 5-digit pattern in front of the hash, there are 16^5 different possibilities, so the probability to get the correct one with a single attempt is 1/16^5, thus needing roughly 16^5 attempts until you succeed.

But we don't care about the position where in the hash we find our pattern, so now there are 28 positions where we have a chance to find our pattern. This roughly multiplies the match probability by 28 (this isn't exact, as this calculation counts a double match twice where the pattern is contained at two different positions). So that factor divides the expected number of attempts.


问:
Accessing Lambda functionality in Amazon Lex console
I started playing around with Amazon Lex to build chatbots. I've been following their examples but one issue is that I can't see to use the Lambda functionality in the user console. I can't tell if this is due to the resource 404s I see in the console or if this functionality cannot be controlled through the UI.

I'm not able to type into the AWS Lambda function field under Fulfillment on an intent, but I can't figure out where to populate what goes in that dropdown. The page does have some 404s, specifically around loading the /lex/api/iam resource.

Is anyone familiar with the Lex console? I've looked through the documentation, I've disabled all browser extensions that might be interfering, I feel like I'm missing something but don't know what. Thanks for reading if you got this far.

答:
These are the lambda functions which you made for your lex bots.
If you have created lambda function already, you need to refresh the browser in order to see it in drop-down. Both lex and lambda must be in same region. Also, you need to provide access permissions to your lambda function for lex.</p>


问:
Ionic native Google Maps Android not working
I have to add a view with Google maps map on my project. I followed the official ionic native Google maps documentation but it does not work.

I assigned background color pink to the div that contains the map (for testing), before adding the map to the div, the div shows correctly. But when the map is added to the div the background of the modal window turns to transparent, and the div disappears. But no error is shown.

I tried different ways to attach the map on the div, but the results are the same.

When I use the code of the Ionic docs I got this error message "GoogleMaps [deprecated] Please use GoogleMaps.create()". I tried using GoogleMaps.create() instead of the argument of the constructor avoiding this error message, but still not working.

My ion-content:

```<code><ion-content fullscreen overflow-scroll="true" class="container">

  <div #map id="map"></div>

</ion-content>
</code>```

Part of the css:

```<code>#map {
        height: 90%;
        width: 100%;
        border-width: 5px;
        border-color: red;
        background: pink;
    }
</code>```

And here we got fragments of the ts:

```<code>import {
  GoogleMaps,
  GoogleMap,
  GoogleMapsEvent,
  GoogleMapOptions,
  CameraPosition,
  MarkerOptions,
  Marker
 } from '@ionic-native/google-maps';

...

export class PerfilPage {
  @ViewChild(Content) content: Content;
  @ViewChild('map') mapElement: ElementRef;
  map: GoogleMap;

...

ionViewDidLoad() {
// I use this for changing the nab-bar color
    this.content.ionScroll.subscribe((scroll) => {
      // console.log('user scrolled', scroll);
      if ( scroll.scrollTop > 100 ) {
        this.toolbar_color = "bg_search"
      } else {
        this.toolbar_color = "transparent"
      }
      this.ref.detectChanges();
    });

    // this.loadMap();
    // this.initMap();
    // this.testMap();
    this.offiMap();
  }

// Official Ionic documentation code
 offiMap() {
    let mapOptions: GoogleMapOptions = {
      camera: {
        target: {
          lat: 43.0741904,
          lng: -89.3809802
        },
        zoom: 18,
        tilt: 30
      }
    };

    this.map = this.googleMaps.create('map', mapOptions);

    // Wait the MAP_READY before using any methods.
    this.map.one(GoogleMapsEvent.MAP_READY)
      .then(() => {
        console.log('Map is ready!');

        // Now you can use all methods safely.
        this.map.addMarker({
            title: 'Ionic',
            icon: 'blue',
            animation: 'DROP',
            position: {
              lat: 43.0741904,
              lng: -89.3809802
            }
          })
          .then(marker => {
            marker.on(GoogleMapsEvent.MARKER_CLICK)
              .subscribe(() => {
                alert('clicked');
              });
          });

      });
  }
}
</code>```

PS: the API key works on other projects (not Ionic projects), so idk where is the problem.

Thanks :)

答:
```<code>   loadMap() {
            let element = document.getElementById('map');
            let mapOptions: GoogleMapOptions = {
              camera: {
                target: {
                   lat: 43.0741904,
                   lng: -89.3809802
                },
               zoom: 18,
               tilt: 30
             }
        };

      let map: GoogleMap = this.googleMaps.create(element, mapOptions);

       map.addMarker({
               title: 'Location',
               icon: 'blue',
               animation: 'DROP',
               position: {
                 lat: 43.0741904,
                 lng: -89.3809802
               }
         })
          .then(marker => {
             marker.on(GoogleMapsEvent.MARKER_CLICK)
                 .subscribe(() => {
                    //alert('clicked');
                  });
              });
  }
</code>```

Try this

Body:
I have to add a view with Google maps map on my project. I followed the official ionic native Google maps documentation but it does not work.

I assigned background color pink to the div that contains the map (for testing), before adding the map to the div, the div shows correctly. But when the map is added to the div the background of the modal window turns to transparent, and the div disappears. But no error is shown.

I tried different ways to attach the map on the div, but the results are the same.

When I use the code of the Ionic docs I got this error message "GoogleMaps [deprecated] Please use GoogleMaps.create()". I tried using GoogleMaps.create() instead of the argument of the constructor avoiding this error message, but still not working.

My ion-content:

<ion-content fullscreen overflow-scroll="true" class="container">

</ion-content>

Part of the css:

#map {
        height: 90%;
        width: 100%;
        border-width: 5px;
        border-color: red;
        background: pink;
    }

And here we got fragments of the ts:

import {
  GoogleMaps,
  GoogleMap,
  GoogleMapsEvent,
  GoogleMapOptions,
  CameraPosition,
  MarkerOptions,
  Marker
 } from '@ionic-native/google-maps';

...

export class PerfilPage {
  @ViewChild(Content) content: Content;
  @ViewChild('map') mapElement: ElementRef;
  map: GoogleMap;

...

ionViewDidLoad() {
// I use this for changing the nab-bar color
    this.content.ionScroll.subscribe((scroll) => {
      // console.log('user scrolled', scroll);
      if ( scroll.scrollTop > 100 ) {
        this.toolbar_color = "bg_search"
      } else {
        this.toolbar_color = "transparent"
      }
      this.ref.detectChanges();
    });

    // this.loadMap();
    // this.initMap();
    // this.testMap();
    this.offiMap();
  }

// Official Ionic documentation code
 offiMap() {
    let mapOptions: GoogleMapOptions = {
      camera: {
        target: {
          lat: 43.0741904,
          lng: -89.3809802
        },
        zoom: 18,
        tilt: 30
      }
    };

    this.map = this.googleMaps.create('map', mapOptions);

    // Wait the MAP_READY before using any methods.
    this.map.one(GoogleMapsEvent.MAP_READY)
      .then(() => {
        console.log('Map is ready!');

        // Now you can use all methods safely.
        this.map.addMarker({
            title: 'Ionic',
            icon: 'blue',
            animation: 'DROP',
            position: {
              lat: 43.0741904,
              lng: -89.3809802
            }
          })
          .then(marker => {
            marker.on(GoogleMapsEvent.MARKER_CLICK)
              .subscribe(() => {
                alert('clicked');
              });
          });

      });
  }
}

PS: the API key works on other projects (not Ionic projects), so idk where is the problem.

Thanks :)

Body:
   loadMap() {
            let element = document.getElementById('map');
            let mapOptions: GoogleMapOptions = {
              camera: {
                target: {
                   lat: 43.0741904,
                   lng: -89.3809802
                },
               zoom: 18,
               tilt: 30
             }
        };

      let map: GoogleMap = this.googleMaps.create(element, mapOptions);

       map.addMarker({
               title: 'Location',
               icon: 'blue',
               animation: 'DROP',
               position: {
                 lat: 43.0741904,
                 lng: -89.3809802
               }
         })
          .then(marker => {
             marker.on(GoogleMapsEvent.MARKER_CLICK)
                 .subscribe(() => {
                    //alert('clicked');
                  });
              });
  }

Try this


问:
How to send dict in Header as value to key 'Authorization' in python requests?
I have to test the results of the API. I am sending

```<code>Key - 'Authorization'
value - { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}
</code>```

I am getting proper output in postman but my code fails in requests

```<code>import requests
from pprint import pprint

def main():
    url = "http://test.example.com/recharger-api/merchant/getPlanList?circleid=1&operatorid=1&categoryid=1"
    headers = {'Authorization': { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}}
    response = requests.get(url, headers = headers)
    data = response.json()
    pprint(data)

if __name__ == "__main__":
    main()
</code>```

The error I get:

```<code>requests.exceptions.InvalidHeader: Value for header {'Authorization': { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}} must be of type str or bytes, not <class 'dict'>
</code>```

答:
The header is almost certainly expecting JSON data. A Python dictionary, even simply converted to a string, is not the same thing as JSON. The requests library doesn't accept anything other than strings for headers anyway. POSTMan only deals in strings, not Python objects, so you wouldn't see the issue there.

Explicitly convert it:

```<code>import json

headers = {
    'Authorization': json.dumps({
        "merchantIp": "13.130.189.149",
        "merchantHash": "c8b71ea1ab250adfc67f90938750cd30",
        "merchantName": "test"
    })
}
</code>```

Body:
I have to test the results of the API. I am sending

Key - 'Authorization'
value - { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}

I am getting proper output in postman but my code fails in requests

import requests
from pprint import pprint

def main():
    url = "http://test.example.com/recharger-api/merchant/getPlanList?circleid=1&operatorid=1&categoryid=1"
    headers = {'Authorization': { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}}
    response = requests.get(url, headers = headers)
    data = response.json()
    pprint(data)

if __name__ == "__main__":
    main()

The error I get:

requests.exceptions.InvalidHeader: Value for header {'Authorization': { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}} must be of type str or bytes, not <class 'dict'>

Body:
The header is almost certainly expecting JSON data. A Python dictionary, even simply converted to a string, is not the same thing as JSON. The requests library doesn't accept anything other than strings for headers anyway. POSTMan only deals in strings, not Python objects, so you wouldn't see the issue there.

Explicitly convert it:

import json

headers = {
    'Authorization': json.dumps({
        "merchantIp": "13.130.189.149",
        "merchantHash": "c8b71ea1ab250adfc67f90938750cd30",
        "merchantName": "test"
    })
}


问:
HTTPRequest to php not returning any values in firefox
I have a HTTPRequest that does not run using firefox, it does run on google chrome as it returns the alerts I have written for test.

```<code>var htpr = new XMLHttpRequest();
  var url = "../something.php";
  var val = "pro_ID="+prod_id+"&quan="+quan;
  alert("test ajx");
  htpr.open("POST", url, true);
  htpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  htpr.onreadystatechange = function(){
    if(htpr.readyState == 4 && htpr.status == 200){
        var dt = htpr.responseText;
        alert(dt);
    }
 }
 htpr.send(val);
}

if(isset($_POST['pro_ID'])) {
    echo "Test";

}
echo "test wrong";
</code>```

UPDATED problem found!

I found the error, as I have the ajax function to be triggered inside a html form I believe the default refresh function from the form was refreshing the page before the ajax was executed, I now set the form to prevent its defaults functions "event.preventDefault()". and it seems to have fixed. really weird! never thought that would be a problem

答:
Under:

```<code>htpr.onreadystatechange = function(){
</code>```

add:

```<code>console.log(htpr);
</code>```

Maybe it will show you why answer does not pass 'code 200, state 4' test.

You can also check 'Network' tab in Firefox. When XHR returns code 4xx or 5xx in Chrome, it shows in console information about it. In Firefox there is no information about XHR request problems - you got to check it in Network (request with problems are red).

Body:
I have a HTTPRequest that does not run using firefox, it does run on google chrome as it returns the alerts I have written for test.

var htpr = new XMLHttpRequest();
  var url = "../something.php";
  var val = "pro_ID="+prod_id+"&quan="+quan;
  alert("test ajx");
  htpr.open("POST", url, true);
  htpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  htpr.onreadystatechange = function(){
    if(htpr.readyState == 4 && htpr.status == 200){
        var dt = htpr.responseText;
        alert(dt);
    }
 }
 htpr.send(val);
}

if(isset($_POST['pro_ID'])) {
    echo "Test";

}
echo "test wrong";

UPDATED problem found!

I found the error, as I have the ajax function to be triggered inside a html form I believe the default refresh function from the form was refreshing the page before the ajax was executed, I now set the form to prevent its defaults functions "event.preventDefault()". and it seems to have fixed. really weird! never thought that would be a problem

Body:
Under:

htpr.onreadystatechange = function(){

add:

console.log(htpr);

Maybe it will show you why answer does not pass 'code 200, state 4' test.

You can also check 'Network' tab in Firefox. When XHR returns code 4xx or 5xx in Chrome, it shows in console information about it. In Firefox there is no information about XHR request problems - you got to check it in Network (request with problems are red).


问:
Firebase "no such instance field" error
As the title says, I have encountered that error when I tried working with Firebase database. I have tried numerous solutions found online but nothing seems to have worked for me. Below you can find my code and also, a brief information regarding on what I've tried so far before posting on stackOverflow.

The code is the following:

```<code>package com.example.vlad.restaurantorder;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.vlad.restaurantorder.Model.User;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rengwuxian.materialedittext.MaterialEditText;

public class LogIn extends AppCompatActivity {
    EditText editPhone, editPassword;
    Button btnLogIn;
    FirebaseDatabase database;
    DatabaseReference tableUser;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_log_in);

    btnLogIn = (Button)findViewById(R.id.btnLogInScreenLogIn);
    editPhone = (MaterialEditText)findViewById(R.id.edtPhone);
    editPassword = (MaterialEditText)findViewById(R.id.edtPassword);

    //database
    database = FirebaseDatabase.getInstance();
    tableUser = database.getReference("User");

    btnLogIn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            final ProgressDialog progressDialog = new ProgressDialog(LogIn.this);
            progressDialog.setMessage("Please wait...");
            progressDialog.show();

            tableUser.addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    if(dataSnapshot.child(editPhone.getText().toString()).exists()){
                        progressDialog.dismiss();
                        User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
                        if(user.getPassword().equals(editPassword.getText().toString())){

                            Toast.makeText(getApplicationContext(), "You are logged in!", Toast.LENGTH_SHORT).show();
                        }
                        else{

                            Toast.makeText(getApplicationContext(), "Log in failed!", Toast.LENGTH_SHORT).show();
                        }
                    }
                    else {
                        progressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), "User does not exists!", Toast.LENGTH_SHORT).show();
                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    });

}
</code>```

}

What I have tried so far before posting here: Disabling proGuard and putting minifyEnable on false in build.gradle in debug{}; Restarting android studio, as I've read other people's posts who also encountered the problem said that this worked for them; On line where I used tableUser = database.getReference("User"); I also tried using tableUser = database.getReference().child("User");

Any help is much appreciated. Thank you very much

Later edit: adding the LogIn activity xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/login_screen_image"
tools:context="com.example.vlad.restaurantorder.LogIn">

<LinearLayout
    android:orientation="vertical"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_centerInParent="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.rengwuxian.materialedittext.MaterialEditText
        android:id="@+id/edtPhone"
        android:hint="Phone Number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="@android:color/white"
        android:text="0293292442"
        android:textColor="@android:color/white"
        android:textSize="34sp"
        android:inputType="phone"
        app:met_floatingLabel="highlight"
        app:met_baseColor="@android:color/white"
        app:met_maxCharacters="11"
        app:met_primaryColor="@android:color/white"
        app:met_singleLineEllipsis="true"
        />

    <com.rengwuxian.materialedittext.MaterialEditText
        android:id="@+id/edtPassword"
        android:hint="Password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="@android:color/white"
        android:text="5678"
        android:textColor="@android:color/white"
        android:textSize="34sp"
        android:inputType="textPassword"
        app:met_floatingLabel="highlight"
        app:met_baseColor="@android:color/white"
        app:met_maxCharacters="11"
        app:met_primaryColor="@android:color/white"
        app:met_singleLineEllipsis="true"
        />

</LinearLayout>

<info.hoang8f.widget.FButton
    android:id="@+id/btnLogInScreenLogIn"
    android:text="@string/LogIn"
    android:textColor="@android:color/white"
    android:layout_marginRight="8dp"
    android:layout_marginLeft="8dp"
    android:layout_alignParentBottom="true"
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:buttonColor="@color/btnLogIn"
    app:shadowColor="@android:color/black"
    app:shadowEnabled="true"
    app:shadowHeight="5dp"
    app:cornerRadius="4dp"
    />
</code>```

Later edit: LogCat image:

答:
It seems your code should work just fine if there is no other warning/error showing up. The missing instance error/message might only be because it takes some time to read the data from Firebase.

After adding the ValueEventListener, the app will take some time to "listen" to or read the data from Firebase. So, add some log messages to each of the if/else block as below, recompile and fire up the app, open the Logcat view in Android Studio and then click the button btnLogIn on the app screen. Then wait (make sure internet is available to the device/emulator and Firebase Database is connected).

In Logcat window, you should see the Log messages show up depending on the if/else block that was entered in onDataChange. E.g..... D/ANY_TAG: entered onDataChange

Code with debug lines:

```<code>tableUser.addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    Log.d("ANY_TAG", "entered onDataChange");
                    if(dataSnapshot.child(editPhone.getText().toString()).exists()){

                        Log.d("ANY_TAG", "entered onDataChange/childExists");
                        progressDialog.dismiss();
                        User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
                        if(user.getPassword().equals(editPassword.getText().toString())){

                            Log.d("ANY_TAG", "entered onDataChange/childExists/equalPassword");
                            Toast.makeText(getApplicationContext(), "You are logged in!", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            Log.d("ANY_TAG", "entered onDataChange/childExists/unEqualPasswords");
                            Toast.makeText(getApplicationContext(), "Log in failed!", Toast.LENGTH_SHORT).show();
                        }
                    }
                    else {
                        Log.d("ANY_TAG", "entered onDataChange/childDoesNotExist");
                        progressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), "User does not exists!", Toast.LENGTH_SHORT).show();
                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}
</code>```

Title: Firebase "no such instance field" error

Body:
As the title says, I have encountered that error when I tried working with Firebase database. I have tried numerous solutions found online but nothing seems to have worked for me. Below you can find my code and also, a brief information regarding on what I've tried so far before posting on stackOverflow.

The code is the following:

package com.example.vlad.restaurantorder;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.vlad.restaurantorder.Model.User;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rengwuxian.materialedittext.MaterialEditText;

public class LogIn extends AppCompatActivity {
    EditText editPhone, editPassword;
    Button btnLogIn;
    FirebaseDatabase database;
    DatabaseReference tableUser;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_log_in);

    btnLogIn = (Button)findViewById(R.id.btnLogInScreenLogIn);
    editPhone = (MaterialEditText)findViewById(R.id.edtPhone);
    editPassword = (MaterialEditText)findViewById(R.id.edtPassword);

    //database
    database = FirebaseDatabase.getInstance();
    tableUser = database.getReference("User");

    btnLogIn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            final ProgressDialog progressDialog = new ProgressDialog(LogIn.this);
            progressDialog.setMessage("Please wait...");
            progressDialog.show();

            tableUser.addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    if(dataSnapshot.child(editPhone.getText().toString()).exists()){
                        progressDialog.dismiss();
                        User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
                        if(user.getPassword().equals(editPassword.getText().toString())){

                            Toast.makeText(getApplicationContext(), "You are logged in!", Toast.LENGTH_SHORT).show();
                        }
                        else{

                            Toast.makeText(getApplicationContext(), "Log in failed!", Toast.LENGTH_SHORT).show();
                        }
                    }
                    else {
                        progressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), "User does not exists!", Toast.LENGTH_SHORT).show();
                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    });

}

}

What I have tried so far before posting here: Disabling proGuard and putting minifyEnable on false in build.gradle in debug{}; Restarting android studio, as I've read other people's posts who also encountered the problem said that this worked for them; On line where I used tableUser = database.getReference("User"); I also tried using tableUser = database.getReference().child("User");

Any help is much appreciated. Thank you very much

Later edit: adding the LogIn activity xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/login_screen_image"
tools:context="com.example.vlad.restaurantorder.LogIn">

<LinearLayout
    android:orientation="vertical"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_centerInParent="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.rengwuxian.materialedittext.MaterialEditText
        android:id="@+id/edtPhone"
        android:hint="Phone Number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="@android:color/white"
        android:text="0293292442"
        android:textColor="@android:color/white"
        android:textSize="34sp"
        android:inputType="phone"
        app:met_floatingLabel="highlight"
        app:met_baseColor="@android:color/white"
        app:met_maxCharacters="11"
        app:met_primaryColor="@android:color/white"
        app:met_singleLineEllipsis="true"
        />

    <com.rengwuxian.materialedittext.MaterialEditText
        android:id="@+id/edtPassword"
        android:hint="Password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="@android:color/white"
        android:text="5678"
        android:textColor="@android:color/white"
        android:textSize="34sp"
        android:inputType="textPassword"
        app:met_floatingLabel="highlight"
        app:met_baseColor="@android:color/white"
        app:met_maxCharacters="11"
        app:met_primaryColor="@android:color/white"
        app:met_singleLineEllipsis="true"
        />

</LinearLayout>

<info.hoang8f.widget.FButton
    android:id="@+id/btnLogInScreenLogIn"
    android:text="@string/LogIn"
    android:textColor="@android:color/white"
    android:layout_marginRight="8dp"
    android:layout_marginLeft="8dp"
    android:layout_alignParentBottom="true"
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:buttonColor="@color/btnLogIn"
    app:shadowColor="@android:color/black"
    app:shadowEnabled="true"
    app:shadowHeight="5dp"
    app:cornerRadius="4dp"
    />

Later edit: LogCat image:

Body:
It seems your code should work just fine if there is no other warning/error showing up. The missing instance error/message might only be because it takes some time to read the data from Firebase.

After adding the ValueEventListener, the app will take some time to "listen" to or read the data from Firebase. So, add some log messages to each of the if/else block as below, recompile and fire up the app, open the Logcat view in Android Studio and then click the button btnLogIn on the app screen. Then wait (make sure internet is available to the device/emulator and Firebase Database is connected).

In Logcat window, you should see the Log messages show up depending on the if/else block that was entered in onDataChange. E.g..... D/ANY_TAG: entered onDataChange

Code with debug lines:

tableUser.addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    Log.d("ANY_TAG", "entered onDataChange");
                    if(dataSnapshot.child(editPhone.getText().toString()).exists()){

                        Log.d("ANY_TAG", "entered onDataChange/childExists");
                        progressDialog.dismiss();
                        User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
                        if(user.getPassword().equals(editPassword.getText().toString())){

                            Log.d("ANY_TAG", "entered onDataChange/childExists/equalPassword");
                            Toast.makeText(getApplicationContext(), "You are logged in!", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            Log.d("ANY_TAG", "entered onDataChange/childExists/unEqualPasswords");
                            Toast.makeText(getApplicationContext(), "Log in failed!", Toast.LENGTH_SHORT).show();
                        }
                    }
                    else {
                        Log.d("ANY_TAG", "entered onDataChange/childDoesNotExist");
                        progressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), "User does not exists!", Toast.LENGTH_SHORT).show();
                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}


问:
How to draw dimensions between sleeve (specialty equipment) and Grid lines
we want to draw dimensions between sleeve (specialty equipment) and Grid lines .

but when we apply dimensions revit throw the error message "Remove References - The references of highlighted dimension are no longer parallel"

```<code>XYZ sleeve_xyz = null;
                    Element elm = doc.GetElement(Sleeve_id.Id);
                    FamilyInstance fi = elm as FamilyInstance;
                    Autodesk.Revit.DB.Location position = elm.Location;
                    Autodesk.Revit.DB.LocationPoint positionPoint = position as Autodesk.Revit.DB.LocationPoint;
                    sleeve_xyz = positionPoint.Point;
                    sleeve_xyz = new XYZ(sleeve_xyz.X, sleeve_xyz.Y, 0);
                    Reference sleeve_ref = GetSleeveReference(fi, SpecialReferenceType.CenterLR);
                    Grid first_grid2 = doc.GetElement(First_Grid_elemID) as Grid;
                    Reference gridRef = null;
                    Options opt = new Options();
                    opt.ComputeReferences = true;
                    opt.IncludeNonVisibleObjects = true;
                    opt.View = doc.ActiveView;
                    foreach (GeometryObject obj in first_grid2.get_Geometry(opt))
                    {
                        if (obj is Autodesk.Revit.DB.Line)
                        {
                            Autodesk.Revit.DB.Line line = obj as Autodesk.Revit.DB.Line;
                            gridRef = line.Reference;
                        }
                    }
                    XYZ gr_point2 = new XYZ(grid_intersection_point.X, sleeve_xyz.Y, 0.000000000);
                    Autodesk.Revit.DB.Line line5 = null;
                    line5 = Autodesk.Revit.DB.Line.CreateBound(gr_point2, sleeve_xyz);
                    ReferenceArray refArray = new ReferenceArray();
                    refArray.Append(sleeve_ref);
                    refArray.Append(gridRef);
                    Dimension dim = doc.Create.NewDimension(doc.ActiveView, line5, refArray);
</code>```

Error

答: Create a dimension that works manually through the user interface first, then use RevitLookup to analyse its properties and find out what exact references it has picked up. In general, if a feature is not available in the Revit product manually through the user interface, then the Revit API will not provide it either.</p>

Body:
we want to draw dimensions between sleeve (specialty equipment) and Grid lines .

but when we apply dimensions revit throw the error message "Remove References - The references of highlighted dimension are no longer parallel"

XYZ sleeve_xyz = null;
                    Element elm = doc.GetElement(Sleeve_id.Id);
                    FamilyInstance fi = elm as FamilyInstance;
                    Autodesk.Revit.DB.Location position = elm.Location;
                    Autodesk.Revit.DB.LocationPoint positionPoint = position as Autodesk.Revit.DB.LocationPoint;
                    sleeve_xyz = positionPoint.Point;
                    sleeve_xyz = new XYZ(sleeve_xyz.X, sleeve_xyz.Y, 0);
                    Reference sleeve_ref = GetSleeveReference(fi, SpecialReferenceType.CenterLR);
                    Grid first_grid2 = doc.GetElement(First_Grid_elemID) as Grid;
                    Reference gridRef = null;
                    Options opt = new Options();
                    opt.ComputeReferences = true;
                    opt.IncludeNonVisibleObjects = true;
                    opt.View = doc.ActiveView;
                    foreach (GeometryObject obj in first_grid2.get_Geometry(opt))
                    {
                        if (obj is Autodesk.Revit.DB.Line)
                        {
                            Autodesk.Revit.DB.Line line = obj as Autodesk.Revit.DB.Line;
                            gridRef = line.Reference;
                        }
                    }
                    XYZ gr_point2 = new XYZ(grid_intersection_point.X, sleeve_xyz.Y, 0.000000000);
                    Autodesk.Revit.DB.Line line5 = null;
                    line5 = Autodesk.Revit.DB.Line.CreateBound(gr_point2, sleeve_xyz);
                    ReferenceArray refArray = new ReferenceArray();
                    refArray.Append(sleeve_ref);
                    refArray.Append(gridRef);
                    Dimension dim = doc.Create.NewDimension(doc.ActiveView, line5, refArray);

Error


问:
Remote database connection in VB.net not working
I'm currently working on a MySQL connection in my VB.net app. I have a form which has the following code:

```<code>Imports System.Data
Imports System.Data.SqlClient

Public Class Form4
    Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    ConnectToSQL()
End Sub

Private Sub ConnectToSQL()
    Dim con As New SqlConnection
    Dim cmd As New SqlCommand
    Dim Password As String
    Dim Password2 As String
    Dim userName As String

    Try
        If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
            con.Open()

            cmd.Connection = con
            cmd.CommandText = "SELECT user_username, user_pass FROM users WHERE (user_username = '" & txtUsername.Text & "' ) AND (user_pass = '" & txtPassword.Text & "')"

            Dim lrd As SqlDataReader = cmd.ExecuteReader()
            If lrd.HasRows Then
                While lrd.Read()

                    Password = lrd("Password").ToString()
                    userName = lrd("UserName").ToString()

                    Password2 = txtPassword.Text()

                    If Password = Password2 And userName = txtUsername.Text Then

                        MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
                                        )
                        Form2.Show()
                        Me.Hide()

                        txtPassword.Text = ""
                        txtUsername.Text = ""

                    End If

                End While

            Else
                MessageBox.Show("Username or Password incorrect...", "Authentication Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtPassword.Text = ""
                txtUsername.Text = ""
            End If

        End If

    Catch ex As Exception
        MessageBox.Show("Error while connecting to SQL Server." & ex.Message)

    Finally
        con.Close()
    End Try
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.Close()
End Sub
End Class
</code>```

Everytime I run the application, I enter the login details correctly and click on the sign in button (Button2). The problem is, it doesn't do anything. It doesn't throw an exception, doesn't even try to login to the server as far as I can tell. I replaced the login details with that of my own server, so that's not the problem. Did I miss something?

答:
Don't store passwords in clear-text!

 Furthermore your code is prone to sql incjection.

Nothing happens because this If will never be true:

```<code>...
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
...
</code>```

Body:
I'm currently working on a MySQL connection in my VB.net app. I have a form which has the following code:

Imports System.Data
Imports System.Data.SqlClient

Public Class Form4
    Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    ConnectToSQL()
End Sub

Private Sub ConnectToSQL()
    Dim con As New SqlConnection
    Dim cmd As New SqlCommand
    Dim Password As String
    Dim Password2 As String
    Dim userName As String

    Try
        If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
            con.Open()

            cmd.Connection = con
            cmd.CommandText = "SELECT user_username, user_pass FROM users WHERE (user_username = '" & txtUsername.Text & "' ) AND (user_pass = '" & txtPassword.Text & "')"

            Dim lrd As SqlDataReader = cmd.ExecuteReader()
            If lrd.HasRows Then
                While lrd.Read()

                    Password = lrd("Password").ToString()
                    userName = lrd("UserName").ToString()

                    Password2 = txtPassword.Text()

                    If Password = Password2 And userName = txtUsername.Text Then

                        MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
                                        )
                        Form2.Show()
                        Me.Hide()

                        txtPassword.Text = ""
                        txtUsername.Text = ""

                    End If

                End While

            Else
                MessageBox.Show("Username or Password incorrect...", "Authentication Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                txtPassword.Text = ""
                txtUsername.Text = ""
            End If

        End If

    Catch ex As Exception
        MessageBox.Show("Error while connecting to SQL Server." & ex.Message)

    Finally
        con.Close()
    End Try
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.Close()
End Sub
End Class

Everytime I run the application, I enter the login details correctly and click on the sign in button (Button2). The problem is, it doesn't do anything. It doesn't throw an exception, doesn't even try to login to the server as far as I can tell. I replaced the login details with that of my own server, so that's not the problem. Did I miss something?

Body:
Don't store passwords in clear-text!

 Furthermore your code is prone to sql incjection.

Nothing happens because this If will never be true:

...
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
...


问:
Why Room entities don't work with immutable properties in Android
I have been exploring Room database object mapping library and I figured something weird.

An entity data model cannot have immutable properties, as this answer suggests.

But I checked out google's persistent example with kotlin, Room works with immutable properties too. Please check this data class from the example.

What could be the reason for this behavior?

This could be a good feature if we could create immutable values (val properties), as this restrict programmers from changing unique identifiers such as ids after an object has been created.

答:
It's weird because I can make my Entity class using val for all of my fields without an issue

```<code>@Entity(tableName = "repo")
data class RepoEntity(
        @PrimaryKey @ColumnInfo(name = "id") @SerializedName("id") val id: Int,
        @ColumnInfo(name = "name") @SerializedName("name") val name: String,
        @ColumnInfo(name = "full_name") @SerializedName("full_name") val fullName: String,
        @Embedded(prefix = "owner") @SerializedName("owner") val owner: RepoOwnerEntity,
        @ColumnInfo(name = "html_url") @SerializedName("html_url") val htmlUrl: String,
        @ColumnInfo(name = "description") @SerializedName("description") val description: String?
)
</code>```

And the data still stored correctly inside the Database.

Body:
It's weird because I can make my Entity class using val for all of my fields without an issue

@Entity(tableName = "repo")
data class RepoEntity(
        @PrimaryKey @ColumnInfo(name = "id") @SerializedName("id") val id: Int,
        @ColumnInfo(name = "name") @SerializedName("name") val name: String,
        @ColumnInfo(name = "full_name") @SerializedName("full_name") val fullName: String,
        @Embedded(prefix = "owner") @SerializedName("owner") val owner: RepoOwnerEntity,
        @ColumnInfo(name = "html_url") @SerializedName("html_url") val htmlUrl: String,
        @ColumnInfo(name = "description") @SerializedName("description") val description: String?
)

And the data still stored correctly inside the Database.


问:
Cannot find org.apache.hadoop.hbase.mapreduce and mapred packages in hbase 1.2.6
I am trying to upgrade an existing project's hbase version which was previously 0.94.1 annd now I will upgrade to 1.2.6. In the official website I can see some packages and classes such as mapreduce and mapred, but they are not available in the jars that I found. I have found hbase-common hbase-annotations and hbase-client jars. However these jars does not includes all the classes in the API. Where can I find them?

Regards

答:
You can usually work this sort of stuff out by looking at the source. Going through the different releases, you can see the following:

0.94.1 - https://github.com/apache/hbase/tree/2fd647d99e4aae7da71cebb9efd017eebfe0e4fb

Everything in hbase was combined in a single package.

1.2.6 - https://github.com/apache/hbase/tree/2f9b9e17d0522e36063bf52ecc58576243d20b3f

The code has been split into numerous packages. In this version the mapred and mapreduce code has been moved into hbase-server [See here].


问:
What's the simplest way to convert a String Array to an int Array using Java 8?
I'm currently learning how to use Java and my friend told me that this block of code can be simplified when using Java 8. He pointed out that the parseIntArray could be simplified. How would you do this in Java 8?

```<code>public class Solution {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String[] tokens = input.nextLine().split(" ");
        int[] ints = parseIntArray(tokens);
    }

    static int[] parseIntArray(String[] arr) {
        int[] ints = new int[arr.length];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = Integer.parseInt(arr[i]);
        }
        return ints;
    }
}
</code>```

答:
You could, also, obtain the array directly from a split:

```<code>String input; //Obtained somewhere
...
int[] result = Arrays.stream(input.split(" "))
        .mapToInt(Integer::valueOf)
        .toArray();
</code>```

Here, Arrays has some nice methods to obtain the stream from an array, so you can split it directly in the call. After that, call mapToInt with Integer::valueOf to obtain the IntStream and toArray for your desired int array.

Body:
I'm currently learning how to use Java and my friend told me that this block of code can be simplified when using Java 8. He pointed out that the parseIntArray could be simplified. How would you do this in Java 8?

public class Solution {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String[] tokens = input.nextLine().split(" ");
        int[] ints = parseIntArray(tokens);
    }

    static int[] parseIntArray(String[] arr) {
        int[] ints = new int[arr.length];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = Integer.parseInt(arr[i]);
        }
        return ints;
    }
}

Body:
You could, also, obtain the array directly from a split:

String input; //Obtained somewhere
...
int[] result = Arrays.stream(input.split(" "))
        .mapToInt(Integer::valueOf)
        .toArray();

Here, Arrays has some nice methods to obtain the stream from an array, so you can split it directly in the call. After that, call mapToInt with Integer::valueOf to obtain the IntStream and toArray for your desired int array.


问:
How can I optimized multiple youtube?
My page has several youtube player, it caused the page loading slowly.
This is my code↓

```<code>var tag = document.createElement('script');

tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('player1', {
      height: '100%',
      width: '100%',
      videoId: 'mCx3oxXBmGA'
    });

player2 = new YT.Player('player2', {
  height: '100%',
  width: '100%',
  videoId: 'SpWR0sSEgMc'
});
</code>```

the HTML↓

```<code><div id="player6"></div>
</code>```

There are 12 video in this page, how can I optimized it?

答:
Do not embed all 12 players at once. Instead present some cover image of the YouTube movie (static img) and bind click event on it.

When user will click specific image, remove it from the DOM and create player instead of it.

Title: How can I optimized multiple youtube?

Body:
My page has several youtube player, it caused the page loading slowly.
This is my code↓

var tag = document.createElement('script');

tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('player1', {
      height: '100%',
      width: '100%',
      videoId: 'mCx3oxXBmGA'
    });

player2 = new YT.Player('player2', {
  height: '100%',
  width: '100%',
  videoId: 'SpWR0sSEgMc'
});

the HTML↓

There are 12 video in this page, how can I optimized it?


问:
Pandas: how to identify columns with dtype object but mixed-type items?
In a pandas dataframe, a column with dtype = object can, in fact, contain items of mixed types, eg integers and strings.

In this example, column a is dtype object, but the first item is string while all the others are int:

```<code>import numpy as np, pandas as pd
df=pd.DataFrame()
df['a']=np.arange(0,9)
df.iloc[0,0]='test'
print(df.dtypes)
print(type(df.iloc[0,0]))
print(type(df.iloc[1,0]))
</code>```

My question is: is there a quick way to identify which columns with dtype=object contain, in fact, mixed types like above? Since pandas does not have a dtype = str, this is not immediately apparent.

However, I have had situations where, importing a large csv file into pandas, I would get a warning like:

```<code>sys:1: DtypeWarning: Columns (15,16) have mixed types. Specify dtype option on import or set low_memory=False
</code>```

Is there an easy way to replicate that and explicitly list the columns with mixed types? Or do I manually have to go through them one by one, see if I can convert them to string, etc?

The background is that I am trying to export a dataframe to a Microsoft SQL Server using DataFrame.to_sql and SQLAlchemy. I get an

```<code>OverflowError: int too big to convert
</code>```

but my dataframe does not contain columns with dtype int - only object and float64. I'm guessing this is because one of the object columns must have both strings and integers.

答:
Setup

```<code>df = pd.DataFrame(np.ones((3, 3)), columns=list('WXY')).assign(Z='c')
df.iloc[0, 0] = 'a'
df.iloc[1, 2] = 'b'

df

   W    X  Y  Z
0  a  1.0  1  c
1  1  1.0  b  c
2  1  1.0  1  c
</code>```

Solution

Find all types and count how many unique ones per column.

```<code>df.loc[:, df.applymap(type).nunique().gt(1)]

   W  Y
0  a  1
1  1  b
2  1  1
</code>```

Body:
In a pandas dataframe, a column with dtype = object can, in fact, contain items of mixed types, eg integers and strings.

In this example, column a is dtype object, but the first item is string while all the others are int:

import numpy as np, pandas as pd
df=pd.DataFrame()
df['a']=np.arange(0,9)
df.iloc[0,0]='test'
print(df.dtypes)
print(type(df.iloc[0,0]))
print(type(df.iloc[1,0]))

My question is: is there a quick way to identify which columns with dtype=object contain, in fact, mixed types like above? Since pandas does not have a dtype = str, this is not immediately apparent.

However, I have had situations where, importing a large csv file into pandas, I would get a warning like:

sys:1: DtypeWarning: Columns (15,16) have mixed types. Specify dtype option on import or set low_memory=False

Is there an easy way to replicate that and explicitly list the columns with mixed types? Or do I manually have to go through them one by one, see if I can convert them to string, etc?

The background is that I am trying to export a dataframe to a Microsoft SQL Server using DataFrame.to_sql and SQLAlchemy. I get an

OverflowError: int too big to convert

but my dataframe does not contain columns with dtype int - only object and float64. I'm guessing this is because one of the object columns must have both strings and integers.

Body:
Setup

df = pd.DataFrame(np.ones((3, 3)), columns=list('WXY')).assign(Z='c')
df.iloc[0, 0] = 'a'
df.iloc[1, 2] = 'b'

df

   W    X  Y  Z
0  a  1.0  1  c
1  1  1.0  b  c
2  1  1.0  1  c

Solution

Find all types and count how many unique ones per column.

df.loc[:, df.applymap(type).nunique().gt(1)]

   W  Y
0  a  1
1  1  b
2  1  1


问:
Starting tomcat from within Java
I am trying to start tomcat from within a simple java snippet but it is failing. I looked at the other questions and duplicated their answers but none worked.

What I'm doing is executing a command through the Runtime:

```<code>Process process = Runtime.getRuntime().exec("startup.bat");
</code>```

Please note that the command is simplified, I normally provide a fully qualified path, environment variables for CATALINA_HOME and some CATALINA_OPTS and made sure the system env variables are available.

What happens is that the process starts normally, but when it spawns the console it is immediately closed, as if Java itself kills it. I tried adding Thread.sleep(x) to the main thread to see if keeping the application alive would let tomcat run but it didn't, the console still died even though the Java app kept running.

I even tried running Tomcat through an Ant script to see if delegating to Ant would work but again to no avail. Even trying through a third party .bat file didn't work

Please do not suggest Cargo, Maven or similar tools, I'm looking for a programmatic solution at the moment.

答:
The problem was with how I was running the cmd script. The correct way is:</p>

```<code>Runtime.getRuntime.exec("start /wait cmd /c catalina.bat run");
</code>```

Title: Starting tomcat from within Java

Body:
I am trying to start tomcat from within a simple java snippet but it is failing. I looked at the other questions and duplicated their answers but none worked.

What I'm doing is executing a command through the Runtime:

Process process = Runtime.getRuntime().exec("startup.bat");

Please note that the command is simplified, I normally provide a fully qualified path, environment variables for CATALINA_HOME and some CATALINA_OPTS and made sure the system env variables are available.

What happens is that the process starts normally, but when it spawns the console it is immediately closed, as if Java itself kills it. I tried adding Thread.sleep(x) to the main thread to see if keeping the application alive would let tomcat run but it didn't, the console still died even though the Java app kept running.

I even tried running Tomcat through an Ant script to see if delegating to Ant would work but again to no avail. Even trying through a third party .bat file didn't work

Please do not suggest Cargo, Maven or similar tools, I'm looking for a programmatic solution at the moment.

Body:
The problem was with how I was running the cmd script. The correct way is:

Runtime.getRuntime.exec("start /wait cmd /c catalina.bat run");