问:
Wrong player is edited
I am trying to insert players into my database. If a player in a team has the same "Rugnummer" as the player that is being inserted, the player's "Rugnummer" that is being inserted should be changed. Instead the code I have know changes the "Rugnummer" of the player that already exists in the table. Running the INSERT again causes the new player to be inserted with the "Rugnummer" the already existing player had.

I have tried a couple of different things, different pieces of code and changing some things, but nothing seems to be wokring, at all, after changing some things up.

I also tried using triggers, but with an insert OLD.Rugnummer can't be used.

```<code>INSERT INTO spelers (Speler_voornaam, Speler_achternaam, Team_ID, Rugnummer)
VALUES ("Bram", "Bakker", 1, 28)

ON DUPLICATE KEY UPDATE Rugnummer =
(select (t*10+u+1) x from (select 0 t union select 1 union select 2 union select 3 union select 4) A,
(select 0 u union select 1 union select 2 union select 3 union select 4 union
select 5 union select 6 union select 7 union select 8 union select 9) B
WHERE (t*10+u+1) NOT IN (SELECT Rugnummer
FROM spelers AS s
WHERE Team_ID = 1)
ORDER BY x
LIMIT 1
</code>```

The Following is an insert I tried. I expect number 1 through 10 and letter A till J. What actually is shown is A-A with the "Rugnummer" 12 and J-J is not shown. A-A is changed instead of J-J (These have the same "Rugnummer)

```<code>INSERT INTO spelers (Speler_voornaam, Speler_achternaam, Team_ID, Rugnummer)
VALUES

("A", "A", 19, 1),
("B", "B", 19, 2),
("C", "C", 19, 3),
("D", "D", 19, 4),
("E", "E", 19, 5),
("F", "F", 19, 6),
("G", "G", 19, 7),
("H", "H", 19, 8),
("I", "I", 19, 9),
("J", "J", 19, 1)

ON DUPLICATE KEY UPDATE Rugnummer =
(select (t*10+u+1) x from (select 0 t union select 1 union select 2 union select 3 union select 4) A,
(select 0 u union select 1 union select 2 union select 3 union select 4 union
select 5 union select 6 union select 7 union select 8 union select 9) B
WHERE (t*10+u+1) NOT IN (SELECT Rugnummer
FROM spelers AS s
WHERE Team_ID = 19)
ORDER BY x
LIMIT 1)
</code>```

The expected result is that the new player is inserted with a not yet used "Rugnummer" instead of needing to use the insert statement twice and changing the "Rugnummer" of the already existing player.

答:
I think you would be better served using a function like:

```<code>    CREATE FUNCTION GetRugnummer (Rugnummer INT, Team INT) RETURNS INT
    BEGIN

      /*CODE if Rugnummer doesn't exist return Rugnummer

Otherwise search for minimum available number (see query below)*/

    END $$
</code>```

Regardless of that for the query to find the minimum available number I would create a table with just one column that contains all the possible numbers.

Then you can just do a left join:

```<code>SELECT MIN(r.num) FROM RugNummers r
LEFT JOIN spelers s ON r.num=s.Rugnummer AND s.Team_ID=@Team
WHERE s.Rugnummer IS NULL;
</code>```

This way in the future (in case you want to have more player numbers) you just have to add rows to the table.

If you decide to use the function then you would use it on the INSERT statement like:

```<code>INSERT INTO spelers (Speler_voornaam, Speler_achternaam, Team_ID, Rugnummer)
VALUES ("A", "A", 19, GetRugnummer(1, 19))
</code>```

I think it would be much better than using DUPLICATE KEY

Title: Wrong player is edited

Body:
I am trying to insert players into my database. If a player in a team has the same "Rugnummer" as the player that is being inserted, the player's "Rugnummer" that is being inserted should be changed. Instead the code I have know changes the "Rugnummer" of the player that already exists in the table. Running the INSERT again causes the new player to be inserted with the "Rugnummer" the already existing player had.

I have tried a couple of different things, different pieces of code and changing some things, but nothing seems to be wokring, at all, after changing some things up.

I also tried using triggers, but with an insert OLD.Rugnummer can't be used.

INSERT INTO spelers (Speler_voornaam, Speler_achternaam, Team_ID, Rugnummer)
VALUES ("Bram", "Bakker", 1, 28)

ON DUPLICATE KEY UPDATE Rugnummer =
(select (t*10+u+1) x from (select 0 t union select 1 union select 2 union select 3 union select 4) A,
(select 0 u union select 1 union select 2 union select 3 union select 4 union
select 5 union select 6 union select 7 union select 8 union select 9) B
WHERE (t*10+u+1) NOT IN (SELECT Rugnummer
FROM spelers AS s
WHERE Team_ID = 1)
ORDER BY x
LIMIT 1

The Following is an insert I tried. I expect number 1 through 10 and letter A till J. What actually is shown is A-A with the "Rugnummer" 12 and J-J is not shown. A-A is changed instead of J-J (These have the same "Rugnummer)

INSERT INTO spelers (Speler_voornaam, Speler_achternaam, Team_ID, Rugnummer)
VALUES

("A", "A", 19, 1),
("B", "B", 19, 2),
("C", "C", 19, 3),
("D", "D", 19, 4),
("E", "E", 19, 5),
("F", "F", 19, 6),
("G", "G", 19, 7),
("H", "H", 19, 8),
("I", "I", 19, 9),
("J", "J", 19, 1)

ON DUPLICATE KEY UPDATE Rugnummer =
(select (t*10+u+1) x from (select 0 t union select 1 union select 2 union select 3 union select 4) A,
(select 0 u union select 1 union select 2 union select 3 union select 4 union
select 5 union select 6 union select 7 union select 8 union select 9) B
WHERE (t*10+u+1) NOT IN (SELECT Rugnummer
FROM spelers AS s
WHERE Team_ID = 19)
ORDER BY x
LIMIT 1)

The expected result is that the new player is inserted with a not yet used "Rugnummer" instead of needing to use the insert statement twice and changing the "Rugnummer" of the already existing player.

Body:
I think you would be better served using a function like:

    CREATE FUNCTION GetRugnummer (Rugnummer INT, Team INT) RETURNS INT
    BEGIN

      /*CODE if Rugnummer doesn't exist return Rugnummer

Otherwise search for minimum available number (see query below)*/

    END $$

Regardless of that for the query to find the minimum available number I would create a table with just one column that contains all the possible numbers.

Then you can just do a left join:

SELECT MIN(r.num) FROM RugNummers r
LEFT JOIN spelers s ON r.num=s.Rugnummer AND s.Team_ID=@Team
WHERE s.Rugnummer IS NULL;

This way in the future (in case you want to have more player numbers) you just have to add rows to the table.

If you decide to use the function then you would use it on the INSERT statement like:

INSERT INTO spelers (Speler_voornaam, Speler_achternaam, Team_ID, Rugnummer)
VALUES ("A", "A", 19, GetRugnummer(1, 19))

I think it would be much better than using DUPLICATE KEY


来源: stackexchange

问:
JavaScript: The function listener called by this event listener is not as expected
Although it is somewhat simplistic, when you execute the following code, this points to the document and you can not get an instance of Hoge.

If you make variables and functions global, there is no meaning defined in the closure, and is there any better way?

```<code>var Hoge = function() {
    this.hogehoge = 'hogehoge';
    document.addEventListener('mousedown', this.change, false);
};

Hoge.prototype = {
    change: function(e) {
        e.pageX
        console.log(this.hogehoge); // undefined
    }
};

let hoge = new Hoge();
</code>```

I expect the output of console.log to be 'hogehoge', but the actual output is undefined.

答:
You are calling this.change in outer context, you need to bind this like this.change.bind(this) to make this context remain the same as you have while clicking.

var Hoge = function() {
    this.hogehoge = 'hogehoge';
    document.addEventListener('mousedown', this.change.bind(this), false);
};

Hoge.prototype = {
    change: function(e) {
        e.pageX;
        console.log(this.hogehoge); // undefined
    }
};

let hoge = new Hoge();```

For more information, Read how this gets its context here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

ContentLicense: CC BY-SA 4.0

Body:
Although it is somewhat simplistic, when you execute the following code, this points to the document and you can not get an instance of Hoge.

If you make variables and functions global, there is no meaning defined in the closure, and is there any better way?

var Hoge = function() {
    this.hogehoge = 'hogehoge';
    document.addEventListener('mousedown', this.change, false);
};

Hoge.prototype = {
    change: function(e) {
        e.pageX
        console.log(this.hogehoge); // undefined
    }
};

let hoge = new Hoge();

I expect the output of console.log to be 'hogehoge', but the actual output is undefined.

Body:
You are calling this.change in outer context, you need to bind this like this.change.bind(this) to make this context remain the same as you have while clicking.

var Hoge = function() {
    this.hogehoge = 'hogehoge';
    document.addEventListener('mousedown', this.change.bind(this), false);
};

Hoge.prototype = {
    change: function(e) {
        e.pageX;
        console.log(this.hogehoge); // undefined
    }
};

let hoge = new Hoge();

For more information, Read how this gets its context here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this


问:
How to reload the components in Vaadin after click internationalization Button?
I use Internationalization I18N in Vaadin. I have a Internationalization class with the method getText.

```<code>public static String getText(String key) {
        String returnValue = "";
        String value = "";
        String space = " ";
        Locale locale = new Locale("de", "DE");
        try {
            // session specific locale stored in attribute "locale"
            // if you want add a new language then add a new else if with the
            // new Locale like ("fr", "FR").
            if (VaadinServletService.getCurrentRequest() != null) {
                if ((Locale) VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale") != null) {
                    if (VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale").toString().equals("en_EN")) {
                        locale = new Locale("en", "US");
                    } else if (VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale").toString().equals("de_DE")) {
                        locale = new Locale("de", "DE");
                    }
                }
            }
            ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale);
            value = bundle.getString(key);
            returnValue = new String(value.getBytes("ISO-8859-1"), "UTF-8");
        } catch (MissingResourceException e) {
            // Missing key
            try {
                // return the Key
                String keyString = key.replace("_", space);
                returnValue = new String(keyString.getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnValue + space;
    }
</code>```

I can call this Method from everywhere to use this getText() method.
My Components they get a internationalization text by call this method like this:
label.setCaption(Internationalization.getText("Willkommen"));

I have now two Buttons "DE" and "EN" for the languages german and english. In the ClickListener of this Buttons i set the new Locale like this:

```<code>    btnLanguageDE.addClickListener(e -> {
VaadinServletService.getCurrentServletRequest().getSession().setAttribute("locale", new Locale("de", "DE"));
        });
</code>```

```<code>btnLanguageEN.addClickListener(e -> {
VaadinServletService.getCurrentServletRequest().getSession().setAttribute("locale", new Locale("en", "EN"));
logger.debug("Internationalization change to: EN");
        });
</code>```

The Problem is, if i click on the Button they set the local but didn't reload the components on the page. It changes only if i reload the page manually.
I tried to call this UI.getCurrent().getPage().getLocation(); but no effects.

How can i reload the components with the actual locale ?

答:
There is a good documentation about internationlization / localization with vaadin.

First up, you seem to have implemented your own logic how you can access translated labels with your Internationalization class.

Vaadin has already implemented this; you can let your Internationalization class implement I18NProvider (and annotate it with @Component if you're using Spring. If not, you need to register it somehow I think the linked docs explain how) and change your methodname from getText to getTranslation. Every Vaadin Component (therefore in every view, since view classes must extend a component) can call getTranslation(keyString); where the I18NProvider is fetched and used.

All this is optional since you already made similar implementations yourself. But doing it like this would be best practice.

Now to your actual question - You need to let every view that has a translateable string implements LocaleChangeObserver. This forces the view to implement the method localeChange(LocaleChangeEvent event) which is called automatically when the locale of the UI is changed.
in the localeChange method, you can set all the texts anew that are translated.

There is no need for refreshing the page!

```<code>public void localeChange(LocaleChangeEvent event){
    label.setCaption(getTranslation("Willkommen"));
}
</code>```

You can change the Locale of the UI like this:

```<code>UI.getCurrent().setLocale(myNewLocale);
</code>```

I have shared the code for my Language Selection in another StackOverflow post - I think you will find the example code relevant, as my Select component has a valueChangeListener that sets a new Locale - which directly triggers localeChange.

Body:
I use Internationalization I18N in Vaadin. I have a Internationalization class with the method getText.

public static String getText(String key) {
        String returnValue = "";
        String value = "";
        String space = " ";
        Locale locale = new Locale("de", "DE");
        try {
            // session specific locale stored in attribute "locale"
            // if you want add a new language then add a new else if with the
            // new Locale like ("fr", "FR").
            if (VaadinServletService.getCurrentRequest() != null) {
                if ((Locale) VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale") != null) {
                    if (VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale").toString().equals("en_EN")) {
                        locale = new Locale("en", "US");
                    } else if (VaadinServletService.getCurrentServletRequest().getSession().getAttribute("locale").toString().equals("de_DE")) {
                        locale = new Locale("de", "DE");
                    }
                }
            }
            ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale);
            value = bundle.getString(key);
            returnValue = new String(value.getBytes("ISO-8859-1"), "UTF-8");
        } catch (MissingResourceException e) {
            // Missing key
            try {
                // return the Key
                String keyString = key.replace("_", space);
                returnValue = new String(keyString.getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnValue + space;
    }

I can call this Method from everywhere to use this getText() method.
My Components they get a internationalization text by call this method like this:
label.setCaption(Internationalization.getText("Willkommen"));

I have now two Buttons "DE" and "EN" for the languages german and english. In the ClickListener of this Buttons i set the new Locale like this:

    btnLanguageDE.addClickListener(e -> {
VaadinServletService.getCurrentServletRequest().getSession().setAttribute("locale", new Locale("de", "DE"));
        });

btnLanguageEN.addClickListener(e -> {
VaadinServletService.getCurrentServletRequest().getSession().setAttribute("locale", new Locale("en", "EN"));
logger.debug("Internationalization change to: EN");
        });

The Problem is, if i click on the Button they set the local but didn't reload the components on the page. It changes only if i reload the page manually.
I tried to call this UI.getCurrent().getPage().getLocation(); but no effects.

How can i reload the components with the actual locale ?

Body:
There is a good documentation about internationlization / localization with vaadin.

First up, you seem to have implemented your own logic how you can access translated labels with your Internationalization class.

Vaadin has already implemented this; you can let your Internationalization class implement I18NProvider (and annotate it with @Component if you're using Spring. If not, you need to register it somehow I think the linked docs explain how) and change your methodname from getText to getTranslation. Every Vaadin Component (therefore in every view, since view classes must extend a component) can call getTranslation(keyString); where the I18NProvider is fetched and used.

All this is optional since you already made similar implementations yourself. But doing it like this would be best practice.

Now to your actual question - You need to let every view that has a translateable string implements LocaleChangeObserver. This forces the view to implement the method localeChange(LocaleChangeEvent event) which is called automatically when the locale of the UI is changed.
in the localeChange method, you can set all the texts anew that are translated.

There is no need for refreshing the page!

public void localeChange(LocaleChangeEvent event){
    label.setCaption(getTranslation("Willkommen"));
}

You can change the Locale of the UI like this:

UI.getCurrent().setLocale(myNewLocale);

I have shared the code for my Language Selection in another StackOverflow post - I think you will find the example code relevant, as my Select component has a valueChangeListener that sets a new Locale - which directly triggers localeChange.


问:
How to fix error - end of central directory record signature not found?
First, I split the video into frames with ffmpeg (on the Converter server, Windows), after that I create an archive that I need to transfer to another server (Generator server, Linux), where the archive with video and/or image, frames, and the data.json file should be unzipped, and the contents of the archive should be used further.

For unzipping, I took the extract-zip library (based on yauzl) and used promisify from the util module.

The problem is that when I send an image to the Converter for processing, everything works as it should; however, when I send a video, I get this error - 'end of central directory record signature not found'.

It seems to me that the problem is related to asynchrony or the event-loop.

I tried not to use promisify, but then I have the following problem - at the moment when I need to use data from the archive, this archive does not yet exist ('folder do not exist');

Tried some more libraries for unarchiving adamzip, unzip, decompress, node-zip;

I tried to make a chain of promises;

```<code>...
const fs = require('fs-extra')
const path = require('path')
cosnt util = require('util')
const extractZip = util.promisify(require('extract-zip'))
...

...
/**
* Factory that creates a project based on the archive.
* @param {string} archive Path to the source archive
* @returns {Promise.<Project>}
*/
static async create (archive) {
  const dir = fs.mkdtempSync(path.join(this.baseDir, '/'))
  await extractZip(archive, { dir })
  const data = await fs.readJson(path.join(dir, 'data.json'))
  return new this(data, dir)
}
...

/* Tried to do this w/ chaining promises:

static async create (archive) {
  const dir = fs.mkdtempSync(path.join(this.baseDir, '/'))
  await extractZip(archive, { dir })
   .then( async () => {
    const data = await fs.readJson(path.join(dir, 'data.json'))
    return data
   })
   .then( async (data) => {
    return new this(data, dir)
   })
}

*/

</code>```

答:
I solved the problem. It turned out that I had been downloading a large archive from the server asynchronously, so correcting this moment, everything worked as it should.

```<code>Wrong:
fs.writeFile(...)
Correct:
fs.writeFileSync(...)
</code>```

Conclusion: faced with a similar problem - you should go through the entire chain of data transfer and functions/call stack that is involved in it.

Body:
First, I split the video into frames with ffmpeg (on the Converter server, Windows), after that I create an archive that I need to transfer to another server (Generator server, Linux), where the archive with video and/or image, frames, and the data.json file should be unzipped, and the contents of the archive should be used further.

For unzipping, I took the extract-zip library (based on yauzl) and used promisify from the util module.

The problem is that when I send an image to the Converter for processing, everything works as it should; however, when I send a video, I get this error - 'end of central directory record signature not found'.

It seems to me that the problem is related to asynchrony or the event-loop.

I tried not to use promisify, but then I have the following problem - at the moment when I need to use data from the archive, this archive does not yet exist ('folder do not exist');

Tried some more libraries for unarchiving adamzip, unzip, decompress, node-zip;

I tried to make a chain of promises;

...
const fs = require('fs-extra')
const path = require('path')
cosnt util = require('util')
const extractZip = util.promisify(require('extract-zip'))
...

...
/**
* Factory that creates a project based on the archive.
* @param {string} archive Path to the source archive
* @returns {Promise.<Project>}
*/
static async create (archive) {
  const dir = fs.mkdtempSync(path.join(this.baseDir, '/'))
  await extractZip(archive, { dir })
  const data = await fs.readJson(path.join(dir, 'data.json'))
  return new this(data, dir)
}
...

/* Tried to do this w/ chaining promises:

static async create (archive) {
  const dir = fs.mkdtempSync(path.join(this.baseDir, '/'))
  await extractZip(archive, { dir })
   .then( async () => {
    const data = await fs.readJson(path.join(dir, 'data.json'))
    return data
   })
   .then( async (data) => {
    return new this(data, dir)
   })
}

*/

Body:
I solved the problem. It turned out that I had been downloading a large archive from the server asynchronously, so correcting this moment, everything worked as it should.

Wrong:
fs.writeFile(...)
Correct:
fs.writeFileSync(...)

Conclusion: faced with a similar problem - you should go through the entire chain of data transfer and functions/call stack that is involved in it.


问:
ENOENT, no such file or directory on fs.mkdirSync
I'm currently starting up my NodeJS application and I have the following if-statement:

```<code>Error: ENOENT, no such file or directory './realworks/objects/'
    at Object.fs.mkdirSync (fs.js:654:18)
    at Object.module.exports.StartScript (/home/nodeusr/huizenier.nl/realworks.js:294:7)
</code>```

The weird thing, however, is that the folder exists already, but the check fails on the following snippet:

```<code>if(fs.existsSync(objectPath)) {
    var existingObjects = fs.readdirSync(objectPath);
    existingObjects.forEach(function (objectFile) {
        var object = JSON.parse(fs.readFileSync(objectPath+objectFile));
        actualObjects[object.ObjectCode] = object;
    });
}else{
    fs.mkdirSync(objectPath); // << this is line 294
}
</code>```

I fail to understand how a no such file or directory can occur on CREATING a directory.

答: When you are using fs.mkdir or fs.mkdirSync, while passing the path like folder1/folder2/folder3, folder1 and folder2 must exist otherwise you will get the above error.

ContentLicense: CC BY-SA 3.0

Body:
I'm currently starting up my NodeJS application and I have the following if-statement:

Error: ENOENT, no such file or directory './realworks/objects/'
    at Object.fs.mkdirSync (fs.js:654:18)
    at Object.module.exports.StartScript (/home/nodeusr/huizenier.nl/realworks.js:294:7)

The weird thing, however, is that the folder exists already, but the check fails on the following snippet:

if(fs.existsSync(objectPath)) {
    var existingObjects = fs.readdirSync(objectPath);
    existingObjects.forEach(function (objectFile) {
        var object = JSON.parse(fs.readFileSync(objectPath+objectFile));
        actualObjects[object.ObjectCode] = object;
    });
}else{
    fs.mkdirSync(objectPath); // << this is line 294
}

I fail to understand how a no such file or directory can occur on CREATING a directory.


问:
Unable to get proper GET response
I am trying to implement a GET and a POST method in spring-boot. While calling GET method not getting proper response.

My Controller class

```<code>@RestController
@RequestMapping("api/public")
public class PublicRestApiController {

@GetMapping("users")
public List<User> users(){
    return this.userRepository.findAll();
}

@PostMapping(path="/save")
@ResponseBody public User insertusers( @RequestBody UserRequest requestUser){
    User user = new User(requestUser.getUsername(),passwordEncoder.encode(requestUser.getPassword()),requestUser.getRoles(),requestUser.getPermissions());
    try {
        user = this.userRepository.save(user);
        return user;
    }
    catch(Error e) {
        return user;
    }
}

}
</code>```

UserRequest class

```<code>public class UserRequest {

public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public int getActive() {
    return active;
}
public void setActive(int active) {
    this.active = active;
}
public String getRoles() {
    return roles;
}
public void setRoles(String roles) {
    this.roles = roles;
}
public String getPermissions() {
    return permissions;
}
public void setPermissions(String permissions) {
    this.permissions = permissions;
}
private String username;
private String password;
private int active;
private String roles = "";
private String permissions = "";

}
</code>```

User Class

```<code>@Entity
@Table(name = "USER_DETAILS")
public class User {

@Id
@Column
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(nullable = false)
private String username;

@Column(nullable = false)
private String PASSWORD;

@Column
private int ACTIVE;

@Column
private String ROLES = "";

@Column
private String PERMISSIONS = "";

public User(String username, String password, String roles, String permissions){
    this.username = username;
    this.PASSWORD = password;
    this.ROLES = roles;
    this.PERMISSIONS = permissions;
    this.ACTIVE = 1;
}

public User(){}

public int getId() {
    return id;
}

public String getUsername() {
    return username;
}

public String getPassword() {
    return PASSWORD;
}

public int getActive() {
    return ACTIVE;
}

public String getRoles() {
    return ROLES;
}

public String getPermissions() {
    return PERMISSIONS;
}

public void setId(int id) {
    this.id = id;
}

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.PASSWORD = password;
}

public void setActive(int active) {
    this.ACTIVE = active;
}

public void setRoles(String roles) {
    this.ROLES = roles;
}

public void setPermissions(String permissions) {
    this.PERMISSIONS = permissions;
}
}
</code>```

UserRepository class

```<code>@Repository
public interface UserRepository extends JpaRepository<User, Long>{

}
</code>```

POST method is working fine, but while calling GET method, id field is coming default value 0.Not fetching proper ID values. And also while running server, if I call POST method, it is inserting data in database, but that newly inserted data is not getting fetched by GET method.Only those data are getting fetched, which I have already inserted in the database.

This is the data in database

This is the response which I am getting form GET method

答:
Your USER class has Primary key with Type int and in your Repository, you have extended
USER class with long which should be Integer as below

Repository:

```<code> @Repository
 public interface UserRepository extends JpaRepository<User, Integer>{

 }
</code>```

UPDATE:

```<code> @Autowired UserRepository userRepository;

         @GetMapping("users")
         public List<User> users(){
              return userRepository.getAllUsers();
         }
</code>```

Repository:

```<code> @Repository
 public interface UserRepository extends JpaRepository<User, Integer>{
      @Query(value="select * from USER_DETAILS",nativeQuery=true)
      List<User> getAllUsers();
 }
</code>```

import @Query from import org.springframework.data.jpa.repository.Query;

UPDATE2:
Idel way of project structure is to have different packages according to class behavior.

Controller

Service

Repository

Models or Entity

DTOs, DAOs

Security, Config etc as per the requirnments

```<code>     //Controller
     @yourMapping
     public returnType method1()
     {
         myService.performBusinessLoginonMethod1(...) //if you are using services
         myReposiroty.DBOpertaion(...) //as per above case
     }

     //Service: myService
     returnType  performBusinessLoginonMethod1(...)
     {
         myRepository.DBOpertaion(...)
     }

     //Repository: myRepository
     @Modifying // import org.springframework.data.jpa.repository.Modifying;
     @Query(...)
     returnType DBOpertaion(...)
</code>```

Title: Unable to get proper GET response

Body:
I am trying to implement a GET and a POST method in spring-boot. While calling GET method not getting proper response.

My Controller class

@RestController
@RequestMapping("api/public")
public class PublicRestApiController {

@GetMapping("users")
public List<User> users(){
    return this.userRepository.findAll();
}

@PostMapping(path="/save")
@ResponseBody public User insertusers( @RequestBody UserRequest requestUser){
    User user = new User(requestUser.getUsername(),passwordEncoder.encode(requestUser.getPassword()),requestUser.getRoles(),requestUser.getPermissions());
    try {
        user = this.userRepository.save(user);
        return user;
    }
    catch(Error e) {
        return user;
    }
}

}

UserRequest class

public class UserRequest {

public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public int getActive() {
    return active;
}
public void setActive(int active) {
    this.active = active;
}
public String getRoles() {
    return roles;
}
public void setRoles(String roles) {
    this.roles = roles;
}
public String getPermissions() {
    return permissions;
}
public void setPermissions(String permissions) {
    this.permissions = permissions;
}
private String username;
private String password;
private int active;
private String roles = "";
private String permissions = "";

}

User Class

@Entity
@Table(name = "USER_DETAILS")
public class User {

@Id
@Column
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(nullable = false)
private String username;

@Column(nullable = false)
private String PASSWORD;

@Column
private int ACTIVE;

@Column
private String ROLES = "";

@Column
private String PERMISSIONS = "";

public User(String username, String password, String roles, String permissions){
    this.username = username;
    this.PASSWORD = password;
    this.ROLES = roles;
    this.PERMISSIONS = permissions;
    this.ACTIVE = 1;
}

public User(){}

public int getId() {
    return id;
}

public String getUsername() {
    return username;
}

public String getPassword() {
    return PASSWORD;
}

public int getActive() {
    return ACTIVE;
}

public String getRoles() {
    return ROLES;
}

public String getPermissions() {
    return PERMISSIONS;
}

public void setId(int id) {
    this.id = id;
}

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.PASSWORD = password;
}

public void setActive(int active) {
    this.ACTIVE = active;
}

public void setRoles(String roles) {
    this.ROLES = roles;
}

public void setPermissions(String permissions) {
    this.PERMISSIONS = permissions;
}
}

UserRepository class

@Repository
public interface UserRepository extends JpaRepository<User, Long>{

}

POST method is working fine, but while calling GET method, id field is coming default value 0.Not fetching proper ID values. And also while running server, if I call POST method, it is inserting data in database, but that newly inserted data is not getting fetched by GET method.Only those data are getting fetched, which I have already inserted in the database.

This is the data in database

This is the response which I am getting form GET method

Body:
Your USER class has Primary key with Type int and in your Repository, you have extended
USER class with long which should be Integer as below

Repository:

 @Repository
 public interface UserRepository extends JpaRepository<User, Integer>{

 }

UPDATE:

 @Autowired UserRepository userRepository;

         @GetMapping("users")
         public List<User> users(){
              return userRepository.getAllUsers();
         }

Repository:

 @Repository
 public interface UserRepository extends JpaRepository<User, Integer>{
      @Query(value="select * from USER_DETAILS",nativeQuery=true)
      List<User> getAllUsers();
 }

import @Query from import org.springframework.data.jpa.repository.Query;

UPDATE2:
Idel way of project structure is to have different packages according to class behavior.

Controller

Service

Repository

Models or Entity

DTOs, DAOs

Security, Config etc as per the requirnments

     //Controller
     @yourMapping
     public returnType method1()
     {
         myService.performBusinessLoginonMethod1(...) //if you are using services
         myReposiroty.DBOpertaion(...) //as per above case
     }

     //Service: myService
     returnType  performBusinessLoginonMethod1(...)
     {
         myRepository.DBOpertaion(...)
     }

     //Repository: myRepository
     @Modifying // import org.springframework.data.jpa.repository.Modifying;
     @Query(...)
     returnType DBOpertaion(...)


答:
I believe you can simply do:

input[mask]
```

Btw. you don't need to call sigmoid and then .gt(0.5). You can directly do .gt(0.0) without calling the sigmoid.

Title: pytorch how to select channels by mask?

Body:
I want to know how do I select channels by the mask in Pytorch.
[channel1 channel2 channel3 channel4] x [1,0,0,1] --> [channel1,channel4]
I tried torch.masked_select() and it did't work.

if the input has a shape like [B,C,H,W] the output's shape should be [B,masked_C,H,W],

import torch
from torch import nn
input = torch.randn((1,5,3,3))
pool = nn.AdaptiveAvgPool2d(1)
w = torch.sigmoid(pool(input)).view(1,-1)
mask = torch.gt(w,0.5)
print(input)
print(w)
print(mask)

the output is as following:

tensor([[[[ 0.9129, -0.9763,  1.4460],
          [ 0.3608,  0.5561, -1.4612],
          [ 1.4953, -1.2474,  0.4069]],

         [[-0.9121,  0.1261,  0.4661],
          [-1.1624, -1.0266, -1.5419],
          [ 1.0644,  1.0039, -0.4022]],

         [[-1.8454, -0.2150,  2.3703],
          [ 0.5224,  0.3366,  1.7545],
          [-0.4624,  1.2639,  1.8032]],

         [[-1.1558, -1.9985, -1.1336],
          [-0.4400, -0.2092,  0.0677],
          [-0.4172, -0.3614, -1.3193]],

         [[-0.9441, -0.2944,  0.3381],
          [ 1.6562, -0.5623,  0.0599],
          [ 0.7229,  0.0472, -0.5122]]]])
tensor([[0.5414, 0.4341, 0.6489, 0.3156, 0.5142]])
tensor([[1, 0, 1, 0, 1]], dtype=torch.uint8)

the result I want is like this:

tensor([[[[ 0.9129, -0.9763,  1.4460],
          [ 0.3608,  0.5561, -1.4612],
          [ 1.4953, -1.2474,  0.4069]],

         [[-1.8454, -0.2150,  2.3703],
          [ 0.5224,  0.3366,  1.7545],
          [-0.4624,  1.2639,  1.8032]],

         [[-0.9441, -0.2944,  0.3381],
          [ 1.6562, -0.5623,  0.0599],
          [ 0.7229,  0.0472, -0.5122]]]])

Body:
I believe you can simply do:

input[mask]

Btw. you don't need to call sigmoid and then .gt(0.5). You can directly do .gt(0.0) without calling the sigmoid.


问:
Receiving messages from ejabberd XMPP server on Android client
I am trying to create an Android chat client using ejabberd XMPP server (19.02), Smack library (4.2.4) and Android SDK 25 using Android Studio.

I followed the example app found here: https://www.blikoontech.com/tutorials/android-smack-xmpp-introductionbuilding-a-simple-client

All is working well and I can send messages between two different Android devices running that sample app.

In ejabberd, there are options to send messages to the clients directly from the server using a CLI tool called ejabberdctl or ejabberd REST API. When I sent messages that way, the Android client doesn’t receive those messages. I tried with other clients like Conversations and Gajim and they could all receive it. I am pretty sure messages sent using those methods arrived because they were received as offline messages (on ejabberd web admin) when sent to offline clients.

Here is the part of the Android (java) code (roosterconnection.java from that sample app) that is to receive incoming messages. Please suggest me if I am missing anything. Thanks a lot.

```<code>ChatManager.getInstanceFor(mConnection).addIncomingListener(new IncomingChatMessageListener() {
            @Override
            public void newIncomingMessage(EntityBareJid messageFrom, Message message, Chat chat) {
                ///ADDED
                Log.d(TAG,"message.getBody() :"+message.getBody());
                Log.d(TAG,"message.getFrom() :"+message.getFrom());

                String from = message.getFrom().toString();

                String contactJid="";
                if ( from.contains("/"))
                {
                    contactJid = from.split("/")[0];
                    Log.d(TAG,"The real jid is :" +contactJid);
                    Log.d(TAG,"The message is from :" +from);
                }else
                {
                    contactJid=from;
                }

                //Bundle up the intent and send the broadcast.
                Intent intent = new Intent(RoosterConnectionService.NEW_MESSAGE);
                intent.setPackage(mApplicationContext.getPackageName());
                intent.putExtra(RoosterConnectionService.BUNDLE_FROM_JID,contactJid);
                intent.putExtra(RoosterConnectionService.BUNDLE_MESSAGE_BODY,message.getBody());
                mApplicationContext.sendBroadcast(intent);
                Log.d(TAG,"Received message from :"+contactJid+" broadcast sent.");
                ///ADDED

            }
        });
</code>```

答:
Here is a possible explanation, based in my experiments with a desktop client, Tkabber:

I login to ejabberd using Tkabber client, account user1@localhost, resource tka1, priority -3. The negative priority in this experiment is important.

Then I execute the command to send to full JID, including the correct resource:

ejabberdctl send_stanza aaa@localhost user1@localhost/tka1
  "<message>..."

The client receives the stanza correctly.

Now I send to bare JID (without providing resource), and another setting another resource:

ejabberdctl send_stanza aaa@localhost user1@localhost
  "<message>..."

ejabberdctl send_stanza aaa@localhost user1@localhost/sdsd
  "<message>..."

In those cases, none of them are received by the client, because the resource doesn't match, and because its priority is negative. I can see those messages stored offline in the database.

In your client, maybe you have to add another call to set the presence online, with a positive priority.

Body:
I am trying to create an Android chat client using ejabberd XMPP server (19.02), Smack library (4.2.4) and Android SDK 25 using Android Studio.

I followed the example app found here: https://www.blikoontech.com/tutorials/android-smack-xmpp-introductionbuilding-a-simple-client

All is working well and I can send messages between two different Android devices running that sample app.

In ejabberd, there are options to send messages to the clients directly from the server using a CLI tool called ejabberdctl or ejabberd REST API. When I sent messages that way, the Android client doesn’t receive those messages. I tried with other clients like Conversations and Gajim and they could all receive it. I am pretty sure messages sent using those methods arrived because they were received as offline messages (on ejabberd web admin) when sent to offline clients.

Here is the part of the Android (java) code (roosterconnection.java from that sample app) that is to receive incoming messages. Please suggest me if I am missing anything. Thanks a lot.

ChatManager.getInstanceFor(mConnection).addIncomingListener(new IncomingChatMessageListener() {
            @Override
            public void newIncomingMessage(EntityBareJid messageFrom, Message message, Chat chat) {
                ///ADDED
                Log.d(TAG,"message.getBody() :"+message.getBody());
                Log.d(TAG,"message.getFrom() :"+message.getFrom());

                String from = message.getFrom().toString();

                String contactJid="";
                if ( from.contains("/"))
                {
                    contactJid = from.split("/")[0];
                    Log.d(TAG,"The real jid is :" +contactJid);
                    Log.d(TAG,"The message is from :" +from);
                }else
                {
                    contactJid=from;
                }

                //Bundle up the intent and send the broadcast.
                Intent intent = new Intent(RoosterConnectionService.NEW_MESSAGE);
                intent.setPackage(mApplicationContext.getPackageName());
                intent.putExtra(RoosterConnectionService.BUNDLE_FROM_JID,contactJid);
                intent.putExtra(RoosterConnectionService.BUNDLE_MESSAGE_BODY,message.getBody());
                mApplicationContext.sendBroadcast(intent);
                Log.d(TAG,"Received message from :"+contactJid+" broadcast sent.");
                ///ADDED

            }
        });


问:
submenu under menu are not displaying
I have four menus in which one menu have 2 submenus I'm using bootstrap for this but after many tries, I'm not getting any way to solve it as I'm new to it. The main menu is not displaying the submenu when clicked.

I have tried various possible ways and when I'm adding CDN to my project it's working fine. But when I'm adding the bootstrap file from my local storage it's not displaying. But other features are working fine

```<code><link rel="stylesheet" href="css/bootstrap.css">
<style>
    .header {
        height: 50px;
        background-color: black;
        margin-top: 3px;
    }

    .column {
        margin-left: 100px;
    }
</style>
<body>
    <nav class="navbar navbar-expand-sm  navbar-dark bg-dark header">
        <a href="#" class="navbar-brand">Stone</a>
        <ul class="nav navbar-nav column">
            <li class="nav-item"><a href="#" class="nav-link">Home</a></li>
            <li class="nav-item"><a href="#" class="nav-link">Add Employee</a></li>

            <li class="nav-item dropdown">
                <a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown" id="searchEmp" role="button">Search Employee</a>
                <div class="dropdown-menu" aria-labelledby="searchEmp">
                    <a href="#" class="dropdown-item">Search With ID</a>
                    <a href="#" class="dropdown-item">Search All Employee</a>
                </div>
            </li>
            <li class="nav-item"><a href="#" class="nav-link">About</a></li>
        </ul>
    </nav>

    <script src="js/bootstrap.js"></script>
    <script src="js/jquery-3.4.1.js"></script>
</body>
</code>```

In console it's not showing any error

答:
you need to add popper.js too for menu to work properly.

```

add this code after jquery but before bootstrap.js

Title: submenu under menu are not displaying

Body:
I have four menus in which one menu have 2 submenus I'm using bootstrap for this but after many tries, I'm not getting any way to solve it as I'm new to it. The main menu is not displaying the submenu when clicked.

I have tried various possible ways and when I'm adding CDN to my project it's working fine. But when I'm adding the bootstrap file from my local storage it's not displaying. But other features are working fine

<link rel="stylesheet" href="css/bootstrap.css">

        Stone

Home

Add Employee

                Search Employee

                    Search With ID
                    Search All Employee

About

In console it's not showing any error

Body:
you need to add popper.js too for menu to work properly.

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

add this code after jquery but before bootstrap.js


问:
Configuration setting updates
How can I remove author name and datetime from drupal article from admin section? I have already tried admin content type configuration setting for the same, but that didn't work.</p>

答:
Edit the node type, in the "Display settings", there is a checkbox "Display author and date information", turn that off.

Hope this helps you

Title: Configuration setting updates


问:
Understanding Rails singular and plural paths
I'm very new to using Rails and at the moment am building an Instagram clone as a project to help me understand Rails a bit better. I am following this very helpful tutorial on how to implement the likes/unlikes feature:

https://medium.com/full-taxx/how-to-add-likes-to-posts-in-rails-e81430101bc2

However, I don't fully understand the Rails paths - please could someone explain the difference between:

post_like_path and post_likes_path as mentioned in the tutorial. I cannot see why one is like and one is likes? :(

Really trying to get my head around this so would be so grateful for any insight!

Thanks :)

答:
I'd suggest to always run this command from terminal:

```<code>rake routes
</code>```

Or just for LikesController:

```<code>rake routes -c likes
</code>```

This shows all the routes related to likes controllers. That's the output, it tells a lot of things. You can see where the plural and singular is used.

```<code>#         Prefix Verb   URI Pattern                              Controller#Action
#     post_likes GET    /posts/:post_id/likes(.:format)          likes#index
#                POST   /posts/:post_id/likes(.:format)          likes#create
#  new_post_like GET    /posts/:post_id/likes/new(.:format)      likes#new
# edit_post_like GET    /posts/:post_id/likes/:id/edit(.:format) likes#edit
#      post_like GET    /posts/:post_id/likes/:id(.:format)      likes#show
#                PATCH  /posts/:post_id/likes/:id(.:format)      likes#update
#                PUT    /posts/:post_id/likes/:id(.:format)      likes#update
#                DELETE /posts/:post_id/likes/:id(.:format)      likes#destroy
</code>```

First column shows you the path, the second the pattern (with required parameters) and the third the controller with action (related to the view).

So, for example, take

```<code># new_post_like GET    /posts/:post_id/likes/new(.:format)      likes#new
</code>```

This says that the form for a new like can be placed to a page linked by this URL:
new_post_like_path(post_id: @post) note the parameter required. The page is views/likes/new.html.erb.
the controller is LikesController and the action is def new; end where you need to instantiate the objects to be used in that page: @like = Like.new and @post = Post.find(params[:post_id]).

The form is then submitted by POST action, so the line to check is the following:

```<code># post_likes POST   /posts/:post_id/likes(.:format)          likes#create
</code>```

As before, the page where the form is located is views/likes/new.html.erb, the url to submit the form is post_likes_path(post.id). The POST action when submitting the form is processed by the controller LikesController and the action is def create; end

Other example:

```<code># post_like GET    /posts/:post_id/likes/:id(.:format)      likes#show
</code>```

It tells that to show the Like object with a certain id, you need to visit this link_to: post_like_path(post.id, like.id), the controller is LikesController, the action is def show; end and the view is in views/likes/show.html.erb.

And so on..

Body:
I'd suggest to always run this command from terminal:

rake routes

Or just for LikesController:

rake routes -c likes

This shows all the routes related to likes controllers. That's the output, it tells a lot of things. You can see where the plural and singular is used.

#         Prefix Verb   URI Pattern                              Controller#Action
#     post_likes GET    /posts/:post_id/likes(.:format)          likes#index
#                POST   /posts/:post_id/likes(.:format)          likes#create
#  new_post_like GET    /posts/:post_id/likes/new(.:format)      likes#new
# edit_post_like GET    /posts/:post_id/likes/:id/edit(.:format) likes#edit
#      post_like GET    /posts/:post_id/likes/:id(.:format)      likes#show
#                PATCH  /posts/:post_id/likes/:id(.:format)      likes#update
#                PUT    /posts/:post_id/likes/:id(.:format)      likes#update
#                DELETE /posts/:post_id/likes/:id(.:format)      likes#destroy

First column shows you the path, the second the pattern (with required parameters) and the third the controller with action (related to the view).

So, for example, take

# new_post_like GET    /posts/:post_id/likes/new(.:format)      likes#new

This says that the form for a new like can be placed to a page linked by this URL:
new_post_like_path(post_id: @post) note the parameter required. The page is views/likes/new.html.erb.
the controller is LikesController and the action is def new; end where you need to instantiate the objects to be used in that page: @like = Like.new and @post = Post.find(params[:post_id]).

The form is then submitted by POST action, so the line to check is the following:

# post_likes POST   /posts/:post_id/likes(.:format)          likes#create

As before, the page where the form is located is views/likes/new.html.erb, the url to submit the form is post_likes_path(post.id). The POST action when submitting the form is processed by the controller LikesController and the action is def create; end

Other example:

# post_like GET    /posts/:post_id/likes/:id(.:format)      likes#show

It tells that to show the Like object with a certain id, you need to visit this link_to: post_like_path(post.id, like.id), the controller is LikesController, the action is def show; end and the view is in views/likes/show.html.erb.

And so on..


问:
Wordpress plugin - users send files to owner
I'm doing a WordPress page and I need that the people that visit the page can send to me (the owner) images.

I don't want them to be able to upload them to the page, I just want to be able to receive the images via mail.

Is there any wordpress plugin that can do this?

答:
use contact form 7, create a form like this

[text* your-name placeholder "Name"]

[tel* your-phone placeholder "Phone Number"]

[email* your-email placeholder "Email Address"]

Attach Image (upto 2mb)// normal hosting space is having this much upload limit only

[file* your-file filetypes:jpeg|png limit:2mb]

[textarea* your-message 40x3  placeholder "Message if any"]

[submit "Send Now"]```

Go to Second Tab called as 'mail'-> Go Down and add this in file attachments - [your-file]

Save contact form and use the shortcode to display on your page as a form.

You will receive image in your email as an attachment.

Body:
use contact form 7, create a form like this

[text* your-name placeholder "Name"]

[tel* your-phone placeholder "Phone Number"]

[email* your-email placeholder "Email Address"]

Attach Image (upto 2mb)// normal hosting space is having this much upload limit only

[file* your-file filetypes:jpeg|png limit:2mb]

[textarea* your-message 40x3  placeholder "Message if any"]

[submit "Send Now"]

Go to Second Tab called as 'mail'-> Go Down and add this in file attachments - [your-file]

Save contact form and use the shortcode to display on your page as a form.

You will receive image in your email as an attachment.


问:
Which COM smart pointer classes to use?
I'm confused by the choices for COM smart pointers classes for C++ programming:

There's three four I'm aware of:

CCOMPtr from ATL

_com_ptr_t from the MS Com Support Classes

TComInterface (because I'm using C++Builder 2009)

CCOMQIPtr, (which I'd previously forgotten)

I've read about the error vs. exception handling differences of the first two, but TComInterface seems totally undocumented. Both the first two seem to have gotchas or 'unexpected' behaviour, from what I can find.

Ideally, I'd like something that's clean and modern C++, but boost::com doesn't exist as far as I know...

I need to control an application from another vendor. They provide a COM interface via a TLB file.

答:
If you are using the type-library import stuff, it will generate code based upon _com_ptr_t and the related COM Support Classes.  Go ahead and use those if you are just using stuff from those libraries.

If you are writing ATL-based code, then use CCOMPtr and the other ATL-based classes.

Things may get ugly if you need to mix-and-match both types, but you should probably just get comfortable with both and use whichever makes the most sense for whatever you are doing at the time.

The nice thing is that you have the source for all of these things, so you don't have to rely only on the documentation (which has not been getting much care since .NET appeared).

Title: Which COM smart pointer classes to use?


问:
elasticsearch querying only the document I want and saving it as a snapshot
I want to find a way to back up (snapshot) and restore only the document(data) that I want out of Elastic Search.

I looked up the reference page of Elastic Search, but there was only a way to backup the entire index, but I couldn't find a backup by querying the desired document(data).
Is there a way to back up only the desired data using mysql?

The code below backs up the entire index by storing a basic snapshot.
How can I modify something here?

PUT /_snapshot/my_backup
{
  "type": "fs",
  "settings": {
    "location": "my_backup_location"
  }
}

答:
You can try creating another index using your query, and then snapshot this new index.
You can use the reindex api to create this new index </p>


问:
Show three dots when TextView is too long
One would think that showing three dots in 2019 at the end of string will be easy, but the opposite seems to be true. I have tried:

```<code>maxLines="1"
drawablePadding="10dp"
ellipsize="end"
ellipsize="marquee"
singleLine="true"
layout_width="match_parent"
layout_width="wrap_content"
</code>```

I went through dozens of questions here at stackoverflow, but it just doesn't work.

My layout file is quite simple:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/dialog_nearest_charger"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="40dp"
    android:orientation="horizontal"
    android:weightSum="10">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="55dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerDistance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/colorCoarseDistance"
            android:textStyle="bold"
            android:textSize="20sp"
            android:text="1.2" />

        <TextView
            android:id="@+id/itemChargerUnits"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="12sp"
            android:text="miles" />

    </LinearLayout>

    <ImageView
        android:id="@+id/itemChargerOperator"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="40dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/dot_cpo_cps_copy_5" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="7dp"
        android:layout_weight="2"
        android:drawablePadding="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawablePadding="10dp"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="Kinross Park and Ride"
            android:textSize="18sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/itemChargerAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginStart="5dp"
                android:textSize="14sp"
                android:text="Junction Road" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>
</code>```

All I need is to show three dots when TextView itemChargerTitle overflows. So far none of the solutions I found worked even in Android Studio preview.

答:
Please try this. I've updated width as 0dp. When you are using android:layout_weight make sure you are using android:layout_width="0dp" and total of all child layout_weight is 1 or 10. That means 100% width.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dialog_nearest_charger"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    android:minHeight="40dp"
    android:orientation="horizontal"
    android:weightSum="10">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerDistance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="1.2"
            android:textColor="@color/colorCoarseDistance"
            android:textSize="20sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/itemChargerUnits"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="miles"
            android:textSize="12sp" />

    </LinearLayout>

    <ImageView
        android:id="@+id/itemChargerOperator"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        app:srcCompat="@drawable/dot_cpo_cps_copy_5"
        android:layout_weight="1" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="7dp"
        android:layout_weight="8"
        android:drawablePadding="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawablePadding="10dp"
            android:ellipsize="end"
            android:lines="1"
            android:maxLines="1"
            android:padding="@dimen/ten_dp"
            android:text="Kinross Park and Ride"
            android:textSize="18sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/itemChargerAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="5dp"
                android:layout_weight="1"
                android:text="Junction Road"
                android:textSize="14sp" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>
</code>```

Body:
One would think that showing three dots in 2019 at the end of string will be easy, but the opposite seems to be true. I have tried:

maxLines="1"
drawablePadding="10dp"
ellipsize="end"
ellipsize="marquee"
singleLine="true"
layout_width="match_parent"
layout_width="wrap_content"

I went through dozens of questions here at stackoverflow, but it just doesn't work.

My layout file is quite simple:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/dialog_nearest_charger"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="40dp"
    android:orientation="horizontal"
    android:weightSum="10">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="55dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerDistance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/colorCoarseDistance"
            android:textStyle="bold"
            android:textSize="20sp"
            android:text="1.2" />

        <TextView
            android:id="@+id/itemChargerUnits"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="12sp"
            android:text="miles" />

    </LinearLayout>

    <ImageView
        android:id="@+id/itemChargerOperator"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="40dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/dot_cpo_cps_copy_5" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="7dp"
        android:layout_weight="2"
        android:drawablePadding="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawablePadding="10dp"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="Kinross Park and Ride"
            android:textSize="18sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/itemChargerAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginStart="5dp"
                android:textSize="14sp"
                android:text="Junction Road" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

All I need is to show three dots when TextView itemChargerTitle overflows. So far none of the solutions I found worked even in Android Studio preview.

Body:
Please try this. I've updated width as 0dp. When you are using android:layout_weight make sure you are using android:layout_width="0dp" and total of all child layout_weight is 1 or 10. That means 100% width.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dialog_nearest_charger"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    android:minHeight="40dp"
    android:orientation="horizontal"
    android:weightSum="10">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerDistance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="1.2"
            android:textColor="@color/colorCoarseDistance"
            android:textSize="20sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/itemChargerUnits"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="miles"
            android:textSize="12sp" />

    </LinearLayout>

    <ImageView
        android:id="@+id/itemChargerOperator"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        app:srcCompat="@drawable/dot_cpo_cps_copy_5"
        android:layout_weight="1" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="7dp"
        android:layout_weight="8"
        android:drawablePadding="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/itemChargerTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawablePadding="10dp"
            android:ellipsize="end"
            android:lines="1"
            android:maxLines="1"
            android:padding="@dimen/ten_dp"
            android:text="Kinross Park and Ride"
            android:textSize="18sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/itemChargerAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="5dp"
                android:layout_weight="1"
                android:text="Junction Road"
                android:textSize="14sp" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>


问:
AWS Lambda to AWS Lambda permissions
Trying to use lambda.invoke method from the AWS docs. However I get permission issues when trying to test this.

Could anyway guide me on how to set up these permissions?

```<code>var aws = require('aws-sdk');
var lambda = new aws.Lambda({
  region: 'us-west-2' //change to your region
});

lambda.invoke({
  FunctionName: 'lambda_function',
  Payload: JSON.stringify('hello world') // pass params
}, function(error, data) {
  if (error) {
    context.done('error', error);
  }
  if(data.Payload){
   context.succeed(data.Payload)
  }
});
</code>```

Using these docs http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html

答:
You'll need to provide permissions to your caller Lambda function to invoke another function,

Your caller function will need an IAM Policy like -

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Lambda permission",
      "Action": [
        "lambda:InvokeFunction"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:lambda:awsRegion:awsAccountId:function:functionName"
    }
  ]
}
</code>```

If you're calling your function from local,

Your AWS Credentials will need the same access

Title: AWS Lambda to AWS Lambda permissions

Body:
Trying to use lambda.invoke method from the AWS docs. However I get permission issues when trying to test this.

Could anyway guide me on how to set up these permissions?

var aws = require('aws-sdk');
var lambda = new aws.Lambda({
  region: 'us-west-2' //change to your region
});

lambda.invoke({
  FunctionName: 'lambda_function',
  Payload: JSON.stringify('hello world') // pass params
}, function(error, data) {
  if (error) {
    context.done('error', error);
  }
  if(data.Payload){
   context.succeed(data.Payload)
  }
});

Using these docs http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html

Body:
You'll need to provide permissions to your caller Lambda function to invoke another function,

Your caller function will need an IAM Policy like -

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Lambda permission",
      "Action": [
        "lambda:InvokeFunction"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:lambda:awsRegion:awsAccountId:function:functionName"
    }
  ]
}

If you're calling your function from local,

Your AWS Credentials will need the same access


问:
React Native, how to find out default value for each inbuilt component style property?
E.g. How to find out the default fontSize of Text component or the default flex value for View component.

React devtools is only showing styles that has been explicitly set in my code.

Also checked the docs e.g. https://facebook.github.io/react-native/docs/view-style-props but no style property lists a default value.

答:
Actually the default fontSize is the fontsize of android or ios device you are using. You can change this default font size in your device settings.

If you want to know you default font size you can check with react-native-device-info . As it provides you a function names as getFontScale() which provides you the font ratio


问:
Missing SPARK_HOME when using SparkLauncher on AWS EMR cluster
I am using EMR 5.0 with Spark 2.0.0.
I am trying to run child spark application from Scala spark application using org.apache.spark.launcher.SparkLauncher

I need to set SPARK_HOME using setSparkHome:

```<code> var handle = new SparkLauncher()
    .setAppResource("s3://my-bucket/python_code.py")
    .setAppName("PythonAPP")
    .setMaster("spark://" + sparkSession.conf.get("spark.driver.host") +":"+ sparkSession.conf.get("spark.driver.port"))
    .setVerbose(true)
    .setConf(SparkLauncher.EXECUTOR_CORES, "1")
    .setSparkHome("/srv/spark") // not working
    .setDeployMode("client")
    .startApplication(
      new SparkAppHandle.Listener() {

        override def infoChanged(hndl: SparkAppHandle): Unit = {
          System.out.println(hndl.getState() + " new  state !")
        }

        override def stateChanged(hndl: SparkAppHandle): Unit = {
          System.out.println(hndl.getState() + "    new  state !")
        }
      })
</code>```

Where can I find the appropriate path to my Spark Home ?
The cluster is built from 1 Master, 1 Core and 1 Task servers.

Thanks!

答:
I find out that Spark on AWS EMR (tested with version emr-5.23.0 & emr-5.22.0) doesn't install Spark on EMR CORE Nodes. Just check the EMR nodes installation on /usr/lib/spark, it's not really a SPARK_HOME like the one installed on the EMR MASTER node.

Installing Spark on EMR CORE Nodes solved my issue.

Body:
I am using EMR 5.0 with Spark 2.0.0.
I am trying to run child spark application from Scala spark application using org.apache.spark.launcher.SparkLauncher

I need to set SPARK_HOME using setSparkHome:

 var handle = new SparkLauncher()
    .setAppResource("s3://my-bucket/python_code.py")
    .setAppName("PythonAPP")
    .setMaster("spark://" + sparkSession.conf.get("spark.driver.host") +":"+ sparkSession.conf.get("spark.driver.port"))
    .setVerbose(true)
    .setConf(SparkLauncher.EXECUTOR_CORES, "1")
    .setSparkHome("/srv/spark") // not working
    .setDeployMode("client")
    .startApplication(
      new SparkAppHandle.Listener() {

        override def infoChanged(hndl: SparkAppHandle): Unit = {
          System.out.println(hndl.getState() + " new  state !")
        }

        override def stateChanged(hndl: SparkAppHandle): Unit = {
          System.out.println(hndl.getState() + "    new  state !")
        }
      })

Where can I find the appropriate path to my Spark Home ?
The cluster is built from 1 Master, 1 Core and 1 Task servers.

Thanks!


问:
How to pass custom parameters in header request
I have to call an API, I need to pass username and password along with header request. How to call API from angular service?

I tried with this code:

```<code>    checkUserApi(url: string): Observable<any> {
       const headers = new HttpHeaders()
           .set('Content-Type', 'application/json')
           .set('Accept', 'text/plain')
          .set('userName', 'username')
         .set('password', 'password');
    return this.http.post(url, { headers })
      .map((response: Response) => {
        console.log("response : " +response);
        return response;
      })
   }
</code>```

答:
Please check this out:

```<code> let tHeader = new Headers();
 tHeader.append('x-username', UserName);
 tHeader.append('x-password', Password);
 return this.http.post(url,{payload}, { headers: tHeaders })
  .map((response: Response) => {
    console.log("response : " +response);
    return response;
  });
</code>```

this.http.post(url, { headers }) ---> this is not the right way of passing header. Please go through the above code.

In every post request , you should pass a payload. If you dont have any payload to send, pass an empty object.

Body:
I have to call an API, I need to pass username and password along with header request. How to call API from angular service?

I tried with this code:

    checkUserApi(url: string): Observable<any> {
       const headers = new HttpHeaders()
           .set('Content-Type', 'application/json')
           .set('Accept', 'text/plain')
          .set('userName', 'username')
         .set('password', 'password');
    return this.http.post(url, { headers })
      .map((response: Response) => {
        console.log("response : " +response);
        return response;
      })
   }

Body:
Please check this out:

 let tHeader = new Headers();
 tHeader.append('x-username', UserName);
 tHeader.append('x-password', Password);
 return this.http.post(url,{payload}, { headers: tHeaders })
  .map((response: Response) => {
    console.log("response : " +response);
    return response;
  });

this.http.post(url, { headers }) ---> this is not the right way of passing header. Please go through the above code.

In every post request , you should pass a payload. If you dont have any payload to send, pass an empty object.


问:
linux find regex
I'm having trouble using the regex of the find command. Probably something I don't understand about escaping on the command line.

Why are these not the same?

```<code>find -regex '.*[1234567890]'
find -regex '.*[[:digit:]]'
</code>```

Bash, Ubuntu

答: Well, you may try this '.*[0-9]'

Title: linux find regex

Body:
I'm having trouble using the regex of the find command. Probably something I don't understand about escaping on the command line.

Why are these not the same?

find -regex '.*[1234567890]'
find -regex '.*[[:digit:]]'

Bash, Ubuntu

Body: Well, you may try this '.*[0-9]'


问:
Get the average mean of entries per month with datetime in Pandas
I have a large df with many entries per month. I would like to see the average entries per month as to see as an example if there are any months that normally have more entries. (Ideally I'd like to plot this with a line of the over all mean to compare with but that is maybe a later question).
My df is something like this:

```<code>ufo=pd.read_csv('https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv')
ufo['Time']=pd.to_datetime(ufo.Time)
</code>```

Where the head looks like this:

So if I'd like to see if there are more ufo-sightings in the summer as an example, how would I go about?

I have tried:

```<code>ufo.groupby(ufo.Time.month).mean()
</code>```

But it does only work if I am calculating a numerical value. If I use count()instead I get the sum of all entries for all months.

EDIT: To clarify, I would like to have the mean of entries - ufo-sightings - per month.

Body:
I have a large df with many entries per month. I would like to see the average entries per month as to see as an example if there are any months that normally have more entries. (Ideally I'd like to plot this with a line of the over all mean to compare with but that is maybe a later question).
My df is something like this:

ufo=pd.read_csv('https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv')
ufo['Time']=pd.to_datetime(ufo.Time)

Where the head looks like this:

So if I'd like to see if there are more ufo-sightings in the summer as an example, how would I go about?

I have tried:

ufo.groupby(ufo.Time.month).mean()

But it does only work if I am calculating a numerical value. If I use count()instead I get the sum of all entries for all months.

EDIT: To clarify, I would like to have the mean of entries - ufo-sightings - per month.

Body:
You could do something like this:

# count the total months in the records
def total_month(x):
    return x.max().year -x.min().year + 1

new_df = ufo.groupby(ufo.Time.dt.month).Time.agg(['size', total_month])

new_df['mean_count'] = new_df['size'] /new_df['total_month']

Output:

    size    total_month     mean_count
Time
1   862     57              15.122807
2   817     70              11.671429
3   1096    55              19.927273
4   1045    68              15.367647
5   1168    53              22.037736
6   3059    71              43.084507
7   2345    65              36.076923
8   1948    64              30.437500
9   1635    67              24.402985
10  1723    65              26.507692
11  1509    50              30.180000
12  1034    56              18.464286


问:
cmake add_custom_command dependent on object library
I am trying to generate a version file using cmake using add_custom_command. I only want the version file to be (re)generated if another target (an object library) had any changes.

Here is my current simplified CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.1)
project (version-test)

# Object file compilation target.
add_library(version-test-objects OBJECT main.cpp)

# Version object file target.
add_custom_command(OUTPUT version.cpp
    COMMAND date "+char const *getVersion\\\(\\\) { return \\\"%Y-%m-%d %H:%M:%S\\\"\; }"
    > version.cpp
    DEPENDS version-test-objects
)
add_library(version-test-version OBJECT
    version.cpp
)

# Binary target.
add_executable(version-test
    $<TARGET_OBJECTS:version-test-objects>
    $<TARGET_OBJECTS:version-test-version>
)
</code>```

And for completeness my simplified main.cpp:

```<code>#include <iostream>

extern char const *getVersion();

int main() {
    std::cout << getVersion() << std::endl;
}
</code>```

The version.cpp is generated fine along with the first build. However, changes to the source (e.g., touch main.cpp) only rebuilds version-test-objects and links the executable, without regenerating version.cpp.

How can I get cmake to regenerate version.cpp if and only if version-test-objects had any changes?

答:
DEPENDS version-test-objects only specifies a target level dependency meaning that this command potentially gets run after building the target version-test-objects.  You stated the requirement that the command should run whenever any object file part of version-test-objects gets updated.  So those also have to be listed in DEPENDS as well.  This could be considered a bug regarding the differences between OBJECT libraries and normal libraries.

```<code># Version object file target.
add_custom_command(OUTPUT version.cpp
    COMMAND date "+char const *getVersion\\\(\\\) { return \\\"%Y-%m-%d %H:%M:%S\\\"\; }"
    > version.cpp
    DEPENDS version-test-objects $<TARGET_OBJECTS:version-test-objects>
)
</code>```

This works for me using CMake 3.13 Makefile generator.  This may not work in versions CMake 3.8 or earlier as the release notes state that this expression wasn't added until 3.9.  If that is the case you probably need to create a dummy archive that uses all the objects and then use that as a dependency.

Body:
I am trying to generate a version file using cmake using add_custom_command. I only want the version file to be (re)generated if another target (an object library) had any changes.

Here is my current simplified CMakeLists.txt:

cmake_minimum_required(VERSION 3.1)
project (version-test)

# Object file compilation target.
add_library(version-test-objects OBJECT main.cpp)

# Version object file target.
add_custom_command(OUTPUT version.cpp
    COMMAND date "+char const *getVersion\\\(\\\) { return \\\"%Y-%m-%d %H:%M:%S\\\"\; }"
    > version.cpp
    DEPENDS version-test-objects
)
add_library(version-test-version OBJECT
    version.cpp
)

# Binary target.
add_executable(version-test
    $<TARGET_OBJECTS:version-test-objects>
    $<TARGET_OBJECTS:version-test-version>
)

And for completeness my simplified main.cpp:

#include <iostream>

extern char const *getVersion();

int main() {
    std::cout << getVersion() << std::endl;
}

The version.cpp is generated fine along with the first build. However, changes to the source (e.g., touch main.cpp) only rebuilds version-test-objects and links the executable, without regenerating version.cpp.

How can I get cmake to regenerate version.cpp if and only if version-test-objects had any changes?

Body:
DEPENDS version-test-objects only specifies a target level dependency meaning that this command potentially gets run after building the target version-test-objects.  You stated the requirement that the command should run whenever any object file part of version-test-objects gets updated.  So those also have to be listed in DEPENDS as well.  This could be considered a bug regarding the differences between OBJECT libraries and normal libraries.

# Version object file target.
add_custom_command(OUTPUT version.cpp
    COMMAND date "+char const *getVersion\\\(\\\) { return \\\"%Y-%m-%d %H:%M:%S\\\"\; }"
    > version.cpp
    DEPENDS version-test-objects $<TARGET_OBJECTS:version-test-objects>
)

This works for me using CMake 3.13 Makefile generator.  This may not work in versions CMake 3.8 or earlier as the release notes state that this expression wasn't added until 3.9.  If that is the case you probably need to create a dummy archive that uses all the objects and then use that as a dependency.


问:
How to add multiple classes to a ReactJS Component?
I am new to ReactJS and JSX and I am having a little problem with the code below.

I am trying to add multiple classes to the className attribute on each li:

```

<p>My React component is:</p>

<pre class="lang-jsx prettyprint-override"><code>var AccountMainMenu = React.createClass({
  getInitialState: function() {
    return { focused: 0 };
  },

  clicked: function(index) {
    this.setState({ focused: index });
  },

  render: function() {
    var self = this;
    var accountMenuData = [
      {
        name: "My Account",
        icon: "icon-account"
      },
      {
        name: "Messages",
        icon: "icon-message"
      },
      {
        name: "Settings",
        icon: "icon-settings"
      }
    /*{
        name:"Help & Support   <span class='font-awesome icon-support'></span>(888) 664.6261",
        listClass:"no-mobile last help-support last"
      }*/
    ];

    return (
      <div className="acc-header-wrapper clearfix">
        <ul className="acc-btns-container">
          {accountMenuData.map(function(data, index) {
            var activeClass = "";

            if (self.state.focused == index) {
              activeClass = "active";
            }

            return (
              <li
                key={index}
                className={activeClass}
                onClick={self.clicked.bind(self, index)}
              >

                  {data.name}

              </li>
            );
          })}
        </ul>
      </div>
    );
  }
});

ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));
</code>```

答:
Use https://www.npmjs.com/package/classnames

import classNames  from 'classnames';

Can use multiple classes using comas seperated:

```<code><li className={classNames(classes.tableCellLabel, classes.tableCell)}>Total</li>
</code>```

Can use multiple classes using comas separated with condition:

```<code><li className={classNames(classes.buttonArea, !nodes.length && classes.buttonAreaHidden)}>Hello World</li>
</code>```

Using array as props to classNames will also work, but gives warning e.g.

```<code>className={[classes.tableCellLabel, classes.tableCell]}
</code>```

Body:
I am new to ReactJS and JSX and I am having a little problem with the code below.

I am trying to add multiple classes to the className attribute on each li:

My React component is:

var AccountMainMenu = React.createClass({
  getInitialState: function() {
    return { focused: 0 };
  },

  clicked: function(index) {
    this.setState({ focused: index });
  },

  render: function() {
    var self = this;
    var accountMenuData = [
      {
        name: "My Account",
        icon: "icon-account"
      },
      {
        name: "Messages",
        icon: "icon-message"
      },
      {
        name: "Settings",
        icon: "icon-settings"
      }
    /*{
        name:"Help & Support   (888) 664.6261",
        listClass:"no-mobile last help-support last"
      }*/
    ];

    return (

          {accountMenuData.map(function(data, index) {
            var activeClass = "";

            if (self.state.focused == index) {
              activeClass = "active";
            }

            return (

                  {data.name}

            );
          })}

    );
  }
});

ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));

Body:
Use https://www.npmjs.com/package/classnames

import classNames  from 'classnames';

Can use multiple classes using comas seperated:

<li className={classNames(classes.tableCellLabel, classes.tableCell)}>Total</li>

Can use multiple classes using comas separated with condition:

<li className={classNames(classes.buttonArea, !nodes.length && classes.buttonAreaHidden)}>Hello World</li>

Using array as props to classNames will also work, but gives warning e.g.

className={[classes.tableCellLabel, classes.tableCell]}


问:
Updating colors of plot_model when I have only a single line?
I want to change the color of the plot outputted by plot_model. I have no trouble with these when I create multiple lines by including multiple variables in terms = c(..., ...), but I can't get the color to be anything other than black when I do the following code:

```<code>df_test <- data.frame('subj' = c('Joe', 'Joe', 'Moe', 'Moe'), 'A' = c(1, 0, 1, 0), 'B' = c(3, 2, 1, 4))

m = glmer(A ~ B + (B | subj), data=df_test, family='binomial')

print(plot_model(m, type='pred', colors = 'blue'))
</code>```

Output: https://imgur.com/a/pApsmH4

What am I missing here?

Thanks for the help

答:
You can use the ggeffects-package, which is internally used by sjPlot when creating marginal effects plots. This makes it a bit easier getting the data and then using ggplot:

library(lme4)
#> Loading required package: Matrix
library(ggeffects)
library(ggplot2)
#> Registered S3 methods overwritten by 'ggplot2':
#>   method         from
#>   [.quosures     rlang
#>   c.quosures     rlang
#>   print.quosures rlang

df_test <- data.frame('subj' = c('Joe', 'Joe', 'Moe', 'Moe'), 'A' = c(1, 0, 1, 0), 'B' = c(3, 2, 1, 4))
m<- glmer(A ~ B + (B | subj), data=df_test, family='binomial')
#> boundary (singular) fit: see ?isSingular

ggpredict(m, "B") %>%
  ggplot(aes(x, predicted)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = .2) +
  geom_line(colour = "blue")
```

Created on 2019-05-29 by the reprex package (v0.3.0)

There are several examples for manually building plots, e.g. here or here.

Body:
I want to change the color of the plot outputted by plot_model. I have no trouble with these when I create multiple lines by including multiple variables in terms = c(..., ...), but I can't get the color to be anything other than black when I do the following code:

df_test <- data.frame('subj' = c('Joe', 'Joe', 'Moe', 'Moe'), 'A' = c(1, 0, 1, 0), 'B' = c(3, 2, 1, 4))

m = glmer(A ~ B + (B | subj), data=df_test, family='binomial')

print(plot_model(m, type='pred', colors = 'blue'))

Output: https://imgur.com/a/pApsmH4

What am I missing here?

Thanks for the help

Body:
You can use the ggeffects-package, which is internally used by sjPlot when creating marginal effects plots. This makes it a bit easier getting the data and then using ggplot:

library(lme4)
#> Loading required package: Matrix
library(ggeffects)
library(ggplot2)
#> Registered S3 methods overwritten by 'ggplot2':
#>   method         from
#>   [.quosures     rlang
#>   c.quosures     rlang
#>   print.quosures rlang

df_test <- data.frame('subj' = c('Joe', 'Joe', 'Moe', 'Moe'), 'A' = c(1, 0, 1, 0), 'B' = c(3, 2, 1, 4))
m<- glmer(A ~ B + (B | subj), data=df_test, family='binomial')
#> boundary (singular) fit: see ?isSingular

ggpredict(m, "B") %>%
  ggplot(aes(x, predicted)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = .2) +
  geom_line(colour = "blue")

Created on 2019-05-29 by the reprex package (v0.3.0)

There are several examples for manually building plots, e.g. here or here.


答:
Your TextView shows three dots at the end but you can't see it, because your layout is beyond the edges of the screen. Change it's parent layout android:layout_weight to 8 to match the container android:weightSum=10 and you will see your dots.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/dialog_nearest_charger"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="40dp"
android:orientation="horizontal"
android:weightSum="10">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:minWidth="55dp"
    android:layout_weight="1"
    android:orientation="vertical">

    <TextView
        android:id="@+id/itemChargerDistance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textColor="@color/colorCoarseDistance"
        android:textStyle="bold"
        android:textSize="20sp"
        android:text="1.2" />

    <TextView
        android:id="@+id/itemChargerUnits"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="12sp"
        android:text="miles" />

</LinearLayout>

<ImageView
    android:id="@+id/itemChargerOperator"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:minWidth="40dp"
    android:layout_weight="1"
    app:srcCompat="@drawable/dot_cpo_cps_copy_5" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginStart="7dp"
    android:layout_weight="8"
    android:drawablePadding="10dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/itemChargerTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawablePadding="10dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="Kinross Park and Ride"
        android:textSize="18sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/itemChargerAddress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginStart="5dp"
            android:textSize="14sp"
            android:text="Junction Road" />
    </LinearLayout>
</LinearLayout>
</code>```

Title: Show three dots when TextView is too long

Body:
Your TextView shows three dots at the end but you can't see it, because your layout is beyond the edges of the screen. Change it's parent layout android:layout_weight to 8 to match the container android:weightSum=10 and you will see your dots.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/dialog_nearest_charger"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="40dp"
android:orientation="horizontal"
android:weightSum="10">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:minWidth="55dp"
    android:layout_weight="1"
    android:orientation="vertical">

    <TextView
        android:id="@+id/itemChargerDistance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textColor="@color/colorCoarseDistance"
        android:textStyle="bold"
        android:textSize="20sp"
        android:text="1.2" />

    <TextView
        android:id="@+id/itemChargerUnits"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="12sp"
        android:text="miles" />

</LinearLayout>

<ImageView
    android:id="@+id/itemChargerOperator"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:minWidth="40dp"
    android:layout_weight="1"
    app:srcCompat="@drawable/dot_cpo_cps_copy_5" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginStart="7dp"
    android:layout_weight="8"
    android:drawablePadding="10dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/itemChargerTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawablePadding="10dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="Kinross Park and Ride"
        android:textSize="18sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/itemChargerAddress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginStart="5dp"
            android:textSize="14sp"
            android:text="Junction Road" />
    </LinearLayout>
</LinearLayout>


问:
REST ASSURED (JAVA): Extract json object value given it's parent object value
Suppose I have the following json:

```<code>{
  "page": 2,
  "per_page": 3,
  "total": 12,
  "total_pages": 4,
  "data": [
 {
    "id": 4,
    "first_name": "Eve",
    "last_name": "Holt",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
},
{
    "id": 5,
    "first_name": "Charles",
    "last_name": "Morris",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"
},
{
    "id": 6,
    "first_name": "Tracey",
    "last_name": "Ramos",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"
}]}
</code>```

I would like to extract only the value of "first_name" which belongs to id = 6.

I can overcome this with something else, but I want to know if there is a straight way with restassured

Something I have tried so far:
data.find { it.id == '6' }.first_name

is it possible? If true, how to do that?
Thanks.

答:
Use below JsonPath, it will give you first_name based on id:</p>

```<code>[?(@.id ==4)].first_name
</code>```

Body:
Suppose I have the following json:

{
  "page": 2,
  "per_page": 3,
  "total": 12,
  "total_pages": 4,
  "data": [
 {
    "id": 4,
    "first_name": "Eve",
    "last_name": "Holt",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
},
{
    "id": 5,
    "first_name": "Charles",
    "last_name": "Morris",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"
},
{
    "id": 6,
    "first_name": "Tracey",
    "last_name": "Ramos",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"
}]}

I would like to extract only the value of "first_name" which belongs to id = 6.

I can overcome this with something else, but I want to know if there is a straight way with restassured

Something I have tried so far:
data.find { it.id == '6' }.first_name

is it possible? If true, how to do that?
Thanks.

Body:
Use below JsonPath, it will give you first_name based on id:

[?(@.id ==4)].first_name


问:
What is the use of overriding the finalize() method of Object class?
As far as I know , in java if we want to manually call the garbage collector we can do System.gc().

1.What are the operations that we do inside our overriden finalize() method?

2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?

答:
1.What are the operations that we do inside our overriden finalize() method?

Cleaning up resources that cannot be handled by garbage collection.

2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?

No, these two things are unrelated.

finalize should certainly not call the garbage collector itself. In fact, finalize is called by the garbage collector (but is not guaranteed to be called at all).