问:
Java - Store the changing int variable
So I'm trying to write the most simple game , everytime "the monster" attacks "the player" I want the variable "int totalHealth" to be lowered .

```<code>public void attack(Player somePlayer) {

    int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();

    int remainingHealth = totalHealth - damage;
    if (remainingHealth == 0 || remainingHealth < 0) {
        System.out.println("Your player died");
    } else {
        System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
        System.out.println("Your remaining health is - " + (remainingHealth - somePlayer.getStrength()));
    }

}
</code>```

But the problem is that variable "remainingHealth" stays same , only the first time when I run the code it lowers , every next time it stays same,  I guess the problem is in this line :

```<code>int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
</code>```

I guess everytime I run the code

```<code>somePlayer.getHitpoints()
</code>```

takes the inserted integer from constructor and that's the problem.

I need to figure out the way to store the remaining health in a variable somehow

Player class :

```<code>public class Player implements ISavable{

private String name;
private int hitPoints ;
private int strength ;
private String weapon;
private int damage;
private int totalHealth = hitPoints + strength;

public Player(String name, int damage , int hitPoints , int strength) {
    this.name = name;
    this.damage = damage;
    this.weapon = "Sword";
    this.hitPoints = hitPoints;
    this.strength = strength;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getHitPoints() {
    return hitPoints;
}

public void setHitPoints(int hitPoints) {
    this.hitPoints = hitPoints;
}

public int getStrength() {
    return strength;
}

public void setStrength(int strength) {
    this.strength = strength;
}

public String getWeapon() {
    return weapon;
}

public void setWeapon(String weapon) {
    this.weapon = weapon;
}

public int getTotalHealth() {
    return totalHealth;
}

public void setTotalHealth(int totalHealth) {
    this.totalHealth = totalHealth;
}

@Override
public String toString() {
    return "Player{" +
            "name='" + name + '\'' +
            ", hitPoints=" + hitPoints +
            ", strength=" + strength +
            ", weapon='" + weapon + '\'' +
            '}';
}

@Override
public List<String> write() {
    List<String> values = new ArrayList<String>();
    values.add(0, this.name);
    values.add(1, "" + this.hitPoints);
    values.add(2, "" + this.strength);
    values.add(3, "" + this.weapon);
    values.add(4,"" + this.damage);
    return values;
}

@Override
public void read(List<String> savedValues) {
    if (savedValues != null && savedValues.size()>0){
        this.name = savedValues.get(0);
        this.hitPoints = Integer.parseInt(savedValues.get(1));
        this.strength = Integer.parseInt(savedValues.get(2));
        this.weapon = savedValues.get(3);
    }
}

public void attack(Monster someMonster){
    int health = someMonster.getHitPoints();
    int remainingHealth = health - damage;
    if (remainingHealth == 0 || remainingHealth < 0) {
        System.out.println("You killed the monster !!!");
    } else {
        System.out.println("You attacked the monster " + " and made " + this.damage + " damage");
        System.out.println("Monsters remaining health is - " + remainingHealth);
    }

    if (someMonster.isDead()){
        this.hitPoints = 100;
        this.strength = 50;
    }
}

public void healPlayer(Player somePlayer){
    int hp = somePlayer.getHitPoints();
    hp += 10;
    System.out.println("You healed the player for 10hp , your current hp is " + hp);
}
</code>```

}

答:
You are not updating the value of totalHealth, you initialize it everytime that attack() method is called, so you always have the same Health.

You can solve it putting out of the attack() method the line:

```<code>int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
</code>```

EDIT:

```<code>public void attack(Player somePlayer) {

    somePlayer.totalHealth = somePlayer.totalHealth - this.damage;
    if (somePlayer.totalHealth.equals(0) || somePlayer.totalHealth < 0) {
        System.out.println("Your player died");
    } else {
        System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
        System.out.println("Your remaining health is - " + (somePlayer.totalHealth - somePlayer.getStrength()));
    }

}
</code>```

Title: Java - Store the changing int variable

Body:
So I'm trying to write the most simple game , everytime "the monster" attacks "the player" I want the variable "int totalHealth" to be lowered .

public void attack(Player somePlayer) {

    int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();

    int remainingHealth = totalHealth - damage;
    if (remainingHealth == 0 || remainingHealth < 0) {
        System.out.println("Your player died");
    } else {
        System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
        System.out.println("Your remaining health is - " + (remainingHealth - somePlayer.getStrength()));
    }

}

But the problem is that variable "remainingHealth" stays same , only the first time when I run the code it lowers , every next time it stays same,  I guess the problem is in this line :

int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();

I guess everytime I run the code

somePlayer.getHitpoints()

takes the inserted integer from constructor and that's the problem.

I need to figure out the way to store the remaining health in a variable somehow

Player class :

public class Player implements ISavable{

private String name;
private int hitPoints ;
private int strength ;
private String weapon;
private int damage;
private int totalHealth = hitPoints + strength;

public Player(String name, int damage , int hitPoints , int strength) {
    this.name = name;
    this.damage = damage;
    this.weapon = "Sword";
    this.hitPoints = hitPoints;
    this.strength = strength;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getHitPoints() {
    return hitPoints;
}

public void setHitPoints(int hitPoints) {
    this.hitPoints = hitPoints;
}

public int getStrength() {
    return strength;
}

public void setStrength(int strength) {
    this.strength = strength;
}

public String getWeapon() {
    return weapon;
}

public void setWeapon(String weapon) {
    this.weapon = weapon;
}

public int getTotalHealth() {
    return totalHealth;
}

public void setTotalHealth(int totalHealth) {
    this.totalHealth = totalHealth;
}

@Override
public String toString() {
    return "Player{" +
            "name='" + name + '\'' +
            ", hitPoints=" + hitPoints +
            ", strength=" + strength +
            ", weapon='" + weapon + '\'' +
            '}';
}

@Override
public List<String> write() {
    List<String> values = new ArrayList<String>();
    values.add(0, this.name);
    values.add(1, "" + this.hitPoints);
    values.add(2, "" + this.strength);
    values.add(3, "" + this.weapon);
    values.add(4,"" + this.damage);
    return values;
}

@Override
public void read(List<String> savedValues) {
    if (savedValues != null && savedValues.size()>0){
        this.name = savedValues.get(0);
        this.hitPoints = Integer.parseInt(savedValues.get(1));
        this.strength = Integer.parseInt(savedValues.get(2));
        this.weapon = savedValues.get(3);
    }
}

public void attack(Monster someMonster){
    int health = someMonster.getHitPoints();
    int remainingHealth = health - damage;
    if (remainingHealth == 0 || remainingHealth < 0) {
        System.out.println("You killed the monster !!!");
    } else {
        System.out.println("You attacked the monster " + " and made " + this.damage + " damage");
        System.out.println("Monsters remaining health is - " + remainingHealth);
    }

    if (someMonster.isDead()){
        this.hitPoints = 100;
        this.strength = 50;
    }
}

public void healPlayer(Player somePlayer){
    int hp = somePlayer.getHitPoints();
    hp += 10;
    System.out.println("You healed the player for 10hp , your current hp is " + hp);
}

}

Body:
You are not updating the value of totalHealth, you initialize it everytime that attack() method is called, so you always have the same Health.

You can solve it putting out of the attack() method the line:

int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();

EDIT:

public void attack(Player somePlayer) {

    somePlayer.totalHealth = somePlayer.totalHealth - this.damage;
    if (somePlayer.totalHealth.equals(0) || somePlayer.totalHealth < 0) {
        System.out.println("Your player died");
    } else {
        System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
        System.out.println("Your remaining health is - " + (somePlayer.totalHealth - somePlayer.getStrength()));
    }

}


来源: stackexchange

问:
Escape XML entities only once
I have the following XML snippet in a string (note the double encoded &):

```<code>...
<PARA>
S&P
</PARA>
...
</code>```

My desired output would be:

```<code>> ... <PARA> S&P </PARA> ...
</code>```

If I use:

StringEscapeUtils.unescapeXml()

The actual oputput is:

```<code> > ... <PARA> S&P </PARA> ...
</code>```

It seems that StringEscapeUtils.unescapeXml() escapes the input twice, or as long as it contains entities.

Is there a better utility method, or simple solution that can unescape every xml entity (not just a few but all accentuated character) once, so that my encoded & part does not get screwed up?

Thank,
Peter

答:
Perhaps a long winded way of doing it, but I can't use Apache Commons

```<code>public static void main(String[] args) {
        String a = "<PARA> S&amp;P </PARA>";
        String ea = unescapeXML(a);
        System.out.println(ea);
    }

    public static String unescapeXML(final String xml) {
        Pattern xmlEntityRegex = Pattern.compile("&(#?)([^;]+);");
        StringBuffer unescapedOutput = new StringBuffer(xml.length());

        Matcher m = xmlEntityRegex.matcher(xml);
        Map<String, String> builtinEntities = null;
        String entity;
        String hashmark;
        String ent;
        int code;
        while (m.find()) {
            ent = m.group(2);
            hashmark = m.group(1);
            if ((hashmark != null) && (hashmark.length() > 0)) {
                code = Integer.parseInt(ent);
                entity = Character.toString((char) code);
            } else {
                if (builtinEntities == null) {
                    builtinEntities = buildBuiltinXMLEntityMap();
                }
                entity = builtinEntities.get(ent);
                if (entity == null) {
                    entity = "&" + ent + ';';
                }
            }
            m.appendReplacement(unescapedOutput, entity);
        }
        m.appendTail(unescapedOutput);
        return unescapedOutput.toString();

    }

    private static Map<String, String> buildBuiltinXMLEntityMap() {
        Map<String, String> entities = new HashMap<>(10);
        entities.put("lt", "<");
        entities.put("gt", ">");
        entities.put("amp", "&");
        entities.put("apos", "'");
        entities.put("quot", "\"");
        return entities;
    }
</code>```

Output:

```<code><PARA> S&P </PARA>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Escape XML entities only once

Body:
I have the following XML snippet in a string (note the double encoded &):

...
<PARA>
S&amp;P
</PARA>
...

My desired output would be:

> ... <PARA> S&P </PARA> ...

If I use:

StringEscapeUtils.unescapeXml()

The actual oputput is:

 > ... <PARA> S&P </PARA> ...

It seems that StringEscapeUtils.unescapeXml() escapes the input twice, or as long as it contains entities.

Is there a better utility method, or simple solution that can unescape every xml entity (not just a few but all accentuated character) once, so that my encoded & part does not get screwed up?

Thank,
Peter

Body:
Perhaps a long winded way of doing it, but I can't use Apache Commons

public static void main(String[] args) {
        String a = "&lt;PARA&gt; S&amp;amp;P &lt;/PARA&gt;";
        String ea = unescapeXML(a);
        System.out.println(ea);
    }

    public static String unescapeXML(final String xml) {
        Pattern xmlEntityRegex = Pattern.compile("&(#?)([^;]+);");
        StringBuffer unescapedOutput = new StringBuffer(xml.length());

        Matcher m = xmlEntityRegex.matcher(xml);
        Map<String, String> builtinEntities = null;
        String entity;
        String hashmark;
        String ent;
        int code;
        while (m.find()) {
            ent = m.group(2);
            hashmark = m.group(1);
            if ((hashmark != null) && (hashmark.length() > 0)) {
                code = Integer.parseInt(ent);
                entity = Character.toString((char) code);
            } else {
                if (builtinEntities == null) {
                    builtinEntities = buildBuiltinXMLEntityMap();
                }
                entity = builtinEntities.get(ent);
                if (entity == null) {
                    entity = "&" + ent + ';';
                }
            }
            m.appendReplacement(unescapedOutput, entity);
        }
        m.appendTail(unescapedOutput);
        return unescapedOutput.toString();

    }

    private static Map<String, String> buildBuiltinXMLEntityMap() {
        Map<String, String> entities = new HashMap<>(10);
        entities.put("lt", "<");
        entities.put("gt", ">");
        entities.put("amp", "&");
        entities.put("apos", "'");
        entities.put("quot", "\"");
        return entities;
    }

Output:

<PARA> S&amp;P </PARA>


问:
Unexpected namespace prefix "app" found for tag TextView when I try to set fontFamily attribute
I set app:fontFamily="@font/montserrat_bold" on TextView and i get error: Unexpected namespace prefix "app" found for tag TextView. I use Android Studio 3.0. Is there any solution?

答:
Not required

```<code>app:fontFamily="@font/montserrat_bold"
</code>```

Change to ,

```<code>android:fontFamily="@font/montserrat_bold"
</code>```

it will work for sure.

Body:
Not required

app:fontFamily="@font/montserrat_bold"

Change to ,

android:fontFamily="@font/montserrat_bold"

it will work for sure.


答: On Player create a function updateHealth(int newHealth) that sets the variable returned from getHitPoints() to newHealth. Then just append somePlayer.updateHealth(somePlayer.getHitPoints() - damage); at the end of the attack function.

Title: Java - Store the changing int variable


问:
Clojure core.async. How to download lazily with go block inside with-open?
It`s a continuation of my previous question How to produce a lazy sequence by portion in clojure?

I want download data from a database by portions. Initially I download first 500 rows and then I send a request to fetch next 500 rows and so on until I receive all data from a server.

I wrote the code:

```<code>(jdbc/atomic conn
 (with-open [cursor (jdbc/fetch-lazy conn [sql_query])]
   (let [lazyseq (jdbc/cursor->lazyseq cursor)
         counter (atom 1)]
     (swap! lazyseq_maps assoc :session_id {:get_next? (chan 1) :over_500 (chan 1) :data []})
     (>!! (:get_next? (:session_id @lazyseq_maps)) true)
     (go
       (doseq [row lazyseq]
         (swap! counter inc)
         (when (<! (:get_next? (:session_id @lazyseq_maps)))
           (swap! lazyseq_maps update-in [:session_id :data] conj row)
           (if (not= 0 (mod @counter 500))
             (>! (:get_next? (:session_id @lazyseq_maps)) true)
             (>! (:over_500 (:session_id @lazyseq_maps)) true))))
        ;
        (close! (:get_next? (:session_id @lazyseq_maps)))
        (close! (:over_500 (:session_id @lazyseq_maps)))
        (.close conn))

     (when (<!! (:over_500 (:session_id @lazyseq_maps))) {:message "over 500 rows"
                                                          :id :session_id
                                                          :data (:data (:session_id @lazyseq_maps))}))))
</code>```

I fetch rows with help of the doseq cycle. When doseq passed 500 rows I park the cycle (when (<! (:get_next? (:session_id @lazyseq_maps))) and wait for a signal from outside to retrieve next 500 rows.

But here I have a problem. When I send the signal, the program throws error "Resultset is closed". I.e connection is closed outside with-open scope. But I don`t understand why, because go block is placed inside with-open scope. Can you help me solve the problem?

答:
Unless you are on a seriously memory constrained system, I would recommend just load all rows at once to RAM and close the DB connection. Otherwise your complete solution will likely be very complex and difficult to test and reason about.

If you have tens of millions of rows maybe you could fetch them in some partitions?

Body:
It`s a continuation of my previous question How to produce a lazy sequence by portion in clojure?

I want download data from a database by portions. Initially I download first 500 rows and then I send a request to fetch next 500 rows and so on until I receive all data from a server.

I wrote the code:

(jdbc/atomic conn
 (with-open [cursor (jdbc/fetch-lazy conn [sql_query])]
   (let [lazyseq (jdbc/cursor->lazyseq cursor)
         counter (atom 1)]
     (swap! lazyseq_maps assoc :session_id {:get_next? (chan 1) :over_500 (chan 1) :data []})
     (>!! (:get_next? (:session_id @lazyseq_maps)) true)
     (go
       (doseq [row lazyseq]
         (swap! counter inc)
         (when (<! (:get_next? (:session_id @lazyseq_maps)))
           (swap! lazyseq_maps update-in [:session_id :data] conj row)
           (if (not= 0 (mod @counter 500))
             (>! (:get_next? (:session_id @lazyseq_maps)) true)
             (>! (:over_500 (:session_id @lazyseq_maps)) true))))
        ;
        (close! (:get_next? (:session_id @lazyseq_maps)))
        (close! (:over_500 (:session_id @lazyseq_maps)))
        (.close conn))

     (when (<!! (:over_500 (:session_id @lazyseq_maps))) {:message "over 500 rows"
                                                          :id :session_id
                                                          :data (:data (:session_id @lazyseq_maps))}))))

I fetch rows with help of the doseq cycle. When doseq passed 500 rows I park the cycle (when (<! (:get_next? (:session_id @lazyseq_maps))) and wait for a signal from outside to retrieve next 500 rows.

But here I have a problem. When I send the signal, the program throws error "Resultset is closed". I.e connection is closed outside with-open scope. But I don`t understand why, because go block is placed inside with-open scope. Can you help me solve the problem?


问:
Scaling generated content in CSS
How do you scale an image added in :before or :after in CSS?

For example, I have a page which contains a book cover:

```<code><span class="book">
    <img src="http://ecx.images-amazon.com/images/I/41t7xMPK%2B6L.jpg" />
</span>
</code>```

I want to use CSS to make it look more like a book, rather than just a cover.  I can use :before to add a second image to do this, but as all books vary in size, I need to be able to scale this image to fit the book cover.

I have tried

```<code>.book:before{
    content:url("/images/book.png");
    position:absolute;
    height:100%;
    width:100%;

}
</code>```

but this doesn't work in scaling the image.

答: Try setting a min-height and a max-height for both of them to the same value, It should then scale the images to the correct size while keeping the correct aspect ratio. (And do that with the width, depending on which one you want to scale)

ContentLicense: CC BY-SA 2.5

Title: Scaling generated content in CSS

Body:
How do you scale an image added in :before or :after in CSS?

For example, I have a page which contains a book cover:

I want to use CSS to make it look more like a book, rather than just a cover.  I can use :before to add a second image to do this, but as all books vary in size, I need to be able to scale this image to fit the book cover.

I have tried

.book:before{
    content:url("/images/book.png");
    position:absolute;
    height:100%;
    width:100%;

}

but this doesn't work in scaling the image.


问:
Getting an exception ORA-00942: table or view does not exist - when inserting into an existing table
I am getting below exception, when trying to insert a batch of rows to an existing table

ORA-00942: table or view does not exist

I can confirm that the table exists in db and I can insert data to that table using oracle
sql developer. But when I try to insert rows using preparedstatement in java, its throwing table does not exist error.

Please find the stack trace of error below

```<code>java.sql.SQLException: ORA-00942: table or view does not exist

    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
    at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
    at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:573)
    at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1889)
    at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1093)
    at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2047)
    at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout>>(OracleStatement.java:2709)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:589)
    at quotecopy.DbConnection.insertIntoDestinationDb(DbConnection.java:591)
    at quotecopy.QuoteCopier.main(QuoteCopier.java:72)
</code>```

Can anyone suggest the reasons for this error ?

Update : Issue solved

There was no problem with my database connection properties or with my table or view name. The solution to the problem was very strange. One of the columns that I was trying insert was of Clob type. As I had a lot of trouble handling clob data in oracle db before, gave a try by replacing the clob setter with a temporary string setter and the same code executed with out any problems and all the rows were correctly inserted!!!.

ie. peparedstatement.setClob(columnIndex, clob)

was replaced with

peparedstatement.setString(columnIndex, "String")

Why an error table or view does exist error was throws for error in inserting clob data. Could anyone of you please explain ?

Thanks a lot for your answers and comments.

答: Here I got the solution for the question. The problem is on glass fish if you are using it. When you create JNDI name  make sure pool name is correct and pool name is the name of connection pool name that you are created.

Body:
I am getting below exception, when trying to insert a batch of rows to an existing table

ORA-00942: table or view does not exist

I can confirm that the table exists in db and I can insert data to that table using oracle
sql developer. But when I try to insert rows using preparedstatement in java, its throwing table does not exist error.

Please find the stack trace of error below

java.sql.SQLException: ORA-00942: table or view does not exist

    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
    at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
    at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:573)
    at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1889)
    at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1093)
    at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2047)
    at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout>>(OracleStatement.java:2709)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:589)
    at quotecopy.DbConnection.insertIntoDestinationDb(DbConnection.java:591)
    at quotecopy.QuoteCopier.main(QuoteCopier.java:72)

Can anyone suggest the reasons for this error ?

Update : Issue solved

There was no problem with my database connection properties or with my table or view name. The solution to the problem was very strange. One of the columns that I was trying insert was of Clob type. As I had a lot of trouble handling clob data in oracle db before, gave a try by replacing the clob setter with a temporary string setter and the same code executed with out any problems and all the rows were correctly inserted!!!.

ie. peparedstatement.setClob(columnIndex, clob)

was replaced with

peparedstatement.setString(columnIndex, "String")

Why an error table or view does exist error was throws for error in inserting clob data. Could anyone of you please explain ?

Thanks a lot for your answers and comments.


问:
How to get RSSI in iOS9
I have BLE source code that displays several warnings and I am new to
BLE. Please see the code below. I have tried replacing with readRSSI but tells me I can’t compare an Int with Void. How do I get an Int value for readRSSI? Or how should I change the code?

```<code>- (void)peripheralDidUpdateRSSI:(CBPeripheral * _Nonnull)peripheral error:(NSError * _Nullable)error
{
    if (!isConnected)
        return;
    if (rssi != peripheral.RSSI.intValue)
    {
        rssi = peripheral.RSSI.intValue;
        [[self delegate] bleDidUpdateRSSI:activePeripheral.RSSI];
    }
}
</code>```

*rssi is a static int.

*isConnected is a boolean.

Edit: The problem is that RSSI is deprecated since iOS 8.0.

答:
swift 3 </p>

```<code>@IBAction func btnGetRSSI(_ sender: UIButton){

    self.selectedPeripehral.readRSSI()
}

func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {

    var rssiInt: Int!

    rssiInt = RSSI.intValue

}
</code>```

Title: How to get RSSI in iOS9

Body:
I have BLE source code that displays several warnings and I am new to
BLE. Please see the code below. I have tried replacing with readRSSI but tells me I can’t compare an Int with Void. How do I get an Int value for readRSSI? Or how should I change the code?

- (void)peripheralDidUpdateRSSI:(CBPeripheral * _Nonnull)peripheral error:(NSError * _Nullable)error
{
    if (!isConnected)
        return;
    if (rssi != peripheral.RSSI.intValue)
    {
        rssi = peripheral.RSSI.intValue;
        [[self delegate] bleDidUpdateRSSI:activePeripheral.RSSI];
    }
}

*rssi is a static int.

*isConnected is a boolean.

Edit: The problem is that RSSI is deprecated since iOS 8.0.

Body:
swift 3

@IBAction func btnGetRSSI(_ sender: UIButton){

    self.selectedPeripehral.readRSSI()
}

func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {

    var rssiInt: Int!

    rssiInt = RSSI.intValue

}


问:
Java batch application and idle thread pool
I have java application processing batch files, the service is bursty, i get many or few files and then no processing for some time, sometimes for hours. I have a thread pool to process batch file requests in parallel. I observe that first procesing after the idle time is slow and then it picks up the speed. Apllication is up for days, warmed up, but there is no consistent response time after application inactivity. Do threads really become 'cold' after idle time? if so, what's the way to keep application warmed up during inactivity time?

Here is my ThreadPoolTaskExecutor initialization:

```<code>final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(100);
        executor.setMaxPoolSize(2000);
        executor.setQueueCapacity(250);
        executor.setThreadNamePrefix(prefix);
        executor.setKeepAliveSeconds(20);
        executor.setWaitForTasksToCompleteOnShutdown(wait);
</code>```

答:
There are two type of threads in ThreadPoolExecutor : core and non-core.
Core threads are always active and can't be terminated by default. It's only possible to terminate them using allowCoreThreadTimeOut. In contrast non-core threads are terminated if they are idle longer than keepAliveTime. Here is comprehensive description of ThreadPoolExecutor configuration parameters. So only core threads can keep pool warm and give you a consistent response time. ExecutorService.newFixedThreadPool with give number of core threads seems like a suitable thread pool configuration for your case. Trade-off is a constant usage of OS resources for keeping threads active.

Body:
I have java application processing batch files, the service is bursty, i get many or few files and then no processing for some time, sometimes for hours. I have a thread pool to process batch file requests in parallel. I observe that first procesing after the idle time is slow and then it picks up the speed. Apllication is up for days, warmed up, but there is no consistent response time after application inactivity. Do threads really become 'cold' after idle time? if so, what's the way to keep application warmed up during inactivity time?

Here is my ThreadPoolTaskExecutor initialization:

final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(100);
        executor.setMaxPoolSize(2000);
        executor.setQueueCapacity(250);
        executor.setThreadNamePrefix(prefix);
        executor.setKeepAliveSeconds(20);
        executor.setWaitForTasksToCompleteOnShutdown(wait);


问:
Want a counter in aws Dynamodb
I have a table with column "Name" and "Vote", I want to increase the Vote count whenever I do update_item. I tried the below query but no luck.

```<code>       db.update_item(Key={ "Name":"Dany"},
                      UpdateExpression='ADD #oldVote :newVote',
                      ExpressionAttributeNames={ '#oldVote' :'Vote'},
                      ExpressionAttributeValues={':newVote': {"N": "1"}}
                      )
</code>```

Getting error as:

"An error occurred (ValidationException) when calling the UpdateItem
  operation: Invalid UpdateExpression: Incorrect operand type for
  operator or function; operator: ADD, operand type: MAP"

error

答:
Please try the below update. It should resolve the problem.</p>

```<code>db.update_item(Key={ "Name":"Dany"},
              UpdateExpression='SET #oldVote = #oldVote + :newVote',
              ExpressionAttributeNames={ '#oldVote' :'Vote'},
              ExpressionAttributeValues={':newVote': 1}
              )
</code>```

Title: Want a counter in aws Dynamodb

Body:
I have a table with column "Name" and "Vote", I want to increase the Vote count whenever I do update_item. I tried the below query but no luck.

       db.update_item(Key={ "Name":"Dany"},
                      UpdateExpression='ADD #oldVote :newVote',
                      ExpressionAttributeNames={ '#oldVote' :'Vote'},
                      ExpressionAttributeValues={':newVote': {"N": "1"}}
                      )

Getting error as:

"An error occurred (ValidationException) when calling the UpdateItem
  operation: Invalid UpdateExpression: Incorrect operand type for
  operator or function; operator: ADD, operand type: MAP"

error

Body:
Please try the below update. It should resolve the problem.

db.update_item(Key={ "Name":"Dany"},
              UpdateExpression='SET #oldVote = #oldVote + :newVote',
              ExpressionAttributeNames={ '#oldVote' :'Vote'},
              ExpressionAttributeValues={':newVote': 1}
              )


问:
How to change EditText background color when I enter text?
My EditText has some color, but when I enter some text it should change. Say it's grey, I started to enter and it's yellow. This EditText is also focused, so when this activity starts -- I already can enter the text. How I tried:

```<code><style name="LoginEnterField">
    <item name="android:textColorHint">@color/black</item>
    <item name="android:textColor">@color/black</item>
    <item name="android:background">@drawable/selector_edittext</item>
    <item name="android:textSize">@dimen/general_text_size</item>
    <item name="android:paddingLeft">@dimen/activity_inner_horizontal_margin</item>
    <item name="android:paddingRight">@dimen/activity_inner_horizontal_margin</item>
</style>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">
    <solid android:color="@color/grey"/>
    <corners android:radius="5dp" />

</shape>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

  android:shape="rectangle">
  <solid android:color="@color/yellow"/>
  <corners android:radius="5dp" />

</shape>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" android:drawable="@drawable/roundbox_active_style"/>
  <item android:drawable="@drawable/roundbox_inactive_style" />
</selector>
</code>```

I think the point is in this selector. My EditText changes color, but it always yellow. How to make it became yellow only if I enter some text? I can't make any code changes! It's very important. I can't add or change only xml files.

EDIT: It's impossible to do from xml only, so make code changes.

答:
Use  TextWatcher.

When an object of a type is attached to an Editable, its methods will be called when the text is changed.

onTextChanged (CharSequence s, int start, int before, int count) -
  This method is called to notify you that, within s, the count
  characters beginning at start have just replaced old text that had
  length before.

```<code>  public void onTextChanged(CharSequence s, int start, int before, int count) {
                // Your Code // call .setBackgroundColor method here

    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My EditText has some color, but when I enter some text it should change. Say it's grey, I started to enter and it's yellow. This EditText is also focused, so when this activity starts -- I already can enter the text. How I tried:

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">
    <solid android:color="@color/grey"/>
    <corners android:radius="5dp" />

</shape>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

  android:shape="rectangle">
  <solid android:color="@color/yellow"/>
  <corners android:radius="5dp" />

</shape>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" android:drawable="@drawable/roundbox_active_style"/>
  <item android:drawable="@drawable/roundbox_inactive_style" />
</selector>

I think the point is in this selector. My EditText changes color, but it always yellow. How to make it became yellow only if I enter some text? I can't make any code changes! It's very important. I can't add or change only xml files.

EDIT: It's impossible to do from xml only, so make code changes.

Body:
Use  TextWatcher.

When an object of a type is attached to an Editable, its methods will be called when the text is changed.

onTextChanged (CharSequence s, int start, int before, int count) -
  This method is called to notify you that, within s, the count
  characters beginning at start have just replaced old text that had
  length before.

  public void onTextChanged(CharSequence s, int start, int before, int count) {
                // Your Code // call .setBackgroundColor method here

    }


问:
Google maps API. Get continent where the country is located
There is a simple query to google API

https://maps.googleapis.com/maps/api/geocode/json?address=&components=country:Russia&language=ru&key=MY_API_KEY

Response contain the bounds, location and full address (for example - Russia)

But i need to now that - Russia -> Europe, USA -> north America, Egypt -> Africa.

How to do it?!

答:
You can use http://country.io/continent.json to map country ISO2 code to continent ISO2 code.

And convert continent ISO2 code to its with this dataset https://github.com/datasets/continent-codes/blob/master/data/continent-codes.csv

Example of country ISO2 code to continent ISO2 code {"BD": "AS", "BE": "EU", "BF": "AF"...}


问:
Unable to view Form page in CodeIgniter facing Error
This is my home.php file in this controller I am facing Fatal error: Uncaught ArgumentCountError:
I have also attached a screenshot, In this screenshot error mentioned, You can easily understand the error through this screenshot, I am newbie in CodeIgniter.
[
I upload only my controller related file.

```<code><?php

class home extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('select');
        $this->load->helper(array('form', 'url', 'html'));
        $this->load->library(array('form_validation', 'session'));
    }

    function records() {
        $ytl['dta'] = $this->users->datas();
        //$this->load->view('info',$ytl);
        //echo "```controller";print_r($ytl);
    }

    function primezone() {
        $ytl['dta'] = $this->users->datas();
        echo "```controller";
        print_r($ytl);
    }

    function form($id) {
        //die($id);
        if ($this->input->post()) {
            //echo"```";print_r( $this->input->post());die;
            $this->form_validation->set_rules('fname', 'First Name', 'required|min_length[5]');
            $this->form_validation->set_rules('lname', 'Last Name', 'required|callback_check_picture[lname]');

            //$this->form_validation->set_rules('email','Email','required');

            $this->form_validation->set_rules('mobile', 'Mobile Number', 'required|callback_valid_phone_number[mobile]');

            $this->form_validation->set_error_delimiters('
', '
');
            if ($this->form_validation->run() == TRUE) {
                $data = [

                    'fname'   => $this->input->post('fname'),
                    'lname'   => $this->input->post('lname'),
                    'email'   => $this->input->post('email'),
                    'mobile'  => $this->input->post('mobile'),
                    'message' => $this->input->post('message'),
                ];
                if (empty($id)) {
                    $ytl = $this->select->insertdata($data);

                } else {
                    $ytl = $this->select->updatedata($data, $id);
                }
                if ($ytl) {
                    $this->session->set_flashdata('message', 'Successfully Added.');
                    redirect('home');
                }
            } else {
                //$this->load->view('form');
            }
        }
        $ytl['dta'] = $this->select->getDataById($id);
        //echo "```";print_r($ytl);die;
        $this->load->view('form', $ytl);
    }

    public function check_picture($a) {
        if ( ! is_numeric($a)) {
            return TRUE;
        } else {
            $this->form_validation->set_message('check_picture', 'Please enter only char value');

            return FALSE;
        }
    }

    function valid_phone_number($value) {
        $value = strlen($value);
        //echo $value;die;
        if ($value == 10) {
            return TRUE;
        } else {
            $this->form_validation->set_message('valid_phone_number', 'Mobile number not in range'); //{10}

            return FALSE;
        }
    }

    public function index() {
        //load the database
        //$this->load->database();
        //load the model
        $this->load->model('select');
        //load the method of model
        $data['h'] = $this->select->select();
        //return the data in view
        $this->load->view('fetch_view', $data);
    }

    public function delete() {
        $this->load->model('select');
        $id = $this->input->get('id');
        if ($this->select->deleteuser($id)) {
            $data['data'] = $this->select->getuser();
            $this->load->view('fetch_view', $data);
        }
    }
}
</code>```

答:
Set default id value in your controller function like</p>

```<code>function form($id = null){
....
}
</code>```

Body:
This is my home.php file in this controller I am facing Fatal error: Uncaught ArgumentCountError:
I have also attached a screenshot, In this screenshot error mentioned, You can easily understand the error through this screenshot, I am newbie in CodeIgniter.
[
I upload only my controller related file.

<?php

class home extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('select');
        $this->load->helper(array('form', 'url', 'html'));
        $this->load->library(array('form_validation', 'session'));
    }

    function records() {
        $ytl['dta'] = $this->users->datas();
        //$this->load->view('info',$ytl);
        //echo "
controller";print_r($ytl);
    }

    function primezone() {
        $ytl['dta'] = $this->users->datas();
        echo "
controller";
        print_r($ytl);
    }

    function form($id) {
        //die($id);
        if ($this->input->post()) {
            //echo"
";print_r( $this->input->post());die;
            $this->form_validation->set_rules('fname', 'First Name', 'required|min_length[5]');
            $this->form_validation->set_rules('lname', 'Last Name', 'required|callback_check_picture[lname]');

            //$this->form_validation->set_rules('email','Email','required');

            $this->form_validation->set_rules('mobile', 'Mobile Number', 'required|callback_valid_phone_number[mobile]');

            $this->form_validation->set_error_delimiters('
', '
');
            if ($this->form_validation->run() == TRUE) {
                $data = [

                    'fname'   => $this->input->post('fname'),
                    'lname'   => $this->input->post('lname'),
                    'email'   => $this->input->post('email'),
                    'mobile'  => $this->input->post('mobile'),
                    'message' => $this->input->post('message'),
                ];
                if (empty($id)) {
                    $ytl = $this->select->insertdata($data);

                } else {
                    $ytl = $this->select->updatedata($data, $id);
                }
                if ($ytl) {
                    $this->session->set_flashdata('message', 'Successfully Added.');
                    redirect('home');
                }
            } else {
                //$this->load->view('form');
            }
        }
        $ytl['dta'] = $this->select->getDataById($id);
        //echo "
";print_r($ytl);die;
        $this->load->view('form', $ytl);
    }

    public function check_picture($a) {
        if ( ! is_numeric($a)) {
            return TRUE;
        } else {
            $this->form_validation->set_message('check_picture', 'Please enter only char value');

            return FALSE;
        }
    }

    function valid_phone_number($value) {
        $value = strlen($value);
        //echo $value;die;
        if ($value == 10) {
            return TRUE;
        } else {
            $this->form_validation->set_message('valid_phone_number', 'Mobile number not in range'); //{10}

            return FALSE;
        }
    }

    public function index() {
        //load the database
        //$this->load->database();
        //load the model
        $this->load->model('select');
        //load the method of model
        $data['h'] = $this->select->select();
        //return the data in view
        $this->load->view('fetch_view', $data);
    }

    public function delete() {
        $this->load->model('select');
        $id = $this->input->get('id');
        if ($this->select->deleteuser($id)) {
            $data['data'] = $this->select->getuser();
            $this->load->view('fetch_view', $data);
        }
    }
}

Body:
Set default id value in your controller function like

function form($id = null){
....
}


问:
Use reflection to set a property value to Nothing (Null)
Edit: Based on the answer from LoveMeSomeCode, I believe this issue only appears in VB.Net.

I'm trying to revert a class to a previous state by saving the old values of changed properties in a dictionary and setting them via reflection when I need to revert. I'm having a problem where if the old value is Nothing (null) I get a null reference exception when trying to set the property. Here's what I've tried.

Assume a for each loop like this:

```<code>For Each pair As KeyValuePair(Of String, Object) In myOldValues
...
Next
</code>```

Method 1:

```<code>CallByName(Me, pair.Key, CallType.Set, pair.Value)
</code>```

Method 2:

```<code>Me.GetType().InvokeMember(pair.Key, Reflection.BindingFlags.SetProperty, Nothing, Me, pair.Value)
</code>```

Method 3:

```<code>Dim propInfo As System.Reflection.PropertyInfo = Me.GetType.GetProperty(pair.Key)
propInfo.SetValue(Me, Convert.ChangeType(pair.Value, propInfo.PropertyType), Nothing)
</code>```

For each of these methods I get a null reference exception when pair.Value is null. The setter is capable of holding a null value (frequently the property is a string). What am I doing wrong or how can I work around it?

Edit: Each method fails if I pass it null directly as well.

Edit: Here are the stack traces if they help anyone:

Method 1
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.VisualBasic.CompilerServices.Symbols.Container.InvokeMethod(Method TargetProcedure, Object[] Arguments, Boolean[] CopyBack, BindingFlags Flags)
   at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean OptimisticSet, Boolean RValueBase, CallType CallType)
   at Microsoft.VisualBasic.CompilerServices.Versioned.CallByName(Object Instance, String MethodName, CallType UseCallType, Object[] Arguments)
   at myProject.Presenter.CustomerDetailPresenter.RevertCustomer() in myfile:line 378

Method 2
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at myProject.Presenter.CustomerDetailPresenter.set_City(String value)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)
   at myProject.Presenter.CustomerDetailPresenter.RevertCustomer()

Method 3
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at myProject.Presenter.CustomerDetailPresenter.set_City(String value)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)

at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)
   at myProject.Presenter.CustomerDetailPresenter.RevertCustomer()

答:
Well, this is C# instead of VB.NET, but this seems to work:

```<code>private Dictionary<string, object> MemoryValues = new Dictionary<string, object>();

        public void Store()
        {
            foreach (PropertyInfo info in this.GetType().GetProperties())
            {
                if (MemoryValues.ContainsKey(info.Name))
                    MemoryValues[info.Name] = info.GetValue(this, null);
                else
                    MemoryValues.Add(info.Name, info.GetValue(this, null));
            }
        }

        public void Recall()
        {
            foreach (PropertyInfo info in this.GetType().GetProperties())
            {
                info.SetValue(this, MemoryValues[info.Name], null);
            }
        }
</code>```

so you can set the properties and call Store(), and they will be saved to the dictionary. Then you can change them and call Recall() and they will be restored. It seems to work will null for strings at least. It seems like a good set of things to put in a base class.

OwnerDisplayName: Bryan Anderson

Body:
Edit: Based on the answer from LoveMeSomeCode, I believe this issue only appears in VB.Net.

I'm trying to revert a class to a previous state by saving the old values of changed properties in a dictionary and setting them via reflection when I need to revert. I'm having a problem where if the old value is Nothing (null) I get a null reference exception when trying to set the property. Here's what I've tried.

Assume a for each loop like this:

For Each pair As KeyValuePair(Of String, Object) In myOldValues
...
Next

Method 1:

CallByName(Me, pair.Key, CallType.Set, pair.Value)

Method 2:

Me.GetType().InvokeMember(pair.Key, Reflection.BindingFlags.SetProperty, Nothing, Me, pair.Value)

Method 3:

Dim propInfo As System.Reflection.PropertyInfo = Me.GetType.GetProperty(pair.Key)
propInfo.SetValue(Me, Convert.ChangeType(pair.Value, propInfo.PropertyType), Nothing)

For each of these methods I get a null reference exception when pair.Value is null. The setter is capable of holding a null value (frequently the property is a string). What am I doing wrong or how can I work around it?

Edit: Each method fails if I pass it null directly as well.

Edit: Here are the stack traces if they help anyone:

Method 1
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.VisualBasic.CompilerServices.Symbols.Container.InvokeMethod(Method TargetProcedure, Object[] Arguments, Boolean[] CopyBack, BindingFlags Flags)
   at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean OptimisticSet, Boolean RValueBase, CallType CallType)
   at Microsoft.VisualBasic.CompilerServices.Versioned.CallByName(Object Instance, String MethodName, CallType UseCallType, Object[] Arguments)
   at myProject.Presenter.CustomerDetailPresenter.RevertCustomer() in myfile:line 378

Method 2
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at myProject.Presenter.CustomerDetailPresenter.set_City(String value)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)
   at myProject.Presenter.CustomerDetailPresenter.RevertCustomer()

Method 3
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at myProject.Presenter.CustomerDetailPresenter.set_City(String value)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)

at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)
   at myProject.Presenter.CustomerDetailPresenter.RevertCustomer()

LastEditorDisplayName: Bryan Anderson

Body:
Well, this is C# instead of VB.NET, but this seems to work:

private Dictionary<string, object> MemoryValues = new Dictionary<string, object>();

        public void Store()
        {
            foreach (PropertyInfo info in this.GetType().GetProperties())
            {
                if (MemoryValues.ContainsKey(info.Name))
                    MemoryValues[info.Name] = info.GetValue(this, null);
                else
                    MemoryValues.Add(info.Name, info.GetValue(this, null));
            }
        }

        public void Recall()
        {
            foreach (PropertyInfo info in this.GetType().GetProperties())
            {
                info.SetValue(this, MemoryValues[info.Name], null);
            }
        }

so you can set the properties and call Store(), and they will be saved to the dictionary. Then you can change them and call Recall() and they will be restored. It seems to work will null for strings at least. It seems like a good set of things to put in a base class.

OwnerDisplayName: LoveMeSomeCode


问:
PhpStorm 'Find in Path' doesn't search everywhere
I'm using PhpStorm 2017.2.4 on Win 8.1.

I'm trying to search for a string within every file in the project.

For that I've opened 'Find in Path', set the File mask to "*", selected the option "Recursively" and began typing.

It seems that the tool is limiting it search to maximum of 100 files, and thus doesn't find that which I'm looking for. If I limit the search to be below 100 files it will work, but that's pointless.

The filetype is not ignored and is added under settings and 'File Types'.

Should I use the Notepad++ 'Find in Files' search function instead, or does PhpStorm/IntelliJ-IDEA has a function like that?

答: Please follow the related issue on YouTrack: https://youtrack.jetbrains.com/issue/IDEA-178771</p>


问:
If dynamic table exists in the database Drop the table
I have a table which gets created Dynamically every 1st of a month. something like test201711 for November.

I want to check if test201711 exists in the DB Drop test201711

What I tried so far:

```<code>Declare @ste varchar(max)
set @ste = 'if exists (select * from INFORMATION_SCHEMA.TABLES where   TABLE_NAME =''test'+CONVERT(varchar(6),getdate(),112) + ''');'  + ' Drop table test'+ CONVERT(varchar(6),getdate(),112)
print @ste
exec(@ste)
</code>```

When I am printing the query it is correct, but when I am executing it is giving me an error.

What is wrong with my code here??

答:
I would guess the problem is the semicolon.

```<code>Declare @ste nvarchar(max);
set @ste = '
if exists (select *
           from INFORMATION_SCHEMA.TABLES
           where TABLE_NAME = ''[tablename]''
          )
     Drop table [tablename]
';
set @ste = replace(@ste, '[tablename]', CONVERT(varchar(6), getdate(), 112));
print @ste

exec sp_executesql @ste;
</code>```

Notes:

This constructs the table name once and then uses replace() to put that into the query string.

The semicolon at the end of the if is removed.

Use sp_executesql.  It is much more powerful than exec(), even if parameters are not useful in this case.

You can also do this with a try/catch block:

```<code>begin try
    drop table [tablename]
end try
begin catch
    -- assume table doesn't exist and ignore error
end catch;
</code>```

Body:
I have a table which gets created Dynamically every 1st of a month. something like test201711 for November.

I want to check if test201711 exists in the DB Drop test201711

What I tried so far:

Declare @ste varchar(max)
set @ste = 'if exists (select * from INFORMATION_SCHEMA.TABLES where   TABLE_NAME =''test'+CONVERT(varchar(6),getdate(),112) + ''');'  + ' Drop table test'+ CONVERT(varchar(6),getdate(),112)
print @ste
exec(@ste)

When I am printing the query it is correct, but when I am executing it is giving me an error.

What is wrong with my code here??

Body:
I would guess the problem is the semicolon.

Declare @ste nvarchar(max);
set @ste = '
if exists (select *
           from INFORMATION_SCHEMA.TABLES
           where TABLE_NAME = ''[tablename]''
          )
     Drop table [tablename]
';
set @ste = replace(@ste, '[tablename]', CONVERT(varchar(6), getdate(), 112));
print @ste

exec sp_executesql @ste;

Notes:

This constructs the table name once and then uses replace() to put that into the query string.

The semicolon at the end of the if is removed.

Use sp_executesql.  It is much more powerful than exec(), even if parameters are not useful in this case.

You can also do this with a try/catch block:

begin try
    drop table [tablename]
end try
begin catch
    -- assume table doesn't exist and ignore error
end catch;


问:
SQL to select and swap id columns so parameter appears in left hand column
I'm looking to put together an SQL query for a matrix-like table to select a certain value (which can appear in either column) and then switch the id columns so that the search value always appears on the left hand side.

I'm having trouble explaining it coherently to search for an answer, but here's an example:

DB Table

```<code>id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5
 2  |  3  |  0.1
</code>```

Desired output if I'm looking for value 1, note the last two columns switching position:

```<code>id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 1  |  2  |  0.3
 1  |  3  |  0.5
</code>```

My current SQL is as follows:

```<code>SELECT (id1, id2, value) FROM db-table WHERE 1 in (id1, id2);
</code>```

Which gets the correct values, but without swapping. The result is:

```<code>id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5
</code>```

I'm using sqlite3 but I can translate/fix domain specific issues if someone is able to point me in the right direction. Thanks!

答:
You can use the below query. Its working fine.

create and insert values

```<code>create table #table1
(
   id1 int,
   id2 int,
   val nvarchar(20)
)

insert into #table1 values (1,4,0.2);
insert into #table1 values (2,1,0.3);
insert into #table1 values (3,1,0.5);
insert into #table1 values (2,3,0.1);
</code>```

write below query to get result

```<code>select * from (
                 SELECT id1 ,id2, val FROM #table1 where id1 = 1
                 union
                 SELECT id2 ,id1, val from #table1 where id2 = 1
              ) t
order by t.val asc
</code>```

here we go with the output.

~ cheers

Body:
I'm looking to put together an SQL query for a matrix-like table to select a certain value (which can appear in either column) and then switch the id columns so that the search value always appears on the left hand side.

I'm having trouble explaining it coherently to search for an answer, but here's an example:

DB Table

id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5
 2  |  3  |  0.1

Desired output if I'm looking for value 1, note the last two columns switching position:

id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 1  |  2  |  0.3
 1  |  3  |  0.5

My current SQL is as follows:

SELECT (id1, id2, value) FROM db-table WHERE 1 in (id1, id2);

Which gets the correct values, but without swapping. The result is:

id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5

I'm using sqlite3 but I can translate/fix domain specific issues if someone is able to point me in the right direction. Thanks!

Body:
You can use the below query. Its working fine.

create and insert values

create table #table1
(
   id1 int,
   id2 int,
   val nvarchar(20)
)

insert into #table1 values (1,4,0.2);
insert into #table1 values (2,1,0.3);
insert into #table1 values (3,1,0.5);
insert into #table1 values (2,3,0.1);

write below query to get result

select * from (
                 SELECT id1 ,id2, val FROM #table1 where id1 = 1
                 union
                 SELECT id2 ,id1, val from #table1 where id2 = 1
              ) t
order by t.val asc

here we go with the output.

~ cheers


问:
Create array of objects based off the same property names
I have form inputs that are generated based off an XML file.

We keep a reference of nested elements in the XML file via data-* attributes which can later be used to build an object. For example:

```<code><parent>
 <child>
  <grandchild1>first</grandchild1>
  <grandchild2>second</grandchild2>
 </child>
</parent>
</code>```

Becomes

<input type="text" data-nest="parent.child.grandchild1" value="first"/>
<input type="text" data-nest="parent.child.grandchild2" value="second"/>

When we submit the form, I create an object (with nested objects) based off of their data-nest attribute. The above would become

```<code>parent:{
 child:{
  grandchild1: first,
  grandchild2: second
  }
}
</code>```

The issue that I am running into is where multiple of the same tag are found in the XML file, e.g.

```<code><child>
 <grandchild>first</grandchild>
 <grandchildFriend>firstFriend</grandchildFriend>
</child>
<child>
 <grandchild>second</grandchild>
 <grandchildFriend>secondFriend</grandchildFriend>
</child>
</code>```

When I create my object, I would like it so that if multiple occurrences of the same data-nest value are found, they are nested inside of an array in order to maintain the different values.

With the current setup, the second occurrence of the tag will understandably overwrite the first.

This is the final object structure I desire:

```<code>parent:{
 child:[
  {
   grandchild: first,
   grandchildFriend: firstFriend
  },
  {
   grandchild: second,
   grandchildFriend: secondFriend
  }
  ]
 }
</code>```

TL;DR

I'd like to change an object to an array of nested objects if they have the same data-* attribute

Here's a fiddle of how the current code works to help give a better understanding.

答:
Try this https://jsfiddle.net/ado7eLL9/19/

by updating the set method of config like this

```<code>if (typeof currentObj[lastKey] === 'undefined') {
   currentObj[lastKey] = value;
} else if(!Array.isArray(currentObj[lastKey])) {
  currentObj[lastKey] = [currentObj[lastKey], value];
} else if(Array.isArray(currentObj[key])){
  currentObj[lastKey].push(value);
}
</code>```

Body:
I have form inputs that are generated based off an XML file.

We keep a reference of nested elements in the XML file via data-* attributes which can later be used to build an object. For example:

<parent>
 <child>
  <grandchild1>first</grandchild1>
  <grandchild2>second</grandchild2>
 </child>
</parent>

Becomes

<input type="text" data-nest="parent.child.grandchild1" value="first"/>
<input type="text" data-nest="parent.child.grandchild2" value="second"/>

When we submit the form, I create an object (with nested objects) based off of their data-nest attribute. The above would become

parent:{
 child:{
  grandchild1: first,
  grandchild2: second
  }
}

The issue that I am running into is where multiple of the same tag are found in the XML file, e.g.

<child>
 <grandchild>first</grandchild>
 <grandchildFriend>firstFriend</grandchildFriend>
</child>
<child>
 <grandchild>second</grandchild>
 <grandchildFriend>secondFriend</grandchildFriend>
</child>

When I create my object, I would like it so that if multiple occurrences of the same data-nest value are found, they are nested inside of an array in order to maintain the different values.

With the current setup, the second occurrence of the tag will understandably overwrite the first.

This is the final object structure I desire:

parent:{
 child:[
  {
   grandchild: first,
   grandchildFriend: firstFriend
  },
  {
   grandchild: second,
   grandchildFriend: secondFriend
  }
  ]
 }

TL;DR

I'd like to change an object to an array of nested objects if they have the same data-* attribute

Here's a fiddle of how the current code works to help give a better understanding.

Body:
Try this https://jsfiddle.net/ado7eLL9/19/

by updating the set method of config like this

if (typeof currentObj[lastKey] === 'undefined') {
   currentObj[lastKey] = value;
} else if(!Array.isArray(currentObj[lastKey])) {
  currentObj[lastKey] = [currentObj[lastKey], value];
} else if(Array.isArray(currentObj[key])){
  currentObj[lastKey].push(value);
}


问:
Trigger a function inside a directive by watching a variable
Assume I have the following directive:

```<code>angular.module("myModule", [])
.directive('myDirective', function ($timeout) {
    return {
        restrict: 'EA',
        scope: {
            value: '=',
            valueIsValid: '='
        },
        link: function (scope, element, attrs) {

             scope.returnValueIsValid = function() {
                  // return valueIsValid = true or false
             };
        }
    }
});
</code>```

invoked the following way:

```<code> <div my-directive  value="value"  value-is-valid="valueIsValid"></div>
</code>```

The value variable is input to the directive, where the directive should return if value is valid or not in the valueIsValid variable. Is there a way to trigger the validation function by just watching valueIsValid ?

答:
I assume valueIsValid will be true when value>0

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {

});

myApp.directive('myDirective', function ($timeout) {
    return {
        restrict: 'EA',
        scope: {
            value: '=',
            valueIsValid: '='
        },
        link: function (scope, element, attrs) {
           scope.$watch("value",function(a,b){
           if(a && a != 0){
             scope.valueIsValid =true;
           }else{
              scope.valueIsValid =false;
              }
           })
        }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<input type="number" value="0" ng-model="value"/>
 <div my-directive  value="value"  value-is-valid="valueIsValid"></div>
 value is valid:-   {{valueIsValid}}
</div></code>```

Body:
Assume I have the following directive:

angular.module("myModule", [])
.directive('myDirective', function ($timeout) {
    return {
        restrict: 'EA',
        scope: {
            value: '=',
            valueIsValid: '='
        },
        link: function (scope, element, attrs) {

             scope.returnValueIsValid = function() {
                  // return valueIsValid = true or false
             };
        }
    }
});

invoked the following way:

The value variable is input to the directive, where the directive should return if value is valid or not in the valueIsValid variable. Is there a way to trigger the validation function by just watching valueIsValid ?

Body:
I assume valueIsValid will be true when value>0

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {

});

myApp.directive('myDirective', function ($timeout) {
    return {
        restrict: 'EA',
        scope: {
            value: '=',
            valueIsValid: '='
        },
        link: function (scope, element, attrs) {
           scope.$watch("value",function(a,b){
           if(a && a != 0){
             scope.valueIsValid =true;
           }else{
              scope.valueIsValid =false;
              }
           })
        }
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<input type="number" value="0" ng-model="value"/>
 <div my-directive  value="value"  value-is-valid="valueIsValid"></div>
 value is valid:-   {{valueIsValid}}
</div>


答:
Try this use addTextChangedListener

addTextChangedListener(TextWatcher watcher)

Adds a TextWatcher to the list of those whose methods are called whenever this editText's text changes.

```<code>editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!editText.getText().toString().trim().isEmpty()) {
                    editText.setBackgroundColor(ContextCompat.getColor(Main2Activity.this, R.color.colorPrimary));
                } else {
                    editText.setBackgroundColor(ContextCompat.getColor(Main2Activity.this, R.color.colorPrimaryDark));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
</code>```

Title: How to change EditText background color when I enter text?

Body:
Try this use addTextChangedListener

addTextChangedListener(TextWatcher watcher)

Adds a TextWatcher to the list of those whose methods are called whenever this editText's text changes.

editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!editText.getText().toString().trim().isEmpty()) {
                    editText.setBackgroundColor(ContextCompat.getColor(Main2Activity.this, R.color.colorPrimary));
                } else {
                    editText.setBackgroundColor(ContextCompat.getColor(Main2Activity.this, R.color.colorPrimaryDark));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


问:
Java Read/Write Excel - Error : The constructor XSSFWorkbook(FileInputStream) is undefined
I am trying to read data from an excel file, i am using the following code :

```<code>File src = new File("T:\\SeleniuminputFiles\\input.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(0);
</code>```

but i am getting the compilation error as The constructor XSSFWorkbook(FileInputStream) is undefined.

I have downloaded External Jar files from The latest stable release Apache POI 3.16 http://poi.apache.org/download.html#POI-3.16

Your help would be highly appreciated.

答:
Maybe you are not using the current version. I had the same issue.

poi-3.8-20120326
poi-ooxml-3.9
poi-ooxml-schemas-3.7
poi-ooxml-schemas-3.9

Try installing this versions or latest versions.

Body:
I am trying to read data from an excel file, i am using the following code :

File src = new File("T:\\SeleniuminputFiles\\input.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(0);

but i am getting the compilation error as The constructor XSSFWorkbook(FileInputStream) is undefined.

I have downloaded External Jar files from The latest stable release Apache POI 3.16 http://poi.apache.org/download.html#POI-3.16

Your help would be highly appreciated.


问:
i have 3 div one after another in horizontal way. when resize it shows div3, div2, and div1
I have problem to achieve design. I have 3 divs: one after another in horizontal way say div1, div2 and div3. When it goes on small device it shows div3, div2, and div1. How can I achieve using HTML, CSS.

I have attached an image for reference.

答:
You can do it with the Flexbox and @media queries:

.parent {
  display: flex; /* displays flex-items (children) inline */
}

.child {
  flex-grow: 1; /* each flex-item grows and takes 1/3 of the parent's width */
  text-align: center;
  border: 1px solid;
}

@media (max-width: 568px) { /* adjust to your needs */
  .parent {flex-direction: column} /* stacks them vertically */
  .child:first-child {order: 1} /* down 1 spot */
  .child:last-child {order: -1} /* up 1 spot */
  /* "order: 0" is by default, therefore :nth-child(2) stays where it is */
  /* the order property only works with flexbox or grid */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">DIV 1</div>
  <div class="child">DIV 2</div>
  <div class="child">DIV 3</div>
</div></code>```

Body:
You can do it with the Flexbox and @media queries:

.parent {
  display: flex; /* displays flex-items (children) inline */
}

.child {
  flex-grow: 1; /* each flex-item grows and takes 1/3 of the parent's width */
  text-align: center;
  border: 1px solid;
}

@media (max-width: 568px) { /* adjust to your needs */
  .parent {flex-direction: column} /* stacks them vertically */
  .child:first-child {order: 1} /* down 1 spot */
  .child:last-child {order: -1} /* up 1 spot */
  /* "order: 0" is by default, therefore :nth-child(2) stays where it is */
  /* the order property only works with flexbox or grid */
}

<div class="parent">
  <div class="child">DIV 1</div>
  <div class="child">DIV 2</div>
  <div class="child">DIV 3</div>
</div>


问:
python update a list of dictionaries using another list of the same length
I am trying to update a list a of dictionaries using another list b of the same length that each dict should add a key which corresponds to a value in b at the same position,

```<code>for x in range(len(a)):
    a[x]['val'] = b[x]
</code>```

I am wondering is there a more efficient/concise way to do it

答:
If you are using python 3.x, you can use a list comprehension to create the new list on the fly:

```<code>a = [{'A': 1}, {'B': 2}]
b = [3,4]
[{**d, **{"val":b[i]}} for i, d in enumerate(a)]
</code>```

Output:

```<code>[{'A': 1, 'val': 3}, {'B': 2, 'val': 4}]
</code>```

Notice, though, that this doesn't apply on python 2.7. Another option would be to use a list comprehension to update each dictionary:

```<code>>>> a = [{'A': 1}, {'B': 2}]
>>> b = [3, 4]
>>> [x.update({"val":b[i]}) for i,x in enumerate(a)]
[None, None]
>>> a
[{'A': 1, 'val': 3}, {'B': 2, 'val': 4}]
</code>```

Body:
I am trying to update a list a of dictionaries using another list b of the same length that each dict should add a key which corresponds to a value in b at the same position,

for x in range(len(a)):
    a[x]['val'] = b[x]

I am wondering is there a more efficient/concise way to do it

Body:
If you are using python 3.x, you can use a list comprehension to create the new list on the fly:

a = [{'A': 1}, {'B': 2}]
b = [3,4]
[{**d, **{"val":b[i]}} for i, d in enumerate(a)]

Output:

[{'A': 1, 'val': 3}, {'B': 2, 'val': 4}]

Notice, though, that this doesn't apply on python 2.7. Another option would be to use a list comprehension to update each dictionary:

>>> a = [{'A': 1}, {'B': 2}]
>>> b = [3, 4]
>>> [x.update({"val":b[i]}) for i,x in enumerate(a)]
[None, None]
>>> a
[{'A': 1, 'val': 3}, {'B': 2, 'val': 4}]


问:
Bootstrap 4 nav pills are not working

                    Driver Details

                    Register Driver

              asdsdd

ffffffffffffffffffffffffffff

```

Hello, I'm using nav-pills in bootstrap but for some reason it is not working properly, Please take a look at the code above, I haven't included bootstrap in the above fiddle

答:
Use something like this for the pills:

```<code><ul class="nav nav-pills">
  <li class="nav-item">
    <a class="nav-link active" data-toggle="pill" href="#driver-details-tab">Driver Details</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="pill" href="#erer">Register Driver</a>
  </li>
</ul>
</code>```

Note the classes that I've added.

Title: Bootstrap 4 nav pills are not working

Body:
                    Driver Details

                    Register Driver

              asdsdd

ffffffffffffffffffffffffffff

Hello, I'm using nav-pills in bootstrap but for some reason it is not working properly, Please take a look at the code above, I haven't included bootstrap in the above fiddle

Body:
Use something like this for the pills:

<ul class="nav nav-pills">
  <li class="nav-item">
    <a class="nav-link active" data-toggle="pill" href="#driver-details-tab">Driver Details</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="pill" href="#erer">Register Driver</a>
  </li>
</ul>

Note the classes that I've added.


问:
react-data-grid: createElement type is invalid with typescript & webpack externals
Hi guys I'm trying to set both the react-data-grid and react-data-grid-addons libraries as externals in webpack, so they don't get included in my asset bundling. I had everything working before I tried to move it all to the externals part of webpack.
I've found the following error message in a few stacktraces, but could not manage to get it to work. Perhaps my use case is a little different and the problem lies somewhere else? This is the message I get:

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of Table.

I use the following versions in my package.json:

```<code>"dependencies": {
    "react": "15.4.2",
    "react-data-grid": "2.0.60",
    "react-data-grid-addons": "2.0.60",
    "react-dom": "15.4.2"
  },
</code>```

In the externals of my webpack module.exports I have:

```<code>externals: {
  "react": "React",
  "react-dom": "ReactDOM",
  "react-data-grid": "ReactDataGrid",
  "react-data-grid-addons": "ReactDataGridPlugins"
}
</code>```

And finally the whole logic for the table I'm trying to render. I've tried playing around with the imports at the top, to no avail :( Is there something I'm not doing right? The table is the example I used from the filterable & sortable table example given by react-data-grid (http://adazzle.github.io/react-data-grid/examples.html#/filterable-sortable-grid). Had to change it to a typescript structure however.

```<code>/** @module Global *//***/

import * as React from "react";
import * as ReactDataGrid from "react-data-grid";
import { Toolbar, Data } from "react-data-grid-addons";
import * as ReactDOM from "react-dom";

const Selectors = Data.Selectors;

/**
 * Row interface
 */
interface Row {
    id: number;
    title: string;
    count: number;
}

/**
 * Column interface
 */
interface Column {
    key: keyof Row;
    name: string;
    filterable?: boolean;
    sortable?: boolean;
}

/**
 * State interface
 */
interface State {
    rows: Row[] | null;
    filters: any;
    sortColumn: string | null;
    sortDirection: string | null;
}

/**
 * Table component
 */
class Table extends React.Component<{}, State> {
    private columns: Column[];
    private rows: Row[];

    public state: State = {
        rows: null,
        filters: {},
        sortColumn: null,
        sortDirection: null,
    };

    /**
     * Table class constructor
     * @param props
     * @param context
     */
    constructor(props: any, context: any) {
        super(props, context);
        this.columns = [
            { key: "id", name: "ID", filterable: true, sortable: true },
            { key: "title", name: "Title", filterable: true, sortable: true },
            { key: "count", name: "Count", filterable: true, sortable: true },
        ];
        this.rows = this.createRows();

        this.state.rows = this.rows;

        this.handleGridSort = this.handleGridSort.bind(this);
        this.handleFilterChange = this.handleFilterChange.bind(this);
        this.onClearFilters = this.onClearFilters.bind(this);
    }

    /**
     * Create the table rows
     * @returns {Row[]}
     */
    public createRows(): Row[]  {
        const rows = [];
        for (let i = 1; i < 1000; i++) {
            rows.push({
                id: i,
                title: "Title " + i,
                count: i * 1000,
            });
        }
        return rows;
    }

    /**
     * Get the table rows as an array of Row objects
     * @returns {Row[]}
     */
    public getRows(): Row[] {
        return Selectors.getRows(this.state) as Row[];
    }

    /**
     * Get the amount of rows
     * @returns {number}
     */
    public getSize(): number {
        return this.getRows().length;
    }

    /**
     * Get a specific row
     * @param {number} i
     * @returns {Row}
     */
    public rowGetter(i: number): Row {
        const rows = this.getRows();
        return rows[i];
    }

    /**
     * Handle the filter change
     * @param filter
     */
    public handleFilterChange(filter: any): void {
        const newFilters = {...this.state.filters};
        if (filter.filterTerm) {
            newFilters[filter.column.key] = filter;
        } else {
            delete newFilters[filter.column.key];
        }

        this.setState({ filters: newFilters });
    }

    /**
     * Handle the table sorting
     * @param {string} sortColumn
     * @param {string} sortDirection
     */
    public handleGridSort(sortColumn: string, sortDirection: string): void {
        this.setState({ sortColumn: sortColumn, sortDirection: sortDirection });
    }

    /**
     * Handles the clearing of the filters
     */
    public onClearFilters(): void {
        this.setState({ filters: {} });
    }

    /**
     * Render table
     * @returns {any}
     */
    public render(): any {
        // console.log(this);
        return  (
            <ReactDataGrid
                columns={this.columns}
                rowGetter={this.rowGetter.bind(this)}
                rowsCount={this.getSize()}
                minHeight={500}
                toolbar={<Toolbar enableFilter={true} />}
                enableCellSelect={true}
                onGridSort={this.handleGridSort}
                onAddFilter={this.handleFilterChange}
                onClearFilters={this.onClearFilters}
            />);
    }
}

ReactDOM.render(
    <Table />,
    document.getElementById("table"),
);
</code>```

答:
I normally get this error when my import statements are wrong. can you try this import * as RRGA from "react-data-grid-addons"; and whereever you are using Toolbar and data use RRGA.Toolbar and RRGA.Data. even in the jsx tags.

```<code> import * as RRGA from "react-data-grid-addons";
</code>```

and in your render function and other places where you use Toolbar and Data

```<code>public render(): any {
    // console.log(this);
    return  (
        <ReactDataGrid
            columns={this.columns}
            rowGetter={this.rowGetter.bind(this)}
            rowsCount={this.getSize()}
            minHeight={500}
            toolbar={<RRGA.Toolbar enableFilter={true} />}
            enableCellSelect={true}
            onGridSort={this.handleGridSort}
            onAddFilter={this.handleFilterChange}
            onClearFilters={this.onClearFilters}
        />);
}
</code>```

Body:
Hi guys I'm trying to set both the react-data-grid and react-data-grid-addons libraries as externals in webpack, so they don't get included in my asset bundling. I had everything working before I tried to move it all to the externals part of webpack.
I've found the following error message in a few stacktraces, but could not manage to get it to work. Perhaps my use case is a little different and the problem lies somewhere else? This is the message I get:

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of Table.

I use the following versions in my package.json:

"dependencies": {
    "react": "15.4.2",
    "react-data-grid": "2.0.60",
    "react-data-grid-addons": "2.0.60",
    "react-dom": "15.4.2"
  },

In the externals of my webpack module.exports I have:

externals: {
  "react": "React",
  "react-dom": "ReactDOM",
  "react-data-grid": "ReactDataGrid",
  "react-data-grid-addons": "ReactDataGridPlugins"
}

And finally the whole logic for the table I'm trying to render. I've tried playing around with the imports at the top, to no avail :( Is there something I'm not doing right? The table is the example I used from the filterable & sortable table example given by react-data-grid (http://adazzle.github.io/react-data-grid/examples.html#/filterable-sortable-grid). Had to change it to a typescript structure however.

/** @module Global *//***/

import * as React from "react";
import * as ReactDataGrid from "react-data-grid";
import { Toolbar, Data } from "react-data-grid-addons";
import * as ReactDOM from "react-dom";

const Selectors = Data.Selectors;

/**
 * Row interface
 */
interface Row {
    id: number;
    title: string;
    count: number;
}

/**
 * Column interface
 */
interface Column {
    key: keyof Row;
    name: string;
    filterable?: boolean;
    sortable?: boolean;
}

/**
 * State interface
 */
interface State {
    rows: Row[] | null;
    filters: any;
    sortColumn: string | null;
    sortDirection: string | null;
}

/**
 * Table component
 */
class Table extends React.Component<{}, State> {
    private columns: Column[];
    private rows: Row[];

    public state: State = {
        rows: null,
        filters: {},
        sortColumn: null,
        sortDirection: null,
    };

    /**
     * Table class constructor
     * @param props
     * @param context
     */
    constructor(props: any, context: any) {
        super(props, context);
        this.columns = [
            { key: "id", name: "ID", filterable: true, sortable: true },
            { key: "title", name: "Title", filterable: true, sortable: true },
            { key: "count", name: "Count", filterable: true, sortable: true },
        ];
        this.rows = this.createRows();

        this.state.rows = this.rows;

        this.handleGridSort = this.handleGridSort.bind(this);
        this.handleFilterChange = this.handleFilterChange.bind(this);
        this.onClearFilters = this.onClearFilters.bind(this);
    }

    /**
     * Create the table rows
     * @returns {Row[]}
     */
    public createRows(): Row[]  {
        const rows = [];
        for (let i = 1; i < 1000; i++) {
            rows.push({
                id: i,
                title: "Title " + i,
                count: i * 1000,
            });
        }
        return rows;
    }

    /**
     * Get the table rows as an array of Row objects
     * @returns {Row[]}
     */
    public getRows(): Row[] {
        return Selectors.getRows(this.state) as Row[];
    }

    /**
     * Get the amount of rows
     * @returns {number}
     */
    public getSize(): number {
        return this.getRows().length;
    }

    /**
     * Get a specific row
     * @param {number} i
     * @returns {Row}
     */
    public rowGetter(i: number): Row {
        const rows = this.getRows();
        return rows[i];
    }

    /**
     * Handle the filter change
     * @param filter
     */
    public handleFilterChange(filter: any): void {
        const newFilters = {...this.state.filters};
        if (filter.filterTerm) {
            newFilters[filter.column.key] = filter;
        } else {
            delete newFilters[filter.column.key];
        }

        this.setState({ filters: newFilters });
    }

    /**
     * Handle the table sorting
     * @param {string} sortColumn
     * @param {string} sortDirection
     */
    public handleGridSort(sortColumn: string, sortDirection: string): void {
        this.setState({ sortColumn: sortColumn, sortDirection: sortDirection });
    }

    /**
     * Handles the clearing of the filters
     */
    public onClearFilters(): void {
        this.setState({ filters: {} });
    }

    /**
     * Render table
     * @returns {any}
     */
    public render(): any {
        // console.log(this);
        return  (
            <ReactDataGrid
                columns={this.columns}
                rowGetter={this.rowGetter.bind(this)}
                rowsCount={this.getSize()}
                minHeight={500}
                toolbar={<Toolbar enableFilter={true} />}
                enableCellSelect={true}
                onGridSort={this.handleGridSort}
                onAddFilter={this.handleFilterChange}
                onClearFilters={this.onClearFilters}
            />);
    }
}

ReactDOM.render(

,
    document.getElementById("table"),
);

Body:
I normally get this error when my import statements are wrong. can you try this import * as RRGA from "react-data-grid-addons"; and whereever you are using Toolbar and data use RRGA.Toolbar and RRGA.Data. even in the jsx tags.

 import * as RRGA from "react-data-grid-addons";

and in your render function and other places where you use Toolbar and Data

public render(): any {
    // console.log(this);
    return  (
        <ReactDataGrid
            columns={this.columns}
            rowGetter={this.rowGetter.bind(this)}
            rowsCount={this.getSize()}
            minHeight={500}
            toolbar={<RRGA.Toolbar enableFilter={true} />}
            enableCellSelect={true}
            onGridSort={this.handleGridSort}
            onAddFilter={this.handleFilterChange}
            onClearFilters={this.onClearFilters}
        />);
}


问:
Drupal generates long links
My drupal site generates long links like:

```<code>example.com/drupal/blog/what-we-do/solutions/about-us/
</code>```

This link works and shows the blog page:

```<code>example.com/drupal/blog/
</code>```

how can i get rid off these kind of links?

答:
If you want to do that automatically depending on the type of content, I think you can use pathauto

The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias.

Title: Drupal generates long links

Body:
My drupal site generates long links like:

example.com/drupal/blog/what-we-do/solutions/about-us/

This link works and shows the blog page:

example.com/drupal/blog/

how can i get rid off these kind of links?


问:
ios UIImageJPEGRepresentation() with large image crash
I am developing an iOS app with xcode 9 and iPhone SE.

I get an large photo which is a 19MB JPEG picture with NSData format from iPhone album.

Then I need to fix this photo orientation, so I have to convert this photo from NSData to UIImage.
Then I need to revert this UIImage to NSData(less than 20MB).

When I try to use UIImageJPEGRepresentation() and the device memory shot up to 1.2G and crash.

When I try to user UIImagePNGRepresentation(), the result NSData object is larger than 20MB.

I have no idea how to do this.
Can anyone help? thanks!

答:
I imagine a 19MB jpeg uncompressed will take up a huge amount of space. I'm not surprised your device memory goes up so much. Jpegs store an orientation attribute in their properties data. To avoid having to uncompress the jpeg you can instead just edit the properties data to fix the orientation.

You can edit properties as follows if imageData is your jpeg data. This uses the Swift Data object but you can jump between NSData and Data fairly easily

```<code>// create an imagesourceref
if let source = CGImageSourceCreateWithData(imageData as CFData, nil) {

    // get image properties
    var properties : NSMutableDictionary = [:]
    if let sourceProperties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) {
        properties = NSMutableDictionary(sourceProperties)
    }

    // set image orientation
    properties[kCGImagePropertyOrientation] = 4

    if let uti = CGImageSourceGetType(source) {

        // create a new data object and write the new image into it
        let destinationData = NSMutableData()
        if let destination = CGImageDestinationCreateWithData(destinationData, uti, 1, nil) {

            // add the image contained in the image source to the destination, overidding the old metadata with our modified metadata
            CGImageDestinationAddImageFromSource(destination, source, 0, properties)
            if CGImageDestinationFinalize(destination) == false {
                return nil
            }
            return destinationData as Data
        }
    }
}
</code>```

The orientation value is as follows

portrait = 6

portraitupsidedown = 8

landscape_volumebuttons_up = 3

landscape_powerbutton_up = 1

Body:
I imagine a 19MB jpeg uncompressed will take up a huge amount of space. I'm not surprised your device memory goes up so much. Jpegs store an orientation attribute in their properties data. To avoid having to uncompress the jpeg you can instead just edit the properties data to fix the orientation.

You can edit properties as follows if imageData is your jpeg data. This uses the Swift Data object but you can jump between NSData and Data fairly easily

// create an imagesourceref
if let source = CGImageSourceCreateWithData(imageData as CFData, nil) {

    // get image properties
    var properties : NSMutableDictionary = [:]
    if let sourceProperties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) {
        properties = NSMutableDictionary(sourceProperties)
    }

    // set image orientation
    properties[kCGImagePropertyOrientation] = 4

    if let uti = CGImageSourceGetType(source) {

        // create a new data object and write the new image into it
        let destinationData = NSMutableData()
        if let destination = CGImageDestinationCreateWithData(destinationData, uti, 1, nil) {

            // add the image contained in the image source to the destination, overidding the old metadata with our modified metadata
            CGImageDestinationAddImageFromSource(destination, source, 0, properties)
            if CGImageDestinationFinalize(destination) == false {
                return nil
            }
            return destinationData as Data
        }
    }
}

The orientation value is as follows

portrait = 6

portraitupsidedown = 8

landscape_volumebuttons_up = 3

landscape_powerbutton_up = 1