问:
how i can resolve the error postman 401 Unauthorized
I am developing the backend part for the registration of a user in my site.

the problem i have is when i want to test if my code works in postman i get the following error:

```<code>{
    "timestamp": "2020-05-29T13:38:13.114+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/adduser"
}
</code>```

I really don't know where this error can come from, here is the configuration code I put for spring security:

```<code>package com.app.habilitation.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure (HttpSecurity http) throws Exception {

        http.cors();
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/**").
        fullyAuthenticated().and().httpBasic();
    }

    @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
        .withUser("hr")
        .password("{noop}hr").roles("USER");
    }
}
</code>```

and this is my controller :

```<code>package com.app.habilitation.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.app.habilitation.entity.UserEntity;
import com.app.habilitation.service.UserService;

@SpringBootApplication
@RestController
@CrossOrigin(origins = "*")
public class UserController {

    private UserService userService;

    @Autowired
    public UserController (UserService theuserService) {
        userService=theuserService;
    }

    @GetMapping("/")
    public String login() {
        return "authenticaated succesfully";
    }

    @GetMapping("/getUsers")
    public String getUsers() {
        return "users";
    }

    @PostMapping("/addUser")
    public UserEntity addUser (@RequestBody UserEntity theUser) {

        userService.save(theUser);

        return theUser;
    }
}
</code>```

I added the cross origin to try to resolve my error but it does not work :( here is what I did as you could see in my controller:

```<code>@CrossOrigin(origins = "*")
</code>```

this is my dao using jpa :

```<code>package com.app.habilitation.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.app.habilitation.entity.UserEntity;

public interface UserDao extends JpaRepository<UserEntity, Integer> {

}
</code>```

and this is my entity class :

```<code>package com.app.habilitation.entity;

import java.sql.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="ORDO_DEP_UTILISATEUR")
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="IDENTIFIANT")
    private Integer IDENTIFIANT;

    /*@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="EMPLOI") */
    @Column(name="EMPLOI")
    private Integer emploi;

    /* @ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="ENTITE") */
    @Column(name="ENTITE")
    private Integer entite;

    @Column(name="LOGIN")
    private String login;

    @Column(name="MOTDEPASSE")
    private String mdp;

    @Column(name="nom")
    private String nom;

    @Column(name="prenom")
    private String prenom;

    @Column(name="CREERPAR")
    private Integer creerpar;

    @Column(name="ANNULEPAR")
    private Integer annulepar;

    @Column(name="STATUT")
    private String statut;

    @Column(name="DATEEFFET")
    private Date dateeffet;

    @Column(name="DATEFIN")
    private Date datefin;

    @Column(name="CREELE")
    private Date creele;

    @Column(name="MOTIFDEDESACTIVATION")
    private String motifdedesactivation;

    @Column(name="ANNULELE")
    private Date annulele;

    public Integer getIDENTIFIANT() {
        return IDENTIFIANT;
    }

    public void setIDENTIFIANT(Integer iDENTIFIANT) {
        IDENTIFIANT = iDENTIFIANT;
    }

    public Integer getEmploi() {
        return emploi;
    }

    public void setEmploi(Integer emploi) {
        this.emploi = emploi;
    }

    public Integer getEntite() {
        return entite;
    }

    public void setEntite(Integer entite) {
        this.entite = entite;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getMdp() {
        return mdp;
    }

    public void setMdp(String mdp) {
        this.mdp = mdp;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    public Integer getCreerpar() {
        return creerpar;
    }

    public void setCreerpar(Integer creerpar) {
        this.creerpar = creerpar;
    }

    public Integer getAnnulepar() {
        return annulepar;
    }

    public void setAnnulepar(Integer annulepar) {
        this.annulepar = annulepar;
    }

    public String getStatut() {
        return statut;
    }

    public void setStatut(String statut) {
        this.statut = statut;
    }

    public Date getDateeffet() {
        return dateeffet;
    }

    public void setDateeffet(Date dateeffet) {
        this.dateeffet = dateeffet;
    }

    public Date getDatefin() {
        return datefin;
    }

    public void setDatefin(Date datefin) {
        this.datefin = datefin;
    }

    public Date getCreele() {
        return creele;
    }

    public void setCreele(Date creele) {
        this.creele = creele;
    }

    public String getMotifdedesactivation() {
        return motifdedesactivation;
    }

    public void setMotifdedesactivation(String motifdedesactivation) {
        this.motifdedesactivation = motifdedesactivation;
    }

    public Date getAnnulele() {
        return annulele;
    }

    public void setAnnulele(Date annulele) {
        this.annulele = annulele;
    }

    public UserEntity(Integer iDENTIFIANT, Integer emploi, Integer entite, String login, String mdp, String nom,
            String prenom, Integer creerpar, Integer annulepar, String statut, Date dateeffet, Date datefin,
            Date creele, String motifdedesactivation, Date annulele) {
        IDENTIFIANT = iDENTIFIANT;
        this.emploi = emploi;
        this.entite = entite;
        this.login = login;
        this.mdp = mdp;
        this.nom = nom;
        this.prenom = prenom;
        this.creerpar = creerpar;
        this.annulepar = annulepar;
        this.statut = statut;
        this.dateeffet = dateeffet;
        this.datefin = datefin;
        this.creele = creele;
        this.motifdedesactivation = motifdedesactivation;
        this.annulele = annulele;
    }

    public UserEntity() {
    }

    @Override
    public String toString() {
        return "UserEntity [IDENTIFIANT=" + IDENTIFIANT + ", emploi=" + emploi + ", entite=" + entite + ", login="
                + login + ", mdp=" + mdp + ", nom=" + nom + ", prenom=" + prenom + ", creerpar=" + creerpar
                + ", annulepar=" + annulepar + ", statut=" + statut + ", dateeffet=" + dateeffet + ", datefin="
                + datefin + ", creele=" + creele + ", motifdedesactivation=" + motifdedesactivation + ", annulele="
                + annulele + "]";
    }

}
</code>```

this is my userService interface :

```<code>package com.app.habilitation.service;

import java.util.List;

import com.app.habilitation.entity.UserEntity;

public interface UserService {

    public void save (UserEntity theUser);

}
</code>```

and this is my userServiceImpl :

```<code>package com.app.habilitation.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.habilitation.dao.UserDao;
import com.app.habilitation.entity.UserEntity;

@Service
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    @Autowired

    public UserServiceImpl (UserDao theuserDao) {

        userDao = theuserDao;
    }

    @Override
    @Transactional
    public void save(UserEntity theUser) {

        userDao.save(theUser);

    }

}
</code>```

and this is my application.properties ( i change port 8080 to 8484 because a nother application use port 8080 and for info i use oracle 10g) :

```<code>spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=nawfel
spring.datasource.password=hr

server.port=8484
</code>```

can someone help me please ? :(

答:
Try changing The AuthenticationManagerBuilder code as given below :-

```<code> @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
        .withUser("hr")
        .password("hr").roles("USER");
    }
</code>```

And set user name password from postman same. username hr and password hr.

If you don't know how to do so follow this link :- https://harperdbhelp.zendesk.com/hc/en-us/articles/115010250207-Basic-Auth-with-Postman

Body:
I am developing the backend part for the registration of a user in my site.

the problem i have is when i want to test if my code works in postman i get the following error:

{
    "timestamp": "2020-05-29T13:38:13.114+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/adduser"
}

I really don't know where this error can come from, here is the configuration code I put for spring security:

package com.app.habilitation.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure (HttpSecurity http) throws Exception {

        http.cors();
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/**").
        fullyAuthenticated().and().httpBasic();
    }

    @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
        .withUser("hr")
        .password("{noop}hr").roles("USER");
    }
}

and this is my controller :

package com.app.habilitation.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.app.habilitation.entity.UserEntity;
import com.app.habilitation.service.UserService;

@SpringBootApplication
@RestController
@CrossOrigin(origins = "*")
public class UserController {

    private UserService userService;

    @Autowired
    public UserController (UserService theuserService) {
        userService=theuserService;
    }

    @GetMapping("/")
    public String login() {
        return "authenticaated succesfully";
    }

    @GetMapping("/getUsers")
    public String getUsers() {
        return "users";
    }

    @PostMapping("/addUser")
    public UserEntity addUser (@RequestBody UserEntity theUser) {

        userService.save(theUser);

        return theUser;
    }
}

I added the cross origin to try to resolve my error but it does not work :( here is what I did as you could see in my controller:

@CrossOrigin(origins = "*")

this is my dao using jpa :

package com.app.habilitation.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.app.habilitation.entity.UserEntity;

public interface UserDao extends JpaRepository<UserEntity, Integer> {

}

and this is my entity class :

package com.app.habilitation.entity;

import java.sql.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="ORDO_DEP_UTILISATEUR")
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="IDENTIFIANT")
    private Integer IDENTIFIANT;

    /*@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="EMPLOI") */
    @Column(name="EMPLOI")
    private Integer emploi;

    /* @ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="ENTITE") */
    @Column(name="ENTITE")
    private Integer entite;

    @Column(name="LOGIN")
    private String login;

    @Column(name="MOTDEPASSE")
    private String mdp;

    @Column(name="nom")
    private String nom;

    @Column(name="prenom")
    private String prenom;

    @Column(name="CREERPAR")
    private Integer creerpar;

    @Column(name="ANNULEPAR")
    private Integer annulepar;

    @Column(name="STATUT")
    private String statut;

    @Column(name="DATEEFFET")
    private Date dateeffet;

    @Column(name="DATEFIN")
    private Date datefin;

    @Column(name="CREELE")
    private Date creele;

    @Column(name="MOTIFDEDESACTIVATION")
    private String motifdedesactivation;

    @Column(name="ANNULELE")
    private Date annulele;

    public Integer getIDENTIFIANT() {
        return IDENTIFIANT;
    }

    public void setIDENTIFIANT(Integer iDENTIFIANT) {
        IDENTIFIANT = iDENTIFIANT;
    }

    public Integer getEmploi() {
        return emploi;
    }

    public void setEmploi(Integer emploi) {
        this.emploi = emploi;
    }

    public Integer getEntite() {
        return entite;
    }

    public void setEntite(Integer entite) {
        this.entite = entite;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getMdp() {
        return mdp;
    }

    public void setMdp(String mdp) {
        this.mdp = mdp;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    public Integer getCreerpar() {
        return creerpar;
    }

    public void setCreerpar(Integer creerpar) {
        this.creerpar = creerpar;
    }

    public Integer getAnnulepar() {
        return annulepar;
    }

    public void setAnnulepar(Integer annulepar) {
        this.annulepar = annulepar;
    }

    public String getStatut() {
        return statut;
    }

    public void setStatut(String statut) {
        this.statut = statut;
    }

    public Date getDateeffet() {
        return dateeffet;
    }

    public void setDateeffet(Date dateeffet) {
        this.dateeffet = dateeffet;
    }

    public Date getDatefin() {
        return datefin;
    }

    public void setDatefin(Date datefin) {
        this.datefin = datefin;
    }

    public Date getCreele() {
        return creele;
    }

    public void setCreele(Date creele) {
        this.creele = creele;
    }

    public String getMotifdedesactivation() {
        return motifdedesactivation;
    }

    public void setMotifdedesactivation(String motifdedesactivation) {
        this.motifdedesactivation = motifdedesactivation;
    }

    public Date getAnnulele() {
        return annulele;
    }

    public void setAnnulele(Date annulele) {
        this.annulele = annulele;
    }

    public UserEntity(Integer iDENTIFIANT, Integer emploi, Integer entite, String login, String mdp, String nom,
            String prenom, Integer creerpar, Integer annulepar, String statut, Date dateeffet, Date datefin,
            Date creele, String motifdedesactivation, Date annulele) {
        IDENTIFIANT = iDENTIFIANT;
        this.emploi = emploi;
        this.entite = entite;
        this.login = login;
        this.mdp = mdp;
        this.nom = nom;
        this.prenom = prenom;
        this.creerpar = creerpar;
        this.annulepar = annulepar;
        this.statut = statut;
        this.dateeffet = dateeffet;
        this.datefin = datefin;
        this.creele = creele;
        this.motifdedesactivation = motifdedesactivation;
        this.annulele = annulele;
    }

    public UserEntity() {
    }

    @Override
    public String toString() {
        return "UserEntity [IDENTIFIANT=" + IDENTIFIANT + ", emploi=" + emploi + ", entite=" + entite + ", login="
                + login + ", mdp=" + mdp + ", nom=" + nom + ", prenom=" + prenom + ", creerpar=" + creerpar
                + ", annulepar=" + annulepar + ", statut=" + statut + ", dateeffet=" + dateeffet + ", datefin="
                + datefin + ", creele=" + creele + ", motifdedesactivation=" + motifdedesactivation + ", annulele="
                + annulele + "]";
    }

}

this is my userService interface :

package com.app.habilitation.service;

import java.util.List;

import com.app.habilitation.entity.UserEntity;

public interface UserService {

    public void save (UserEntity theUser);

}

and this is my userServiceImpl :

package com.app.habilitation.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.habilitation.dao.UserDao;
import com.app.habilitation.entity.UserEntity;

@Service
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    @Autowired

    public UserServiceImpl (UserDao theuserDao) {

        userDao = theuserDao;
    }

    @Override
    @Transactional
    public void save(UserEntity theUser) {

        userDao.save(theUser);

    }

}

and this is my application.properties ( i change port 8080 to 8484 because a nother application use port 8080 and for info i use oracle 10g) :

spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=nawfel
spring.datasource.password=hr

server.port=8484

can someone help me please ? :(

Body:
Try changing The AuthenticationManagerBuilder code as given below :-

 @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
        .withUser("hr")
        .password("hr").roles("USER");
    }

And set user name password from postman same. username hr and password hr.

If you don't know how to do so follow this link :- https://harperdbhelp.zendesk.com/hc/en-us/articles/115010250207-Basic-Auth-with-Postman


来源: stackexchange

答:
In theory, there could be various reasons. However, there's one thing in this example that definitely requires clarification.

Sparse categorical crossentropy is expecting you to feed probabilities (values from 0 to 1) for the predictions, unless you instantiate it with from_logits=True. Your last layer, however, has no activation specified. So the output values are not restricted to [0,1].

I would start with changing the last layer to model.add(keras.layers.Dense(2, activation='softmax')). And then ensure that your ground truth class labels are fed in the correct format (according to https://www.tensorflow.org/api_docs/python/tf/keras/losses/sparse_categorical_crossentropy).

ContentLicense: CC BY-SA 4.0

Title: tensorflow keras model predicts similar value for every test

Body:
I'm trying to do a binary classification with an RNN with tensorflow. The labels of m y training and test data are 0 and 1. When I try to use my RNN on my finished model, it returns almost the same predictions for every single sample:

model.predict(holdout_x[400:500])

array([[-4.116061 , -1.3410028],
   [-4.1405125, -1.3521721],
   [-4.171639 , -1.3665637],
   [-4.1515126, -1.356805 ],
   [-4.1466017, -1.3546   ],
   [-4.1306634, -1.3479614],
   [-4.1259437, -1.3455958],
   [-4.1161146, -1.3414239],
   [-4.135389 , -1.3504343],
   [-4.1410503, -1.3527975],
   [-4.1413574, -1.3528765],
   [-4.1483955, -1.3562942],
   [-4.208541 , -1.383785 ],
   [-4.212775 , -1.3856986],
   [-4.2415767, -1.3998709],
   [-4.250041 , -1.4033642],
   [-4.2150397, -1.3866954],
   [-4.2094893, -1.3843822],
   [-4.1996937, -1.380172 ],
   [-4.0357003, -1.3077384],
   [-4.030937 , -1.3050178],
   [-4.0273657, -1.3041242],
   [-4.0044518, -1.2939129],
   [-4.003211 , -1.2922926],
   [-4.015193 , -1.2991027],
   [-3.9627366, -1.2757865],
   [-3.9252415, -1.2586563],
   [-3.936089 , -1.265475 ],
   [-3.8994193, -1.2497959],
   [-3.918683 , -1.2593002],
   [-3.7673016, -1.1924615],
   [-3.7568831, -1.1912583]], dtype=float32)

This is how my model looks:

model = tf.keras.Sequential()

model.add(keras.layers.LSTM(200, input_shape=(200, 7), return_sequences=True))

model.add(keras.layers.LSTM(200, input_shape=(200, 7), return_sequences=True))

model.add(keras.layers.LSTM(200))

# Add a Dense layer with 10 units.
model.add(keras.layers.Dense(2))

model.summary()

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

How can I prevent this from happening?


问:
How can I redirect to homepage window.location= 'URL'?
I'm trying to redirect my users back to my homepage. I've written the following JavaScript code, but it isn't working. I'm not sure what I'm doing wrong.

var app = {
  paused: 0,
  init: function() {
    // add full screen object
    $('body').prepend('

');
    //if mouse moves hide object
    $(document).mousemove(function(e) {
      $('#cover').hide();
    })

    // check every 5 seconds to see if object has been hidden by mouse move
    var int = setInterval(function() {
      if ($('#cover').is(":hidden")) {
        $('#cover').show();
        app.paused = 0;
      } else {
        app.paused += 5;
      }
      //if mouse hasn't moved, go back to main page
      if (app.paused >= 15) {
        window.location = 'https://www.google.com/';
      }
      console.log(app.paused);
    }, 5000);

  }
}

$(document).ready(function() {
  app.init();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

答:
```<code> if(app.paused >= 15){
       window.location = '/';
        }
</code>```

This worked!

```<code>$(document).ready(function() {
 // app.init();
 });
</code>```

app.init() was also commented out. Uncommented it and it works now.

Body:
 if(app.paused >= 15){
       window.location = '/';
        }

This worked!

$(document).ready(function() {
 // app.init();
 });

app.init() was also commented out. Uncommented it and it works now.


问:
PowerManager.isIgnoringBatteryOptimizations always returns true even if is removed from 'Not optimized apps'
I have a mileage logbook app which does GPS tracking and is able to establish a OBDII connection to a car in background.

Now I want to show a Popup which informs the users if my app is not whitelisted in doze since this may stop my background (actually foreground) services...

I do:

```<code> String PACKAGE_NAME = getApplicationContext().getPackageName();
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            boolean status = false;
            status = pm.isIgnoringBatteryOptimizations(PACKAGE_NAME);

            if (!status) {
                // show popup
            }
</code>```

but PowerManager.isIgnoringBatteryOptimizations always returns 'true' even if it is removed from 'Not optimized apps' again. Only if I uninstall the app 'false' is returned again...
Tested on Galaxy Note 8 (Android 8.0) and Emulator 8.1

Question is simple: Is this a bug? Or how to remove the app from whitelist so that PowerManager.isIgnoringBatteryOptimizations is returnung 'false' again?

答:
I have made simple one activity app that requests

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

and put this code into onCreate

```<code>    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent();
    String packageName = this.getPackageName();
    PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    if (pm.isIgnoringBatteryOptimizations(packageName))
        intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
    else {
        intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + packageName));
    }
    this.startActivity(intent);
}
</code>```

I have tested it on 8.1 emulator and I got the same behavior. You can possibly unisntall app or switch its state from optimized to not optimized in all app list in settings. I guess Bob Snyder showed right issue in google tracker.

Body:
I have a mileage logbook app which does GPS tracking and is able to establish a OBDII connection to a car in background.

Now I want to show a Popup which informs the users if my app is not whitelisted in doze since this may stop my background (actually foreground) services...

I do:

 String PACKAGE_NAME = getApplicationContext().getPackageName();
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            boolean status = false;
            status = pm.isIgnoringBatteryOptimizations(PACKAGE_NAME);

            if (!status) {
                // show popup
            }

but PowerManager.isIgnoringBatteryOptimizations always returns 'true' even if it is removed from 'Not optimized apps' again. Only if I uninstall the app 'false' is returned again...
Tested on Galaxy Note 8 (Android 8.0) and Emulator 8.1

Question is simple: Is this a bug? Or how to remove the app from whitelist so that PowerManager.isIgnoringBatteryOptimizations is returnung 'false' again?

Body:
I have made simple one activity app that requests

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

and put this code into onCreate

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent();
    String packageName = this.getPackageName();
    PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    if (pm.isIgnoringBatteryOptimizations(packageName))
        intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
    else {
        intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + packageName));
    }
    this.startActivity(intent);
}

I have tested it on 8.1 emulator and I got the same behavior. You can possibly unisntall app or switch its state from optimized to not optimized in all app list in settings. I guess Bob Snyder showed right issue in google tracker.


问:
what are name lookup rules within the hypothetical declaration that required in some contexts
Issues 1:

int v = 10;
auto f = [v = v](){};
```

<p>Consider the above code,some rules mentioned in the standard will work for it.    </p>

<p>[expr.prim.lambda.capture#6] </p>

<blockquote>
  <p>An init-capture behaves as if it declares and explicitly captures a variable of the form “auto init-capture ;” whose declarative region is the lambda-expression's compound-statement.   </p>
</blockquote>

<p>The quote means that <code>auto v = v;</code> would be declared in the lambda's compound-statement as if it like this:   </p>

<pre class="lang-cpp prettyprint-override"><code>//hypothetical code
int v = 10;
auto f = [](){
  auto v = v;  //the second `v` is the first `v` and will be initialized by an indetermined value.
};
</code>```

So,For the hypothetical declaration auto v = v;,I think it will conflict with the following rules.

[basic.scope.pdecl#1]

The point of declaration for a name is immediately after its complete declarator and before its initializer (if any)  [ Example:

  unsigned char x = 12;

  { unsigned char x = x; }

  Here the second x is initialized with its own (indeterminate) value.  — end example ]

Issue 2:

void func(int v){}
int v = 0;
func(v);
```

<p>We know the initialization of the function's parameter will occur within the context of the calling function and it will be copy-initialization.We ignore the quotes in the standard,because they are too much.So the copy-initialization of parameter will appear in somewhere within the context of the calling function as if it likes such form:    </p>

<pre class="lang-cpp prettyprint-override"><code>//hypothetical code
int v = v; // initialization of a parameter that occured in somewhere within context of calling function
</code>```

The same issue like issue 1,how to interpret these issues when the name of the declarator-id is the same as that of the  id-expression that within a initializer when they occured in these hypothetical copy-initialization contexts.Does these hypothetical copy-initializations contradict with the rule [basic.scope.pdecl#1]

Question:

I wonder that Is the lookup for the id-expression within initializer preceded than the hypothetical declaration occures? why do I think so? because, as the opposite, During the usual declaration, the lookup for initializer occures after the declarator immediately complete, as said in [basic.scope.pdecl#1], It means the declarator-id would hide the id-expression that within the initializer if they are the same name.

Is there any quote in the standard interpret this?

答:
initializer in [basic.scope.pdecl] refers to an element of a grammar rule, that is used by the parser. It is defined in [dlc.init] and it appears in the init-declarator grammar rule.

For the case of the lambda capture, the standard specifies that it is equivalent to an init-declarator but whose declarative region is the lambda-expression's compound-statement[...] that is, the capture name is not in the scope of the initializer.

The term initialization does not refer to the grammar rule referred by the term initilizer. initialization is an expression evaluation that initialize a variable, this is not a grammar rule. The rules which involve those two terms cannot conflict because they are not part of the same phase of the compilation->execution process:

1) The grammar rules for initializer, declarator, or init-caputure, etc... are used to determine to which object refers an id-expression (a name within an expression) that appears within an initializer. An id-expression is a glvalue. A glvalue referes to an object, and it has no name.

2) Then those glvalues are parts of the expression that perform initialization. When this initialization takes place, names are irrelevant.

NB: In the standard, many rules referrers to grammar rules and you should take care of the formatting to recognize them, because their name has no more sense in itself than the name of a variables that appear inside mathematical equations.

Body:
Issues 1:

int v = 10;
auto f = [v = v](){};

Consider the above code,some rules mentioned in the standard will work for it.

[expr.prim.lambda.capture#6]

An init-capture behaves as if it declares and explicitly captures a variable of the form “auto init-capture ;” whose declarative region is the lambda-expression's compound-statement.

The quote means that auto v = v; would be declared in the lambda's compound-statement as if it like this:

//hypothetical code
int v = 10;
auto f = [](){
  auto v = v;  //the second `v` is the first `v` and will be initialized by an indetermined value.
};

So,For the hypothetical declaration auto v = v;,I think it will conflict with the following rules.

[basic.scope.pdecl#1]

The point of declaration for a name is immediately after its complete declarator and before its initializer (if any)  [ Example:

  unsigned char x = 12;

  { unsigned char x = x; }

  Here the second x is initialized with its own (indeterminate) value.  — end example ]

Issue 2:

void func(int v){}
int v = 0;
func(v);

We know the initialization of the function's parameter will occur within the context of the calling function and it will be copy-initialization.We ignore the quotes in the standard,because they are too much.So the copy-initialization of parameter will appear in somewhere within the context of the calling function as if it likes such form:

//hypothetical code
int v = v; // initialization of a parameter that occured in somewhere within context of calling function

The same issue like issue 1,how to interpret these issues when the name of the declarator-id is the same as that of the  id-expression that within a initializer when they occured in these hypothetical copy-initialization contexts.Does these hypothetical copy-initializations contradict with the rule [basic.scope.pdecl#1]

Question:

I wonder that Is the lookup for the id-expression within initializer preceded than the hypothetical declaration occures? why do I think so? because, as the opposite, During the usual declaration, the lookup for initializer occures after the declarator immediately complete, as said in [basic.scope.pdecl#1], It means the declarator-id would hide the id-expression that within the initializer if they are the same name.

Is there any quote in the standard interpret this?


问:
How do i correctly call API with ajax in Cordova?
I have a cordova weather app where I call an API which returns a JSON file with weather data. But every time i call the API with ajax it returns 404, but if i copy the same url in the browser it works.

Here's the part of the code where i call the API(the url is set before):

```<code>$.ajax({
    type: 'GET',
    url: url,
    data: {
        format: 'json'
    },
    dataType: 'jsonp',
    success: function(data, status){
        console.log(data);
    },
    error: function(data, status) {
        console.log(data.status);
    }
});
</code>```

答:
From my comment:

Are you including https:// in the url? or just api... as you have here?

Try https://api.openweathermap.org/data/2.5/weather?q=london&appid=b3a1cd2134e9f28c43beacab95ea8a1a

Cordova or jQuery may or may not prepend http:// or https:// to scheme-free URLS

Body:
I have a cordova weather app where I call an API which returns a JSON file with weather data. But every time i call the API with ajax it returns 404, but if i copy the same url in the browser it works.

Here's the part of the code where i call the API(the url is set before):

$.ajax({
    type: 'GET',
    url: url,
    data: {
        format: 'json'
    },
    dataType: 'jsonp',
    success: function(data, status){
        console.log(data);
    },
    error: function(data, status) {
        console.log(data.status);
    }
});


问:
Autowiring in Quartz multiple Jobs with Spring Boot not working
I'm try to use quartz scheduler in spring. I get below exception when configuring multiple jobs

Parameter 0 of method jobTrigger in Job2 required a bean of type 'org.quartz.JobDetail' that could not be found.

quartz - v2.3, Spring - v4.2.x

Config Class

```<code>@Configuration
 public class SchedulerConfig {

private static final Logger LOG = LoggerFactory.getLogger(SchedulerConfig.class);

@Autowired
List<Trigger> triggers;

@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    return jobFactory;
}

@Bean
public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory)  throws IOException {
    SchedulerFactoryBean factory = new SchedulerFactoryBean();
          factory.setAutoStartup(true);
    factory.setJobFactory(jobFactory);
         factory.setQuartzProperties(quartzProperties());
    if (triggers != null && !triggers.isEmpty()) {
         LOG.info("starting jobs... Total Triggers - " + triggers.size());
        factory.setTriggers(triggers.toArray(new Trigger[triggers.size()]));
    }

    return factory;
}

@Bean
public Properties quartzProperties() throws IOException {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
    propertiesFactoryBean.afterPropertiesSet();
    return propertiesFactoryBean.getObject();
}

public static CronTriggerFactoryBean createCronTrigger(JobDetail jobDetail, String cronExpression) {
    CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
    factoryBean.setJobDetail(jobDetail);
    factoryBean.setCronExpression(cronExpression);
    factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
    return factoryBean;
}

public static JobDetailFactoryBean createJobDetail(Class jobClass) {
    JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
    factoryBean.setJobClass(jobClass);
    factoryBean.setDurability(true);
    return factoryBean;
}
</code>```

SpringBeanJobFactory

```<code>public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

private static final Logger LOG = LoggerFactory.getLogger(AutowiringSpringBeanJobFactory.class);

private transient AutowireCapableBeanFactory beanFactory;

@Override
public void setApplicationContext(final ApplicationContext context) {
    beanFactory = context.getAutowireCapableBeanFactory();
}

@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    final Object job = super.createJobInstance(bundle);
    LOG.info("create job instance");
    beanFactory.autowireBean(job);
    return job;
}
</code>```

}

Job 1

```<code>@Component
@DisallowConcurrentExecution
public class Job1 implements Job {

private final Logger log = LoggerFactory.getLogger(this.getClass());

@Value("${schedule}")
private String frequency;

@Autowired
private Service service;

@Override
public void execute(JobExecutionContext jobExecutionContext) {
    log.info("execute");
}

@Bean(name = "jobBean1")
public JobDetailFactoryBean job() {
    return SchedulerConfig.createJobDetail(this.getClass());
}

@Bean(name = "jobBean1Trigger")
public CronTriggerFactoryBean jobTrigger(@Qualifier("jobBean1")JobDetail jobDetail) {
    return SchedulerConfig.createCronTrigger(jobDetail, frequency);
}
</code>```

Job 2

```<code>@Component
@DisallowConcurrentExecution
public class Job2 implements Job {

private final Logger log = LoggerFactory.getLogger(this.getClass());

@Value("${schedule}")
private String frequency;

@Autowired
private Service service;

@Override
public void execute(JobExecutionContext jobExecutionContext) {
    log.info("execute");
}

@Bean(name = "jobBean2")
public JobDetailFactoryBean job() {
    return SchedulerConfig.createJobDetail(this.getClass());
}

@Bean(name = "jobBean2Trigger")
public CronTriggerFactoryBean jobTrigger(@Qualifier("jobBean2")JobDetail jobDetail) {
    return SchedulerConfig.createCronTrigger(jobDetail, frequency);
}
</code>```

The Service class has Spring JPA repos.
The root cause of the problem is the below autowired service. If I remove the below autowired service from both the jobs, it works fine.

@Autowired
    private Service service;

If there is only one job with this autowired bean, then there is no exception.
How to configure multiple jobs using the same autowired dependency?
What is cause this issue?

答:
I had the same issue, but it got resolved now

```<code>package com.crif.credity.config;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

public class SchedulerJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
    private AutowireCapableBeanFactory beanFacotry;

    @Override
    protected Object createJobInstance(TriggerFiredBundle triggerBundle) throws Exception {
        Object createJobInstance = super.createJobInstance(triggerBundle);
        beanFacotry.autowireBean(createJobInstance);
        return createJobInstance;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        beanFacotry = applicationContext.getAutowireCapableBeanFactory();
    }

}
</code>```

in configuration java file you can create below bean

```<code>@Autowired
    private ApplicationContext applicationContext;

/** The data source. */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerJobFactory jobFactory = new SchedulerJobFactory();
        jobFactory.setApplicationContext(applicationContext);

        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        factoryBean.setOverwriteExistingJobs(true);
        factoryBean.setJobFactory(jobFactory);
        return factoryBean;
    }
</code>```

after this in implementation of job class . you can use autowired

```<code>package com.crif.credity.jobs;

public class Test implements Job  {

    @Autowired
    private BatchClientService batchClientService;

    @Override
public void execute(JobExecutionContext context) throws JobExecutionException{
        try {
            batchClientService.executeJob(CredityJob.NEWSCHECK, instanceId);
        } catch (Exception ex) {
            LOG.info(ex.getMessage());
        }
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm try to use quartz scheduler in spring. I get below exception when configuring multiple jobs

Parameter 0 of method jobTrigger in Job2 required a bean of type 'org.quartz.JobDetail' that could not be found.

quartz - v2.3, Spring - v4.2.x

Config Class

@Configuration
 public class SchedulerConfig {

private static final Logger LOG = LoggerFactory.getLogger(SchedulerConfig.class);

@Autowired
List<Trigger> triggers;

@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    return jobFactory;
}

@Bean
public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory)  throws IOException {
    SchedulerFactoryBean factory = new SchedulerFactoryBean();
          factory.setAutoStartup(true);
    factory.setJobFactory(jobFactory);
         factory.setQuartzProperties(quartzProperties());
    if (triggers != null && !triggers.isEmpty()) {
         LOG.info("starting jobs... Total Triggers - " + triggers.size());
        factory.setTriggers(triggers.toArray(new Trigger[triggers.size()]));
    }

    return factory;
}

@Bean
public Properties quartzProperties() throws IOException {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
    propertiesFactoryBean.afterPropertiesSet();
    return propertiesFactoryBean.getObject();
}

public static CronTriggerFactoryBean createCronTrigger(JobDetail jobDetail, String cronExpression) {
    CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
    factoryBean.setJobDetail(jobDetail);
    factoryBean.setCronExpression(cronExpression);
    factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
    return factoryBean;
}

public static JobDetailFactoryBean createJobDetail(Class jobClass) {
    JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
    factoryBean.setJobClass(jobClass);
    factoryBean.setDurability(true);
    return factoryBean;
}

SpringBeanJobFactory

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

private static final Logger LOG = LoggerFactory.getLogger(AutowiringSpringBeanJobFactory.class);

private transient AutowireCapableBeanFactory beanFactory;

@Override
public void setApplicationContext(final ApplicationContext context) {
    beanFactory = context.getAutowireCapableBeanFactory();
}

@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    final Object job = super.createJobInstance(bundle);
    LOG.info("create job instance");
    beanFactory.autowireBean(job);
    return job;
}

}

Job 1

@Component
@DisallowConcurrentExecution
public class Job1 implements Job {

private final Logger log = LoggerFactory.getLogger(this.getClass());

@Value("${schedule}")
private String frequency;

@Autowired
private Service service;

@Override
public void execute(JobExecutionContext jobExecutionContext) {
    log.info("execute");
}

@Bean(name = "jobBean1")
public JobDetailFactoryBean job() {
    return SchedulerConfig.createJobDetail(this.getClass());
}

@Bean(name = "jobBean1Trigger")
public CronTriggerFactoryBean jobTrigger(@Qualifier("jobBean1")JobDetail jobDetail) {
    return SchedulerConfig.createCronTrigger(jobDetail, frequency);
}

Job 2

@Component
@DisallowConcurrentExecution
public class Job2 implements Job {

private final Logger log = LoggerFactory.getLogger(this.getClass());

@Value("${schedule}")
private String frequency;

@Autowired
private Service service;

@Override
public void execute(JobExecutionContext jobExecutionContext) {
    log.info("execute");
}

@Bean(name = "jobBean2")
public JobDetailFactoryBean job() {
    return SchedulerConfig.createJobDetail(this.getClass());
}

@Bean(name = "jobBean2Trigger")
public CronTriggerFactoryBean jobTrigger(@Qualifier("jobBean2")JobDetail jobDetail) {
    return SchedulerConfig.createCronTrigger(jobDetail, frequency);
}

The Service class has Spring JPA repos.
The root cause of the problem is the below autowired service. If I remove the below autowired service from both the jobs, it works fine.

@Autowired
    private Service service;

If there is only one job with this autowired bean, then there is no exception.
How to configure multiple jobs using the same autowired dependency?
What is cause this issue?

Body:
I had the same issue, but it got resolved now

package com.crif.credity.config;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

public class SchedulerJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
    private AutowireCapableBeanFactory beanFacotry;

    @Override
    protected Object createJobInstance(TriggerFiredBundle triggerBundle) throws Exception {
        Object createJobInstance = super.createJobInstance(triggerBundle);
        beanFacotry.autowireBean(createJobInstance);
        return createJobInstance;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        beanFacotry = applicationContext.getAutowireCapableBeanFactory();
    }

}

in configuration java file you can create below bean

@Autowired
    private ApplicationContext applicationContext;

/** The data source. */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerJobFactory jobFactory = new SchedulerJobFactory();
        jobFactory.setApplicationContext(applicationContext);

        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        factoryBean.setOverwriteExistingJobs(true);
        factoryBean.setJobFactory(jobFactory);
        return factoryBean;
    }

after this in implementation of job class . you can use autowired

package com.crif.credity.jobs;

public class Test implements Job  {

    @Autowired
    private BatchClientService batchClientService;

    @Override
public void execute(JobExecutionContext context) throws JobExecutionException{
        try {
            batchClientService.executeJob(CredityJob.NEWSCHECK, instanceId);
        } catch (Exception ex) {
            LOG.info(ex.getMessage());
        }
    }

}


问:
How to start remote celery workers from django
I'm trying to use django in combination with celery.

Therefore I came across autodiscover_tasks() and I'm not fully sure on how to use them. The celery workers get tasks added by other applications (in this case a node backend).

So far I used this to start the worker:

```<code>celery worker -Q extraction --hostname=extraction_worker
</code>```

which works fine.

Now I'm not sure what the general idea of the django-celery integration is. Should workers still be started from external (e.g. with the command above), or should they be managed and started from the django application?

My celery.py looks like:

```<code># set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings')

app = Celery('app')

app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
</code>```

then I have 2 apps containing a tasks.py file with:

```<code>@shared_task
def extraction(total):
    return 'Task executed'
</code>```

how can I now register django to register the worker for those tasks?

答:
You just start worker process as documented, you don't need to register anything else

In a production environment you’ll want to run the worker in the
  background as a daemon - see Daemonization - but for testing and
  development it is useful to be able to start a worker instance by
  using the celery worker manage command, much as you’d use Django’s
  manage.py runserver:

```<code>celery -A proj worker -l info
</code>```

For a complete listing of the command-line options available, use the
  help command:

```<code>celery help
</code>```

celery worker collects/registers task when it runs and also consumes tasks which it found out

Body:
I'm trying to use django in combination with celery.

Therefore I came across autodiscover_tasks() and I'm not fully sure on how to use them. The celery workers get tasks added by other applications (in this case a node backend).

So far I used this to start the worker:

celery worker -Q extraction --hostname=extraction_worker

which works fine.

Now I'm not sure what the general idea of the django-celery integration is. Should workers still be started from external (e.g. with the command above), or should they be managed and started from the django application?

My celery.py looks like:

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings')

app = Celery('app')

app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

then I have 2 apps containing a tasks.py file with:

@shared_task
def extraction(total):
    return 'Task executed'

how can I now register django to register the worker for those tasks?

Body:
You just start worker process as documented, you don't need to register anything else

In a production environment you’ll want to run the worker in the
  background as a daemon - see Daemonization - but for testing and
  development it is useful to be able to start a worker instance by
  using the celery worker manage command, much as you’d use Django’s
  manage.py runserver:

celery -A proj worker -l info

For a complete listing of the command-line options available, use the
  help command:

celery help

celery worker collects/registers task when it runs and also consumes tasks which it found out


问:
Automatic reboot on systemd emergency mode?
Is it possible that, when systemd enters emergency mode, instead of prompting :

```<code>You are in emergency mode. After logging in, type "journalctl -xb" to view
system logs, "systemctl reboot" to reboot, "systemctl default" or "exit"
to boot into default mode.
Press Enter for maintenance
(or press Control-D to continue):
</code>```

and waiting for a user input, it automatically reboots after a delay ?

This would be needed in my case because I'm working on rollbacking the operating system to a previous state in case of a boot failure.

This would have to happen whatever the issue there is with the current operating system trying to boot. I haven't found anything about this yet, so any suggestion would be helpful!

Thanks

答:
Well I've found a way to do what I wanted. I've overriden the emergency service with systemctl edit emergency.service and added :

```<code>[Service]
ExecStartPre=/bin/sh -c "read -t 30 || /bin/systemctl reboot"
</code>```

which will wait for a user input to enter emergency mode. Otherwise, the system reboots.

This also works for the rescue mode, by doing systemctl edit rescue.service.

Body:
Is it possible that, when systemd enters emergency mode, instead of prompting :

You are in emergency mode. After logging in, type "journalctl -xb" to view
system logs, "systemctl reboot" to reboot, "systemctl default" or "exit"
to boot into default mode.
Press Enter for maintenance
(or press Control-D to continue):

and waiting for a user input, it automatically reboots after a delay ?

This would be needed in my case because I'm working on rollbacking the operating system to a previous state in case of a boot failure.

This would have to happen whatever the issue there is with the current operating system trying to boot. I haven't found anything about this yet, so any suggestion would be helpful!

Thanks

Body:
Well I've found a way to do what I wanted. I've overriden the emergency service with systemctl edit emergency.service and added :

[Service]
ExecStartPre=/bin/sh -c "read -t 30 || /bin/systemctl reboot"

which will wait for a user input to enter emergency mode. Otherwise, the system reboots.

This also works for the rescue mode, by doing systemctl edit rescue.service.


问:
A problem with web scraping using python ,BeautifulSoup and pandas 'read_html'
Thank you for the helpers !

I am scraping a table of data about covid19 and push it into a pandas data frame , it was working until this morning .

That the code :

```<code>import pandas as pd
import requests
from bs4 import BeautifulSoup

url = 'https://www.worldometers.info/coronavirus/'

req = requests.get(url)

page = BeautifulSoup(req.content, 'html.parser')

table = page.find_all('table',id="main_table_countries_today")[0]

print(table)

df = pd.read_html(str(table))[0]
</code>```

This morning I starting to get the next error :

```<code>ValueError: No tables found matching pattern '.+'
</code>```

Can you please help me figure it out ?

答:
Try changing the last line to: df = pd.read_html(str(table), displayed_only=False)[0]
The table header at the url has changed its style attribute to style="width:100%;margin-top: 0px !important;display:none;".  Previously it did not have the 'display' tag set.

Body:
Thank you for the helpers !

I am scraping a table of data about covid19 and push it into a pandas data frame , it was working until this morning .

That the code :

import pandas as pd
import requests
from bs4 import BeautifulSoup

url = 'https://www.worldometers.info/coronavirus/'

req = requests.get(url)

page = BeautifulSoup(req.content, 'html.parser')

table = page.find_all('table',id="main_table_countries_today")[0]

print(table)

df = pd.read_html(str(table))[0]

This morning I starting to get the next error :

ValueError: No tables found matching pattern '.+'

Can you please help me figure it out ?


问:
How to Navigate and Scroll to an Element with ID in a Next.js Page wrapped with AnimatePresence
I am using Framer Motion to animate Next.js page transitions. However using the using AnimatePresence breaks the hash link navigation and the page no longer goes to the targeted id element.

The page transitions are perfect until you want to navigate to a harsh ID on the page :(

```<code>// I have a link component setup like this
// index.tsx
<Link href="/about#the-team" scroll={false}>
  <a>The Team</a>
</Link>

// Targeting another page `about.tsx` with the id
// about.tsx

{/* ...many sections before.. */}
<section id="the-team">{content}</section>
</code>```

I have a custom _app.tsx as shown below.

```<code>// _app.tsx
import { AppProps } from 'next/app';
import { useRouter } from 'next/router';
import { AnimatePresence } from 'framer-motion';

const MyApp = ({ Component, pageProps }: AppProps): JSX.Element => {
  const router = useRouter();
  return (
    <AnimatePresence exitBeforeEnter>
      <Component {...pageProps} key={router.route} />
    </AnimatePresence>
  );
};

export default MyApp;

</code>```

I am expecting to go directly to the section with id="the-team" but it won't work. A refresh of the page with the hash link shows that it's originally at the target element but quickly jumps to the top. It's so fast and easy to miss. How do I retain the page transitions but still be able to navigate to hash id?

答:
The Culprit is the exitBeforeEnter
prop on on AnimatePresence. Removing the prop fixes the hash id navigation but breaks some of my use-case.

If set to true, AnimatePresence will only render one component at a time. The exiting component will finish its exit animation before the entering component is rendered.
  - framer-motion docs

I couldn't just remove the exitBeforeEnter prop as I had included it to fix a bug I had where targeting a node in the entering page collided with the identical one in the old instance of the exiting page. For example a ref logic on an animated svg header in the exiting Page colliding with the entering page's header svg ref logic.

To get the best of both worlds, Using the onExitComplete
that "Fires when all exiting nodes have completed animating out", I passed it a callback that checks for the hash from the widow.location.hash and smooth scrolls to the id using scrollIntoView
Note: onExitComplete is only effective if exitBeforeEnter prop is true.

```<code>// pages/_app.tsx
import { AppProps } from 'next/app';
import { useRouter } from 'next/router';
import { AnimatePresence } from 'framer-motion';

// The handler to smoothly scroll the element into view
const handExitComplete = (): void => {
  if (typeof window !== 'undefined') {
    // Get the hash from the url
    const hashId = window.location.hash;

    if (hashId) {
      // Use the hash to find the first element with that id
      const element = document.querySelector(hashId);

      if (element) {
        // Smooth scroll to that elment
        element.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
          inline: 'nearest',
        });
      }
    }
  }
};

const MyApp = ({ Component, pageProps }: AppProps): JSX.Element => {
  const router = useRouter();
  return (
    <AnimatePresence exitBeforeEnter onExitComplete={handExitComplete}>
      <Component {...pageProps} key={router.route} />
    </AnimatePresence>
  );
};

export default MyApp;

</code>```

Live CodeSandbox here.

PS: For some reason the the window.location.hash in the sandbox preview is always an empty string, breaking the hash navigation but opening the preview in a separate browser tab works like a charm.

Body:
I am using Framer Motion to animate Next.js page transitions. However using the using AnimatePresence breaks the hash link navigation and the page no longer goes to the targeted id element.

The page transitions are perfect until you want to navigate to a harsh ID on the page :(

// I have a link component setup like this
// index.tsx
<Link href="/about#the-team" scroll={false}>
  The Team
</Link>

// Targeting another page `about.tsx` with the id
// about.tsx

{/* ...many sections before.. */}

{content}

I have a custom _app.tsx as shown below.

// _app.tsx
import { AppProps } from 'next/app';
import { useRouter } from 'next/router';
import { AnimatePresence } from 'framer-motion';

const MyApp = ({ Component, pageProps }: AppProps): JSX.Element => {
  const router = useRouter();
  return (
    <AnimatePresence exitBeforeEnter>
      <Component {...pageProps} key={router.route} />
    </AnimatePresence>
  );
};

export default MyApp;

I am expecting to go directly to the section with id="the-team" but it won't work. A refresh of the page with the hash link shows that it's originally at the target element but quickly jumps to the top. It's so fast and easy to miss. How do I retain the page transitions but still be able to navigate to hash id?

Body:
The Culprit is the exitBeforeEnter
prop on on AnimatePresence. Removing the prop fixes the hash id navigation but breaks some of my use-case.

If set to true, AnimatePresence will only render one component at a time. The exiting component will finish its exit animation before the entering component is rendered.
  - framer-motion docs

I couldn't just remove the exitBeforeEnter prop as I had included it to fix a bug I had where targeting a node in the entering page collided with the identical one in the old instance of the exiting page. For example a ref logic on an animated svg header in the exiting Page colliding with the entering page's header svg ref logic.

To get the best of both worlds, Using the onExitComplete
that "Fires when all exiting nodes have completed animating out", I passed it a callback that checks for the hash from the widow.location.hash and smooth scrolls to the id using scrollIntoView
Note: onExitComplete is only effective if exitBeforeEnter prop is true.

// pages/_app.tsx
import { AppProps } from 'next/app';
import { useRouter } from 'next/router';
import { AnimatePresence } from 'framer-motion';

// The handler to smoothly scroll the element into view
const handExitComplete = (): void => {
  if (typeof window !== 'undefined') {
    // Get the hash from the url
    const hashId = window.location.hash;

    if (hashId) {
      // Use the hash to find the first element with that id
      const element = document.querySelector(hashId);

      if (element) {
        // Smooth scroll to that elment
        element.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
          inline: 'nearest',
        });
      }
    }
  }
};

const MyApp = ({ Component, pageProps }: AppProps): JSX.Element => {
  const router = useRouter();
  return (
    <AnimatePresence exitBeforeEnter onExitComplete={handExitComplete}>
      <Component {...pageProps} key={router.route} />
    </AnimatePresence>
  );
};

export default MyApp;

Live CodeSandbox here.

PS: For some reason the the window.location.hash in the sandbox preview is always an empty string, breaking the hash navigation but opening the preview in a separate browser tab works like a charm.


问:
make pairwise difference of array with python
I have an array with numbers like this, in this case 5 numbers:

```<code>a = array([2.88581812, 2.8930633 , 2.85603976, 2.86739916, 2.85736707])
</code>```

I would like to create an array of 10 elements in which the pairwise difference of all the numbers of the array is present.
For now i used nested loop for like this:

```<code>diffmean = []
for i in range(len(a)-1):
    for j in range(i+1, len(a)):
        diffmean.append(a[i]-a[j])
</code>```

Obtaining a list with 10 elements of pairwise difference

```<code>    [-0.007245185215707384,
 0.029778354907735505,
 0.018418952746142025,
 0.0284510446999775,
 0.03702354012344289,
 0.02566413796184941,
 0.035696229915684885,
 -0.01135940216159348,
 -0.0013273102077580035,
 0.010032091953835476]
</code>```

there is a "pythonic" way to perform this? without loopfor or nested loop for?

答:
Assuming a is is numpy array. The below should work, but perhaps a more efficient solution exists as this calculates differences twices

```<code>np.expand_dims(a, 1) - a
d[np.tril_indices(a.size, k=-1)]
</code>```

Body:
I have an array with numbers like this, in this case 5 numbers:

a = array([2.88581812, 2.8930633 , 2.85603976, 2.86739916, 2.85736707])

I would like to create an array of 10 elements in which the pairwise difference of all the numbers of the array is present.
For now i used nested loop for like this:

diffmean = []
for i in range(len(a)-1):
    for j in range(i+1, len(a)):
        diffmean.append(a[i]-a[j])

Obtaining a list with 10 elements of pairwise difference

    [-0.007245185215707384,
 0.029778354907735505,
 0.018418952746142025,
 0.0284510446999775,
 0.03702354012344289,
 0.02566413796184941,
 0.035696229915684885,
 -0.01135940216159348,
 -0.0013273102077580035,
 0.010032091953835476]

there is a "pythonic" way to perform this? without loopfor or nested loop for?

Body:
Assuming a is is numpy array. The below should work, but perhaps a more efficient solution exists as this calculates differences twices

np.expand_dims(a, 1) - a
d[np.tril_indices(a.size, k=-1)]


问:
Determine path and root cause of FirebaseError Missing or insufficient permissions
I'm using Firebase and Firestore. My web app was throwing an error when rendering:

```<code>FirebaseError: Missing or insufficient permissions
</code>```

but the stacktrace is very long and all library code as far as I can tell, making it nearly impossible to determine what code is actually causing this.

After lots of hunting through my code base I determined that a library was trying to fetch data from /profiles/{uid}, and fixed the error, but if I had some better debugging tools this would have been  much faster.

Is there a way to get the path that was attempting to be read from the error, or any other metadata related to the error? I checked monitoring and logs in Firebase web console but couldn't find anything. A log of Firestore denies, including the attempted path would be very helpful for this purpose.

答:
According to this answer by Doug Stevenson there's no way of logging this since it may reveal security measures to a potential attacker.

Still, you should find more logs if you use the local emulator to test your queries before deploying.

Body:
I'm using Firebase and Firestore. My web app was throwing an error when rendering:

FirebaseError: Missing or insufficient permissions

but the stacktrace is very long and all library code as far as I can tell, making it nearly impossible to determine what code is actually causing this.

After lots of hunting through my code base I determined that a library was trying to fetch data from /profiles/{uid}, and fixed the error, but if I had some better debugging tools this would have been  much faster.

Is there a way to get the path that was attempting to be read from the error, or any other metadata related to the error? I checked monitoring and logs in Firebase web console but couldn't find anything. A log of Firestore denies, including the attempted path would be very helpful for this purpose.


问:
Update context depending on axios response
I'm facing a problem,

Unhandled Rejection (Error): Invalid hook call.

Apparently it's breaking the rule of "Do not call in event handlers." ? I can't find an alternative to update my context. I need the context, to update several components like menu.js, to manage the accessibility to private routes...

My AuthContext.js

export const AuthContext = React.createContext({
    token: localStorage.getItem('token') || '',
    setToken: () => {}
});
```

<p>My <em>LoginForm.js</em></p>

<pre class="lang-js prettyprint-override"><code>class LoginForm extends Component {
  authContext = useContext(AuthContext);

  constructor() {
    super();
    this.state = {
      email: 'eve.holt@reqres.in',
      password: 'cityslicka',
      error: ''
    };

    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleEmailChange = this.handleEmailChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(evt) {
    evt.preventDefault();
    axios({
      method: 'POST',
      url: 'https://reqres.in/api/login',
      data: {
        email: this.state.email,
        password: this.state.password
      }
    }).then(result => {
      if (result.status === 200) {
        this.authContext.setToken(result.data.token);
        localStorage.setItem('token', result.data.token);
      } else { }
    });
  }

 ...
}
</code>```

I've found some answers but I can't understand or solve my problem. If you can explain your answers, I'd appreciate it

Thanks for helping

答:
You need to rewrite your classical component into functional component, since hooks are not designed to work inside classes.
Check out react doc's rule of hooks:
https://reactjs.org/docs/hooks-rules.html#only-call-hooks-from-react-functions</p>

Body:
I'm facing a problem,

Unhandled Rejection (Error): Invalid hook call.

Apparently it's breaking the rule of "Do not call in event handlers." ? I can't find an alternative to update my context. I need the context, to update several components like menu.js, to manage the accessibility to private routes...

My AuthContext.js

export const AuthContext = React.createContext({
    token: localStorage.getItem('token') || '',
    setToken: () => {}
});

My LoginForm.js

class LoginForm extends Component {
  authContext = useContext(AuthContext);

  constructor() {
    super();
    this.state = {
      email: 'eve.holt@reqres.in',
      password: 'cityslicka',
      error: ''
    };

    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleEmailChange = this.handleEmailChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(evt) {
    evt.preventDefault();
    axios({
      method: 'POST',
      url: 'https://reqres.in/api/login',
      data: {
        email: this.state.email,
        password: this.state.password
      }
    }).then(result => {
      if (result.status === 200) {
        this.authContext.setToken(result.data.token);
        localStorage.setItem('token', result.data.token);
      } else { }
    });
  }

 ...
}

I've found some answers but I can't understand or solve my problem. If you can explain your answers, I'd appreciate it

Thanks for helping


问:
How can I parse this as an object or array with javascript?
When I call this url: https://dogsatmyjob.tumblr.com/api/read/json?id=165570102911

I get a string response like this:

```<code>var tumblr_api_read = {"tumblelog":{"title":"Dogs At My Job","description":"<p>Just a simple collection of the pups that I see everyday at my dog care job.<\/p>","name":"dogsatmyjob","timezone":"US\/Mountain","cname":false,"feeds":[]},"posts-start":0,"posts-total":1359,"posts-type":false,"posts":[{"id":"165570102911","url":"https:\/\/dogsatmyjob.tumblr.com\/post\/165570102911","url-with-slug":"https:\/\/dogsatmyjob.tumblr.com\/post\/165570102911\/dogsatmyjob-catcher-is-always-camera-ready","type":"photo","date-gmt":"2017-09-21 04:00:40 GMT","date":"Wed, 20 Sep 2017 22:00:40","bookmarklet":0,"mobile":0,"feed-item":"","from-feed-id":0,"unix-timestamp":1505966440,"format":"html","reblog-key":"FpmqGk7D","slug":"dogsatmyjob-catcher-is-always-camera-ready","is-submission":false,"like-button":"<div class=\"like_button\" data-post-id=\"165570102911\" data-blog-name=\"dogsatmyjob\" id=\"like_button_165570102911\"><iframe id=\"like_iframe_165570102911\" src=\"https:\/\/assets.tumblr.com\/assets\/html\/like_iframe.html?_v=66c22ab5319d742bca5762b8d18f9d06#name=dogsatmyjob&post_id=165570102911&color=black&rk=FpmqGk7D&root_id=159690206439\" scrolling=\"no\" width=\"20\" height=\"20\" frameborder=\"0\" class=\"like_toggle\" allowTransparency=\"true\" name=\"like_iframe_165570102911\"><\/iframe><\/div>","reblog-button":"<a href=\"https:\/\/www.tumblr.com\/reblog\/165570102911\/FpmqGk7D\" class=\"reblog_button\"style=\"display: block;width:20px;height:20px;\"><svg width=\"100%\" height=\"100%\" viewBox=\"0 0 21 21\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" xmlns:xlink=\"http:\/\/www.w3.org\/1999\/xlink\" fill=\"#000\"><path d=\"M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z\"><\/path><path d=\"M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203\"><\/path><\/svg><\/a>","state":"published","note-count":"219","reblogged-from-url":"https:\/\/dogsatmyjob.tumblr.com\/post\/159690206439\/catcher-is-always-camera-ready","reblogged-from-name":"dogsatmyjob","reblogged-from-title":"Dogs At My Job","reblogged_from_avatar_url_512":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_512.png","reblogged_from_avatar_url_128":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_128.png","reblogged_from_avatar_url_96":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_96.png","reblogged_from_avatar_url_64":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_64.png","reblogged_from_avatar_url_48":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_48.png","reblogged_from_avatar_url_40":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_40.png","reblogged_from_avatar_url_30":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_30.png","reblogged_from_avatar_url_24":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_24.png","reblogged_from_avatar_url_16":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_16.png","reblogged-root-url":"https:\/\/dogsatmyjob.tumblr.com\/post\/159690206439\/catcher-is-always-camera-ready","reblogged-root-name":"dogsatmyjob","reblogged-root-title":"Dogs At My Job","reblogged_root_avatar_url_512":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_512.png","reblogged_root_avatar_url_128":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_128.png","reblogged_root_avatar_url_96":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_96.png","reblogged_root_avatar_url_64":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_64.png","reblogged_root_avatar_url_48":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_48.png","reblogged_root_avatar_url_40":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_40.png","reblogged_root_avatar_url_30":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_30.png","reblogged_root_avatar_url_24":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_24.png","reblogged_root_avatar_url_16":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_16.png","tumblelog":{"title":"Dogs At My Job","name":"dogsatmyjob","cname":false,"url":"https:\/\/dogsatmyjob.tumblr.com\/","timezone":"US\/Mountain","avatar_url_512":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_512.png","avatar_url_128":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_128.png","avatar_url_96":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_96.png","avatar_url_64":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_64.png","avatar_url_48":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_48.png","avatar_url_40":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_40.png","avatar_url_30":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_30.png","avatar_url_24":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_24.png","avatar_url_16":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_16.png"},"photo-caption":"<p><a href=\"https:\/\/dogsatmyjob.tumblr.com\/post\/159690206439\/catcher-is-always-camera-ready\" class=\"tumblr_blog\">dogsatmyjob<\/a>:<\/p>\n\n<blockquote><p>Catcher is always camera-ready.<\/p><\/blockquote>","width":960,"height":1280,"photo-url-1280":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_1280.jpg","photo-url-500":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_500.jpg","photo-url-400":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_400.jpg","photo-url-250":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_250.jpg","photo-url-100":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_100.jpg","photo-url-75":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_75sq.jpg","photos":[],"tags":["catcher","german shepherd","germanshepherd","cute","adorable","beautiful","dog","dogs","puppy","puppies","dogsatmyjob","dogblr"]}]};
</code>```

The thing is that this is a string of an asignment of a json body. Not just that, the / are shown as \/, so I would need to parse it but also escape these characters.

What would be the best way of parsing this so I can treat it as an object / array ?

Body:
When I call this url: https://dogsatmyjob.tumblr.com/api/read/json?id=165570102911

I get a string response like this:

var tumblr_api_read = {"tumblelog":{"title":"Dogs At My Job","description":"
Just a simple collection of the pups that I see everyday at my dog care job.<\/p>","name":"dogsatmyjob","timezone":"US\/Mountain","cname":false,"feeds":[]},"posts-start":0,"posts-total":1359,"posts-type":false,"posts":[{"id":"165570102911","url":"https:\/\/dogsatmyjob.tumblr.com\/post\/165570102911","url-with-slug":"https:\/\/dogsatmyjob.tumblr.com\/post\/165570102911\/dogsatmyjob-catcher-is-always-camera-ready","type":"photo","date-gmt":"2017-09-21 04:00:40 GMT","date":"Wed, 20 Sep 2017 22:00:40","bookmarklet":0,"mobile":0,"feed-item":"","from-feed-id":0,"unix-timestamp":1505966440,"format":"html","reblog-key":"FpmqGk7D","slug":"dogsatmyjob-catcher-is-always-camera-ready","is-submission":false,"like-button":"
<\/iframe><\/div>","reblog-button":"<svg width=\"100%\" height=\"100%\" viewBox=\"0 0 21 21\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" xmlns:xlink=\"http:\/\/www.w3.org\/1999\/xlink\" fill=\"#000\"><path d=\"M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z\"><\/path><path d=\"M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203\"><\/path><\/svg><\/a>","state":"published","note-count":"219","reblogged-from-url":"https:\/\/dogsatmyjob.tumblr.com\/post\/159690206439\/catcher-is-always-camera-ready","reblogged-from-name":"dogsatmyjob","reblogged-from-title":"Dogs At My Job","reblogged_from_avatar_url_512":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_512.png","reblogged_from_avatar_url_128":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_128.png","reblogged_from_avatar_url_96":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_96.png","reblogged_from_avatar_url_64":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_64.png","reblogged_from_avatar_url_48":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_48.png","reblogged_from_avatar_url_40":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_40.png","reblogged_from_avatar_url_30":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_30.png","reblogged_from_avatar_url_24":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_24.png","reblogged_from_avatar_url_16":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_16.png","reblogged-root-url":"https:\/\/dogsatmyjob.tumblr.com\/post\/159690206439\/catcher-is-always-camera-ready","reblogged-root-name":"dogsatmyjob","reblogged-root-title":"Dogs At My Job","reblogged_root_avatar_url_512":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_512.png","reblogged_root_avatar_url_128":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_128.png","reblogged_root_avatar_url_96":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_96.png","reblogged_root_avatar_url_64":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_64.png","reblogged_root_avatar_url_48":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_48.png","reblogged_root_avatar_url_40":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_40.png","reblogged_root_avatar_url_30":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_30.png","reblogged_root_avatar_url_24":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_24.png","reblogged_root_avatar_url_16":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_16.png","tumblelog":{"title":"Dogs At My Job","name":"dogsatmyjob","cname":false,"url":"https:\/\/dogsatmyjob.tumblr.com\/","timezone":"US\/Mountain","avatar_url_512":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_512.png","avatar_url_128":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_128.png","avatar_url_96":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_96.png","avatar_url_64":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_64.png","avatar_url_48":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_48.png","avatar_url_40":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_40.png","avatar_url_30":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_30.png","avatar_url_24":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_24.png","avatar_url_16":"https:\/\/66.media.tumblr.com\/avatar_89ca7a2e202d_16.png"},"photo-caption":"
dogsatmyjob<\/a>:<\/p>\n\n

Catcher is always camera-ready.<\/p><\/blockquote>","width":960,"height":1280,"photo-url-1280":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_1280.jpg","photo-url-500":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_500.jpg","photo-url-400":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_400.jpg","photo-url-250":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_250.jpg","photo-url-100":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_100.jpg","photo-url-75":"https:\/\/66.media.tumblr.com\/cac87bd90ea04d2ed28194aed7a79308\/tumblr_oojzetRpQD1w71lqmo1_75sq.jpg","photos":[],"tags":["catcher","german shepherd","germanshepherd","cute","adorable","beautiful","dog","dogs","puppy","puppies","dogsatmyjob","dogblr"]}]};

The thing is that this is a string of an asignment of a json body. Not just that, the / are shown as \/, so I would need to parse it but also escape these characters.

What would be the best way of parsing this so I can treat it as an object / array ?

Body:
The API documentation expects you to access a URL like that as the source of a <script> tag. That way the code returned will create the tumblr_api_read global variable.

What you could do when reading via an xhr would be to make a Function instance from it with an additional return statement:

var tumblrObject = new Function(responseString + " return tumblr_api_read;")();

Alternatively, you could chop off the trailing semicolon and the var declaration with some string hackery and then pass what's left to JSON.parse(). The backslashes before the slashes won't cause a problem; that's actually part of the JSON standard.

I should add that using the new Function() approach would introduce a risk. If tumblr.com is hacked, the API could return code that attempted to do bad things. That risk is present when using the <script> tag approach too. Modifying the string and using JSON.parse() is probably preferable from that standpoint.


问:
how to dynamically set an environment variable to true within a dockerfile
my app has feature flags that i would like to dynamically set to true for my npm build.
essentially i'd like to do something like
COMPILE_ASSETS=true npm build or NEW_EMAILS=true npm build, only dynamically from CI.

i have a CI pipeline that will grab the flag, but am having trouble setting it to the true and running npm in the Dockerfile.

my Dockerfile -

```<code>FROM ubuntu:bionic
ARG FEATURE_FLAG
RUN if [ "x$FEATURE_FLAG" = "x" ] ; \
    then npm run build ; \
    else $FEATURE_FLAG=true npm run build; \
    fi

</code>```

this gets run with --

docker build --no-cache --rm -t testing --build-arg FEATURE_FLAG=my_feature_flag . (i would like to keep this the way it is)

in CI i get

/bin/sh: 1: my_feature_flag=true: not found

i've tried various forms of the else statement --

else export $FEATURE_FLAG=true npm run build; (this actually looks like it works on my mac but fails in CI with export: : bad variable name

else ${FEATURE_FLAG:+$FEATURE_FLAG=true} npm build;

else eval(`$FEATURE_FLAG=true npm build`);

`else env $FEATURE_FLAG=true bash -c 'npm build';

these all fail :(

i've tried reworking the Dockerfile completely and setting the flag to true as an ENV --

```<code>ARG FEATURE_FLAG
ENV FF_SET_TRUE=${FEATURE_FLAG:+$FEATURE_FLAG=true}
ENV FF_SET_TRUE=${FF_SET_TRUE:-null}
RUN if [ "$FF_SET_TRUE" = "null" ] ; \
    then npm build; \
    else $FF_SET_TRUE npm build; \
    fi
</code>```

nothing works! is this simply a bash limitation? is expanding a variable before running a command is not possible?

or is this not possible with Docker?

答:
this worked!</p>

```<code>ARG FEATURE_FLAG

RUN if [ -z "$FEATURE_FLAG" ] ; \
    then npm run build ; \
    else \
      echo setting $FEATURE_FLAG to true; \
      env "$FEATURE_FLAG"=true sh -c 'npm run build'; \
    fi
</code>```

Body:
my app has feature flags that i would like to dynamically set to true for my npm build.
essentially i'd like to do something like
COMPILE_ASSETS=true npm build or NEW_EMAILS=true npm build, only dynamically from CI.

i have a CI pipeline that will grab the flag, but am having trouble setting it to the true and running npm in the Dockerfile.

my Dockerfile -

FROM ubuntu:bionic
ARG FEATURE_FLAG
RUN if [ "x$FEATURE_FLAG" = "x" ] ; \
    then npm run build ; \
    else $FEATURE_FLAG=true npm run build; \
    fi

this gets run with --

docker build --no-cache --rm -t testing --build-arg FEATURE_FLAG=my_feature_flag . (i would like to keep this the way it is)

in CI i get

/bin/sh: 1: my_feature_flag=true: not found

i've tried various forms of the else statement --

else export $FEATURE_FLAG=true npm run build; (this actually looks like it works on my mac but fails in CI with export: : bad variable name

else ${FEATURE_FLAG:+$FEATURE_FLAG=true} npm build;

else eval(`$FEATURE_FLAG=true npm build`);

`else env $FEATURE_FLAG=true bash -c 'npm build';

these all fail :(

i've tried reworking the Dockerfile completely and setting the flag to true as an ENV --

ARG FEATURE_FLAG
ENV FF_SET_TRUE=${FEATURE_FLAG:+$FEATURE_FLAG=true}
ENV FF_SET_TRUE=${FF_SET_TRUE:-null}
RUN if [ "$FF_SET_TRUE" = "null" ] ; \
    then npm build; \
    else $FF_SET_TRUE npm build; \
    fi

nothing works! is this simply a bash limitation? is expanding a variable before running a command is not possible?

or is this not possible with Docker?

Body:
this worked!

ARG FEATURE_FLAG

RUN if [ -z "$FEATURE_FLAG" ] ; \
    then npm run build ; \
    else \
      echo setting $FEATURE_FLAG to true; \
      env "$FEATURE_FLAG"=true sh -c 'npm run build'; \
    fi


问:
Silverlight - how to call a command based upon a property wihtin the view
I have been banging my head on this one for hours and I am hoping someone can point me in the correct direction.

I have a button within my view which has a click event and a command attached. The click event sets the visibility of a grid row to collapsed or visible based upon the current state.

xaml

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="120" />
        <RowDefinition x:Name="DetailHolder" Height="*" />
    </Grid.RowDefinitions>
    <Grid x:Name="LayoutRoot">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="92.915" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Button x:Name="DetailButton"
                Grid.Column="1"
                Width="107"
                Height="23"
                Margin="196,94,0,0"
                HorizontalAlignment="Left"
                VerticalAlignment="Top"
                Click= "MoreDetail_Click"
                Command="{Binding GetCFSDetailCommand}"
                Content="View Details [+]" >
            <Button.DataContext>
                <mdc:SearchViewModel/>
            </Button.DataContext>
        </Button>
    </Grid>
    <Grid x:Name="MyDetail"
          Grid.Row="1"
          MinHeight="150"
          Visibility="Collapsed">
        <TextBlock Text="My Hidden Data" />
    </Grid>
</Grid>
</code>```

The click command calls a method that tests the current visual state of the MyDetail section and expands or collapses it

The Command calls GetCFSDetailCommand from my viewModel etc

Where I am stuck is that I only want to call the Command GetCFSDetailCommand when the view is collapsed. The way it is set now is that command will fire every time the button is clicked. I can't use ICommand CanExecute because I don't want to disable the button.  I'd appreciate any suggestions or ideas on how to go about achieving this. One thought was to test the visibility within the event code behind and then based upon that have the event call the Command. If this is the correct approach I would really appreciate a code sample as I have had no luck in calling the command from an event.

Thanks in advance

答:
It is legit to call a command from an event and you can do it right from your XAML too. You can pass in the visibility state as a command parameter as well.

See the sample below:

```<code>xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"

<Rectangle Fill="White"
           Stroke="Black"
           Width="200"
           Height="100">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseEnter">
            <cmd:EventToCommand Command="{Binding TestCommand,
                                          Mode=OneWay}"
               CommandParameter="{Binding Text,
                                  ElementName=MyTextBox,
                                  Mode=OneWay}"
               MustToggleIsEnabledValue="True" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Rectangle>
</code>```

You'll the MvvmLight toolkit for this. You can easily install it through NuGet.

Source: MvvmLight

Body:
I have been banging my head on this one for hours and I am hoping someone can point me in the correct direction.

I have a button within my view which has a click event and a command attached. The click event sets the visibility of a grid row to collapsed or visible based upon the current state.

xaml

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="120" />
        <RowDefinition x:Name="DetailHolder" Height="*" />
    </Grid.RowDefinitions>
    <Grid x:Name="LayoutRoot">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="92.915" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Button x:Name="DetailButton"
                Grid.Column="1"
                Width="107"
                Height="23"
                Margin="196,94,0,0"
                HorizontalAlignment="Left"
                VerticalAlignment="Top"
                Click= "MoreDetail_Click"
                Command="{Binding GetCFSDetailCommand}"
                Content="View Details [+]" >
            <Button.DataContext>
                <mdc:SearchViewModel/>
            </Button.DataContext>
        </Button>
    </Grid>
    <Grid x:Name="MyDetail"
          Grid.Row="1"
          MinHeight="150"
          Visibility="Collapsed">
        <TextBlock Text="My Hidden Data" />
    </Grid>
</Grid>

The click command calls a method that tests the current visual state of the MyDetail section and expands or collapses it

The Command calls GetCFSDetailCommand from my viewModel etc

Where I am stuck is that I only want to call the Command GetCFSDetailCommand when the view is collapsed. The way it is set now is that command will fire every time the button is clicked. I can't use ICommand CanExecute because I don't want to disable the button.  I'd appreciate any suggestions or ideas on how to go about achieving this. One thought was to test the visibility within the event code behind and then based upon that have the event call the Command. If this is the correct approach I would really appreciate a code sample as I have had no luck in calling the command from an event.

Thanks in advance

Body:
It is legit to call a command from an event and you can do it right from your XAML too. You can pass in the visibility state as a command parameter as well.

See the sample below:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"

<Rectangle Fill="White"
           Stroke="Black"
           Width="200"
           Height="100">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseEnter">
            <cmd:EventToCommand Command="{Binding TestCommand,
                                          Mode=OneWay}"
               CommandParameter="{Binding Text,
                                  ElementName=MyTextBox,
                                  Mode=OneWay}"
               MustToggleIsEnabledValue="True" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Rectangle>

You'll the MvvmLight toolkit for this. You can easily install it through NuGet.

Source: MvvmLight


问:
Read xml data with rvest
I am trying to read xml data from the following link:

https://www.sec.gov/Archives/edgar/data/1026081/000092189520001626/infotable.xml

I am using the rvest package and doing this

```<code>library(rvest)
url <- "https://www.sec.gov/Archives/edgar/data/1026081/000092189520001626/infotable.xml"

test <- url %>%
  read_xml() %>%
  xml_nodes("nameOfIssuer") %>%
  xml_text()
</code>```

But this is not working. "test" is empty. I have also tried xpath. I have also tried other variations such as

```<code>test <- url %>%
  read_xml() %>%
  xml_nodes("infoTable") %>%
  xml_text()
</code>```

I feel like I am missing something super basic. How would I go about scraping specific node information from here.

Thanks in advance!

答:
Yes, you're missing the fact that the nodes you are trying to scrape are inside a specific xml namespace. Strip out the namespace and you're good to go.</p>

```<code>url %>% read_xml() %>% xml_ns_strip() %>% xml_nodes("nameOfIssuer") %>% xml_text()
#>  [1] "BANCORP 34 INC"               "BANC OF CALIFORNIA INC"
#>  [3] "BANKWELL FINL GROUP INC"      "CBM BANCORP INC"
#>  [5] "CARTER BK & TR MARTINSVILLE"  "CITIZENS FINL GROUP"
#>  [7] "CIVISTA BANCSHARES INC"       "COLUMBIA FINL INC"
#>  [9] "CONNECTONE BANCORP INC NEW"   "FSB BANCORP INC"
#> [11] "FIRST UTD CORP"               "HV BANCORP INC"
#> [13] "HARBORONE BANCORP INC NEW"    "INVESTORS BANCORP INC NEW"
#> [15] "MSB FINL CORP NEW"            "MALVERN BANCORP INC"
#> [17] "MID SOUTHERN BANCORP INC"     "NORTHEAST BK LEWISTON ME"
#> [19] "PB BANCORP INC"               "PEAPACK-GLADSTONE FINL CORP"
#> [21] "PIONEER BANCORP INC"          "PROVIDENT BANCORP INC"
#> [23] "PRUDENTIAL BANCORP INC NEW"   "RICHMOND MUT BANCORPORATIN I"
#> [25] "SELECT BANCORP INC NEW"       "STERLING BANCORP DEL"
#> [27] "WATERSTONE FINL INC MD"       "WINTRUST FINL CORP"
</code>```

Title: Read xml data with rvest

Body:
I am trying to read xml data from the following link:

https://www.sec.gov/Archives/edgar/data/1026081/000092189520001626/infotable.xml

I am using the rvest package and doing this

library(rvest)
url <- "https://www.sec.gov/Archives/edgar/data/1026081/000092189520001626/infotable.xml"

test <- url %>%
  read_xml() %>%
  xml_nodes("nameOfIssuer") %>%
  xml_text()

But this is not working. "test" is empty. I have also tried xpath. I have also tried other variations such as

test <- url %>%
  read_xml() %>%
  xml_nodes("infoTable") %>%
  xml_text()

I feel like I am missing something super basic. How would I go about scraping specific node information from here.

Thanks in advance!

Body:
Yes, you're missing the fact that the nodes you are trying to scrape are inside a specific xml namespace. Strip out the namespace and you're good to go.

url %>% read_xml() %>% xml_ns_strip() %>% xml_nodes("nameOfIssuer") %>% xml_text()
#>  [1] "BANCORP 34 INC"               "BANC OF CALIFORNIA INC"
#>  [3] "BANKWELL FINL GROUP INC"      "CBM BANCORP INC"
#>  [5] "CARTER BK & TR MARTINSVILLE"  "CITIZENS FINL GROUP"
#>  [7] "CIVISTA BANCSHARES INC"       "COLUMBIA FINL INC"
#>  [9] "CONNECTONE BANCORP INC NEW"   "FSB BANCORP INC"
#> [11] "FIRST UTD CORP"               "HV BANCORP INC"
#> [13] "HARBORONE BANCORP INC NEW"    "INVESTORS BANCORP INC NEW"
#> [15] "MSB FINL CORP NEW"            "MALVERN BANCORP INC"
#> [17] "MID SOUTHERN BANCORP INC"     "NORTHEAST BK LEWISTON ME"
#> [19] "PB BANCORP INC"               "PEAPACK-GLADSTONE FINL CORP"
#> [21] "PIONEER BANCORP INC"          "PROVIDENT BANCORP INC"
#> [23] "PRUDENTIAL BANCORP INC NEW"   "RICHMOND MUT BANCORPORATIN I"
#> [25] "SELECT BANCORP INC NEW"       "STERLING BANCORP DEL"
#> [27] "WATERSTONE FINL INC MD"       "WINTRUST FINL CORP"