问:
Gradle clean unable to delete dependent jar
I have a multi-module Gradle 4.4 project - there's a parent build.gradle and then two child Gradle projects, each with their own build.gradle. Both are Java projects (one is for dev code, the other for QA). The dev project is a dependency of the QA project (I have testCompile project(':dev-project') in the QA project's build.gradle). Otherwise there is nothing remotely interesting or unusual in the build.gradle files - they import the java plugin and com.github.johnrengelman.shadow.

If I try to build the parent project twice in a row (no IDEs open, running ./gradlew clean build from Git Bash without Administrator privileges), the build fails:

```<code>09:55:24.449 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Execute clean for :dev-project:clean'
09:55:24.449 [DEBUG] [org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter] Removed task artifact state for {} from context.
09:55:24.450 [DEBUG] [org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter] Finished executing task ':dev-project:clean'
09:55:24.450 [LIFECYCLE] [class org.gradle.internal.buildevents.TaskExecutionLogger] :dev-project:clean FAILED
09:55:24.451 [WARN] [org.gradle.api.Project] :dev-project:clean took 1587ms
09:55:24.451 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Task :dev-project:clean'
09:55:24.451 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Build operation 'Task :dev-project:clean' completed
09:55:24.452 [INFO] [org.gradle.execution.taskgraph.DefaultTaskPlanExecutor] :dev-project:clean (Thread[Task worker for ':',5,main]) completed. Took 1.588 secs.
09:55:24.452 [DEBUG] [org.gradle.internal.work.DefaultWorkerLeaseService] Worker lease root.1.14 completed (1 worker(s) in use)
09:55:24.452 [DEBUG] [org.gradle.internal.resources.AbstractTrackedResourceLock] Task worker for ':': released lock on root.1.14
09:55:24.452 [DEBUG] [org.gradle.internal.resources.AbstractTrackedResourceLock] Task worker for ':': released lock on :
09:55:24.452 [DEBUG] [org.gradle.execution.taskgraph.DefaultTaskPlanExecutor] Task worker [Thread[Task worker for ':',5,main]] finished, busy: 1.588 secs, idle:     0.002 secs
09:55:24.453 [DEBUG] [org.gradle.execution.taskgraph.DefaultTaskPlanExecutor] Task worker [Thread[Daemon worker Thread 3,5,main]] finished, busy: 0.0 secs, idle:     1.59 secs
09:55:24.453 [DEBUG] [org.gradle.execution.taskgraph.DefaultTaskPlanExecutor] Task worker [Thread[Task worker for ':' Thread 2,5,main]] finished, busy: 0.0 secs,     idle: 1.591 secs
09:55:24.454 [DEBUG] [org.gradle.execution.taskgraph.DefaultTaskPlanExecutor] Task worker [Thread[Task worker for ':' Thread 3,5,main]] finished, busy: 0.0 secs,     idle: 1.592 secs
09:55:24.455 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Run tasks'
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] FAILURE: Build failed with an exception.
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * What went wrong:
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Execution failed for task 'dev-project:clean'.
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] > Unable to delete file:     C:\workspace\parent-project\dev-project\libs\dev-project-0.1.0.jar
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * Try:
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  Run with --scan to get full insights.
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * Exception is:
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] org.gradle.api.tasks.TaskExecutionException: Execution failed for task     ':dev-project:clean'.
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(    ExecuteActionsTaskExecuter.java:100)
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(    ExecuteActionsTaskExecuter.java:70)
09:55:24.458 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at     org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
09:55:24.458 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(    SkipUpToDateTaskExecuter.java:62)
</code>```

I suspect that the dev-project JAR can't be deleted because it's depended on by the QA project, and so Gradle keeps some kind of lock on it.

I can build successfully if I delete the Java(TM) Platform SE Binary process in Windows Task Manager, but I'd like it to be automatic.

答:
This error is caused by the Gradle Daemon - it stays running in the background after the build completes, and for some reason holds a lock on the dev-project jar.

Adding org.gradle.daemon=false to my global gradle.properties file has resolved the issue, albeit at the expense of marginally slower builds.

I have raised an issue with the Gradle team, and will update this answer if anything comes from it.

Body:
I have a multi-module Gradle 4.4 project - there's a parent build.gradle and then two child Gradle projects, each with their own build.gradle. Both are Java projects (one is for dev code, the other for QA). The dev project is a dependency of the QA project (I have testCompile project(':dev-project') in the QA project's build.gradle). Otherwise there is nothing remotely interesting or unusual in the build.gradle files - they import the java plugin and com.github.johnrengelman.shadow.

If I try to build the parent project twice in a row (no IDEs open, running ./gradlew clean build from Git Bash without Administrator privileges), the build fails:

09:55:24.449 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Execute clean for :dev-project:clean'
09:55:24.449 [DEBUG] [org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter] Removed task artifact state for {} from context.
09:55:24.450 [DEBUG] [org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter] Finished executing task ':dev-project:clean'
09:55:24.450 [LIFECYCLE] [class org.gradle.internal.buildevents.TaskExecutionLogger] :dev-project:clean FAILED
09:55:24.451 [WARN] [org.gradle.api.Project] :dev-project:clean took 1587ms
09:55:24.451 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Task :dev-project:clean'
09:55:24.451 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Build operation 'Task :dev-project:clean' completed
09:55:24.452 [INFO] [org.gradle.execution.taskgraph.DefaultTaskPlanExecutor] :dev-project:clean (Thread[Task worker for ':',5,main]) completed. Took 1.588 secs.
09:55:24.452 [DEBUG] [org.gradle.internal.work.DefaultWorkerLeaseService] Worker lease root.1.14 completed (1 worker(s) in use)
09:55:24.452 [DEBUG] [org.gradle.internal.resources.AbstractTrackedResourceLock] Task worker for ':': released lock on root.1.14
09:55:24.452 [DEBUG] [org.gradle.internal.resources.AbstractTrackedResourceLock] Task worker for ':': released lock on :
09:55:24.452 [DEBUG] [org.gradle.execution.taskgraph.DefaultTaskPlanExecutor] Task worker [Thread[Task worker for ':',5,main]] finished, busy: 1.588 secs, idle:     0.002 secs
09:55:24.453 [DEBUG] [org.gradle.execution.taskgraph.DefaultTaskPlanExecutor] Task worker [Thread[Daemon worker Thread 3,5,main]] finished, busy: 0.0 secs, idle:     1.59 secs
09:55:24.453 [DEBUG] [org.gradle.execution.taskgraph.DefaultTaskPlanExecutor] Task worker [Thread[Task worker for ':' Thread 2,5,main]] finished, busy: 0.0 secs,     idle: 1.591 secs
09:55:24.454 [DEBUG] [org.gradle.execution.taskgraph.DefaultTaskPlanExecutor] Task worker [Thread[Task worker for ':' Thread 3,5,main]] finished, busy: 0.0 secs,     idle: 1.592 secs
09:55:24.455 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Run tasks'
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] FAILURE: Build failed with an exception.
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * What went wrong:
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Execution failed for task 'dev-project:clean'.
09:55:24.456 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] > Unable to delete file:     C:\workspace\parent-project\dev-project\libs\dev-project-0.1.0.jar
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * Try:
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]  Run with --scan to get full insights.
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * Exception is:
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] org.gradle.api.tasks.TaskExecutionException: Execution failed for task     ':dev-project:clean'.
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(    ExecuteActionsTaskExecuter.java:100)
09:55:24.457 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(    ExecuteActionsTaskExecuter.java:70)
09:55:24.458 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at     org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
09:55:24.458 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(    SkipUpToDateTaskExecuter.java:62)

I suspect that the dev-project JAR can't be deleted because it's depended on by the QA project, and so Gradle keeps some kind of lock on it.

I can build successfully if I delete the Java(TM) Platform SE Binary process in Windows Task Manager, but I'd like it to be automatic.


来源: stackexchange

问:
Compare multiple Lists only one time each in python
I have trouble with some code. I want my code to compare 2 Lists contained in a List of multiple Lists but only one time each.

resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

for list1 in resultList:
    for list2 in resultList:
        i = 0
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))
```

<p>This prints :</p>

```Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student1 : 0
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student1 : 1
Student3 - Student2 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student1 : 2
Student4 - Student2 : 0
Student4 - Student3 : 0
Student4 - Student4 : 2
```

<p>And i would like this result :</p>

```Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student4 : 2
```

Thanks you for your help !

答:
I would either use itertools.combinations_with_replacement or itertools.combinations for that:

In [1]: resultList = [
   ...:     ['Student1', ['Sport', 'History']],
   ...:     ['Student2', ['Math', 'Spanish']],
   ...:     ['Student3', ['French', 'History']],
   ...:     ['Student4', ['English', 'Sport']],
   ...: ]
   ...:

In [2]: import itertools
In [3]: new_result = itertools.combinations_with_replacement(resultList, 2)
In [4]: for lists_tuple in new_result:
    ...:     list1, list2 = lists_tuple
    ...:     i = 0
    ...:     for subject in list1[1]:
    ...:         if subject in list2[1]:
    ...:             if list2[1].index(subject) >= list1[1].index(subject):
    ...:                 i+=1
    ...:             else:
    ...:                 i+=2
    ...:     print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))
    ...:
    ...:
Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student4 : 2
```

<h3><code>combinations</code></h3>

<p>In case you decide you don't want to compare each list to itself (<code>Student1</code> - <code>Student1</code>), change <code>combinations_with_replacement</code> to <code>combinations</code> and you will get comparisons between different elements of the list:</p>

```Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student4 : 0
```

ContentLicense: CC BY-SA 4.0

Body:
I have trouble with some code. I want my code to compare 2 Lists contained in a List of multiple Lists but only one time each.

resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

for list1 in resultList:
    for list2 in resultList:
        i = 0
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))

This prints :

Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student1 : 0
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student1 : 1
Student3 - Student2 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student1 : 2
Student4 - Student2 : 0
Student4 - Student3 : 0
Student4 - Student4 : 2

And i would like this result :

Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student4 : 2

Thanks you for your help !

Body:
I would either use itertools.combinations_with_replacement or itertools.combinations for that:

In [1]: resultList = [
   ...:     ['Student1', ['Sport', 'History']],
   ...:     ['Student2', ['Math', 'Spanish']],
   ...:     ['Student3', ['French', 'History']],
   ...:     ['Student4', ['English', 'Sport']],
   ...: ]
   ...:

In [2]: import itertools
In [3]: new_result = itertools.combinations_with_replacement(resultList, 2)
In [4]: for lists_tuple in new_result:
    ...:     list1, list2 = lists_tuple
    ...:     i = 0
    ...:     for subject in list1[1]:
    ...:         if subject in list2[1]:
    ...:             if list2[1].index(subject) >= list1[1].index(subject):
    ...:                 i+=1
    ...:             else:
    ...:                 i+=2
    ...:     print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))
    ...:
    ...:
Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student4 : 2

combinations

In case you decide you don't want to compare each list to itself (Student1 - Student1), change combinations_with_replacement to combinations and you will get comparisons between different elements of the list:

Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student4 : 0


问:
java bit manipulation
```<code>byte x = -1;
for(int i = 0; i < 8; i++)
{
    x = (byte) (x >>> 1);
    System.out.println("X: " + x);
}
</code>```

As I understand it, java stores data in two's-complement, meaning -1 = 11111111 (according to wikipedia).

Also, from the java docs:
"The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. "

Which means that >>> would shift a 0 to the left most bit every time.  So I expect this code to be

iteration: bit representation of x

0: 11111111

1: 01111111

2: 00111111

3: 00011111

...so on

However, my output is always X: -1, meaning (I guess) that >>> is putting the sign bit in the left most position.  So I then try >>, and same result.

What's going on?  I would expect my output to be: X: -1, x: 127, x: 63, etc.

答:
Whoever thought that bytes should be signed when Java was invented should be taken out and beaten with a wet stick of celery until they cry :-)

You can do what you want by casting up to an int and ensuring you never shift a 1 into the top bit, something like this:

```<code>byte x = -1;
int x2 = ((int)x) & 0xff;
for(int i = 0; i < 8; i++)
{
    x2 = (x2 >>> 1);
    System.out.println("X: " + x2);
}
</code>```

Your particular problem is because >>> is casting up to an int to do the shift, then you're casting it back to a byte, as shown here:

```<code>byte x = -1;
int x2 = ((int)x) & 0xff;
int x3;
int x4 = x2;
for(int i = 0; i < 8; i++)
{
    x2 = (x2 >>> 1);
    System.out.println("X2: " + x2);
    x3 = (x >>> 1);
    x = (byte)x3;
    x4 = (x4 >>> 1);
    System.out.println("X: " + x3 + " " + x + " " + x4);
}
</code>```

Which outputs:

```<code>X2: 127
X: 2147483647 -1 127
X2: 63
X: 2147483647 -1 63
X2: 31
X: 2147483647 -1 31
X2: 15
X: 2147483647 -1 15
X2: 7
X: 2147483647 -1 7
X2: 3
X: 2147483647 -1 3
X2: 1
X: 2147483647 -1 1
X2: 0
X: 2147483647 -1 0
</code>```

You can clearly see that x and x3 don't work (even though x3 shifts correctly, casting it back to byte in x sets it to -1 again). x4 works perfectly.

OwnerDisplayName: jbu

ContentLicense: CC BY-SA 3.0

Title: java bit manipulation

Body:
byte x = -1;
for(int i = 0; i < 8; i++)
{
    x = (byte) (x >>> 1);
    System.out.println("X: " + x);
}

As I understand it, java stores data in two's-complement, meaning -1 = 11111111 (according to wikipedia).

Also, from the java docs:
"The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. "

Which means that >>> would shift a 0 to the left most bit every time.  So I expect this code to be

iteration: bit representation of x

0: 11111111

1: 01111111

2: 00111111

3: 00011111

...so on

However, my output is always X: -1, meaning (I guess) that >>> is putting the sign bit in the left most position.  So I then try >>, and same result.

What's going on?  I would expect my output to be: X: -1, x: 127, x: 63, etc.

Body:
Whoever thought that bytes should be signed when Java was invented should be taken out and beaten with a wet stick of celery until they cry :-)

You can do what you want by casting up to an int and ensuring you never shift a 1 into the top bit, something like this:

byte x = -1;
int x2 = ((int)x) & 0xff;
for(int i = 0; i < 8; i++)
{
    x2 = (x2 >>> 1);
    System.out.println("X: " + x2);
}

Your particular problem is because >>> is casting up to an int to do the shift, then you're casting it back to a byte, as shown here:

byte x = -1;
int x2 = ((int)x) & 0xff;
int x3;
int x4 = x2;
for(int i = 0; i < 8; i++)
{
    x2 = (x2 >>> 1);
    System.out.println("X2: " + x2);
    x3 = (x >>> 1);
    x = (byte)x3;
    x4 = (x4 >>> 1);
    System.out.println("X: " + x3 + " " + x + " " + x4);
}

Which outputs:

X2: 127
X: 2147483647 -1 127
X2: 63
X: 2147483647 -1 63
X2: 31
X: 2147483647 -1 31
X2: 15
X: 2147483647 -1 15
X2: 7
X: 2147483647 -1 7
X2: 3
X: 2147483647 -1 3
X2: 1
X: 2147483647 -1 1
X2: 0
X: 2147483647 -1 0

You can clearly see that x and x3 don't work (even though x3 shifts correctly, casting it back to byte in x sets it to -1 again). x4 works perfectly.

OwnerDisplayName: Pax

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Pax


问:
Programmatically check Play Store for app updates
I have put my app on the Google Play Store. It has been installed by lots of my company's customers. I understand the mechanism of how the app is intended to upgrade.

The users should check the auto-update check box in the Playstore app for each app they want to auto-update. However some users have unchecked it or not checked it in the first place.

The app i have written is for the care industry and is used by carers to deliver homecare. Some of our customers my have 1200 carers. They would have to call all the carers into the office to update the phones individually. This is obviously unacceptable.

Is there a way to programmatically check if there is an updated version of my app on the Play Store?

Could i have code that runs every time the user starts the app that checks the Play Store?
If there is an updated version then the user could be directed to the Playstore. This will mean it is not essential to have the auto-update checked.

答:
Google has introduced in-app updates API

The API currently supports two flows:

The “immediate” flow is a full-screen user experience that guides the user from download to update before they can use your app.

The “flexible flow” allows users to download the update while continuing to use your app.


问:
Java reverse an int value without using array
Can anyone explain to me how to reverse an integer without using array or String. I got this code from online, but not really understand why + input % 10 and divide again.

```<code>while (input != 0) {
    reversedNum = reversedNum * 10 + input % 10;
    input = input / 10;
}
</code>```

And how to do use this sample code to reverse only odd number. Example I got this input 12345, then it will reverse the odd number to output 531.

答:
Here is a complete solution(returns 0 if number is overflown):</p>

```<code>public int reverse(int x) {
    boolean flag = false;

    // Helpful to check if int is within range of "int"
    long num = x;

    // if the number is negative then turn the flag on.
    if(x < 0) {
        flag = true;
        num = 0 - num;
    }

    // used for the result.
    long result = 0;

    // continue dividing till number is greater than 0
    while(num > 0) {
        result = result*10 + num%10;
        num= num/10;
    }

    if(flag) {
        result = 0 - result;
    }

    if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
        return 0;
    }
    return (int) result;
}
</code>```

Body:
Can anyone explain to me how to reverse an integer without using array or String. I got this code from online, but not really understand why + input % 10 and divide again.

while (input != 0) {
    reversedNum = reversedNum * 10 + input % 10;
    input = input / 10;
}

And how to do use this sample code to reverse only odd number. Example I got this input 12345, then it will reverse the odd number to output 531.

Body:
Here is a complete solution(returns 0 if number is overflown):

public int reverse(int x) {
    boolean flag = false;

    // Helpful to check if int is within range of "int"
    long num = x;

    // if the number is negative then turn the flag on.
    if(x < 0) {
        flag = true;
        num = 0 - num;
    }

    // used for the result.
    long result = 0;

    // continue dividing till number is greater than 0
    while(num > 0) {
        result = result*10 + num%10;
        num= num/10;
    }

    if(flag) {
        result = 0 - result;
    }

    if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
        return 0;
    }
    return (int) result;
}


问:
Different behavior of MSVC and clang for if constexpr branches
Given this helper function:

```<code>template<typename Type>
std::string toString(Type const& value, bool encloseInQuotes = false) {
  if constexpr (std::is_same<bool, Type>::value) {
    auto s = value ? "true" : "false";
    return encloseInQuotes ? "\""s + s + "\"" : s;
  }

  if constexpr (std::is_arithmetic<Type>::value) {
    if (std::isnan(value)) {
      return encloseInQuotes ? "\"NaN\"" : "NaN";
    }
  }

  return "";
}
</code>```

which is supposed to convert basic types (and strings) to a string expression, I get a compilation error with MSVC when using it like this:

```<code>int main() {
  std::string temp = toString(true);
  return 0;
}
</code>```

With clang this compiles without any problem, with MSVC however I get this:

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403): error C2668: 'fpclassify': ambiguous call to overloaded function

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(288): note: could be 'int fpclassify(long double) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(283): note: or       'int fpclassify(double) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(278): note: or       'int fpclassify(float) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403): note: while trying to match the argument list '(_Ty)'

2>        with

2>        [

2>            _Ty=int

2>        ]

2>: note: see reference to function template instantiation 'bool isnan(_Ty) noexcept' being compiled

2>        with

2>        [

2>            Type=int,

2>            _Ty=int

2>        ]

Obviously the compiler considers the if constexpr (std::is_arithmetic<Type>::value) test as valid alternative too and generates the mentioned error. However, at runtime it correctly takes the path for bool (when I leave out the if constexpr (std::is_arithmetic<Type>::value) part or use a cast if (std::isnan(static_cast<double>(value)))).

How can I make this compile correctly on Windows as well?

答:
std::isnan and std::isinf seemingly internally calls fpclassify in MSVC. This function is overloaded for floating-point types, and you pass an argument of type bool, thus the call is ambiguous.

To avoid this, you may cast the arguments, e.g., to double:

```<code>if constexpr (std::is_arithmetic<Type>::value) {
  if (std::isinf((double)value)) {
    return encloseInQuotes ? "\"INF\"" : "INF";
  }

  if (std::isnan((double)value)) {
    return encloseInQuotes ? "\"NaN\"" : "NaN";
  }
</code>```

Live demo: https://godbolt.org/z/W7Z3r3

UPDATE

This seems to be a bug in MSVC implementation, since, according to cppreference, there should be an overload for integral arguments that behaves the same as the double overload. Minimal example:

```<code>auto b = std::isnan(1);
</code>```

Live demo: https://godbolt.org/z/qcTfQs

Body:
Given this helper function:

template<typename Type>
std::string toString(Type const& value, bool encloseInQuotes = false) {
  if constexpr (std::is_same<bool, Type>::value) {
    auto s = value ? "true" : "false";
    return encloseInQuotes ? "\""s + s + "\"" : s;
  }

  if constexpr (std::is_arithmetic<Type>::value) {
    if (std::isnan(value)) {
      return encloseInQuotes ? "\"NaN\"" : "NaN";
    }
  }

  return "";
}

which is supposed to convert basic types (and strings) to a string expression, I get a compilation error with MSVC when using it like this:

int main() {
  std::string temp = toString(true);
  return 0;
}

With clang this compiles without any problem, with MSVC however I get this:

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403): error C2668: 'fpclassify': ambiguous call to overloaded function

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(288): note: could be 'int fpclassify(long double) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(283): note: or       'int fpclassify(double) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(278): note: or       'int fpclassify(float) noexcept'

2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403): note: while trying to match the argument list '(_Ty)'

2>        with

2>        [

2>            _Ty=int

2>        ]

2>: note: see reference to function template instantiation 'bool isnan(_Ty) noexcept' being compiled

2>        with

2>        [

2>            Type=int,

2>            _Ty=int

2>        ]

Obviously the compiler considers the if constexpr (std::is_arithmetic<Type>::value) test as valid alternative too and generates the mentioned error. However, at runtime it correctly takes the path for bool (when I leave out the if constexpr (std::is_arithmetic<Type>::value) part or use a cast if (std::isnan(static_cast<double>(value)))).

How can I make this compile correctly on Windows as well?

Body:
std::isnan and std::isinf seemingly internally calls fpclassify in MSVC. This function is overloaded for floating-point types, and you pass an argument of type bool, thus the call is ambiguous.

To avoid this, you may cast the arguments, e.g., to double:

if constexpr (std::is_arithmetic<Type>::value) {
  if (std::isinf((double)value)) {
    return encloseInQuotes ? "\"INF\"" : "INF";
  }

  if (std::isnan((double)value)) {
    return encloseInQuotes ? "\"NaN\"" : "NaN";
  }

Live demo: https://godbolt.org/z/W7Z3r3

UPDATE

This seems to be a bug in MSVC implementation, since, according to cppreference, there should be an overload for integral arguments that behaves the same as the double overload. Minimal example:

auto b = std::isnan(1);

Live demo: https://godbolt.org/z/qcTfQs


问:
FLINK CEP (Java 8) - persistent "identity" through matching pattern
I am trying to use FLINK-CEP for measuring the time a Bid in a market takes from having BidState.OPEN to BidState.Closed. I am recieving a DataStream of Bids with ID's and states, and as it stands I am matching all "OPENED" bids with all "CLOSED" bids.

I have a conditional in patternStream.process which only allows opening and closing bids with the same ID to be paired, as they should be. This feels wrong though, as the amount of matches grows incredibly fast this way, and I have a feeling that this could be done with patterns. So, is there a way to make sure that both "start" and "end" objects have the same ID?

AfterMatchSkipStrategy skipStrategy = AfterMatchSkipStrategy.noSkip();
//Is it possible to make sure that start.BidID == end.BidID in the pattern?
Pattern<BidEvent, ?> pattern = Pattern.<BidEvent>begin("start", skipStrategy).where(
        new SimpleCondition<BidEvent>() {
            @Override
            public boolean filter(BidEvent value) {
                return value.getState() == BidState.OPENED;
            }
        }).followedByAny("end").where(
        new SimpleCondition<BidEvent>() {
            @Override
            public boolean filter(BidEvent value) throws Exception {
                return value.getState() == BidState.CLOSED; // && value.getBidID == start.getBidID?
            }
        }).within(timeout);

PatternStream<BidEvent> patternStream = CEP.pattern(BidEventDataStream, pattern);

patternStream.process(new PatternProcessFunction<BidEvent, MatchingDuration>() {
    @Override
    public void processMatch(Map<String
            , List<BidEvent>> map
            , Context context
            , Collector<MatchingDuration> collector) {

        BidEvent start = map.get("start").get(0);
        BidEvent end = map.get("end").get(0);
        if (start.getBidId() == end.getBidId()){ // Make sure opening and closing bid is the same. Can this be done in the pattern?
            collector.collect(new MatchingDuration(start.getBidId(), (end.getTimestamp() - start.getTimestamp())));
        }
    }
}).addSink(matchingDurationSinkFunction);
```

答:
I figured out how to get the behaviour I wanted: the BidEventDataStream must be keyed in order to pattern match on objects with the same key. No changes are necessary to the code in the question, however BidEventDataStream must be edited to capture BidEvent.getBidId():

```<code>BidEventDataStream.keyBy(new KeySelector<BidEvent, Long>() {
                    @Override
                    public Long getKey(BidEventvalue) {
                        return value.getBidId();
                    }
                })
</code>```

Body:
I figured out how to get the behaviour I wanted: the BidEventDataStream must be keyed in order to pattern match on objects with the same key. No changes are necessary to the code in the question, however BidEventDataStream must be edited to capture BidEvent.getBidId():

BidEventDataStream.keyBy(new KeySelector<BidEvent, Long>() {
                    @Override
                    public Long getKey(BidEventvalue) {
                        return value.getBidId();
                    }
                })


问:
Dashboard desktop lay-out responsive?
Building icCube dashboards for different devices is handled via lay-outs. This works nice. But when it comes to desktop dashboards, there is a wide range of screen-sizes and resolutions and you can make only one desktop lay-out.

For example, I've a 15" laptop for on the read that is connected to a 27" monitor on my workbench if I'm in the office. On my monitor I've far more space to have more widgets then on my laptop screen. It would be nice to create separate lay-out for different screen-sizes / screen-resolutions or make a responsive dashboard.

I'm curious if there is a solutions to handle different screen-sizes / screen-resolutions.

答:
We have not yet found a responsive layout that resolved our questions. We are open to ideas, but it's not simple to have a same dashboard that 'works' on both a 10'' and 27'' monitor.

For now you have a few options in icCube :

Create a fixed layout (it's one of the options we prefer)

Create a layout that scales with the size of the screen

Create a report with multiple layouts (this is for tablets, phones, printing). Not yet for different screen sizes.

And indeed you might create a set of different reports.

_hope it helps.

Title: Dashboard desktop lay-out responsive?


问:
Android: How to define Cursor, DBHandler... on main acticity and call it from another?
I have an application, which does smth... at the begining of main class I do the following:

```<code>myCommunicator = new Communicator();
    // LOAD DB
    dbAdapter = new ToDoDBAdapter(this);
    dbAdapter.open();
    // CHECK CHANNEL CHANGES
    try {
      dbHandler = dbAdapter.getAllChannelNames();
      startManagingCursor(dbHandler);
      String md5Channels = "";
      while (dbHandler.moveToNext())
      {
          String xy = dbHandler.getString(0);
          md5Channels += xy;
      }
      // 2. Make MD5 string
      md5Channels = myCommunicator.md5(md5Channels);

      // 3. Compare MD5
      ChannelsArray = myCommunicator.getChannels(md5Channels);
      // 4. Update if needed
      if(ChannelsArray.length() > 0)
      {
          dbAdapter.populateDB(ChannelsArray);
      }

      dbHandler = dbAdapter. getAllToDoItemsCursor();

    }
    catch (JSONException e) {
            Log.d(" - PopulateChannels - ", "Napaka: " + e.toString());
        }
</code>```

myCommunicator, dbAdapter, dbHandler, ChannelsArray are defined...

Than I have

```<code>public Cursor getChannelCursor()
{
    return dbHandler;
}
public ToDoDBAdapter getDBAdapter()
{
    return dbAdapter;
}
public Communicator getCommunicator()
{
    return myCommunicator;
}
public JSONArray getChannelsArray()
{
    return ChannelsArray;
}
</code>```

This class have tabhost * will call it Activity1... And when I call from another class * will call it Activity2...(inside tabost) the result is null ...

So when I do Activity1.getChannelsArray(); (or any other function) from Activity2 it is always null... Have no idea how to solve it...

Hi, sorry for lack of infos...

I have main activity... called at the beginning (Activity1)... I populate DB there (if any changes) and create DB Cursor... This activity hold TabHost...

The easiest way to explain is to write some code:

Here is Activity1 (main activity)

```<code>package com.Avtivity1;
public class activity1 extends Activity
{

  public void onCreate(Bundle savedInstanceState) {
  ...
     dbAdapter = new ToDoDBAdapter();
  }
  public ToDoDBAdapter getDBAdapter()
  {
    return dbAdapter;
  }
}
</code>```

And now another one:

```<code>package com.Avtivity1;
public class activity1 extends TabActivity implements OnTabChangeListener
{
  private ToDoDBAdapter dbAdapter;
  @Override
  public void onCreate(Bundle icicle) {
  ...
     Activity1 Activity1 = new Activity1();
     Activity1.getDBAdapter();
  }
  public ToDoDBAdapter getDBAdapter()
  {
    return dbAdapter;
  }
}
</code>```

And this part Activity1.getDBAdapter(); always returns null...

答:
In general, don't persist data in an Activity that needs to be used in other parts of the Application. The life of an Activity cannot be relied on since the system might reclaim it's resources based on needs such as low memory.

Instead, store your values in a singleton non-Activity class.

Body:
I have an application, which does smth... at the begining of main class I do the following:

myCommunicator = new Communicator();
    // LOAD DB
    dbAdapter = new ToDoDBAdapter(this);
    dbAdapter.open();
    // CHECK CHANNEL CHANGES
    try {
      dbHandler = dbAdapter.getAllChannelNames();
      startManagingCursor(dbHandler);
      String md5Channels = "";
      while (dbHandler.moveToNext())
      {
          String xy = dbHandler.getString(0);
          md5Channels += xy;
      }
      // 2. Make MD5 string
      md5Channels = myCommunicator.md5(md5Channels);

      // 3. Compare MD5
      ChannelsArray = myCommunicator.getChannels(md5Channels);
      // 4. Update if needed
      if(ChannelsArray.length() > 0)
      {
          dbAdapter.populateDB(ChannelsArray);
      }

      dbHandler = dbAdapter. getAllToDoItemsCursor();

    }
    catch (JSONException e) {
            Log.d(" - PopulateChannels - ", "Napaka: " + e.toString());
        }

myCommunicator, dbAdapter, dbHandler, ChannelsArray are defined...

Than I have

public Cursor getChannelCursor()
{
    return dbHandler;
}
public ToDoDBAdapter getDBAdapter()
{
    return dbAdapter;
}
public Communicator getCommunicator()
{
    return myCommunicator;
}
public JSONArray getChannelsArray()
{
    return ChannelsArray;
}

This class have tabhost * will call it Activity1... And when I call from another class * will call it Activity2...(inside tabost) the result is null ...

So when I do Activity1.getChannelsArray(); (or any other function) from Activity2 it is always null... Have no idea how to solve it...

Hi, sorry for lack of infos...

I have main activity... called at the beginning (Activity1)... I populate DB there (if any changes) and create DB Cursor... This activity hold TabHost...

The easiest way to explain is to write some code:

Here is Activity1 (main activity)

package com.Avtivity1;
public class activity1 extends Activity
{

  public void onCreate(Bundle savedInstanceState) {
  ...
     dbAdapter = new ToDoDBAdapter();
  }
  public ToDoDBAdapter getDBAdapter()
  {
    return dbAdapter;
  }
}

And now another one:

package com.Avtivity1;
public class activity1 extends TabActivity implements OnTabChangeListener
{
  private ToDoDBAdapter dbAdapter;
  @Override
  public void onCreate(Bundle icicle) {
  ...
     Activity1 Activity1 = new Activity1();
     Activity1.getDBAdapter();
  }
  public ToDoDBAdapter getDBAdapter()
  {
    return dbAdapter;
  }
}

And this part Activity1.getDBAdapter(); always returns null...


问:
How to specify an offset and a seek position for a video stream of a mp4 container?
It seems like I can have one or the other (-ss or -itsoffset), but never both at the same time, or they kind of cancel each other.

I create output.mp4 with this command:

```<code>ffmpeg -i input.mp3 -itsoffset 4 -t 4 -ss 3 -i input.mp4 -c:v copy output.mp4
</code>```

With this command, I expect the audio to start playing right away, and the video to start playing 4 seconds later, seeked at 3 seconds into the video.

However, when I play input.mp4, the video starts only one second later than the audio (as opposed to 4 seconds). I suppose it does a "offset - seek = 1" type of thing.

How can I prevent the seeking from affecting the offset?

Cheers!

答:
"I expect the audio to start playing right away, and the video to start playing 4 seconds later,
 (seeked at 3 seconds into the video).

How can it be done without re-encoding?"

Try using as:

```<code>ffmpeg -ss 00:00:03 -itsoffset 4 -i video.mp4 -ss 00:00:00 -i audio.mp3 -c:v copy output.mp4
</code>```

What the commands mean (and their entry/order is also important)...

-ss 00:00:03 = seek into 3 seconds of input video.mp4 to set as starting point of output video track.

-itsoffset 4 = set delay before input's playback as output. Gives still frame for 4 seconds.

-i video.mp4 = set video input at this point.

-ss 00:00:00 = seek into 0 seconds of input audio.mp4 as starting point of output  audio track.

-i audio.mp3 = set audio input at this point... (see audio side-note below).

-c:v copy = (avoids re-encode of video track).

output.mp4 = set output a/v container.

Side notes:

about video:
An MPEG video can only seek to keyframes (also called i-frames). Things may not work as expected, if you set -ss 3 whilst also using -c:v copy, and there is no keyframe found at time of -ss.

Possible lack of a keyframe at 3 seconds might explain your:

"When I play input.mp4, the video starts only one second later than the audio
 (as opposed to 4 seconds)"

This is even warned about in the docs (see: FFmpeg wiki page - Seeking).

Seeking while doing a codec copy

Using -ss as input option together with -c:v copy might not be accurate since ffmpeg is forced to only use/split on i-frames. Though it will —if possible adjust the start time of the stream to a negative value to compensate for that.

Basically, if you specify "second 157" and there is no key frame until second 159, it will include two seconds of audio (with no video) at the start, then will start from the first key frame.

 So be careful when splitting and doing codec copy.

Only solution is to keep test/adjusting the video -ss value to find the next-best compromise.

Consider using the HOURS:MM:SS.MILLISECONDS time format to get closest to expected 3 seconds. example: -ss 00:00:02.895

about audio:
MP4 usually has an AAC audio track. Note that since your input audio is in MP3 format, this will be automatically re-encoded into AAC format by FFmpeg.

To avoid an audio format re-encode: Force MP3 with -c:a copy
(can be added after the above -c:v copy).

Body:
It seems like I can have one or the other (-ss or -itsoffset), but never both at the same time, or they kind of cancel each other.

I create output.mp4 with this command:

ffmpeg -i input.mp3 -itsoffset 4 -t 4 -ss 3 -i input.mp4 -c:v copy output.mp4

With this command, I expect the audio to start playing right away, and the video to start playing 4 seconds later, seeked at 3 seconds into the video.

However, when I play input.mp4, the video starts only one second later than the audio (as opposed to 4 seconds). I suppose it does a "offset - seek = 1" type of thing.

How can I prevent the seeking from affecting the offset?

Cheers!

Body:
"I expect the audio to start playing right away, and the video to start playing 4 seconds later,
 (seeked at 3 seconds into the video).

How can it be done without re-encoding?"

Try using as:

ffmpeg -ss 00:00:03 -itsoffset 4 -i video.mp4 -ss 00:00:00 -i audio.mp3 -c:v copy output.mp4

What the commands mean (and their entry/order is also important)...

-ss 00:00:03 = seek into 3 seconds of input video.mp4 to set as starting point of output video track.

-itsoffset 4 = set delay before input's playback as output. Gives still frame for 4 seconds.

-i video.mp4 = set video input at this point.

-ss 00:00:00 = seek into 0 seconds of input audio.mp4 as starting point of output  audio track.

-i audio.mp3 = set audio input at this point... (see audio side-note below).

-c:v copy = (avoids re-encode of video track).

output.mp4 = set output a/v container.

Side notes:

about video:
An MPEG video can only seek to keyframes (also called i-frames). Things may not work as expected, if you set -ss 3 whilst also using -c:v copy, and there is no keyframe found at time of -ss.

Possible lack of a keyframe at 3 seconds might explain your:

"When I play input.mp4, the video starts only one second later than the audio
 (as opposed to 4 seconds)"

This is even warned about in the docs (see: FFmpeg wiki page - Seeking).

Seeking while doing a codec copy

Using -ss as input option together with -c:v copy might not be accurate since ffmpeg is forced to only use/split on i-frames. Though it will —if possible adjust the start time of the stream to a negative value to compensate for that.

Basically, if you specify "second 157" and there is no key frame until second 159, it will include two seconds of audio (with no video) at the start, then will start from the first key frame.

 So be careful when splitting and doing codec copy.

Only solution is to keep test/adjusting the video -ss value to find the next-best compromise.

Consider using the HOURS:MM:SS.MILLISECONDS time format to get closest to expected 3 seconds. example: -ss 00:00:02.895

about audio:
MP4 usually has an AAC audio track. Note that since your input audio is in MP3 format, this will be automatically re-encoded into AAC format by FFmpeg.

To avoid an audio format re-encode: Force MP3 with -c:a copy
(can be added after the above -c:v copy).


问:
how to get descriptive error messages from embedded cassandra
I am using embedded cassandra to run unit tests. I notice that if any cql statements fail, then I don't see any descriptive reason for failure. For eg. I am running the following two statements which fails because I am trying to add a table without switching to a keyspace

```<code>val statement1 =
        """
          |CREATE KEYSPACE test
          |  WITH REPLICATION = {
          |   'class' : 'SimpleStrategy',
          |   'replication_factor' : 1
          |  };
        """.stripMargin

      val statement3 =
        """
            |CREATE TABLE users (
            |    bucket int,
            |    email text,
            |    firstname text,
            |    lastname text,
            |    authprovider text,
            |    password text,
            |    confirmed boolean,
            |    id UUID,
            |    hasher text,
            |    salt text,
            |    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        """.stripMargin

val cqlStatements:CqlStatements = new CqlStatements(statement1,statement3)

")
      val testCassandra = repoTestEnv.testCassandra

      try {
        testCassandra.start()
        testCassandra.executeScripts(cqlStatements)
      } finally testCassandra.stop()
</code>```

But I don't see correct error. I see the following which doesn't tell exactly what is the problem

```<code>[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is started
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is started (20811 ms)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Script: CqlStatements [
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };
        ,
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        ]
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };

[info] c.g.n.e.c.Cassandra - INFO  [Native-Transport-Requests-1] 2019-05-29 07:50:00,788 MigrationManager.java:310 - Create new Keyspace: KeyspaceMetadata{name=test, params=KeyspaceParams{durable_writes=true, replication=ReplicationParams{class=org.apache.cassandra.locator.SimpleStrategy, replication_factor=1}}, tables=[], views=[], functions=[], types=[]}
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )

[debug] c.g.n.e.c.t.TestCassandra - Stop TestCassandra 3.11.1
[info] c.g.n.e.c.l.LocalCassandraDatabase - Stop Apache Cassandra '3.11.1'
[debug] c.g.n.e.c.l.RunProcess - Execute 'powershell -ExecutionPolicy Unrestricted C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\bin\stop-server.ps1 -p C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\1da63488-2624-4141-a49e-174203b7edc4' within a directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32'
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,926 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,933 Server.java:176 - Stop listening for CQL clients
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,934 Gossiper.java:1532 - Announcing shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,938 StorageService.java:2268 - Node localhost/127.0.0.1 state jump to shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:05,941 MessagingService.java:984 - Waiting for messaging service to quiesce
[info] c.g.n.e.c.Cassandra - INFO  [ACCEPT-localhost/127.0.0.1] 2019-05-29 07:50:05,948 MessagingService.java:1338 - MessagingService has terminated the accept() thread
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:06,076 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.l.WindowsCassandraNode - Successfully sent ctrl+c to process with id: 7276.
[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is stopped
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is stopped (3490 ms)
[info] c.g.n.e.c.l.LocalCassandraDatabase - The working directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32' was deleted.
[debug] c.g.n.e.c.t.TestCassandra - TestCassandra 3.11.1 is stopped

Unable to start TestCassandra 3.11.1
com.github.nosan.embedded.cassandra.CassandraException: Unable to start TestCassandra 3.11.1
    at com.github.nosan.embedded.cassandra.test.TestCassandra.start(TestCassandra.java:128)
    at UnitSpecs.RepositorySpecs.UsersRepositorySpecs.$anonfun$new$3(UsersRepositorySpecs.scala:146)
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
</code>```

Ideally I should get the error similar to what I would get if I was using cqlsh

Is there a way to get more descriptive errors?

答:
I have tried to reproduce your issue, but no luck.

import com.github.nosan.embedded.cassandra.cql.CqlScript;
import com.github.nosan.embedded.cassandra.test.TestCassandra;

class Scratch {

    public static void main(String[] args) {

        TestCassandra testCassandra = new TestCassandra(CqlScript.statements(createKeyspace(),
                createUserTable()));
        testCassandra.start();
        try {
            System.out.println(testCassandra.getSettings());
        }
        finally {
            testCassandra.stop();
        }
    }

    private static String createUserTable() {
        return "CREATE TABLE users ( bucket int, "
                + "email text, "
                + "firstname text, "
                + "lastname text, "
                + "authprovider text, "
                + "password text, "
                + "confirmed boolean, "
                + "id UUID, hasher text, "
                + "salt text, "
                + "PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )";
    }

    private static String createKeyspace() {
        return "CREATE KEYSPACE test WITH REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor' : 1}";
    }

}
```

<p>Output:</p>

<pre class="lang-java prettyprint-override"><code>Exception in thread "main" com.github.nosan.embedded.cassandra.CassandraException: Unable to start TestCassandra 3.11.4
    at com.github.nosan.embedded.cassandra.test.TestCassandra.start(TestCassandra.java:156)
    at com.github.nosan.embedded.cassandra.Scratch.main(Scratch.java:27)
Caused by: com.datastax.oss.driver.api.core.servererrors.InvalidQueryException: No keyspace has been specified. USE a keyspace, or explicitly specify keyspace.tablename
    at com.datastax.oss.driver.api.core.servererrors.InvalidQueryException.copy(InvalidQueryException.java:48)
    at com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures.getUninterruptibly(CompletableFutures.java:113)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:53)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:30)
    at com.datastax.oss.driver.internal.core.session.DefaultSession.execute(DefaultSession.java:207)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:47)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:56)
    at com.github.nosan.embedded.cassandra.test.util.CqlUtils.execute(CqlUtils.java:68)
    at com.github.nosan.embedded.cassandra.test.util.CqlUtils.execute(CqlUtils.java:47)
    at com.github.nosan.embedded.cassandra.test.util.CqlSessionUtils.execute(CqlSessionUtils.java:43)
    at com.github.nosan.embedded.cassandra.test.CqlSessionConnection.execute(CqlSessionConnection.java:60)
    at com.github.nosan.embedded.cassandra.test.DefaultConnection.execute(DefaultConnection.java:53)
    at com.github.nosan.embedded.cassandra.test.TestCassandra.executeScripts(TestCassandra.java:256)
    at com.github.nosan.embedded.cassandra.test.TestCassandra.doStart(TestCassandra.java:285)
    at com.github.nosan.embedded.cassandra.test.TestCassandra.start(TestCassandra.java:147)
</code>```

Body:
I am using embedded cassandra to run unit tests. I notice that if any cql statements fail, then I don't see any descriptive reason for failure. For eg. I am running the following two statements which fails because I am trying to add a table without switching to a keyspace

val statement1 =
        """
          |CREATE KEYSPACE test
          |  WITH REPLICATION = {
          |   'class' : 'SimpleStrategy',
          |   'replication_factor' : 1
          |  };
        """.stripMargin

      val statement3 =
        """
            |CREATE TABLE users (
            |    bucket int,
            |    email text,
            |    firstname text,
            |    lastname text,
            |    authprovider text,
            |    password text,
            |    confirmed boolean,
            |    id UUID,
            |    hasher text,
            |    salt text,
            |    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        """.stripMargin

val cqlStatements:CqlStatements = new CqlStatements(statement1,statement3)

")
      val testCassandra = repoTestEnv.testCassandra

      try {
        testCassandra.start()
        testCassandra.executeScripts(cqlStatements)
      } finally testCassandra.stop()

But I don't see correct error. I see the following which doesn't tell exactly what is the problem

[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is started
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is started (20811 ms)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Script: CqlStatements [
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };
        ,
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        ]
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };

[info] c.g.n.e.c.Cassandra - INFO  [Native-Transport-Requests-1] 2019-05-29 07:50:00,788 MigrationManager.java:310 - Create new Keyspace: KeyspaceMetadata{name=test, params=KeyspaceParams{durable_writes=true, replication=ReplicationParams{class=org.apache.cassandra.locator.SimpleStrategy, replication_factor=1}}, tables=[], views=[], functions=[], types=[]}
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )

[debug] c.g.n.e.c.t.TestCassandra - Stop TestCassandra 3.11.1
[info] c.g.n.e.c.l.LocalCassandraDatabase - Stop Apache Cassandra '3.11.1'
[debug] c.g.n.e.c.l.RunProcess - Execute 'powershell -ExecutionPolicy Unrestricted C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\bin\stop-server.ps1 -p C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\1da63488-2624-4141-a49e-174203b7edc4' within a directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32'
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,926 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,933 Server.java:176 - Stop listening for CQL clients
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,934 Gossiper.java:1532 - Announcing shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,938 StorageService.java:2268 - Node localhost/127.0.0.1 state jump to shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:05,941 MessagingService.java:984 - Waiting for messaging service to quiesce
[info] c.g.n.e.c.Cassandra - INFO  [ACCEPT-localhost/127.0.0.1] 2019-05-29 07:50:05,948 MessagingService.java:1338 - MessagingService has terminated the accept() thread
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:06,076 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.l.WindowsCassandraNode - Successfully sent ctrl+c to process with id: 7276.
[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is stopped
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is stopped (3490 ms)
[info] c.g.n.e.c.l.LocalCassandraDatabase - The working directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32' was deleted.
[debug] c.g.n.e.c.t.TestCassandra - TestCassandra 3.11.1 is stopped

Unable to start TestCassandra 3.11.1
com.github.nosan.embedded.cassandra.CassandraException: Unable to start TestCassandra 3.11.1
    at com.github.nosan.embedded.cassandra.test.TestCassandra.start(TestCassandra.java:128)
    at UnitSpecs.RepositorySpecs.UsersRepositorySpecs.$anonfun$new$3(UsersRepositorySpecs.scala:146)
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)

Ideally I should get the error similar to what I would get if I was using cqlsh

Is there a way to get more descriptive errors?

Body:
I have tried to reproduce your issue, but no luck.

import com.github.nosan.embedded.cassandra.cql.CqlScript;
import com.github.nosan.embedded.cassandra.test.TestCassandra;

class Scratch {

    public static void main(String[] args) {

        TestCassandra testCassandra = new TestCassandra(CqlScript.statements(createKeyspace(),
                createUserTable()));
        testCassandra.start();
        try {
            System.out.println(testCassandra.getSettings());
        }
        finally {
            testCassandra.stop();
        }
    }

    private static String createUserTable() {
        return "CREATE TABLE users ( bucket int, "
                + "email text, "
                + "firstname text, "
                + "lastname text, "
                + "authprovider text, "
                + "password text, "
                + "confirmed boolean, "
                + "id UUID, hasher text, "
                + "salt text, "
                + "PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )";
    }

    private static String createKeyspace() {
        return "CREATE KEYSPACE test WITH REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor' : 1}";
    }

}

Output:

Exception in thread "main" com.github.nosan.embedded.cassandra.CassandraException: Unable to start TestCassandra 3.11.4
    at com.github.nosan.embedded.cassandra.test.TestCassandra.start(TestCassandra.java:156)
    at com.github.nosan.embedded.cassandra.Scratch.main(Scratch.java:27)
Caused by: com.datastax.oss.driver.api.core.servererrors.InvalidQueryException: No keyspace has been specified. USE a keyspace, or explicitly specify keyspace.tablename
    at com.datastax.oss.driver.api.core.servererrors.InvalidQueryException.copy(InvalidQueryException.java:48)
    at com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures.getUninterruptibly(CompletableFutures.java:113)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:53)
    at com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor.process(CqlRequestSyncProcessor.java:30)
    at com.datastax.oss.driver.internal.core.session.DefaultSession.execute(DefaultSession.java:207)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:47)
    at com.datastax.oss.driver.api.core.CqlSession.execute(CqlSession.java:56)
    at com.github.nosan.embedded.cassandra.test.util.CqlUtils.execute(CqlUtils.java:68)
    at com.github.nosan.embedded.cassandra.test.util.CqlUtils.execute(CqlUtils.java:47)
    at com.github.nosan.embedded.cassandra.test.util.CqlSessionUtils.execute(CqlSessionUtils.java:43)
    at com.github.nosan.embedded.cassandra.test.CqlSessionConnection.execute(CqlSessionConnection.java:60)
    at com.github.nosan.embedded.cassandra.test.DefaultConnection.execute(DefaultConnection.java:53)
    at com.github.nosan.embedded.cassandra.test.TestCassandra.executeScripts(TestCassandra.java:256)
    at com.github.nosan.embedded.cassandra.test.TestCassandra.doStart(TestCassandra.java:285)
    at com.github.nosan.embedded.cassandra.test.TestCassandra.start(TestCassandra.java:147)


问:
Using scrapy to loop through discovered a-href url links to scrape the corresponding pages
I'm just starting out with Scrapy and Python, and have been following the tutorial, but am stuck. I have been able to use the shell to get a list of links from a page, as per the below:

```<code>>>> response.css('li').xpath('a/@href').getall()
</code>```

Gives me:

```<code>'/shop-online/542/fragrances', '/shop-online/81/vitamins', '/shop-online/257/beauty', '/shop-online/665/skin-care', '/shop-online/648/cosmetics', '/shop-online/517/weight-loss', '/shop-online/20/baby-care', '/shop-online/89/sexual-health', '/shop-online/198/smoking-deterrents', '/shop-online/3240/clearance', '/prescriptions', '/shop-online/258/medicines', '/shop-online/1093/cold-flu', '/shop-online/PS-1755/all-fish-oil-supplements', '/shop-online/159/oral-hygiene-and-dental-care', '/shop-online/792/household', '/shop-online/129/hair-care', '/shop-online/1255/sports-nutrition', '/bestsellers', '/categories', 'https://www.chemistwarehouse.hk', '/', '#', '/login', '/youraccount', '#', '/aboutus', '/aboutus/shipping', '/shop-online/542/fragrances', '/shop-online/81/vitamins', '/shop-online/257/beauty', '/shop-online/665/skin-care', '/shop-online/648/cosmetics', '/shop-online/517/weight-loss', '/shop-online/20/baby-care', '/shop-online/89/sexual-health', '/shop-online/198/smoking-deterrents', '/prescriptions', '/shop-online/258/medicines', '/shop-online/1093/cold-flu', '/shop-online/PS-1755/all-fish-oil-supplements', '/shop-online/159/oral-hygiene-and-dental-care', '/shop-online/792/household', '/shop-online/129/hair-care', '/shop-online/1255/sports-nutrition', '/bestsellers']
</code>```

What I want to be able to do, at least using the shell for now (and then scripting it) is to be able to parse out any links that don't contain shop-online, and then scrape the corresponding URLs, which will be www..website/the link I've scraped

But I'm not sure how to do this. I am aware there are regex expressions you can use, but I'm not sure how to apply them, and even if I could, I'm not sure how to then tell scrapy to iterate through what I've found and scrape THOSE pages?

答:
I want to […] parse out any links that don't contain shop-online, and then scrape the corresponding URLs

In a spider callback, that would be:

for link in response.xpath('//li//a/@href[contains(., "/shop-online/")]'):
    yield response.follow(link.get())
```

<p>In the shell, you only can handle one request at a time, because it is only meant for debugging purposes, so you would just pick one of the links and fetch it:</p>

<pre class="lang-py prettyprint-override"><code>link = response.xpath('//li//a/@href[contains(., "/shop-online/")]').get()  # Gets the first link only
fetch(response.follow(link))
</code>```

Body:
I'm just starting out with Scrapy and Python, and have been following the tutorial, but am stuck. I have been able to use the shell to get a list of links from a page, as per the below:

>>> response.css('li').xpath('a/@href').getall()

Gives me:

'/shop-online/542/fragrances', '/shop-online/81/vitamins', '/shop-online/257/beauty', '/shop-online/665/skin-care', '/shop-online/648/cosmetics', '/shop-online/517/weight-loss', '/shop-online/20/baby-care', '/shop-online/89/sexual-health', '/shop-online/198/smoking-deterrents', '/shop-online/3240/clearance', '/prescriptions', '/shop-online/258/medicines', '/shop-online/1093/cold-flu', '/shop-online/PS-1755/all-fish-oil-supplements', '/shop-online/159/oral-hygiene-and-dental-care', '/shop-online/792/household', '/shop-online/129/hair-care', '/shop-online/1255/sports-nutrition', '/bestsellers', '/categories', 'https://www.chemistwarehouse.hk', '/', '#', '/login', '/youraccount', '#', '/aboutus', '/aboutus/shipping', '/shop-online/542/fragrances', '/shop-online/81/vitamins', '/shop-online/257/beauty', '/shop-online/665/skin-care', '/shop-online/648/cosmetics', '/shop-online/517/weight-loss', '/shop-online/20/baby-care', '/shop-online/89/sexual-health', '/shop-online/198/smoking-deterrents', '/prescriptions', '/shop-online/258/medicines', '/shop-online/1093/cold-flu', '/shop-online/PS-1755/all-fish-oil-supplements', '/shop-online/159/oral-hygiene-and-dental-care', '/shop-online/792/household', '/shop-online/129/hair-care', '/shop-online/1255/sports-nutrition', '/bestsellers']

What I want to be able to do, at least using the shell for now (and then scripting it) is to be able to parse out any links that don't contain shop-online, and then scrape the corresponding URLs, which will be www..website/the link I've scraped

But I'm not sure how to do this. I am aware there are regex expressions you can use, but I'm not sure how to apply them, and even if I could, I'm not sure how to then tell scrapy to iterate through what I've found and scrape THOSE pages?

Body:
I want to […] parse out any links that don't contain shop-online, and then scrape the corresponding URLs

In a spider callback, that would be:

for link in response.xpath('//li//a/@href[contains(., "/shop-online/")]'):
    yield response.follow(link.get())

In the shell, you only can handle one request at a time, because it is only meant for debugging purposes, so you would just pick one of the links and fetch it:

link = response.xpath('//li//a/@href[contains(., "/shop-online/")]').get()  # Gets the first link only
fetch(response.follow(link))


问:
R dataframe - extract pair of rows based on two variables then combine the rows based on custom colwise function
Trying to consolidate sample pairs and their variables based on whether the sample pair has a TRUE or FALSE boolean in one or both of its sample type. some samples may have only one sample type, but never more than 1 A and 1 B type samples.

for the dataframe below:

```<code>   a     b     c      d      e     f      g     h      samples_name sample_type
1  FALSE FALSE FALSE  FALSE  FALSE TRUE   FALSE FALSE  PAEEYP         A
2  FALSE TRUE  FALSE  FALSE  FALSE FALSE  FALSE FALSE  PAEEYP         B
3  FALSE FALSE FALSE  FALSE  FALSE FALSE  FALSE TRUE   PAERAH         A
4  FALSE FALSE FALSE  FALSE  FALSE FALSE  FALSE TRUE   PAERAH         B
5  FALSE FALSE FALSE  TRUE   TRUE  FALSE  FALSE FALSE  PAKIYW         A  \\only has A sample
</code>```

4 possible values 1) FALSE = both FALSE; 2)A = TRUE in A only; 3)B = TRUE in B only, 4)TRUE = both TRUE

```<code>   a     b     c      d      e     f      g     h      samples_name
1  FALSE B     FALSE  FALSE  FALSE A      FALSE FALSE  PAEEYP
2  FALSE FALSE FALSE  FALSE  FALSE FALSE  FALSE TRUE   PAERAH
3  FALSE FALSE FALSE  A      A     FALSE  FALSE FALSE  PAKIYW
</code>```

I am stuck and don't know how to do it. I suppose I need to subset/group them by samples name, sort them based on sample type, then apply some colwise ifelse function in each subset/group before merging into a dataframe. I thought about using ddply to do the subsetting and apply colwise function but I can't get my head around. Somehow I think I am overthinking the problem, any help will be appreciated .

答:
I ran into some issues because your desired output mixes logical and character...

This solution is not the most pretty. It is hacked together on the fly ;-).

But perhaps it will set you in the right direction, or inspire others to come up with better answers...

sample data

```<code>library( data.table )

DT <- fread("a     b     c      d      e     f      g     h      samples_name sample_type
  FALSE FALSE FALSE  FALSE  FALSE TRUE   FALSE FALSE  PAEEYP         A
  FALSE TRUE  FALSE  FALSE  FALSE FALSE  FALSE FALSE  PAEEYP         B
  FALSE FALSE FALSE  FALSE  FALSE FALSE  FALSE TRUE   PAERAH         A
  FALSE FALSE FALSE  FALSE  FALSE FALSE  FALSE TRUE   PAERAH         B
  FALSE FALSE FALSE  TRUE   TRUE  FALSE  FALSE FALSE  PAKIYW         A")
</code>```

code

```<code>#melt to long
DT.melt <- melt( DT, id.vars = c( "samples_name", "sample_type" ) )
#set TRUE/FALSE to 1/0
DT.melt[, value := as.numeric( value )]
#only keep roes where value > 0
ans <- DT.melt[ !value == 0, ]
ans <- ans[, .(total = paste0(sample_type, collapse = "")), by = .(samples_name, variable)]
ans[ total == "AB", total := "TRUE"]
#    samples_name variable total
# 1:       PAEEYP        b     B
# 2:       PAKIYW        d     A
# 3:       PAKIYW        e     A
# 4:       PAEEYP        f     A
# 5:       PAERAH        h  TRUE

#create new melt without the sample_type
DT.melt2 <- melt( DT, id.vars = c( "samples_name" ), measure.vars = patterns("^[a-h]$") )
#set value to character, drop duplicates
DT.melt2 <- unique( DT.melt2[, value := as.character(value)], by = c("samples_name", "variable"))
#update join answer
DT.melt2[ ans, value := i.total, on = .(samples_name, variable)]
#and cast back to wide format
dcast(DT.melt2, samples_name ~ variable, value.var = "value")
</code>```

output

```<code>#    samples_name     a     b     c     d     e     f     g     h
# 1:       PAEEYP FALSE     B FALSE FALSE FALSE     A FALSE FALSE
# 2:       PAERAH FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
# 3:       PAKIYW FALSE FALSE FALSE     A     A FALSE FALSE FALSE
</code>```

Body:
Trying to consolidate sample pairs and their variables based on whether the sample pair has a TRUE or FALSE boolean in one or both of its sample type. some samples may have only one sample type, but never more than 1 A and 1 B type samples.

for the dataframe below:

   a     b     c      d      e     f      g     h      samples_name sample_type
1  FALSE FALSE FALSE  FALSE  FALSE TRUE   FALSE FALSE  PAEEYP         A
2  FALSE TRUE  FALSE  FALSE  FALSE FALSE  FALSE FALSE  PAEEYP         B
3  FALSE FALSE FALSE  FALSE  FALSE FALSE  FALSE TRUE   PAERAH         A
4  FALSE FALSE FALSE  FALSE  FALSE FALSE  FALSE TRUE   PAERAH         B
5  FALSE FALSE FALSE  TRUE   TRUE  FALSE  FALSE FALSE  PAKIYW         A  \\only has A sample

4 possible values 1) FALSE = both FALSE; 2)A = TRUE in A only; 3)B = TRUE in B only, 4)TRUE = both TRUE

   a     b     c      d      e     f      g     h      samples_name
1  FALSE B     FALSE  FALSE  FALSE A      FALSE FALSE  PAEEYP
2  FALSE FALSE FALSE  FALSE  FALSE FALSE  FALSE TRUE   PAERAH
3  FALSE FALSE FALSE  A      A     FALSE  FALSE FALSE  PAKIYW

I am stuck and don't know how to do it. I suppose I need to subset/group them by samples name, sort them based on sample type, then apply some colwise ifelse function in each subset/group before merging into a dataframe. I thought about using ddply to do the subsetting and apply colwise function but I can't get my head around. Somehow I think I am overthinking the problem, any help will be appreciated .

Body:
I ran into some issues because your desired output mixes logical and character...

This solution is not the most pretty. It is hacked together on the fly ;-).

But perhaps it will set you in the right direction, or inspire others to come up with better answers...

sample data

library( data.table )

DT <- fread("a     b     c      d      e     f      g     h      samples_name sample_type
  FALSE FALSE FALSE  FALSE  FALSE TRUE   FALSE FALSE  PAEEYP         A
  FALSE TRUE  FALSE  FALSE  FALSE FALSE  FALSE FALSE  PAEEYP         B
  FALSE FALSE FALSE  FALSE  FALSE FALSE  FALSE TRUE   PAERAH         A
  FALSE FALSE FALSE  FALSE  FALSE FALSE  FALSE TRUE   PAERAH         B
  FALSE FALSE FALSE  TRUE   TRUE  FALSE  FALSE FALSE  PAKIYW         A")

code

#melt to long
DT.melt <- melt( DT, id.vars = c( "samples_name", "sample_type" ) )
#set TRUE/FALSE to 1/0
DT.melt[, value := as.numeric( value )]
#only keep roes where value > 0
ans <- DT.melt[ !value == 0, ]
ans <- ans[, .(total = paste0(sample_type, collapse = "")), by = .(samples_name, variable)]
ans[ total == "AB", total := "TRUE"]
#    samples_name variable total
# 1:       PAEEYP        b     B
# 2:       PAKIYW        d     A
# 3:       PAKIYW        e     A
# 4:       PAEEYP        f     A
# 5:       PAERAH        h  TRUE

#create new melt without the sample_type
DT.melt2 <- melt( DT, id.vars = c( "samples_name" ), measure.vars = patterns("^[a-h]$") )
#set value to character, drop duplicates
DT.melt2 <- unique( DT.melt2[, value := as.character(value)], by = c("samples_name", "variable"))
#update join answer
DT.melt2[ ans, value := i.total, on = .(samples_name, variable)]
#and cast back to wide format
dcast(DT.melt2, samples_name ~ variable, value.var = "value")

output

#    samples_name     a     b     c     d     e     f     g     h
# 1:       PAEEYP FALSE     B FALSE FALSE FALSE     A FALSE FALSE
# 2:       PAERAH FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
# 3:       PAKIYW FALSE FALSE FALSE     A     A FALSE FALSE FALSE


问:
GULP Create JSON file from another JSON file
I am trying to create a local lang file that will be formatted as json. I have the following navigation in json format below. And I need to create a new JSON file using GULP to create a lang file (see below)

```<code>  "lists": [
    {
      "title": "Application Intel",
      "items": [
        {
          "title": "Analytics Dashboard",
          "href": "intel_analytics_dashboard.html"
        },
        {
          "title": "Marketing Dashboard",
          "href": "intel_marketing_dashboard.html"
        },
        {
          "title": "CEO Dashboard",
          "href": "intel_ceo_dashboard.html"
        },
        {
          "title": "Introduction",
          "href": "intel_introduction.html"
        },
        {
          "title": "Build Notes",
          "href": "intel_build_notes.html",
          "text": "Build Notes",
          "span": {
            "class": "",
            "text": "v{{version}}"
          }
        }
      ]
    }
</code>```

I need to create a file that looks like the following json:

```<code>  "nav": {
    "application_intel": "Application Intel",
    "intel_analytics_dashboard": "Analytics Dashboard",
    "intel_marketing_dashboard": "Marketing Dashboard",
    "intel_ceo_dashboard": "CEO Dashboard",
    "intel_introduction": "Introduction",
    "intel_build_notes": "Build Notes",
  }
</code>```

Whats the best way to go about this?

答:
Here is solution.
Let's say you have nav.json file inside src and you want to change its shape and place it into dest directory. You can achieve this from within gulpfile.js

```<code>const { src, dest } = require("gulp");
const through = require("through2");

// gulp task
function json() {
  return src("src/nav.json")
    .pipe(
      through.obj((file, enc, cb) => {
        // get content of json file
        const rawJSON = file.contents.toString();

        // parse raw json into javscript object
        const parsed = JSON.parse(rawJSON);

        // transform json into desired shape
        const transformed = transformJson(parsed);

        // make string from javascript obj
        const stringified = JSON.stringify(transformed, null, 2);

        // make bufer from string and attach it as current file content
        file.contents = Buffer.from(stringified);

        // pass transformed file into next gulp pipe
        cb(null, file);
      })
    )
    .pipe(dest("dest"));
}

// transformation
function transformJson(input) {
  const result = { nav: {} };

  // read json field by field
  Object.keys(input).forEach(topLevelKey => {
    // current object
    const topLevelItem = input[topLevelKey];

    // in your design topLevelItems are arrays
    topLevelItem.forEach(menuItem => {
      if (menuItem.title) {
        // make url either from item href or title
        const itemUrl = makeUrl(menuItem.href || menuItem.title);
        result.nav[itemUrl] = menuItem.title;
      }

      // prcoess children
      if (menuItem.items) {
        menuItem.items
          .filter(child => !!child.title) // process only child items with title
          .forEach(child => {
            const childUrl = makeUrl(child.href || child.title);
            result.nav[childUrl] = child.title;
          });
      }
    });
  });

  return result;
}

// helper func
function makeUrl(href) {
  return href
    .toLowerCase()
    .replace(/\.html$/, "")
    .replace(/\s/g, "_");
}

// export for use in command line
exports.json = json;

</code>```

json transformation function is bit forEachy and if you have deep nested navigation structure, maybe you should change it into something recursive

Body:
I am trying to create a local lang file that will be formatted as json. I have the following navigation in json format below. And I need to create a new JSON file using GULP to create a lang file (see below)

  "lists": [
    {
      "title": "Application Intel",
      "items": [
        {
          "title": "Analytics Dashboard",
          "href": "intel_analytics_dashboard.html"
        },
        {
          "title": "Marketing Dashboard",
          "href": "intel_marketing_dashboard.html"
        },
        {
          "title": "CEO Dashboard",
          "href": "intel_ceo_dashboard.html"
        },
        {
          "title": "Introduction",
          "href": "intel_introduction.html"
        },
        {
          "title": "Build Notes",
          "href": "intel_build_notes.html",
          "text": "Build Notes",
          "span": {
            "class": "",
            "text": "v{{version}}"
          }
        }
      ]
    }

I need to create a file that looks like the following json:

  "nav": {
    "application_intel": "Application Intel",
    "intel_analytics_dashboard": "Analytics Dashboard",
    "intel_marketing_dashboard": "Marketing Dashboard",
    "intel_ceo_dashboard": "CEO Dashboard",
    "intel_introduction": "Introduction",
    "intel_build_notes": "Build Notes",
  }

Whats the best way to go about this?

Body:
Here is solution.
Let's say you have nav.json file inside src and you want to change its shape and place it into dest directory. You can achieve this from within gulpfile.js

const { src, dest } = require("gulp");
const through = require("through2");

// gulp task
function json() {
  return src("src/nav.json")
    .pipe(
      through.obj((file, enc, cb) => {
        // get content of json file
        const rawJSON = file.contents.toString();

        // parse raw json into javscript object
        const parsed = JSON.parse(rawJSON);

        // transform json into desired shape
        const transformed = transformJson(parsed);

        // make string from javascript obj
        const stringified = JSON.stringify(transformed, null, 2);

        // make bufer from string and attach it as current file content
        file.contents = Buffer.from(stringified);

        // pass transformed file into next gulp pipe
        cb(null, file);
      })
    )
    .pipe(dest("dest"));
}

// transformation
function transformJson(input) {
  const result = { nav: {} };

  // read json field by field
  Object.keys(input).forEach(topLevelKey => {
    // current object
    const topLevelItem = input[topLevelKey];

    // in your design topLevelItems are arrays
    topLevelItem.forEach(menuItem => {
      if (menuItem.title) {
        // make url either from item href or title
        const itemUrl = makeUrl(menuItem.href || menuItem.title);
        result.nav[itemUrl] = menuItem.title;
      }

      // prcoess children
      if (menuItem.items) {
        menuItem.items
          .filter(child => !!child.title) // process only child items with title
          .forEach(child => {
            const childUrl = makeUrl(child.href || child.title);
            result.nav[childUrl] = child.title;
          });
      }
    });
  });

  return result;
}

// helper func
function makeUrl(href) {
  return href
    .toLowerCase()
    .replace(/\.html$/, "")
    .replace(/\s/g, "_");
}

// export for use in command line
exports.json = json;

json transformation function is bit forEachy and if you have deep nested navigation structure, maybe you should change it into something recursive


问:
Can anyone convert this linq code into a SQL query (because I don't understand what is it doing)?
```<code>var don2 = db.Panels.Include(y => y.Invoice)
                    .Include(x => x.PanelTypeEntries
                                   .Select(a => a.SubItems))
                    .Where(v => v.Invoice_Id == Quotation_Id)
                    .ToList();
</code>```

答:
Here is what is doing this piece of LinQ :

The code is using the Panels Entity set of you dbContext, that's mean the Panels table in your database.

Then, you are including an Invoice Entity, because it is part of your Panels one. It is most likely another table with a relation with Panels.

You are also including what looks like a collection of PanelTypeEntries to your Panels Entity. You probably have a N-N relation between those tables in your database. While including PanelTypeEntries, you are just SELECTing its SubItems property. Probably because Panels does not contains a List ofPanelTypeEntries, but a List of SubItems.

The where() clause is the same as in SQL.

Finaly, the ToList() ask to the provider to execute the request and to store it in a List. That's why var don2's type is of List.


问:
AS3 1120 Error on instantiating
I am trying to create a basic functionality in AS3.

I have a class like this:

```<code>package tax
{
    public class Calculator
    {

        public function Calculator()
        {
        }

        private var grwage:Number;
        private var taxes:Number;
        private var superannuation:Number;
        private var insurance:Number;
        private var net:Number;

        public function getGrwage():Number {
            return grwage;
        }

        public function setGrwage(grwage:Number):void {
            this.grwage = grwage;
        }

        public function getTaxes():Number {
            return grwage;
        }

        public function setTaxes(taxes:Number):void {
            this.taxes = grwage * 0.2;
        }

        public function getSup():Number {
            return superannuation;
        }

        public function setSup(superannuation:Number):void {
            this.superannuation = superannuation * 0.05;
        }

        public function getIns():Number {
            return insurance;
        }

        public function setIns(insurance:Number):void {
            this.insurance = insurance * 0.1;
        }

        public function getNet():Number {
            return net;
        }

        public function setNet(net:Number):void {
            this.net = grwage - taxes - superannuation - insurance;
        }

    }
}
</code>```

Just some getters and setters.

And in my mxml file:

```<code>        import tax.Calculator;

                    public var calculate:Calculator = new Calculator();

        calculate.setGrwage(1000);
        trace(calculate.getTaxes());
        trace(calculate.getSup());
        trace(calculate.getIns());
        trace(calculate.getNet());
</code>```

I get an error 1120 Access to undefinded property when I try to access calculate. Do you have any ideas?

Thanks.

答:
I guess you're mixing up things a bit between getters and setters. If a variable depends on another, you have to write the calculation in its getter. This variable shouldn't exist as a private member and the accesses to it must always be done through the appropriate getter.

for example:

```<code>public function getNet():Number {
    return getGrwage() - getTaxes() - getSup() - getIns();
}
</code>```

So here, you only need one setter (setGrwage), you can remove the others ones and put the calculation in the getters.

Note that there is a more appropriate syntax for setters and getters in AS3.

```<code>class GetSet
{
    private var privateProperty:String;

    public function get publicAccess():String
    {
        return privateProperty;
    }

    public function set publicAccess(setValue:String):void
    {
        privateProperty = setValue;
    }
}
</code>```

Title: AS3 1120 Error on instantiating

Body:
I am trying to create a basic functionality in AS3.

I have a class like this:

package tax
{
    public class Calculator
    {

        public function Calculator()
        {
        }

        private var grwage:Number;
        private var taxes:Number;
        private var superannuation:Number;
        private var insurance:Number;
        private var net:Number;

        public function getGrwage():Number {
            return grwage;
        }

        public function setGrwage(grwage:Number):void {
            this.grwage = grwage;
        }

        public function getTaxes():Number {
            return grwage;
        }

        public function setTaxes(taxes:Number):void {
            this.taxes = grwage * 0.2;
        }

        public function getSup():Number {
            return superannuation;
        }

        public function setSup(superannuation:Number):void {
            this.superannuation = superannuation * 0.05;
        }

        public function getIns():Number {
            return insurance;
        }

        public function setIns(insurance:Number):void {
            this.insurance = insurance * 0.1;
        }

        public function getNet():Number {
            return net;
        }

        public function setNet(net:Number):void {
            this.net = grwage - taxes - superannuation - insurance;
        }

    }
}

Just some getters and setters.

And in my mxml file:

        import tax.Calculator;

                    public var calculate:Calculator = new Calculator();

        calculate.setGrwage(1000);
        trace(calculate.getTaxes());
        trace(calculate.getSup());
        trace(calculate.getIns());
        trace(calculate.getNet());

I get an error 1120 Access to undefinded property when I try to access calculate. Do you have any ideas?

Thanks.

Body:
I guess you're mixing up things a bit between getters and setters. If a variable depends on another, you have to write the calculation in its getter. This variable shouldn't exist as a private member and the accesses to it must always be done through the appropriate getter.

for example:

public function getNet():Number {
    return getGrwage() - getTaxes() - getSup() - getIns();
}

So here, you only need one setter (setGrwage), you can remove the others ones and put the calculation in the getters.

Note that there is a more appropriate syntax for setters and getters in AS3.

class GetSet
{
    private var privateProperty:String;

    public function get publicAccess():String
    {
        return privateProperty;
    }

    public function set publicAccess(setValue:String):void
    {
        privateProperty = setValue;
    }
}


问:
flyway/springboot - configure to run on production/test but not on dev
How to check through spring-boot that if the database schema is already present do not run but run if no matching schema. Can I do the following through spring-boot flyway integration.

DEV - already has the database tables matching the sql scripts (e.g V1_Baseline.sql has both table creation and reference data) so should not run this but will need to create the internal SCHEMA_VERSION table and make this script as already run so that V2_....sql will run next)

TEST - has tables that should not be dropped but the scripts need to be run and internal SCHEMA_VERSION table created.

PROD - this is empty. So no issues should be there (same as test i guess).

From flyway site  I saw this:

flyway clean  (cannot run - nothing should be dropped)

flyway baseline (i think this is the one I need? check if current db is matching then just make current scripts as baseline and dont run if not run the scripts)

Nothing concrete here on here spring io too and on baeldung too.

I think answer is here with baseline and doing some checks but not sure what works.

答: Baseline is indeed what you need here as it serves this exact purpose.</p>


问:
How to run some code before page is displayed
I have trouble running some code before page loads in jquery or js. Anything I do the page would have a brief load then my codes run. I run code before user sees the page but it loads in a brief milliseconds then my code runs.

I have done some solutions and didn't do what I want:

I've put my codes before document.ready

I've put my code in head section

I've put my code in a function then called the function in head tag

I also tried onload() in js

But the same result: my code runs after milliseconds and user sees the page before running code in these milliseconds

Any ideas?

答:
Jquery and Javascript are client side languages, and are read by the browser as the page loads.

Usually we would use something like:

```<code>$(document).ready(function(){
    //do stuff
});
</code>```

This is to make sure the elements are loaded on screen before the JS functions run to make sure any elements that are needed for the script have been loaded.

What you seem to be doing is running the script at the same time as the page loads so there might be something in the script that prevents the rest of the HTML from loading as this is running and thats why you see the load time.

You should look at PHP. (hypertext pre-processor) This is a server side language rather than client side. So it pre-processes what you want server side and then sends that to the users client/browser.

Check out http://www.developphp.com/

Body:
Jquery and Javascript are client side languages, and are read by the browser as the page loads.

Usually we would use something like:

$(document).ready(function(){
    //do stuff
});

This is to make sure the elements are loaded on screen before the JS functions run to make sure any elements that are needed for the script have been loaded.

What you seem to be doing is running the script at the same time as the page loads so there might be something in the script that prevents the rest of the HTML from loading as this is running and thats why you see the load time.

You should look at PHP. (hypertext pre-processor) This is a server side language rather than client side. So it pre-processes what you want server side and then sends that to the users client/browser.

Check out http://www.developphp.com/


问:
Convert HTML to PDF in .NET
I want to generate a PDF by passing HTML contents to a function. I have made use of iTextSharp for this but it does not perform well when it encounters tables and the layout just gets messy.

Is there a better way?

答:
Most HTML to PDF converter relies on IE to do the HTML parsing and rendering. This can break when user updates their IE. Here is one that does not rely on IE.

The code is something like this:

```<code>EO.Pdf.HtmlToPdf.ConvertHtml(htmlText, pdfFileName);
</code>```

Like many other converters, you can pass text, file name, or Url. The result can be saved into a file or a stream.

OwnerDisplayName: SandHurst

Title: Convert HTML to PDF in .NET

Body:
Most HTML to PDF converter relies on IE to do the HTML parsing and rendering. This can break when user updates their IE. Here is one that does not rely on IE.

The code is something like this:

EO.Pdf.HtmlToPdf.ConvertHtml(htmlText, pdfFileName);

Like many other converters, you can pass text, file name, or Url. The result can be saved into a file or a stream.


问:
A simple pivot but can't get my head around it - please assist..:-)
I try to do a simple pivot in MS SSMS, but can't figure it out.

This is my data set:

```<code>Date        CallerANI      Skills               CallerDNIS
2019-05-27  27315391449    loc-SPD-CSR-OverFlow 47515070001
2019-05-27  27315391449    cc-Loc-Voice         Transfer
</code>```

and statement:

```<code>SELECT [Date],
       CallerANI,
       [47515001101],
       [Transfer]
FROM (SELECT [Date], Skills, CallerANI, CallerDNIS FROM #TempDB) AS p
PIVOT (MAX(Skills)
       FOR CallerDNIS IN ([47515001101], [Transfer])) AS pvt;
</code>```

I want to pivot so that the result looks like this:

```<code>Date            CallerANI              [47515070001]            [Transfer]
2019-05-27      273135391449           loc-SPD-CSR-OverFlow     cc-loc-Voice
</code>```

答:
The below code helps you to dynamically Pivot N number of rows

```<code>DECLARE @DynamicCols VARCHAR(MAX);

CREATE TABLE #temp ([Date] DATE, [CallerANI] VARCHAR(MAX), [Skills] VARCHAR(MAX), [CallerDNIS] VARCHAR(MAX))

INSERT INTO #temp
VALUES ('2019-05-27','27315391449','loc-SPD-CSR-OverFlow','47515070001'),
       ('2019-05-27','27315391449','cc-Loc-Voice','Transfer'),
       ('2019-05-27','27315391449','cc-Loc-Voice-abc','SoMe')

SELECT * FROM #temp

SELECT @DynamicCols = STUFF([Cols],1,1,'') FROM (
SELECT [Cols] = (SELECT ',' + QUOTENAME([CallerDNIS]) FROM #temp A
                   FOR XML PATH('') ) ) A;

EXEC ('
SELECT [Date], [CallerANI], ' + @DynamicCols+'
FROM #temp
PIVOT
(
  MAX([Skills])
  FOR [CallerDNIS] in (' + @DynamicCols+')
) PIV');
</code>```

Body:
I try to do a simple pivot in MS SSMS, but can't figure it out.

This is my data set:

Date        CallerANI      Skills               CallerDNIS
2019-05-27  27315391449    loc-SPD-CSR-OverFlow 47515070001
2019-05-27  27315391449    cc-Loc-Voice         Transfer

and statement:

SELECT [Date],
       CallerANI,
       [47515001101],
       [Transfer]
FROM (SELECT [Date], Skills, CallerANI, CallerDNIS FROM #TempDB) AS p
PIVOT (MAX(Skills)
       FOR CallerDNIS IN ([47515001101], [Transfer])) AS pvt;

I want to pivot so that the result looks like this:

Date            CallerANI              [47515070001]            [Transfer]
2019-05-27      273135391449           loc-SPD-CSR-OverFlow     cc-loc-Voice

Body:
The below code helps you to dynamically Pivot N number of rows

DECLARE @DynamicCols VARCHAR(MAX);

CREATE TABLE #temp ([Date] DATE, [CallerANI] VARCHAR(MAX), [Skills] VARCHAR(MAX), [CallerDNIS] VARCHAR(MAX))

INSERT INTO #temp
VALUES ('2019-05-27','27315391449','loc-SPD-CSR-OverFlow','47515070001'),
       ('2019-05-27','27315391449','cc-Loc-Voice','Transfer'),
       ('2019-05-27','27315391449','cc-Loc-Voice-abc','SoMe')

SELECT * FROM #temp

SELECT @DynamicCols = STUFF([Cols],1,1,'') FROM (
SELECT [Cols] = (SELECT ',' + QUOTENAME([CallerDNIS]) FROM #temp A
                   FOR XML PATH('') ) ) A;

EXEC ('
SELECT [Date], [CallerANI], ' + @DynamicCols+'
FROM #temp
PIVOT
(
  MAX([Skills])
  FOR [CallerDNIS] in (' + @DynamicCols+')
) PIV');