问:
Find the first and follow set of a given grammar in java
I have been given the problem to complete, and the algorithms to find the first and follow, but my problem is I cant quite find a data structure to implement to find these sets.

```<code>import java.util.Stack;

public class FirstFollowSet {

private final String[] term_tokens = { "begin", "end", ";", "if", "then", "else", "fi", "i", "=", "+", "-", "*",
        "/", "(", ")", "const" };
private final static String[] non_term_tokens = { "Start", "Prog", "Block", "Body", "S", "E", "T", "F" };
private static RuleStack rules;
private Stack<String> firstSet;
private Stack<String> followSet;

private boolean is_terminal(String str) {
    boolean test = false;
    for (int i = 0; i < term_tokens.length; i++) {
        if (str.equals(term_tokens[i]))
            test = true;
    }

    return test;
}

private boolean is_non_term(String str){
    for(int i = 0; i < non_term_tokens.length; i++)
    {
        if(str.equals(non_term_tokens[i]))
        {
            return true;
        }

    }
    return false;
}

private class Rule{
    String def, token;

    public Rule()
    {
        def = "";
        token = "";
    }

    public Rule(String d, String t)
    {
        def = d;
        token = t;
    }

    public String getDef() {
        return def;
    }

    public String getToken() {
        return token;
    }

    public String toString()
    {
        String str = "";
        str+= token + " " + def + '\n';
        return str;
    }
}

public class RuleStack{
    Stack<Rule> rules;

    public RuleStack(String grammar)
    {
        if(grammar.equals("G1"));
        {
            rules = new Stack();
            Rule rule = new Rule("Prog", "Start");
            rules.push(rule);
            rule = new Rule("Block #", "Prog");
            rules.push(rule);
            rule = new Rule("begin Body end", "Block");
            rules.push(rule);
            rule = new Rule("begin S end", "Body");
            rules.push(rule);
            rule = new Rule("Body ; S", "Body");
            rules.push(rule);
            rule = new Rule("S", "Body");
            rules.push(rule);
            rule = new Rule("if E then S else S fi", "S");
            rules.push(rule);
            rule = new Rule("if E else S fi", "S");
            rules.push(rule);
            rule = new Rule("i = E", "S");
            rules.push(rule);
            rule = new Rule("Block", "S");
            rules.push(rule);
            rule = new Rule("E + T", "E");
            rules.push(rule);
            rule = new Rule("E * T", "E");
            rules.push(rule);
            rule = new Rule("T", "E");
            rules.push(rule);
            rule = new Rule("T * F", "T");
            rules.push(rule);
            rule = new Rule("T / F", "T");
            rules.push(rule);
            rule = new Rule("F", "T");
            rules.push(rule);
            rule = new Rule("const", "F");
            rules.push(rule);
            rule = new Rule("( E )", "F");
            rules.push(rule);
        }
    }

}

public FirstFollowSet()
{
    rules = new RuleStack("G1");
    firstSet = new Stack();
    followSet = new Stack();
}

public String FindFirstSet(String str, Stack<String> used)
{
    if(used.contains(str))
    {
        return null;
    }
    String firstToken = "";
    String win = "";
    if(str.indexOf(" ") != -1)
        firstToken = str.substring(0, str.indexOf(" "));
    else
        firstToken = str;
    if(is_terminal(firstToken))
    {
        if(!(firstSet.contains(firstToken)))
            win = firstToken;
            if(win.equals("") != true)
                firstSet.push(win);
    }

    else if(is_non_term(firstToken) && !(used.contains(firstToken)))
    {
        used.push(firstToken);
        if(firstToken.equals("lambda"))
        {
            if(!(firstSet.contains(firstToken)))
            win = firstToken;
        }
        else
        {
            RuleStack rules = new RuleStack("G1");
            while(rules.rules.isEmpty() != true)
            {
                Rule winner = rules.rules.pop();
                if(winner.token.equals(firstToken))
                {
                    String test = FindFirstSet(winner.def, used);
                    if(!(test.equals("lambda")))
                    {
                        if(!(firstSet.contains(test)))
                        win = test;
                    }
                }
            }
        }
    }

    return win;
}

public String findFollowSet(String str)
{
    if(str.equals("S"))
    {
        followSet.push("$");
    }

    for(int i = 0; i < non_term_tokens.length; i++)
    {
        if(str.contains(non_term_tokens[i]))
        {
            int index = str.indexOf(non_term_tokens[i]);
            Stack<String> used = new Stack();
            FirstFollowSet test = new FirstFollowSet();
            if(index > 0 && index < str.length()-1)
            {
                test.FindFirstSet(str, used);
                while(test.firstSet.isEmpty() != true)
                {
                    String token = firstSet.pop();
                    if(!(token.equals("lambda")))
                        test.followSet.push(token);
                }
            }

            else if(index > 0 && index == str.length()-1)
            {

            }
        }
    }
}

public static void main(String[] args) {
    FirstFollowSet test = new FirstFollowSet();
    Stack<String> used = new Stack();
    test.FindFirstSet("S", used);
    while(test.firstSet.isEmpty() != true)
    {
        String str = test.firstSet.pop();
        System.out.println(str);
    }
}
</code>```

}

This is the code I have so far, and the find first set works just fine, but the findfollowset method I'm not quite sure how to implement. The only idea I can seem to come up with is making a stack for each non-terminal symbol, apply the algorithm, and add each terminal symbol returned to the set it belongs to. This method just feel like its more work then necessary.

If anyone has ever solved this problem, or has seen a way to solve this problem I would just like to know what sort of data structure was used and how it the algorithm was implemented for said structure.

Thank you for taking the time to read this, and i appreciate any feedback given.

答:
package modelo;

import java.util.ArrayList;

/**
 *
 * @author celeste
 */
public class Axioma {

```<code>public char getSimbolo() {
    return simbolo;
}

public void setSimbolo(char simbolo) {
    this.simbolo = simbolo;
}

public ArrayList<Character> getPrimeros() {
    return primeros;
}

public void setPrimeros(ArrayList<Character> primeros) {
    this.primeros = primeros;
}

public ArrayList<Character> getSiguientes() {
    return siguientes;
}

public void setSiguientes(ArrayList<Character> siguientes) {
    this.siguientes = siguientes;
}

public ArrayList<Character> getPredictivos() {
    return predictivos;
}

public void setPredictivos(ArrayList<Character> predictivos) {
    this.predictivos = predictivos;
}

public ArrayList<Character> getRegla() {
    return regla;
}

public void setRegla(ArrayList<Character> regla) {
    this.regla = regla;
}
private ArrayList<Character> primeros = new ArrayList<>();
private ArrayList<Character> siguientes = new ArrayList<>();
private ArrayList<Character> predictivos = new ArrayList<>();
private ArrayList<Character> regla = new ArrayList<>();
private char simbolo;
</code>```

}

Body:
I have been given the problem to complete, and the algorithms to find the first and follow, but my problem is I cant quite find a data structure to implement to find these sets.

import java.util.Stack;

public class FirstFollowSet {

private final String[] term_tokens = { "begin", "end", ";", "if", "then", "else", "fi", "i", "=", "+", "-", "*",
        "/", "(", ")", "const" };
private final static String[] non_term_tokens = { "Start", "Prog", "Block", "Body", "S", "E", "T", "F" };
private static RuleStack rules;
private Stack<String> firstSet;
private Stack<String> followSet;

private boolean is_terminal(String str) {
    boolean test = false;
    for (int i = 0; i < term_tokens.length; i++) {
        if (str.equals(term_tokens[i]))
            test = true;
    }

    return test;
}

private boolean is_non_term(String str){
    for(int i = 0; i < non_term_tokens.length; i++)
    {
        if(str.equals(non_term_tokens[i]))
        {
            return true;
        }

    }
    return false;
}

private class Rule{
    String def, token;

    public Rule()
    {
        def = "";
        token = "";
    }

    public Rule(String d, String t)
    {
        def = d;
        token = t;
    }

    public String getDef() {
        return def;
    }

    public String getToken() {
        return token;
    }

    public String toString()
    {
        String str = "";
        str+= token + " " + def + '\n';
        return str;
    }
}

public class RuleStack{
    Stack<Rule> rules;

    public RuleStack(String grammar)
    {
        if(grammar.equals("G1"));
        {
            rules = new Stack();
            Rule rule = new Rule("Prog", "Start");
            rules.push(rule);
            rule = new Rule("Block #", "Prog");
            rules.push(rule);
            rule = new Rule("begin Body end", "Block");
            rules.push(rule);
            rule = new Rule("begin S end", "Body");
            rules.push(rule);
            rule = new Rule("Body ; S", "Body");
            rules.push(rule);
            rule = new Rule("S", "Body");
            rules.push(rule);
            rule = new Rule("if E then S else S fi", "S");
            rules.push(rule);
            rule = new Rule("if E else S fi", "S");
            rules.push(rule);
            rule = new Rule("i = E", "S");
            rules.push(rule);
            rule = new Rule("Block", "S");
            rules.push(rule);
            rule = new Rule("E + T", "E");
            rules.push(rule);
            rule = new Rule("E * T", "E");
            rules.push(rule);
            rule = new Rule("T", "E");
            rules.push(rule);
            rule = new Rule("T * F", "T");
            rules.push(rule);
            rule = new Rule("T / F", "T");
            rules.push(rule);
            rule = new Rule("F", "T");
            rules.push(rule);
            rule = new Rule("const", "F");
            rules.push(rule);
            rule = new Rule("( E )", "F");
            rules.push(rule);
        }
    }

}

public FirstFollowSet()
{
    rules = new RuleStack("G1");
    firstSet = new Stack();
    followSet = new Stack();
}

public String FindFirstSet(String str, Stack<String> used)
{
    if(used.contains(str))
    {
        return null;
    }
    String firstToken = "";
    String win = "";
    if(str.indexOf(" ") != -1)
        firstToken = str.substring(0, str.indexOf(" "));
    else
        firstToken = str;
    if(is_terminal(firstToken))
    {
        if(!(firstSet.contains(firstToken)))
            win = firstToken;
            if(win.equals("") != true)
                firstSet.push(win);
    }

    else if(is_non_term(firstToken) && !(used.contains(firstToken)))
    {
        used.push(firstToken);
        if(firstToken.equals("lambda"))
        {
            if(!(firstSet.contains(firstToken)))
            win = firstToken;
        }
        else
        {
            RuleStack rules = new RuleStack("G1");
            while(rules.rules.isEmpty() != true)
            {
                Rule winner = rules.rules.pop();
                if(winner.token.equals(firstToken))
                {
                    String test = FindFirstSet(winner.def, used);
                    if(!(test.equals("lambda")))
                    {
                        if(!(firstSet.contains(test)))
                        win = test;
                    }
                }
            }
        }
    }

    return win;
}

public String findFollowSet(String str)
{
    if(str.equals("S"))
    {
        followSet.push("$");
    }

    for(int i = 0; i < non_term_tokens.length; i++)
    {
        if(str.contains(non_term_tokens[i]))
        {
            int index = str.indexOf(non_term_tokens[i]);
            Stack<String> used = new Stack();
            FirstFollowSet test = new FirstFollowSet();
            if(index > 0 && index < str.length()-1)
            {
                test.FindFirstSet(str, used);
                while(test.firstSet.isEmpty() != true)
                {
                    String token = firstSet.pop();
                    if(!(token.equals("lambda")))
                        test.followSet.push(token);
                }
            }

            else if(index > 0 && index == str.length()-1)
            {

            }
        }
    }
}

public static void main(String[] args) {
    FirstFollowSet test = new FirstFollowSet();
    Stack<String> used = new Stack();
    test.FindFirstSet("S", used);
    while(test.firstSet.isEmpty() != true)
    {
        String str = test.firstSet.pop();
        System.out.println(str);
    }
}

}

This is the code I have so far, and the find first set works just fine, but the findfollowset method I'm not quite sure how to implement. The only idea I can seem to come up with is making a stack for each non-terminal symbol, apply the algorithm, and add each terminal symbol returned to the set it belongs to. This method just feel like its more work then necessary.

If anyone has ever solved this problem, or has seen a way to solve this problem I would just like to know what sort of data structure was used and how it the algorithm was implemented for said structure.

Thank you for taking the time to read this, and i appreciate any feedback given.

Body:
package modelo;

import java.util.ArrayList;

/**
 *
 * @author celeste
 */
public class Axioma {

public char getSimbolo() {
    return simbolo;
}

public void setSimbolo(char simbolo) {
    this.simbolo = simbolo;
}

public ArrayList<Character> getPrimeros() {
    return primeros;
}

public void setPrimeros(ArrayList<Character> primeros) {
    this.primeros = primeros;
}

public ArrayList<Character> getSiguientes() {
    return siguientes;
}

public void setSiguientes(ArrayList<Character> siguientes) {
    this.siguientes = siguientes;
}

public ArrayList<Character> getPredictivos() {
    return predictivos;
}

public void setPredictivos(ArrayList<Character> predictivos) {
    this.predictivos = predictivos;
}

public ArrayList<Character> getRegla() {
    return regla;
}

public void setRegla(ArrayList<Character> regla) {
    this.regla = regla;
}
private ArrayList<Character> primeros = new ArrayList<>();
private ArrayList<Character> siguientes = new ArrayList<>();
private ArrayList<Character> predictivos = new ArrayList<>();
private ArrayList<Character> regla = new ArrayList<>();
private char simbolo;

}


来源: stackexchange

问:
Insert content into php page template from wordpress editor as shortcode or other way
I have an HTML inside the custom page template in WordPress theme. and this HTML is somewhere between in a bunch of code so I want to dynamically appear that h2 text
"Our Best Posts About Coffee"
through WordPress editor and not going to edit the PHP file.
Is this something possible through shortcodes or any other mean?

Our Best Posts About Coffee
```

答:
Okay i solved this on my own
Create a custom field in wordpress page/post, set a value and key, then this code needs to add on the page-template.php

echo get_post_meta( $post_id, $key = 'homepage_text1', $single = true );```

ContentLicense: CC BY-SA 4.0


问:
Regex.Replace - HELP!
I am trying to do what should be a simple pattern match and replace:

```<code>Regex.Replace(sUserSettings, @"Name={could_be_anything};", "Name=Tim;");
</code>```

I have been try along the lines of:

```<code>Regex.Replace(sUserSettings, @"Name=\*[];", "Name=Tim;");
</code>```

No joy - where am I going wrong?

答:
[] matches nothing.

To match anything (ungreedily), use .*?:

```<code>Regex.Replace(sUserSettings, @"Name=\*.*+?;", "Name=Tim;");
</code>```

Now, I'm not sure why you need to match an asterisk first (\*). If it doesn't matter, you can leave it out:

```<code>Regex.Replace(sUserSettings, @"Name=.*?;", "Name=Tim;");
</code>```

ContentLicense: CC BY-SA 3.0

Title: Regex.Replace - HELP!

Body:
I am trying to do what should be a simple pattern match and replace:

Regex.Replace(sUserSettings, @"Name={could_be_anything};", "Name=Tim;");

I have been try along the lines of:

Regex.Replace(sUserSettings, @"Name=\*[];", "Name=Tim;");

No joy - where am I going wrong?

Body:
[] matches nothing.

To match anything (ungreedily), use .*?:

Regex.Replace(sUserSettings, @"Name=\*.*+?;", "Name=Tim;");

Now, I'm not sure why you need to match an asterisk first (\*). If it doesn't matter, you can leave it out:

Regex.Replace(sUserSettings, @"Name=.*?;", "Name=Tim;");


问:
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
The following code:

```<code>Class.forName("com.mysql.jdbc.Driver");
Connection m_connection = DriverManager.getConnection("jdbc:mysql://localhost","root","root");
</code>```

Throws this exception on getConnection():

```<code>java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2397)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2430)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at db.Database.<init>(Database.java:91)
    at db.Main.main(Main.java:10)
</code>```

How is this caused and how can I solve it?

EDIT:

```<code>    public static void main(String[] args) throws ClassNotFoundException, ServletException, SQLException
    {

        try
        {
            Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword");
            Statement   s = (Statement) conn.createStatement();
            int result = s.executeUpdate("CREATE DATABASE databasename");
        }

        catch ( Exception e)
        {
            e.printStackTrace();
        }
}
</code>```

Produces :

```<code>java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2397)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2430)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at db.Main.main(Main.java:19)
</code>```

答:
The order of declaring:

Driver

Connection string

username

password

If we declaring in order

Connection string

username

password

Driver

the application will fail

Body:
The following code:

Class.forName("com.mysql.jdbc.Driver");
Connection m_connection = DriverManager.getConnection("jdbc:mysql://localhost","root","root");

Throws this exception on getConnection():

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2397)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2430)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at db.Database.<init>(Database.java:91)
    at db.Main.main(Main.java:10)

How is this caused and how can I solve it?

EDIT:

    public static void main(String[] args) throws ClassNotFoundException, ServletException, SQLException
    {

        try
        {
            Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword");
            Statement   s = (Statement) conn.createStatement();
            int result = s.executeUpdate("CREATE DATABASE databasename");
        }

        catch ( Exception e)
        {
            e.printStackTrace();
        }
}

Produces :

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
    at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1244)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2397)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2430)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at db.Main.main(Main.java:19)


问:
git-commit vim-like syntax highlighting in emacs
I've recently picked up emacs as a general editor to replace gedit and vim. The one thing I miss terribly about vim is the git syntax highlighting. I have tried git-el, apparently with no luck.

The vim git-commit highlighting features a "subject line" highlight for the first fifty characters of the first line of the commit message, "error" highlights for the second line, comments, and red and green highlighting for added or removed files (which are themselves written in the precomposed comments.)

Is there a similarly functional syntax highlighting for emacs, and if so, how would I install it?

答:
2019 update:

The answers presented here are 5 and 7 year old and it took me some time to figure out how to get various git highlightings without magit. Most links now lead to the magit repo and it is not particularly clear from there what the list of git-related packages currently is, nor whether they are on Melpa.

The EmacsWiki page does give the information, but with all the history of the movements of those various packages and their minor change of names, it is not totally easy to follow and see where things are now and what they are called.

So I thought that I would post a summary of these packages.

They are all on Melpa and any of these packages can be installed independently of the others, so you can pick and choose what you need.

the package which allows syntax highlighting for commit messages is called git-commit

for .gitignore highlighting, it is called gitignore-mode

for .gitattributes, it is called gitattributes-mode

and for .gitconfig, it is called gitconfig-mode

The package which answers the question is thus currently called git-commit and it is on Melpa.


问:
How can I remove nested lists encompassing all of my elements within a list?
I'm reading in a .csv file into a list and the output list contains nested lists for each string element.I need to my list to contain only string elements. Am I using the csv module incorrectly?

```<code>import csv
import os

with open(os.path.expanduser("~/Desktop/Tracking_Info/kw_tracking_numbers.csv"), 'r') as tracking:
    reader = csv.reader(tracking)
    TrackList = list(reader)
    print(TrackList)
</code>```

Expected output: ['PL431243161', 'PL431245166', 'PL423032770']

Actual output: [['PL431243161'], ['PL431245166'], ['PL423032770']]

答:
maybe we can modify the code in this way:</p>

```<code>import csv
import os

with open(os.path.expanduser("~/Desktop/Tracking_Info/kw_tracking_numbers.csv"), 'r') as tracking:
    TrackList = [i[0] for i in csv.reader(tracking)]

    print(TrackList)
</code>```

Body:
I'm reading in a .csv file into a list and the output list contains nested lists for each string element.I need to my list to contain only string elements. Am I using the csv module incorrectly?

import csv
import os

with open(os.path.expanduser("~/Desktop/Tracking_Info/kw_tracking_numbers.csv"), 'r') as tracking:
    reader = csv.reader(tracking)
    TrackList = list(reader)
    print(TrackList)

Expected output: ['PL431243161', 'PL431245166', 'PL423032770']

Actual output: [['PL431243161'], ['PL431245166'], ['PL423032770']]

Body:
maybe we can modify the code in this way:

import csv
import os

with open(os.path.expanduser("~/Desktop/Tracking_Info/kw_tracking_numbers.csv"), 'r') as tracking:
    TrackList = [i[0] for i in csv.reader(tracking)]

    print(TrackList)


问:
Future not being returned from await function as expected
The function signInWithGoogle calls the getUser function to retrieve the user information from the Firestore Database and expects a User as the return. Because this is a Firestore API call, the User returned by getUser is a Future and getUser is called with an await.

In the getUser function, the User is populated as expected and verified with the debugPrint("new user schedule 0: " + i[0].toJson());

However in the signInWithGoogle function, the User is not received back from the Future<User>, as seen in the null reference to schedule when performing debugPrint("user schedule 0: " + u.schedule[0].toJson());

I have tried setting the return value in multiple ways (getUser function), including instantiating a user class separately before setting it's values and returning it.

Future<User> getUser(_uid) async {
    DocumentSnapshot qs = await Firestore.instance
        .collection('users')
        .document(_uid)
        .get();
    if (qs.exists) {
      setState(() {
        state.loadingStatus = "Getting User Information";
      });
      return new User(
        schedule: await getRecipes(
            Firestore.instance
                .collection('users')
                .document(_uid)
                .collection('schedule')
        ).then((i) {
          debugPrint("get schedule");
          debugPrint("new user schedule 0: " + i[0].toJson());
        }).catchError((error) {
          debugPrint('Error: $error');
        }),
        favorites: await getRecipes(
            Firestore.instance
                .collection('users')
                .document(_uid)
                .collection('favorites')
        ).then((i) {debugPrint("get favorites");}).catchError((error) {
          debugPrint('Error: $error');
        }),
        subscription: await getSubscription(_uid).then((i) {debugPrint("get subscription");}),
        pantry: await getIngredientsList(
            Firestore.instance
                .collection('users')
                .document(_uid)
                .collection('pantry')
        ).then((i) {debugPrint("get pantry");}).catchError((error) {
          debugPrint('Error: $error');
        }),
        shopping: await getIngredientsList(
            Firestore.instance
                .collection('users')
                .document(_uid)
                .collection('shopping')
        ).then((i) {debugPrint("get shopping list");}).catchError((error) {
          debugPrint('Error: $error');
        }),
        preferences: await getPreferences(_uid).then((i) {debugPrint("get preferences");}),
      );
    }else {
      setState(() {
        state.loadingStatus = "Creating new User Information";
      });
      return User.newUser();
    }
  }

  Future<Null> signInWithGoogle() async {
    setState(() {
      state.loadingStatus = "Signing in with Google";
    });
    if (googleAccount == null) {
      // Start the sign-in process:
      googleAccount = await googleSignIn.signIn();
    }
    FirebaseUser firebaseUser = await signIntoFirebase(googleAccount);
    User user = await getUser(firebaseUser.uid);
    debugPrint("user schedule 0: " + user.schedule[0].toJson());
    setState(() {
      state.isLoading = false;
      state.loadingStatus = "";
      state.user = firebaseUser;
      state.userInfo = user;
    });
  }
```

```I/flutter (17962): new user schedule 0: {Proper data is printed here...
I/flutter (17962): get favorites
I/flutter (17962): get subscription
I/flutter (17962): get pantry
I/flutter (17962): get shopping list
I/flutter (17962): get preferences
E/flutter (17962): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter (17962): Receiver: null
E/flutter (17962): Tried calling: [](0)
```

I expect to not receive a null reference error when printing the schedule[0] from signInWithGoogle when the same call to print schedule[0] works in the  getUser function.

This is probably something stupid simple I am missing, but I cannot figure out what is happening after looking through my code for the past 3 hours.

If you need any further information, please let me know.

答:
I don't know if this is causing the issue but you're mixing Futures and async/awaits. You really only need one. This line:

```<code> User user = await getUser(firebaseUser.uid).then((u) {debugPrint("user schedule 0: " + u.schedule[0].toJson());});
</code>```

...could be seen a little simpler as:

```<code>User user = await getUser(firebaseUser.uid);

print(user.schedule[0].toJson());
</code>```

The async/await is returning a future. Placing a .then() callback with an async/await statement isn't necessary.

Body:
The function signInWithGoogle calls the getUser function to retrieve the user information from the Firestore Database and expects a User as the return. Because this is a Firestore API call, the User returned by getUser is a Future and getUser is called with an await.

In the getUser function, the User is populated as expected and verified with the debugPrint("new user schedule 0: " + i[0].toJson());

However in the signInWithGoogle function, the User is not received back from the Future<User>, as seen in the null reference to schedule when performing debugPrint("user schedule 0: " + u.schedule[0].toJson());

I have tried setting the return value in multiple ways (getUser function), including instantiating a user class separately before setting it's values and returning it.

Future<User> getUser(_uid) async {
    DocumentSnapshot qs = await Firestore.instance
        .collection('users')
        .document(_uid)
        .get();
    if (qs.exists) {
      setState(() {
        state.loadingStatus = "Getting User Information";
      });
      return new User(
        schedule: await getRecipes(
            Firestore.instance
                .collection('users')
                .document(_uid)
                .collection('schedule')
        ).then((i) {
          debugPrint("get schedule");
          debugPrint("new user schedule 0: " + i[0].toJson());
        }).catchError((error) {
          debugPrint('Error: $error');
        }),
        favorites: await getRecipes(
            Firestore.instance
                .collection('users')
                .document(_uid)
                .collection('favorites')
        ).then((i) {debugPrint("get favorites");}).catchError((error) {
          debugPrint('Error: $error');
        }),
        subscription: await getSubscription(_uid).then((i) {debugPrint("get subscription");}),
        pantry: await getIngredientsList(
            Firestore.instance
                .collection('users')
                .document(_uid)
                .collection('pantry')
        ).then((i) {debugPrint("get pantry");}).catchError((error) {
          debugPrint('Error: $error');
        }),
        shopping: await getIngredientsList(
            Firestore.instance
                .collection('users')
                .document(_uid)
                .collection('shopping')
        ).then((i) {debugPrint("get shopping list");}).catchError((error) {
          debugPrint('Error: $error');
        }),
        preferences: await getPreferences(_uid).then((i) {debugPrint("get preferences");}),
      );
    }else {
      setState(() {
        state.loadingStatus = "Creating new User Information";
      });
      return User.newUser();
    }
  }

  Future<Null> signInWithGoogle() async {
    setState(() {
      state.loadingStatus = "Signing in with Google";
    });
    if (googleAccount == null) {
      // Start the sign-in process:
      googleAccount = await googleSignIn.signIn();
    }
    FirebaseUser firebaseUser = await signIntoFirebase(googleAccount);
    User user = await getUser(firebaseUser.uid);
    debugPrint("user schedule 0: " + user.schedule[0].toJson());
    setState(() {
      state.isLoading = false;
      state.loadingStatus = "";
      state.user = firebaseUser;
      state.userInfo = user;
    });
  }

I/flutter (17962): new user schedule 0: {Proper data is printed here...
I/flutter (17962): get favorites
I/flutter (17962): get subscription
I/flutter (17962): get pantry
I/flutter (17962): get shopping list
I/flutter (17962): get preferences
E/flutter (17962): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter (17962): Receiver: null
E/flutter (17962): Tried calling: [](0)

I expect to not receive a null reference error when printing the schedule[0] from signInWithGoogle when the same call to print schedule[0] works in the  getUser function.

This is probably something stupid simple I am missing, but I cannot figure out what is happening after looking through my code for the past 3 hours.

If you need any further information, please let me know.

Body:
I don't know if this is causing the issue but you're mixing Futures and async/awaits. You really only need one. This line:

 User user = await getUser(firebaseUser.uid).then((u) {debugPrint("user schedule 0: " + u.schedule[0].toJson());});

...could be seen a little simpler as:

User user = await getUser(firebaseUser.uid);

print(user.schedule[0].toJson());

The async/await is returning a future. Placing a .then() callback with an async/await statement isn't necessary.


问:
Getting error when trying to use JSON loads. Believe string to be in the correct format
When I try to use json.loads on this string in Python, I get the following error.

I don't understand why because I believe I am formatting the string correctly for JSON.

Code example below creates the following error: json.decoder.JSONDecodeError: Extra data: line 1 column 132 (char 131)

import pymongo

import json

mongo_import_str = '{"Top_Level": {"NextLevelDown": {"First": "1","Second":"2","Third":"3"}}, "NextLevelDown2": {"First":"1","Second":"2","Third":"3"}}}'

mongo_import = json.loads(mongo_import_str)
collection.insert_one(mongo_import)

答:
Here's how the JSON looks with some better formatting.

```<code>{
    "Top_Level":{
        "NextLevelDown":{
            "First": "1","Second":"2","Third":"3"
        }
    },
    "NextLevelDown2":{
        "First":"1","Second":"2","Third":"3"
    }
}
}
</code>```

As you can see, there's a spare } in there. Remove it.

Body:
Here's how the JSON looks with some better formatting.

{
    "Top_Level":{
        "NextLevelDown":{
            "First": "1","Second":"2","Third":"3"
        }
    },
    "NextLevelDown2":{
        "First":"1","Second":"2","Third":"3"
    }
}
}

As you can see, there's a spare } in there. Remove it.


问:
How can I extract a subtree from my SVN repository into a new one?
We have a Subversion repository with one directory that is:

Not really in need of revision control beyond the capabilities of RCS

Not versioned in conjunction with anything else in the repository

Modified about six times as often as the rest of the repository

Although I know that high revision numbers aren't a problem, nonetheless I'd like to pull this one single directory out of my main repository and into a second, ideally new one.

What is the best process for that? If it makes a difference, the SVN repository is hosted on a (... checks... ) FreeBSD machine.

It's worth noting that while I need to retain the version history in the new repository, there's no need to obliterate the content in the old; it can just sit there, for all I care.

答: I don't know if I understand this correctly, but there's a nice solution to that. If your original repository was at svn://domain, and the folder you use a lot is called "folder", I believe you can simply perform the following command: svn co svn://domain/folder to checkout only that folder.

OwnerDisplayName: Chris R

LastEditorDisplayName: Chris R

OwnerDisplayName: Andrew Szeto

ContentLicense: CC BY-SA 2.5


问:
How to load an ImageView by URL in Android?
How do you use an image referenced by URL in an ImageView?

答:
I wrote a class to handle this, as it seems to be a recurring need in my various projects:

https://github.com/koush/UrlImageViewHelper

UrlImageViewHelper will fill an
  ImageView with an image that is found
  at a URL.

The sample will do a Google Image
  Search and load/show the results
  asynchronously.

UrlImageViewHelper will automatically
  download, save, and cache all the
  image urls the BitmapDrawables.
  Duplicate urls will not be loaded into
  memory twice. Bitmap memory is managed
  by using a weak reference hash table,
  so as soon as the image is no longer
  used by you, it will be garbage
  collected automatically.


问:
Mock unit testing for RxJava
I'm writing unit tests base on Google's samples: TaskDetailPresenterTest.kt#L102

They use ArgumentCaptor<TasksDataSource.GetTaskCallback> to trigger callback with fake data COMPLETED_TASK

```<code>@Test
fun getCompletedTaskFromRepositoryAndLoadIntoView() {
    presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView)
    presenter.start()

    // Then task is loaded from model, callback is captured
    verify(tasksRepository).getTask(
                eq(COMPLETED_TASK.id), capture(taskCallbackCaptor))

    // When task is finally loaded
    taskCallbackCaptor.value.onTaskLoaded(COMPLETED_TASK) // Trigger callback
}
</code>```

Everything work fine because they use TasksDataSource.GetTaskCallback to return data. See: TaskDetailPresenter.kt#L36:

```<code>fun getTask(taskId: String, callback: GetTaskCallback)
</code>```

Then use as

```<code>tasksRepository.getTask(taskId, object : TasksDataSource.GetTaskCallback {
    override fun onTaskLoaded(task: Task) {
        showTask(task)
    }
}
</code>```

But when I try to use RxJava Single<> instead of normal callback, like:

```<code>fun getTask(taskId: String): Single<Task>
</code>```

Then use as

```<code>tasksRepository.getTask(taskId)
    .subscribe(object : SingleObserver<Task> {
        override fun onSuccess(task: Task) {
            showTask(task)
        }

        override fun onError(e: Throwable) {
        }
    })
}
</code>```

Then I cannot use ArgumentCaptor<> to trigger return fake data. It always throw NullPointerException when I execute my test, because  tasksRepository.getTask(taskId) is always return null.

So how can I achieve the same unit test like Google did, but in RxJava?

My unit test code:

```<code>@Mock private lateinit var tasksRepository: TasksRepository

@Captor private lateinit var taskCaptor: ArgumentCaptor<SingleObserver<Task>>

private lateinit var presenter: TaskDetailPresenter

@Before fun setup() {
    MockitoAnnotations.initMocks(this)
}

@Test
fun getCompletedTaskFromRepositoryAndLoadIntoView() {
    presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView)
    presenter.start()

    // Then task is loaded from model, callback is captured
    verify(tasksRepository).getTask(
                eq(COMPLETED_TASK.id)).subscribe(taskCaptor.capture())

    // When task is finally loaded
    taskCaptor.value.onSuccess(COMPLETED_TASK) // Trigger callback
}
</code>```

Note that all other parts (declare, setup, mocking,..) is the same as Google.

答: All this method is doing is showTask(task: Task). So assert that this method is called after your observer starts observing. You shouldn't care what the showTask is going to do once it's called. If you use Rx it is much better to make your methods take arguments and return value of the observe pattern to make it easier write unit test. </p>

Title: Mock unit testing for RxJava

Body:
I'm writing unit tests base on Google's samples: TaskDetailPresenterTest.kt#L102

They use ArgumentCaptor<TasksDataSource.GetTaskCallback> to trigger callback with fake data COMPLETED_TASK

@Test
fun getCompletedTaskFromRepositoryAndLoadIntoView() {
    presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView)
    presenter.start()

    // Then task is loaded from model, callback is captured
    verify(tasksRepository).getTask(
                eq(COMPLETED_TASK.id), capture(taskCallbackCaptor))

    // When task is finally loaded
    taskCallbackCaptor.value.onTaskLoaded(COMPLETED_TASK) // Trigger callback
}

Everything work fine because they use TasksDataSource.GetTaskCallback to return data. See: TaskDetailPresenter.kt#L36:

fun getTask(taskId: String, callback: GetTaskCallback)

Then use as

tasksRepository.getTask(taskId, object : TasksDataSource.GetTaskCallback {
    override fun onTaskLoaded(task: Task) {
        showTask(task)
    }
}

But when I try to use RxJava Single<> instead of normal callback, like:

fun getTask(taskId: String): Single<Task>

Then use as

tasksRepository.getTask(taskId)
    .subscribe(object : SingleObserver<Task> {
        override fun onSuccess(task: Task) {
            showTask(task)
        }

        override fun onError(e: Throwable) {
        }
    })
}

Then I cannot use ArgumentCaptor<> to trigger return fake data. It always throw NullPointerException when I execute my test, because  tasksRepository.getTask(taskId) is always return null.

So how can I achieve the same unit test like Google did, but in RxJava?

My unit test code:

@Mock private lateinit var tasksRepository: TasksRepository

@Captor private lateinit var taskCaptor: ArgumentCaptor<SingleObserver<Task>>

private lateinit var presenter: TaskDetailPresenter

@Before fun setup() {
    MockitoAnnotations.initMocks(this)
}

@Test
fun getCompletedTaskFromRepositoryAndLoadIntoView() {
    presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView)
    presenter.start()

    // Then task is loaded from model, callback is captured
    verify(tasksRepository).getTask(
                eq(COMPLETED_TASK.id)).subscribe(taskCaptor.capture())

    // When task is finally loaded
    taskCaptor.value.onSuccess(COMPLETED_TASK) // Trigger callback
}

Note that all other parts (declare, setup, mocking,..) is the same as Google.


问:
Firehose - Only copy specific specific data from stream
I'm currently using a Amazon Kinesis Firehose to dump analytics data into a Redshift database table.  This table has grown very large over time, and queries are becoming slower and slower.

To speed things up, I would like to set up multiple Firehoses, and differentiate COPY command based on the content of the json document.

For example, if I have two json documents that look like the following:

```<code>  tableName: 'abc',
  data: 'some string of data'
}

{
  tableName: 'xyz',
  data: 'some string of data'
}
</code>```

I would set up two Firehoses.  Firehose abc would run the COPY command in to table abc, and Firehose xyz would run the COPY command in to table xyz.  However, they should ignore each other's data based on the tableName specified in the json.  For example, if xyz is copying over data, and the json has tableName: 'abc', it should ignore that document.

My question is, is this possible or does anyone have experience solving the problem of a Redshift table growing to massive amounts of data and slowing down queries?

答:
You can create a delivery stream which allows you to introduce a Lambda function to perform transformations/filtering on the data before it goes to its destination.

Here is an article that discuss how to set this up.  It uses S3 as the destination but you should be able to use this same method with Redshift as the destination.

Body:
I'm currently using a Amazon Kinesis Firehose to dump analytics data into a Redshift database table.  This table has grown very large over time, and queries are becoming slower and slower.

To speed things up, I would like to set up multiple Firehoses, and differentiate COPY command based on the content of the json document.

For example, if I have two json documents that look like the following:

  tableName: 'abc',
  data: 'some string of data'
}

{
  tableName: 'xyz',
  data: 'some string of data'
}

I would set up two Firehoses.  Firehose abc would run the COPY command in to table abc, and Firehose xyz would run the COPY command in to table xyz.  However, they should ignore each other's data based on the tableName specified in the json.  For example, if xyz is copying over data, and the json has tableName: 'abc', it should ignore that document.

My question is, is this possible or does anyone have experience solving the problem of a Redshift table growing to massive amounts of data and slowing down queries?


问:
Making Array Of Requests Using Requests Library In Python
I am using the requests library to map an array of requests after I get an array from another API request. I am using a loop for the requests but I sure there is a better way to do this because this API request can have 500+ items, so finishing this looping is taking 20+ minutes sometimes.

I tried to use the grequests library and I kept getting recursion complaints. I would love to use an async/map method if possible but after researching apparently the async library is not supported anymore.

```<code>self.set_header("Access-Control-Allow-Origin", "*")
response = requests.get("https://hacker-news.firebaseio.com/v0/paststories.json?print=pretty")
data = response.json()
story_list = []

for story in data:
    temp_string = "https://hacker-news.firebaseio.com/v0/item/{}.json?print=pretty".format(story)
    story_data = requests.get(temp_string)
    story_list.append(story_data.json())
</code>```

There should be a better way to do this looping than the current method because 20+ minutes to get the data is not acceptable. The API response in the original array can return an array of 500+ so the method should be scalable.

答:
requests is synchronous, so your script waits for a response to make a new request.
So Maybe you should look into aiohttp and aysnchronous requests.

This could be an example : Is that benchmark reliable - aiohttp vs requests

Body:
I am using the requests library to map an array of requests after I get an array from another API request. I am using a loop for the requests but I sure there is a better way to do this because this API request can have 500+ items, so finishing this looping is taking 20+ minutes sometimes.

I tried to use the grequests library and I kept getting recursion complaints. I would love to use an async/map method if possible but after researching apparently the async library is not supported anymore.

self.set_header("Access-Control-Allow-Origin", "*")
response = requests.get("https://hacker-news.firebaseio.com/v0/paststories.json?print=pretty")
data = response.json()
story_list = []

for story in data:
    temp_string = "https://hacker-news.firebaseio.com/v0/item/{}.json?print=pretty".format(story)
    story_data = requests.get(temp_string)
    story_list.append(story_data.json())

There should be a better way to do this looping than the current method because 20+ minutes to get the data is not acceptable. The API response in the original array can return an array of 500+ so the method should be scalable.


问:
can i use reactjs and mongodb without MERN Stack
i'm looking creating a reacrjs  web-app connectting to mongodb database directly !!
withe out using "MERN STACK" or "express" or "nodejs"</p>

答:
Connecting to a database (including MongoDB) from a web app is dangerous. Web applications send all their code to the user's browser when they visit the website. A user can right click on a page and click 'view page source' to see all the code. A user can also see the code in chrome developer tools. They can see any username, passwords, or urls you might use to connect. They can see all the queries that are sent and figure out how your data is structured. It becomes very easy for a hacker to find weak spots in your code and steal data or take over the website. ReactJS has a chrome browser extension which tells you if a website is using React. If it is, the extension will show you the code in the React tab of chrome developers tools.

If you are building a ReactJS web app then you are already using NodeJS. ReactJS web apps are NodeJS apps with some imported ReactJS libraries.


问:
How can I use a for loop to modify a variable inside a string while I download a list of images using BS?
I am using BeautifulSoup to scrape a page with a table. When I am going to download some images inside that table using  a for loop and "urlretrieve", I am not able to give each image a different name, thus the each time an image is downloaded, it is replaced by a new image because they have the same name.

In other words, I am not able to change a variable inside a string so that I can give each downloaded image a different name.

答:
From your last picture, you are setting num to 0 at each loop iteration. You want to take it out of the loop.

```<code>for ...
  num=0
</code>```

to

```<code>num = 0
for ...
  num += 1
</code>```

Body:
From your last picture, you are setting num to 0 at each loop iteration. You want to take it out of the loop.

for ...
  num=0

to

num = 0
for ...
  num += 1


问:
How should I create a binary variable that is exactly the opposite of another one?
I'm trying to create a binary variable as answer to another binary variable

This is the gpa2 dataset from wooldridge library. I tried to create the variable male with a while loop too but it still doesn't work. I've already tried adding else statements but it didn't work.

```<code>library(wooldridge)
gpa2 <- gpa2
for(i in 1:length(gpa2$female)){
if(gpa2$female == 0 ){
gpa2$male = 1
 }
}
</code>```

I expect male be 0 when female is 1 and male be 1 when female is 0, but the output I get is male = 0 for every observation.

答:
```<code>gpa2$male<-as.numeric(!gpa2$female)
</code>```

You're really missing out on R if you do everything with for-loops. More often than not, there's a much faster way of doing what you're trying to do using r's in-built ability to vectorize actions. In this case, we simply take gpa2$female, use ! to flip 0's into TRUEs and 1's into FALSEs, and then turn that into a numeric format so they appear as 1s and 0s respectively, and place that whole vector into gpa2$male.

Body:
I'm trying to create a binary variable as answer to another binary variable

This is the gpa2 dataset from wooldridge library. I tried to create the variable male with a while loop too but it still doesn't work. I've already tried adding else statements but it didn't work.

library(wooldridge)
gpa2 <- gpa2
for(i in 1:length(gpa2$female)){
if(gpa2$female == 0 ){
gpa2$male = 1
 }
}

I expect male be 0 when female is 1 and male be 1 when female is 0, but the output I get is male = 0 for every observation.

Body:
gpa2$male<-as.numeric(!gpa2$female)

You're really missing out on R if you do everything with for-loops. More often than not, there's a much faster way of doing what you're trying to do using r's in-built ability to vectorize actions. In this case, we simply take gpa2$female, use ! to flip 0's into TRUEs and 1's into FALSEs, and then turn that into a numeric format so they appear as 1s and 0s respectively, and place that whole vector into gpa2$male.


问:
Currently have a huge csv file, and want to sort the values by date?
I have a csv file with a lot of tables, and dates ranging from 1/1/2019 - 31/1/2019 ... of different years
I need to sum all the columns X for all the years, and have a graph, of how Each month changes per different years.
and how in one specific year different months show the X values differently.

using pandas. and matplotlib.

```<code>muestradatos[muestradatos.DateMonth == 1]

This is what the query in pandas shows
1/1/2019 455
1/2/2019 555
1/3/2019 15
1/4/2019 655
.
.
1/1/2017 644
</code>```

I need it to show

```<code>Year 2019

JANUARY (the whole month) 50

FEBRUARY                  30

Year 2012
...
...
...
</code>```

答:
pd.to_datetime()  to turn it into a date.
df.sort_values(by='Date')</p>

Body:
I have a csv file with a lot of tables, and dates ranging from 1/1/2019 - 31/1/2019 ... of different years
I need to sum all the columns X for all the years, and have a graph, of how Each month changes per different years.
and how in one specific year different months show the X values differently.

using pandas. and matplotlib.

muestradatos[muestradatos.DateMonth == 1]

This is what the query in pandas shows
1/1/2019 455
1/2/2019 555
1/3/2019 15
1/4/2019 655
.
.
1/1/2017 644

I need it to show

Year 2019

JANUARY (the whole month) 50

FEBRUARY                  30

Year 2012
...
...
...


问:
Is it worth using Python's re.compile?
Is there any benefit in using compile for regular expressions in Python?

```<code>h = re.compile('hello')
h.match('hello world')
</code>```

vs

```<code>re.match('hello', 'hello world')
</code>```

答:
As an alternative answer, as I see that it hasn't been mentioned before, I'll go ahead and quote the Python 3 docs:

Should you use these module-level functions, or should you get the pattern and call its methods yourself? If you’re accessing a regex within a loop, pre-compiling it will save a few function calls. Outside of loops, there’s not much difference thanks to the internal cache.

OwnerDisplayName: Mat

Title: Is it worth using Python's re.compile?

Body:
Is there any benefit in using compile for regular expressions in Python?

h = re.compile('hello')
h.match('hello world')

vs

re.match('hello', 'hello world')

LastEditorDisplayName: Chad Birch


问:
In PyTorch/Numpy, how to multiply rows of a matrix with "matrices" in a 3-D tensor?
For example, a = torch.Tensor([[1,2],[3,4]]) (for numpy it is just a = np.array([[1,2],[3,4]])), and b = torch.ones((2,2,2)),

I would like to product every row of a with the two 2x2 matrices, and get a new matrix [[3,3],[7,7]] (i.e. [1,2]*[[1,1],[1,1]]=[3,3], [3,4]*[[1,1],[1,1]]=[7,7]). Is it possible to achieve this? Thanks!

答:
You can just use regular matrix multiplication a @ b:

```<code>a = np.array([[1,2],[3,4]])
b = np.ones((2,2,2))

print(a @ b)
</code>```

Output:

```<code>[[[3. 3.]
  [7. 7.]]

 [[3. 3.]
  [7. 7.]]]
</code>```

Each "row" of the result (ie the first index) will be a separate 2 x 2 matrix:

```<code>print((a @ b)[1])
</code>```

Output:

```<code>[[3. 3.]
 [7. 7.]]
</code>```

Body:
You can just use regular matrix multiplication a @ b:

a = np.array([[1,2],[3,4]])
b = np.ones((2,2,2))

print(a @ b)

Output:

[[[3. 3.]
  [7. 7.]]

 [[3. 3.]
  [7. 7.]]]

Each "row" of the result (ie the first index) will be a separate 2 x 2 matrix:

print((a @ b)[1])

Output:

[[3. 3.]
 [7. 7.]]


问:
How do use Javascript Async-Await as an alternative to polling for a statechange?
I'd like to accomplish the following using promises: only execute further once the state of something is ready. I.e. like polling for an external state-change.

I've tried using promises and async-await but am not getting the desired outcome. What am I doing wrong here, and how do I fix it?

The MDN docs have something similar but their settimeout is called within the promise--that's not exactly what I'm looking for though.

I expect the console.log to show "This function is now good to go!" after 5 seconds, but instead execution seems to stop after calling await promiseForState();

var state = false;

function stateReady (){
 state = true;
}

function promiseForState(){
 var msg = "good to go!";
 var promise = new Promise(function (resolve,reject){
        if (state){
            resolve(msg);
        }
    });

  return promise;
}

async function waiting (intro){

    var result = await promiseForState();
    console.log(intro + result)

}
setTimeout(stateReady,5000);
waiting("This function is now ");```

答:
What you're doing wrong is the promise constructor executor function executes immediately when the promise is created, and then never again. At that point, state is false, so nothing happens.

Promises (and async/await) are not a replacement for polling. You still need to poll somewhere.

The good news: async functions make it easy to do conditional code with loops and promises.

But don't put code inside promise constructor executor functions, because of their poor error handling characteristics. They are meant to wrap legacy code.

Instead, try this:

var state = false;

function stateReady() {
 state = true;
}

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

async function promiseForState() {
  while (!state) {
    await wait(1000);
  }
  return "good to go!";
}

async function waiting(intro) {
    var result = await promiseForState();
    console.log(intro + result)
}
setTimeout(stateReady,5000);
waiting("This function is now ");```


答:
well, you just need to boost the speed of your io-bond code, there are tones of the solution, please refer to this related answer in stackoverflow: How could I use requests in asyncio?

due to asyncio is too much fundamental, there are a lot of package built base on it, try this package: aiohttp-requests

hope these information can help.

Title: Making Array Of Requests Using Requests Library In Python


问:
Visual Studio Key Strokes: Swapping lines
Is there a keystroke in visual studio similar to Eclipse's Alt + ↑/↓?

For example:

```<code>int x = 0; // Cursor is anywhere on this line.
int y = 1;
</code>```

and Alt + Down were pressed, then:

```<code>int y = 1;
int x = 0; // Cursor is anywhere on this line.
</code>```

答:
VS 2013 and later:

Alt + ↑ (Edit.MoveSelectedLinesUp)

Alt + ↓ (Edit.MoveSelectedLinesDown)

VS 2012:

Shift+Alt+ T
(Edit.LineTranspose)

but this only swaps between the current and the next line (move down only).

VS 2012 does not support macros but there is the Productivity Power Tools 2012 extension that adds (besides some other nice features) commands to move a line up or down with Alt + ↑ and Alt + ↓.

VS 2010 and earlier:

Line transpose works (Shift+Alt+ T) but still no move up.

You could write a macro for those commands, I think this question may help you: Visual Studio: hotkeys to move line up/down and move through recent changes

Body:
Is there a keystroke in visual studio similar to Eclipse's Alt + ↑/↓?

For example:

int x = 0; // Cursor is anywhere on this line.
int y = 1;

and Alt + Down were pressed, then:

int y = 1;
int x = 0; // Cursor is anywhere on this line.


问:
Script produces different result when executed by Bash than by cron
Please consider following crontab (root):

```<code>SHELL=/bin/bash
...
...
0 */3 * * * /var/maintenance/raid.sh
</code>```

And the bash script /var/maintenance/raid.sh:

```<code>#!/bin/bash

echo -n "Checking /dev/md0... "
if ! [ $(mdadm --detail /dev/md0 | grep -c "active sync") -eq 2 ]; then
    mdadm --detail /dev/md0 | mail -s "Raid problem /dev/md0" "my@email.com";
    echo "ERROR"
else
    echo "ALL OK"
fi;

#-------------------------------------------------------

echo -n "Checking /dev/md1... "
...
</code>```

And this is what happen when...

...executed from shell prompt (bash):

Mail with mdadm --detail /dev/md0 output is sent to my email (proper behaviour)

...executed by cron:

Blank mail is sent to my email (subject is there, but there is no message)

Why such difference and how to fix it?

答:
Before running your script as a cron job, you can test it with no environment variables using env -i

```<code>env -i /var/maintenance/raid.sh
</code>```

Body:
Please consider following crontab (root):

SHELL=/bin/bash
...
...
0 */3 * * * /var/maintenance/raid.sh

And the bash script /var/maintenance/raid.sh:

#!/bin/bash

echo -n "Checking /dev/md0... "
if ! [ $(mdadm --detail /dev/md0 | grep -c "active sync") -eq 2 ]; then
    mdadm --detail /dev/md0 | mail -s "Raid problem /dev/md0" "my@email.com";
    echo "ERROR"
else
    echo "ALL OK"
fi;

#-------------------------------------------------------

echo -n "Checking /dev/md1... "
...

And this is what happen when...

...executed from shell prompt (bash):

Mail with mdadm --detail /dev/md0 output is sent to my email (proper behaviour)

...executed by cron:

Blank mail is sent to my email (subject is there, but there is no message)

Why such difference and how to fix it?

Body:
Before running your script as a cron job, you can test it with no environment variables using env -i

env -i /var/maintenance/raid.sh


问:
Create a new vector model in gensim
I already trained a word2vec model with gensim library. For example, my model contains vectors for 2 words: "new" and "york". However, I also want to train a vector for the word "new york", so I transform "new york" into "new_york" and train a new vector model. Finally, I want to combine 3 vectors: vector of the word "new", "york" and "new_york" into one vector representation for the word "new york".

How can I save the new vector value to the model?

I try to assign the new vector to the model but gensim did not allow to assign the new value for vector model.

答:
Word-vectors are generally only comparable to each other if they were trained together.

So, if you want to have vectors for all of 'new', 'york', and 'new_york', you should prepare a corpus which includes them all, in a variety of uses, and train a Word2Vec model from that.

Title: Create a new vector model in gensim


问:
How to grab a value from a dictionary which contains multiple keys?
I have this dictionary:

```<code> mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}
</code>```

My question is, how do I obtain value value1 by using only one of the keys e.g 950001?

In other words, I want to do something like:

```<code>mydict['950001']
</code>```

and get printed:

```<code>value1
</code>```

I know I may reverse the keys and values, but in this case it won't work for the script I am working on.

Body:
I have this dictionary:

 mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}

My question is, how do I obtain value value1 by using only one of the keys e.g 950001?

In other words, I want to do something like:

mydict['950001']

and get printed:

value1

I know I may reverse the keys and values, but in this case it won't work for the script I am working on.

Body:
def get_value(n):
    newdict = {
        "value1": ["950001", "959070", "959071", "959072", "950908", "959073"],
        "value2": ["400856", "400857", "400858", "400859", "400860", "400861"],
        "value3": ["920100"],
        "value4": ["950107", "950109", "950108"]
    }
    # Loop through dictionary to find a match and its value
    for value, nums in newdict.items():
        if n in nums:
            return(value)


问:
How to get current Locale in Spring?
I use this method

LocaleContextHolder.getLocale()

to get switched locale (Japanise) but it returns me English (default). How can I retrieve the jp_JP locale?

答:
There are several ways to create a Locale object.To get the current Local object.

```<code>Locale locale = LocaleContextHolder.getLocale();
</code>```

or

```<code>Locale locale;
</code>```

to get the current language

```<code>Locale locale;
locale.getLanguage()

Locale locales = LocaleContextHolder.getLocale();
locales.getLanguage();
</code>```

Title: How to get current Locale in Spring?

Body:
There are several ways to create a Locale object.To get the current Local object.

Locale locale = LocaleContextHolder.getLocale();

or

Locale locale;

to get the current language

Locale locale;
locale.getLanguage()

Locale locales = LocaleContextHolder.getLocale();
locales.getLanguage();


问:
Disassemble x86 code in a program at a specific address
Is there any x86 disassembler framework that can be used to analyze code from a specific address in a program, as in:

```<code>info = disassemble(  startAddress , stopAddress)
</code>```

It should show every instruction and its operands and any other info that is good for analysis but it should have also fast mode where it isn't so important to obtain that much info for each instruction, but only for some of them that can be specified.

答:
The cross-platform InstructionAPI suits this purpose, it will analyze the code and can print out the disassembly or provide a machine-independent view of the instructions for you to query.  InstructionAPI is a shared library that you would link your code against.

http://www.paradyn.org/html/manuals.html

Body:
Is there any x86 disassembler framework that can be used to analyze code from a specific address in a program, as in:

info = disassemble(  startAddress , stopAddress)

It should show every instruction and its operands and any other info that is good for analysis but it should have also fast mode where it isn't so important to obtain that much info for each instruction, but only for some of them that can be specified.


问:
Access denied error for Process.Start inside .NET Standard library referenced in UWP
In my VS2017 solution, I created a UWP and .NET Standard Library 2.0.3 projects. Referenced Library project from UWP. Library project is using a System.Diagnostics.Process to start a process. In debug mode, I get access denied error at line Process.Start(...) of the code inside Library project.

I thought the purpose of new .NET Standard Library project was to support various platforms (.NET, .NET Core, UWP etc) uniformly. But I guess, the sandbox nature of UWP apps is probably not allowing me to run Process.Start(...) albeit the process is running inside Library project. Question: What I may be missing and/or how can we resolve the above issue?

答: According to this answer, you can't use Process.Start in a UWP app. There are some alternatives for launching other apps, but you can't execute arbitrary .exe or other processes.


问:
How to create IObservable from delegate?
This code:

```<code>// NOTE: IQuote DOES NOT inherit from EventArgs
public interface IQuote// : EventArgs
{
}

class C
{
   //NOTE, this is NOT public event EventHandler<IQuote> QuoteChangeEvent;
    public delegate void QuoteChangeEvent(IQuote q);
}

var c = new C();

c.OnQuoteChange += ProcessQuoteChange;

public static void ProcessQuoteChange(IQuote q)
{
}
</code>```

works fine. Now I want to use Rx. This doesn't work, i.e., it doesn't even compile:

```<code>var priceChangedObservable = Observable.FromEvent<QuoteChangeEvent, QuoteChangeEvent>(
    (handler) =>
    {
        QuoteChangeEvent quoteHandler = (e) => handler(e);
    },
    eh => c.OnQuoteChange += eh,
    eh => c.OnQuoteChange -= eh
    );
</code>```

On the line (handler) =>

```<code>- "Severity Code    Description Project File    Line    Suppression State
   Error    CS1643  Not all code paths return a value in lambda expression
   of type 'Func<Action<QuoteChangeEvent>,
   QuoteChangeEvent>'       294 Active"
</code>```

On the handler(e)

Error CS1503  Argument 1: cannot convert from 'IQuote' to
  'QuoteChangeEvent'        296 Active

What is the correct way to create an IObservable from a delegate?

答:
When using Observable.FromEvent<TDelegate, TEventArgs>, you should pass <QuoteChangeEvent, IQuote>:

```<code>var priceChangedObservable = Observable.FromEvent<QuoteChangeEvent, IQuote>(
    handler =>
    {
        QuoteChangeEvent quoteHandler = (e) => { handler(e); };
        return quoteHandler;
    },
    eh => c.OnQuoteChange += eh,
    eh => c.OnQuoteChange -= eh
);

</code>```

Body:
This code:

// NOTE: IQuote DOES NOT inherit from EventArgs
public interface IQuote// : EventArgs
{
}

class C
{
   //NOTE, this is NOT public event EventHandler<IQuote> QuoteChangeEvent;
    public delegate void QuoteChangeEvent(IQuote q);
}

var c = new C();

c.OnQuoteChange += ProcessQuoteChange;

public static void ProcessQuoteChange(IQuote q)
{
}

works fine. Now I want to use Rx. This doesn't work, i.e., it doesn't even compile:

var priceChangedObservable = Observable.FromEvent<QuoteChangeEvent, QuoteChangeEvent>(
    (handler) =>
    {
        QuoteChangeEvent quoteHandler = (e) => handler(e);
    },
    eh => c.OnQuoteChange += eh,
    eh => c.OnQuoteChange -= eh
    );

On the line (handler) =>

- "Severity Code    Description Project File    Line    Suppression State
   Error    CS1643  Not all code paths return a value in lambda expression
   of type 'Func<Action<QuoteChangeEvent>,
   QuoteChangeEvent>'       294 Active"

On the handler(e)

Error CS1503  Argument 1: cannot convert from 'IQuote' to
  'QuoteChangeEvent'        296 Active

What is the correct way to create an IObservable from a delegate?

Body:
When using Observable.FromEvent<TDelegate, TEventArgs>, you should pass <QuoteChangeEvent, IQuote>:

var priceChangedObservable = Observable.FromEvent<QuoteChangeEvent, IQuote>(
    handler =>
    {
        QuoteChangeEvent quoteHandler = (e) => { handler(e); };
        return quoteHandler;
    },
    eh => c.OnQuoteChange += eh,
    eh => c.OnQuoteChange -= eh
);


问:
Is there a function that can display an object from a class that I've created into a QTextBrowser?
I'm creating a GUI that stores and displays objects of various data types such as int, double, string and three other class that i have created that are Rational, Date, and Complex. These objects are stored into Linked Lists of the same type. For int, double, and string i've had to problem storing values that the user enters into a QPlainTextEdit to the lists and displaying them into the QTextBrowser, however, i'm unsure on how to display objects from classes that i've created into the QTextBrowser. Is there a function that can do this?

I'm currently working with my Rational class that takes in objects in the form of "Rational(3,4);" and displays them like fractions such as "3/4".
I've managed to create the objects from user inputs that are in the form "3/4" and push them into the linked list but i have not been able to display them into my QTextBrowser

```<code>//sample code
else if(ui->Rational_button->isChecked())
{
    ui->main_display->setText("");

    //Iterator that goes through the linked list to get the objects
    LinkedList<Rational>::Iterator it = rationalvec.begin();

    while(it != nullptr)
    {
       ui->main_display->append(QString::fromStdString(*it));
                                      /* Trying to display all Rational
                                      objects in the QTextBrowser */
       ++it;
    }
}

//There should be an output like the following inside the QTextBrowser

4/5
2/3
7/9
9/11

//These are all Rational type objects
</code>```

I'm getting a "semantic issue" no viable conversion from 'Rational' to QString/const std::string. I can't seem to find a way to convert or display these objects into the QTextBrowser.

EDIT: Here is the Rational class

```<code>class Rational
{
private:
    int numer;  //IN/OUT - the numerator int
    int denom;  //IN/OUT - the denominator int
public:
    /******************************
    ** CONSTRUCTOR & DESTRUCTOR **
    ******************************/
    Rational()         //Constructor
    {
       numer = 0;
       denom = 1;
    }
    Rational(int number)               //Constructor
    {
       numer = number;
       denom = 1;
    }
    Rational(int number1, int number2) //Constructor
    {
      numer = number1;
      denom = number2;
    }

    /***************
    ** ACCESSORS **
    ***************/
    const Rational add(const Rational &) const;
    const Rational subtract(const Rational &) const;
    const Rational multiply(const Rational &) const;
    const Rational divide(const Rational &) const;

    void display() const
    {
       cout << numer << "/" << denom;
    }

    friend ostream& operator<<(ostream &, const Rational &)    //FOR WIDGET
    {
       out << object.numer;
       out << '/';
       out << object.denom;

       return out;
   }

    bool operator <(const Rational& )                          //FOR WIDGET
    {
       if((numer/denom) < (other.numer/other.denom))
           return true;
       else
           return false;
    }
    bool operator >(const Rational& )                          //FOR WIDGET
    {
       if((numer/denom) > (other.numer/other.denom))
           return true;
       else
           return false;
     }

};
</code>```

Only showing the function definition for the functions i'm using, the other functions whose definitions are not shown are the ones im not gonna use during this program.

答:
i'm unsure on how to display objects from classes that i've created into the QTextBrowser. Is there a function that can do this?

Only if you write one. It's your class, so it's your job to provide such a function.

How you go about this depends on how your class is intended to be used. If it is reasonable to think of your class as being a string (seems unlikely for a rational number), you could provide an implicit user-defined conversion to string. You should not provide an implicit conversion in other cases since implicit conversions often hamper the compiler's ability to identify bugs. An explicit conversion is another option, but often people go with a conversion function. (Examples from the standard library include stringstream::str and bitset::to_string.)

You already have most of a conversion function written. All you need is to stream your object to a std::stringstream then call that stream's str() method. Re-use your code as much as reasonable.

Body:
I'm creating a GUI that stores and displays objects of various data types such as int, double, string and three other class that i have created that are Rational, Date, and Complex. These objects are stored into Linked Lists of the same type. For int, double, and string i've had to problem storing values that the user enters into a QPlainTextEdit to the lists and displaying them into the QTextBrowser, however, i'm unsure on how to display objects from classes that i've created into the QTextBrowser. Is there a function that can do this?

I'm currently working with my Rational class that takes in objects in the form of "Rational(3,4);" and displays them like fractions such as "3/4".
I've managed to create the objects from user inputs that are in the form "3/4" and push them into the linked list but i have not been able to display them into my QTextBrowser

//sample code
else if(ui->Rational_button->isChecked())
{
    ui->main_display->setText("");

    //Iterator that goes through the linked list to get the objects
    LinkedList<Rational>::Iterator it = rationalvec.begin();

    while(it != nullptr)
    {
       ui->main_display->append(QString::fromStdString(*it));
                                      /* Trying to display all Rational
                                      objects in the QTextBrowser */
       ++it;
    }
}

//There should be an output like the following inside the QTextBrowser

4/5
2/3
7/9
9/11

//These are all Rational type objects

I'm getting a "semantic issue" no viable conversion from 'Rational' to QString/const std::string. I can't seem to find a way to convert or display these objects into the QTextBrowser.

EDIT: Here is the Rational class

class Rational
{
private:
    int numer;  //IN/OUT - the numerator int
    int denom;  //IN/OUT - the denominator int
public:
    /******************************
    ** CONSTRUCTOR & DESTRUCTOR **
    ******************************/
    Rational()         //Constructor
    {
       numer = 0;
       denom = 1;
    }
    Rational(int number)               //Constructor
    {
       numer = number;
       denom = 1;
    }
    Rational(int number1, int number2) //Constructor
    {
      numer = number1;
      denom = number2;
    }

    /***************
    ** ACCESSORS **
    ***************/
    const Rational add(const Rational &) const;
    const Rational subtract(const Rational &) const;
    const Rational multiply(const Rational &) const;
    const Rational divide(const Rational &) const;

    void display() const
    {
       cout << numer << "/" << denom;
    }

    friend ostream& operator<<(ostream &, const Rational &)    //FOR WIDGET
    {
       out << object.numer;
       out << '/';
       out << object.denom;

       return out;
   }

    bool operator <(const Rational& )                          //FOR WIDGET
    {
       if((numer/denom) < (other.numer/other.denom))
           return true;
       else
           return false;
    }
    bool operator >(const Rational& )                          //FOR WIDGET
    {
       if((numer/denom) > (other.numer/other.denom))
           return true;
       else
           return false;
     }

};

Only showing the function definition for the functions i'm using, the other functions whose definitions are not shown are the ones im not gonna use during this program.


问:
How do you get integer values in an NSPoint to display as integer rather than as decimal
How do you get integer values in an NSPoint to display as integer rather than as decimal?

```<code>let temp:NSPoint = NSMakePoint(5,7)

print(temp.x) . // displays 5.0
</code>```

I only want it to display 5, not 5.0

答:
You ask:

How do you get integer values in an NSPoint to display as integer rather than as decimal.

This question may be based upon a false premise. The parameters you supply to NSMakePoint(_:_:) are actually CGFloat (as are the the underlying properties, x and y). So although you supplied integers, but Swift stores them as CGFloat for x and y, regardless.

So, the question is “How do you display the CGFloat properties of a NSPoint without any fractional digits?”

Certainly, as others have suggested, you can create an integer from the CGFloat properties with Int(point.x), etc., but I might suggest that you really might want want to just display these CGFloat without decimal places. There are a bunch of ways of doing this.

Consider:

```<code>let point = NSPoint(x: 5000, y: 7000)
</code>```

You can use NSMakePoint, too, but this is a little more natural in Swift.

Then to display this without decimal places, you have a few options:

In macOS, NSStringFromPoint will generate the full CGPoint without decimal places:

```<code>print(NSStringFromPoint(point))             // "{5000, 7000}"
</code>```

You can use String(format:_:), using a format string that explicitly specifies no decimal places:

```<code>print(String(format: "%.0f", point.x))      // "5000"
</code>```

You can use NumberFormatter and specify the minimumFractionDigits:

```<code>let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.numberStyle = .decimal
print(formatter.string(for: point.x)!)      // "5,000"
</code>```

Needless to say, you can save that formatter and you can use it repeatedly, as needed, if you want to keep your code from getting too verbose.

If you’re just logging this to the console, you can use Unified Logging with import os.log and then do:

```<code>os_log("%.0f", point.x)                      // "5000"
</code>```

Body:
How do you get integer values in an NSPoint to display as integer rather than as decimal?

let temp:NSPoint = NSMakePoint(5,7)

print(temp.x) . // displays 5.0

I only want it to display 5, not 5.0

Body:
You ask:

How do you get integer values in an NSPoint to display as integer rather than as decimal.

This question may be based upon a false premise. The parameters you supply to NSMakePoint(_:_:) are actually CGFloat (as are the the underlying properties, x and y). So although you supplied integers, but Swift stores them as CGFloat for x and y, regardless.

So, the question is “How do you display the CGFloat properties of a NSPoint without any fractional digits?”

Certainly, as others have suggested, you can create an integer from the CGFloat properties with Int(point.x), etc., but I might suggest that you really might want want to just display these CGFloat without decimal places. There are a bunch of ways of doing this.

Consider:

let point = NSPoint(x: 5000, y: 7000)

You can use NSMakePoint, too, but this is a little more natural in Swift.

Then to display this without decimal places, you have a few options:

In macOS, NSStringFromPoint will generate the full CGPoint without decimal places:

print(NSStringFromPoint(point))             // "{5000, 7000}"

You can use String(format:_:), using a format string that explicitly specifies no decimal places:

print(String(format: "%.0f", point.x))      // "5000"

You can use NumberFormatter and specify the minimumFractionDigits:

let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.numberStyle = .decimal
print(formatter.string(for: point.x)!)      // "5,000"

Needless to say, you can save that formatter and you can use it repeatedly, as needed, if you want to keep your code from getting too verbose.

If you’re just logging this to the console, you can use Unified Logging with import os.log and then do:

os_log("%.0f", point.x)                      // "5000"


问:
Fold expressions maximum number of elements in expansion pack
Please consider the following program:

```<code>#include <iostream>
#include <algorithm>

template<typename T, std::size_t N, std::size_t... I>
T sum_impl(T (&a)[N], std::index_sequence<I...>)
{
  return (a[I] + ...);
}

template<typename T, std::size_t N>
T sum(T (&a)[N])
{
  return sum_impl(a, std::make_index_sequence<N>{});
}

int main()
{
    int a[512] = {[0 ... 511] = 1};
    std::cout << "Sum =" << sum(a) << std::endl;
}
</code>```

Demo

In cases as the above, fold expressions are IMHO a good way to unfold what otherwise would have been a for loop. The questions that naturally arise are:

Is there a maximum number of elements in the expansion pack of the fold expression per vendor and how we can get/access this number (e.g., in VC++2017 for some reason the maximum number is 745, otherwise the program doesn't compile)?

Is there a number of elements in the expansion pack of the fold expression that if exceeded the performance is compromised. That is, is there a rule of thumb that if this number is exceeded it would have been better if we have used a for loop?

答:
The specification of a fold expression in the C++ specification begins as follows:

8.1.6 Fold expressions                                                                                [expr.prim.fold]

A fold expression performs a fold of a template parameter pack
  (17.5.3) over a binary operator...

It goes on for a couple of paragraphs. Nothing in them sets the minimum or a maximum size of a fold expression that a C++ compiler must support. This is unspecified, in this section of the C++ standard; so this is entirely up to the individual C++ implementation. There are no specified means for determining a particular compiler's limits. You've discovered that your particular compiler limits the fold expression to 745 values. The reason for that limit obviously has something to do with your compiler's internal implementation details; and without being familiar with them, there's not really much more that can be said about it. Other compilers' limits might be smaller or larger, or be limited only by the amount of available memory.

PS. Regarding the reference to the specification for a template parameter pack, that part of the C++ standard does not specify a minimum/maximum size of a parameter pack that a C++ compiler must support.

EDIT: It's been pointed out that Annex B lists some recommendation, but does not specify them as absolute requirements; and does not explicitly call out the maximum limits of a fold expression.

However, Annex B does call out:

Template arguments in a template declaration [1 024].

One could argue that if this usage of "arguments" incorporates the arguments in a parameter pack, which will indirectly affect fold expressions.

Body:
Please consider the following program:

#include <iostream>
#include <algorithm>

template<typename T, std::size_t N, std::size_t... I>
T sum_impl(T (&a)[N], std::index_sequence)
{
  return (a[I] + ...);
}

template<typename T, std::size_t N>
T sum(T (&a)[N])
{
  return sum_impl(a, std::make_index_sequence<N>{});
}

int main()
{
    int a[512] = {[0 ... 511] = 1};
    std::cout << "Sum =" << sum(a) << std::endl;
}

Demo

In cases as the above, fold expressions are IMHO a good way to unfold what otherwise would have been a for loop. The questions that naturally arise are:

Is there a maximum number of elements in the expansion pack of the fold expression per vendor and how we can get/access this number (e.g., in VC++2017 for some reason the maximum number is 745, otherwise the program doesn't compile)?

Is there a number of elements in the expansion pack of the fold expression that if exceeded the performance is compromised. That is, is there a rule of thumb that if this number is exceeded it would have been better if we have used a for loop?


问:
Aggregate parallel results from different web services in Windows Azure
Webservice1 can receive a set of Lon/Lat variables. Based on these variables it returns a resultset of items nearby.

In order to create the resultset Webservice1 has to pass the variables to multiple webservices of our own and multiple external webservices. All these webservice return a resultset. The combination of these resultsets of these secondary Webservices is the resultset to be returned by Webservice1.

What is the best design approach within Windows Azure with costs and performance in mind?

Should we sequential fire requests from Webservice1 to the other webservices wait for a response and continue? Or can we eg use a queue where we post the variables to be picked up by the secondary webservices?

答:
I think you've answered you're own question in the title.

I wouldn't worry about using a queue.  Queues are great for sending information off to get dealt with by something else when it doesn't matter how long it takes to process.  As you've got a web service that's waiting to return results, this is not ideal.

Sending the requests to each of the other web services one at a time will work and is the easiest option technically, but it won't give you the best performance.

In this situation I would send requests to each of the other web services in parallel using the Task Parallel Library.  Presuming the order of the items that you return isn't important your code might look a bit like this.

```<code>    public List<LocationResult> PlacesOfInterest(LocationParameters parameters)
    {
        WebService[] webServices = GetArrayOfAllWebServices();

        LocationResult[][] results = new LocationResult[webServices.Count()][];

        // Call all of the webservices parallel
        Parallel.For((long)0,
                        webServices.Count(),
                        i =>
                        {
                            results[i] = webServices[i].PlacesOfInterest(parameters);
                        });

        var finalResults = new List<LocationResult>();

// Put all the results together
        for (int i = 0; i < webServices.Count(); i++)
        {
            finalResults.AddRange(results[i]);
        }

        return finalResults;
    }
</code>```

Body:
I think you've answered you're own question in the title.

I wouldn't worry about using a queue.  Queues are great for sending information off to get dealt with by something else when it doesn't matter how long it takes to process.  As you've got a web service that's waiting to return results, this is not ideal.

Sending the requests to each of the other web services one at a time will work and is the easiest option technically, but it won't give you the best performance.

In this situation I would send requests to each of the other web services in parallel using the Task Parallel Library.  Presuming the order of the items that you return isn't important your code might look a bit like this.

    public List<LocationResult> PlacesOfInterest(LocationParameters parameters)
    {
        WebService[] webServices = GetArrayOfAllWebServices();

        LocationResult[][] results = new LocationResult[webServices.Count()][];

        // Call all of the webservices parallel
        Parallel.For((long)0,
                        webServices.Count(),
                        i =>
                        {
                            results[i] = webServices[i].PlacesOfInterest(parameters);
                        });

        var finalResults = new List<LocationResult>();

// Put all the results together
        for (int i = 0; i < webServices.Count(); i++)
        {
            finalResults.AddRange(results[i]);
        }

        return finalResults;
    }