问:
It's showing error while building signed apk
When I am building apk it's not showing any error but while generating signed apk it's showing following error in logcat.

Error:

```<code>  Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
  referenced class java.lang.management.ManagementFactory
   Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
   referenced class java.lang.management.ThreadMXBean
   Warning:org.junit.rules.DisableOnDebug: can't find referenced class
   java.lang.management.RuntimeMXBean
   Warning:org.junit.rules.DisableOnDebug: can't find referenced class
   java.lang.management.RuntimeMXBean
  Error:Execution failed for task
  ':app:transformClassesAndResourcesWithProguardForRelease'.
 > Job failed, see logs for details
 Warning:there were 10 unresolved references to classes or interfaces.
 Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
 referenced class java.lang.management.ManagementFactory
 Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
 referenced class java.lang.management.ThreadMXBean
 Warning:Exception while processing task java.io.IOException: Please correct
 the above warnings first.
 Warning:org.junit.rules.DisableOnDebug: can't find referenced class
 java.lang.management.ManagementFactory
 Warning:org.junit.rules.DisableOnDebug: can't find referenced class
 java.lang.management.ManagementFactory
</code>```

my build.gradle file is:

```<code>apply plugin: 'com.android.application'
</code>```

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'

```<code>defaultConfig {
    applicationId "com.infinity.wall_to_paper"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    buildTypes{
        debug{
            debuggable true
        }
    }
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
dexOptions {
    incremental true
    javaMaxHeapSize "4g"
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENCE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENCE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/licence.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}
</code>```

}

```<code>    dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile('com.android.support:appcompat-v7:23.4.0') {
    exclude module: 'support-v4'
}
compile('com.android.support:support-v4:23.4.0') {
    exclude module: 'support-v4'
}
android {
    buildTypes {
        debug {
            debuggable true
        }
    }
    compile 'com.android.support:recyclerview-v7:23.4.0'
    compile 'com.android.support:cardview-v7:23.4.0'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-ads:10.2.4'
}
</code>```

}

答:
Inside your build.gradle look for the dexOptions:

```<code>dexOptions {
    incremental true
    javaMaxHeapSize "4g"
    }
</code>```

Comment out the line:incremental true.

By default incremental is turned on Java compilation in 2.1.0-rc1 (2016/4/22) or later. So its redundant to declare it in build.gradle file.
For more information check this out: https://stackoverflow.com/a/37540467/5192105

Open your proguard-project.txt(config file) and add.

```<code>-dontwarn sun.reflect.**
-dontwarn android.test.**
</code>```

Hope this helps.

To disable this:

```<code>Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
 referenced class java.lang.management.ManagementFactory
Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
referenced class java.lang.management.ThreadMXBean
Warning:org.junit.rules.DisableOnDebug: can't find referenced class
java.lang.management.RuntimeMXBean
Warning:org.junit.rules.DisableOnDebug: can't find referenced class
java.lang.management.RuntimeMXBean
Error:Execution failed for task
':app:transformClassesAndResourcesWithProguardForRelease'.
</code>```

Open your proguard.pro and add :

-dontwarn java.lang.management.**

Body:
When I am building apk it's not showing any error but while generating signed apk it's showing following error in logcat.

Error:

  Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
  referenced class java.lang.management.ManagementFactory
   Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
   referenced class java.lang.management.ThreadMXBean
   Warning:org.junit.rules.DisableOnDebug: can't find referenced class
   java.lang.management.RuntimeMXBean
   Warning:org.junit.rules.DisableOnDebug: can't find referenced class
   java.lang.management.RuntimeMXBean
  Error:Execution failed for task
  ':app:transformClassesAndResourcesWithProguardForRelease'.
 > Job failed, see logs for details
 Warning:there were 10 unresolved references to classes or interfaces.
 Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
 referenced class java.lang.management.ManagementFactory
 Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
 referenced class java.lang.management.ThreadMXBean
 Warning:Exception while processing task java.io.IOException: Please correct
 the above warnings first.
 Warning:org.junit.rules.DisableOnDebug: can't find referenced class
 java.lang.management.ManagementFactory
 Warning:org.junit.rules.DisableOnDebug: can't find referenced class
 java.lang.management.ManagementFactory

my build.gradle file is:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'

defaultConfig {
    applicationId "com.infinity.wall_to_paper"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    buildTypes{
        debug{
            debuggable true
        }
    }
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
dexOptions {
    incremental true
    javaMaxHeapSize "4g"
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENCE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENCE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/licence.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}

}

    dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile('com.android.support:appcompat-v7:23.4.0') {
    exclude module: 'support-v4'
}
compile('com.android.support:support-v4:23.4.0') {
    exclude module: 'support-v4'
}
android {
    buildTypes {
        debug {
            debuggable true
        }
    }
    compile 'com.android.support:recyclerview-v7:23.4.0'
    compile 'com.android.support:cardview-v7:23.4.0'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-ads:10.2.4'
}

}

Body:
Inside your build.gradle look for the dexOptions:

dexOptions {
    incremental true
    javaMaxHeapSize "4g"
    }

Comment out the line:incremental true.

By default incremental is turned on Java compilation in 2.1.0-rc1 (2016/4/22) or later. So its redundant to declare it in build.gradle file.
For more information check this out: https://stackoverflow.com/a/37540467/5192105

Open your proguard-project.txt(config file) and add.

-dontwarn sun.reflect.**
-dontwarn android.test.**

Hope this helps.

To disable this:

Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
 referenced class java.lang.management.ManagementFactory
Warning:org.junit.internal.runners.statements.FailOnTimeout: can't find
referenced class java.lang.management.ThreadMXBean
Warning:org.junit.rules.DisableOnDebug: can't find referenced class
java.lang.management.RuntimeMXBean
Warning:org.junit.rules.DisableOnDebug: can't find referenced class
java.lang.management.RuntimeMXBean
Error:Execution failed for task
':app:transformClassesAndResourcesWithProguardForRelease'.

Open your proguard.pro and add :

-dontwarn java.lang.management.**


来源: stackexchange

问:
Links being acted on -- style in CSS or using JavaScript?
Should you use a:hover, a:active, a:visited and a:link, or similar javascript things (tags??) instead?</p>

答: If a:active, etc. will meet your needs, I would definitely use those in your CSS. I do all the time. Did you want additional functionality?</p>

ContentLicense: CC BY-SA 2.5


问:
Strange FPS and frame number while re-encoding a video
I am re-encoding a video using below command:

```<code>ffmpeg -i input.mp4 -q 20 output.avi
</code>```

The video is 10 mins approx, i.e, it has around 18K frames. However, I am getting last frame number as 5061, but the re-encoded video is playing for all 10 mins. I don't understand the reason why it is showing such a low frame number. Below is last few lines of output.

```<code>frame= 5028 fps=143 q=20.0 size=   24863kB time=00:09:53.20 bitrate= 343.4kbits/s dup=0 drop=2087
Past duration 1.703728 too large
Past duration 0.986687 too large
Past duration 0.704277 too large
Past duration 0.954399 too large
Past duration 1.951469 too large
Past duration 0.879509 too large
Past duration 0.942192 too large
Past duration 0.815910 too large
Past duration 0.785393 too large
Past duration 0.792351 too large
Past duration 0.644402 too large
frame= 5061 fps=143 q=20.0 Lsize=   25493kB time=00:09:56.45 bitrate= 350.1kbits/s dup=0 drop=2098
video:22458kB audio:2320kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 2.886272%
</code>```

Edit: Here is the log

答:
As the log shows, the input FPS is 12.

Stream #0:0(eng): Video: h264 (Baseline) (avc1 / 0x31637661), yuv420p, 1280x720, 3354 kb/s, 12 fps, 90k tbr, 90k tbn, 180k tbc (default)

It's probably variable frame rate and ffmpeg writes constant frame rate for AVI, so portions of the video with FPS greater than 12 FPS will have dropped frames. You could avoid that by specifying a higher manual framerate e.g. -r 20 but you will end up duplicating frames elsewhere.

ContentLicense: CC BY-SA 3.0

Body:
I am re-encoding a video using below command:

ffmpeg -i input.mp4 -q 20 output.avi

The video is 10 mins approx, i.e, it has around 18K frames. However, I am getting last frame number as 5061, but the re-encoded video is playing for all 10 mins. I don't understand the reason why it is showing such a low frame number. Below is last few lines of output.

frame= 5028 fps=143 q=20.0 size=   24863kB time=00:09:53.20 bitrate= 343.4kbits/s dup=0 drop=2087
Past duration 1.703728 too large
Past duration 0.986687 too large
Past duration 0.704277 too large
Past duration 0.954399 too large
Past duration 1.951469 too large
Past duration 0.879509 too large
Past duration 0.942192 too large
Past duration 0.815910 too large
Past duration 0.785393 too large
Past duration 0.792351 too large
Past duration 0.644402 too large
frame= 5061 fps=143 q=20.0 Lsize=   25493kB time=00:09:56.45 bitrate= 350.1kbits/s dup=0 drop=2098
video:22458kB audio:2320kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 2.886272%

Edit: Here is the log


问:
R Estimating the population median value by combining sample medians
I need to calculate the population median for several time periods by combining the medians of 10 different samples in each period (dataset Median). Each of the sample median has been obtained by taking a different number of observations (dataset Observation).

Median - dataset

```<code>       Time1    Time2   Time3   Time4   Time5
Sample1 60000   71139   70000   75000   75000
Sample2 80000   88000   87750   88500   90000
Sample3 66000   73325   73000   78126   75000
Sample4 60000   74000   72000   75500   73000
Sample5 50500   60000   60000   66750   81500
Sample6 60000   70000   72000   78500   80000
Sample7 50000   60000   59999   63000   60000
Sample8 53000   55000   58300   59995   64500
Sample9 92529   111000  115000  120063  118000
Sample10 92500  115000  101000  104100  110075
</code>```

Observations - dataset

```<code>Time1   Time2   Time3   Time4   Time5
Sample1 159 202 174 134 172
Sample2 148 178 148 121 140
Sample3 563 680 652 513 678
Sample4 554 634 518 512 595
Sample5 343 415 347 270 390
Sample6 738 954 769 720 825
Sample7 704 949 863 648 762
Sample8 595 681 640 517 663
Sample9 517 782 610 504 472
Sample10    627 733 621 493 512
</code>```

I am trying to generate a vector with the Median[1:1] repeated Observations[1:1] times, this vector need to be concatenate to another vector Median[1:2] repeated Observations[1:2] times, then concatenate the vector to another vector Median[1:3] repeated Observations[1:3] times , and so on...

I aim to generate 5 vectors (as many as columns - periods) each of these vectors with a length equal to the aggregate number of sample observations in each time frame.

```<code> for (i in 1:ncol(Median))  {

   for (j in 1:nrow(Median)) {

  vector_median=(seq(as.numeric(Med[i,j]),as.numeric(Med   [i,j]),length.out=as.numeric(Observations[i,j])))

 }
 }
</code>```

Body:
I need to calculate the population median for several time periods by combining the medians of 10 different samples in each period (dataset Median). Each of the sample median has been obtained by taking a different number of observations (dataset Observation).

Median - dataset

       Time1    Time2   Time3   Time4   Time5
Sample1 60000   71139   70000   75000   75000
Sample2 80000   88000   87750   88500   90000
Sample3 66000   73325   73000   78126   75000
Sample4 60000   74000   72000   75500   73000
Sample5 50500   60000   60000   66750   81500
Sample6 60000   70000   72000   78500   80000
Sample7 50000   60000   59999   63000   60000
Sample8 53000   55000   58300   59995   64500
Sample9 92529   111000  115000  120063  118000
Sample10 92500  115000  101000  104100  110075

Observations - dataset

Time1   Time2   Time3   Time4   Time5
Sample1 159 202 174 134 172
Sample2 148 178 148 121 140
Sample3 563 680 652 513 678
Sample4 554 634 518 512 595
Sample5 343 415 347 270 390
Sample6 738 954 769 720 825
Sample7 704 949 863 648 762
Sample8 595 681 640 517 663
Sample9 517 782 610 504 472
Sample10    627 733 621 493 512

I am trying to generate a vector with the Median[1:1] repeated Observations[1:1] times, this vector need to be concatenate to another vector Median[1:2] repeated Observations[1:2] times, then concatenate the vector to another vector Median[1:3] repeated Observations[1:3] times , and so on...

I aim to generate 5 vectors (as many as columns - periods) each of these vectors with a length equal to the aggregate number of sample observations in each time frame.

 for (i in 1:ncol(Median))  {

   for (j in 1:nrow(Median)) {

  vector_median=(seq(as.numeric(Med[i,j]),as.numeric(Med   [i,j]),length.out=as.numeric(Observations[i,j])))

 }
 }

Body:
Consider a nested mapply (the multiple-input version of apply family) where you pass both Med and Observations columns in pairwise iteration and then pass each of the columns corresponding Sample values in a pairwise iteration into the rep() function:

Data

txt = "       Time1    Time2   Time3   Time4   Time5
Sample1 60000   71139   70000   75000   75000
Sample2 80000   88000   87750   88500   90000
Sample3 66000   73325   73000   78126   75000
Sample4 60000   74000   72000   75500   73000
Sample5 50500   60000   60000   66750   81500
Sample6 60000   70000   72000   78500   80000
Sample7 50000   60000   59999   63000   60000
Sample8 53000   55000   58300   59995   64500
Sample9 92529   111000  115000  120063  118000
Sample10 92500  115000  101000  104100  110075 "

Med = read.table(text=txt, header=TRUE)

txt = "Time1   Time2   Time3   Time4   Time5
Sample1 159 202 174 134 172
Sample2 148 178 148 121 140
Sample3 563 680 652 513 678
Sample4 554 634 518 512 595
Sample5 343 415 347 270 390
Sample6 738 954 769 720 825
Sample7 704 949 863 648 762
Sample8 595 681 640 517 663
Sample9 517 782 610 504 472
Sample10    627 733 621 493 512"

Obs = read.table(text=txt, header=TRUE)

Process

replicate_medians <- function(m,o){
  mapply(function(m_sub, o_sub) rep(m_sub, times=o_sub), m, o)
}

output <- mapply(function(x,y) unlist(replicate_medians(x,y)), Med, Obs, SIMPLIFY=FALSE)

# EQUIVALENT WITH Map() WRAPPER
output <- Map(function(x,y) unlist(replicate_medians(x,y)), Med, Obs)

Output (returns a list of 5 named numeric vectors)

str(output)
# List of 5
#  $ Time1: int [1:4948] 60000 60000 60000 60000 60000 60000 60000 60000 60000 60000 ...
#  $ Time2: int [1:6208] 71139 71139 71139 71139 71139 71139 71139 71139 71139 71139 ...
#  $ Time3: int [1:5342] 70000 70000 70000 70000 70000 70000 70000 70000 70000 70000 ...
#  $ Time4: int [1:4432] 75000 75000 75000 75000 75000 75000 75000 75000 75000 75000 ...
#  $ Time5: int [1:5209] 75000 75000 75000 75000 75000 75000 75000 75000 75000 75000 ...

length(output$Time1[output$Time1==60000])
#[1] 1451   <---- THREE SAMPLES WITH THIS MEDIAN: 159 + 554 + 738 = 1,451

length(output$Time1[output$Time1==80000])
# [1] 148

length(output$Time1[output$Time1==66000])
# [1] 563


问:
VBA Looping through range and deleting rows based on value
I'm not sure why but i'm having a lot of difficulty running this code to loop through the range and delete the rows based on the value.  This code is part of a bigger macro i'm writing but it all runs well up to this point. </p>

```<code>Dim Lastrowresults as integer
Dim Counter as integer
Dim Resultsheet as worksheet
Dim rowcounter as integer

Set resultsheet=sheets("Search Results")
LastRowResults = ResultSheet.Range("A1").End(xlDown).Row
    For Counter = 3 To LastRowResults
      If ResultSheet.Range("I" & Counter).Value = "No" Then
         RowCounter = ResultSheet.Range("I" & Counter).Row
         Rows(RowCounter).EntireRow.Delete
     End If
    Next Counter
</code>```

答:
It turns out that it was deleting rows but that would move the row up to #3 again, so then it would essentially skip that row by moving to row #4..  this is the workaround i figured out</p>

```<code>    If SgLendsQ.Value = True Then
        LastRowResults = ResultSheet.Range("A1").End(xlDown).Row
        DelC = 3
        For Counter = 3 To LastRowResults
            If ResultSheet.Range("I" & DelC).Value = "No" Then
                ResultSheet.Rows(DelC).EntireRow.Delete
            ElseIf ResultSheet.Range("I" & DelC).Value = "Yes" Then
                DelC = DelC + 1
            End If
        Next Counter
    End If
</code>```

Body:
I'm not sure why but i'm having a lot of difficulty running this code to loop through the range and delete the rows based on the value.  This code is part of a bigger macro i'm writing but it all runs well up to this point.

Dim Lastrowresults as integer
Dim Counter as integer
Dim Resultsheet as worksheet
Dim rowcounter as integer

Set resultsheet=sheets("Search Results")
LastRowResults = ResultSheet.Range("A1").End(xlDown).Row
    For Counter = 3 To LastRowResults
      If ResultSheet.Range("I" & Counter).Value = "No" Then
         RowCounter = ResultSheet.Range("I" & Counter).Row
         Rows(RowCounter).EntireRow.Delete
     End If
    Next Counter

Body:
It turns out that it was deleting rows but that would move the row up to #3 again, so then it would essentially skip that row by moving to row #4..  this is the workaround i figured out

    If SgLendsQ.Value = True Then
        LastRowResults = ResultSheet.Range("A1").End(xlDown).Row
        DelC = 3
        For Counter = 3 To LastRowResults
            If ResultSheet.Range("I" & DelC).Value = "No" Then
                ResultSheet.Rows(DelC).EntireRow.Delete
            ElseIf ResultSheet.Range("I" & DelC).Value = "Yes" Then
                DelC = DelC + 1
            End If
        Next Counter
    End If


问:
Postman upload file on API using raw
How do you upload a file on postman using raw mode.

I used a json entry like this:

```<code>{
    "inp_doc_uid": "750761691595cf3398da311004881705",
    "tas_uid": "71415152859433e07c33b11085554015",
    "app_doc_comment":"test upload",
    "form":"@/User/images.jpg"
}
</code>```

the problem was the @ in php was deprecated and now recommended to use curlFile, how to do it in a json form?

Thanks.

答:
Since you are sending the image as part of the JSON, you would need to encode it. Base64 encoding is a good choice. On the server side, you will need to decode it as well.

See this answer to How to convert an image to base64 encoding?:

```<code>$imagedata = file_get_contents("/path/to/image.jpg");
$base64 = base64_encode($imagedata);
</code>```

Once you have the data, you can add it to the JSON:

```<code>{
    "inp_doc_uid": "750761691595cf3398da311004881705",
    "tas_uid": "71415152859433e07c33b11085554015",
    "app_doc_comment":"test upload",
    "form":"TWFuIGlzIGRpc3R..."
}
</code>```

Also see Base64 Reference

Title: Postman upload file on API using raw

Body:
How do you upload a file on postman using raw mode.

I used a json entry like this:

{
    "inp_doc_uid": "750761691595cf3398da311004881705",
    "tas_uid": "71415152859433e07c33b11085554015",
    "app_doc_comment":"test upload",
    "form":"@/User/images.jpg"
}

the problem was the @ in php was deprecated and now recommended to use curlFile, how to do it in a json form?

Thanks.

Body:
Since you are sending the image as part of the JSON, you would need to encode it. Base64 encoding is a good choice. On the server side, you will need to decode it as well.

See this answer to How to convert an image to base64 encoding?:

$imagedata = file_get_contents("/path/to/image.jpg");
$base64 = base64_encode($imagedata);

Once you have the data, you can add it to the JSON:

{
    "inp_doc_uid": "750761691595cf3398da311004881705",
    "tas_uid": "71415152859433e07c33b11085554015",
    "app_doc_comment":"test upload",
    "form":"TWFuIGlzIGRpc3R..."
}

Also see Base64 Reference


问:
Protected attributes in Python
Let's say I have this class in my module:

```<code>class Person:
    def __init__(self, name):
        self._name = name
</code>```

So I have in my class a protected attribute called _name but I'm still able to call this attribute like this:

```<code>p = Person('Felipe')
print(p._name)
</code>```

Why? Shouldn't protected attributes be protected from direct access outside their class or subclasses?

答:
@coldspeed got it right.
You need a name which starts with a double underscore if you want Python apply the "mangling" to names: it basically changes the variable name and makes it not accessible from outside.

See here and this is the official python doc

And don't forge this is Python, non Java.

Title: Protected attributes in Python

Body:
Let's say I have this class in my module:

class Person:
    def __init__(self, name):
        self._name = name

So I have in my class a protected attribute called _name but I'm still able to call this attribute like this:

p = Person('Felipe')
print(p._name)

Why? Shouldn't protected attributes be protected from direct access outside their class or subclasses?


问:
Qt double from JSON precision
I receive a JSON Array from a server which looks like: [0.00015099, 1, -672.41163]
These values are orderbook entries. If I try to parse all values as double, my price differs slightly from the price in the JSON array. It is clear for me, that this happens because of the double conversion, but how to program around some crazy stuff like this?
Need these values also for calculation, compares etc.
I am using Qt5 and C++.

Any hint?

答: Well, you should use some Decimal type if you want to deal with money to be on a safe side. Unfortunately, Qt does not have decimal type for some reason. So, you may end up with some rounding rules/conventions if you have no other choice. Otherwise you'd better to implement your own implementation or use some existing solution like qdecimal.

Title: Qt double from JSON precision


问:
Spyder Python "object arrays are currently not supported"
I have a problem in Anaconda Spyder (Python).

Object type array can not be seen under Windows 10 in the variable explorer. If I click on X or Y, I see an error:

object arrays are currently not supported.

I have Win 10 Home 64bit (i7-4710HQ) and Python 3.5.2 | Anaconda 4.2.0 (64-bit) [MSC v.1900 64 bit (AMD64)]

答:
This is because the data are not encoded. All the categorical data should be "encoded".
After looking at the data in variable explorer of your sypder(https://i.stack.imgur.com/uApwt.jpg), it is clear that
X contains data about some country (like [France, 44.0, 72000]), so the name of the country should be encoded and similarly
y contains "Yes" or "No", so it should also be encoded

Add the following code after line 21, you will be able to see the object array

```<code># Encoding categorical data

from sklearn.preprocessing import LabelEncoder, OneHotEncoder

'''
To prevent the machine learning equations from thinking
(if there are more than one country) that one country is greater than
another, use the concept of dummy variables
'''
labelencoder_X = LabelEncoder()
X[:, 0] = labelencoder_X.fit_transform(X[:, 0])
onehotencoder = OneHotEncoder(categorical_features = [0])
X = onehotencoder.fit_transform(X).toarray()

'''
Since y is dependent variable, the machine learning model will know
that its a category, so we are going to use only the LableEncoder()
'''
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is because the data are not encoded. All the categorical data should be "encoded".
After looking at the data in variable explorer of your sypder(https://i.stack.imgur.com/uApwt.jpg), it is clear that
X contains data about some country (like [France, 44.0, 72000]), so the name of the country should be encoded and similarly
y contains "Yes" or "No", so it should also be encoded

Add the following code after line 21, you will be able to see the object array

# Encoding categorical data

from sklearn.preprocessing import LabelEncoder, OneHotEncoder

'''
To prevent the machine learning equations from thinking
(if there are more than one country) that one country is greater than
another, use the concept of dummy variables
'''
labelencoder_X = LabelEncoder()
X[:, 0] = labelencoder_X.fit_transform(X[:, 0])
onehotencoder = OneHotEncoder(categorical_features = [0])
X = onehotencoder.fit_transform(X).toarray()

'''
Since y is dependent variable, the machine learning model will know
that its a category, so we are going to use only the LableEncoder()
'''
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)


问:
Static ArrayList from a service is empty when accessed from my MainActivity
I am making a basic app that just reads RSS files from google and displays the headlines in a listview. The problem I am having is that the static ArrayList I am using in an IntentService is empty when I access it after I start the intent for the service. There could be something very basic I am missing here but tit used to work before I added more RSS links to the service. I tried commenting them out to see if there was some sort of overloading somewhere but nothing changed, which I guess means that I changed something else without realizing or remembering it.

Here is my relavent code, the ArrayList I am trying to access is the newsList variable in RSSsearcher. In the past I have logged the string values of the arraylist and confirmed that it was being populated in the RSSsearcher class, but empty in the MainActivity class.

Relevant code:

RSSsearcher:

```<code>public class RSSsearcher extends IntentService {
    public static ArrayList<NewsCard> newsList = new ArrayList<>();
    private static String TAG = "RSS";

    public RSSsearcher() {
        super("RSSsearcher");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        parseNewsLists();
        Log.i(TAG,"newsList in onHandleIntent" + newsList);
    }

    public static ArrayList<NewsCard> getNewsCards() {
        return newsList;
    }

    //helper method to create all the RSSfeed objects
    private void parseNewsLists() {
        Log.i(TAG, "the service has been started");
        //Creating the RSS feed objects
        RSSfeed topStories = new RSSfeed("https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&output=rss");
        RSSfeed worldNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/WORLD?ned=us&hl=en");
        RSSfeed usNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/NATION?ned=us&hl=en");
        RSSfeed buisnessNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/BUSINESS?ned=us&hl=en");
        RSSfeed technologyNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/TECHNOLOGY?ned=us&hl=en");
        RSSfeed entertainmentNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/ENTERTAINMENT?ned=us&hl=en");
        RSSfeed sportsNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/SPORTS?ned=us&hl=en");
        RSSfeed scienceNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/SCIENCE?ned=us&hl=en");
        RSSfeed healthNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/HEALTH?ned=us&hl=en");

        try {
            //getting RSS feeds
            topStories.FileReader();
            worldNews.FileReader();
            usNews.FileReader();
            buisnessNews.FileReader();
            technologyNews.FileReader();
            entertainmentNews.FileReader();
            sportsNews.FileReader();
            scienceNews.FileReader();
            healthNews.FileReader();
        } catch (Exception e) {
            Log.i(TAG, Log.getStackTraceString(e));
        }
        //adding stories to main
        newsList.addAll(topStories.getNews());
        newsList.addAll(worldNews.getNews());
        newsList.addAll(usNews.getNews());
        newsList.addAll(buisnessNews.getNews());
        newsList.addAll(technologyNews.getNews());
        newsList.addAll(entertainmentNews.getNews());
        newsList.addAll(sportsNews.getNews());
        newsList.addAll(scienceNews.getNews());
        newsList.addAll(healthNews.getNews());
    }

}
</code>```

MainActivity:

```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //TODO remove and have actual tags show up
        TagCard onecard = new TagCard("TestCard");
        TagCard twocard = new TagCard("TestCard2");

        dummyTags.add(onecard);
        dummyTags.add(twocard);

        mainListView = (ListView) findViewById(R.id.main_content_list);
        drawerLayout = (DrawerLayout) findViewById(R.id.main_layout);
        tagDrawerList = (ListView) findViewById(R.id.tag_drawer);

        //setting an intent for the RSSsearcher to fetch the news
        //TODO make this happen every 15 minutes or so
        Intent intent = new Intent(this, RSSsearcher.class);
        startService(intent);

        NewsCard card = new NewsCard("Testing", "linkeroni");

        //adding all the NewsCard objects to this classes newsList
        newsList.addAll(RSSsearcher.getNewsCards());

        MainAdapter adapter = new MainAdapter(this, newsList);
        mainListView.setAdapter(adapter);

        Log.i(TAG, "This is the array from main activity" + newsList.toString());

        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open_drawer, R.string.close_drawer){

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle("Closed");
            }

            public void onDrawerOpened(View view){
                super.onDrawerOpened(view);
                getActionBar().setTitle("Open");
            }
        };

        //TODO removed dummytags and add actual tag implementation
        tagDrawerList.setAdapter(new TagAdapter(this,dummyTags));

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

    }
</code>```

Thank you in advance!

答:
I think that when you call </p>

```<code>newsList.addAll(RSSsearcher.getNewsCards());
</code>```

<p>The intent is still in execution   </p>

Body:
I am making a basic app that just reads RSS files from google and displays the headlines in a listview. The problem I am having is that the static ArrayList I am using in an IntentService is empty when I access it after I start the intent for the service. There could be something very basic I am missing here but tit used to work before I added more RSS links to the service. I tried commenting them out to see if there was some sort of overloading somewhere but nothing changed, which I guess means that I changed something else without realizing or remembering it.

Here is my relavent code, the ArrayList I am trying to access is the newsList variable in RSSsearcher. In the past I have logged the string values of the arraylist and confirmed that it was being populated in the RSSsearcher class, but empty in the MainActivity class.

Relevant code:

RSSsearcher:

public class RSSsearcher extends IntentService {
    public static ArrayList<NewsCard> newsList = new ArrayList<>();
    private static String TAG = "RSS";

    public RSSsearcher() {
        super("RSSsearcher");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        parseNewsLists();
        Log.i(TAG,"newsList in onHandleIntent" + newsList);
    }

    public static ArrayList<NewsCard> getNewsCards() {
        return newsList;
    }

    //helper method to create all the RSSfeed objects
    private void parseNewsLists() {
        Log.i(TAG, "the service has been started");
        //Creating the RSS feed objects
        RSSfeed topStories = new RSSfeed("https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&output=rss");
        RSSfeed worldNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/WORLD?ned=us&hl=en");
        RSSfeed usNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/NATION?ned=us&hl=en");
        RSSfeed buisnessNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/BUSINESS?ned=us&hl=en");
        RSSfeed technologyNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/TECHNOLOGY?ned=us&hl=en");
        RSSfeed entertainmentNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/ENTERTAINMENT?ned=us&hl=en");
        RSSfeed sportsNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/SPORTS?ned=us&hl=en");
        RSSfeed scienceNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/SCIENCE?ned=us&hl=en");
        RSSfeed healthNews = new RSSfeed("https://news.google.com/news/rss/headlines/section/topic/HEALTH?ned=us&hl=en");

        try {
            //getting RSS feeds
            topStories.FileReader();
            worldNews.FileReader();
            usNews.FileReader();
            buisnessNews.FileReader();
            technologyNews.FileReader();
            entertainmentNews.FileReader();
            sportsNews.FileReader();
            scienceNews.FileReader();
            healthNews.FileReader();
        } catch (Exception e) {
            Log.i(TAG, Log.getStackTraceString(e));
        }
        //adding stories to main
        newsList.addAll(topStories.getNews());
        newsList.addAll(worldNews.getNews());
        newsList.addAll(usNews.getNews());
        newsList.addAll(buisnessNews.getNews());
        newsList.addAll(technologyNews.getNews());
        newsList.addAll(entertainmentNews.getNews());
        newsList.addAll(sportsNews.getNews());
        newsList.addAll(scienceNews.getNews());
        newsList.addAll(healthNews.getNews());
    }

}

MainActivity:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //TODO remove and have actual tags show up
        TagCard onecard = new TagCard("TestCard");
        TagCard twocard = new TagCard("TestCard2");

        dummyTags.add(onecard);
        dummyTags.add(twocard);

        mainListView = (ListView) findViewById(R.id.main_content_list);
        drawerLayout = (DrawerLayout) findViewById(R.id.main_layout);
        tagDrawerList = (ListView) findViewById(R.id.tag_drawer);

        //setting an intent for the RSSsearcher to fetch the news
        //TODO make this happen every 15 minutes or so
        Intent intent = new Intent(this, RSSsearcher.class);
        startService(intent);

        NewsCard card = new NewsCard("Testing", "linkeroni");

        //adding all the NewsCard objects to this classes newsList
        newsList.addAll(RSSsearcher.getNewsCards());

        MainAdapter adapter = new MainAdapter(this, newsList);
        mainListView.setAdapter(adapter);

        Log.i(TAG, "This is the array from main activity" + newsList.toString());

        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open_drawer, R.string.close_drawer){

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle("Closed");
            }

            public void onDrawerOpened(View view){
                super.onDrawerOpened(view);
                getActionBar().setTitle("Open");
            }
        };

        //TODO removed dummytags and add actual tag implementation
        tagDrawerList.setAdapter(new TagAdapter(this,dummyTags));

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

    }

Thank you in advance!

Body:
I think that when you call

newsList.addAll(RSSsearcher.getNewsCards());

The intent is still in execution


问:
How to hide the double-pattern of a map obtained from the raster calculator in ArcGIS?
I am currently working on a map model in ArcGIS and I use 3 maps as predictors: DEM, Slope and TDD (all 5 m resolution). However, TDD was obtained from a multiplication of snow persistence map (250 m resolution but resampled to 5 m) and temperatures map (5 m resolution). This probably is the cause of the problem I get in the final map: even if I resampled every predictor, the final map still shows the pattern of the snow persistence map showed below.
Is there a solution to hide this pattern?

答:
Even though your raster is resampled to 5m cells, it is still using data with 250m resolution. The 5m resolution TDD would visibly appear to be identical to the 250m resolution.

Rather than resampling the raster, you need to interpolate to get a finer resolution than the source data. (Convert from raster to points, interpolate the points into a 5m resolution raster) However, be aware that this can be very prone to error and inaccuracy. Whether that is acceptable or not for your particular analysis is up to you.


问:
Caused by: org.apache.solr.common.SolrException: Index locked for write for core
We are using solr4.3 with master/slave setup, today I got the following error and solr stopped responding. What could be causing this,</p>

```<code> Caused by: org.apache.solr.common.SolrException: Index locked for write for core XXX
    at org.apache.solr.core.SolrCore.<init>(SolrCore.java:821)
    at org.apache.solr.core.SolrCore.<init>(SolrCore.java:618)
    at org.apache.solr.core.CoreContainer.createFromLocal(CoreContainer.java:949)
    at org.apache.solr.core.CoreContainer.create(CoreContainer.java:984)
    at org.apache.solr.core.CoreContainer$2.call(CoreContainer.java:597)
    at org.apache.solr.core.CoreContainer$2.call(CoreContainer.java:592)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    ... 1 more
Caused by: org.apache.lucene.store.LockObtainFailedException: Index locked for write for core XX        at org.apache.solr.core.SolrCore.initIndex(SolrCore.java:484)
    at org.apache.solr.core.SolrCore.<init>(SolrCore.java:745)
    ... 13 more
</code>```

答:
If you are using Rails,

just add into solr.xml this line

```<code><lockType>simple</lockType>
</code>```

its works for me)

Body:
We are using solr4.3 with master/slave setup, today I got the following error and solr stopped responding. What could be causing this,

 Caused by: org.apache.solr.common.SolrException: Index locked for write for core XXX
    at org.apache.solr.core.SolrCore.<init>(SolrCore.java:821)
    at org.apache.solr.core.SolrCore.<init>(SolrCore.java:618)
    at org.apache.solr.core.CoreContainer.createFromLocal(CoreContainer.java:949)
    at org.apache.solr.core.CoreContainer.create(CoreContainer.java:984)
    at org.apache.solr.core.CoreContainer$2.call(CoreContainer.java:597)
    at org.apache.solr.core.CoreContainer$2.call(CoreContainer.java:592)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    ... 1 more
Caused by: org.apache.lucene.store.LockObtainFailedException: Index locked for write for core XX        at org.apache.solr.core.SolrCore.initIndex(SolrCore.java:484)
    at org.apache.solr.core.SolrCore.<init>(SolrCore.java:745)
    ... 13 more

Body:
If you are using Rails,

just add into solr.xml this line

<lockType>simple</lockType>

its works for me)


问:
Spring Batch Integration -- Remote Chunking Slave Exceptions
What's the standard configuration for ensuring that exceptions on the slave are mapped to a response on the master that will indicate that the remote step actually failed?

At the moment any exceptions that happen in the service activator on the slave just completely stop the flow, and I get no response on the master until the whole thing times out.  I can add a couple retries on the slave (using this info from the manual) but if it just fails completely or is an exception I don't want to retry I need a failure response to be sent to the master immediately.

The docs on remote chunking are unfortunately pretty sparse and I can't find anything showing how to handle this.

答:
With partitioning, you should get a StepExecution back, regardless of success/failure:

```<code>@ServiceActivator
public StepExecution handle(StepExecutionRequest request) {

    Long jobExecutionId = request.getJobExecutionId();
    Long stepExecutionId = request.getStepExecutionId();
    StepExecution stepExecution = jobExplorer.getStepExecution(jobExecutionId, stepExecutionId);
    if (stepExecution == null) {
        throw new NoSuchStepException("No StepExecution could be located for this request: " + request);
    }

    String stepName = request.getStepName();
    Step step = stepLocator.getStep(stepName);
    if (step == null) {
        throw new NoSuchStepException(String.format("No Step with name [%s] could be located.", stepName));
    }

    try {
        step.execute(stepExecution);
    }
    catch (JobInterruptedException e) {
        stepExecution.setStatus(BatchStatus.STOPPED);
        // The receiver should update the stepExecution in repository
    }
    catch (Throwable e) {
        stepExecution.addFailureException(e);
        stepExecution.setStatus(BatchStatus.FAILED);
        // The receiver should update the stepExecution in repository
    }

    return stepExecution;

}
</code>```

(StepExecutionRequestHandler).

With chunking you should get a ChunkResponse either way...

```<code>@ServiceActivator
public ChunkResponse handleChunk(ChunkRequest<S> chunkRequest) throws Exception {

    if (logger.isDebugEnabled()) {
        logger.debug("Handling chunk: " + chunkRequest);
    }

    StepContribution stepContribution = chunkRequest.getStepContribution();

    Throwable failure = process(chunkRequest, stepContribution);
    if (failure != null) {
        logger.debug("Failed chunk", failure);
        return new ChunkResponse(false, chunkRequest.getSequence(), chunkRequest.getJobId(), stepContribution, failure.getClass().getName()
                + ": " + failure.getMessage());
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Completed chunk handling with " + stepContribution);
    }
    return new ChunkResponse(true, chunkRequest.getSequence(), chunkRequest.getJobId(), stepContribution);

}
</code>```

(ChunkProcessorChunkHandler)

Body:
With partitioning, you should get a StepExecution back, regardless of success/failure:

@ServiceActivator
public StepExecution handle(StepExecutionRequest request) {

    Long jobExecutionId = request.getJobExecutionId();
    Long stepExecutionId = request.getStepExecutionId();
    StepExecution stepExecution = jobExplorer.getStepExecution(jobExecutionId, stepExecutionId);
    if (stepExecution == null) {
        throw new NoSuchStepException("No StepExecution could be located for this request: " + request);
    }

    String stepName = request.getStepName();
    Step step = stepLocator.getStep(stepName);
    if (step == null) {
        throw new NoSuchStepException(String.format("No Step with name [%s] could be located.", stepName));
    }

    try {
        step.execute(stepExecution);
    }
    catch (JobInterruptedException e) {
        stepExecution.setStatus(BatchStatus.STOPPED);
        // The receiver should update the stepExecution in repository
    }
    catch (Throwable e) {
        stepExecution.addFailureException(e);
        stepExecution.setStatus(BatchStatus.FAILED);
        // The receiver should update the stepExecution in repository
    }

    return stepExecution;

}

(StepExecutionRequestHandler).

With chunking you should get a ChunkResponse either way...

@ServiceActivator
public ChunkResponse handleChunk(ChunkRequest<S> chunkRequest) throws Exception {

    if (logger.isDebugEnabled()) {
        logger.debug("Handling chunk: " + chunkRequest);
    }

    StepContribution stepContribution = chunkRequest.getStepContribution();

    Throwable failure = process(chunkRequest, stepContribution);
    if (failure != null) {
        logger.debug("Failed chunk", failure);
        return new ChunkResponse(false, chunkRequest.getSequence(), chunkRequest.getJobId(), stepContribution, failure.getClass().getName()
                + ": " + failure.getMessage());
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Completed chunk handling with " + stepContribution);
    }
    return new ChunkResponse(true, chunkRequest.getSequence(), chunkRequest.getJobId(), stepContribution);

}

(ChunkProcessorChunkHandler)


问:
reset and start a new time interval
I am having hard time with reseting and starting a time interval function in javascript. Here is what I have worked so far:

$(document).ready(function(){
$("#start").click(function(){
var valu = $("#in").val()
setInterval(function()
{
console.log("hello")
},1000*valu)
})

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="in">
<button id="start">Start</button></code>```

Issue: When I input a new value and press start, the old interval keeps working instead of just the new one. For example, if you input 1 and press start the console outputs every 1 sec(good). However, If you input 10, instead of change to 10 sec interval it keeps the old 1 sec interval.
Goal: When I input a new value I want the old interval function to be removed and start a new interval.

Can you help me fix the issue?

答:
$(document).ready(function(){
    $("#start").click(function(){
        var valu = $("#in").val();
        if(typeof myTimer != "undefined") {
            clearInterval(myTimer);
        }

        window.myTimer = setInterval(function()
        {
            console.log("hello")
        },1000*valu);
    })

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="in">
<button id="start">Start</button></code>```

Store your setInterval in a global variable that can be accessed again the next time you call the function.

Then, you check if the variable is set and use clearInterval to stop the timer. It's then starting a fresh timer with your setInterval again.

Title: reset and start a new time interval

Body:
I am having hard time with reseting and starting a time interval function in javascript. Here is what I have worked so far:

$(document).ready(function(){
$("#start").click(function(){
var valu = $("#in").val()
setInterval(function()
{
console.log("hello")
},1000*valu)
})

})

<input id="in">
<button id="start">Start</button>

Issue: When I input a new value and press start, the old interval keeps working instead of just the new one. For example, if you input 1 and press start the console outputs every 1 sec(good). However, If you input 10, instead of change to 10 sec interval it keeps the old 1 sec interval.
Goal: When I input a new value I want the old interval function to be removed and start a new interval.

Can you help me fix the issue?

Body:
$(document).ready(function(){
    $("#start").click(function(){
        var valu = $("#in").val();
        if(typeof myTimer != "undefined") {
            clearInterval(myTimer);
        }

        window.myTimer = setInterval(function()
        {
            console.log("hello")
        },1000*valu);
    })

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="in">
<button id="start">Start</button>

Store your setInterval in a global variable that can be accessed again the next time you call the function.

Then, you check if the variable is set and use clearInterval to stop the timer. It's then starting a fresh timer with your setInterval again.


问:
sql query/oracle
I have a 2 tables Existing_tools and Recommendation_tool having 4 columns (Account, Activity, Tools_name, count) but last column gives me number of existing tools and number of recommended tools count in respective tables.

I want output (Account, Activity, Tools_name, existing_tools_count, recommendation_tools_count), group by account and activity
and all tools present in both the tables comes in output.

If tool name is not present in existing table then count will be 0 against existing_tools_count, same way if tool is not present in recommendation table count against recommendation_tools_count count will be 0.

And if tool is present in both the tables then given count will come accordingly.

Existing_TOOLS

```<code>Account Activity       tools_Name   Number of Existing_tool
x   Agile/Proj. Mgmt    JIRA             5
x   Agile/Proj. Mgmt    Collabnet        4
x   Build               ANT              3
x   Build               MAVEN            3
y   Agile/Proj. Mgmt    JIRA             5
y   Agile/Proj. Mgmt    Collabnet        4
y   Build               ANT              3
y   Build               MAVEN            3
</code>```

Recommendation_tool

```<code>Account    Activity    tools_Name    Number of recommendation_tool
x    Agile/Proj. Mgmt    JIRA         5
x    Agile/Proj. Mgmt    HP ALM       4
x    Build               MS build     3
y    Agile/Proj. Mgmt    JIRA         5
y    Agile/Proj. Mgmt    HP ALM       4
y    Build               MS build     3
</code>```

Required_TABLE

```<code>Account    Activity    tools_Name    Number of Existing_tool    Number of recommendation_tool
x    Agile/Proj. Mgmt    JIRA                5                         5
x    Agile/Proj. Mgmt    Collabnet           4                         0
x    Agile/Proj. Mgmt    HP ALM              0                         4
x    Build               ANT                 3                         0
x    Build               MAVEN               3                         0
x    Build               MS build            0                         3
y    Agile/Proj. Mgmt    JIRA                5                         5
y    Agile/Proj. Mgmt    Collabnet           4                         0
y    Agile/Proj. Mgmt    HP ALM              0                         4
y    Build               ANT                 3                         0
y    Build               MAVEN               3                         0
y    Build               MS build            0                         3
</code>```

答:
I think it might be "cleaner" to do a union all and group by:

```<code>select account, activity, tools_name,
       sum(et_count) as et_count, sum(rt_count) as rt_count
from ((select et.account, et.activity, et.tools_name,
             et.count as et_count, 0 as rt_count
       from Existing_tools
      ) union all
      (select rt.account, rt.activity, rt.tools_name, 0, rt.count
       from Recommendation_Tool
      )
     ) er
group by account, activity, tools_name
order by Account, Activity, Tools_Name;
</code>```

All the coalesce()s needed for the full outer join get tiresome.

Of course, you can also eliminate most of them using USING:

SELECT Account, Activity, Tools_Name,
       COALESCE(RT.Count, 0) as Rec_tool_Count,
       COALESCE(ET.Count, 0) as Existing_tool_count
FROM Existing_tools ET FULL OUTER JOIN
     Recomendation_Tool RT
     USING (Account, Activity, Tools_Name)
ORDER BY Account, Activity, Tools_Name

Title: sql query/oracle

Body:
I have a 2 tables Existing_tools and Recommendation_tool having 4 columns (Account, Activity, Tools_name, count) but last column gives me number of existing tools and number of recommended tools count in respective tables.

I want output (Account, Activity, Tools_name, existing_tools_count, recommendation_tools_count), group by account and activity
and all tools present in both the tables comes in output.

If tool name is not present in existing table then count will be 0 against existing_tools_count, same way if tool is not present in recommendation table count against recommendation_tools_count count will be 0.

And if tool is present in both the tables then given count will come accordingly.

Existing_TOOLS

Account Activity       tools_Name   Number of Existing_tool
x   Agile/Proj. Mgmt    JIRA             5
x   Agile/Proj. Mgmt    Collabnet        4
x   Build               ANT              3
x   Build               MAVEN            3
y   Agile/Proj. Mgmt    JIRA             5
y   Agile/Proj. Mgmt    Collabnet        4
y   Build               ANT              3
y   Build               MAVEN            3

Recommendation_tool

Account    Activity    tools_Name    Number of recommendation_tool
x    Agile/Proj. Mgmt    JIRA         5
x    Agile/Proj. Mgmt    HP ALM       4
x    Build               MS build     3
y    Agile/Proj. Mgmt    JIRA         5
y    Agile/Proj. Mgmt    HP ALM       4
y    Build               MS build     3

Required_TABLE

Account    Activity    tools_Name    Number of Existing_tool    Number of recommendation_tool
x    Agile/Proj. Mgmt    JIRA                5                         5
x    Agile/Proj. Mgmt    Collabnet           4                         0
x    Agile/Proj. Mgmt    HP ALM              0                         4
x    Build               ANT                 3                         0
x    Build               MAVEN               3                         0
x    Build               MS build            0                         3
y    Agile/Proj. Mgmt    JIRA                5                         5
y    Agile/Proj. Mgmt    Collabnet           4                         0
y    Agile/Proj. Mgmt    HP ALM              0                         4
y    Build               ANT                 3                         0
y    Build               MAVEN               3                         0
y    Build               MS build            0                         3

Body:
I think it might be "cleaner" to do a union all and group by:

select account, activity, tools_name,
       sum(et_count) as et_count, sum(rt_count) as rt_count
from ((select et.account, et.activity, et.tools_name,
             et.count as et_count, 0 as rt_count
       from Existing_tools
      ) union all
      (select rt.account, rt.activity, rt.tools_name, 0, rt.count
       from Recommendation_Tool
      )
     ) er
group by account, activity, tools_name
order by Account, Activity, Tools_Name;

All the coalesce()s needed for the full outer join get tiresome.

Of course, you can also eliminate most of them using USING:

SELECT Account, Activity, Tools_Name,
       COALESCE(RT.Count, 0) as Rec_tool_Count,
       COALESCE(ET.Count, 0) as Existing_tool_count
FROM Existing_tools ET FULL OUTER JOIN
     Recomendation_Tool RT
     USING (Account, Activity, Tools_Name)
ORDER BY Account, Activity, Tools_Name


问:
How to merge array inside foreach loop?
How to merge array inside foreach loop in php ? </p>

<p>Here is my Code: </p>

```<code>$subjects = $this->db->order_by('id','desc')->get_where('tbl_class_management', array('status'=>'1','teacher_id'=>$this->teacher->id))->result();
foreach ($subjects as $key => $s) {
   $std = $this->db->get_where('tbl_student', array('batch'=>$s->batch,'semester'=>$s->semester,'faculty'=>$s->faculty))->result();
debug($std);
}
</code>```

答:
if you want to store all your data in $std array by iterating over $subjects array, declare your $std array outside the loop then sipmly push data in this one by one when you iterating over loop, use like this

```<code>$subjects = $this->db->order_by('id','desc')->get_where('tbl_class_management', array('status'=>'1','teacher_id'=>$this->teacher->id))->result();
$std=[];
foreach ($subjects as $key => $s) {
    $std[] = $this->db->get_where('tbl_student', array('batch'=>$s->batch,'semester'=>$s->semester,'faculty'=>$s->faculty))->result();
}
$std = json_decode(json_encode($std,true),true);
print_r($std);
</code>```

Title: How to merge array inside foreach loop?

Body:
How to merge array inside foreach loop in php ?

Here is my Code:

$subjects = $this->db->order_by('id','desc')->get_where('tbl_class_management', array('status'=>'1','teacher_id'=>$this->teacher->id))->result();
foreach ($subjects as $key => $s) {
   $std = $this->db->get_where('tbl_student', array('batch'=>$s->batch,'semester'=>$s->semester,'faculty'=>$s->faculty))->result();
debug($std);
}

Body:
if you want to store all your data in $std array by iterating over $subjects array, declare your $std array outside the loop then sipmly push data in this one by one when you iterating over loop, use like this

$subjects = $this->db->order_by('id','desc')->get_where('tbl_class_management', array('status'=>'1','teacher_id'=>$this->teacher->id))->result();
$std=[];
foreach ($subjects as $key => $s) {
    $std[] = $this->db->get_where('tbl_student', array('batch'=>$s->batch,'semester'=>$s->semester,'faculty'=>$s->faculty))->result();
}
$std = json_decode(json_encode($std,true),true);
print_r($std);


问:
How to check if a button has this image

I want to check if myButton has a named image.

I try this but it doesn't work

```<code>if (myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")) != nil){
        print("YES")
    } else {
        print("NO")
    }
</code>```

and this too doesn't work

```<code>if myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")){
        print("YES")
    } else {
        print("NO")
    }
</code>```

答:
You can convert the button's image and the named image to NSDatas and compare the two data objects:

```<code>let imgData1 = UIImagePNGRepresentation(buttonImage)
let imgData2 = UIImagePNGRepresentation(namedImage)
let equal = imgData1 == imgData2
</code>```

Note that this will only work if the two images are completely identical (e.g. come from the same source file); if one is a scaled down version of the other, it won't work.

Also, it should be mentioned that this can be a pretty expensive operation and should not be run frequently.

Title: How to check if a button has this image

Body:
I want to check if myButton has a named image.

I try this but it doesn't work

if (myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")) != nil){
        print("YES")
    } else {
        print("NO")
    }

and this too doesn't work

if myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")){
        print("YES")
    } else {
        print("NO")
    }

Body:
You can convert the button's image and the named image to NSDatas and compare the two data objects:

let imgData1 = UIImagePNGRepresentation(buttonImage)
let imgData2 = UIImagePNGRepresentation(namedImage)
let equal = imgData1 == imgData2

Note that this will only work if the two images are completely identical (e.g. come from the same source file); if one is a scaled down version of the other, it won't work.

Also, it should be mentioned that this can be a pretty expensive operation and should not be run frequently.


问:
Could not find com.google.firebase:firebase-core:11.0.0 when i try to add mobile-center-push to React Native project
I want integrate the push notification to my React Native project follow the guide
https://mobile.azure.com/orgs/....../push/setup
and when i run

```<code>react-native run-android
</code>```

i got an error:

```<code>-> % react-native run-android
Scanning 744 folders for symlinks in /Users/kalaliu/temp/RNBase/node_modules (5ms)
JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug)...
File /Users/kalaliu/.android/repositories.cfg could not be loaded.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApk'.
   > A problem occurred configuring project ':mobile-center-push'.
      > Could not resolve all dependencies for configuration ':mobile-center-push:_debugPublishCopy'.
         > Could not find com.google.firebase:firebase-core:11.0.0.
           Required by:
               RNBase:mobile-center-push:unspecified > com.microsoft.azure.mobile:mobile-center-push:0.10.0
         > Could not find com.google.firebase:firebase-messaging:11.0.0.
           Required by:
               RNBase:mobile-center-push:unspecified > com.microsoft.azure.mobile:mobile-center-push:0.10.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED
</code>```

it looks like that i need upgrade my android SDK in my RN project?
any idea about this?
my android configuration

```<code> compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.rnbase"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0.1"
        ndk {
            abiFilters "armeabi-v7a"
        }
        vectorDrawables.useSupportLibrary = true
    }
</code>```

my package.json

```<code>"mobile-center": "^0.6.0",
"mobile-center-analytics": "^0.6.0"
"mobile-center-crashes": "^0.6.0",
"mobile-center-push": "^0.7.0",
"react": "16.0.0-alpha.12",
"react-native": "^0.45.1",
</code>```

PS:
i find the firebase tips:

答: The Firebase SDK is in a local repository that you need to update if outdated:

Body:
I want integrate the push notification to my React Native project follow the guide
https://mobile.azure.com/orgs/....../push/setup
and when i run

react-native run-android

i got an error:

-> % react-native run-android
Scanning 744 folders for symlinks in /Users/kalaliu/temp/RNBase/node_modules (5ms)
JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug)...
File /Users/kalaliu/.android/repositories.cfg could not be loaded.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApk'.
   > A problem occurred configuring project ':mobile-center-push'.
      > Could not resolve all dependencies for configuration ':mobile-center-push:_debugPublishCopy'.
         > Could not find com.google.firebase:firebase-core:11.0.0.
           Required by:
               RNBase:mobile-center-push:unspecified > com.microsoft.azure.mobile:mobile-center-push:0.10.0
         > Could not find com.google.firebase:firebase-messaging:11.0.0.
           Required by:
               RNBase:mobile-center-push:unspecified > com.microsoft.azure.mobile:mobile-center-push:0.10.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

it looks like that i need upgrade my android SDK in my RN project?
any idea about this?
my android configuration

 compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.rnbase"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0.1"
        ndk {
            abiFilters "armeabi-v7a"
        }
        vectorDrawables.useSupportLibrary = true
    }

my package.json

"mobile-center": "^0.6.0",
"mobile-center-analytics": "^0.6.0"
"mobile-center-crashes": "^0.6.0",
"mobile-center-push": "^0.7.0",
"react": "16.0.0-alpha.12",
"react-native": "^0.45.1",

PS:
i find the firebase tips:


问:
spring boot configuration properties not working
This is driving me up the wall trying to get spring boot @configurationproperties annotation working. So hoping someone can shed some light on this for me as to what I am doing wrong.
I have a spring boot application and it contains a application.properties on the classpath. It has a value in there of

```<code>server.contextPath=/test/v1
server.port=8080

spring.profiles.active=dev
vendors=me
</code>```

I have a application.class which has the spring boot annotation and sits at the top of my package hierarchy

```<code>package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableConfigurationProperties
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

I am trying to map the property vendors into a configurationproperties bean as below

```<code>package com.test.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:application.properties")
@ConfigurationProperties
public class GlobalProperties {

    private String vendors;

    public String getVendors() {
        return vendors;
    }

    public void setVendors(String vendors) {
        this.vendors = vendors;
    }
}
</code>```

and then call this bean from my rest controller. I know it resolves the property as when i rename it the server fails to start. In the code below the props bean is not getting autowired and is null. //code ommitted for brevity

```<code>package com.test.controller;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.test.config.GlobalProperties;

@RestController
@Component
public class MController {

    //TODO should be wired in from properties file
    @Autowired
    GlobalProperties props;

    private boolean vendorUnknown(String vendor) {
        if(props.getAllowedVendor().equalsIgnoreCase(vendor)) {
            return true;
        }
        return false;
    }

    @RequestMapping(value = "/test/{id}", method = RequestMethod.GET, produces = { "application/json" })
    public ResponseEntity<?> getStatus(
            @PathVariable String id) {
        //@RequestBody Bookmark input
        if(vendorUnknown("me")) {
        System.out.println("found");
    };
        return ResponseEntity.noContent().build();
    }

}
</code>```

Anybody point me to what i have done wrong please?

UPDATE:

changed the code above to be a more simplistic version with a test class to recreate the issue. See below for my pom.xml and test class

Pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.me.test</groupId>
    <artifactId>test-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- tag::actuator[] -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- end::actuator[] -->
        <!-- tag::tests[] -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- end::tests[] -->
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Test class:

```<code>package com.test.controller;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @InjectMocks
    MController testController;

    @Before
    public void setup() {

        // this must be called for the @Mock annotations above to be processed
        // and for the mock service to be injected into the controller under
        // test.
        MockitoAnnotations.initMocks(this);

        this.mockMvc = MockMvcBuilders.standaloneSetup(testController).build();
    }

    @Test
    public void testPropertiesMsg() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/test/1").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());
    }
}
</code>```

答: Add @EnableConfigurationProperties to your Application class to enable scanning ConfigurationProperties beans.</p>

Body:
This is driving me up the wall trying to get spring boot @configurationproperties annotation working. So hoping someone can shed some light on this for me as to what I am doing wrong.
I have a spring boot application and it contains a application.properties on the classpath. It has a value in there of

server.contextPath=/test/v1
server.port=8080

spring.profiles.active=dev
vendors=me

I have a application.class which has the spring boot annotation and sits at the top of my package hierarchy

package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableConfigurationProperties
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

I am trying to map the property vendors into a configurationproperties bean as below

package com.test.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:application.properties")
@ConfigurationProperties
public class GlobalProperties {

    private String vendors;

    public String getVendors() {
        return vendors;
    }

    public void setVendors(String vendors) {
        this.vendors = vendors;
    }
}

and then call this bean from my rest controller. I know it resolves the property as when i rename it the server fails to start. In the code below the props bean is not getting autowired and is null. //code ommitted for brevity

package com.test.controller;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.test.config.GlobalProperties;

@RestController
@Component
public class MController {

    //TODO should be wired in from properties file
    @Autowired
    GlobalProperties props;

    private boolean vendorUnknown(String vendor) {
        if(props.getAllowedVendor().equalsIgnoreCase(vendor)) {
            return true;
        }
        return false;
    }

    @RequestMapping(value = "/test/{id}", method = RequestMethod.GET, produces = { "application/json" })
    public ResponseEntity<?> getStatus(
            @PathVariable String id) {
        //@RequestBody Bookmark input
        if(vendorUnknown("me")) {
        System.out.println("found");
    };
        return ResponseEntity.noContent().build();
    }

}

Anybody point me to what i have done wrong please?

UPDATE:

changed the code above to be a more simplistic version with a test class to recreate the issue. See below for my pom.xml and test class

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.me.test</groupId>
    <artifactId>test-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Test class:

package com.test.controller;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @InjectMocks
    MController testController;

    @Before
    public void setup() {

        // this must be called for the @Mock annotations above to be processed
        // and for the mock service to be injected into the controller under
        // test.
        MockitoAnnotations.initMocks(this);

        this.mockMvc = MockMvcBuilders.standaloneSetup(testController).build();
    }

    @Test
    public void testPropertiesMsg() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/test/1").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());
    }
}


问:
Delphi 10.1 and CEF3 troubles with cookies
I have this code:

```<code>function VisitCookie(const name, value, domain, path: ustring;
  secure, httponly, hasExpires: Boolean; const creation, lastAccess,
  expires: TdateTime; Count, total: integer; out deleteCookie: Boolean)
  : Boolean;
begin
  RichEdit1.Lines.Add('cookie ' + inttostr(Count) + '/' + inttostr(total));
  RichEdit1.Lines.Add('name ' + name);
  RichEdit1.Lines.Add('value ' + value);
  RichEdit1.Lines.Add('domain ' + domain);
  RichEdit1.Lines.Add('path ' + path);
  RichEdit1.Lines.Add('secure ' + BoolToStr(secure));
  RichEdit1.Lines.Add('httponly ' + BoolToStr(httponly));
  RichEdit1.Lines.Add('hasExpires ' + BoolToStr(hasExpires));
  RichEdit1.Lines.Add('creation ' + DateToStr(creation));
  RichEdit1.Lines.Add('lastAccess ' + DateToStr(lastAccess));
  RichEdit1.Lines.Add('expires ' + DateToStr(expires));
  RichEdit1.Lines.Add('------------------------');
  Result := true;
end;

function GetCookies: Boolean;
begin
  CookieManager := TCefCookieManagerRef.Global(nil);
  CookieManager.VisitAllCookiesProc(VisitCookie);
end;
</code>```

If I set Result := false in my function VisitCookie - I only get the value of the first cookie, that's all. I.e. pass through the cookies does not happen. But if I set Result := true - I got an access violation, but it works fine, until I have not so much cookies records in Chromium, for example 5-10 records. I have no idea why this happens.

答:
The problem is that the visitor callback function of the VisitAllCookies method is executed in the context of a CEF worker thread, not in a context of the main thread hence you cannot access VCL controls from there. The VisitAllCookies method returns immediately and the callback function is then called asynchronously from the CEF worker thread.

There are many ways how to implement such cooperation. But it's not CEF specific. It's about how to pass (or collect) certain data from a worker thread callback and pass it back to the main thread. Optionally also about taking the callback under control in a synchronous way (to interrupt running enumeration).

Here is one untested example (maybe too overcomplicated). The principle remains, how to collect data from an uncontrolled thread callback function for the main thread (or take it under control in a synchronous way):

```<code>type
  TCookie = record
    Name: string;
    Value: string;
    Expires: TDateTime;
  end;

  TProcessCookieEvent = procedure(Sender: TObject; const Cookie: TCookie;
    const IsLast: Boolean; var Delete: Boolean; var Cancel: Boolean) of object;

  TCookieManager = class
  private
    FWndHandle: HWND;
    FOnProcessCookie: TProcessCookieEvent;
  protected
    procedure WndProc(var Msg: TMessage); virtual;
  public
    constructor Create;
    destructor Destroy; override;
    procedure ProcessCookies(Timeout: UINT = 5000);
    property OnProcessCookie: TProcessCookieEvent read FOnProcessCookie write FOnProcessCookie;
  end;

implementation

const
  PA_CANCEL = 1;
  PA_DELETE = 2;
  CM_PROCESSCOOKIE = WM_USER + 100;

type
  PCookie = ^TCookie;

constructor TCookieManager.Create;
begin
  inherited;
  FWndHandle := AllocateHWnd(WndProc);
end;

destructor TCookieManager.Destroy;
begin
  DeallocateHWnd(FWndHandle);
  inherited;
end;

procedure TCookieManager.WndProc(var Msg: TMessage);
var
  Delete: Boolean;
  Cancel: Boolean;
  IsLast: Boolean;
begin
  if Msg.Msg = CM_PROCESSCOOKIE then
  begin
    Msg.Result := 0;

    if Assigned(FOnProcessCookie) then
    try
      Delete := False;
      Cancel := False;
      IsLast := Boolean(Msg.wParam);

      FOnProcessCookie(Self, PCookie(Msg.lParam)^, IsLast, Delete, Cancel);

      if Delete then
        Msg.Result := Msg.Result or PA_DELETE;
      if Cancel then
        Msg.Result := Msg.Result or PA_CANCEL;
    except
      Application.HandleException(Self);
    end;
  end
  else
    Msg.Result := DefWindowProc(FWndHandle, Msg.Msg, Msg.wParam, Msg.lParam);
end;

procedure TCookieManager.ProcessCookies(Timeout: UINT = 5000);
var
  CookieManager: ICefCookieManager;
begin
  CookieManager := TCefCookieManagerRef.Global(nil);
  CookieManager.VisitAllCookiesProc(

    { this function will be called asynchronously from a CEF worker thread }
    function(const Name, Value, Domain, Path: UString; Secure, HTTPOnly,
      HasExpires: Boolean; const Creation, LastAccess, Expires: TDateTime;
      Count, Total: Integer; out DeleteCookie: Boolean): Boolean
    var
      MsgRet: DWORD;
      Cookie: TCookie;
      IsLast: Boolean;
    begin
      { initialize cancel of enumeration and no cookie deletion }
      Result := False;
      DeleteCookie := False;

      { fill the cookie structure }
      Cookie.Name := string(Name);
      Cookie.Value := string(Value);
      Cookie.Expires := Expires;

      { determine if it's the last enumerated cookie }
      IsLast := Count = Total-1;

      { yes, I'm doing what many would not do, but let me explain, this is not
        SendMessage, that could get stuck forever when the message pump of the
        receiver got stucked so I've let this thread responsive (SMTO_NORMAL),
        let this call fail when the receiver is "hung" (SMTO_ABORTIFHUNG) and
        let the function fail if the receiver is destroyed (SMTO_ERRORONEXIT)
        and there is the timeout, in which the receiver needs to process this
        message (if the message is not processed for some reason, enumerating
        stops) }
      if SendMessageTimeout(FWndHandle, CM_PROCESSCOOKIE, WPARAM(IsLast),
        LPARAM(@Cookie), SMTO_NORMAL or SMTO_ABORTIFHUNG or SMTO_ERRORONEXIT,
        Timeout, MsgRet) <> 0 then
      begin
        Result := MsgRet and PA_CANCEL <> PA_CANCEL;
        DeleteCookie := MsgRet and PA_DELETE = PA_DELETE;
      end;
      { else GetLastError and try to signal error by posting another message }
    end;

  );
end;
</code>```

And a possible usage:

```<code>type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    FCookieList: TList<TCookie>;
    FCookieManager: TCookieManager;
    procedure DoProcessCookie(Sender: TObject; const Cookie: TCookie;
      const IsLast: Boolean; var Delete: Boolean; var Cancel: Boolean);
  end;

implementation

procedure TForm1.FormCreate(Sender: TObject);
begin
  FCookieList := TList<TCookie>.Create;
  FCookieManager := TCookieManager.Create;
  FCookieManager.OnProcessCookie := DoProcessCookie;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FCookieManager.Free;
  FCookieList.Free;
end;

procedure TForm1.DoProcessCookie(Sender: TObject; const Cookie: TCookie;
  const IsLast: Boolean; var Delete: Boolean; var Cancel: Boolean);
begin
  { IsLast signals last enumerated cookie, Delete output parameter can delete
    the currently enumerated cookie, and Cancel output parameter can stop the
    enumeration }
  FCookieList.Add(Cookie);
  if IsLast then
    ShowMessage('All cookies has been enumerated!');
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  FCookieList.Clear;
  FCookieManager.ProcessCookies;
end;
</code>```

Body:
I have this code:

function VisitCookie(const name, value, domain, path: ustring;
  secure, httponly, hasExpires: Boolean; const creation, lastAccess,
  expires: TdateTime; Count, total: integer; out deleteCookie: Boolean)
  : Boolean;
begin
  RichEdit1.Lines.Add('cookie ' + inttostr(Count) + '/' + inttostr(total));
  RichEdit1.Lines.Add('name ' + name);
  RichEdit1.Lines.Add('value ' + value);
  RichEdit1.Lines.Add('domain ' + domain);
  RichEdit1.Lines.Add('path ' + path);
  RichEdit1.Lines.Add('secure ' + BoolToStr(secure));
  RichEdit1.Lines.Add('httponly ' + BoolToStr(httponly));
  RichEdit1.Lines.Add('hasExpires ' + BoolToStr(hasExpires));
  RichEdit1.Lines.Add('creation ' + DateToStr(creation));
  RichEdit1.Lines.Add('lastAccess ' + DateToStr(lastAccess));
  RichEdit1.Lines.Add('expires ' + DateToStr(expires));
  RichEdit1.Lines.Add('------------------------');
  Result := true;
end;

function GetCookies: Boolean;
begin
  CookieManager := TCefCookieManagerRef.Global(nil);
  CookieManager.VisitAllCookiesProc(VisitCookie);
end;

If I set Result := false in my function VisitCookie - I only get the value of the first cookie, that's all. I.e. pass through the cookies does not happen. But if I set Result := true - I got an access violation, but it works fine, until I have not so much cookies records in Chromium, for example 5-10 records. I have no idea why this happens.

Body:
The problem is that the visitor callback function of the VisitAllCookies method is executed in the context of a CEF worker thread, not in a context of the main thread hence you cannot access VCL controls from there. The VisitAllCookies method returns immediately and the callback function is then called asynchronously from the CEF worker thread.

There are many ways how to implement such cooperation. But it's not CEF specific. It's about how to pass (or collect) certain data from a worker thread callback and pass it back to the main thread. Optionally also about taking the callback under control in a synchronous way (to interrupt running enumeration).

Here is one untested example (maybe too overcomplicated). The principle remains, how to collect data from an uncontrolled thread callback function for the main thread (or take it under control in a synchronous way):

type
  TCookie = record
    Name: string;
    Value: string;
    Expires: TDateTime;
  end;

  TProcessCookieEvent = procedure(Sender: TObject; const Cookie: TCookie;
    const IsLast: Boolean; var Delete: Boolean; var Cancel: Boolean) of object;

  TCookieManager = class
  private
    FWndHandle: HWND;
    FOnProcessCookie: TProcessCookieEvent;
  protected
    procedure WndProc(var Msg: TMessage); virtual;
  public
    constructor Create;
    destructor Destroy; override;
    procedure ProcessCookies(Timeout: UINT = 5000);
    property OnProcessCookie: TProcessCookieEvent read FOnProcessCookie write FOnProcessCookie;
  end;

implementation

const
  PA_CANCEL = 1;
  PA_DELETE = 2;
  CM_PROCESSCOOKIE = WM_USER + 100;

type
  PCookie = ^TCookie;

constructor TCookieManager.Create;
begin
  inherited;
  FWndHandle := AllocateHWnd(WndProc);
end;

destructor TCookieManager.Destroy;
begin
  DeallocateHWnd(FWndHandle);
  inherited;
end;

procedure TCookieManager.WndProc(var Msg: TMessage);
var
  Delete: Boolean;
  Cancel: Boolean;
  IsLast: Boolean;
begin
  if Msg.Msg = CM_PROCESSCOOKIE then
  begin
    Msg.Result := 0;

    if Assigned(FOnProcessCookie) then
    try
      Delete := False;
      Cancel := False;
      IsLast := Boolean(Msg.wParam);

      FOnProcessCookie(Self, PCookie(Msg.lParam)^, IsLast, Delete, Cancel);

      if Delete then
        Msg.Result := Msg.Result or PA_DELETE;
      if Cancel then
        Msg.Result := Msg.Result or PA_CANCEL;
    except
      Application.HandleException(Self);
    end;
  end
  else
    Msg.Result := DefWindowProc(FWndHandle, Msg.Msg, Msg.wParam, Msg.lParam);
end;

procedure TCookieManager.ProcessCookies(Timeout: UINT = 5000);
var
  CookieManager: ICefCookieManager;
begin
  CookieManager := TCefCookieManagerRef.Global(nil);
  CookieManager.VisitAllCookiesProc(

    { this function will be called asynchronously from a CEF worker thread }
    function(const Name, Value, Domain, Path: UString; Secure, HTTPOnly,
      HasExpires: Boolean; const Creation, LastAccess, Expires: TDateTime;
      Count, Total: Integer; out DeleteCookie: Boolean): Boolean
    var
      MsgRet: DWORD;
      Cookie: TCookie;
      IsLast: Boolean;
    begin
      { initialize cancel of enumeration and no cookie deletion }
      Result := False;
      DeleteCookie := False;

      { fill the cookie structure }
      Cookie.Name := string(Name);
      Cookie.Value := string(Value);
      Cookie.Expires := Expires;

      { determine if it's the last enumerated cookie }
      IsLast := Count = Total-1;

      { yes, I'm doing what many would not do, but let me explain, this is not
        SendMessage, that could get stuck forever when the message pump of the
        receiver got stucked so I've let this thread responsive (SMTO_NORMAL),
        let this call fail when the receiver is "hung" (SMTO_ABORTIFHUNG) and
        let the function fail if the receiver is destroyed (SMTO_ERRORONEXIT)
        and there is the timeout, in which the receiver needs to process this
        message (if the message is not processed for some reason, enumerating
        stops) }
      if SendMessageTimeout(FWndHandle, CM_PROCESSCOOKIE, WPARAM(IsLast),
        LPARAM(@Cookie), SMTO_NORMAL or SMTO_ABORTIFHUNG or SMTO_ERRORONEXIT,
        Timeout, MsgRet) <> 0 then
      begin
        Result := MsgRet and PA_CANCEL <> PA_CANCEL;
        DeleteCookie := MsgRet and PA_DELETE = PA_DELETE;
      end;
      { else GetLastError and try to signal error by posting another message }
    end;

  );
end;

And a possible usage:

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    FCookieList: TList<TCookie>;
    FCookieManager: TCookieManager;
    procedure DoProcessCookie(Sender: TObject; const Cookie: TCookie;
      const IsLast: Boolean; var Delete: Boolean; var Cancel: Boolean);
  end;

implementation

procedure TForm1.FormCreate(Sender: TObject);
begin
  FCookieList := TList<TCookie>.Create;
  FCookieManager := TCookieManager.Create;
  FCookieManager.OnProcessCookie := DoProcessCookie;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FCookieManager.Free;
  FCookieList.Free;
end;

procedure TForm1.DoProcessCookie(Sender: TObject; const Cookie: TCookie;
  const IsLast: Boolean; var Delete: Boolean; var Cancel: Boolean);
begin
  { IsLast signals last enumerated cookie, Delete output parameter can delete
    the currently enumerated cookie, and Cancel output parameter can stop the
    enumeration }
  FCookieList.Add(Cookie);
  if IsLast then
    ShowMessage('All cookies has been enumerated!');
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  FCookieList.Clear;
  FCookieManager.ProcessCookies;
end;


问:
why stderr fails to be redirected using the 2>&1 instruction? and how outputs are expected to work?
this fails stderr redirection:

(echo a >/dev/stdout;echo b >/dev/stderr) 2>&1 >test2.log;ls test2.log;cat test2.log

so, the above will output: "b" at terminal, and will log "a"

this fails to log stderr too:

(echo a >&1;echo b >&2) 2>&1 >test2.log;ls test2.log;cat test2.log

this vanishes with stdout and logs stderr:

(echo a >/dev/stdout;echo b >/dev/stderr) &>test2.log;ls test2.log;cat test2.log

this fully works:

(echo a >&1;echo b >&2) &>test2.log;ls test2.log;cat test2.log

is this some bug related to the way things should be outputted or I am missing some knowledge?

Obs.: I found this problem because I wasnt being able to log strace dosbox, this is NOT a dosbox question, this is just a comment to say that the origin of the problem was found on a non script application (could be any other application...), and I was able to replicate the problem on a command line terminal in a script way.

PS.: ubuntu 16.04.1 , bash 4.3.48(1)

答:
```<code># Wrong
(echo a >/dev/stdout;echo b >/dev/stderr) 2>&1 >test2.log
</code>```

This first redirects stderr to where stdout is pointing: the console. Then it redirects stdout to test2.log. The second redirection doesn't affect the first. The end result is that stderr is still visible, it isn't logged.

```<code># Right
(echo a >/dev/stdout;echo b >/dev/stderr) >test2.log 2>&1
</code>```

Solution: swap the order of the redirections. Reading left to right, you want to redirect stdout to test2.log, and then redirect stderr to where stdout is pointing: test2.log.

Body:
# Wrong
(echo a >/dev/stdout;echo b >/dev/stderr) 2>&1 >test2.log

This first redirects stderr to where stdout is pointing: the console. Then it redirects stdout to test2.log. The second redirection doesn't affect the first. The end result is that stderr is still visible, it isn't logged.

# Right
(echo a >/dev/stdout;echo b >/dev/stderr) >test2.log 2>&1

Solution: swap the order of the redirections. Reading left to right, you want to redirect stdout to test2.log, and then redirect stderr to where stdout is pointing: test2.log.


问:
How to set background color in MAC OSX in Objective c
I am very new to MAC OSX implementation. Can you guys please suggest any documentations that how to get some grip on Menus,background colors, text fields and all UIElements programatically  with out using interface builder.

Thanking you,
S.

答:
Here! http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSTextField_Class/Reference/Reference.html

Check the setBackground:(NSColor *)color method

Mucking around with colours is lots of fun, but read the Apple Human Interface Guidelines before publishing an app with coloured textfields...