问:
Connecting Spring Boot Docker container to MongoDB docker container
I am trying to connect a spring boot docker container to a mongodb docker container. While developing Spring Boot app, I used a MongoDB docker container with port 27017 mapped to the host machine's 27017 port with docker run -p 27017:27017 mongo:3.4. When development finished, I containerized the spring app, but containerized spring app could not connect to the mongodb container. I know the problem is spring app is looking for mongodb at localhost. My question is how should I modify the app so that instead of looking for mongodb at localhost, it uses mongodb containers's address?

My database connections are handled with class below:

```<code>public class DB {
private final Datastore datastore;
private Morphia morphia;

/**
 * Constructor for creating database instance
 */
public DB() {
    morphia = new Morphia();
    morphia.mapPackage("users");
    datastore =
            morphia.createDatastore(new MongoClient(), "test");
    datastore.ensureIndexes();
}

/**
 * Inserts given user to the database
 *
 * @param u a newly created user.
 */
public void addUser(User u) {
    datastore.save(u);
}

/**
 * Fetches and prints all documents in database
 *
 * @return json array of all documents in database
 */
public String getUsers() {
    final Query<User> query = datastore.createQuery(User.class);
    final List<User> employees = query.asList();

    return objToJson(employees);
}

/**
 * Returns the user with the specified ID.
 *
 * @param userID is the ID of the document in database
 * @return document in json format
 */
public String getUser(ObjectId userID) {
    final Query<User> query = datastore.createQuery(User.class)
            .field("id").equal(userID);

    final List<User> employees = query.asList();
    return objToJson(employees);
}

/**
 * Deletes the document with the given ID from database.
 *
 * @param userID is the ID of the document to be removed
 */
public void removeUser(ObjectId userID) {
    final Query<User> query = datastore.createQuery(User.class)
            .field("id").equal(userID);
    datastore.delete(query);
}

/**
 * Deletes all documents from database.
 */
public void removeUsers() {
    final Query<User> query = datastore.createQuery(User.class);
    datastore.delete(query);
}

/**
 * Updates the fields of the document with given ID.
 *
 * @param userID  is the ID of the document to be updated
 * @param newUser contains the new fields
 * @return results of the update in json format
 */
public String updateUser(ObjectId userID, User newUser) {
    final Query<User> query = datastore.createQuery(User.class)
            .field("id").equal(userID);
    final UpdateOperations<User> updateOperations = datastore.createUpdateOperations(User.class);

    if (newUser.getFirst_name() != null) {
        String newName = newUser.getFirst_name();
        updateOperations.set("first_name", newName);
    }

    if (newUser.getLast_name() != null) {
        String newLastName = newUser.getLast_name();
        updateOperations.set("last_name", newLastName);
    }

    if (newUser.getSalary() != 0) {
        int newSalary = newUser.getSalary();
        updateOperations.set("salary", newSalary);
    }

    final UpdateResults results = datastore.update(query, updateOperations);
    return results.toString();

}

/**
 * Translate object lists to the json array.
 *
 * @param query is the list of the user objects
 * @return json array of the given users
 */
private String objToJson(List<User> query) {
    List<String> attsToRemove = Arrays.asList(new String[]{"className"});

    List<DBObject> dbObjList = new ArrayList<>(query.size());
    DBObject dbObj;
    for (Object obj : query) {
        dbObj = morphia.toDBObject(obj);
        for (int i = 0; i < attsToRemove.size(); i++) {
            dbObj.removeField(attsToRemove.get(i));
        }
        dbObjList.add(dbObj);
    }
    String json = JSON.serialize(dbObjList);
    return json;
}
</code>```

Here is my spring boot controller

```<code>@RestController
public class DemoController {

DB mongodb = new DB();

@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
    return "Greetings from Spring Boot";
}

@RequestMapping(value = "/users/{user_id}", method = RequestMethod.GET)
public String getUser(@PathVariable("user_id") ObjectId userID) {
    return mongodb.getUser(userID);
}

@RequestMapping(value = "/users", method = RequestMethod.GET)
public String getUsers() {
    return mongodb.getUsers();
}

@RequestMapping(value = "/users", method = RequestMethod.POST)
public void createUser(@RequestBody User u) {
    try {
        mongodb.addUser(u);
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

@RequestMapping(value = "/users", method = RequestMethod.DELETE)
public void deleteUsers() {
    try {
        mongodb.removeUsers();
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

@RequestMapping(value = "/users/{user-id}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable("user-id") ObjectId userID) {
    try {
        mongodb.removeUser(userID);
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

@RequestMapping(value = "/users/{user-id}", method = RequestMethod.PUT)
public String updateUser(@PathVariable("user-id") ObjectId userID, @RequestBody User u) {
    return mongodb.updateUser(userID, u);
}
</code>```

And here is my Dockerfile:

FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD demo-0.0.1-SNAPSHOT.jar app.jar
EXPOSE 27017
EXPOSE 8080
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]

I read the solutions mentioned here and here. Also read through couple of tutorials but I couldn't fit any of these solutions to my code. In my code, where should I change?

答:
The main issue is that your containers are not in the same network. I guess you can find a working example by this How to run Spring Boot and MongoDB in Docker containe. Here is a short extract:

docker network create spring_demo_net  create a network

docker run --name spring-demo-mongo --network=spring_demo_net -v /home/ubuntu/mongo-data:/data/db -d mongo start a mongo container

Modify mongo host in application properties as following spring.data.mongodb.uri=mongodb://spring-demo-mongo/YOUR_DB here spring-demo-mongo is the name of container that you created on step 1.

Since you are not using SpringData repositories it will not work so you need to create a MongoClient by explicitly passing host and port:

```<code>MongoClient mongoClient2 = new MongoClient("spring-demo-mongo", 27017);
</code>```

docker build --tag=spring-demo-1.0 build your docker image  with tag

docker run -d --name spring-demo --network=spring_demo_net -p 8080:8080  spring-demo-1.0 start your docker image

Body:
I am trying to connect a spring boot docker container to a mongodb docker container. While developing Spring Boot app, I used a MongoDB docker container with port 27017 mapped to the host machine's 27017 port with docker run -p 27017:27017 mongo:3.4. When development finished, I containerized the spring app, but containerized spring app could not connect to the mongodb container. I know the problem is spring app is looking for mongodb at localhost. My question is how should I modify the app so that instead of looking for mongodb at localhost, it uses mongodb containers's address?

My database connections are handled with class below:

public class DB {
private final Datastore datastore;
private Morphia morphia;

/**
 * Constructor for creating database instance
 */
public DB() {
    morphia = new Morphia();
    morphia.mapPackage("users");
    datastore =
            morphia.createDatastore(new MongoClient(), "test");
    datastore.ensureIndexes();
}

/**
 * Inserts given user to the database
 *
 * @param u a newly created user.
 */
public void addUser(User u) {
    datastore.save(u);
}

/**
 * Fetches and prints all documents in database
 *
 * @return json array of all documents in database
 */
public String getUsers() {
    final Query<User> query = datastore.createQuery(User.class);
    final List<User> employees = query.asList();

    return objToJson(employees);
}

/**
 * Returns the user with the specified ID.
 *
 * @param userID is the ID of the document in database
 * @return document in json format
 */
public String getUser(ObjectId userID) {
    final Query<User> query = datastore.createQuery(User.class)
            .field("id").equal(userID);

    final List<User> employees = query.asList();
    return objToJson(employees);
}

/**
 * Deletes the document with the given ID from database.
 *
 * @param userID is the ID of the document to be removed
 */
public void removeUser(ObjectId userID) {
    final Query<User> query = datastore.createQuery(User.class)
            .field("id").equal(userID);
    datastore.delete(query);
}

/**
 * Deletes all documents from database.
 */
public void removeUsers() {
    final Query<User> query = datastore.createQuery(User.class);
    datastore.delete(query);
}

/**
 * Updates the fields of the document with given ID.
 *
 * @param userID  is the ID of the document to be updated
 * @param newUser contains the new fields
 * @return results of the update in json format
 */
public String updateUser(ObjectId userID, User newUser) {
    final Query<User> query = datastore.createQuery(User.class)
            .field("id").equal(userID);
    final UpdateOperations<User> updateOperations = datastore.createUpdateOperations(User.class);

    if (newUser.getFirst_name() != null) {
        String newName = newUser.getFirst_name();
        updateOperations.set("first_name", newName);
    }

    if (newUser.getLast_name() != null) {
        String newLastName = newUser.getLast_name();
        updateOperations.set("last_name", newLastName);
    }

    if (newUser.getSalary() != 0) {
        int newSalary = newUser.getSalary();
        updateOperations.set("salary", newSalary);
    }

    final UpdateResults results = datastore.update(query, updateOperations);
    return results.toString();

}

/**
 * Translate object lists to the json array.
 *
 * @param query is the list of the user objects
 * @return json array of the given users
 */
private String objToJson(List<User> query) {
    List<String> attsToRemove = Arrays.asList(new String[]{"className"});

    List<DBObject> dbObjList = new ArrayList<>(query.size());
    DBObject dbObj;
    for (Object obj : query) {
        dbObj = morphia.toDBObject(obj);
        for (int i = 0; i < attsToRemove.size(); i++) {
            dbObj.removeField(attsToRemove.get(i));
        }
        dbObjList.add(dbObj);
    }
    String json = JSON.serialize(dbObjList);
    return json;
}

Here is my spring boot controller

@RestController
public class DemoController {

DB mongodb = new DB();

@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
    return "Greetings from Spring Boot";
}

@RequestMapping(value = "/users/{user_id}", method = RequestMethod.GET)
public String getUser(@PathVariable("user_id") ObjectId userID) {
    return mongodb.getUser(userID);
}

@RequestMapping(value = "/users", method = RequestMethod.GET)
public String getUsers() {
    return mongodb.getUsers();
}

@RequestMapping(value = "/users", method = RequestMethod.POST)
public void createUser(@RequestBody User u) {
    try {
        mongodb.addUser(u);
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

@RequestMapping(value = "/users", method = RequestMethod.DELETE)
public void deleteUsers() {
    try {
        mongodb.removeUsers();
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

@RequestMapping(value = "/users/{user-id}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable("user-id") ObjectId userID) {
    try {
        mongodb.removeUser(userID);
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

@RequestMapping(value = "/users/{user-id}", method = RequestMethod.PUT)
public String updateUser(@PathVariable("user-id") ObjectId userID, @RequestBody User u) {
    return mongodb.updateUser(userID, u);
}

And here is my Dockerfile:

FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD demo-0.0.1-SNAPSHOT.jar app.jar
EXPOSE 27017
EXPOSE 8080
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]

I read the solutions mentioned here and here. Also read through couple of tutorials but I couldn't fit any of these solutions to my code. In my code, where should I change?

Body:
The main issue is that your containers are not in the same network. I guess you can find a working example by this How to run Spring Boot and MongoDB in Docker containe. Here is a short extract:

docker network create spring_demo_net  create a network

docker run --name spring-demo-mongo --network=spring_demo_net -v /home/ubuntu/mongo-data:/data/db -d mongo start a mongo container

Modify mongo host in application properties as following spring.data.mongodb.uri=mongodb://spring-demo-mongo/YOUR_DB here spring-demo-mongo is the name of container that you created on step 1.

Since you are not using SpringData repositories it will not work so you need to create a MongoClient by explicitly passing host and port:

MongoClient mongoClient2 = new MongoClient("spring-demo-mongo", 27017);

docker build --tag=spring-demo-1.0 build your docker image  with tag

docker run -d --name spring-demo --network=spring_demo_net -p 8080:8080  spring-demo-1.0 start your docker image


来源: stackexchange

问:
Looping Syntax within Formula
In my macro, I want to loop within formulas:

```<code>    Range("D4").Formula = "=Inputs!D8
</code>```

transforms successfully to:

```<code>    For i = 1 To 5
    Range("D4").Formula = "=Inputs!D" & i + 7
</code>```

I want to do the same for the code below:

```<code> Range("G4").Formula = "=IF($C4<=Inputs!$E$8+Portfolio_Duration-1,SUM($H4:$DC4),"""")"
</code>```

I tried

```<code>    For i = 1 To 5
    Range("G4").Formula = "=IF($C4<=Inputs!$E$" & i + 7+Portfolio_Duration-1,SUM($H4:$DC4),"""")"
</code>```

But I am getting a compile error:
Expected: end of statement.

Could you please assist?

Thanks!

答:
Try this out,

```<code>Range("G4").Formula = "=IF($C4<=Inputs!$E$" & i + 7 + Portfolio_Duration - 1 & ",SUM($H4:$DC4),"""")"
</code>```

You are missing a " and a &

ContentLicense: CC BY-SA 3.0

Title: Looping Syntax within Formula

Body:
In my macro, I want to loop within formulas:

    Range("D4").Formula = "=Inputs!D8

transforms successfully to:

    For i = 1 To 5
    Range("D4").Formula = "=Inputs!D" & i + 7

I want to do the same for the code below:

 Range("G4").Formula = "=IF($C4<=Inputs!$E$8+Portfolio_Duration-1,SUM($H4:$DC4),"""")"

I tried

    For i = 1 To 5
    Range("G4").Formula = "=IF($C4<=Inputs!$E$" & i + 7+Portfolio_Duration-1,SUM($H4:$DC4),"""")"

But I am getting a compile error:
Expected: end of statement.

Could you please assist?

Thanks!

Body:
Try this out,

Range("G4").Formula = "=IF($C4<=Inputs!$E$" & i + 7 + Portfolio_Duration - 1 & ",SUM($H4:$DC4),"""")"

You are missing a " and a &


问:
How to access & modify the content of yaml file from python?
I would like to access and modify the content of a YAML file which looks like the following:

```<code>A: Sonstige
B:
  C: Sonstige
  D: null
  E: 1
</code>```

I know that in order to access & modify the value of A in the above YAML file, I would use  code like the following:

```<code>def set_state(state):
    with open('my_file.yaml') as f:
        doc = yaml.load(f)

    doc['A'] = state

    with open('my_file.yaml', 'w') as f:
        yaml.dump(doc, f)
</code>```

But what if I would like to modify the value of E in the above YAML file? How can I access the value of E and modify its value and dump it in a YAML file, similar to the above code. I have gone over the reference docs and was unable to find an answer for this.

答:
If you want to change the value for E, e.g. to 2 you could do the following:

```<code>import yaml

def set_state(state):
    with open('my_file.yaml') as f:
        doc = yaml.load(f)

    doc['B']['E'] = state

    with open('my_file.yaml', 'w') as f:
        yaml.dump(doc, f)

set_state(2)
</code>```

To get to the value of E first index on B.

There are multiple problems with this in my experience:

You are using load() which in PyYAML is an unsafe operation without warning. Your data can be loaded with safe_load() and even if it couldn't it is much better to extend safe_load() to handle tags (and only those tags) than to extend load().

Your output looks like:

```<code>A: Sonstige
B: {C: Sonstige, D: null, E: 2}
</code>```

not at all like your input, so use the option default_flow_style=False
to get something with your original block-style layout.

You don't need dump(), as data consisting of dicts, and primitives (and lists) can be dumped with safe_dump(). There is no safety issue there, but if you would call set_state() accidentally with a non-primitive:

```<code>class Dice:
    def __init__(self, sides):
        self.sides = sides

set_state(Dice(6))
</code>```

then dump() will silently generate the non-portable:

```<code>A: Sonstige
B:
  C: Sonstige
  D: null
  E: !!python/object:__main__.Dice {sides: 6}
</code>```

instead of raising an Representer error.

Any comments in your original file will be lost. PyYAML does not preserve these.

With PyYAML you should do:

```<code>import yaml

def set_state(state):
    with open('my_file.yaml') as f:
        doc = yaml.safe_load(f)

    doc['B']['E'] = state

    with open('my_file.yaml', 'w') as f:
        yaml.safe_dump(doc, f, default_flow_style=False)

set_state(2)
</code>```

If you also want to preserve comments, or have a mixture of block-style and flow-style you want to preserve, I recommend you use ruamel.yaml (disclaimer: I am the author of that package):

```<code>import pathlib
from ruamel.yaml import YAML

def set_state(state):
    yaml = YAML()
    mf = pathlib.Path('my_file.yaml')
    doc = yaml.load(mf)

    doc['B']['E'] = state

    yaml.dump(doc, mf)
</code>```

This has the same result as before, with the load() method being safe by default, preserving your layout (plus any comments in the YAML file you might have) and opening the Path instance for reading or writing as necessary (so you don't need the with statement, nor need the double action of calling dump and provide the w to open()).

Body:
I would like to access and modify the content of a YAML file which looks like the following:

A: Sonstige
B:
  C: Sonstige
  D: null
  E: 1

I know that in order to access & modify the value of A in the above YAML file, I would use  code like the following:

def set_state(state):
    with open('my_file.yaml') as f:
        doc = yaml.load(f)

    doc['A'] = state

    with open('my_file.yaml', 'w') as f:
        yaml.dump(doc, f)

But what if I would like to modify the value of E in the above YAML file? How can I access the value of E and modify its value and dump it in a YAML file, similar to the above code. I have gone over the reference docs and was unable to find an answer for this.

Body:
If you want to change the value for E, e.g. to 2 you could do the following:

import yaml

def set_state(state):
    with open('my_file.yaml') as f:
        doc = yaml.load(f)

    doc['B']['E'] = state

    with open('my_file.yaml', 'w') as f:
        yaml.dump(doc, f)

set_state(2)

To get to the value of E first index on B.

There are multiple problems with this in my experience:

You are using load() which in PyYAML is an unsafe operation without warning. Your data can be loaded with safe_load() and even if it couldn't it is much better to extend safe_load() to handle tags (and only those tags) than to extend load().

Your output looks like:

A: Sonstige
B: {C: Sonstige, D: null, E: 2}

not at all like your input, so use the option default_flow_style=False
to get something with your original block-style layout.

You don't need dump(), as data consisting of dicts, and primitives (and lists) can be dumped with safe_dump(). There is no safety issue there, but if you would call set_state() accidentally with a non-primitive:

class Dice:
    def __init__(self, sides):
        self.sides = sides

set_state(Dice(6))

then dump() will silently generate the non-portable:

A: Sonstige
B:
  C: Sonstige
  D: null
  E: !!python/object:__main__.Dice {sides: 6}

instead of raising an Representer error.

Any comments in your original file will be lost. PyYAML does not preserve these.

With PyYAML you should do:

import yaml

def set_state(state):
    with open('my_file.yaml') as f:
        doc = yaml.safe_load(f)

    doc['B']['E'] = state

    with open('my_file.yaml', 'w') as f:
        yaml.safe_dump(doc, f, default_flow_style=False)

set_state(2)

If you also want to preserve comments, or have a mixture of block-style and flow-style you want to preserve, I recommend you use ruamel.yaml (disclaimer: I am the author of that package):

import pathlib
from ruamel.yaml import YAML

def set_state(state):
    yaml = YAML()
    mf = pathlib.Path('my_file.yaml')
    doc = yaml.load(mf)

    doc['B']['E'] = state

    yaml.dump(doc, mf)

This has the same result as before, with the load() method being safe by default, preserving your layout (plus any comments in the YAML file you might have) and opening the Path instance for reading or writing as necessary (so you don't need the with statement, nor need the double action of calling dump and provide the w to open()).


问:
Python: How to pip install opencv2 with specific version 2.4.9?
I know that I could pip install opencv-python which installs opencv3, but is there a separate command or name for opencv specific version such as 2.4.9?

If not, how can I specify which version to install?

Thanks.

答:
There's another easy way, you can type in terminal

```<code>sudo apt-get install python-opencv
</code>```

Install OpenCV-Python in Ubuntu

After installing it, you can use opencv version 2.4 in both c++ and python.

But I recommend you should use opencv 3.2.0 and opencv-contrib, it gives more features

Hope this can help!

ContentLicense: CC BY-SA 4.0

Body:
There's another easy way, you can type in terminal

sudo apt-get install python-opencv

Install OpenCV-Python in Ubuntu

After installing it, you can use opencv version 2.4 in both c++ and python.

But I recommend you should use opencv 3.2.0 and opencv-contrib, it gives more features

Hope this can help!


问:
Collapse columns into a new variable
I have a data frame that looks like this.

```<code>name = c("p1","p2","p3","p4")
place = c("f","g","h","i")
v1 = c("x", "NA", "NA", "NA")
v2 = c("NA", "y", "y", "NA")
v3 = c("NA", "NA", "z", "NA")
region = c("n","w","s","e")
grade = c("f1","f2","f3","f4")
df = data.frame(name, place, v1, v2, v3, region, grade)

  name place v1 v2 v3 region grade
1   p1     f  x NA NA      n    f1
2   p2     g NA  y NA      w    f2
3   p3     h NA  y  z      s    f3
4   p4     i NA NA NA      e    f4
</code>```

I would like to add a new character vector v4 that contains the character from any of columns v1 v2 v3.

```<code>  name place v1 v2 v3 v4 region grade
1   p1     f  x NA NA  x      n    f1
2   p2     g NA  y NA  y      w    f2
3   p3     h NA  y  z yz      s    f3
4   p4     i NA NA NA NA      e    f4
</code>```

many thanks

答:
The dplyr alternative:

```<code>install.packages("dplyr")
library(dplyr)
df <- df %>%
      mutate( v4 = gsub( "NA", "", paste0(v1,v2,v3) ) ) %>%
      mutate( v4 = ifelse( v4 == "", NA, v4 ) )
</code>```

This should work if NA/"NA" is NA (not-a-value) or "NA" (character). And if you don't care whether v4 contains "" or NA, you can leave off the last line (and delete the last pipe).

Title: Collapse columns into a new variable

Body:
I have a data frame that looks like this.

name = c("p1","p2","p3","p4")
place = c("f","g","h","i")
v1 = c("x", "NA", "NA", "NA")
v2 = c("NA", "y", "y", "NA")
v3 = c("NA", "NA", "z", "NA")
region = c("n","w","s","e")
grade = c("f1","f2","f3","f4")
df = data.frame(name, place, v1, v2, v3, region, grade)

  name place v1 v2 v3 region grade
1   p1     f  x NA NA      n    f1
2   p2     g NA  y NA      w    f2
3   p3     h NA  y  z      s    f3
4   p4     i NA NA NA      e    f4

I would like to add a new character vector v4 that contains the character from any of columns v1 v2 v3.

  name place v1 v2 v3 v4 region grade
1   p1     f  x NA NA  x      n    f1
2   p2     g NA  y NA  y      w    f2
3   p3     h NA  y  z yz      s    f3
4   p4     i NA NA NA NA      e    f4

many thanks

Body:
The dplyr alternative:

install.packages("dplyr")
library(dplyr)
df <- df %>%
      mutate( v4 = gsub( "NA", "", paste0(v1,v2,v3) ) ) %>%
      mutate( v4 = ifelse( v4 == "", NA, v4 ) )

This should work if NA/"NA" is NA (not-a-value) or "NA" (character). And if you don't care whether v4 contains "" or NA, you can leave off the last line (and delete the last pipe).


问:
BasicScrollBarUI? How to use it
I am working on a code editor for Minecraft, and I am not very happy with the normal UI design in Java. I managed to change the buttons, but it doesn't really work for scroll bars. Could you please help me?

This is my ButtonUI class.

```<code>public class UIButton extends BasicButtonUI implements MouseListener {

    private Color hoverColor;
    private Color normalColor;
    private Color pressedColor;

    public UIButton(ColorSheme cs) {
        super();
        if (cs == ColorSheme.WHITE_BLUE_GRAY) {
            hoverColor = new Color(212, 211, 255);
            normalColor = new Color(184, 183, 206);
            pressedColor = new Color(197, 196, 228);
        }else if (cs == ColorSheme.GREEN_GRAY) {
            hoverColor = new Color(22, 179, 103);
            normalColor = new Color(9, 126, 101);
            pressedColor = new Color(17, 158, 102);
        }else if (cs == ColorSheme.RED_GRAY) {
            hoverColor = new Color(204, 86, 88);
            normalColor = new Color(171, 79, 91);
            pressedColor = new Color(187, 82, 90);
        }else if (cs == ColorSheme.BLUE_GRAY) {
            hoverColor = new Color(126, 176, 191);
            normalColor = new Color(104, 134, 179);
            pressedColor = new Color(111, 148, 183);
        }
    }

    @Override
    public void installUI(JComponent c) {
        super.installUI(c);
        c.addMouseListener(this);
        c.setBorder(null);
        c.setFont(Main.getDefaultFont());
    }

    @Override
    public void uninstallUI(JComponent c) {
        super.uninstallUI(c);
        c.removeMouseListener(this);
    }

    @Override
    protected void installDefaults(AbstractButton b) {
        super.installDefaults(b);
        changeButtonColor((JButton) b, normalColor);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        changeButtonColor((JButton) e.getComponent(), hoverColor);
    }

    @Override
    public void mousePressed(MouseEvent e) {
        changeButtonColor((JButton) e.getComponent(), pressedColor);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        changeButtonColor((JButton) e.getComponent(), normalColor);
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        changeButtonColor((JButton) e.getComponent(), hoverColor);
    }

    @Override
    public void mouseExited(MouseEvent e) {
        changeButtonColor((JButton) e.getComponent(), normalColor);
    }

    private void changeButtonColor(JButton b, Color c) {
        b.setBackground(c);
    }
}
</code>```

And this is my UIScrollBarUI class.

```<code>public class UIScrollBar extends BasicScrollBarUI implements MouseListener {

    private Color hoverColor;
    private Color normalColor;
    private Color pressedColor;

    public UIScrollBar(ColorSheme cs) {
        super();
        if (cs == ColorSheme.WHITE_BLUE_GRAY) {
            hoverColor = new Color(212, 211, 255);
            normalColor = new Color(184, 183, 206);
            pressedColor = new Color(197, 196, 228);
        }else if (cs == ColorSheme.GREEN_GRAY) {
            hoverColor = new Color(22, 179, 103);
            normalColor = new Color(9, 126, 101);
            pressedColor = new Color(17, 158, 102);
        }else if (cs == ColorSheme.RED_GRAY) {
            hoverColor = new Color(204, 86, 88);
            normalColor = new Color(171, 79, 91);
            pressedColor = new Color(187, 82, 90);
        }else if (cs == ColorSheme.BLUE_GRAY) {
            hoverColor = new Color(126, 176, 191);
            normalColor = new Color(104, 134, 179);
            pressedColor = new Color(111, 148, 183);
        }
    }

    @Override
    public void installUI(JComponent c) {
        super.installUI(c);
        c.addMouseListener(this);
        c.setBorder(null);
    }

    @Override
    public void uninstallUI(JComponent c) {
        super.uninstallUI(c);
        c.removeMouseListener(this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {

    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {
        System.out.print("Entered");
        changeBarColor(e.getComponent(), hoverColor);
    }

    @Override
    public void mouseExited(MouseEvent e) {
        System.out.print("Exited");
    }

    private void changeBarColor(Component c, Color co) {
        c.setBackground(co);
    }
}
</code>```

答:
First of all, if you are not happy with the "normal" UI design, you should consider changing Look And Feel.
I personally hate MetalLookAndFeel, and i'm used to set a system dependent look and feel for my swing applications.
Check this link for further details.

If you just want to change track and/or thumb color, you can override BasicScrollBarUI paintThumb and paintTrack methods.

Scrollbar's buttons can be changed as well.

Try this example (screenshot below):

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicScrollBarUI;
public class Main
{
    public static void main (String [] a) {
        SwingUtilities.invokeLater (new Runnable () {
            @Override public void run () {
                try {
                    UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName ());
                    createAndShowGUI ();
                }
                catch (Exception e) {
                    JOptionPane.showMessageDialog (null, "An unexpected error occurred : " + e.getClass ().getSimpleName (), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }
    private static void createAndShowGUI () {
        JFrame frame = new JFrame ("Test ScrollBar");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setContentPane (new CustomScrollPane ());
        frame.pack ();
        frame.setLocationRelativeTo (null);
        frame.setVisible (true);
    }
}
class CustomScrollPane extends JScrollPane
{
    public CustomScrollPane () {
        super (VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS);
        Image imageThumb = createImage (16, 16, Color.RED);
        Image imageThumbPressed = createImage (16, 16, Color.MAGENTA);
        Image imageTrack = createImage (16, 16, Color.YELLOW);
        // Adding some test labels
        JPanel view = new JPanel (new GridLayout (10, 5, 20, 50));
        for (int i = 0; i < 50; i++) view.add (new JLabel ("Test Label " + String.valueOf (i)));
        setViewportView (view);
        setHorizontalScrollBar (new CustomScrollBar (JScrollBar.HORIZONTAL, imageThumb, imageThumbPressed, imageTrack));
        setVerticalScrollBar (new CustomScrollBar (JScrollBar.VERTICAL, imageThumb, imageThumbPressed, imageTrack));
        // Setting preferred size for convenience. Not a good practice !
        setPreferredSize (new Dimension (200, 200));
    }
    private Image createImage (int width, int height, Color color) {
        BufferedImage image = new BufferedImage (width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics g = image.getGraphics ();
        g.setColor (color);
        g.fillRect (0, 0, width, height);
        g.dispose ();
        return image;
    }
}
class CustomScrollBar extends JScrollBar
{
    private boolean isThumbPressed;

    public CustomScrollBar (final int orientation, final Image thumb, final Image thumbPressed, final Image track) {
        super (orientation);
        addMouseListener (new MouseAdapter () {
            public void mousePressed (MouseEvent e) {
                isThumbPressed = true;
            }
            public void mouseReleased (MouseEvent e) {
                isThumbPressed = false;
            }
        });
        setUI (new BasicScrollBarUI () {
            @Override protected void paintThumb (Graphics g, JComponent c, Rectangle r) {
                if (isThumbPressed) g.drawImage (thumbPressed, r.x, r.y, r.width, r.height, null);
                else g.drawImage (thumb, r.x, r.y, r.width, r.height, null);
            }
            @Override protected void paintTrack (Graphics g, JComponent c, Rectangle r) {
                g.drawImage(track, r.x, r.y, r.width, r.height, null);
            }
        });
    }
}
</code>```

Title: BasicScrollBarUI? How to use it

Body:
I am working on a code editor for Minecraft, and I am not very happy with the normal UI design in Java. I managed to change the buttons, but it doesn't really work for scroll bars. Could you please help me?

This is my ButtonUI class.

public class UIButton extends BasicButtonUI implements MouseListener {

    private Color hoverColor;
    private Color normalColor;
    private Color pressedColor;

    public UIButton(ColorSheme cs) {
        super();
        if (cs == ColorSheme.WHITE_BLUE_GRAY) {
            hoverColor = new Color(212, 211, 255);
            normalColor = new Color(184, 183, 206);
            pressedColor = new Color(197, 196, 228);
        }else if (cs == ColorSheme.GREEN_GRAY) {
            hoverColor = new Color(22, 179, 103);
            normalColor = new Color(9, 126, 101);
            pressedColor = new Color(17, 158, 102);
        }else if (cs == ColorSheme.RED_GRAY) {
            hoverColor = new Color(204, 86, 88);
            normalColor = new Color(171, 79, 91);
            pressedColor = new Color(187, 82, 90);
        }else if (cs == ColorSheme.BLUE_GRAY) {
            hoverColor = new Color(126, 176, 191);
            normalColor = new Color(104, 134, 179);
            pressedColor = new Color(111, 148, 183);
        }
    }

    @Override
    public void installUI(JComponent c) {
        super.installUI(c);
        c.addMouseListener(this);
        c.setBorder(null);
        c.setFont(Main.getDefaultFont());
    }

    @Override
    public void uninstallUI(JComponent c) {
        super.uninstallUI(c);
        c.removeMouseListener(this);
    }

    @Override
    protected void installDefaults(AbstractButton b) {
        super.installDefaults(b);
        changeButtonColor((JButton) b, normalColor);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        changeButtonColor((JButton) e.getComponent(), hoverColor);
    }

    @Override
    public void mousePressed(MouseEvent e) {
        changeButtonColor((JButton) e.getComponent(), pressedColor);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        changeButtonColor((JButton) e.getComponent(), normalColor);
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        changeButtonColor((JButton) e.getComponent(), hoverColor);
    }

    @Override
    public void mouseExited(MouseEvent e) {
        changeButtonColor((JButton) e.getComponent(), normalColor);
    }

    private void changeButtonColor(JButton b, Color c) {
        b.setBackground(c);
    }
}

And this is my UIScrollBarUI class.

public class UIScrollBar extends BasicScrollBarUI implements MouseListener {

    private Color hoverColor;
    private Color normalColor;
    private Color pressedColor;

    public UIScrollBar(ColorSheme cs) {
        super();
        if (cs == ColorSheme.WHITE_BLUE_GRAY) {
            hoverColor = new Color(212, 211, 255);
            normalColor = new Color(184, 183, 206);
            pressedColor = new Color(197, 196, 228);
        }else if (cs == ColorSheme.GREEN_GRAY) {
            hoverColor = new Color(22, 179, 103);
            normalColor = new Color(9, 126, 101);
            pressedColor = new Color(17, 158, 102);
        }else if (cs == ColorSheme.RED_GRAY) {
            hoverColor = new Color(204, 86, 88);
            normalColor = new Color(171, 79, 91);
            pressedColor = new Color(187, 82, 90);
        }else if (cs == ColorSheme.BLUE_GRAY) {
            hoverColor = new Color(126, 176, 191);
            normalColor = new Color(104, 134, 179);
            pressedColor = new Color(111, 148, 183);
        }
    }

    @Override
    public void installUI(JComponent c) {
        super.installUI(c);
        c.addMouseListener(this);
        c.setBorder(null);
    }

    @Override
    public void uninstallUI(JComponent c) {
        super.uninstallUI(c);
        c.removeMouseListener(this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {

    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {
        System.out.print("Entered");
        changeBarColor(e.getComponent(), hoverColor);
    }

    @Override
    public void mouseExited(MouseEvent e) {
        System.out.print("Exited");
    }

    private void changeBarColor(Component c, Color co) {
        c.setBackground(co);
    }
}

Body:
First of all, if you are not happy with the "normal" UI design, you should consider changing Look And Feel.
I personally hate MetalLookAndFeel, and i'm used to set a system dependent look and feel for my swing applications.
Check this link for further details.

If you just want to change track and/or thumb color, you can override BasicScrollBarUI paintThumb and paintTrack methods.

Scrollbar's buttons can be changed as well.

Try this example (screenshot below):

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicScrollBarUI;
public class Main
{
    public static void main (String [] a) {
        SwingUtilities.invokeLater (new Runnable () {
            @Override public void run () {
                try {
                    UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName ());
                    createAndShowGUI ();
                }
                catch (Exception e) {
                    JOptionPane.showMessageDialog (null, "An unexpected error occurred : " + e.getClass ().getSimpleName (), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }
    private static void createAndShowGUI () {
        JFrame frame = new JFrame ("Test ScrollBar");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setContentPane (new CustomScrollPane ());
        frame.pack ();
        frame.setLocationRelativeTo (null);
        frame.setVisible (true);
    }
}
class CustomScrollPane extends JScrollPane
{
    public CustomScrollPane () {
        super (VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS);
        Image imageThumb = createImage (16, 16, Color.RED);
        Image imageThumbPressed = createImage (16, 16, Color.MAGENTA);
        Image imageTrack = createImage (16, 16, Color.YELLOW);
        // Adding some test labels
        JPanel view = new JPanel (new GridLayout (10, 5, 20, 50));
        for (int i = 0; i < 50; i++) view.add (new JLabel ("Test Label " + String.valueOf (i)));
        setViewportView (view);
        setHorizontalScrollBar (new CustomScrollBar (JScrollBar.HORIZONTAL, imageThumb, imageThumbPressed, imageTrack));
        setVerticalScrollBar (new CustomScrollBar (JScrollBar.VERTICAL, imageThumb, imageThumbPressed, imageTrack));
        // Setting preferred size for convenience. Not a good practice !
        setPreferredSize (new Dimension (200, 200));
    }
    private Image createImage (int width, int height, Color color) {
        BufferedImage image = new BufferedImage (width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics g = image.getGraphics ();
        g.setColor (color);
        g.fillRect (0, 0, width, height);
        g.dispose ();
        return image;
    }
}
class CustomScrollBar extends JScrollBar
{
    private boolean isThumbPressed;

    public CustomScrollBar (final int orientation, final Image thumb, final Image thumbPressed, final Image track) {
        super (orientation);
        addMouseListener (new MouseAdapter () {
            public void mousePressed (MouseEvent e) {
                isThumbPressed = true;
            }
            public void mouseReleased (MouseEvent e) {
                isThumbPressed = false;
            }
        });
        setUI (new BasicScrollBarUI () {
            @Override protected void paintThumb (Graphics g, JComponent c, Rectangle r) {
                if (isThumbPressed) g.drawImage (thumbPressed, r.x, r.y, r.width, r.height, null);
                else g.drawImage (thumb, r.x, r.y, r.width, r.height, null);
            }
            @Override protected void paintTrack (Graphics g, JComponent c, Rectangle r) {
                g.drawImage(track, r.x, r.y, r.width, r.height, null);
            }
        });
    }
}


问:
Merging partial duplicate cases without losing data
I have a question in regards to preparing my dataset for research.

I have a dataset in SPSS 20 in long format as I am researching on individual level over multiple years. However some individuals were added twice to my dataset because there were differences in some variables matched to those individuals (5000 individuals with 25 variables per individual). I would like to merge those duplicates so that I can run my analysis over time. For those variables that differ between the duplicates I would like spss to make additional variables when all the duplicates are merged.

Is this at all possible and if yes HOW?

答:
Try this:

```<code>sort cases by caseID otherVar.
compute ind=1.
if $casenum>1 and caseID=lag(caseID) ind=lag(ind)+1.
casestovars /id=caseID /index=ind.
</code>```

If a caseID is repeated more then once, after restructure there will be only one line for that case, while all the variables will be repeated with indexes.
If the order of the caseID repeats, replace the otherVar in the sort command with the corresponding variable (e.g. date). This way your new variables will also be indexed accordingly.

Body:
Try this:

sort cases by caseID otherVar.
compute ind=1.
if $casenum>1 and caseID=lag(caseID) ind=lag(ind)+1.
casestovars /id=caseID /index=ind.

If a caseID is repeated more then once, after restructure there will be only one line for that case, while all the variables will be repeated with indexes.
If the order of the caseID repeats, replace the otherVar in the sort command with the corresponding variable (e.g. date). This way your new variables will also be indexed accordingly.


问:
Why is there a NullPointerException in this method call?
When I call a method like this:

```<code>int value1;
Integer value2 = null;

setValue(value2);

private void setValue(int value) {
    value1 = value;
}
</code>```

Why is there a NullPointerException?

答:
The case which hasn't been mentioned in the current answers is if the formal parameter type is primitive:

```<code>void setValue(int a) {
  // ...
}
</code>```

This can be called with a parameter null, because the compiler will attempt to auto-unbox the value. Effectively:

```<code>setValue(null);
</code>```

Would be invoked as:

```<code>setValue(((Integer) null).intValue());
</code>```

However, this will always fail with NPE, because you can't dereference a null value.

But note that the NPE doesn't occur because null is passed to the method, but rather because of how the value which would be passed is evaluated. The difference is subtle, but important.

Any IDE worth using should flag this as a problem.

Body:
When I call a method like this:

int value1;
Integer value2 = null;

setValue(value2);

private void setValue(int value) {
    value1 = value;
}

Why is there a NullPointerException?

Body:
The case which hasn't been mentioned in the current answers is if the formal parameter type is primitive:

void setValue(int a) {
  // ...
}

This can be called with a parameter null, because the compiler will attempt to auto-unbox the value. Effectively:

setValue(null);

Would be invoked as:

setValue(((Integer) null).intValue());

However, this will always fail with NPE, because you can't dereference a null value.

But note that the NPE doesn't occur because null is passed to the method, but rather because of how the value which would be passed is evaluated. The difference is subtle, but important.

Any IDE worth using should flag this as a problem.


问:
How to Inject Angular Interceptor
I realize there are quite a few posts on interceptors but I am still having a hard time getting mine to work. My angular knowledge is so so when it comes to understanding how different things should be injected, where, etc. I believe the code is correct but i am not really sure how to get it injected into my application.

I believe the main issue resides in how i am using angular.module('devtestApp') in the interceptor file. I have tried moving $httpProvider.interceptors.push('JwtAuthInterceptor') to different locations but either nothing happens, ie the interceptor is not used, or, i get the following error when i have $httpProvider.interceptors.push('JwtAuthInterceptor') uncommented in the main app file.

jquery.js:3869 Uncaught Error: [$injector:unpr] Unknown provider: JwtAuthInterceptorProvider <- JwtAuthInterceptor <- $http <- $templateRequest <- $route

INTERCEPTOR FILE:

```<code> angular.module('devtestApp')
  .factory('JwtAuthInterceptor', function ($localStorage, $q, $location) {

 return {
    request: function(config) {
      console.log('in the interceptor');
      config.headers.Authorization = 'Bearer ';
      config.headers = config.headers || {};
      if ($localStorage.getItem('token')) {
        // may also use sessionStorage
        config.headers.Authorization = 'Bearer ' +
        $localStorage.getItem('token');
      }
      return config || $q.when(config);
    },
    response: function(response) {
      if (response.status === 401) {
        //  Redirect user to login page / signup Page.
        $location.path('/login');
      }
      return response || $q.when(response);
    }
  };
});

// Register the previously created JwtAuthInterceptor.
angular
  .module('devtestApp').config(function ($httpProvider) {
     $httpProvider.interceptors.push('JwtAuthInterceptor');
});
</code>```

MAIN APP FILE:

```<code> angular
  .module('devtestApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'angularSpinner',
'ngStorage'
  ])
  .config(function ($routeProvider, $locationProvider, $httpProvider, $qProvider) {
$routeProvider

  .when('/', {
    templateUrl: '/app/views/main.html',
    controller: 'MainCtrl',
    controllerAs: 'main'
  })
  ..... more of these

  // $httpProvider.interceptors.push('JwtAuthInterceptor');
  $locationProvider.html5Mode(false);
  $locationProvider.hashPrefix("!");

});
</code>```

Headers logged server side(node):

```<code> { host: 'localhost:8081',
  connection: 'keep-alive',
  pragma: 'no-cache',
  'cache-control': 'no-cache',
  accept: 'application/json, text/plain, */*',
  'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36
   (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
   referer: 'http://localhost:8081/',
   'accept-encoding': 'gzip, deflate, sdch, br',
    'accept-language': 'en-US,en;q=0.8',
    cookie: 'SQLiteManager_currentLangue=2;
</code>```

connect.sid=s%3AS4dpz1_ZhfwHFfVl9qBWnVKom8D4mgHh.04Kb%2B%2BsferIBZNavKQjRRoOvDwhFY7NjTjcabldEbio; JSESSIONID=d28168fff4793599a8c24f2f037c; treeForm_tree-hi=treeForm:tree:applications',
          dnt: '1' }

Sorry the headers aren't formatted well, but that is them in their entirety. Thanks for any help you can provide, if you need anymore information please let me know!

答:
Can you try the following ?? ? This is the structure that I use for my project.

Creating your own module

```<code>angular.module('myInterceptorModule')
  .factory('JwtAuthInterceptor', function ($localStorage, $q, $location) {

 return {
    request: function(config) {
      console.log('in the interceptor');
      config.headers.Authorization = 'Bearer ';
      config.headers = config.headers || {};
      if ($localStorage.getItem('token')) {
        // may also use sessionStorage
        config.headers.Authorization = 'Bearer ' +
        $localStorage.getItem('token');
      }
      return config || $q.when(config);
    },
    response: function(response) {
      if (response.status === 401) {
        //  Redirect user to login page / signup Page.
        $location.path('/login');
      }
      return response || $q.when(response);
    }
  };
})

// Register the previously created JwtAuthInterceptor.
// I have removed the declaration of the module again; it is unecessary
.config(function ($httpProvider) {
     $httpProvider.interceptors.push('JwtAuthInterceptor');
});
</code>```

MAIN APP FILE; add your new module

```<code> angular
  .module('devtestApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'angularSpinner',
'ngStorage',
'myInterceptorModule'
  ])
  .config(function ($routeProvider, $locationProvider, $httpProvider, $qProvider) {
$routeProvider
  .when('/', {
    templateUrl: '/app/views/main.html',
    controller: 'MainCtrl',
    controllerAs: 'main'
  })
  ..... more of these

  // $httpProvider.interceptors.push('JwtAuthInterceptor');
  $locationProvider.html5Mode(false);
  $locationProvider.hashPrefix("!");

});
</code>```

Title: How to Inject Angular Interceptor

Body:
I realize there are quite a few posts on interceptors but I am still having a hard time getting mine to work. My angular knowledge is so so when it comes to understanding how different things should be injected, where, etc. I believe the code is correct but i am not really sure how to get it injected into my application.

I believe the main issue resides in how i am using angular.module('devtestApp') in the interceptor file. I have tried moving $httpProvider.interceptors.push('JwtAuthInterceptor') to different locations but either nothing happens, ie the interceptor is not used, or, i get the following error when i have $httpProvider.interceptors.push('JwtAuthInterceptor') uncommented in the main app file.

jquery.js:3869 Uncaught Error: [$injector:unpr] Unknown provider: JwtAuthInterceptorProvider <- JwtAuthInterceptor <- $http <- $templateRequest <- $route

INTERCEPTOR FILE:

 angular.module('devtestApp')
  .factory('JwtAuthInterceptor', function ($localStorage, $q, $location) {

 return {
    request: function(config) {
      console.log('in the interceptor');
      config.headers.Authorization = 'Bearer ';
      config.headers = config.headers || {};
      if ($localStorage.getItem('token')) {
        // may also use sessionStorage
        config.headers.Authorization = 'Bearer ' +
        $localStorage.getItem('token');
      }
      return config || $q.when(config);
    },
    response: function(response) {
      if (response.status === 401) {
        //  Redirect user to login page / signup Page.
        $location.path('/login');
      }
      return response || $q.when(response);
    }
  };
});

// Register the previously created JwtAuthInterceptor.
angular
  .module('devtestApp').config(function ($httpProvider) {
     $httpProvider.interceptors.push('JwtAuthInterceptor');
});

MAIN APP FILE:

 angular
  .module('devtestApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'angularSpinner',
'ngStorage'
  ])
  .config(function ($routeProvider, $locationProvider, $httpProvider, $qProvider) {
$routeProvider

  .when('/', {
    templateUrl: '/app/views/main.html',
    controller: 'MainCtrl',
    controllerAs: 'main'
  })
  ..... more of these

  // $httpProvider.interceptors.push('JwtAuthInterceptor');
  $locationProvider.html5Mode(false);
  $locationProvider.hashPrefix("!");

});

Headers logged server side(node):

 { host: 'localhost:8081',
  connection: 'keep-alive',
  pragma: 'no-cache',
  'cache-control': 'no-cache',
  accept: 'application/json, text/plain, */*',
  'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36
   (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
   referer: 'http://localhost:8081/',
   'accept-encoding': 'gzip, deflate, sdch, br',
    'accept-language': 'en-US,en;q=0.8',
    cookie: 'SQLiteManager_currentLangue=2;

connect.sid=s%3AS4dpz1_ZhfwHFfVl9qBWnVKom8D4mgHh.04Kb%2B%2BsferIBZNavKQjRRoOvDwhFY7NjTjcabldEbio; JSESSIONID=d28168fff4793599a8c24f2f037c; treeForm_tree-hi=treeForm:tree:applications',
          dnt: '1' }

Sorry the headers aren't formatted well, but that is them in their entirety. Thanks for any help you can provide, if you need anymore information please let me know!

Body:
Can you try the following ?? ? This is the structure that I use for my project.

Creating your own module

angular.module('myInterceptorModule')
  .factory('JwtAuthInterceptor', function ($localStorage, $q, $location) {

 return {
    request: function(config) {
      console.log('in the interceptor');
      config.headers.Authorization = 'Bearer ';
      config.headers = config.headers || {};
      if ($localStorage.getItem('token')) {
        // may also use sessionStorage
        config.headers.Authorization = 'Bearer ' +
        $localStorage.getItem('token');
      }
      return config || $q.when(config);
    },
    response: function(response) {
      if (response.status === 401) {
        //  Redirect user to login page / signup Page.
        $location.path('/login');
      }
      return response || $q.when(response);
    }
  };
})

// Register the previously created JwtAuthInterceptor.
// I have removed the declaration of the module again; it is unecessary
.config(function ($httpProvider) {
     $httpProvider.interceptors.push('JwtAuthInterceptor');
});

MAIN APP FILE; add your new module

 angular
  .module('devtestApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'angularSpinner',
'ngStorage',
'myInterceptorModule'
  ])
  .config(function ($routeProvider, $locationProvider, $httpProvider, $qProvider) {
$routeProvider
  .when('/', {
    templateUrl: '/app/views/main.html',
    controller: 'MainCtrl',
    controllerAs: 'main'
  })
  ..... more of these

  // $httpProvider.interceptors.push('JwtAuthInterceptor');
  $locationProvider.html5Mode(false);
  $locationProvider.hashPrefix("!");

});


问:
Latex - Change margins of only a few pages
I have a Latex document where I need to change the margins of only a few pages (the pages where I'm adding a lot of graphics).

In particular, I'd like to change the top margins (\voffset). I've tried doing:

```<code>\addtolength{\voffset}{-4cm}

% Insert images here

\addtolength{\voffset}{4cm}
</code>```

but it didn't work. I've seen references to the geometry package, but I haven't found how to use it for a bunch of pages, and not for the whole document.

Any hints?

答:
I was struggling a lot with different solutions including  \vspace{-Xmm} on the top and bottom of the page and dealing with warnings and errors. Finally I found this answer:

You can change the margins of just one or more pages and then restore it to its default:

```<code>\usepackage{geometry}
...
...
...
\newgeometry{top=5mm, bottom=10mm}     % use whatever margins you want for left, right, top and bottom.
...
... %<The contents of enlarged page(s)>
...
\restoregeometry     %so it does not affect the rest of the pages.
...
...
...
</code>```

PS:

1- This can also fix the following warning:

LaTeX Warning: Float too large for page by ...pt on input line ...

2- For more detailed answer look at this.

3- I just found that this is more elaboration on Kevin Chen's answer.

ContentLicense: CC BY-SA 2.5

Body:
I have a Latex document where I need to change the margins of only a few pages (the pages where I'm adding a lot of graphics).

In particular, I'd like to change the top margins (\voffset). I've tried doing:

\addtolength{\voffset}{-4cm}

% Insert images here

\addtolength{\voffset}{4cm}

but it didn't work. I've seen references to the geometry package, but I haven't found how to use it for a bunch of pages, and not for the whole document.

Any hints?

Body:
I was struggling a lot with different solutions including  \vspace{-Xmm} on the top and bottom of the page and dealing with warnings and errors. Finally I found this answer:

You can change the margins of just one or more pages and then restore it to its default:

\usepackage{geometry}
...
...
...
\newgeometry{top=5mm, bottom=10mm}     % use whatever margins you want for left, right, top and bottom.
...
... %<The contents of enlarged page(s)>
...
\restoregeometry     %so it does not affect the rest of the pages.
...
...
...

PS:

1- This can also fix the following warning:

LaTeX Warning: Float too large for page by ...pt on input line ...

2- For more detailed answer look at this.

3- I just found that this is more elaboration on Kevin Chen's answer.


问:
Java 3D Draw on models
How to draw on a 3D model in java 3D. Like draw Line or a point.

I have been able to import models.
But stuck on how to draw on models.

Please Help

Thanks

答: In java3d you don't really "draw" on a model.  In java3d you create a scene graph with the model to be displayed.  Then you compile the scene and display it in a view.  If you want to draw something else in the display you have to create geometry that represents what you are drawing in the model.  You can place text and words on the geometry using texture mapping.  You can place words in the scene using Text3D.  If you haven't done much 3D stuff before it takes a while to learn.  There are a lot of good examples and tutorials on the java3d site https://java3d.dev.java.net/.</p>

Title: Java 3D Draw on models


问:
SQL Call function foreach row on every record in other table
I have two tables; Table1 (name, latitude, longitude) with 400 records in and Table2 (name, latitude, longitude) with 10,000 records in.

I want to find all records in Table2 that are physically close to the 400 records in Table1. (excluding all the 400 records in Table1).

I have a function that works out the distance between two records. My problem is in SQL I can't figure out how to run it for every record in Table1, on every record in Table2. I am calling my function as below;

```<code>dbo.fnCalcDistanceKM(item1.lat, item2.lat, item1.long, item2.long) < 0.150
</code>```

This gets the distance between the two coordinates and will only return the ones if it is within 150 metres. It works fine but I am struggling with running it for each record in Table1 over every record in Table2.

Any pointers would be greatly appriciated! I think this is fairly simple to do in SQL but my experience is lacking.

答:
I guess you are looking for the cross join operator:</p>

```<code>SELECT
    *
FROM
    Table1 T1
    cross join Table2 T2
WHERE
    dbo.fnCalcDistanceKM(T1.lat, T2.lat, T1.long, T2.long) < 0.150
</code>```

Body:
I have two tables; Table1 (name, latitude, longitude) with 400 records in and Table2 (name, latitude, longitude) with 10,000 records in.

I want to find all records in Table2 that are physically close to the 400 records in Table1. (excluding all the 400 records in Table1).

I have a function that works out the distance between two records. My problem is in SQL I can't figure out how to run it for every record in Table1, on every record in Table2. I am calling my function as below;

dbo.fnCalcDistanceKM(item1.lat, item2.lat, item1.long, item2.long) < 0.150

This gets the distance between the two coordinates and will only return the ones if it is within 150 metres. It works fine but I am struggling with running it for each record in Table1 over every record in Table2.

Any pointers would be greatly appriciated! I think this is fairly simple to do in SQL but my experience is lacking.

Body:
I guess you are looking for the cross join operator:

SELECT
    *
FROM
    Table1 T1
    cross join Table2 T2
WHERE
    dbo.fnCalcDistanceKM(T1.lat, T2.lat, T1.long, T2.long) < 0.150


问:
Auto incrementing ID as primary key on all tables
I am designing a database for an e-Commerce website which uses MySQL. I have made the list of tables necessary and all the fields necessary for the table. I have a total of 9 tables.

What I have done is include an auto incrementing ID as primary key on all the tables.

All my tables except 2 are normalized to 3NF. Two tables 'users' and 'outlets' are not normalized to 2NF.

Along the way I realized that normalization is cumbersome when using auto incrementing ID as a primary key. As normalization is not strictly required, I want to know if there are any downsides of using auto incrementing ID as primary key on all the tables?

答: Its good to use auto incrementing ID as primary key in all the table. This will help you to auto indexing data. If you are planning to us any ORM (Doctrine2 as example) you must need primary key for each table.</p>


问:
DeviceInfo native module is not installed correctly

So I tried implementing Facebook Login and followed all the steps accordingly. After having errors with FBSDKcorekit/FBSDKcorekit.h' file not found, I decided to pivot over to working on other components.

Lo' and behold, I have this error giving me trouble now. I followed along with this video: https://www.youtube.com/watch?v=rAXVKapP5cM&t=458s where I used the react-native install react-native-fbsdk and react-native link react-native-fbsdk commands in my terminal.

If it helps, I'm getting the following compile error in my terminal:
The following build commands failed:

```<code>CompileC /Users/someUser/desiredProject/ios/build/Build/Intermediates/RCTFBSDK.build/Debug-iphonesimulator/RCTFBSDK.build/Objects-normal/x86_64/RCTFBSDKGraphRequestManager.o RCTFBSDK/core/RCTFBSDKGraphRequestManager.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
</code>```

(1 failure)

I'm not sure if it was the tinkering around with the react-native-fbsdk or making links to it that caused this error. Note my project was working before I was trying to implement Facebook Login and using the link command.

What's going on here?

Thanks in advance for your time and patience.

edit: Also I did not implement any of the Facebook login code yet since I couldn't get a successful build on Xcode.

答:
This may happen when upgrading a project to a newer version of react-native. To fix it,

Stop your packager.

Quit your iOS/android simulator.

Reinstall your modules: rm -rf node_modules && npm install

Restart your packager and simulator, e.g. react-native run-ios

Body:
So I tried implementing Facebook Login and followed all the steps accordingly. After having errors with FBSDKcorekit/FBSDKcorekit.h' file not found, I decided to pivot over to working on other components.

Lo' and behold, I have this error giving me trouble now. I followed along with this video: https://www.youtube.com/watch?v=rAXVKapP5cM&t=458s where I used the react-native install react-native-fbsdk and react-native link react-native-fbsdk commands in my terminal.

If it helps, I'm getting the following compile error in my terminal:
The following build commands failed:

CompileC /Users/someUser/desiredProject/ios/build/Build/Intermediates/RCTFBSDK.build/Debug-iphonesimulator/RCTFBSDK.build/Objects-normal/x86_64/RCTFBSDKGraphRequestManager.o RCTFBSDK/core/RCTFBSDKGraphRequestManager.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler

(1 failure)

I'm not sure if it was the tinkering around with the react-native-fbsdk or making links to it that caused this error. Note my project was working before I was trying to implement Facebook Login and using the link command.

What's going on here?

Thanks in advance for your time and patience.

edit: Also I did not implement any of the Facebook login code yet since I couldn't get a successful build on Xcode.


问:
iOS momentum scrolling on scrollable div with fixed positioned child element
I'm working on an angular webapp that has a main navbar and several views that each has its own sub-navbar.

Each view is maintained within a scrollable div, and only a single div is visible at any given time.

These views are hardware accelerated using the 'will-change' CSS property, and momentum scrolling is enabled using the -webkit-overflow-scrolling CSS property.

Inside each of these DIVs there is a sub-navbar that is fixed positioned after the main navbar.

Everything works as expected except for one annoying glitch, on iPad/iPhone the sub-navbar keeps bouncing out and then into its position.

Here's a pen illustrating the problem. Notice those glitches on that yellow SUB MENU when you scroll on iPad/iPhone...

HTML:

```<code><html>
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  </head>
  <body>
    <div class="main_header">
      MAIN MENU
    </div>
    <div class="views-container">
      <div class="view">
        <div class="view-header test">
          SUB MENU
        </div>
        <div>
          CONTENT
        </div>
      </div>
    </div>
  </body>
</html>
</code>```

CSS:

```<code>html, body {
    overflow-x: hidden;
    overflow-y: hidden;
    height: 100%;
}

.main_header {
  background-color:green;
  position: fixed;
  top:0px;
  left: 0px;
  width: 100%;
  opacity: 0.9;
}

.views-container {
  position: fixed;
  top: 18px;
  bottom: 0px;
  left: 0px;
  right: 0px;
}

.view {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  will-change: opacity;
}

.view-header {
  background-color:yellow;
  position: fixed;
  width: 100%;
  opacity: 0.9;
  z-index: 1000;
}
</code>```

I've scoured the web in search for a solution but came up with nothing thus far.
Ideas?

答:
(See bottom of answer for codepen solution)

Testing on my iPhone I could get the sub-menu to not act up by changing from:

```<code><body>
    <div class="main_header">
      MAIN MENU
    </div>
    <div class="views-container">
      <div class="view"> <-- move this div below "view-header test"
        <div class="view-header test">
          SUB MENU
        </div>
        <div class="container-fluid">
</code>```

to:

```<code><body>
    <div class="main_header">
      MAIN MENU
    </div>
    <div class="views-container">
      <div class="view-header test">
          SUB MENU
      </div>
      <div class="view"> <-- move to here
        <div class="container-fluid">
</code>```

It seems like the view class's css causes the sub menu to try and scroll on iphones and ipads.

Let me know if this works for you

EDIT:

Another solution would be to mess around with the css. Basically your .view class contains your .view-header class and therefore with content of the .view-header will also be influenced by the .view class. One solution might be to make a .view-body class where you place any code relevant to the body of the view which you don't want to influence your header. then do

```<code><div class="view">
   <div class="view-header">
      header content. probably does not need to be scroll-able
   </div>
   <div class="view-body">
      body content. probably needs to be scroll-able
   </div
</div>
</code>```

DOUBLE EDIT:

Forked your code and made the changes that I recommended. It works perfectly now on my iPhone. Hope this helps!
https://codepen.io/anon/pen/RgWOGx

Body:
I'm working on an angular webapp that has a main navbar and several views that each has its own sub-navbar.

Each view is maintained within a scrollable div, and only a single div is visible at any given time.

These views are hardware accelerated using the 'will-change' CSS property, and momentum scrolling is enabled using the -webkit-overflow-scrolling CSS property.

Inside each of these DIVs there is a sub-navbar that is fixed positioned after the main navbar.

Everything works as expected except for one annoying glitch, on iPad/iPhone the sub-navbar keeps bouncing out and then into its position.

Here's a pen illustrating the problem. Notice those glitches on that yellow SUB MENU when you scroll on iPad/iPhone...

HTML:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

      MAIN MENU

          SUB MENU

          CONTENT

CSS:

html, body {
    overflow-x: hidden;
    overflow-y: hidden;
    height: 100%;
}

.main_header {
  background-color:green;
  position: fixed;
  top:0px;
  left: 0px;
  width: 100%;
  opacity: 0.9;
}

.views-container {
  position: fixed;
  top: 18px;
  bottom: 0px;
  left: 0px;
  right: 0px;
}

.view {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  will-change: opacity;
}

.view-header {
  background-color:yellow;
  position: fixed;
  width: 100%;
  opacity: 0.9;
  z-index: 1000;
}

I've scoured the web in search for a solution but came up with nothing thus far.
Ideas?

Body:
(See bottom of answer for codepen solution)

Testing on my iPhone I could get the sub-menu to not act up by changing from:

<body>
    <div class="main_header">
      MAIN MENU
    </div>
    <div class="views-container">
      <div class="view"> <-- move this div below "view-header test"
        <div class="view-header test">
          SUB MENU
        </div>
        <div class="container-fluid">

to:

<body>
    <div class="main_header">
      MAIN MENU
    </div>
    <div class="views-container">
      <div class="view-header test">
          SUB MENU
      </div>
      <div class="view"> <-- move to here
        <div class="container-fluid">

It seems like the view class's css causes the sub menu to try and scroll on iphones and ipads.

Let me know if this works for you

EDIT:

Another solution would be to mess around with the css. Basically your .view class contains your .view-header class and therefore with content of the .view-header will also be influenced by the .view class. One solution might be to make a .view-body class where you place any code relevant to the body of the view which you don't want to influence your header. then do

<div class="view">
   <div class="view-header">
      header content. probably does not need to be scroll-able
   </div>
   <div class="view-body">
      body content. probably needs to be scroll-able
   </div
</div>

DOUBLE EDIT:

Forked your code and made the changes that I recommended. It works perfectly now on my iPhone. Hope this helps!
https://codepen.io/anon/pen/RgWOGx


问:
Microsoft bot: How to log each conversation step?
I'm learning how to build a Microsoft Bot and I need to send every message (ie log the user progress through the bot) to an API.

Let's say I have these dialogs with 3 steps each:

/

/welcome

/onboarding

/finish

When a user joins the conversation (Root dialog), I need to make a POST to our API with the following data:

{
  "conversationId": "8n21b2mkmdb9abi26",
  "dialog": "root",
  "step": 1
}

And then, for each following user message, I would update that conversation in our server with the dialog and step.

I tried to use the middleware hook, but it doesn't have the information of which dialog/step the user is currently in.

Any suggestion?

答:
The middleware feature gives you access to the session object. Store the metadata you need in the session object, then access it in your logging middleware.

For a code example, check out: Microsoft/BotBuilder-Samples - Middleware and Logging with BotBuilder Node SDK


问:
Saving Password with Md5
I am using Postgresql,hibernate and Java and I need to store a password. Can someone suggest me how to encrypt the password with md5. Else is there a better way to store secure password in the database

Thanks

答: I've found the Jasypt encryption library to be quite useful.</p>

Title: Saving Password with Md5


问:
Android make view height 50% of screen width
I wish to make a view with the width to be match_parent, but the height to be 50% of the width.

How do I do it?

Is the only way to do it through java code inside the activity? I'll have to read the screen width and set the height that way.

答:
You can achieve any aspect ratio you want using ConstraintLayout.

To set up ConstraintLayout follow this: Build a Responsive UI with ConstraintLayout.
Then you can do something like this:

```<code><android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintDimensionRatio="h,2:1"
        app:layout_constraintHorizontal_bias="0.0" />

</android.support.constraint.ConstraintLayout>
</code>```

Body:
You can achieve any aspect ratio you want using ConstraintLayout.

To set up ConstraintLayout follow this: Build a Responsive UI with ConstraintLayout.
Then you can do something like this:

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintDimensionRatio="h,2:1"
        app:layout_constraintHorizontal_bias="0.0" />

</android.support.constraint.ConstraintLayout>


问:
pandas rows gets shifted after I try to sort
I have this dataframe whose head looks like this:

```<code>Out[8]:
        Date    Value
0   2016-06-30  481100.0
1   2016-05-31  493800.0
2   2015-12-31  514000.0
3   2015-10-31  510700.0
</code>```

I want to use the Dates column as the index and then sort the rows based on order of the Dates.

When I try to sort it based on the first column with:

```<code>df.set_index('Date', inplace=True)
</code>```

the head then looks like this:

```<code>            Value
Date
2016-06-30  481100.0
2016-05-31  493800.0
2015-12-31  514000.0
2015-10-31  510700.0
</code>```

Not only the dataframe is not ordered based on the dates, the headers are messed up:

Why does this happen and how should I correct it?

Body:
I have this dataframe whose head looks like this:

Out[8]:
        Date    Value
0   2016-06-30  481100.0
1   2016-05-31  493800.0
2   2015-12-31  514000.0
3   2015-10-31  510700.0

I want to use the Dates column as the index and then sort the rows based on order of the Dates.

When I try to sort it based on the first column with:

df.set_index('Date', inplace=True)

the head then looks like this:

            Value
Date
2016-06-30  481100.0
2016-05-31  493800.0
2015-12-31  514000.0
2015-10-31  510700.0

Not only the dataframe is not ordered based on the dates, the headers are messed up:

Why does this happen and how should I correct it?

Body:
You should use sort_values:

In [3]: df
Out[3]:
         Date     Value
0  2016-06-30  481100.0
1  2016-05-31  493800.0
2  2015-12-31  514000.0
3  2015-10-31  510700.0

In [4]: df = df.sort_values(by='Date')

In [5]: df
Out[5]:
         Date     Value
3  2015-10-31  510700.0
2  2015-12-31  514000.0
1  2016-05-31  493800.0
0  2016-06-30  481100.0

EDIT:
Once sorted, you can set your desired column as index of the dataframe:

In [6]: df.set_index('Date', inplace=True)

In [7]: df
Out[7]:
               Value
Date
2015-10-31  510700.0
2015-12-31  514000.0
2016-05-31  493800.0
2016-06-30  481100.0


问:
Compile CSS/JS files on Save using Bundler and Minifier
I have recently switched from Visual Studio 2013 to Visual Studio 2015 for developing my Web Application in MVC.
We are using the LESS and JS files to compile to the Minified versions of both these files types.

Now in VS2013 there was a feature where in the LESS file used to compile automatically to .CSS file on any change made to .LESS files.The Same used to happen on JS files with .min.js file being updated on any change to JS files.

So now for VS2015 I know that there are new independent extensions for doing this namely the "Web Compiler" and "Bundler and Minifier" for which I have done comprehensive study as well, but I am still not able to use them to update the minified versions if .LESS or .JS files are changed accordingly.

I know that there are these Task Runners called Grunt and Gulp available for VS2015 but I need to know how can I achieve this compilation on save using these tools.

答:
Answer 1
This can often be fixed by deleting the %localappdata%\temp\WebCompiler??? folder.

Sometimes you need to restart VS, sometimes you don't.

Doesn't work for everyone, but seems to work for a lot of people.

Answer 2
For those interested, I found another answer to this, which seems to offer an extra side benefit.

If you add a Razor view to your project (I named it JsHelper.cshtml and added it in \Views\Shared) and use the following for the contents (extra line breaks added to make it fit in the SO width)...

```<code>@model string
@{
  string ext = HttpContext.Current != null
               && HttpContext.Current.Request.Url.Host.Contains("localhost")
    ? ""
    : ".es5.min";
}
<script src="/Scripts/@Model@(ext).js" type="text/javascript"></script>
</code>```

...then instead of adding script tags like this...

```<code><script src="/Scripts/General.es5.min.js" type="text/javascript"></script>
</code>```

...you can add this...

```<code>@Html.Partial("~/Views/Shared/JsHelper.cshtml", "General")
</code>```

When you are running the web site in Visual Studio, the uncompiled version of the Javascript file will be used. When running anywhere else (eg on the production server), the .es5.min.js version will be used.

As publishing a web project involves building it, which will compile the .js files, you can be confident that the compiled and minified files that are published are up-to-date.

This has the side-benefit that when debugging your scripts in the browser, you have access to the full version of the .js file, instead of the compiled and minified version that you would get if you referenced them directly. As another breaking change that occurred in the latest version of Web Compiler is that they no longer produce .map.js files when compiling, this is a huge side benefit.

Hope this helps.

Body:
Answer 1
This can often be fixed by deleting the %localappdata%\temp\WebCompiler??? folder.

Sometimes you need to restart VS, sometimes you don't.

Doesn't work for everyone, but seems to work for a lot of people.

Answer 2
For those interested, I found another answer to this, which seems to offer an extra side benefit.

If you add a Razor view to your project (I named it JsHelper.cshtml and added it in \Views\Shared) and use the following for the contents (extra line breaks added to make it fit in the SO width)...

@model string
@{
  string ext = HttpContext.Current != null
               && HttpContext.Current.Request.Url.Host.Contains("localhost")
    ? ""
    : ".es5.min";
}
<script src="/Scripts/@Model@(ext).js" type="text/javascript"></script>

...then instead of adding script tags like this...

<script src="/Scripts/General.es5.min.js" type="text/javascript"></script>

...you can add this...

@Html.Partial("~/Views/Shared/JsHelper.cshtml", "General")

When you are running the web site in Visual Studio, the uncompiled version of the Javascript file will be used. When running anywhere else (eg on the production server), the .es5.min.js version will be used.

As publishing a web project involves building it, which will compile the .js files, you can be confident that the compiled and minified files that are published are up-to-date.

This has the side-benefit that when debugging your scripts in the browser, you have access to the full version of the .js file, instead of the compiled and minified version that you would get if you referenced them directly. As another breaking change that occurred in the latest version of Web Compiler is that they no longer produce .map.js files when compiling, this is a huge side benefit.

Hope this helps.