问:
JAVA - SCANNER to get user input
I have the following block code:

```<code>    boolean run = true;
    while (run) {
        Scanner scanner = new Scanner(System.in);
        // do something

        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNn]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f"))
            run = false;

        scanner.close();
    }
</code>```

I want to perform something until the user types 'N'.
Currently, I'm able to run the while loop only one time.
The second time I'm not able to type my choice and I have the following error:

```<code>Another action? [Y/N]     <--- here no chance to type choice
Incorrect input
java.util.NoSuchElementException
    at java.util.Scanner.throwFor
    at java.util.Scanner.next
</code>```

What is wrong?
Thanks

EDIT: I think my problem is in "do something". It is in turn a sequence of user input where i close the scanner.

答:
The problem in fact is in your while loop condition. Let's debug:

When you only input chars that do not match with the pattern [YyNn] all goes ok (user will always get the Incorrect input message). But when you give, let's say an Y, your while loop will stop but Y will not be consumed. Therefore, this char will be consumed in the next instruction, i.e. in String choice = scanner.next(); (if you print variable choice you will see it has an Y).

After this, we go to the next iteration. Because there are no input to be consumed, scanner.hasNext("[YyNn]") will be false. But your while loop condition is !scanner.hasNext("[YyNn]"), which give us a true and enters inside the loop. Inside the loop we have the instruction scanner.next(). Since there are no input to be consumed, BOOM, you get a java.util.NoSuchElementException, which says the following:

Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

Other of your problems is in your scanner position. At each iteration you are initializing a new instance and closing it. You could just move the scanner initialization and its closure outside the loops.

Below I provide a similar sample code that does what you want with some explanations.

FULL CODE

```<code>public static void main(String[] args) {
    boolean run = true;
    Scanner scanner = new Scanner(System.in); // Init before loops
    String userInput = ""; // tmp var that holds input

    while (run) {
        // do something

        System.out.println("Another action? [Y/N]");
        userInput = scanner.next(); // Read first time

        // Run while user does not put Y || y || N || n
        while (!userInput.matches("[YyNn]")){
            System.out.println("Incorrect input");
            userInput = scanner.next();
        }

        // User does not want more actions
        if(userInput.matches("[Nn]")){
            System.out.println("Do you wish to exit the program? [Y/Any other key]");
            String choice = scanner.next();

            // Stop the program
            if (choice.toLowerCase().equals("y"))
                run = false;
        }
    }
    scanner.close(); // Close scanner outside
}
</code>```

Hope it helped!

Title: JAVA - SCANNER to get user input

Body:
I have the following block code:

    boolean run = true;
    while (run) {
        Scanner scanner = new Scanner(System.in);
        // do something

        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNn]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f"))
            run = false;

        scanner.close();
    }

I want to perform something until the user types 'N'.
Currently, I'm able to run the while loop only one time.
The second time I'm not able to type my choice and I have the following error:

Another action? [Y/N]     <--- here no chance to type choice
Incorrect input
java.util.NoSuchElementException
    at java.util.Scanner.throwFor
    at java.util.Scanner.next

What is wrong?
Thanks

EDIT: I think my problem is in "do something". It is in turn a sequence of user input where i close the scanner.

Body:
The problem in fact is in your while loop condition. Let's debug:

When you only input chars that do not match with the pattern [YyNn] all goes ok (user will always get the Incorrect input message). But when you give, let's say an Y, your while loop will stop but Y will not be consumed. Therefore, this char will be consumed in the next instruction, i.e. in String choice = scanner.next(); (if you print variable choice you will see it has an Y).

After this, we go to the next iteration. Because there are no input to be consumed, scanner.hasNext("[YyNn]") will be false. But your while loop condition is !scanner.hasNext("[YyNn]"), which give us a true and enters inside the loop. Inside the loop we have the instruction scanner.next(). Since there are no input to be consumed, BOOM, you get a java.util.NoSuchElementException, which says the following:

Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

Other of your problems is in your scanner position. At each iteration you are initializing a new instance and closing it. You could just move the scanner initialization and its closure outside the loops.

Below I provide a similar sample code that does what you want with some explanations.

FULL CODE

public static void main(String[] args) {
    boolean run = true;
    Scanner scanner = new Scanner(System.in); // Init before loops
    String userInput = ""; // tmp var that holds input

    while (run) {
        // do something

        System.out.println("Another action? [Y/N]");
        userInput = scanner.next(); // Read first time

        // Run while user does not put Y || y || N || n
        while (!userInput.matches("[YyNn]")){
            System.out.println("Incorrect input");
            userInput = scanner.next();
        }

        // User does not want more actions
        if(userInput.matches("[Nn]")){
            System.out.println("Do you wish to exit the program? [Y/Any other key]");
            String choice = scanner.next();

            // Stop the program
            if (choice.toLowerCase().equals("y"))
                run = false;
        }
    }
    scanner.close(); // Close scanner outside
}

Hope it helped!


来源: stackexchange

问:
RavenDB 4 RC2: Cannot execute command of type PutAutoIndexCommand for database - Can not update auto-index:
I am using a RavenDB 4 RC 2 database. Some of my database auto generated indexes keep 'freezing' and causing errors in my API. Deleting the frozen index provides a short term solution. But even though I am regenerating them, it just a matter of time before they 'freeze' again.

FYI => They get an orange colour state in the RavenDb Studio instead of the normal green status colour. I had this with the beta and RC1 as well. So the timeframe in which this is happening is a few months.

Does anyone know how I can fix this? See full Stacktrace below.

```<code>Failed to generate order number Raven.Client.Exceptions.Cluster.CommandExecutionException: Cannot execute command of type PutAutoIndexCommand for database <my-database> ---> System.NotSupportedException: Can not update auto-index: Auto/Orders/ByCreatedBy.IdAndOrderNumberAndWorkspace
at Raven.Client.ServerWide.DatabaseRecord.AddIndex(AutoIndexDefinition definition) in C:\Builds\RavenDB-4.0-RC\src\Raven.Client\ServerWide\DatabaseRecord.cs:line 119
at Raven.Server.ServerWide.Commands.Indexes.PutAutoIndexCommand.UpdateDatabaseRecord(DatabaseRecord record, Int64 etag) in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\ServerWide\Commands\Indexes\PutAutoIndexCommand.cs:line 34
at Raven.Server.ServerWide.ClusterStateMachine.UpdateDatabase(TransactionOperationContext context, String type, BlittableJsonReaderObject cmd, Int64 index, Leader leader, ServerStore serverStore) in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\ServerWide\ClusterStateMachine.cs:line 802
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Rachis.RachisConsensus.<PutAsync>d__92.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Rachis\RachisConsensus.cs:line 589
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.ServerWide.ServerStore.<SendToLeaderAsyncInternal>d__124.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\ServerWide\ServerStore.cs:line 1479
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Indexes.IndexStore.<CreateIndex>d__23.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Indexes\IndexStore.cs:line 435
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Queries.Dynamic.DynamicQueryRunner.<MatchIndex>d__7.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Queries\Dynamic\DynamicQueryRunner.cs:line 102
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Queries.Dynamic.DynamicQueryRunner.<ExecuteQuery>d__3.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Queries\Dynamic\DynamicQueryRunner.cs:line 39
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Queries.QueryRunner.<ExecuteQuery>d__5.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Queries\QueryRunner.cs:line 53
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Handlers.QueriesHandler.<Query>d__3.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Handlers\QueriesHandler.cs:line 123
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Handlers.QueriesHandler.<Post>d__0.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Handlers\QueriesHandler.cs:line 51
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Routing.RequestRouter.<HandlePath>d__5.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Routing\RequestRouter.cs:line 107
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
at Raven.Server.RavenServerStartup.<RequestHandler>d__11.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\RavenServerStartup.cs:line 159. Response: {"Error":"Raven.Client.Exceptions.Cluster.CommandExecutionException: Cannot execute command of type PutAutoIndexCommand for database <my-database> ---> System.NotSupportedException: Can not update auto-index: Auto/Orders/ByCreatedBy.IdAndOrderNumberAndWorkspace\r\n at Raven.Client.ServerWide.DatabaseRecord.AddIndex(AutoIndexDefinition definition) in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Client\\ServerWide\\DatabaseRecord.cs:line 119\r\n at Raven.Server.ServerWide.Commands.Indexes.PutAutoIndexCommand.UpdateDatabaseRecord(DatabaseRecord record, Int64 etag) in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\ServerWide\\Commands\\Indexes\\PutAutoIndexCommand.cs:line 34\r\n at Raven.Server.ServerWide.ClusterStateMachine.UpdateDatabase(TransactionOperationContext context, String type, BlittableJsonReaderObject cmd, Int64 index, Leader leader, ServerStore serverStore) in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\ServerWide\\ClusterStateMachine.cs:line 802\r\n --- End of inner exception stack trace ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Rachis.RachisConsensus.<PutAsync>d__92.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Rachis\\RachisConsensus.cs:line 589\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.ServerWide.ServerStore.<SendToLeaderAsyncInternal>d__124.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\ServerWide\\ServerStore.cs:line 1479\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Indexes.IndexStore.<CreateIndex>d__23.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Indexes\\IndexStore.cs:line 435\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Queries.Dynamic.DynamicQueryRunner.<MatchIndex>d__7.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Queries\\Dynamic\\DynamicQueryRunner.cs:line 102\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Queries.Dynamic.DynamicQueryRunner.<ExecuteQuery>d__3.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Queries\\Dynamic\\DynamicQueryRunner.cs:line 39\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Queries.QueryRunner.<ExecuteQuery>d__5.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Queries\\QueryRunner.cs:line 53\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Handlers.QueriesHandler.<Query>d__3.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Handlers\\QueriesHandler.cs:line 123\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Handlers.QueriesHandler.<Post>d__0.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Handlers\\QueriesHandler.cs:line 51\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Routing.RequestRouter.<HandlePath>d__5.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Routing\\RequestRouter.cs:line 107\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()\r\n at Raven.Server.RavenServerStartup.<RequestHandler>d__11.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\RavenServerStartup.cs:line 159","Message":"Cannot execute command of type PutAutoIndexCommand for database <my-database>","Type":"Raven.Client.Exceptions.Cluster.CommandExecutionException","Url":"/databases/<my-database>/queries?query-hash=11022226452836968979"}
</code>```

答:
This was reported and fixed in nightly:

issues.hibernatingrhinos.com/issue/RavenDB-7919

ContentLicense: CC BY-SA 3.0

Body:
I am using a RavenDB 4 RC 2 database. Some of my database auto generated indexes keep 'freezing' and causing errors in my API. Deleting the frozen index provides a short term solution. But even though I am regenerating them, it just a matter of time before they 'freeze' again.

FYI => They get an orange colour state in the RavenDb Studio instead of the normal green status colour. I had this with the beta and RC1 as well. So the timeframe in which this is happening is a few months.

Does anyone know how I can fix this? See full Stacktrace below.

Failed to generate order number Raven.Client.Exceptions.Cluster.CommandExecutionException: Cannot execute command of type PutAutoIndexCommand for database <my-database> ---> System.NotSupportedException: Can not update auto-index: Auto/Orders/ByCreatedBy.IdAndOrderNumberAndWorkspace
at Raven.Client.ServerWide.DatabaseRecord.AddIndex(AutoIndexDefinition definition) in C:\Builds\RavenDB-4.0-RC\src\Raven.Client\ServerWide\DatabaseRecord.cs:line 119
at Raven.Server.ServerWide.Commands.Indexes.PutAutoIndexCommand.UpdateDatabaseRecord(DatabaseRecord record, Int64 etag) in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\ServerWide\Commands\Indexes\PutAutoIndexCommand.cs:line 34
at Raven.Server.ServerWide.ClusterStateMachine.UpdateDatabase(TransactionOperationContext context, String type, BlittableJsonReaderObject cmd, Int64 index, Leader leader, ServerStore serverStore) in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\ServerWide\ClusterStateMachine.cs:line 802
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Rachis.RachisConsensus.<PutAsync>d__92.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Rachis\RachisConsensus.cs:line 589
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.ServerWide.ServerStore.<SendToLeaderAsyncInternal>d__124.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\ServerWide\ServerStore.cs:line 1479
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Indexes.IndexStore.<CreateIndex>d__23.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Indexes\IndexStore.cs:line 435
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Queries.Dynamic.DynamicQueryRunner.<MatchIndex>d__7.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Queries\Dynamic\DynamicQueryRunner.cs:line 102
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Queries.Dynamic.DynamicQueryRunner.<ExecuteQuery>d__3.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Queries\Dynamic\DynamicQueryRunner.cs:line 39
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Queries.QueryRunner.<ExecuteQuery>d__5.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Queries\QueryRunner.cs:line 53
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Handlers.QueriesHandler.<Query>d__3.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Handlers\QueriesHandler.cs:line 123
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Documents.Handlers.QueriesHandler.<Post>d__0.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Documents\Handlers\QueriesHandler.cs:line 51
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Server.Routing.RequestRouter.<HandlePath>d__5.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\Routing\RequestRouter.cs:line 107
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
at Raven.Server.RavenServerStartup.<RequestHandler>d__11.MoveNext() in C:\Builds\RavenDB-4.0-RC\src\Raven.Server\RavenServerStartup.cs:line 159. Response: {"Error":"Raven.Client.Exceptions.Cluster.CommandExecutionException: Cannot execute command of type PutAutoIndexCommand for database <my-database> ---> System.NotSupportedException: Can not update auto-index: Auto/Orders/ByCreatedBy.IdAndOrderNumberAndWorkspace\r\n at Raven.Client.ServerWide.DatabaseRecord.AddIndex(AutoIndexDefinition definition) in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Client\\ServerWide\\DatabaseRecord.cs:line 119\r\n at Raven.Server.ServerWide.Commands.Indexes.PutAutoIndexCommand.UpdateDatabaseRecord(DatabaseRecord record, Int64 etag) in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\ServerWide\\Commands\\Indexes\\PutAutoIndexCommand.cs:line 34\r\n at Raven.Server.ServerWide.ClusterStateMachine.UpdateDatabase(TransactionOperationContext context, String type, BlittableJsonReaderObject cmd, Int64 index, Leader leader, ServerStore serverStore) in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\ServerWide\\ClusterStateMachine.cs:line 802\r\n --- End of inner exception stack trace ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Rachis.RachisConsensus.<PutAsync>d__92.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Rachis\\RachisConsensus.cs:line 589\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.ServerWide.ServerStore.<SendToLeaderAsyncInternal>d__124.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\ServerWide\\ServerStore.cs:line 1479\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Indexes.IndexStore.<CreateIndex>d__23.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Indexes\\IndexStore.cs:line 435\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Queries.Dynamic.DynamicQueryRunner.<MatchIndex>d__7.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Queries\\Dynamic\\DynamicQueryRunner.cs:line 102\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Queries.Dynamic.DynamicQueryRunner.<ExecuteQuery>d__3.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Queries\\Dynamic\\DynamicQueryRunner.cs:line 39\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Queries.QueryRunner.<ExecuteQuery>d__5.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Queries\\QueryRunner.cs:line 53\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Handlers.QueriesHandler.<Query>d__3.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Handlers\\QueriesHandler.cs:line 123\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Documents.Handlers.QueriesHandler.<Post>d__0.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Documents\\Handlers\\QueriesHandler.cs:line 51\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Raven.Server.Routing.RequestRouter.<HandlePath>d__5.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\Routing\\RequestRouter.cs:line 107\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()\r\n at Raven.Server.RavenServerStartup.<RequestHandler>d__11.MoveNext() in C:\\Builds\\RavenDB-4.0-RC\\src\\Raven.Server\\RavenServerStartup.cs:line 159","Message":"Cannot execute command of type PutAutoIndexCommand for database <my-database>","Type":"Raven.Client.Exceptions.Cluster.CommandExecutionException","Url":"/databases/<my-database>/queries?query-hash=11022226452836968979"}


问:
Django Form save - circular dependency
I have 2 models Account and User. An Account can have multiple users.

When the first User(Owner) is created at the same time the Account will be created.

Because User have a ForeignKey to Account, I need first to create the Account, and after the User.

But Account had a field created_by which is request.user. So is a circular problem.

I think I need to create first the Account and created_by to be a superuser(first) and than create the User, and update the Account with the new user.

```<code>class Account(MetaData):
    name = models.CharField(max_length=255)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,
                                   related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE)

class User(AbstractBaseUser):
    account = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='owner')
</code>```

How can I do that ?

I need this only first time, for the first user, because after that for the other users the Account will exist.

When I'm saying first user, I'm not referring to staff users (as superusers), but normal users for which an account is mandatory thru a register form.

blank=True is just for staff members.

答:
Since it's only a problem for the first user, you might want to override the method create_superuser of the manager to add the account. Also, since you've defined the ForeignKeys with null=True, it should not be a problem to first create a superuser (using super().create_superuser()) and then create the account and attach it to the superuser.

When deploying your site the first time, you'll have to manually run the ./manage.py createsuperuser command.

Title: Django Form save - circular dependency

Body:
I have 2 models Account and User. An Account can have multiple users.

When the first User(Owner) is created at the same time the Account will be created.

Because User have a ForeignKey to Account, I need first to create the Account, and after the User.

But Account had a field created_by which is request.user. So is a circular problem.

I think I need to create first the Account and created_by to be a superuser(first) and than create the User, and update the Account with the new user.

class Account(MetaData):
    name = models.CharField(max_length=255)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,
                                   related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE)

class User(AbstractBaseUser):
    account = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='owner')

How can I do that ?

I need this only first time, for the first user, because after that for the other users the Account will exist.

When I'm saying first user, I'm not referring to staff users (as superusers), but normal users for which an account is mandatory thru a register form.

blank=True is just for staff members.


问:
Foreach syntax issue have used code in different project now broken

So my problem is I do not understand why I am getting this error as I have used this code previously for a different task and it worked. Here is the sample code:

```<code>  <?php

  include('assets/php/sql/con.php');

  if (isset($_GET['age'])) {
    $AGE = $_GET['age'];
    $GENDER = $_GET['gender'];

      $results = DB::query('SELECT * FROM gift_db WHERE age =:age',array(':age' => $_GET['age']))[0]['age'];

      // DB::query('SELECT * FROM gift_db WHERE age=:age', array(':age'=>$_GET['age']));
      $allResults = "";
      foreach ($results as $r) {

        $allResults = $r;

    }
  }
   ?>
</code>```

If anyone would be able to help out that would be amazing. Thanks :)

答:
When use query function this function returned an array but you selected the first element of this array.

$results = DB::query('SELECT * FROM gift_db WHERE age =:age',array(':age' => $_GET['age']))[0]['age'];

Can you try with:

$results = DB::query('SELECT * FROM gift_db WHERE age =:age',array(':age' => (int) $AGE));

It's possible in your code insert any value on age.

PD:Sorry for my English

Body:
So my problem is I do not understand why I am getting this error as I have used this code previously for a different task and it worked. Here is the sample code:

  <?php

  include('assets/php/sql/con.php');

  if (isset($_GET['age'])) {
    $AGE = $_GET['age'];
    $GENDER = $_GET['gender'];

      $results = DB::query('SELECT * FROM gift_db WHERE age =:age',array(':age' => $_GET['age']))[0]['age'];

      // DB::query('SELECT * FROM gift_db WHERE age=:age', array(':age'=>$_GET['age']));
      $allResults = "";
      foreach ($results as $r) {

        $allResults = $r;

    }
  }
   ?>

If anyone would be able to help out that would be amazing. Thanks :)


问:
Push Remote Notification to ViewController from AppDelegate
I have a problem am trying to solve.
I have a tabbar as my rootViewController defined like this
window?.rootViewController = MainTabViewController()
I need to push to a viewController From a remote push notification with the snippet below, but my app crash with cannot cast MainTabViewController to UINavigationViewController I know I cannot do that cast since MainTabViewController is not embedded in a NavigationViewController. What is the best way to approach this?

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let userInfo = response.notification.request.content.userInfo

    if let type = userInfo["type"] as? String, let data = userInfo["data"] as? String, let title = userInfo["title"] as? String {
        let params = ["type": type, "data": data, "title": title]
        Analytics.AddEvent(title: "Notification Open", params: params)

        let backItem = UIBarButtonItem()
        backItem.title = ""
        let navVC = window?.rootViewController as! UINavigationController
        NSLog("Controller Type: \(navVC.description)")
        navVC.navigationController?.navigationBar.tintColor = .black
        navVC.navigationItem.backBarButtonItem = backItem
        if type == "category_product"{
            //Show product list
            var params = [String: String]()
            params["CategoryName"] = title
            params["CategoryId"] = data
            Analytics.AddEvent(title: "Category Opened", params: params)

            let vc = ProductListingVC()
            vc.categoryName = title
            vc.category_id = data
            vc.hidesBottomBarWhenPushed = false
            navVC.pushViewController(vc, animated: true)
        }
</code>```

答: You have tabBarController as rootViewController and you are type casting it into navigation controller, this is the issue in your code. You need to cast your rootViewController to MainTabViewController and then get the selected tab on your MainTabViewController if there you have navigation controller then push the ProductListingVC controller to that navigation controller else you need to present ProductListingVC.

Body:
I have a problem am trying to solve.
I have a tabbar as my rootViewController defined like this
window?.rootViewController = MainTabViewController()
I need to push to a viewController From a remote push notification with the snippet below, but my app crash with cannot cast MainTabViewController to UINavigationViewController I know I cannot do that cast since MainTabViewController is not embedded in a NavigationViewController. What is the best way to approach this?

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let userInfo = response.notification.request.content.userInfo

    if let type = userInfo["type"] as? String, let data = userInfo["data"] as? String, let title = userInfo["title"] as? String {
        let params = ["type": type, "data": data, "title": title]
        Analytics.AddEvent(title: "Notification Open", params: params)

        let backItem = UIBarButtonItem()
        backItem.title = ""
        let navVC = window?.rootViewController as! UINavigationController
        NSLog("Controller Type: \(navVC.description)")
        navVC.navigationController?.navigationBar.tintColor = .black
        navVC.navigationItem.backBarButtonItem = backItem
        if type == "category_product"{
            //Show product list
            var params = [String: String]()
            params["CategoryName"] = title
            params["CategoryId"] = data
            Analytics.AddEvent(title: "Category Opened", params: params)

            let vc = ProductListingVC()
            vc.categoryName = title
            vc.category_id = data
            vc.hidesBottomBarWhenPushed = false
            navVC.pushViewController(vc, animated: true)
        }


问:
What is the O(n) time algorithm for Union and intersection of two sorted arrays?
The sets a and b have n elements each given in the form of sorted arrays. Present an O(n) time algorithm to compute a union b and a intersection b.</p>

答:
You just have two pointers to each array and you are always moving the one which is lesser or same.

Then if you get two same numbers at both pointers you get intersection. If you want union, you just put the one you have moved. (and if you dont want duplicities for the same numbers, you just have to check if you have already added that number)


问:
Raising event from base class
I understand that one can raise an event in the class that the implementation declaration occurs, but I wish to raise the event at the base class level and have the derived class's  event be raised:

```<code>public interface IFoo
{
    event EventHandler<FooEventArgs> FooValueChanged;
    void RaiseFooValueChanged(IFooView sender, FooEventArgs  e);
}

[TypeDescriptionProvider(typeof(FooBaseImplementor))]
public abstract class FooBase : Control, IFoo
{
    public virtual event EventHandler<FooEventArgs> FooValueChanged;

    public void RaiseFooValueChanged(IFooView sender, FooEventArgs e)
    {
        FooValueChanged(sender, e);
    }
}
</code>```

I cannot have the FooValueChanged event abstract, because then the base class cannot raise  the event. Current the code runs, but the call FooValueChanged(sender, e) throws a NullReferenceException because it doesn't call the derived class's event, only that of the base class.

Where am I going wrong?

I can have the event and the raiser both abstract, but then I need to remember to call FooValueChanged(sender, e) in every single derived class. I'm trying to avoid this while being able to use the Visual Studio designer for derived controls.

答: Why do you need to use an event? Can't you just use an overridden method. The base calls the overridable method, which is 'intercepted' by the derived class, which can then raise an event?</p>

OwnerDisplayName: vanslly

ContentLicense: CC BY-SA 2.5

Title: Raising event from base class

Body:
I understand that one can raise an event in the class that the implementation declaration occurs, but I wish to raise the event at the base class level and have the derived class's  event be raised:

public interface IFoo
{
    event EventHandler<FooEventArgs> FooValueChanged;
    void RaiseFooValueChanged(IFooView sender, FooEventArgs  e);
}

[TypeDescriptionProvider(typeof(FooBaseImplementor))]
public abstract class FooBase : Control, IFoo
{
    public virtual event EventHandler<FooEventArgs> FooValueChanged;

    public void RaiseFooValueChanged(IFooView sender, FooEventArgs e)
    {
        FooValueChanged(sender, e);
    }
}

I cannot have the FooValueChanged event abstract, because then the base class cannot raise  the event. Current the code runs, but the call FooValueChanged(sender, e) throws a NullReferenceException because it doesn't call the derived class's event, only that of the base class.

Where am I going wrong?

I can have the event and the raiser both abstract, but then I need to remember to call FooValueChanged(sender, e) in every single derived class. I'm trying to avoid this while being able to use the Visual Studio designer for derived controls.

LastEditorDisplayName: vanslly

OwnerDisplayName: Mitch Wheat


问:
looping through an array backwards from current position
I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.

What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?

Question Class

```<code>// This file contains questions from QuestionBank
class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}
</code>```

Main Activity.java

```<code>     public class MainActivityextends AppCompatActivity {
                private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
                private int mQuestionNumber = 1; // current question number
            //initialising navigation buttons
                private Button mPrevious;
                private Button mNext;
            private TextView mQuestionText;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_beginner_review);
                    mPrevious = (Button) findViewById(R.id.previous);
                    mNext = (Button) findViewById(R.id.next);
  mQuestionText = (TextView) findViewById(R.id.txtQuestion);
                    // receive the current question number from last activity by Intent

        Intent intent = getIntent();
             currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
                    mNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
    // checking against total number of questions the user has attempted instead of total number of questions from Question Class
    if (mQuestionNumber < currentQuestionNumber) {
             updateQuestion();
                        }
                    });
                    mPrevious.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
            // i want it to loop backwards from here
                        }
                    });

            // logic to update question from array
                private void updateQuestion() {
                    if (mQuestionNumber < mQuestionLibrary.getLength()) {
                        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
                        mQuestionNumber++;
                    }
                }

            }
</code>```

答:
I would change the following methodes:

would remove mQuestionNummer++; from update question.

You can increment mQuestions directly in the onClickMethode of NextButton.

So you can implement your solution simply by decrement mQuestion-- in onClick of previous Button.

Code would look like this:

```<code>public class MainActivityextends AppCompatActivity {
    private QuestionLibraryBeginner mQuestionLibrary = new
    QuestionLibraryBeginner();
    private int mQuestionNumber = 1; // current question number
    //initialising navigation buttons
    private Button mPrevious;
    private Button mNext;
    private TextView mQuestionText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_beginner_review);
        mPrevious = (Button) findViewById(R.id.previous);
        mNext = (Button) findViewById(R.id.next);
        // receive the current question number from last activity by Intent
        Intent intent = getIntent();
        mNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            if (mQuestionNumber < mQuestionLibrary.getLength()) {
                mQuestionNumber++;
                updateQuestion();
            }
        });
        mPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // i want it to loop backwards from here
                            if(mQuestionNumber > 0){
                                mQuestionNumber--;
                                updateQuestion();
                            }
                            else
                                {}//don't do anything to prevent IndexOutOfBounds
            }
    });

    // logic to update question from array
    private void updateQuestion() {
        if (mQuestionNumber < mQuestionLibrary.getLength()) {
            mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
        }
    }

}
</code>```

Body:
I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.

What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?

Question Class

// This file contains questions from QuestionBank
class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}

Main Activity.java

     public class MainActivityextends AppCompatActivity {
                private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
                private int mQuestionNumber = 1; // current question number
            //initialising navigation buttons
                private Button mPrevious;
                private Button mNext;
            private TextView mQuestionText;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_beginner_review);
                    mPrevious = (Button) findViewById(R.id.previous);
                    mNext = (Button) findViewById(R.id.next);
  mQuestionText = (TextView) findViewById(R.id.txtQuestion);
                    // receive the current question number from last activity by Intent

        Intent intent = getIntent();
             currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
                    mNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
    // checking against total number of questions the user has attempted instead of total number of questions from Question Class
    if (mQuestionNumber < currentQuestionNumber) {
             updateQuestion();
                        }
                    });
                    mPrevious.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
            // i want it to loop backwards from here
                        }
                    });

            // logic to update question from array
                private void updateQuestion() {
                    if (mQuestionNumber < mQuestionLibrary.getLength()) {
                        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
                        mQuestionNumber++;
                    }
                }

            }

Body:
I would change the following methodes:

would remove mQuestionNummer++; from update question.

You can increment mQuestions directly in the onClickMethode of NextButton.

So you can implement your solution simply by decrement mQuestion-- in onClick of previous Button.

Code would look like this:

public class MainActivityextends AppCompatActivity {
    private QuestionLibraryBeginner mQuestionLibrary = new
    QuestionLibraryBeginner();
    private int mQuestionNumber = 1; // current question number
    //initialising navigation buttons
    private Button mPrevious;
    private Button mNext;
    private TextView mQuestionText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_beginner_review);
        mPrevious = (Button) findViewById(R.id.previous);
        mNext = (Button) findViewById(R.id.next);
        // receive the current question number from last activity by Intent
        Intent intent = getIntent();
        mNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            if (mQuestionNumber < mQuestionLibrary.getLength()) {
                mQuestionNumber++;
                updateQuestion();
            }
        });
        mPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // i want it to loop backwards from here
                            if(mQuestionNumber > 0){
                                mQuestionNumber--;
                                updateQuestion();
                            }
                            else
                                {}//don't do anything to prevent IndexOutOfBounds
            }
    });

    // logic to update question from array
    private void updateQuestion() {
        if (mQuestionNumber < mQuestionLibrary.getLength()) {
            mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
        }
    }

}


问:
Divide num by (num / 10) recursively
I'm trying to write a function that divides a number by his tens recursively.

For ex: Given the number 555, the function will return 2:

555 / 55 / 5 = 2

The following code outputs 11:

555 / (55 / 5) = 50

function recursion(num){
    return num < 10 ? num : Math.floor(num / recursion(Math.floor(num / 10)));
}

console.log(recursion(555));```

How should the desired function to be programmed recursively yet conventionally?

答:
Try this one. </p>

```<code>function int recursion(int num) {

    var count = 0;
    var remainder = num/10;

    if remainder > 0 {

        count = recursion(remainder);
        count += 1;
    }

    return count;
}

recursion(5555);
</code>```

Title: Divide num by (num / 10) recursively

Body:
I'm trying to write a function that divides a number by his tens recursively.

For ex: Given the number 555, the function will return 2:

555 / 55 / 5 = 2

The following code outputs 11:

555 / (55 / 5) = 50

function recursion(num){
    return num < 10 ? num : Math.floor(num / recursion(Math.floor(num / 10)));
}

console.log(recursion(555));

How should the desired function to be programmed recursively yet conventionally?

Body:
Try this one.

function int recursion(int num) {

    var count = 0;
    var remainder = num/10;

    if remainder > 0 {

        count = recursion(remainder);
        count += 1;
    }

    return count;
}

recursion(5555);


问:
How do I change the order of columns in a Julia DataFrame?
Suppose I have a DataFrame like this:

```<code>julia> df = DataFrame(a = [1,2,3], b = [3,4,5])
3×2 DataFrames.DataFrame
│ Row │ a │ b │
├─────┼───┼───┤
│ 1   │ 1 │ 3 │
│ 2   │ 2 │ 4 │
│ 3   │ 3 │ 5 │
</code>```

How do I subsequently change the order of columns so that column :b comes before column :a?

答:
It's simple enough but it took a while to dawn on me so I thought I'd post it here:</p>
```<code>julia> df = df[!, [:b, :a]]
3×2 DataFrames.DataFrame
│ Row │ b │ a │
├─────┼───┼───┤
│ 1   │ 3 │ 1 │
│ 2   │ 4 │ 2 │
│ 3   │ 5 │ 3 │
</code>```

Body:
Suppose I have a DataFrame like this:

julia> df = DataFrame(a = [1,2,3], b = [3,4,5])
3×2 DataFrames.DataFrame
│ Row │ a │ b │
├─────┼───┼───┤
│ 1   │ 1 │ 3 │
│ 2   │ 2 │ 4 │
│ 3   │ 3 │ 5 │

How do I subsequently change the order of columns so that column :b comes before column :a?

Body:
It's simple enough but it took a while to dawn on me so I thought I'd post it here:

julia> df = df[!, [:b, :a]]
3×2 DataFrames.DataFrame
│ Row │ b │ a │
├─────┼───┼───┤
│ 1   │ 3 │ 1 │
│ 2   │ 4 │ 2 │
│ 3   │ 5 │ 3 │

ContentLicense: CC BY-SA 4.0


问:
When creating a char array, its length is different from required
I need to create a newStr array with length of str array. But after its created the strlen(newStr) is totally different. For example if a strlen(str) is 5, then strlen(newStr) would be 22. What am I doing wrong?

```<code>#include <iostream>
using namespace std;
int main()
{
    char *str = "Hello";
    int strLength = strlen(str);
    std::cout << "str = " << str << "\t" << "strLength = " << strLength << std::endl;
    char *newStr = new char[strLength];
    std::cout << "newStrLength = " << strlen(newStr) << std::endl;
    system("pause");
    return 0;
}
</code>```

In the console will be

```<code>str = Hello     strLength = 5
newStrLength = 22
</code>```

答:
You are mixing up two different concepts:

new[] allocates uninitialized memory block to your program,

strlen(...) counts characters in a C string before null terminator '\0' is reached.

The size of the allocated block cannot be measured with strlen. In fact, it cannot be measured at all - your program must know how much memory it has requested, and make sure that it does not go past the limit.

Once you allocated new char[n], you can safely copy a C string of length up to n-1 into that block. C++ guarantees that enough memory would be there for you to complete the operation successfully:

```<code>char *newStr = new char[strLength+1]; // Note +1 for null terminator
strcpy(newStr, str);
std::cout << "newStrLength = " << strlen(newStr) << std::endl;
delete[] newStr;
</code>```

Body:
I need to create a newStr array with length of str array. But after its created the strlen(newStr) is totally different. For example if a strlen(str) is 5, then strlen(newStr) would be 22. What am I doing wrong?

#include <iostream>
using namespace std;
int main()
{
    char *str = "Hello";
    int strLength = strlen(str);
    std::cout << "str = " << str << "\t" << "strLength = " << strLength << std::endl;
    char *newStr = new char[strLength];
    std::cout << "newStrLength = " << strlen(newStr) << std::endl;
    system("pause");
    return 0;
}

In the console will be

str = Hello     strLength = 5
newStrLength = 22

Body:
You are mixing up two different concepts:

new[] allocates uninitialized memory block to your program,

strlen(...) counts characters in a C string before null terminator '\0' is reached.

The size of the allocated block cannot be measured with strlen. In fact, it cannot be measured at all - your program must know how much memory it has requested, and make sure that it does not go past the limit.

Once you allocated new char[n], you can safely copy a C string of length up to n-1 into that block. C++ guarantees that enough memory would be there for you to complete the operation successfully:

char *newStr = new char[strLength+1]; // Note +1 for null terminator
strcpy(newStr, str);
std::cout << "newStrLength = " << strlen(newStr) << std::endl;
delete[] newStr;


问:
How to check if a subnode exists using xmlstarlet and bash?
I have a script that is adding a subnode to my XML file, and it is working fine.

Problem is I'm running this script lots of time and I only want to add my subnode once, So what I need is to check if it exists and if it does do nothing if it doesn't exist I want to create it. (In my example create subnode with the name 66.66.66)

```<code>#!/bin/bash
LOCK_BRANCH="66.66.66"
#Adding a new subnode to certain nodes
xmlstarlet ed -L --subnode  "/configurations/rules" --type elem -n rule config.xml

#Adding text to the new node
xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n name -v "$LOCK_BRANCH" config.xml
xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n repo -v "mqm" config.xml
xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n branch -v "refs/heads/12.55.99" config.xml
xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n emailTo -v "imichael@gmail.com" config.xml
xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n path -v "Server/.*/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/" config.xml
</code>```

This is the original XML file:

```<code><?xml version="1.0" encoding="utf-8" standalone="no"?>
<configurations>
    <smtpHost>smtp3.gmail.com</smtpHost>
    <smtpPort>25</smtpPort>
    <emailFrom>GitPushNotifier@gmail.com</emailFrom>
    <emailSubject>Push notification</emailSubject>
    <!-- Stash general URL-->
    <gitViewerURL>http://server0005.gmail.net:7990/projects/</gitViewerURL>
  <rules>
    <rule>
        <name>test_12.55.4</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.4</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.10</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.10</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.6</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.6</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
  </rules>
</configurations>
</code>```

答:
After looking a lot I found out that nobody using this option and there is a good reason for it, I can just delete the subnode I want to create prior to its creation, In the case that it already exists it will be deleted and in the case that it doesn't exist it will do nothing - So I will be able to create it later on.

So this is the final script:

```<code>    #!/bin/bash
    LOCK_BRANCH="66.66.66"
    #Delete subnode $LOCK_BRANCH if already exist
    xmlstarlet ed -L -d  "/configurations/rules/rule[name='$LOCK_BRANCH']" config.xml
    #Adding a new subnode to certain nodes
    xmlstarlet ed -L --subnode  "/configurations/rules" --type elem -n rule config.xml

    #Adding text to the new node
    xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n name -v "$LOCK_BRANCH" config.xml
    xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n repo -v "mqm" config.xml
    xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n branch -v "refs/heads/12.55.99" config.xml
    xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n emailTo -v "imichael@gmail.com" config.xml
    xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n path -v "Server/.*/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/" config.xml
</code>```

Body:
I have a script that is adding a subnode to my XML file, and it is working fine.

Problem is I'm running this script lots of time and I only want to add my subnode once, So what I need is to check if it exists and if it does do nothing if it doesn't exist I want to create it. (In my example create subnode with the name 66.66.66)

#!/bin/bash
LOCK_BRANCH="66.66.66"
#Adding a new subnode to certain nodes
xmlstarlet ed -L --subnode  "/configurations/rules" --type elem -n rule config.xml

#Adding text to the new node
xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n name -v "$LOCK_BRANCH" config.xml
xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n repo -v "mqm" config.xml
xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n branch -v "refs/heads/12.55.99" config.xml
xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n emailTo -v "imichael@gmail.com" config.xml
xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n path -v "Server/.*/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/" config.xml

This is the original XML file:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<configurations>
    <smtpHost>smtp3.gmail.com</smtpHost>
    <smtpPort>25</smtpPort>
    <emailFrom>GitPushNotifier@gmail.com</emailFrom>
    <emailSubject>Push notification</emailSubject>

    <gitViewerURL>http://server0005.gmail.net:7990/projects/</gitViewerURL>
  <rules>
    <rule>
        <name>test_12.55.4</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.4</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.10</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.10</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.6</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.6</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
  </rules>
</configurations>

Body:
After looking a lot I found out that nobody using this option and there is a good reason for it, I can just delete the subnode I want to create prior to its creation, In the case that it already exists it will be deleted and in the case that it doesn't exist it will do nothing - So I will be able to create it later on.

So this is the final script:

    #!/bin/bash
    LOCK_BRANCH="66.66.66"
    #Delete subnode $LOCK_BRANCH if already exist
    xmlstarlet ed -L -d  "/configurations/rules/rule[name='$LOCK_BRANCH']" config.xml
    #Adding a new subnode to certain nodes
    xmlstarlet ed -L --subnode  "/configurations/rules" --type elem -n rule config.xml

    #Adding text to the new node
    xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n name -v "$LOCK_BRANCH" config.xml
    xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n repo -v "mqm" config.xml
    xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n branch -v "refs/heads/12.55.99" config.xml
    xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n emailTo -v "imichael@gmail.com" config.xml
    xmlstarlet ed -L --subnode "/configurations/rules/rule[last()]" --type elem -n path -v "Server/.*/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/" config.xml


问:
Remove # from url in react
I am creating a project using reactjs.In my project i want to remove # from the url. Currently i am using the react-router version 4. here is my code</p>

```<code> import { HashRouter as Router, Route,browserHistory } from 'react-router-dom';
<Router history={browserHistory} >
  <App>
    <Route  path="/dashboard" component={Dashboard} />
    <Route path="/revenue" component={RevenueReports} />
</App>
 </Router>,
</code>```

答:
browserHistory is not available in latest react-router-dom. However BrowserRouter uses the default as browserHistory and you could simply do

```<code>import { BrowserRouter as Router, Route } from 'react-router-dom';
<Router >
  <App>
    <Route  path="/dashboard" component={Dashboard} />
    <Route path="/revenue" component={RevenueReports} />
  </App>
</Router>,
</code>```

According to the docs:

A BrowserRouter is a <Router> that uses the HTML5 history API
  (pushState, replaceState and the popstate event) to keep your UI in
  sync with the URL.

Title: Remove # from url in react

Body:
I am creating a project using reactjs.In my project i want to remove # from the url. Currently i am using the react-router version 4. here is my code

 import { HashRouter as Router, Route,browserHistory } from 'react-router-dom';
<Router history={browserHistory} >
  <App>
    <Route  path="/dashboard" component={Dashboard} />
    <Route path="/revenue" component={RevenueReports} />
</App>
 </Router>,

Body:
browserHistory is not available in latest react-router-dom. However BrowserRouter uses the default as browserHistory and you could simply do

import { BrowserRouter as Router, Route } from 'react-router-dom';
<Router >
  <App>
    <Route  path="/dashboard" component={Dashboard} />
    <Route path="/revenue" component={RevenueReports} />
  </App>
</Router>,

According to the docs:

A BrowserRouter is a <Router> that uses the HTML5 history API
  (pushState, replaceState and the popstate event) to keep your UI in
  sync with the URL.


问:
Vertically center text in a table header
I'm new to CSS and HTML and I'm trying to vertically center some text in a table header. At the moment the text is aligned with the top of the table cell. I was unsuccessful with vertical-align: middle;, and the only solution seems to be to add padding-top to match the space underneath the text. However this is not the best solution because I would like to have the text fit snugly within the table cell. Any ideas are appreciated.

body {
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    text-align: center;
    color: black;
    background-size: 100%;
    padding:0;
}

.mytable {
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  width: 80%;
}

.mytable thead th {
  background-color: #DDEFEF;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  /*padding: 30px;*/
  text-align: center;
  vertical-align: middle;
}

.mytable tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="myWebPage" style="display:block">
  <br><br><br><br>
  <h3>Page title here</h3><br><br><br>

  <table class="mytable" align="center">
    <thead>
      <tr>
        <th><u>Resource</u><br><br><br></th>
        <th><u>Contact</u><br><br><br></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th align="left">Resource 1<br><br></th>
        <th align="left" width=35%;>999-999-9999<br> <br></th>
      </tr>
      <tr>
        <th align="left">Resource 2<br><br></th>
        <th align="left">888-888-8888<br><br></th>
      </tr>
      <tr>
        <th align="left">Resource 3<br><br></th>
        <th align="left" width=35%;>777-777-7777<br> <br></th>
      </tr>
    </tbody>
  </table>
</div></code>```

答:
Don't use
 tags for layout - that's a no-go! It will mess up whatever you try concerning vertical alignment and top/bottom padding and margins, like in the code in your question.

Erase them all and use top and bottom padding instead.

If still needed, use vertical-align,  but in most cases you won't need it. And use the td tag for cells in the tbody, not th.

body {
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    text-align: center;
    color: black;
    background-size: 100%;
    padding:0;
}
#myWebPage > h3 {
  padding: 40px 0;
}

.mytable {
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  width: 80%;
}

.mytable thead th {
  background-color: #DDEFEF;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  padding: 30px 0;
  /*padding: 30px;*/
  text-align: center;
  vertical-align: middle;
}

.mytable tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="myWebPage">
  <h3>Page title here</h3>
  <table class="mytable" align="center">
    <thead>
      <tr>
        <th><u>Resource</u></th>
        <th><u>Contact</u></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td align="left">Resource 1</td>
        <td align="left" width=35%;>999-999-9999</td>
      </tr>
      <tr>
        <td align="left">Resource 2</td>
        <td align="left">888-888-8888</td>
      </tr>
      <tr>
        <td align="left">Resource 3</td>
        <td align="left" width=35%;>777-777-7777</td>
      </tr>
    </tbody>
  </table>
</div></code>```

Body:
I'm new to CSS and HTML and I'm trying to vertically center some text in a table header. At the moment the text is aligned with the top of the table cell. I was unsuccessful with vertical-align: middle;, and the only solution seems to be to add padding-top to match the space underneath the text. However this is not the best solution because I would like to have the text fit snugly within the table cell. Any ideas are appreciated.

body {
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    text-align: center;
    color: black;
    background-size: 100%;
    padding:0;
}

.mytable {
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  width: 80%;
}

.mytable thead th {
  background-color: #DDEFEF;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  /*padding: 30px;*/
  text-align: center;
  vertical-align: middle;
}

.mytable tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 30px;
}

Page title here

        Resource

        Contact

        Resource 1

        999-999-9999

        Resource 2

        888-888-8888

        Resource 3

        777-777-7777

Body:
Don't use <br> tags for layout - that's a no-go! It will mess up whatever you try concerning vertical alignment and top/bottom padding and margins, like in the code in your question.

Erase them all and use top and bottom padding instead.

If still needed, use vertical-align,  but in most cases you won't need it. And use the td tag for cells in the tbody, not th.

body {
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    text-align: center;
    color: black;
    background-size: 100%;
    padding:0;
}
#myWebPage > h3 {
  padding: 40px 0;
}

.mytable {
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  width: 80%;
}

.mytable thead th {
  background-color: #DDEFEF;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  padding: 30px 0;
  /*padding: 30px;*/
  text-align: center;
  vertical-align: middle;
}

.mytable tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 30px;
}

<div id="myWebPage">
  <h3>Page title here</h3>
  <table class="mytable" align="center">
    <thead>
      <tr>
        <th><u>Resource</u></th>
        <th><u>Contact</u></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td align="left">Resource 1</td>
        <td align="left" width=35%;>999-999-9999</td>
      </tr>
      <tr>
        <td align="left">Resource 2</td>
        <td align="left">888-888-8888</td>
      </tr>
      <tr>
        <td align="left">Resource 3</td>
        <td align="left" width=35%;>777-777-7777</td>
      </tr>
    </tbody>
  </table>
</div>


问:
How to run a Python script by adding its path to Environment variables?
I have a python script at C:\users\harrypoter\Documents. (lets assume as sample.py).
Now I added Python path(C:\python) and Documents folder path(C:\Users\harrypoter\Documents) to Environment Varialbes and tried typing in command prompt sample.py and sample but it saying " sample is not a recognized..."

Where have i went wrong?

答:
I also faced similar issues. So include Python PATH in Environment Variables in

Control Panel\All Control Panel Items\System -> Select Advanced System Settings -> go to Advanced Tab -> Select Environment Variables -> Go to bottom Pan -> Add the python path after ;

After that a restart may be required.

Should be used like python sample.py from any path of command path


答:
The way strlen works is that it examines the contents of the string passed to it, and counts how many characters there are until the first terminating character.  The terminating character for a string is '\0' (or 0).

What you've done is asked for the length of a string that you've not assigned any value to; leading to strlen examining random memory; looking for the first 0.  In this case, it found it 22 bytes further down; but it could be anything.  It could even crash because you start looking into memory you don't have read access to.

The best way to resolve this is to use std::string and then you can call length and other helper functions without having to worry about the underlying pointers too much; which will also resolve your memory leak.

Title: When creating a char array, its length is different from required


问:
How to make KnokoutJS and ClipboardJS work together?
I try to copy to clipboard some information from Knockout foreach:

```<code><tbody data-bind="foreach: selections">
    <tr>
        <td>
            <a href="#" class="copy_btn" data-bind="attr: { 'data-clipboard-text' : name}"><i class="fa fa-copy"></i></a>
        </td>
    </tr>
</tbody>
</code>```

with ClipboardJS:

```<code>var btns = document.querySelectorAll('a.copy_btn');
var clipboard = new Clipboard(btns);

clipboard.on('success', function (e) {
    console.log(e);
});
clipboard.on('error', function (e) {
    console.log(e);
});
</code>```

But it's not copying.
What I'm doing wrong?

答:
Alrighty, thanks @devspec for your initial answer. I built on it in some crucial ways:

so my final binding handler is:

```<code>ko.bindingHandlers.clipboard = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
            // This will be called when the binding is first applied to an element
            // Set up any initial state, event handlers, etc. here
            var options = ko.unwrap(valueAccessor());
            if(options.textComputed) {
                options.text = function(nodeToIgnore) { return options.textComputed(); };
            }

            if(options.onmodal) {
                options.container = element;
            }

            var cboard = new Clipboard(element, options);
            if(options.success) {
                cboard.on('success', options.success);
            }
            if(options.error) {
                cboard.on('error', options.error);
            }

            ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
                        // This will be called when the element is removed by Knockout or
                        // if some other part of your code calls ko.removeNode(element)
                        cboard.destroy();
                    });
        },
}
</code>```

And an example of usage is:

The Html:

```<code><a href="#" data-bind="clipboard: { onmodal: true, textComputed: command, success: function(event) { copyCommandResult(true, event); },
error: function(event) { copyCommandResult(false, event); }}"><small
    data-bind="text: clipboardLink ">copy to clipboard</small></a>
</code>```

on the view model command is a computed, if it was a function that returned a string (without an argument) you could use the text attribute only

And the copyCommandResult is simply:

```<code> self.copyCommandResult = function(success, e) {
//    console.log("Copy to clipboard success? " + success)
//    console.info('Action:', e.action);
//    console.info('Text:', e.text);
//    console.info('Trigger:', e.trigger);

    if(success) {
      self.clipboardLink("Copied successfully!");
    } else {
      self.clipboardLink("Could not copy to clipboard");
    }
    setTimeout(function(){ self.clipboardLink(DEFAULT_CLIPBOARD_LINK_TEXT); }, 3000);

  }
</code>```

Body:
I try to copy to clipboard some information from Knockout foreach:

with ClipboardJS:

var btns = document.querySelectorAll('a.copy_btn');
var clipboard = new Clipboard(btns);

clipboard.on('success', function (e) {
    console.log(e);
});
clipboard.on('error', function (e) {
    console.log(e);
});

But it's not copying.
What I'm doing wrong?

Body:
Alrighty, thanks @devspec for your initial answer. I built on it in some crucial ways:

so my final binding handler is:

ko.bindingHandlers.clipboard = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
            // This will be called when the binding is first applied to an element
            // Set up any initial state, event handlers, etc. here
            var options = ko.unwrap(valueAccessor());
            if(options.textComputed) {
                options.text = function(nodeToIgnore) { return options.textComputed(); };
            }

            if(options.onmodal) {
                options.container = element;
            }

            var cboard = new Clipboard(element, options);
            if(options.success) {
                cboard.on('success', options.success);
            }
            if(options.error) {
                cboard.on('error', options.error);
            }

            ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
                        // This will be called when the element is removed by Knockout or
                        // if some other part of your code calls ko.removeNode(element)
                        cboard.destroy();
                    });
        },
}

And an example of usage is:

The Html:

<a href="#" data-bind="clipboard: { onmodal: true, textComputed: command, success: function(event) { copyCommandResult(true, event); },
error: function(event) { copyCommandResult(false, event); }}"><small
    data-bind="text: clipboardLink ">copy to clipboard</small></a>

on the view model command is a computed, if it was a function that returned a string (without an argument) you could use the text attribute only

And the copyCommandResult is simply:

 self.copyCommandResult = function(success, e) {
//    console.log("Copy to clipboard success? " + success)
//    console.info('Action:', e.action);
//    console.info('Text:', e.text);
//    console.info('Trigger:', e.trigger);

    if(success) {
      self.clipboardLink("Copied successfully!");
    } else {
      self.clipboardLink("Could not copy to clipboard");
    }
    setTimeout(function(){ self.clipboardLink(DEFAULT_CLIPBOARD_LINK_TEXT); }, 3000);

  }


问:
How to reverse a dummy variables from a pandas dataframe
I would like to reverse a dataframe with dummy variables. For example,

from df_input:

```<code>Course_01 Course_02 Course_03
  0           0         1
  1           0         0
  0           1         0
</code>```

To df_output

```<code>   Course
0 03
1 01
2 02
</code>```

I have been looking at the solution provided at Reconstruct a categorical variable from dummies in pandas but it did not work. Please, Any help would be much appreciated.

Many Thanks,
Best Regards,
Carlo

答:
We can use wide_to_long, then select rows that are not equal to zero i.e

```<code>ndf = pd.wide_to_long(df, stubnames='T_', i='id',j='T')

      T_
id  T
id1 30   0
id2 30   1
id1 40   1
id2 40   0

not_dummy = ndf[ndf['T_'].ne(0)].reset_index().drop('T_',1)

   id   T
0  id2  30
1  id1  40
</code>```

Update based on your edit :

```<code>ndf = pd.wide_to_long(df.reset_index(), stubnames='T_',i='index',j='T')

not_dummy = ndf[ndf['T_'].ne(0)].reset_index(level='T').drop('T_',1)

        T
index
1      30
0      40
</code>```

Body:
I would like to reverse a dataframe with dummy variables. For example,

from df_input:

Course_01 Course_02 Course_03
  0           0         1
  1           0         0
  0           1         0

To df_output

   Course
0 03
1 01
2 02

I have been looking at the solution provided at Reconstruct a categorical variable from dummies in pandas but it did not work. Please, Any help would be much appreciated.

Many Thanks,
Best Regards,
Carlo

Body:
We can use wide_to_long, then select rows that are not equal to zero i.e

ndf = pd.wide_to_long(df, stubnames='T_', i='id',j='T')

      T_
id  T
id1 30   0
id2 30   1
id1 40   1
id2 40   0

not_dummy = ndf[ndf['T_'].ne(0)].reset_index().drop('T_',1)

   id   T
0  id2  30
1  id1  40

Update based on your edit :

ndf = pd.wide_to_long(df.reset_index(), stubnames='T_',i='index',j='T')

not_dummy = ndf[ndf['T_'].ne(0)].reset_index(level='T').drop('T_',1)

        T
index
1      30
0      40


问:
EF 4.0 - mapping to readonly property with private field
Is it possible to map following POCO class with EF 4.0?

```<code>public class MyClass
{
  private string _myData;

  public MyClass()
  { }

  public MyClass(string myData)
  {
    _myData = myData;
  }

  public string MyData
  {
    get
    {
      return _myData;
    }
  }
}
</code>```

In NHibernate I think it is possible when I use Access attribute in mapping like:

```<code><class name="MyClass" table="MyTable">
  <property name="MyData" access="field.camelcase-underscore" column="MyCol" type="string" length="50" />
</class>
</code>```

I wonder if there is some Access equivalent in EF 4.0? Currently I'm able to map the class only if I add protected setter to the MyData property:

```<code>  public string MyData
  {
    get
    {
      return _myData;
    }
    protected set
    {
      _myData = value;
    }
  }
</code>```

It works but for legacy classes it means update all properties which don't have setter.

Edit:

I have updated the last code example because it also doesn't work with private setter. Setter has to be at least protected. If the setter is private or doesn't exists following exception is thrown:

System.InvalidOperationException:
  Mapping and metadata information could
  not be found for EntityType
  'MyNamespace.MyClass'.

答:
I played with this little bit and my conclusion is:

I can't map legacy types which don't have setter at all.

I can map types which have private setter but I must set Setter accessibility in EDMX as well. It is not enough to define setter accessibily in POCO class - EDMX must know about it.

Body:
Is it possible to map following POCO class with EF 4.0?

public class MyClass
{
  private string _myData;

  public MyClass()
  { }

  public MyClass(string myData)
  {
    _myData = myData;
  }

  public string MyData
  {
    get
    {
      return _myData;
    }
  }
}

In NHibernate I think it is possible when I use Access attribute in mapping like:

<class name="MyClass" table="MyTable">
  <property name="MyData" access="field.camelcase-underscore" column="MyCol" type="string" length="50" />
</class>

I wonder if there is some Access equivalent in EF 4.0? Currently I'm able to map the class only if I add protected setter to the MyData property:

  public string MyData
  {
    get
    {
      return _myData;
    }
    protected set
    {
      _myData = value;
    }
  }

It works but for legacy classes it means update all properties which don't have setter.

Edit:

I have updated the last code example because it also doesn't work with private setter. Setter has to be at least protected. If the setter is private or doesn't exists following exception is thrown:

System.InvalidOperationException:
  Mapping and metadata information could
  not be found for EntityType
  'MyNamespace.MyClass'.


问:
Invoking callbacks from PowerShell functions
I'm trying to add some callback capabilities to a PowerShell function but I want to be able to define the behaviour of the callbacks outside of the function definition, so basically a very simple Inversion of Control for PowerShell.

I'm trying to be as backward compatible as is practical, and this is what I've come up with so far (error handling removed for brevity):

```<code>$ErrorActionPreference = "Stop";
Set-StrictMode -Version "Latest";

function Invoke-DoSomethingMethod
{
    param
    (
        [hashtable] $Callbacks
    )
    $CallBacks["OnStarted"].Invoke();
    for( $i = 1; $i -le 10; $i++ )
    {
        # ... do something here ...
        $CallBacks["OnProgress"].Invoke($i * 10);
    }
    $CallBacks["OnFinished"].Invoke();
}

$myHostCallbacks = @{
    "OnStarted"  = { write-host "started" }
    "OnProgress" = { write-host "processing $($args[0])%" }
    "OnFinished" = { write-host "finished" }
}

$myFileCallbacks = @{
    "OnStarted"  = { Add-Content "C:\temp\log.txt" "started" }
    "OnProgress" = { Add-Content "C:\temp\log.txt" "processing $($args[0])%" }
    "OnFinished" = { Add-Content "C:\temp\log.txt" "finished" }
}

$myWebCallbacks = @{
    "OnStarted"  = { Invoke-WebRequest -Uri "http://example.org/OnStarted" }
    "OnProgress" = { Invoke-WebRequest -Uri "http://example.org/OnProgress/$($args[0])" }
    "OnFinished" = { Invoke-WebRequest -Uri "http://example.org/OnFinish" }
}

Invoke-DoSomethingMethod -Callbacks $myHostCallbacks;
</code>```

When run, this outputs the following:

```<code>c:\temp>powershell .\callbacks.ps1

started
processing 10%
processing 20%
processing 30%
processing 40%
processing 50%
processing 60%
processing 70%
processing 80%
processing 90%
processing 100%
finished
</code>```

Without using external modules or C# code, is there a more idomatic way of doing this with PowerShell that doesn't rely on matching up the magic strings for callback names and the order of $args[] parameters? (Preferrably compatible with version 2.0).

Cheers,

Mike

Update

For some context, my Invoke-DoSomething function is part of a CI build framework
(https://github.com/ASOS/OctopusStepTemplateCi) which is currently hard-coded to send TeamCity service messages using Write-Host during the build process.

We're interested in supporting other build server products so I'm investigating a way to abstract out the various interactions with the build server into user-definable callbacks like "OnBuildStarted", "OnBuildStepFailed", etc, like you might do with an IoC framework in C#.

This would make it easier to ship support for new build servers from within the project, and also for users to write callbacks for build servers which don't come out-of-the-box.

This might help give a flavour of what I'm trying to do:

```<code>function Invoke-BuildScript
{
    param( [hashtable] $Callbacks )
    $CallBacks["OnBuildStarted"].Invoke();
    ... build script here ...
    $CallBacks["OnBuildFinished"].Invoke();
}

$teamCityCallbacks = @{
    "OnBuildStarted"  = { write-host "started" }
    "OnBuildFinished" = { write-host "finished" }
    "OnBuildError"    = { write-host "error '$($args[0])'" }
}

$jenkinsCallbacks = @{
    "OnBuildStarted"  = { ... }
    "OnBuildFinished" = { ... }
    "OnBuildError"    = { ... }
}

Invoke-BuildScript -Callbacks $teamCityCallbacks;
</code>```

答:
Not so much an answer to my original question about IoC in PowerShell, but I managed to at least hide the magic strings and callback parameters behind some wrapper cmdlets so the callback structure becomes an opaque type:

```<code># knowledge of magic strings and parameter orders confined to here

function Invoke-OnStartedCallback
{
    param
    (
        [hashtable] $Callbacks
    )
    Invoke-Callback -Callbacks $CallBacks -Name "OnStarted";
}

function Invoke-OnProgressCallback
{
    param
    (
        [hashtable] $Callbacks,
        [int]       $PercentComplete
    )
    Invoke-Callback -Callbacks $CallBacks -Name "OnProgress" -Parameters @( $PercentComplete );
}

function Invoke-OnFinishedCallback
{
    param
    (
        [hashtable] $Callbacks
    )
    Invoke-Callback -Callbacks $CallBacks -Name "OnFinished";
}

function New-DoSomethingCallbacks
{
    param
    (
        [scriptblock] $OnStarted,
        [scriptblock] $OnProgress,
        [scriptblock] $OnFinished
    )
    return @{
        "OnStarted"  = $OnStarted
        "OnProgress" = $OnProgress
        "OnFinished" = $OnFinished
    };
}
</code>```

The rest of the code can then be written as:

```<code># no knowledge of magic strings below here

function Invoke-DoSomethingMethod
{
    param
    (
        [hashtable] $Callbacks
    )
    Invoke-OnStartedCallback $CallBacks;
    for( $i = 1; $i -le 10; $i++ )
    {
        # ... do something ...
        Invoke-OnProgressCallback $CallBacks -PercentComplete ($i * 10);
    }
    Invoke-OnFinishedCallback $CallBacks;
}

$myHostCallbacks = New-DoSomethingCallbacks -OnStarted  { write-host "started" } `
                                            -OnProgress { write-host "processing $($args[0])%" } `
                                            -OnFinished { write-host "finished" };

$myFileCallbacks = New-DoSomethingCallbacks -OnStarted  { Add-Content "C:\temp\log.txt" "started" } `
                                            -OnProgress { Add-Content "C:\temp\log.txt" "processing $($args[0])%" } `
                                            -OnFinished { Add-Content "C:\temp\log.txt" "finished" };

$myWebCallbacks  = New-DoSomethingCallbacks -OnStarted  { Invoke-WebRequest -Uri "http://example.org/OnStarted" } `
                                            -OnProgress { Invoke-WebRequest -Uri "http://example.org/OnProgress/$($args[0])" } `
                                            -OnFinished { Invoke-WebRequest -Uri "http://example.org/OnFinish" };

Invoke-DoSomethingMethod -Callbacks $myHostCallbacks;
</code>```

with a small helper cmdlet:

```<code>function Invoke-Callback
{
    param
    (
        [hashtable] $Callbacks,
        [string]    $Name,
        [object[]]  $Parameters
    )
    if( -not $Callbacks.ContainsKey($Name) )
    {
        return;
    }
    $callback = $Callbacks[$Name];
    if( $null -eq $callback )
    {
        return;
    }
    if( $null -eq $Parameters )
    {
        $callback.Invoke();
    }
    else
    {
        $callback.Invoke($Parameters);
    }
}
</code>```

Body:
I'm trying to add some callback capabilities to a PowerShell function but I want to be able to define the behaviour of the callbacks outside of the function definition, so basically a very simple Inversion of Control for PowerShell.

I'm trying to be as backward compatible as is practical, and this is what I've come up with so far (error handling removed for brevity):

$ErrorActionPreference = "Stop";
Set-StrictMode -Version "Latest";

function Invoke-DoSomethingMethod
{
    param
    (
        [hashtable] $Callbacks
    )
    $CallBacks["OnStarted"].Invoke();
    for( $i = 1; $i -le 10; $i++ )
    {
        # ... do something here ...
        $CallBacks["OnProgress"].Invoke($i * 10);
    }
    $CallBacks["OnFinished"].Invoke();
}

$myHostCallbacks = @{
    "OnStarted"  = { write-host "started" }
    "OnProgress" = { write-host "processing $($args[0])%" }
    "OnFinished" = { write-host "finished" }
}

$myFileCallbacks = @{
    "OnStarted"  = { Add-Content "C:\temp\log.txt" "started" }
    "OnProgress" = { Add-Content "C:\temp\log.txt" "processing $($args[0])%" }
    "OnFinished" = { Add-Content "C:\temp\log.txt" "finished" }
}

$myWebCallbacks = @{
    "OnStarted"  = { Invoke-WebRequest -Uri "http://example.org/OnStarted" }
    "OnProgress" = { Invoke-WebRequest -Uri "http://example.org/OnProgress/$($args[0])" }
    "OnFinished" = { Invoke-WebRequest -Uri "http://example.org/OnFinish" }
}

Invoke-DoSomethingMethod -Callbacks $myHostCallbacks;

When run, this outputs the following:

c:\temp>powershell .\callbacks.ps1

started
processing 10%
processing 20%
processing 30%
processing 40%
processing 50%
processing 60%
processing 70%
processing 80%
processing 90%
processing 100%
finished

Without using external modules or C# code, is there a more idomatic way of doing this with PowerShell that doesn't rely on matching up the magic strings for callback names and the order of $args[] parameters? (Preferrably compatible with version 2.0).

Cheers,

Mike

Update

For some context, my Invoke-DoSomething function is part of a CI build framework
(https://github.com/ASOS/OctopusStepTemplateCi) which is currently hard-coded to send TeamCity service messages using Write-Host during the build process.

We're interested in supporting other build server products so I'm investigating a way to abstract out the various interactions with the build server into user-definable callbacks like "OnBuildStarted", "OnBuildStepFailed", etc, like you might do with an IoC framework in C#.

This would make it easier to ship support for new build servers from within the project, and also for users to write callbacks for build servers which don't come out-of-the-box.

This might help give a flavour of what I'm trying to do:

function Invoke-BuildScript
{
    param( [hashtable] $Callbacks )
    $CallBacks["OnBuildStarted"].Invoke();
    ... build script here ...
    $CallBacks["OnBuildFinished"].Invoke();
}

$teamCityCallbacks = @{
    "OnBuildStarted"  = { write-host "started" }
    "OnBuildFinished" = { write-host "finished" }
    "OnBuildError"    = { write-host "error '$($args[0])'" }
}

$jenkinsCallbacks = @{
    "OnBuildStarted"  = { ... }
    "OnBuildFinished" = { ... }
    "OnBuildError"    = { ... }
}

Invoke-BuildScript -Callbacks $teamCityCallbacks;

Body:
Not so much an answer to my original question about IoC in PowerShell, but I managed to at least hide the magic strings and callback parameters behind some wrapper cmdlets so the callback structure becomes an opaque type:

# knowledge of magic strings and parameter orders confined to here

function Invoke-OnStartedCallback
{
    param
    (
        [hashtable] $Callbacks
    )
    Invoke-Callback -Callbacks $CallBacks -Name "OnStarted";
}

function Invoke-OnProgressCallback
{
    param
    (
        [hashtable] $Callbacks,
        [int]       $PercentComplete
    )
    Invoke-Callback -Callbacks $CallBacks -Name "OnProgress" -Parameters @( $PercentComplete );
}

function Invoke-OnFinishedCallback
{
    param
    (
        [hashtable] $Callbacks
    )
    Invoke-Callback -Callbacks $CallBacks -Name "OnFinished";
}

function New-DoSomethingCallbacks
{
    param
    (
        [scriptblock] $OnStarted,
        [scriptblock] $OnProgress,
        [scriptblock] $OnFinished
    )
    return @{
        "OnStarted"  = $OnStarted
        "OnProgress" = $OnProgress
        "OnFinished" = $OnFinished
    };
}

The rest of the code can then be written as:

# no knowledge of magic strings below here

function Invoke-DoSomethingMethod
{
    param
    (
        [hashtable] $Callbacks
    )
    Invoke-OnStartedCallback $CallBacks;
    for( $i = 1; $i -le 10; $i++ )
    {
        # ... do something ...
        Invoke-OnProgressCallback $CallBacks -PercentComplete ($i * 10);
    }
    Invoke-OnFinishedCallback $CallBacks;
}

$myHostCallbacks = New-DoSomethingCallbacks -OnStarted  { write-host "started" } `
                                            -OnProgress { write-host "processing $($args[0])%" } `
                                            -OnFinished { write-host "finished" };

$myFileCallbacks = New-DoSomethingCallbacks -OnStarted  { Add-Content "C:\temp\log.txt" "started" } `
                                            -OnProgress { Add-Content "C:\temp\log.txt" "processing $($args[0])%" } `
                                            -OnFinished { Add-Content "C:\temp\log.txt" "finished" };

$myWebCallbacks  = New-DoSomethingCallbacks -OnStarted  { Invoke-WebRequest -Uri "http://example.org/OnStarted" } `
                                            -OnProgress { Invoke-WebRequest -Uri "http://example.org/OnProgress/$($args[0])" } `
                                            -OnFinished { Invoke-WebRequest -Uri "http://example.org/OnFinish" };

Invoke-DoSomethingMethod -Callbacks $myHostCallbacks;

with a small helper cmdlet:

function Invoke-Callback
{
    param
    (
        [hashtable] $Callbacks,
        [string]    $Name,
        [object[]]  $Parameters
    )
    if( -not $Callbacks.ContainsKey($Name) )
    {
        return;
    }
    $callback = $Callbacks[$Name];
    if( $null -eq $callback )
    {
        return;
    }
    if( $null -eq $Parameters )
    {
        $callback.Invoke();
    }
    else
    {
        $callback.Invoke($Parameters);
    }
}