问:
After iOS update, can't get past splashscreen in ionic app
Instead of launching my app, things stall here:

```<code>(lldb)     command script add -f fruitstrap_2e5ac6066864be48322a757c4d0ccdfde52cf356.connect_command connect
(lldb)     command script add -s asynchronous -f fruitstrap_2e5ac6066864be48322a757c4d0ccdfde52cf356.run_command run
(lldb)     command script add -s asynchronous -f fruitstrap_2e5ac6066864be48322a757c4d0ccdfde52cf356.autoexit_command autoexit
    (lldb)     command script add -s asynchronous -f fruitstrap_2e5ac6066864be48322a757c4d0ccdfde52cf356.safequit_command safequit
(lldb)     connect
(lldb)     run
    success
(lldb)     safequit
Process 1762 detached
</code>```

Normally the app loads after the output...but now it is just stuck on the splashscreen. I updated my iOS a few days ago...and haven't developed on it since then (I've been using my browser), but now I am trying to go back to my phone and this is happening - so I think it has something to do with the iOS update. I had this problem once before actually with this app...and it was because this line:

```<code><script src="build/vendor.js"></script>
</code>```

was missing from my index.html but I checked and it is there. Has anyone started having this problem with the update?

Here is my environment info:

```<code>cli packages: (/Users/eamonwhite/ionicmane/myApp/node_modules)

    @ionic/cli-utils  : 1.12.0
    ionic (Ionic CLI) : 3.12.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.0.0
    Cordova Platforms  : android 6.2.3 ios 4.4.0
    Ionic Framework    : ionic-angular 3.7.0

System:

    ios-deploy : 1.9.2
    ios-sim    : 6.1.2
    Node       : v7.7.3
    npm        : 4.1.2
    OS         : macOS High Sierra
    Xcode      : Xcode 9.1 Build version 9B55

Misc:

    backend : legacy
</code>```

答: Make sure WiFi is turned on, on your device :)

Body:
Instead of launching my app, things stall here:

(lldb)     command script add -f fruitstrap_2e5ac6066864be48322a757c4d0ccdfde52cf356.connect_command connect
(lldb)     command script add -s asynchronous -f fruitstrap_2e5ac6066864be48322a757c4d0ccdfde52cf356.run_command run
(lldb)     command script add -s asynchronous -f fruitstrap_2e5ac6066864be48322a757c4d0ccdfde52cf356.autoexit_command autoexit
    (lldb)     command script add -s asynchronous -f fruitstrap_2e5ac6066864be48322a757c4d0ccdfde52cf356.safequit_command safequit
(lldb)     connect
(lldb)     run
    success
(lldb)     safequit
Process 1762 detached

Normally the app loads after the output...but now it is just stuck on the splashscreen. I updated my iOS a few days ago...and haven't developed on it since then (I've been using my browser), but now I am trying to go back to my phone and this is happening - so I think it has something to do with the iOS update. I had this problem once before actually with this app...and it was because this line:

was missing from my index.html but I checked and it is there. Has anyone started having this problem with the update?

Here is my environment info:

cli packages: (/Users/eamonwhite/ionicmane/myApp/node_modules)

    @ionic/cli-utils  : 1.12.0
    ionic (Ionic CLI) : 3.12.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.0.0
    Cordova Platforms  : android 6.2.3 ios 4.4.0
    Ionic Framework    : ionic-angular 3.7.0

System:

    ios-deploy : 1.9.2
    ios-sim    : 6.1.2
    Node       : v7.7.3
    npm        : 4.1.2
    OS         : macOS High Sierra
    Xcode      : Xcode 9.1 Build version 9B55

Misc:

    backend : legacy


来源: stackexchange

问:
PFQuery where pointer exists
I've got 2 tables in my database:

```<code>Posts
    -    content
    -    user (pointer)
Likes
    -    post (pointer)
    -    user (pointer)
</code>```

I'm doing a calculation on how many posts the user has 'Liked' - but the only thing is some posts don't exist because they've been deleted. So what i'm basically trying to do is fetch all 'Likes' where the posts exist too.

My current query is like so:

```<code>PFQuery *query = [PFQuery queryWithClassName:@"Likes"];
[query whereKey:@"user" isEqualTo:self.user];
[query includeKey:@"post"];
[query includeKey:@"post.owner"];
</code>```

答:
You could create a second query targeting the Post class using the -whereKey:matchesKey:inQuery: method:

PFQuery *likesQuery = [PFQuery queryWithClassName:@"Likes"];
[query whereKey:@"user" isEqualTo:self.user];
// don't have to include these since this is a subquery
//[query includeKey:@"post"];
//[query includeKey:@"post.owner"];

PFQuery *postsQuery = [PFQuery queryWithClassName:@"Posts"];
[query whereKey:@"objectId" matchesKey:"post" inQuery:likesQuery];
```

Then postsQuery will be able give you the number of posts that exist and were liked by the user.

ContentLicense: CC BY-SA 3.0

Title: PFQuery where pointer exists

Body:
I've got 2 tables in my database:

Posts
    -    content
    -    user (pointer)
Likes
    -    post (pointer)
    -    user (pointer)

I'm doing a calculation on how many posts the user has 'Liked' - but the only thing is some posts don't exist because they've been deleted. So what i'm basically trying to do is fetch all 'Likes' where the posts exist too.

My current query is like so:

PFQuery *query = [PFQuery queryWithClassName:@"Likes"];
[query whereKey:@"user" isEqualTo:self.user];
[query includeKey:@"post"];
[query includeKey:@"post.owner"];

Body:
You could create a second query targeting the Post class using the -whereKey:matchesKey:inQuery: method:

PFQuery *likesQuery = [PFQuery queryWithClassName:@"Likes"];
[query whereKey:@"user" isEqualTo:self.user];
// don't have to include these since this is a subquery
//[query includeKey:@"post"];
//[query includeKey:@"post.owner"];

PFQuery *postsQuery = [PFQuery queryWithClassName:@"Posts"];
[query whereKey:@"objectId" matchesKey:"post" inQuery:likesQuery];

Then postsQuery will be able give you the number of posts that exist and were liked by the user.


问:
How do I store data from a server when not using redux
I'm new to react-native. I have a journaling app that, to date, has been a web app built in rails.

A user has many journal entries.

When they login to the app, I want to pull all of their previous entries and display it to them. My question is this:

when they login and I pull all of their past entries, where do I store it?

If I store it in local storage on the phone, my concern is that some users have thousands of entries and I'm not sure if that's the appropriate thing to do.

Any thoughts?

答:
Do you really need the data to persist? You can pull the data only each time they need it instead, an effective way of doing this for thousands of records is to implement lazy loading AKA "infinite scrolling". This allows you to pull a defined number of records when they are needed and then load more when the user scrolls beyond the records that are provided initially.

There's an article Implementing an Infinite Scroll In React Native, which walks you through an example of how to do just that


问:
How do I become "test infected" with TDD?
I keep reading about people who are "test infected", meaning that they don't just "get" TDD but also can't live without it.  They've "had the makeover" as it were.  The question is, how do I get like that?</p>

答:
You've already read about TDD; reading more isn't going to excite you.

Instead, you need a genuine personal success story.

Here's how.  Grab some code from a core module, code that doesn't depend on external systems or too many other subroutines.  Doesn't matter how complex or simple the routine is.

Then start writing unit tests against it.  (I'm assuming you have an xUnit or similar for your language.)  Be really obnoxious with the tests -- test every boundary case, test max-int and min-int, test null's, test strings and lists with millions of elements, test strings with Korean and control characters and right-to-left Arabic and quotes and backslashes and periods and other things that tend to break things if not escaped.

What you'll find is.... bugs!  At first you might think these bugs aren't important -- you haven't run into these problems yet, your code probably would never do this, etc. etc..  But my experience is if you keep pushing forward you'll be amazed at the number of little problems.  Eventually it becomes hard to believe that none of these bugs will ever cause a problem.

Plus you get a great feeling of accomplishment with something is done really, really well.  We know code is never perfect and rarely free of bugs, so it's nice when we've exhausted so many tests that we really do feel confident.  Confidence is a nice feeling.

Finally, I think the last event that will trigger the love will happen weeks or months later.  Maybe you're fixing a bug or adding a feature or refactoring some code, and something you do will break a unit test.  "Huh?" you'll say, not understanding why the new change was even relevant to the broken test.  Then you'll find it, and find enlightenment.  Because you really didn't know that you were breaking code, and the tests saved you.

Hallelujah!

OwnerDisplayName: Andrew Harmel-Law

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jason Cohen


问:
Username and Password in C
so basically I want to create a program that asks for an username and a password in order to enter the actual program. I tried doing something like that but when I type the first username and password it doesn't let me go through. On the other hand when I type the second username and password it does work. Can someone explain me why?</p>

```<code>    #include<stdio.h>
    #include<string.h>
    #define MAX 100
    #define LEN 40

    int names(char listName[][LEN]);
    void pass(char listPass[][LEN]);

    int main()
    {
    char name[LEN];
    char password[LEN];
    char listName[MAX][LEN];
    char listPass[MAX][LEN];
    int i;

    names(listName);
    pass(listPass);

    printf("Enter username: ");
    scanf("%s", name);

    printf("Enter password: ");
    scanf("%s", password);

    for(i = 0; i< 2; i++)
    {
        if (strcmp(listName[i], name) == 0 && strcmp(listPass[i], password) == 0)
        {
            printf("Access granted\n");
            break;
        }
        else
        {
            printf("Access denied\n");
            break;
        }
    }

    getch();
    }

    int names(char listName[][LEN])
    {
        int i;
        strcpy(listName[i], "Vince");
        strcpy(listName[i], "Jeremy");
    }

    void pass(char listPass[][LEN])
    {
        int i;
        strcpy(listPass[i], "aBc2xyz8");
        strcpy(listPass[i], "fa7saC12");
    }
</code>```

答:
Compile with warnings enabled and you'd see that the variable i is used uninitialized here:

```<code>int names(char listName[][LEN])
{
    int i;
    strcpy(listName[i], "Vince");
    strcpy(listName[i], "Jeremy");
}

void pass(char listPass[][LEN])
{
    int i;
    strcpy(listPass[i], "aBc2xyz8");
    strcpy(listPass[i], "fa7saC12");
}
</code>```

What you have now is undefined behaviour, i.e. anything can happen. More likely you'd just get a random crash.

You meant strcpy(listName[0], "Vince");, strcpy(listName[1], "Jeremy");

However, what you'd really want to do is to define these variables *out of main, and initialize them there. Also, allow for varying length passwords and usernames by using an array of pointers to char. For example:

```<code>char *listName[MAX] = { "Vince", "Jeremy" };
char *listPass[MAX] = { "aBc2xyz8", "fa7saC12" };

int main(void) { ...
</code>```

Or even better, use a structure for user data:

```<code>struct user_data {
    char *username, *password;
};

struct user_data users[MAX] = {
    { "Vince", "aBc2xyz8" },
    { "Jeremy", "fa7saC12" }
};
</code>```

Title: Username and Password in C

Body:
so basically I want to create a program that asks for an username and a password in order to enter the actual program. I tried doing something like that but when I type the first username and password it doesn't let me go through. On the other hand when I type the second username and password it does work. Can someone explain me why?

    #include<stdio.h>
    #include<string.h>
    #define MAX 100
    #define LEN 40

    int names(char listName[][LEN]);
    void pass(char listPass[][LEN]);

    int main()
    {
    char name[LEN];
    char password[LEN];
    char listName[MAX][LEN];
    char listPass[MAX][LEN];
    int i;

    names(listName);
    pass(listPass);

    printf("Enter username: ");
    scanf("%s", name);

    printf("Enter password: ");
    scanf("%s", password);

    for(i = 0; i< 2; i++)
    {
        if (strcmp(listName[i], name) == 0 && strcmp(listPass[i], password) == 0)
        {
            printf("Access granted\n");
            break;
        }
        else
        {
            printf("Access denied\n");
            break;
        }
    }

    getch();
    }

    int names(char listName[][LEN])
    {
        int i;
        strcpy(listName[i], "Vince");
        strcpy(listName[i], "Jeremy");
    }

    void pass(char listPass[][LEN])
    {
        int i;
        strcpy(listPass[i], "aBc2xyz8");
        strcpy(listPass[i], "fa7saC12");
    }

Body:
Compile with warnings enabled and you'd see that the variable i is used uninitialized here:

int names(char listName[][LEN])
{
    int i;
    strcpy(listName[i], "Vince");
    strcpy(listName[i], "Jeremy");
}

void pass(char listPass[][LEN])
{
    int i;
    strcpy(listPass[i], "aBc2xyz8");
    strcpy(listPass[i], "fa7saC12");
}

What you have now is undefined behaviour, i.e. anything can happen. More likely you'd just get a random crash.

You meant strcpy(listName[0], "Vince");, strcpy(listName[1], "Jeremy");

However, what you'd really want to do is to define these variables *out of main, and initialize them there. Also, allow for varying length passwords and usernames by using an array of pointers to char. For example:

char *listName[MAX] = { "Vince", "Jeremy" };
char *listPass[MAX] = { "aBc2xyz8", "fa7saC12" };

int main(void) { ...

Or even better, use a structure for user data:

struct user_data {
    char *username, *password;
};

struct user_data users[MAX] = {
    { "Vince", "aBc2xyz8" },
    { "Jeremy", "fa7saC12" }
};


问:
ERROR: No suitable driver found for jdbc:oracle:thin:@localhost:1521:xe
This is my first trial application in Hibernate
I am getting following error

ERROR: No suitable driver found for jdbc:oracle:thin:@localhost:1521:xe
  Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Could not open connection
      at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
      at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
      at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
      at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
      at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
      at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
      at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
      at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
      at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1363)
      at com.model.HibernetTest.main(HibernetTest.java:24)
  Caused by: java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:@localhost:1521:xe
      at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:703)
      at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:190)
      at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:192)
      at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:278)
      at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
      ... 5 more

Here is my hibernate.cfg.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

<session-factory>
    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
    <property name="hibernate.connection.username">sample</property>
    <property name="hinernate.connection.password">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>

    <property name="show_sql">true</property>

    <mapping class="com.model.Student" resource="com/model/Student.hbm.xml" />
</session-factory>
</code>```

I have added odbc jar in my classpath but still I am getting error saying Driver not found. I tried following JDBC connection class and it works great.

```<code>public class OracleJDBCExample {

public static void main(String[] args) {

    try {

        Class.forName("oracle.jdbc.driver.OracleDriver");

    } catch (ClassNotFoundException e) {

        System.out.println("Where is your Oracle JDBC Driver?");
        e.printStackTrace();
        return;

    }

    System.out.println("Oracle JDBC Driver Registered!");

    Connection connection = null;

    try {

        connection = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe", "sample", "root");

        PreparedStatement ps=connection.prepareStatement("select * from Employee");
        System.out.println("*******");
        ResultSet rs=ps.executeQuery();
        System.out.println("--->"+rs.toString());
        if(rs.next()) {
            System.out.println("---> "+rs.getString(1));
        }
        rs.close();
        ps.close();

    } catch (SQLException e) {

        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;

    }

    if (connection != null) {
        System.out.println("You made it, take control your database now!");
    } else {
        System.out.println("Failed to make connection!");
    }

}
</code>```

}

Please help me understand what is wrong with the code?

答: As looks by code is nothing wrong but your odbc.jar is not found in your application server as i think. Can you tell which server you are using?

Body:
This is my first trial application in Hibernate
I am getting following error

ERROR: No suitable driver found for jdbc:oracle:thin:@localhost:1521:xe
  Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Could not open connection
      at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
      at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
      at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
      at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
      at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
      at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
      at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
      at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
      at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1363)
      at com.model.HibernetTest.main(HibernetTest.java:24)
  Caused by: java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:@localhost:1521:xe
      at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:703)
      at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:190)
      at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:192)
      at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:278)
      at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
      ... 5 more

Here is my hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

<session-factory>
    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
    <property name="hibernate.connection.username">sample</property>
    <property name="hinernate.connection.password">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>

    <property name="show_sql">true</property>

    <mapping class="com.model.Student" resource="com/model/Student.hbm.xml" />
</session-factory>

I have added odbc jar in my classpath but still I am getting error saying Driver not found. I tried following JDBC connection class and it works great.

public class OracleJDBCExample {

public static void main(String[] args) {

    try {

        Class.forName("oracle.jdbc.driver.OracleDriver");

    } catch (ClassNotFoundException e) {

        System.out.println("Where is your Oracle JDBC Driver?");
        e.printStackTrace();
        return;

    }

    System.out.println("Oracle JDBC Driver Registered!");

    Connection connection = null;

    try {

        connection = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe", "sample", "root");

        PreparedStatement ps=connection.prepareStatement("select * from Employee");
        System.out.println("*******");
        ResultSet rs=ps.executeQuery();
        System.out.println("--->"+rs.toString());
        if(rs.next()) {
            System.out.println("---> "+rs.getString(1));
        }
        rs.close();
        ps.close();

    } catch (SQLException e) {

        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;

    }

    if (connection != null) {
        System.out.println("You made it, take control your database now!");
    } else {
        System.out.println("Failed to make connection!");
    }

}

}

Please help me understand what is wrong with the code?


问:
Cannot disable submit button by $invalid while page load
I am trying to invalidate and disable the submit button on the load of the page, as not entering text into textbox is invalid, but my code is not working, can someone please provide the solution.

```<code><div id="reg_bground">
    <div id="formdiv" ng-app="myApp" ng-controller="valCtrl">
        <form name="myForm" novalidate>
            <div style="font-family:calibri; font-size:30px; font-weight:bolder;">
                <span>Register:</span>
            </div>
            <div>
                <span>Name:</span><br>
                <input type="text" name="user" ng-model="user" required><br>
                <p ng-show="myForm.user.$dirty && myForm.user.$invalid">*Please insert the name</p>
            </div>
            <input type="number">
            <input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid">
        </form>
    </div>
</div>
</code>```

答:
Delete the dirty check in the submit button: </p>

```<code><input type="submit" ng-disabled=" ̶m̶y̶F̶o̶r̶m̶.̶u̶s̶e̶r̶.̶$̶d̶i̶r̶t̶y̶ ̶&̶&̶ ̶ myForm.user.$invalid">
</code>```

Body:
I am trying to invalidate and disable the submit button on the load of the page, as not entering text into textbox is invalid, but my code is not working, can someone please provide the solution.

        <form name="myForm" novalidate>

                Register:

                Name:

                <input type="text" name="user" ng-model="user" required>

*Please insert the name

            <input type="number">
            <input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid">
        </form>

Body:
Delete the dirty check in the submit button:

<input type="submit" ng-disabled=" ̶m̶y̶F̶o̶r̶m̶.̶u̶s̶e̶r̶.̶$̶d̶i̶r̶t̶y̶ ̶&̶&̶ ̶ myForm.user.$invalid">


问:
How to only restore variables in the checkpoint in Tensorflow?
In Tensorflow, my model is based on a pre-trained model, and I added a few more variables and remove some in the pre-trained model. When I restore the variables from the checkpoint file, I have to explicitly specify all variables I added to the graph that need to be excluded. For example, I did

```<code>exclude = # explicitly list all variables to exclude
variables_to_restore = slim.get_variables_to_restore(exclude=exclude)
saver = tf.train.Saver(variables_to_restore)
</code>```

Is there a simpler way to do this? Namely, as long as a variable is not in checkpoint, then don't try to restore.

答:
The only thing that you can do is firstly having the same model as in the checkpoint, secondly restoring the checkpoint values to the same model. After restoring the variables for the same model, you can add new layers, delete existing layers or change the weights of the layers.

But there is an important point that you need to be careful. After added new layers you need to initialize them. If you use tf.global_variables_initializer(), you will lose the values of reloaded layers. So you should only initialize the uninitialized weights, you can use following function for this.

```<code>def initialize_uninitialized(sess):
    global_vars = tf.global_variables()
    is_not_initialized = sess.run([tf.is_variable_initialized(var) for var in global_vars])
    not_initialized_vars = [v for (v, f) in zip(global_vars, is_not_initialized) if not f]

    # for i in not_initialized_vars: # only for testing
    #    print(i.name)

    if len(not_initialized_vars):
        sess.run(tf.variables_initializer(not_initialized_vars))
</code>```

Body:
In Tensorflow, my model is based on a pre-trained model, and I added a few more variables and remove some in the pre-trained model. When I restore the variables from the checkpoint file, I have to explicitly specify all variables I added to the graph that need to be excluded. For example, I did

exclude = # explicitly list all variables to exclude
variables_to_restore = slim.get_variables_to_restore(exclude=exclude)
saver = tf.train.Saver(variables_to_restore)

Is there a simpler way to do this? Namely, as long as a variable is not in checkpoint, then don't try to restore.

Body:
The only thing that you can do is firstly having the same model as in the checkpoint, secondly restoring the checkpoint values to the same model. After restoring the variables for the same model, you can add new layers, delete existing layers or change the weights of the layers.

But there is an important point that you need to be careful. After added new layers you need to initialize them. If you use tf.global_variables_initializer(), you will lose the values of reloaded layers. So you should only initialize the uninitialized weights, you can use following function for this.

def initialize_uninitialized(sess):
    global_vars = tf.global_variables()
    is_not_initialized = sess.run([tf.is_variable_initialized(var) for var in global_vars])
    not_initialized_vars = [v for (v, f) in zip(global_vars, is_not_initialized) if not f]

    # for i in not_initialized_vars: # only for testing
    #    print(i.name)

    if len(not_initialized_vars):
        sess.run(tf.variables_initializer(not_initialized_vars))


问:
Providing lower bound for the support in apriori Algorithm
Suppose in a market basket scenario, the following association rules are detected with a support of at least 15% and a confidence of at least 60%:

{A, B} → {C}
{B, C} → {D}

How accurately can you present a lower bound for the support of the itemset {A, B, C, D}?

Can anyone help me understand what is the lower bound I am looking here at in the apriori algorithm ?

答:
Break this down into two steps. What is the minimum support of ABC?

Then, what is the minimum support of ABCD?


答: In names() and pass() you use i uninitialized, both strcpy operations are going to copy to the same array index.</p>

Title: Username and Password in C


问:
Angular *ngFor not populating any data
```<code>export class AppComponent {
  pickBtnClicked = false;
  selectedPickNumber: 'string';
  selectedRegion: 'string';
  currentPickSelection: any[];
  channelList: any[];

  constructor(private pickGroupService: PickGroupService, private channelsService: ChannelsService) {}

  onPkClick(btnPicked) {
    this.pickBtnClicked = true;
    this.selectedPickNumber = btnPicked;
  }
  onRegionClick(regionPicked) {
    this.selectedRegion = regionPicked;
    this.currentPickSelection = this.pickGroupService.getPickSet(this.selectedPickNumber, this.selectedRegion);
    console.log(this.currentPickSelection);
  }
}
</code>```

The console.log prints out this data to the browser console

But the ngFor in the below doesn't pick up any data from the "currentPickSelection" array.

```<code><ul class="w3-ul w3-card-4" align="right" >
          <li class="list-group-item" *ngFor="let channels of currentPickSelection">
            <strong><font size="2">{{ channels.channel }}</font><span class="w3-right"><font size="2">{{ channels.pickCode }}</font></span></strong>
          </li>
        </ul>
</code>```

Please advise! thanks

答:
You need to use nested ngFor since your channels is again an array</p>

```<code>  <ul *ngFor="let channels of currentPickSelection">
        <li *ngFor="let channel of channels">
              <strong><font size="2">{{ channel.channel }}</font><span class="w3-right"><font size="2">{{ channel.pickCode }}</font></span></strong>
        </li>
  </ul>
</code>```

Title: Angular *ngFor not populating any data

Body:
export class AppComponent {
  pickBtnClicked = false;
  selectedPickNumber: 'string';
  selectedRegion: 'string';
  currentPickSelection: any[];
  channelList: any[];

  constructor(private pickGroupService: PickGroupService, private channelsService: ChannelsService) {}

  onPkClick(btnPicked) {
    this.pickBtnClicked = true;
    this.selectedPickNumber = btnPicked;
  }
  onRegionClick(regionPicked) {
    this.selectedRegion = regionPicked;
    this.currentPickSelection = this.pickGroupService.getPickSet(this.selectedPickNumber, this.selectedRegion);
    console.log(this.currentPickSelection);
  }
}

The console.log prints out this data to the browser console

But the ngFor in the below doesn't pick up any data from the "currentPickSelection" array.

            {{ channels.channel }}{{ channels.pickCode }}

Please advise! thanks

Body:
You need to use nested ngFor since your channels is again an array

  <ul *ngFor="let channels of currentPickSelection">
        <li *ngFor="let channel of channels">
              <strong><font size="2">{{ channel.channel }}</font><span class="w3-right"><font size="2">{{ channel.pickCode }}</font></span></strong>
        </li>
  </ul>


问:
How to convert a numpy array of tensors to a tensor?
I have a numpy array list something like the follows:

```<code>a=np.array([tf.convert_to_tensor(1),tf.convert_to_tensor(2)])
</code>```

I want to convert this list into a tensor.
My real list is not like the constant example but some complex tensor, so does anyone know how to do this?

答:
I assume all of the tensors have the same shape. Then you can just call tf.stack:

>>> print(tf.stack([tf.convert_to_tensor(1), tf.convert_to_tensor(2)]))
Tensor("stack:0", shape=(2,), dtype=int32)
```

Note that it accepts the list, not numpy array.

Body:
I have a numpy array list something like the follows:

a=np.array([tf.convert_to_tensor(1),tf.convert_to_tensor(2)])

I want to convert this list into a tensor.
My real list is not like the constant example but some complex tensor, so does anyone know how to do this?

Body:
I assume all of the tensors have the same shape. Then you can just call tf.stack:

>>> print(tf.stack([tf.convert_to_tensor(1), tf.convert_to_tensor(2)]))
Tensor("stack:0", shape=(2,), dtype=int32)

Note that it accepts the list, not numpy array.


答:
Following code is not what you intended:

```<code>int names(char listName[][LEN])
{
     int i;
     strcpy(listName[i], "Vince");
     strcpy(listName[i], "Jeremy");
}

void pass(char listPass[][LEN])
{
    int i;
    strcpy(listPass[i], "aBc2xyz8");
    strcpy(listPass[i], "fa7saC12");
}
</code>```

You should initialize i and increment it between the statements, or simply use:

```<code>int names(char listName[][LEN])
{
    strcpy(listName[0], "Vince");
    strcpy(listName[1], "Jeremy");
}

void pass(char listPass[][LEN])
{
    strcpy(listPass[0], "aBc2xyz8");
    strcpy(listPass[1], "fa7saC12");
}
</code>```

Title: Username and Password in C

Body:
Following code is not what you intended:

int names(char listName[][LEN])
{
     int i;
     strcpy(listName[i], "Vince");
     strcpy(listName[i], "Jeremy");
}

void pass(char listPass[][LEN])
{
    int i;
    strcpy(listPass[i], "aBc2xyz8");
    strcpy(listPass[i], "fa7saC12");
}

You should initialize i and increment it between the statements, or simply use:

int names(char listName[][LEN])
{
    strcpy(listName[0], "Vince");
    strcpy(listName[1], "Jeremy");
}

void pass(char listPass[][LEN])
{
    strcpy(listPass[0], "aBc2xyz8");
    strcpy(listPass[1], "fa7saC12");
}


问:
Address sanitizing Boost.Python modules
My project includes a large C++ library and Python bindings (via Boost.Python).  The test suite is mostly written on top of the Python bindings, and I would like to run it with sanitizers, starting with ASAN.

I'm running macOS (10.13.1 FWIW, but I had the problem with previous versions too), and I can't seem to find a way to run ASAN on Python modules (I very much doubt this is related to Boost.Python, I suppose it's the same with other techniques).

Here is a simple Python module:

```<code>// hello_ext.cc
#include <boost/python.hpp>

char const* greet()
{
  auto* res = new char[100];
  std::strcpy(res, "Hello, world!");
  delete [] res;
  return res;
}

BOOST_PYTHON_MODULE(hello_ext)
{
  using namespace boost::python;
  def("greet", greet);
}
</code>```

here is the Makefile I used, made for MacPorts:

```<code>// Makefile
CXX = clang++-mp-4.0
CXXFLAGS = -g -std=c++14 -fsanitize=address -fno-omit-frame-pointer
CPPFLAGS = -isystem/opt/local/include $$($(PYTHON_CONFIG) --includes)
LDFLAGS = -L/opt/local/lib
PYTHON = python3.5
PYTHON_CONFIG = python3.5-config
LIBS = -lboost_python3-mt $$($(PYTHON_CONFIG) --ldflags)

all: hello_ext.so

hello_ext.so: hello_ext.cc
        $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) -shared -o $@ $< $(LIBS)

check: all
        $(ENV) $(PYTHON) -c 'import hello_ext; print(hello_ext.greet())'

clean:
        -rm -f hello_ext.so
</code>```

Without asan, everything works well (well, too well actually...).  But with ASAN, I hit LD_PRELOAD like issues:

```<code>$ make check
python -c 'import hello_ext; print(hello_ext.greet())'
==19013==ERROR: Interceptors are not working. This may be because AddressSanitizer is loaded too late (e.g. via dlopen). Please launch the executable with:
DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
"interceptors not installed" && 0make: *** [check] Abort trap: 6
</code>```

Okay, let's do that: define DYLD_INSERT_LIBRARIES

```<code>$ DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib \
  python -c 'import hello_ext; print(hello_ext.greet())'
==19023==ERROR: Interceptors are not working. This may be because AddressSanitizer is loaded too late (e.g. via dlopen). Please launch the executable with:
DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
"interceptors not installed" && 0zsh: abort      DYLD_INSERT_LIBRARIES= python -c 'import hello_ext; print(hello_ext.greet())'
</code>```

Let's be suspicious about SIP, so I have disabled SIP here, and let's resolve the symlinks:

```<code>$ DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib \
  /opt/local/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 -c 'import hello_ext; print(hello_ext.greet())'
==19026==ERROR: Interceptors are not working. This may be because AddressSanitizer is loaded too late (e.g. via dlopen). Please launch the executable with:
DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
"interceptors not installed" && 0zsh: abort      DYLD_INSERT_LIBRARIES=  -c 'import hello_ext; print(hello_ext.greet())'
</code>```

What's the right way to do that?  I have also tried to load libasan with ctypes.PyDLL, and even with sys.setdlopenflags(os.RTLD_NOW | os.RTLD_GLOBAL) I can't get this to work.

答:
This may be a less than ideal answer, but it should provide you with what you need.

I'm proposing you make an Xcode project to build everything (yes, I know you want to use make, that comes later)

Assuming you already know how to get a Xcode project building everything I'll skip ahead to enabling Address Sanitizer:

Product -> Scheme -> Edit Scheme will open this window:

Check the boxes for Address Sanitizer. You should only have to do this for your main Application. In my experience all the dependancies will be built appropriately.

Next Build the main application target. We will need to examine the compiler and linker invocations so we can copy any necessary flags/steps to the make files.

I've circled the 2 relevant buttons to get the output. The rightmost button will expand the compiler invocation used to build.

This shot shows both a save button (it may be easier to examine in another program) and some of the relevant flags used for building. You will have to examine the output for all targets (dependancies) to get a clear picture.

Hope this helps. FWIW the project in my example has a custom Python module written in C++ (directly using libPython, not Boost) so I know you can use Asan on those even using the System supplied Python frameworks.

Title: Address sanitizing Boost.Python modules

Body:
My project includes a large C++ library and Python bindings (via Boost.Python).  The test suite is mostly written on top of the Python bindings, and I would like to run it with sanitizers, starting with ASAN.

I'm running macOS (10.13.1 FWIW, but I had the problem with previous versions too), and I can't seem to find a way to run ASAN on Python modules (I very much doubt this is related to Boost.Python, I suppose it's the same with other techniques).

Here is a simple Python module:

// hello_ext.cc
#include <boost/python.hpp>

char const* greet()
{
  auto* res = new char[100];
  std::strcpy(res, "Hello, world!");
  delete [] res;
  return res;
}

BOOST_PYTHON_MODULE(hello_ext)
{
  using namespace boost::python;
  def("greet", greet);
}

here is the Makefile I used, made for MacPorts:

// Makefile
CXX = clang++-mp-4.0
CXXFLAGS = -g -std=c++14 -fsanitize=address -fno-omit-frame-pointer
CPPFLAGS = -isystem/opt/local/include $$($(PYTHON_CONFIG) --includes)
LDFLAGS = -L/opt/local/lib
PYTHON = python3.5
PYTHON_CONFIG = python3.5-config
LIBS = -lboost_python3-mt $$($(PYTHON_CONFIG) --ldflags)

all: hello_ext.so

hello_ext.so: hello_ext.cc
        $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) -shared -o $@ $< $(LIBS)

check: all
        $(ENV) $(PYTHON) -c 'import hello_ext; print(hello_ext.greet())'

clean:
        -rm -f hello_ext.so

Without asan, everything works well (well, too well actually...).  But with ASAN, I hit LD_PRELOAD like issues:

$ make check
python -c 'import hello_ext; print(hello_ext.greet())'
==19013==ERROR: Interceptors are not working. This may be because AddressSanitizer is loaded too late (e.g. via dlopen). Please launch the executable with:
DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
"interceptors not installed" && 0make: *** [check] Abort trap: 6

Okay, let's do that: define DYLD_INSERT_LIBRARIES

$ DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib \
  python -c 'import hello_ext; print(hello_ext.greet())'
==19023==ERROR: Interceptors are not working. This may be because AddressSanitizer is loaded too late (e.g. via dlopen). Please launch the executable with:
DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
"interceptors not installed" && 0zsh: abort      DYLD_INSERT_LIBRARIES= python -c 'import hello_ext; print(hello_ext.greet())'

Let's be suspicious about SIP, so I have disabled SIP here, and let's resolve the symlinks:

$ DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib \
  /opt/local/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 -c 'import hello_ext; print(hello_ext.greet())'
==19026==ERROR: Interceptors are not working. This may be because AddressSanitizer is loaded too late (e.g. via dlopen). Please launch the executable with:
DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
"interceptors not installed" && 0zsh: abort      DYLD_INSERT_LIBRARIES=  -c 'import hello_ext; print(hello_ext.greet())'

What's the right way to do that?  I have also tried to load libasan with ctypes.PyDLL, and even with sys.setdlopenflags(os.RTLD_NOW | os.RTLD_GLOBAL) I can't get this to work.


问:
Use of await in Razor views
Is it possible to await on tasks in Razor .cshtml views?

By default it complains that it can only be used in methods marked with async so I'm wondering if maybe there is a hidden switch somewhere that enables it?

答:
I've wanted something like this for a long time - a lot of the pages we write could be thrown together by a Jr Dev if they didn't have to write a bunch of queries; and, it's the same basic query boilerplate every time anyway - why should they have to write them for each Controller, when the majority of their work is to get content up? I use C# so I don't have to deal with memory management, why should an HTML coder have to deal with query details?

There is a trick you can use to sort of implicitly load data async into the View. First, you define a class that expresses what data you want. Then, at the top of each View, instantiate that class. Back in the Controller, you can lookup the View you know you're going to use, open it, then compile that class. You can then use it to go get the data the View will need, async, in the Controller the way MVC enforces. Finally, pass it off with a ViewModel to the View as MVC prescribes, and, through some trickery - you have a View that declares what data it's going to use.

Here's a StoryController. Jr Devs write stories as simple .cshtml files without having to know what a Controller, database or LINQ is:

```<code>public class StoryController : BaseController
{
    [OutputCache(Duration=CacheDuration.Days1)]
    // /story/(id)
    public async Task<ActionResult> Id(string id = null)
    {
        string storyFilename = id;

        // Get the View - story file
        if (storyFilename == null || storyFilename.Contains('.'))
            return Redirect("/");   // Disallow ../ for example

        string path = App.O.AppRoot + App.HomeViews + @"story\" + storyFilename + ".cshtml";
        if (!System.IO.File.Exists(path))
            return Redirect("/");

        return View(storyFilename);
</code>```

All this does for now is go get the View file based on the URL, allowing something like WebForms (except inside MVC and using Razor). But we want to show some data - in our case, people and projects that accumulate in the database - with some standard ViewModels and Partials. Let's define how and compile that out. (Note that ConservX happens to be the core Project namespace in my case.)

```<code>    public async Task<ActionResult> Id(string id = null)
    {
        string storyFilename = id;

        // 1) Get the View - story file
        if (storyFilename == null || storyFilename.Contains('.'))
            return Redirect("/");   // Disallow ../ for example

        string path = App.O.AppRoot + App.HomeViews + @"story\" + storyFilename + ".cshtml";
        if (!System.IO.File.Exists(path))
            return Redirect("/");

        // 2) It exists - begin parsing it for StoryDataIds
        var lines = await FileHelper.ReadLinesUntilAsync(path, line => line.Contains("@section"));

        // 3) Is there a line that says "new StoryDataIds"?
        int i = 0;
        int l = lines.Count;
        for (; i < l && !lines[i].Contains("var dataIds = new StoryDataIds"); i++)
        {}

        if (i == l) // No StoryDataIds defined, just pass an empty StoryViewModel
            return View(storyFilename, new StoryViewModel());

        // https://stackoverflow.com/questions/1361965/compile-simple-string
        // https://msdn.microsoft.com/en-us/library/system.codedom.codecompileunit.aspx
        // https://msdn.microsoft.com/en-us/library/system.codedom.compiler.codedomprovider(v=vs.110).aspx
        string className = "__StoryData_" + storyFilename;
        string code = String.Join(" ",
            (new[] {
                "using ConservX.Areas.Home.ViewModels.Storying;",
                "public class " + className + " { public static StoryDataIds Get() {"
            }).Concat(
                lines.Skip(i).TakeWhile(line => !line.Contains("};"))
            ).Concat(
                new[] { "}; return dataIds; } }" }
            ));

        var refs = AppDomain.CurrentDomain.GetAssemblies();
        var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
        var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
        var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
        compileParams.GenerateInMemory = true;
        compileParams.GenerateExecutable = false;

        var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
        var asm = compilerResult.CompiledAssembly;
        var tempType = asm.GetType(className);
        var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);

        using (var db... // Fetch the relevant data here

        var vm = new StoryViewModel();
        return View(storyFilename, vm);
    }
</code>```

That's the majority of the work. Now Jr Devs can just declare the data they need like so:

```<code>@using ConservX.Areas.Home.ViewModels.Storying
@model StoryViewModel
@{
    var dataIds = new StoryDataIds
    {
        ProjectIds = new[] { 4 }
    };

    string title = "Story Title";
    ViewBag.Title = title;
    Layout = "~/Areas/Home/Views/Shared/_Main.cshtml";
}
@section css {
...
</code>```

Title: Use of await in Razor views

Body:
I've wanted something like this for a long time - a lot of the pages we write could be thrown together by a Jr Dev if they didn't have to write a bunch of queries; and, it's the same basic query boilerplate every time anyway - why should they have to write them for each Controller, when the majority of their work is to get content up? I use C# so I don't have to deal with memory management, why should an HTML coder have to deal with query details?

There is a trick you can use to sort of implicitly load data async into the View. First, you define a class that expresses what data you want. Then, at the top of each View, instantiate that class. Back in the Controller, you can lookup the View you know you're going to use, open it, then compile that class. You can then use it to go get the data the View will need, async, in the Controller the way MVC enforces. Finally, pass it off with a ViewModel to the View as MVC prescribes, and, through some trickery - you have a View that declares what data it's going to use.

Here's a StoryController. Jr Devs write stories as simple .cshtml files without having to know what a Controller, database or LINQ is:

public class StoryController : BaseController
{
    [OutputCache(Duration=CacheDuration.Days1)]
    // /story/(id)
    public async Task<ActionResult> Id(string id = null)
    {
        string storyFilename = id;

        // Get the View - story file
        if (storyFilename == null || storyFilename.Contains('.'))
            return Redirect("/");   // Disallow ../ for example

        string path = App.O.AppRoot + App.HomeViews + @"story\" + storyFilename + ".cshtml";
        if (!System.IO.File.Exists(path))
            return Redirect("/");

        return View(storyFilename);

All this does for now is go get the View file based on the URL, allowing something like WebForms (except inside MVC and using Razor). But we want to show some data - in our case, people and projects that accumulate in the database - with some standard ViewModels and Partials. Let's define how and compile that out. (Note that ConservX happens to be the core Project namespace in my case.)

    public async Task<ActionResult> Id(string id = null)
    {
        string storyFilename = id;

        // 1) Get the View - story file
        if (storyFilename == null || storyFilename.Contains('.'))
            return Redirect("/");   // Disallow ../ for example

        string path = App.O.AppRoot + App.HomeViews + @"story\" + storyFilename + ".cshtml";
        if (!System.IO.File.Exists(path))
            return Redirect("/");

        // 2) It exists - begin parsing it for StoryDataIds
        var lines = await FileHelper.ReadLinesUntilAsync(path, line => line.Contains("@section"));

        // 3) Is there a line that says "new StoryDataIds"?
        int i = 0;
        int l = lines.Count;
        for (; i < l && !lines[i].Contains("var dataIds = new StoryDataIds"); i++)
        {}

        if (i == l) // No StoryDataIds defined, just pass an empty StoryViewModel
            return View(storyFilename, new StoryViewModel());

        // https://stackoverflow.com/questions/1361965/compile-simple-string
        // https://msdn.microsoft.com/en-us/library/system.codedom.codecompileunit.aspx
        // https://msdn.microsoft.com/en-us/library/system.codedom.compiler.codedomprovider(v=vs.110).aspx
        string className = "__StoryData_" + storyFilename;
        string code = String.Join(" ",
            (new[] {
                "using ConservX.Areas.Home.ViewModels.Storying;",
                "public class " + className + " { public static StoryDataIds Get() {"
            }).Concat(
                lines.Skip(i).TakeWhile(line => !line.Contains("};"))
            ).Concat(
                new[] { "}; return dataIds; } }" }
            ));

        var refs = AppDomain.CurrentDomain.GetAssemblies();
        var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
        var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
        var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
        compileParams.GenerateInMemory = true;
        compileParams.GenerateExecutable = false;

        var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
        var asm = compilerResult.CompiledAssembly;
        var tempType = asm.GetType(className);
        var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);

        using (var db... // Fetch the relevant data here

        var vm = new StoryViewModel();
        return View(storyFilename, vm);
    }

That's the majority of the work. Now Jr Devs can just declare the data they need like so:

@using ConservX.Areas.Home.ViewModels.Storying
@model StoryViewModel
@{
    var dataIds = new StoryDataIds
    {
        ProjectIds = new[] { 4 }
    };

    string title = "Story Title";
    ViewBag.Title = title;
    Layout = "~/Areas/Home/Views/Shared/_Main.cshtml";
}
@section css {
...


问:
time.sleep function within while loop keeps crashing program, solution or alternative method?
I am trying to make a space invaders game using turtle, and in order to move the bullet up the screen I am trying to update the y coordinate of the bullet every 0.5 seconds. I tried to do this with a while loop and the time.sleep() function, but everytime I try to fire a bullet, the program crashes. Is there any way I can stop it from doing this? Or why is it not working? Is there an equally effective method that will not crash my program? </p>

```<code>import turtle
import time

userx = 0

x = 0
y = -300

enemies = [(300,50, "left"), (400,50, "left"), (350, -50, "right")]

bullets = []

gameover = False

def frame():
    pass
    ship = turtle.Turtle()
    ship.pu()
    ship.ht()
    ship.setpos(userx, -300)
    ship.pd()
    ship.circle(5)

    bullet = turtle.Turtle()
    bullet.pu()
    bullet.ht()
    bullet.setpos(x, y)
    bullet.pd()
    bullet.circle(2)

def key_left():
    global userx
    pass
    userx += -10
    print(userx)

def key_right():
    global userx
    pass
    userx += 10
    print(userx)

def key_space():
    pass # your code here
    global x
    global y
    global bullets
    x = userx
    while y <= 300:
        time.sleep(0.5)
        y += 4
    else: y = 0
    bullets += (x,y)

def physics():
    global bullets
    global enemies
    pass

def ai():
    global enemies
    global gameover
    pass

def reset():
    global enemies
    global bullets
    global userx
    global gameover
    pass

def main():
    turtle.tracer(0,0)
    turtle.hideturtle()
    turtle.onkey(key_left, "Left")
    turtle.onkey(key_right, "Right")
    turtle.onkey(key_space, "space")
    turtle.listen()
    reset()
    while not gameover:
        turtle.clear()
        physics()
        ai()
        frame()
        turtle.update()
        time.sleep(0.05)

main()
</code>```

答:
It is not ideal but it starts working.

In key_space you only add new bullet to list.

In while not gameover you run function which will move all bullets.

In frame you draw all bullets.

```<code>import turtle
import time

userx = 0

x = 0
y = -300

enemies = [(300,50, "left"), (400,50, "left"), (350, -50, "right")]

bullets = []

gameover = False

def frame():
    pass
    ship = turtle.Turtle()
    ship.pu()
    ship.ht()
    ship.setpos(userx, -300)
    ship.pd()
    ship.circle(5)

    # redraw bullets
    for x, y in bullets:
        bullet = turtle.Turtle()
        bullet.pu()
        bullet.ht()
        bullet.setpos(x, y)
        bullet.pd()
        bullet.circle(2)

def key_left():
    global userx
    pass
    userx += -10
    print(userx)

def key_right():
    global userx
    pass
    userx += 10
    print(userx)

def key_space():
    pass # your code here
    global x
    global y
    global bullets
    x = userx

    # add bullet to list
    bullets.append([x, -300])

def move_bullets():
    global bullets

    live_bullets = []

    # move every bullet and check if should still live
    for x, y in bullets:
        y += 4

        # keep only some bullets and other forget (kill/remove)
        if y <= 300:
            live_bullets.append([x, y])

    bullets = live_bullets

def physics():
    global bullets
    global enemies
    pass

def ai():
    global enemies
    global gameover
    pass

def reset():
    global enemies
    global bullets
    global userx
    global gameover
    pass

def main():
    turtle.tracer(0,0)
    turtle.hideturtle()
    turtle.onkey(key_left, "Left")
    turtle.onkey(key_right, "Right")
    turtle.onkey(key_space, "space")
    turtle.listen()
    reset()
    while not gameover:
        turtle.clear()
        physics()
        ai()
        move_bullets() # <--  move bullets (or maybe before physics)
        frame()
        turtle.update()
        time.sleep(0.05)

main()
</code>```

Body:
I am trying to make a space invaders game using turtle, and in order to move the bullet up the screen I am trying to update the y coordinate of the bullet every 0.5 seconds. I tried to do this with a while loop and the time.sleep() function, but everytime I try to fire a bullet, the program crashes. Is there any way I can stop it from doing this? Or why is it not working? Is there an equally effective method that will not crash my program?

import turtle
import time

userx = 0

x = 0
y = -300

enemies = [(300,50, "left"), (400,50, "left"), (350, -50, "right")]

bullets = []

gameover = False

def frame():
    pass
    ship = turtle.Turtle()
    ship.pu()
    ship.ht()
    ship.setpos(userx, -300)
    ship.pd()
    ship.circle(5)

    bullet = turtle.Turtle()
    bullet.pu()
    bullet.ht()
    bullet.setpos(x, y)
    bullet.pd()
    bullet.circle(2)

def key_left():
    global userx
    pass
    userx += -10
    print(userx)

def key_right():
    global userx
    pass
    userx += 10
    print(userx)

def key_space():
    pass # your code here
    global x
    global y
    global bullets
    x = userx
    while y <= 300:
        time.sleep(0.5)
        y += 4
    else: y = 0
    bullets += (x,y)

def physics():
    global bullets
    global enemies
    pass

def ai():
    global enemies
    global gameover
    pass

def reset():
    global enemies
    global bullets
    global userx
    global gameover
    pass

def main():
    turtle.tracer(0,0)
    turtle.hideturtle()
    turtle.onkey(key_left, "Left")
    turtle.onkey(key_right, "Right")
    turtle.onkey(key_space, "space")
    turtle.listen()
    reset()
    while not gameover:
        turtle.clear()
        physics()
        ai()
        frame()
        turtle.update()
        time.sleep(0.05)

main()

Body:
It is not ideal but it starts working.

In key_space you only add new bullet to list.

In while not gameover you run function which will move all bullets.

In frame you draw all bullets.

import turtle
import time

userx = 0

x = 0
y = -300

enemies = [(300,50, "left"), (400,50, "left"), (350, -50, "right")]

bullets = []

gameover = False

def frame():
    pass
    ship = turtle.Turtle()
    ship.pu()
    ship.ht()
    ship.setpos(userx, -300)
    ship.pd()
    ship.circle(5)

    # redraw bullets
    for x, y in bullets:
        bullet = turtle.Turtle()
        bullet.pu()
        bullet.ht()
        bullet.setpos(x, y)
        bullet.pd()
        bullet.circle(2)

def key_left():
    global userx
    pass
    userx += -10
    print(userx)

def key_right():
    global userx
    pass
    userx += 10
    print(userx)

def key_space():
    pass # your code here
    global x
    global y
    global bullets
    x = userx

    # add bullet to list
    bullets.append([x, -300])

def move_bullets():
    global bullets

    live_bullets = []

    # move every bullet and check if should still live
    for x, y in bullets:
        y += 4

        # keep only some bullets and other forget (kill/remove)
        if y <= 300:
            live_bullets.append([x, y])

    bullets = live_bullets

def physics():
    global bullets
    global enemies
    pass

def ai():
    global enemies
    global gameover
    pass

def reset():
    global enemies
    global bullets
    global userx
    global gameover
    pass

def main():
    turtle.tracer(0,0)
    turtle.hideturtle()
    turtle.onkey(key_left, "Left")
    turtle.onkey(key_right, "Right")
    turtle.onkey(key_space, "space")
    turtle.listen()
    reset()
    while not gameover:
        turtle.clear()
        physics()
        ai()
        move_bullets() # <--  move bullets (or maybe before physics)
        frame()
        turtle.update()
        time.sleep(0.05)

main()


问:
C# Custom text file based resource provider that allows space in keys
I have read much about .resx files and know that we can also create a custom resource provider which may support db or XML.

I have a requirement however where my keys will contain spaces. Plus I want them in a simple .txt file. No .resx or XML files.

An example would be like:

```<code>My Key 1=Hello Dude
My Key 2=Hello world
</code>```

I was wondering if there is any way to fetch such keys in .net by writing some custom resource provider in C#. Is it possible?

答:
Would JSON format do?

```<code>var someText = "{\"my key 1\" : \"hello dude\", \"my key 2\" : \"hello world\"}";

JObject resource = JObject.Parse(someText);

foreach (var p in resource.Properties())
{
    Console.WriteLine("The key is {0} and it's value is {1}", p.Name, p.Value);
}
</code>```

Dependency: JSON.Net

Hth...

Body:
I have read much about .resx files and know that we can also create a custom resource provider which may support db or XML.

I have a requirement however where my keys will contain spaces. Plus I want them in a simple .txt file. No .resx or XML files.

An example would be like:

My Key 1=Hello Dude
My Key 2=Hello world

I was wondering if there is any way to fetch such keys in .net by writing some custom resource provider in C#. Is it possible?

Body:
Would JSON format do?

var someText = "{\"my key 1\" : \"hello dude\", \"my key 2\" : \"hello world\"}";

JObject resource = JObject.Parse(someText);

foreach (var p in resource.Properties())
{
    Console.WriteLine("The key is {0} and it's value is {1}", p.Name, p.Value);
}

Dependency: JSON.Net

Hth...


问:
Access: Create n records with recordset
I'm trying something with VBA in Access but I cannot see what I'm doing wrong.

I have in a form a text control (numeric) where I can write some number. What I want is when I clic on a button in the form, cretat as many records in another table (not the source of the form) as the number in the text control.

I'm trying this, but it doesn't do anything:

```<code>Dim db As Database
Dim rst As Recordset

Set db = CurrentDb()
Set rst = db.OpenRecordset("Table")

If Not rst.EOF And rst.BOF Then
    Do While rst.RecordCount < Me.Txt_Control
        rst.Edit
            rst.Fields("Field_01") = "Example 1"
            rst.Fields("Field_02") = "Example 2"
            rst.Fields("Field_03") = "Example 3"
        rst.Update
        rst.MoveNext
    Loop
    rst.Close
End If
</code>```

Can someone give me a hand?

Regards.

答:
You're editing one existing record, not adding new ones. Also, your code may run into trouble since you're opening a recordset with possible records present.

You can use the following:

```<code>Dim db As DAO.Database
Dim rst As DAO.Recordset

Set db = CurrentDb()
Set rst = db.OpenRecordset("SELECT * FROM Table WHERE 1=0") 'Open the table, but don't select anything
Do While rst.RecordCount < Me.Txt_Control
    rst.AddNew 'Add a new record
    rst.Fields("Field_01") = "Example 1"
    rst.Fields("Field_02") = "Example 2"
    rst.Fields("Field_03") = "Example 3"
    rst.Update
Loop
rst.Close
</code>```

Title: Access: Create n records with recordset

Body:
I'm trying something with VBA in Access but I cannot see what I'm doing wrong.

I have in a form a text control (numeric) where I can write some number. What I want is when I clic on a button in the form, cretat as many records in another table (not the source of the form) as the number in the text control.

I'm trying this, but it doesn't do anything:

Dim db As Database
Dim rst As Recordset

Set db = CurrentDb()
Set rst = db.OpenRecordset("Table")

If Not rst.EOF And rst.BOF Then
    Do While rst.RecordCount < Me.Txt_Control
        rst.Edit
            rst.Fields("Field_01") = "Example 1"
            rst.Fields("Field_02") = "Example 2"
            rst.Fields("Field_03") = "Example 3"
        rst.Update
        rst.MoveNext
    Loop
    rst.Close
End If

Can someone give me a hand?

Regards.

Body:
You're editing one existing record, not adding new ones. Also, your code may run into trouble since you're opening a recordset with possible records present.

You can use the following:

Dim db As DAO.Database
Dim rst As DAO.Recordset

Set db = CurrentDb()
Set rst = db.OpenRecordset("SELECT * FROM Table WHERE 1=0") 'Open the table, but don't select anything
Do While rst.RecordCount < Me.Txt_Control
    rst.AddNew 'Add a new record
    rst.Fields("Field_01") = "Example 1"
    rst.Fields("Field_02") = "Example 2"
    rst.Fields("Field_03") = "Example 3"
    rst.Update
Loop
rst.Close


问:
jQuery effects run smoothly, but sometimes get jumpy - why?
I have been playing with a few jQuery effects and when they run smoothly look pretty neat, but sometimes (at random times when the script is invoked) the effects lock up and jump to the end result.

```<code>//--Expand Panel
$(".open-menu").live('click', function(){
    $("#wrap").css({ 'height' : newH + 'px' });
    $(".mini-menu").fadeOut(500);
    $("#headerCompany").animate({
        marginLeft: '+=142'
    }, 650);
    $("#avatar_box").fadeIn(650);
    $("#pinboard").fadeIn(550);
    $("div#centerHeader").slideDown("slow");
    $("#toggle-pinboard a").removeClass("open-menu").addClass("close-menu");
    return false;
});
// Collapse Panel
$(".close-menu").live('click', function(){
    $("#wrap").css({ 'height' : newH + 'px' });
    $("#avatar_box").fadeOut(550);
    $("#pinboard").fadeOut(550);
    $("#headerCompany").animate({
        marginLeft: '-=142'
    }, 650);
    $("div#centerHeader").slideUp(750).delay(300);
    $.post('resources/ajax/ajax.php', {
        action: 'mini_menu'
    }, function(menu){
        $("#mini-menu").hide().html(menu).addClass("mini-menu").fadeIn(1500);
    });
    $("#toggle-pinboard a").removeClass("close-menu").addClass("open-menu");
    return false;
});
</code>```

PHP:

```<code>switch($post['action']) {
    case 'mini_menu':
        echo "<nav>
                <a href='/' class='dashboard-menu-link'>Dashboard</a>
                 | <a href='contacts.php'>Contacts</a>
                 | <a href='mail.php'>Mail</a>
                 | <a href='files.php' class='files-menu-link'>Files</a>
                 | <a href='toolbox.php' id='toolbox-menu-link'>Toolbox</a>
                 | <a href='agenda.php' id='agenda-menu-link'>Agenda</a>
                 | <a href='settings.php' id='settings-menu-link'>Settings</a>
            </nav>";
    break;
</code>```

HTML:

```<code>    <div id="header">
        <div id="topHeader">
            <div id="topHeaderGroup">
                <div id="headerCompany">
                    <span><b><?=$company;?></b></span>
                </div>
    -------->>>     <span id="mini-menu"></span> <<<--------
                <div id="toggle-pinboard">
                    <a id="toggle-menu" class="close-menu" href="#"><span></span></a>
                </div>
                <div id="headerWelcomeAccount">
                    <div class="nav_profile_menu" >
                        <a href="helix-007"><span class="top-header-color-change">View My Profile</span></a> |
                        <a href="logout.php"><span class="top-header-color-change">Logout</span></a> |
                        <a href="#" class="menu_drop"><span class="top-header-color-change">My Account</span></a>
                    </div><!-- end nav_profile_menu -->
                </div><!-- end headerWelcomeAccount -->
            </div><!-- end topHeaderGroup -->
        </div><!-- end topHeader -->

        <div id="centerHeader">
            <div id="header_container">
                <div id="avatar_box" class="border trans_white_gloss"></div>
                <div id="pinboard"></div>
            </div>
        </div><!-- end centerHeader -->
    </div><!-- END HEADER -->
</code>```

CSS:

```<code>.mini-menu {
    margin: 0 auto;
    width: 400px;
    height: <?=$header_top_height;?>px;
    /*float: left;*/
    color: #FFF;
    padding-left: 20px;
}
.mini-menu a{
    color: #FFF;
}
</code>```

Tested in FireFox 3.6 with firebug on

答:
Probably

Problem could be with your hardware configuration, browser version

You can check effect on multiple platforms if problem exist then we need your full code with html.

Body:
I have been playing with a few jQuery effects and when they run smoothly look pretty neat, but sometimes (at random times when the script is invoked) the effects lock up and jump to the end result.

//--Expand Panel
$(".open-menu").live('click', function(){
    $("#wrap").css({ 'height' : newH + 'px' });
    $(".mini-menu").fadeOut(500);
    $("#headerCompany").animate({
        marginLeft: '+=142'
    }, 650);
    $("#avatar_box").fadeIn(650);
    $("#pinboard").fadeIn(550);
    $("div#centerHeader").slideDown("slow");
    $("#toggle-pinboard a").removeClass("open-menu").addClass("close-menu");
    return false;
});
// Collapse Panel
$(".close-menu").live('click', function(){
    $("#wrap").css({ 'height' : newH + 'px' });
    $("#avatar_box").fadeOut(550);
    $("#pinboard").fadeOut(550);
    $("#headerCompany").animate({
        marginLeft: '-=142'
    }, 650);
    $("div#centerHeader").slideUp(750).delay(300);
    $.post('resources/ajax/ajax.php', {
        action: 'mini_menu'
    }, function(menu){
        $("#mini-menu").hide().html(menu).addClass("mini-menu").fadeIn(1500);
    });
    $("#toggle-pinboard a").removeClass("close-menu").addClass("open-menu");
    return false;
});

PHP:

switch($post['action']) {
    case 'mini_menu':
        echo "
                Dashboard
                 | Contacts
                 | Mail
                 | Files
                 | Toolbox
                 | Agenda
                 | Settings
            ";
    break;

HTML:

                    <?=$company;?>

    -------->>>      <<<--------

                        View My Profile |
                        Logout |
                        My Account

CSS:

.mini-menu {
    margin: 0 auto;
    width: 400px;
    height: <?=$header_top_height;?>px;
    /*float: left;*/
    color: #FFF;
    padding-left: 20px;
}
.mini-menu a{
    color: #FFF;
}

Tested in FireFox 3.6 with firebug on


问:
Can someone explain to me what this error is and why it's deleting my cpp file?
I am pretty sure I added the main file but I don't know why my cpp file is being deleted and why I am getting this error. I typed in the terminal
g++ -o assign8.cpp -lboost_system -lboost_thread

I would add my code but the file got deleted

```<code>/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 20 has invalid symbol index 20
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
</code>```

答:
-o

you want to compile with something like: g++ -o assign8 assign8.cpp -lboost_system -lboost_thread
assign8.cpp is going to write to assign8.cpp, almost certainly not what you want. .cpp files are input not output.

Body:
I am pretty sure I added the main file but I don't know why my cpp file is being deleted and why I am getting this error. I typed in the terminal
g++ -o assign8.cpp -lboost_system -lboost_thread

I would add my code but the file got deleted

/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 20 has invalid symbol index 20
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status


问:
$scope vs var in AngularJS
I've been using var and $scope.varname and both work fine in AngularJS. I was wondering if there was a difference between the two functionally, and what best practice was in which one to use?</p>

答: $scope bind value to the view and var is the local variable to the application.</p>

Title: $scope vs var in AngularJS


问:
Order of evaluation in C++ function parameters
If we have three functions (foo, bar, and baz) that are composed like so...

```<code>foo(bar(), baz())
</code>```

Is there any guarantee by the C++ standard that bar will be evaluated before baz?

答:
As others have already pointed out, the standard does not give any guidance on order of evaluation for this particular scenario. This order of evaluation is then left to the compiler, and the compiler might have a guarantee.

It's important to remember that the C++ standard is really a language to instruct a compiler on constructing assembly/machine code. The standard is only one part of the equation. Where the standard is ambiguous or is specifically implementation defined you should turn to the compiler and understand how it translates C++ instructions into true machine language.

So, if order of evaluation is a requirement, or at least important, and being cross-compiler compatible is not a requirement, investigate how your compiler will ultimately piece this together, your answer could ultimate lie there. Note that the compiler could change it's methodology in the future

Body:
If we have three functions (foo, bar, and baz) that are composed like so...

foo(bar(), baz())

Is there any guarantee by the C++ standard that bar will be evaluated before baz?


问:
Is this stack or stack emulation?
```<code>package java.util;
public
class Stack<E> extends Vector<E> {
    public Stack() {
    }

    public E push(E item) {
        addElement(item);
        return item;
    }

    public synchronized E pop() {
        E obj;
        int len = size();

        obj = peek();
        removeElementAt(len - 1);

        return obj;
    }

    public synchronized E peek() {
        int     len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }

    public synchronized int search(Object o) {
        int i = lastIndexOf(o);

        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }

    private static final long serialVersionUID = 1224463164541339165L;
}
</code>```

Above is the java source code for stack.
I realized that it is only emulating a stack and not a real one.So my questions are

Am I right in saying that this is just an imitation of Stack and not the real one?

If I can say the above and I want to build it from scratch,how would I do it?(arrays of fixed size or arraylist which in turn uses list(single/double linked)?)

答:
There is no "real Stack", a stack is just an idea, a so-called abstract data type. It supports two operations, push and pop, and the order of elements is defined to be last-in first-out (LIFO). In addition to java.util.Stack (based on Vector, which is array-based), you also have java.util.LinkedList (a doubly-linked list), which also supports stack operations, so it's also a stack as much as the other one.. There are several other implementations, for example all implementations of java.util.Deque.

You can do it from scratch in a number of ways, each has their own trade-offs. Your question is not defined enough for a good answer.

Title: Is this stack or stack emulation?

Body:
package java.util;
public
class Stack<E> extends Vector<E> {
    public Stack() {
    }

    public E push(E item) {
        addElement(item);
        return item;
    }

    public synchronized E pop() {
        E obj;
        int len = size();

        obj = peek();
        removeElementAt(len - 1);

        return obj;
    }

    public synchronized E peek() {
        int     len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }

    public synchronized int search(Object o) {
        int i = lastIndexOf(o);

        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }

    private static final long serialVersionUID = 1224463164541339165L;
}

Above is the java source code for stack.
I realized that it is only emulating a stack and not a real one.So my questions are

Am I right in saying that this is just an imitation of Stack and not the real one?

If I can say the above and I want to build it from scratch,how would I do it?(arrays of fixed size or arraylist which in turn uses list(single/double linked)?)


问:
increase accuracy of model in sklearn
The decision tree classification gives an accuracy of 0.52 but I want to increase the accuracy. How can I increase the accuracy by using any of the classification model available in sklearn.

I have used knn, decision tree, and cross-validation but all of them gives less accuracy.

Thanks

```<code>import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

#read from the csv file and return a Pandas DataFrame.
nba = pd.read_csv('wine.csv')

# print the column names
original_headers = list(nba.columns.values)
print(original_headers)

#print the first three rows.
print(nba[0:3])

# "Position (pos)" is the class attribute we are predicting.
class_column = 'quality'

#The dataset contains attributes such as player name and team name.
#We know that they are not useful for classification and thus do not
#include them as features.
feature_columns = ['fixed acidity', 'volatile acidity', 'citric     acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur         dioxide', 'density', 'pH','sulphates', 'alcohol']

#Pandas DataFrame allows you to select columns.
#We use column selection to split the data into features and class.
nba_feature = nba[feature_columns]
nba_class = nba[class_column]

print(nba_feature[0:3])
print(list(nba_class[0:3]))

train_feature, test_feature, train_class, test_class = \
train_test_split(nba_feature, nba_class, stratify=nba_class, \
train_size=0.75, test_size=0.25)

training_accuracy = []
test_accuracy = []

knn = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=1)
knn.fit(train_feature, train_class)
prediction = knn.predict(test_feature)
print("Test set predictions:\n{}".format(prediction))
print("Test set accuracy: {:.2f}".format(knn.score(test_feature, test_class)))

train_class_df = pd.DataFrame(train_class,columns=[class_column])
train_data_df = pd.merge(train_class_df, train_feature, left_index=True, right_index=True)
train_data_df.to_csv('train_data.csv', index=False)

temp_df = pd.DataFrame(test_class,columns=[class_column])
temp_df['Predicted Pos']=pd.Series(prediction, index=temp_df.index)
test_data_df = pd.merge(temp_df, test_feature, left_index=True, right_index=True)
test_data_df.to_csv('test_data.csv', index=False)

tree = DecisionTreeClassifier(max_depth=4, random_state=0)
tree.fit(train_feature, train_class)
print("Training set score: {:.3f}".format(tree.score(train_feature, train_class)))
print("Test set score Decision: {:.3f}".format(tree.score(test_feature, test_class)))

prediction = tree.predict(test_feature)
print("Confusion matrix:")
print(pd.crosstab(test_class, prediction, rownames=['True'], colnames=['Predicted'], margins=True))
cancer = nba.as_matrix()
tree = DecisionTreeClassifier(max_depth=4, random_state=0)

scores = cross_val_score(tree, train_feature,train_class, cv=10)
print("Cross-validation scores: {}".format(scores))
print("Average cross-validation score: {:.2f}".format(scores.mean()))
</code>```

答:
Improve your preprocessing.

Methods such as DT and kNN may be sensitive to how you preprocess your columns. For example, a DT can benefit much from well-chosen thresholds on the continuous variables.

Title: increase accuracy of model in sklearn

Body:
The decision tree classification gives an accuracy of 0.52 but I want to increase the accuracy. How can I increase the accuracy by using any of the classification model available in sklearn.

I have used knn, decision tree, and cross-validation but all of them gives less accuracy.

Thanks

import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

#read from the csv file and return a Pandas DataFrame.
nba = pd.read_csv('wine.csv')

# print the column names
original_headers = list(nba.columns.values)
print(original_headers)

#print the first three rows.
print(nba[0:3])

# "Position (pos)" is the class attribute we are predicting.
class_column = 'quality'

#The dataset contains attributes such as player name and team name.
#We know that they are not useful for classification and thus do not
#include them as features.
feature_columns = ['fixed acidity', 'volatile acidity', 'citric     acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur         dioxide', 'density', 'pH','sulphates', 'alcohol']

#Pandas DataFrame allows you to select columns.
#We use column selection to split the data into features and class.
nba_feature = nba[feature_columns]
nba_class = nba[class_column]

print(nba_feature[0:3])
print(list(nba_class[0:3]))

train_feature, test_feature, train_class, test_class = \
train_test_split(nba_feature, nba_class, stratify=nba_class, \
train_size=0.75, test_size=0.25)

training_accuracy = []
test_accuracy = []

knn = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=1)
knn.fit(train_feature, train_class)
prediction = knn.predict(test_feature)
print("Test set predictions:\n{}".format(prediction))
print("Test set accuracy: {:.2f}".format(knn.score(test_feature, test_class)))

train_class_df = pd.DataFrame(train_class,columns=[class_column])
train_data_df = pd.merge(train_class_df, train_feature, left_index=True, right_index=True)
train_data_df.to_csv('train_data.csv', index=False)

temp_df = pd.DataFrame(test_class,columns=[class_column])
temp_df['Predicted Pos']=pd.Series(prediction, index=temp_df.index)
test_data_df = pd.merge(temp_df, test_feature, left_index=True, right_index=True)
test_data_df.to_csv('test_data.csv', index=False)

tree = DecisionTreeClassifier(max_depth=4, random_state=0)
tree.fit(train_feature, train_class)
print("Training set score: {:.3f}".format(tree.score(train_feature, train_class)))
print("Test set score Decision: {:.3f}".format(tree.score(test_feature, test_class)))

prediction = tree.predict(test_feature)
print("Confusion matrix:")
print(pd.crosstab(test_class, prediction, rownames=['True'], colnames=['Predicted'], margins=True))
cancer = nba.as_matrix()
tree = DecisionTreeClassifier(max_depth=4, random_state=0)

scores = cross_val_score(tree, train_feature,train_class, cv=10)
print("Cross-validation scores: {}".format(scores))
print("Average cross-validation score: {:.2f}".format(scores.mean()))


问:
java StringTokenizer - can nextToken return null?
Is there any case where StringTokenizer.nextToken will return null?
I'm trying to debug a NullPointerException in my code, and so far the only possibility I've found is that the string returned from nextToken() returned null. Is that a possibility? Didn't find anything in the java doc.

Thanks

答:
nextToken() throws NoSuchElementException if there are no more tokens in the tokenizer's string; so I would say that it doesn't return null.

http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html#nextToken()


问:
Install app via usb: The device is temporarily restricted
When I toggle on the install via USB in developer mode:

it will pop the toast message said that the device is temporarily restricted

then toggle off the settings.

Is there any solution for this?

I searched through all the way like turning off MIUI optimization but still does not work. I cannot debug my application by Android Studio in this way......

答:
Please verify your email and phone number in Mi account first then try this:

Settings -> Additional Settings -> Developer options -> Turn off Miui Optimizations -> Restart

Security -> Permissions -> Gear Icon at top right corner -> Turn On "Install via USB"

Settings -> Additional Settings -> Developer options -> Turn On/Off "USB Debugging" -> Turn On "Install vis USB"


问:
MongoDB - I want to specify a primary key and operate it with name other than `_id`
I had a Tag schema (defined with mongoose):

```<code>var Tag = new Schema({
  _id: String  // Not ObjectId but the name of the tag.
});
</code>```

I want to use the tag name as its _id, but I don't want to operate this field with name _id. For example, I would like to add a new tag with code new Tag({name: 'tagA'}) instead of new Tag({_id: 'tagA'}). Since the code is more expressive in this way.

So I need to change name to _id. One method would be using the pre-save hook.

```<code>Tag.pre('save', function(next) {
  if (!this._id && this.name) this._id = this.name;
  next();
});
</code>```

Are there ways better than this one?

答:
This seems to be the best option I found with mongoose for implementing custom primary keys.

```<code><schemaToHook>.pre('save', true, function(next, done) {
   // trigger next middleware in parallel
   next();
   if (!this._id && this.name) {
       this._id = this.name;
   }
   done();
 });
</code>```

I am using a parallel middleware and expecting better performance. Also, while using the above implementation you might want to consider using findOneAndUpdate with upsert = true for INSERT or REPLACE equivalent implementation.

```<code>MyModel.findOneAndUpdate(
    {foo: 'bar'}, // find a document with that filter
    modelDoc, // document to insert when nothing was found
    {upsert: true, new: true, runValidators: true}, // options
    function (err, doc) { // callback
        if (err) {
            // handle error
        } else {
            // handle document
        }
    }
);
</code>```

Body:
I had a Tag schema (defined with mongoose):

var Tag = new Schema({
  _id: String  // Not ObjectId but the name of the tag.
});

I want to use the tag name as its _id, but I don't want to operate this field with name _id. For example, I would like to add a new tag with code new Tag({name: 'tagA'}) instead of new Tag({_id: 'tagA'}). Since the code is more expressive in this way.

So I need to change name to _id. One method would be using the pre-save hook.

Tag.pre('save', function(next) {
  if (!this._id && this.name) this._id = this.name;
  next();
});

Are there ways better than this one?

Body:
This seems to be the best option I found with mongoose for implementing custom primary keys.

<schemaToHook>.pre('save', true, function(next, done) {
   // trigger next middleware in parallel
   next();
   if (!this._id && this.name) {
       this._id = this.name;
   }
   done();
 });

I am using a parallel middleware and expecting better performance. Also, while using the above implementation you might want to consider using findOneAndUpdate with upsert = true for INSERT or REPLACE equivalent implementation.

MyModel.findOneAndUpdate(
    {foo: 'bar'}, // find a document with that filter
    modelDoc, // document to insert when nothing was found
    {upsert: true, new: true, runValidators: true}, // options
    function (err, doc) { // callback
        if (err) {
            // handle error
        } else {
            // handle document
        }
    }
);


问:
Is there any Angular 4 Performance tool like react-perf for React Application?
Is there any Angular 4 Performance tool to test the angular component rendering performance
like react-perf for React Application?</p>

答:
Chrome dev tools.

Anyway react says: "As of React 16, react-addons-perf is not supported. Please use your browser’s profiling tools to get insight into which components re-render."


问:
Triplet model for image retrieval from the Keras pretrained network
I want to implement a model for image retrieval. The model will be trained with a triplet loss function (same as facenet or similar architectures). My idea was to use a pretrained classification model from Keras (e.g. resnet50), and make it a triple architecture. This is my model in Keras:

```<code>resnet_input = Input(shape=(224,224,3))
resnet_model = ResNet50(weights='imagenet', include_top = False, input_tensor=resnet_input)
net = resnet_model.output

net = Flatten(name='flatten')(net)
net = Dense(512, activation='relu', name='embded')(net)
net = Lambda(l2Norm, output_shape=[512])(net)

base_model = Model(resnet_model.input, net, name='resnet_model')

input_shape=(224,224,3)
input_anchor = Input(shape=input_shape, name='input_anchor')
input_positive = Input(shape=input_shape, name='input_pos')
input_negative = Input(shape=input_shape, name='input_neg')

net_anchor = base_model(input_anchor)
net_positive = base_model(input_positive)
net_negative = base_model(input_negative)

positive_dist = Lambda(euclidean_distance, name='pos_dist')([net_anchor, net_positive])
negative_dist = Lambda(euclidean_distance, name='neg_dist')([net_anchor, net_negative])

stacked_dists = Lambda(
            lambda vects: K.stack(vects, axis=1),
            name='stacked_dists'
)([positive_dist, negative_dist])

model = Model([input_anchor, input_positive, input_negative], stacked_dists, name='triple_siamese')

def triplet_loss(_, y_pred):
    margin = K.constant(1)
    return K.mean(K.maximum(K.constant(0), K.square(y_pred[0]) - K.square(y_pred[1]) + margin))

def accuracy(_, y_pred):
    return K.mean(y_pred[0] < y_pred[1])

def l2Norm(x):
    return  K.l2_normalize(x, axis=-1)

def euclidean_distance(vects):
    x, y = vects
    return K.sqrt(K.maximum(K.sum(K.square(x - y), axis=1, keepdims=True), K.epsilon()))
</code>```

The model should predict a feature vector for every image. The distances (euclidean in this case) between these vectors should be close to zero if the images are from the same class, or close to one if they're not.

I already tried different learning steps, batch sizes, different margins in the loss function, choosing different output layers from the original resnet model, different layers added to the end of the resnet, training just the new added layers vs training the whole model. I also tried to use this resnet model without pretrained weights, the result was still the same, around 0.5 accuracy and 1.0 loss, no matter what I did. (The input images were preprocessed in the way which was expected for this model with keras.applications.resnet50.preprocess_input)

I didn't do any hard negative mining which may result in slow convergence, but still, 0.5 accuracy in this case (check the function) is random predictions.

So I started thinking maybe I miss something really important here (it's a quite difficult architecture). So please, if you notice something wrong or suspicious in my implementation I'd be really glad for that.

答:
In case someone'd be interested, rewriting

y_pred[0] and y_pred[1]

to

y_pred[:,0,0] and y_pred[:,1,0]

fixed it.

Now the model seems to be training (the loss is decreasing and the accuracy is increasing).

Body:
I want to implement a model for image retrieval. The model will be trained with a triplet loss function (same as facenet or similar architectures). My idea was to use a pretrained classification model from Keras (e.g. resnet50), and make it a triple architecture. This is my model in Keras:

resnet_input = Input(shape=(224,224,3))
resnet_model = ResNet50(weights='imagenet', include_top = False, input_tensor=resnet_input)
net = resnet_model.output

net = Flatten(name='flatten')(net)
net = Dense(512, activation='relu', name='embded')(net)
net = Lambda(l2Norm, output_shape=[512])(net)

base_model = Model(resnet_model.input, net, name='resnet_model')

input_shape=(224,224,3)
input_anchor = Input(shape=input_shape, name='input_anchor')
input_positive = Input(shape=input_shape, name='input_pos')
input_negative = Input(shape=input_shape, name='input_neg')

net_anchor = base_model(input_anchor)
net_positive = base_model(input_positive)
net_negative = base_model(input_negative)

positive_dist = Lambda(euclidean_distance, name='pos_dist')([net_anchor, net_positive])
negative_dist = Lambda(euclidean_distance, name='neg_dist')([net_anchor, net_negative])

stacked_dists = Lambda(
            lambda vects: K.stack(vects, axis=1),
            name='stacked_dists'
)([positive_dist, negative_dist])

model = Model([input_anchor, input_positive, input_negative], stacked_dists, name='triple_siamese')

def triplet_loss(_, y_pred):
    margin = K.constant(1)
    return K.mean(K.maximum(K.constant(0), K.square(y_pred[0]) - K.square(y_pred[1]) + margin))

def accuracy(_, y_pred):
    return K.mean(y_pred[0] < y_pred[1])

def l2Norm(x):
    return  K.l2_normalize(x, axis=-1)

def euclidean_distance(vects):
    x, y = vects
    return K.sqrt(K.maximum(K.sum(K.square(x - y), axis=1, keepdims=True), K.epsilon()))

The model should predict a feature vector for every image. The distances (euclidean in this case) between these vectors should be close to zero if the images are from the same class, or close to one if they're not.

I already tried different learning steps, batch sizes, different margins in the loss function, choosing different output layers from the original resnet model, different layers added to the end of the resnet, training just the new added layers vs training the whole model. I also tried to use this resnet model without pretrained weights, the result was still the same, around 0.5 accuracy and 1.0 loss, no matter what I did. (The input images were preprocessed in the way which was expected for this model with keras.applications.resnet50.preprocess_input)

I didn't do any hard negative mining which may result in slow convergence, but still, 0.5 accuracy in this case (check the function) is random predictions.

So I started thinking maybe I miss something really important here (it's a quite difficult architecture). So please, if you notice something wrong or suspicious in my implementation I'd be really glad for that.