问:
com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed on android 3.2.1 SDK 28.0.3
REVISED: got a new error after upgrading to AS(3.2.1) and Gradle(4.6).

Here is build.gradle code. Gradle property has "
android.enableAapt2 = true" and wrapper property has "distributionUrl=https://services.gradle.org/distributions/gradle-4.6-all.zip"

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

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/CHANGES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
    defaultConfig {
        applicationId "com.abc.app"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0.0"
        multiDexEnabled true
        testInstrumentationRunner "com.android.test.runner.MultiDexTestRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        javaMaxHeapSize "2048M"
    }
    configurations {
        all*.exclude module: 'mediarouter-v7'
        all*.exclude module: 'support-compat'
        compile.exclude group: "org.apache.httpcomponents", module: "httpclient"
    }

    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation 'ch.acra:acra:4.9.1'

    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support:multidex:1.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:percent:28.0.0'

    implementation 'com.google.android.gms:play-services:10.2.1'
    implementation 'com.google.android.gms:play-services-gcm:10.2.1'
    implementation 'com.google.android.gms:play-services-ads:10.2.1'
    implementation 'com.google.android.gms:play-services-auth:10.2.1'

    implementation 'com.google.maps.android:android-maps-utils:0.3.+'
    implementation 'de.hdodenhof:circleimageview:1.3.0'
    implementation 'com.jakewharton:butterknife:8.5.1'
    implementation 'com.uber.sdk:rides-android:0.5.3'
    implementation 'com.google.code.gson:gson:2.8.1'
    implementation 'org.jsoup:jsoup:1.11.3'
    testImplementation 'junit:junit:4.12'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
}

apply plugin: 'com.google.gms.google-services'
</code>```

The new error is

```<code>    Caused by: com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed

C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_btn_colored_text_material.xml:20: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_btn_checkable.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_default.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_edittext.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_seek_thumb.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_spinner.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_switch_track.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_switch_track.xml:20: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_switch_track.xml:21: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\design-28.0.0.aar\d2abd1d1eab13b237ffd0fc5d63d6820\res\color\design_tint_password_toggle.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media.xml:23: error: resource layout/notification_template_icon_group (aka com.abc.app:layout/notification_template_icon_group) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media.xml:23: error: resource dimen/notification_large_icon_height (aka com.abc.app:dimen/notification_large_icon_height) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media.xml:23: error: resource dimen/notification_large_icon_width (aka com.abc.app:dimen/notification_large_icon_width) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media.xml:34: error: resource dimen/notification_large_icon_width (aka com.abc.app:dimen/notification_large_icon_width) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media.xml:34: error: resource dimen/notification_large_icon_width (aka com.abc.app:dimen/notification_large_icon_width) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media_custom.xml:23: error: resource layout/notification_template_icon_group (aka com.abc.app:layout/notification_template_icon_group) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media_custom.xml:23: error: resource dimen/notification_large_icon_height (aka com.abc.app:dimen/notification_large_icon_height) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media_custom.xml:23: error: resource dimen/notification_large_icon_width (aka com.abc.app:dimen/notification_large_icon_width) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media_custom.xml:34: error: resource dimen/notification_large_icon_height (aka com.abc.app:dimen/notification_large_icon_height) not found.
</code>```

Tried many solutions including Invalidate Caches/Restart,  Close and Import Project, remove cache file, reinstall Android Studio, Clean & Rebuild. None of them could make the project build successfully.

Any other possible solutions?

答:
In such situations where you can't find the source of bug, try to create a new project and then first, only copy your .java files into the new project then, try to copy your layout and drawable folders.
Then try to add your dependencies in the build.gradle file  one by one syncing after each add to see which one is causing the problem.

Also I should mention some recommendations in your build.gradle:

First move this line to the top:

apply plugin: 'com.google.gms.google-services'

Right after apply plugin: 'com.android.application'

Also I advise you to migrate to Androidx instead of Support libraries.

Also I wouldn't use jakewharton's butterknife anymore. There is View Binding in Android now. use that: explained here

Body:
REVISED: got a new error after upgrading to AS(3.2.1) and Gradle(4.6).

Here is build.gradle code. Gradle property has "
android.enableAapt2 = true" and wrapper property has "distributionUrl=https://services.gradle.org/distributions/gradle-4.6-all.zip"

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/CHANGES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
    defaultConfig {
        applicationId "com.abc.app"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0.0"
        multiDexEnabled true
        testInstrumentationRunner "com.android.test.runner.MultiDexTestRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        javaMaxHeapSize "2048M"
    }
    configurations {
        all*.exclude module: 'mediarouter-v7'
        all*.exclude module: 'support-compat'
        compile.exclude group: "org.apache.httpcomponents", module: "httpclient"
    }

    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation 'ch.acra:acra:4.9.1'

    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support:multidex:1.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:percent:28.0.0'

    implementation 'com.google.android.gms:play-services:10.2.1'
    implementation 'com.google.android.gms:play-services-gcm:10.2.1'
    implementation 'com.google.android.gms:play-services-ads:10.2.1'
    implementation 'com.google.android.gms:play-services-auth:10.2.1'

    implementation 'com.google.maps.android:android-maps-utils:0.3.+'
    implementation 'de.hdodenhof:circleimageview:1.3.0'
    implementation 'com.jakewharton:butterknife:8.5.1'
    implementation 'com.uber.sdk:rides-android:0.5.3'
    implementation 'com.google.code.gson:gson:2.8.1'
    implementation 'org.jsoup:jsoup:1.11.3'
    testImplementation 'junit:junit:4.12'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
}

apply plugin: 'com.google.gms.google-services'

The new error is

    Caused by: com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed

C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_btn_colored_text_material.xml:20: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_btn_checkable.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_default.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_edittext.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_seek_thumb.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_spinner.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_switch_track.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_switch_track.xml:20: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\888450102b7519d6fb3ec4fed42688ef\res\color\abc_tint_switch_track.xml:21: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\design-28.0.0.aar\d2abd1d1eab13b237ffd0fc5d63d6820\res\color\design_tint_password_toggle.xml:19: error: attribute alpha (aka com.abc.app:alpha) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media.xml:23: error: resource layout/notification_template_icon_group (aka com.abc.app:layout/notification_template_icon_group) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media.xml:23: error: resource dimen/notification_large_icon_height (aka com.abc.app:dimen/notification_large_icon_height) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media.xml:23: error: resource dimen/notification_large_icon_width (aka com.abc.app:dimen/notification_large_icon_width) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media.xml:34: error: resource dimen/notification_large_icon_width (aka com.abc.app:dimen/notification_large_icon_width) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media.xml:34: error: resource dimen/notification_large_icon_width (aka com.abc.app:dimen/notification_large_icon_width) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media_custom.xml:23: error: resource layout/notification_template_icon_group (aka com.abc.app:layout/notification_template_icon_group) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media_custom.xml:23: error: resource dimen/notification_large_icon_height (aka com.abc.app:dimen/notification_large_icon_height) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media_custom.xml:23: error: resource dimen/notification_large_icon_width (aka com.abc.app:dimen/notification_large_icon_width) not found.
C:\Users\<User>\.gradle\caches\transforms-1\files-1.1\support-media-compat-28.0.0.aar\f0a6c1a9d43f0b2d6cca2c26c28e9e86\res\layout\notification_template_big_media_custom.xml:34: error: resource dimen/notification_large_icon_height (aka com.abc.app:dimen/notification_large_icon_height) not found.

Tried many solutions including Invalidate Caches/Restart,  Close and Import Project, remove cache file, reinstall Android Studio, Clean & Rebuild. None of them could make the project build successfully.

Any other possible solutions?


来源: stackexchange

问:
Error protocol_version Java 6 with maven 3.2.5
Hi I'm having an error with maven in java 1.6.

I already tried a lot of solutions in stackoverflow and other websites but I don't know how to solve it.

So here's the Error log:

```<code>    [ERROR] Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.5: Could not transfer artifact org.apache.maven.plugins:maven-clean-plugin:pom:2.5 from/to uk (https://repo1.maven.org/maven2/): Received fatal alert: protocol_version -> [Help 1]
org.apache.maven.plugin.PluginResolutionException: Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.5
    at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.resolve(DefaultPluginDependenciesResolver.java:122)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getPluginDescriptor(DefaultMavenPluginManager.java:150)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getMojoDescriptor(DefaultMavenPluginManager.java:269)
    at org.apache.maven.plugin.DefaultBuildPluginManager.getMojoDescriptor(DefaultBuildPluginManager.java:239)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.setupMojoExecution(DefaultLifecycleExecutionPlanCalculator.java:158)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.setupMojoExecutions(DefaultLifecycleExecutionPlanCalculator.java:145)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan(DefaultLifecycleExecutionPlanCalculator.java:122)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan(DefaultLifecycleExecutionPlanCalculator.java:135)
    at org.apache.maven.lifecycle.internal.builder.BuilderCommon.resolveBuildPlan(BuilderCommon.java:97)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:109)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:120)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:355)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:155)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:216)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:160)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.eclipse.aether.resolution.ArtifactDescriptorException: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.5
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:302)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor(DefaultArtifactDescriptorReader.java:217)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.readArtifactDescriptor(DefaultRepositorySystem.java:287)
    at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.resolve(DefaultPluginDependenciesResolver.java:108)
    ... 25 more
</code>```

I'm using Java 1.6 JDK and Maven 3.2.5 (found that this is the last version that allows java 1.6).

I already tried using set MAVEN_OPTS=-Dhttps.protocols=TLSv1.1,TLSv1.2 on maven settings.xml

If I do an "Update Project" with maven, it works perfectly and also if I try to connect to the URL that maven try to reach I can open it, but in Eclipse it fails.

If you need more information let me know and I will be updating the post.

Thanks in advise.

答:
The root causes of your problems:

Maven Central no longer supports TLSv1.1; see Party's over: TLS 1.1 will be discontinued on Maven Central THIS FRIDAY

Java 6 does not support TLSv1.2.

(The Maven version is not implicated in this.  The "protocol_version" error is coming from the Java 6 built-in JCE provider which doesn't understand TLSv1.2 or later.)

Your possible solutions are:

Upgrade to Java 7 (or better still Java 8 or 11).  Java 6 is EOL.  You shouldn't be using it, and your customers shouldn't be using it.

Try to use a 3rd-party JCE provider in the Java 6 JVM that is running Maven; see How to use TLS 1.2 in Java 6 for suggestions.

Set up your own Artifactory or Nexus repository as a cache for Maven Central, and configure Maven to use it.

Configure Maven to use HTTP (not HTTPS) when talking to Maven Central; see Force m2e to use http instead of https.  (But note this makes your build processes vulnerable to sneaky injection of trojan horse versions of your dependencies.)

Download and add the artifacts that you need (dependency POM and JAR files) to your local (e.g. ~/.m2) Maven repository by hand.

Note that upgrading is the best solution.  Life is only going to get more difficult for people who don't upgrade their Java platform.  You (or your predecessors) should have upgraded in 2012 ... before Java 6 public updates ceased.

ContentLicense: CC BY-SA 4.0

Body:
Hi I'm having an error with maven in java 1.6.

I already tried a lot of solutions in stackoverflow and other websites but I don't know how to solve it.

So here's the Error log:

    [ERROR] Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.5: Could not transfer artifact org.apache.maven.plugins:maven-clean-plugin:pom:2.5 from/to uk (https://repo1.maven.org/maven2/): Received fatal alert: protocol_version -> [Help 1]
org.apache.maven.plugin.PluginResolutionException: Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.5
    at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.resolve(DefaultPluginDependenciesResolver.java:122)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getPluginDescriptor(DefaultMavenPluginManager.java:150)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getMojoDescriptor(DefaultMavenPluginManager.java:269)
    at org.apache.maven.plugin.DefaultBuildPluginManager.getMojoDescriptor(DefaultBuildPluginManager.java:239)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.setupMojoExecution(DefaultLifecycleExecutionPlanCalculator.java:158)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.setupMojoExecutions(DefaultLifecycleExecutionPlanCalculator.java:145)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan(DefaultLifecycleExecutionPlanCalculator.java:122)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan(DefaultLifecycleExecutionPlanCalculator.java:135)
    at org.apache.maven.lifecycle.internal.builder.BuilderCommon.resolveBuildPlan(BuilderCommon.java:97)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:109)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:120)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:355)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:155)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:216)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:160)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.eclipse.aether.resolution.ArtifactDescriptorException: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.5
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:302)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor(DefaultArtifactDescriptorReader.java:217)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.readArtifactDescriptor(DefaultRepositorySystem.java:287)
    at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.resolve(DefaultPluginDependenciesResolver.java:108)
    ... 25 more

I'm using Java 1.6 JDK and Maven 3.2.5 (found that this is the last version that allows java 1.6).

I already tried using set MAVEN_OPTS=-Dhttps.protocols=TLSv1.1,TLSv1.2 on maven settings.xml

If I do an "Update Project" with maven, it works perfectly and also if I try to connect to the URL that maven try to reach I can open it, but in Eclipse it fails.

If you need more information let me know and I will be updating the post.

Thanks in advise.


问:
Quartiles and other parameters in groupby on multiple keys in pandas python
df columns are as below:

```<code>  Key1   Key2   Val1
</code>```

Output needed
I want groupby output where Val1 column has values clubbed together with groupby in python on keys Key1 and Key2.

Output expected: df2  [groupby on key1 and key2]

```<code>Key1 Key2 Val1  Count Sum Q1  Q2  Q3
</code>```

答:
Create a function to calculate Q1, Q2 and Q3: 25th, 50th and 75th percentiles as below:

```<code>def percentile(n):
    def percentile_(x):
        return np.percentile(x, n)
    percentile_.__name__ = 'percentile_%s' % n
    return percentile_
</code>```

Now you can use named aggregation as mentioned below to obtain count, sum and the 3 quartile columns as you want.

```<code>      df2 = (df.groupby(["Key1", "Key2"])
             .agg(Count=(" Val1", 'count'),
                  Sum=('Val1','sum'),
                  Q1= (' Val1',percentile(25), #This is for first quartile
                  Q2= (' Val1',percentile(50), #2nd Quartile
                  Q3= (' Val1',percentile(75)) #This is for Quartile 3
</code>```

Random eg.

df say was

```<code>Key1   Key2  Val1
a       a     1
a       a     2
a       a     3
a       a     4
b       b     5
b       b     6
b       b     7
b       b     8
</code>```

df2 will have below columns as asked for groupby on keys Key1 and Key2.

```<code>Key1 Key2  Count  Sum   Q1  Q2  Q3
 a    a     4     10    1   2.5 3
 b    b     4     6.5   5   6.5 7
</code>```

Body:
df columns are as below:

  Key1   Key2   Val1

Output needed
I want groupby output where Val1 column has values clubbed together with groupby in python on keys Key1 and Key2.

Output expected: df2  [groupby on key1 and key2]

Key1 Key2 Val1  Count Sum Q1  Q2  Q3

Body:
Create a function to calculate Q1, Q2 and Q3: 25th, 50th and 75th percentiles as below:

def percentile(n):
    def percentile_(x):
        return np.percentile(x, n)
    percentile_.__name__ = 'percentile_%s' % n
    return percentile_

Now you can use named aggregation as mentioned below to obtain count, sum and the 3 quartile columns as you want.

      df2 = (df.groupby(["Key1", "Key2"])
             .agg(Count=(" Val1", 'count'),
                  Sum=('Val1','sum'),
                  Q1= (' Val1',percentile(25), #This is for first quartile
                  Q2= (' Val1',percentile(50), #2nd Quartile
                  Q3= (' Val1',percentile(75)) #This is for Quartile 3

Random eg.

df say was

Key1   Key2  Val1
a       a     1
a       a     2
a       a     3
a       a     4
b       b     5
b       b     6
b       b     7
b       b     8

df2 will have below columns as asked for groupby on keys Key1 and Key2.

Key1 Key2  Count  Sum   Q1  Q2  Q3
 a    a     4     10    1   2.5 3
 b    b     4     6.5   5   6.5 7


问:
Splitting an array of points into multiple arrays that have a specific distance from each other
I have an array of points that look like this (x,y):

```<code>6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25
18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25
</code>```

This array represents a two, separate, series of points that are on a 1.25" offset from each other.  There is two series, but there can be [n] series, and I need to split them up into the appropriate number of arrays based on the specific offset like this:

```<code>6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25

18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25
</code>```

The offset can be in the X or the Y, but not both.  I have been working on it for a little while now and am kind of stuck.

Edit

What I have tried so far, is to get a point in the array, and search for all points that are on the interval specified (getDist calculates the distance from one point to another):

```<code>foreach(Point firstPoint in points){
    foreach(Point nextPoint in points){
        if(isSame(firstPoint, nextPoint)
            continue;

        if(getDist(firstPoint, nextPoint) % 1.25 == 0){
            // add to new array
        }
    }
}

double getDist(Point p1, Point p2) => Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));

bool isSame(Point p1, Point p2) => p1.X == p2.X && p1.Y == p2.Y;
</code>```

The problem I run into is that this looks at all the points, then looks at them each one again creating a huge set of arrays.

Body:
I have an array of points that look like this (x,y):

6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25
18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25

This array represents a two, separate, series of points that are on a 1.25" offset from each other.  There is two series, but there can be [n] series, and I need to split them up into the appropriate number of arrays based on the specific offset like this:

6,12
6,13.25
6,14.5
6,15.75
6,17
6,18.25

18,12
18,13.25
18,14.5
18,15.75
18,17
18,18.25

The offset can be in the X or the Y, but not both.  I have been working on it for a little while now and am kind of stuck.

Edit

What I have tried so far, is to get a point in the array, and search for all points that are on the interval specified (getDist calculates the distance from one point to another):

foreach(Point firstPoint in points){
    foreach(Point nextPoint in points){
        if(isSame(firstPoint, nextPoint)
            continue;

        if(getDist(firstPoint, nextPoint) % 1.25 == 0){
            // add to new array
        }
    }
}

double getDist(Point p1, Point p2) => Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));

bool isSame(Point p1, Point p2) => p1.X == p2.X && p1.Y == p2.Y;

The problem I run into is that this looks at all the points, then looks at them each one again creating a huge set of arrays.

Body:
Using linq :

            decimal[,] data = {{6,12}, {6,13.25M}, {6, 14.5M}, {6,15.75M}, {6,17}, {6,18.25M},
                                  {18,12},{18,13.25M}, {18,14.5M},{18,15.75M},{18,17},{18,18.25M}};

            var groups = data.Cast<decimal>()
                .Select((x, i) => new { num = x, index = i })
                .GroupBy(x => x.index / 2)
                .Select(x => new decimal[] { x.FirstOrDefault().num, x.LastOrDefault().num })
                .GroupBy(x => x.FirstOrDefault())
                .Select(x => x.ToArray()).ToArray();


问:
How to make IntelliJ understand annotations
I have recently switched from using Eclipse to IntelliJ, and am preferring the experience.

However, the IDE is not understanding any of the Annotations.  I am using Spring @Autowired annotation as well as some of the Spring-WS annotations and the IDE is telling me that they are unresolved.

When the project is built using Maven, it builds fine, and the Annotations are recognised in Eclipse.

Im sure this is a simple setup thing, but cannot find any information on how to set it up.

答: As Peter said, when correctly importing the Maven project the dependencies should be correctly recognized. The IntelliJ manual has a section on how to import a Maven project.</p>

ContentLicense: CC BY-SA 3.0


问:
Skipping NA rows in index column
I have a dataframe with a column with values TRUE and NA. I'd like to add an index column to the df that indexes all rows with TRUE but simply skips all rows with NA, without removing them. Like this:

```<code>VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    2
TRUE    3
</code>```

At the moment I'm doing it as:

```<code>i = 1:nrow(df)
df$ID <- ifelse(df$VarA == TRUE, i, NA)
</code>```

but that gives me

```<code>VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    4
TRUE    5
</code>```

which is not what I want. I know this should be super easy with something like na.omit but somehow I just can't figure it out.

答:
Using tidyverse, you can do this:

```<code>library(tidyverse)

df %>%
  group_by(VarA) %>%
  mutate(counter = row_number(ID))
</code>```

Output:

```<code>  VarA     ID counter
  <lgl> <int>   <int>
1 TRUE      1       1
2 NA       NA      NA
3 NA       NA      NA
4 TRUE      2       2
5 TRUE      3       3
</code>```

Sample data:

```<code>df <- read.table(text = "VarA    ID
TRUE    1
           NA      NA
           NA      NA
           TRUE    2
           TRUE    3", header = TRUE,
           stringsAsFactors = FALSE)
</code>```

Title: Skipping NA rows in index column

Body:
I have a dataframe with a column with values TRUE and NA. I'd like to add an index column to the df that indexes all rows with TRUE but simply skips all rows with NA, without removing them. Like this:

VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    2
TRUE    3

At the moment I'm doing it as:

i = 1:nrow(df)
df$ID <- ifelse(df$VarA == TRUE, i, NA)

but that gives me

VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    4
TRUE    5

which is not what I want. I know this should be super easy with something like na.omit but somehow I just can't figure it out.

Body:
Using tidyverse, you can do this:

library(tidyverse)

df %>%
  group_by(VarA) %>%
  mutate(counter = row_number(ID))

Output:

  VarA     ID counter
  <lgl> <int>   <int>
1 TRUE      1       1
2 NA       NA      NA
3 NA       NA      NA
4 TRUE      2       2
5 TRUE      3       3

Sample data:

df <- read.table(text = "VarA    ID
TRUE    1
           NA      NA
           NA      NA
           TRUE    2
           TRUE    3", header = TRUE,
           stringsAsFactors = FALSE)


问:
Is there any way to wait for first byte when clicking an HTML anchor?
I have an anchor that when clicked, downloads a file that first needs to be generated. This takes a few seconds, so to the user it seems like nothing is happening. I want to display a loading animation while waiting for the first byte (after which the browser shows the download progress), but I can't figure how to do that.

I don't want to perform an ajax request and register for the progress events, because I want the browser's download manager to handle the actual download.

Is there a way to be notified when the download is actually starting?

答:
I ended up solving it by creating 2 endpoints:

endpoint that generates the file and buffers the result and returns an url to the second enpoint

endpoint that returns the generated (buffered) result

The HTML button the user clicks will ask the first endpoint for the URL, which doesn't return until the file has been generated. While that request is running, a loading animation is displayed to indicate to the user that the file is being generated. When the URL is returned, I stop the animation, create an (invisible) anchor, set the href to that url, attach it to the document and click it, causing the browser to download the file (which will now start to download immediately).


问:
Django dynamic css implementation: only one item changes (background) dynamically. How to?
I would like to set up one single css style which gets the background dynamically
from some django variable.

I think the added difficulty is that it is related to a:hover.

The original static style.css code runs like:

```<code>.titles-button h2 a {
    margin-left: 4em;
    margin-right: 4em;
    margin-top: 1em;
    margin-bottom: 1em;
    display: block;
    width: 240px;
    height: 80px;
    /* background: transparent url(../logos/djangoVX_logo.png) center left no-repeat; */
    text-indent: -999em;
    border: 1px dashed green;
}
.titles-button h2 a:hover {
    /* background: transparent url(../logos/djangoVX_logo2.png) center left no-repeat; */
}
</code>```

Note the background is now commented.

I would like to use this style within a DIV and update dynamically the background.

Like:

```<code>{% if the_apps_list %}
    {% for apps in the_apps_list %}
    <div class="titles-button">
        <h2><a href="/{{ apps.app_name }}/" style="X">{{ apps.app_name }}</a></h2>
    </div>
    {% endfor %}
{% else %}
    <p>No APPS are available. Internal Error.</p>
{% endif %}
</code>```

I did my best for "X" but with no results.

With the exception of:
 - Rewrite the full style in X
 - Use some javascript fancy stuff (on_mouse_over...)
 - I have even seen a class: inheritALL

None of this solution fits my idea of using django.

I might get the bull from the wrong side...

..which one is the right side?

cheers
F

答:
Let's say you have "dark" and "light" versions of background. Your code may look like:

views.py:

```<code>...
if i_want_dark_version:
    context['style']='dark'
else:
    context['style']='light'
</code>```

template.html:

```<code><div id="titles-button" class="{{ style }}">
    ...
</div>
</code>```

style.css:

```<code>#titles-button.dark h2 a {
    background: ...;
}
#titles-button.dark h2 a:hover {
    background: ...;
}

#titles-button.light h2 a {
    background: ...;
}
#titles-button.light h2 a:hover {
    background: ...;
}
</code>```

Body:
I would like to set up one single css style which gets the background dynamically
from some django variable.

I think the added difficulty is that it is related to a:hover.

The original static style.css code runs like:

.titles-button h2 a {
    margin-left: 4em;
    margin-right: 4em;
    margin-top: 1em;
    margin-bottom: 1em;
    display: block;
    width: 240px;
    height: 80px;
    /* background: transparent url(../logos/djangoVX_logo.png) center left no-repeat; */
    text-indent: -999em;
    border: 1px dashed green;
}
.titles-button h2 a:hover {
    /* background: transparent url(../logos/djangoVX_logo2.png) center left no-repeat; */
}

Note the background is now commented.

I would like to use this style within a DIV and update dynamically the background.

Like:

{% if the_apps_list %}
    {% for apps in the_apps_list %}

{{ apps.app_name }}

    {% endfor %}
{% else %}

No APPS are available. Internal Error.

{% endif %}

I did my best for "X" but with no results.

With the exception of:
 - Rewrite the full style in X
 - Use some javascript fancy stuff (on_mouse_over...)
 - I have even seen a class: inheritALL

None of this solution fits my idea of using django.

I might get the bull from the wrong side...

..which one is the right side?

cheers
F

Body:
Let's say you have "dark" and "light" versions of background. Your code may look like:

views.py:

...
if i_want_dark_version:
    context['style']='dark'
else:
    context['style']='light'

template.html:

<div id="titles-button" class="{{ style }}">
    ...
</div>

style.css:

#titles-button.dark h2 a {
    background: ...;
}
#titles-button.dark h2 a:hover {
    background: ...;
}

#titles-button.light h2 a {
    background: ...;
}
#titles-button.light h2 a:hover {
    background: ...;
}


问:
What is the approach to subscribe events from Azure Storage account which has access to only a limited virtual networks?
I am getting the following error when trying to create an Azure Event Subscription from Azure Storage to Azure Function.

```<code>The attempt to configure storage notifications for the provided storage account <storage-name> failed.
Please ensure that your storage account meets the requirements described at https://aka.ms/storageevents.
The error is Failed to retrieve credentials for request=RequestUri=https://management.azure.com/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAcco...
</code>```

I suspect the issue is related to Azure Event Subscription unable to connect to the Storage Account due to the network restrictions. Am I missing some necessary steps?

答:
This error is not due to the virtual network. In fact, the errors displayed already tell you the direction of the problem. View this document: https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-event-overview

Only storage accounts of kind StorageV2 (general purpose v2) and BlobStorage support event integration. Storage (genral purpose v1) does not support integration with Event Grid.

Create a v2 Storage account and the problem should disappear.

Body:
I am getting the following error when trying to create an Azure Event Subscription from Azure Storage to Azure Function.

The attempt to configure storage notifications for the provided storage account <storage-name> failed.
Please ensure that your storage account meets the requirements described at https://aka.ms/storageevents.
The error is Failed to retrieve credentials for request=RequestUri=https://management.azure.com/subscriptions//resourceGroups/<rg>/providers/Microsoft.Storage/storageAcco...

I suspect the issue is related to Azure Event Subscription unable to connect to the Storage Account due to the network restrictions. Am I missing some necessary steps?


答:
One option in base:

```<code>transform(df, ID = replace(cumsum(!is.na(VarA)), is.na(VarA), NA))
</code>```

Output:

```<code>   VarA ID
1: TRUE  1
2:   NA NA
3:   NA NA
4: TRUE  2
5: TRUE  3
</code>```

Title: Skipping NA rows in index column

Body:
One option in base:

transform(df, ID = replace(cumsum(!is.na(VarA)), is.na(VarA), NA))

Output:

   VarA ID
1: TRUE  1
2:   NA NA
3:   NA NA
4: TRUE  2
5: TRUE  3


问:
Random populations of empty lists
I have to write a program in Python in which I give a range and a number of selections to append for 2 empty lists, so the approach of this program should be like this:

Give range to select from: 10

Give number of selections: 5

I should get:

List of numbers selected randomly: [2,3,7,1,8]

List of numbers not selected:  [4,6,5,9,10]

Numbers should not be repeated nor exist in both lists

I have this code:

```<code>import random
selected_list=[]
not_selected=[]
selecting_number=int(input('give range to select from : '))
select_num=int(input('give number of selections: '))
if selecting_number<select_num:
    print('error')
elif selecting_number>=select_num:
    for x in range(select_num):
        selected_list.append(random.randint(1,select_num))
    print(f'List of numbers selected randomly: {selected_list}')
    if not_selected not in selected_list:
        for y in range(select_num):
            not_selected.append(random.randint(1,select_num))
    print(f'List of numbers not selected previously: {not_selected}')
</code>```

This is the output

```<code>List of numbers selected randomly: [6, 7, 7, 7, 7]

List of numbers not selected: [2, 4, 4, 8, 5]
</code>```

答:
What is causing the error is that random is picking random numbers independently and because they are random sometimes the same number is getting picked multiple times.

To fix this, you can use random.sample(the_list_to_pick_from, number_to_pick)
 From the docs:

Returns a list of unique elements chosen from the population sequence
  or set. Used for random sampling without replacement.

One implementation is this:

```<code>import random

range_to_pick_from = list(range(1,10))
selected = random.sample(x, 5)
not_selected = [a for a in range_to_pick_from if a not in selected]
print(selected,not_selected)
</code>```

not_selected can also be written as a traditional for loop:

```<code>not_selected = []
for num in range_to_pick_from:
    if num not in selected:
        not_selected.append(num)
</code>```

Documentation for random.sample

Title: Random populations of empty lists

Body:
I have to write a program in Python in which I give a range and a number of selections to append for 2 empty lists, so the approach of this program should be like this:

Give range to select from: 10

Give number of selections: 5

I should get:

List of numbers selected randomly: [2,3,7,1,8]

List of numbers not selected:  [4,6,5,9,10]

Numbers should not be repeated nor exist in both lists

I have this code:

import random
selected_list=[]
not_selected=[]
selecting_number=int(input('give range to select from : '))
select_num=int(input('give number of selections: '))
if selecting_number<select_num:
    print('error')
elif selecting_number>=select_num:
    for x in range(select_num):
        selected_list.append(random.randint(1,select_num))
    print(f'List of numbers selected randomly: {selected_list}')
    if not_selected not in selected_list:
        for y in range(select_num):
            not_selected.append(random.randint(1,select_num))
    print(f'List of numbers not selected previously: {not_selected}')

This is the output

List of numbers selected randomly: [6, 7, 7, 7, 7]

List of numbers not selected: [2, 4, 4, 8, 5]

Body:
What is causing the error is that random is picking random numbers independently and because they are random sometimes the same number is getting picked multiple times.

To fix this, you can use random.sample(the_list_to_pick_from, number_to_pick)
 From the docs:

Returns a list of unique elements chosen from the population sequence
  or set. Used for random sampling without replacement.

One implementation is this:

import random

range_to_pick_from = list(range(1,10))
selected = random.sample(x, 5)
not_selected = [a for a in range_to_pick_from if a not in selected]
print(selected,not_selected)

not_selected can also be written as a traditional for loop:

not_selected = []
for num in range_to_pick_from:
    if num not in selected:
        not_selected.append(num)

Documentation for random.sample


问:
Visual Studio 2019 - TFS Queries - missing list of queries per team project / team
For VSTS 2019 on premise, connected via Team Explorer to a specific TeamProject / Team :

Upon click on "Work Items", a list of work items is shown, in difference from VSTS 2018, where a list of favorites and queries was shown. This list is needed also in 2019 in order to open a bulk of queries to update definitions, and in order to copy / move bulk of queries between teams and team projects.

Does anyone know where this list was moved to, or how to bypass and resolve ? Thank u

答:
The Azure DevOps Work Items experience has been simplified in Visual Studio 2019.  You'll need to use the Azure DevOps web portal to manage your queries.

Hope this helps.


问:
Send data from an array in api and show response in next screen React Native
I want to send my data from textinputs from an array, the reason why I choose array is because the api which I am calling is basically an array, all I want to do is to set those values from textinput to api and show response to next screen.
Here's my screen One which is taking these values and sending it to api, but problem is it is not sending value neither showing me response onto next screen:

```<code> constructor(props){
        super(props);
        this.state={
            ze:[userid="",
            ID="",
            titlex="",
            switchValue=false,]
        }
    }
 handleSubmit(){
     fetch("https://jsonplaceholder.typicode.com/todos/1", {
        method: "POST",
       // headers: headers,
        body:  JSON.stringify({
          userId:this.state.ze.userid,
          id:this.state.ze.ID,
          title:this.state.ze.titlex,
          completed:this.state.ze.switchValue,
        })
     })
     .then(function(response){
      return response.json();

     })
     .then(function(z){
     console.log(z)
     });
     this.props.navigation.navigate('Pg',{value:this.state.ze});
    }
</code>```

This is my next screen on which it will show me response this is what I've done so far and I dont know how to show response from an array to next screen:

```<code> componentDidMount = () => {
      const item = JSON.stringify(this.props.navigation.getParam('value'));
       Alert.alert(item.id);
     }
     render() {
        return (
           <View>
              <Text>
               {/* Name:{this.state.} */}
              </Text>
           </View>
        )
     }
</code>```

答:
You're sending it correctly but you're not reading it correctly.

Instead of this:

```<code>const item = JSON.stringify(this.props.navigation.getParam('value'));
</code>```

Simply do this:

```<code>const item = this.props.navigation.getParam('value');
</code>```

now to quickly display it, you can use something like this in your JSX:

```<code><Text>{JSON.stringify(item)}</Text>
</code>```

For something more user-friendly, each item on its own line, you can try something like this in your JSX:

```<code>{!!item.length && item.map(i => <Text>i</Text>)}
</code>```

Of course, it depends on what type of items your array contains. Just adjust the code above.

Body:
I want to send my data from textinputs from an array, the reason why I choose array is because the api which I am calling is basically an array, all I want to do is to set those values from textinput to api and show response to next screen.
Here's my screen One which is taking these values and sending it to api, but problem is it is not sending value neither showing me response onto next screen:

 constructor(props){
        super(props);
        this.state={
            ze:[userid="",
            ID="",
            titlex="",
            switchValue=false,]
        }
    }
 handleSubmit(){
     fetch("https://jsonplaceholder.typicode.com/todos/1", {
        method: "POST",
       // headers: headers,
        body:  JSON.stringify({
          userId:this.state.ze.userid,
          id:this.state.ze.ID,
          title:this.state.ze.titlex,
          completed:this.state.ze.switchValue,
        })
     })
     .then(function(response){
      return response.json();

     })
     .then(function(z){
     console.log(z)
     });
     this.props.navigation.navigate('Pg',{value:this.state.ze});
    }

This is my next screen on which it will show me response this is what I've done so far and I dont know how to show response from an array to next screen:

 componentDidMount = () => {
      const item = JSON.stringify(this.props.navigation.getParam('value'));
       Alert.alert(item.id);
     }
     render() {
        return (
           <View>
              <Text>
               {/* Name:{this.state.} */}
              </Text>
           </View>
        )
     }

Body:
You're sending it correctly but you're not reading it correctly.

Instead of this:

const item = JSON.stringify(this.props.navigation.getParam('value'));

Simply do this:

const item = this.props.navigation.getParam('value');

now to quickly display it, you can use something like this in your JSX:

<Text>{JSON.stringify(item)}</Text>

For something more user-friendly, each item on its own line, you can try something like this in your JSX:

{!!item.length && item.map(i => <Text>i</Text>)}

Of course, it depends on what type of items your array contains. Just adjust the code above.


问:
Why isn't text anti-aliasing working, while using a SWT GC to draw text?
Right now my goal is to have anti-aliased text on my Labels. If my research was correct, SWT Labels do not natively support anti-aliasing on text, so my current workaround attempt is to create an image, turn text anti-aliasing on, draw my text to that image, then give that image to the Label.

My current image drawing code is as follows:

```<code>Image image = new Image(Display.getDefault(), width, height);
GC gc = new GC(image);

gc.setAntialias(SWT.ON);
gc.setTextAntialias(SWT.ON);

gc.setBackground(background);
gc.fillRectangle(0, 0, width, height);

gc.setFont(font);
gc.setForeground(foreground);

int yPos = offset.y;
for (String rawLine : lines)
{
    String line = rawLine.trim();
    Point lineSize = gc.textExtent(line);
    int xPos = offset.x;
    switch (alignment)
    {
    case SWT.RIGHT:
        xPos += width - lineSize.x;
        break;
    case SWT.CENTER:
        xPos += width / 2 - lineSize.x / 2;
        break;
    case SWT.LEFT:
    default:
        xPos += 0;
    }
    gc.drawText(line, xPos, yPos, true);
    yPos += lineSize.y;
}

gc.dispose();
return image;
</code>```

I have had inconsistent results on two different computers:
At work, the text in the resulting images appears as choppy as ever- as if text anti-aliasing wasn't even on. But at home, connected to my work computer via remote desktop, I saw exactly the results I wanted.

Obviously I'd like things to work correctly on both computers, but I am currently stumped as to why they aren't. Each computer is running Windows 7, Eclipse v3.6.

What could be the problem that is causing this inconsistency? And if my workaround is just absurd and I am completely missing an easier way, what is that way? Thank you for any help!

答: If you can't get it working in SWT, perhaps you could try rendering to a Swing image and copy the resulting pixels.</p>

ContentLicense: CC BY-SA 2.5

Body:
Right now my goal is to have anti-aliased text on my Labels. If my research was correct, SWT Labels do not natively support anti-aliasing on text, so my current workaround attempt is to create an image, turn text anti-aliasing on, draw my text to that image, then give that image to the Label.

My current image drawing code is as follows:

Image image = new Image(Display.getDefault(), width, height);
GC gc = new GC(image);

gc.setAntialias(SWT.ON);
gc.setTextAntialias(SWT.ON);

gc.setBackground(background);
gc.fillRectangle(0, 0, width, height);

gc.setFont(font);
gc.setForeground(foreground);

int yPos = offset.y;
for (String rawLine : lines)
{
    String line = rawLine.trim();
    Point lineSize = gc.textExtent(line);
    int xPos = offset.x;
    switch (alignment)
    {
    case SWT.RIGHT:
        xPos += width - lineSize.x;
        break;
    case SWT.CENTER:
        xPos += width / 2 - lineSize.x / 2;
        break;
    case SWT.LEFT:
    default:
        xPos += 0;
    }
    gc.drawText(line, xPos, yPos, true);
    yPos += lineSize.y;
}

gc.dispose();
return image;

I have had inconsistent results on two different computers:
At work, the text in the resulting images appears as choppy as ever- as if text anti-aliasing wasn't even on. But at home, connected to my work computer via remote desktop, I saw exactly the results I wanted.

Obviously I'd like things to work correctly on both computers, but I am currently stumped as to why they aren't. Each computer is running Windows 7, Eclipse v3.6.

What could be the problem that is causing this inconsistency? And if my workaround is just absurd and I am completely missing an easier way, what is that way? Thank you for any help!


问:
Adding/Deleting an object to an Obervable of an object array in Angular/RXJS?
Goal: To add an object to an existing Observable array of objects. Having this reflect on the DOM is the final step.

NewObject.ts:

```<code>export class NewObject {
  name: string;
  title: string;
}
</code>```

Here's the example.component.ts:

```<code>import { Observable } from 'rxjs';
import { Component, OnInit, Inject, EventEmitter } from '@angular/core';
import { NewObject } from 'objects';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  // Initializing the object array Observable from a service (step 1)
  readonly objects$: Observable<NewObject[]> = this.objectSvc.getAllObjects("objects").pipe(
    map(obj => obj.map(x => ({ name: x.name, title: alterString(x.title) }))),
    shareReplay(1)
  );

  constructor(
    private objectSvc: ObjectService
  ) { }

  ngOnInit() {

    somethingThatHappensToAdd = (response: any) => {
      let data = JSON.parse(response);
      data.forEach(x => {
        let obj: NewObject = { name: x.name, title: alterString(x.title) }

        // Here's where I'm trying to add the obj object into the already existing object array Observable
      });
    };

    somethingThatHappensToDelete = (response: any) => {
      let data = JSON.parse(response);
      data.forEach(x => {
        let obj: NewObject = { name: x.name, title: alterString(x.title) }

        // Here's where I'm trying to delete the obj object from the already existing object array Observable
      });
    };

  }
}
</code>```

This is my example.component.html:

```<code><div *ngFor="let o of objects$ | async">
   <p>{{ o.name }}</p>
   <p>{{ o.title}}</p>
</div>
</code>```

Here's my service object.service.ts:

```<code>import { Injectable } from '@angular/core';
import { Observable, throwError, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { ClientApi, ApiException, NewObject } from '../client-api.service';

@Injectable({
  providedIn: 'root'
})
export class ObjectService {

  constructor(
    private clientApi: ClientApi
  ) { }

  getAllObjects(name: string): Observable<NewObject[]> {
    return this.clientApi.getAllObjects(name)
      .pipe(
        map((x) => x.result),
        catchError(err => {
          if (ApiException.isApiException(err)) {
            if (err.status === 404) {
              return of<NewObject[]>(undefined);
            }
          }
          return throwError(err);
        })
      );
  }
}
</code>```

After formatting of the response in JSON, I want to be able to insert the obj object into objects$ Observable and have it reflect on the UI.

I am advised to use a BehaviorSubject element to make this happen. Can anyone advise on how this can be easily done?

答:
I found two ways to go about this solution.

Solution 1: https://stackblitz.com/edit/angular-rajvqq

```<code>constructor(private myService: MyService){
  this.myService.getObjects().subscribe(x => this.somethingThatHappensToAdd(x));
}

resultsArray = []
resultsSubject = new BehaviorSubject(this.resultsArray);

readonly objects$: Observable<number[]> = combineLatest(
  this.resultsSubject,
).pipe(
  map(([results]) => ([...results])),
  shareReplay(1)
)

somethingThatHappensToAdd( arrayOfValues ) {
  arrayOfValues.forEach(x => {
    this.resultsArray.push(x)
  });
  this.resultsSubject.next(this.resultsArray)
};

delete(o: any) {

  // This is the same as just accessing this.resultsArray
  let newArray: any[] = this.resultsSubject.getValue();
  for (let i = newArray.length - 1; i >= 0; i--) {
    if (newArray[i] == o) {
      newArray.splice(i, 1);
    }
  }

  this.resultsSubject.next(newArray);
}
</code>```

Solution 2: https://stackblitz.com/edit/angular-gxfk16

```<code>deleteSubject = new Subject<any>();
addSubject = new Subject<any[]>();

objects$ = this.myService.getObjects().pipe(
  switchMap(x => merge(
    of(x),
    this.deleteSubject.pipe(map(y => this.deleteAll(y, x))),
    this.addSubject.pipe(map(y => { x.push(...y); return x; }))
  )),
  shareReplay(1)
);
constructor(private myService: MyService){ }

deleteAll(o: any, v: any[]) {
  for (let i = v.length - 1; i >= 0; i--) {
    if (v[i] == o) {
      v.splice(i, 1);
    }
  }
  return v;
}
</code>```

Body:
Goal: To add an object to an existing Observable array of objects. Having this reflect on the DOM is the final step.

NewObject.ts:

export class NewObject {
  name: string;
  title: string;
}

Here's the example.component.ts:

import { Observable } from 'rxjs';
import { Component, OnInit, Inject, EventEmitter } from '@angular/core';
import { NewObject } from 'objects';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  // Initializing the object array Observable from a service (step 1)
  readonly objects$: Observable<NewObject[]> = this.objectSvc.getAllObjects("objects").pipe(
    map(obj => obj.map(x => ({ name: x.name, title: alterString(x.title) }))),
    shareReplay(1)
  );

  constructor(
    private objectSvc: ObjectService
  ) { }

  ngOnInit() {

    somethingThatHappensToAdd = (response: any) => {
      let data = JSON.parse(response);
      data.forEach(x => {
        let obj: NewObject = { name: x.name, title: alterString(x.title) }

        // Here's where I'm trying to add the obj object into the already existing object array Observable
      });
    };

    somethingThatHappensToDelete = (response: any) => {
      let data = JSON.parse(response);
      data.forEach(x => {
        let obj: NewObject = { name: x.name, title: alterString(x.title) }

        // Here's where I'm trying to delete the obj object from the already existing object array Observable
      });
    };

  }
}

This is my example.component.html:

{{ o.name }}

{{ o.title}}

Here's my service object.service.ts:

import { Injectable } from '@angular/core';
import { Observable, throwError, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { ClientApi, ApiException, NewObject } from '../client-api.service';

@Injectable({
  providedIn: 'root'
})
export class ObjectService {

  constructor(
    private clientApi: ClientApi
  ) { }

  getAllObjects(name: string): Observable<NewObject[]> {
    return this.clientApi.getAllObjects(name)
      .pipe(
        map((x) => x.result),
        catchError(err => {
          if (ApiException.isApiException(err)) {
            if (err.status === 404) {
              return of<NewObject[]>(undefined);
            }
          }
          return throwError(err);
        })
      );
  }
}

After formatting of the response in JSON, I want to be able to insert the obj object into objects$ Observable and have it reflect on the UI.

I am advised to use a BehaviorSubject element to make this happen. Can anyone advise on how this can be easily done?

Body:
I found two ways to go about this solution.

Solution 1: https://stackblitz.com/edit/angular-rajvqq

constructor(private myService: MyService){
  this.myService.getObjects().subscribe(x => this.somethingThatHappensToAdd(x));
}

resultsArray = []
resultsSubject = new BehaviorSubject(this.resultsArray);

readonly objects$: Observable<number[]> = combineLatest(
  this.resultsSubject,
).pipe(
  map(([results]) => ([...results])),
  shareReplay(1)
)

somethingThatHappensToAdd( arrayOfValues ) {
  arrayOfValues.forEach(x => {
    this.resultsArray.push(x)
  });
  this.resultsSubject.next(this.resultsArray)
};

delete(o: any) {

  // This is the same as just accessing this.resultsArray
  let newArray: any[] = this.resultsSubject.getValue();
  for (let i = newArray.length - 1; i >= 0; i--) {
    if (newArray[i] == o) {
      newArray.splice(i, 1);
    }
  }

  this.resultsSubject.next(newArray);
}

Solution 2: https://stackblitz.com/edit/angular-gxfk16

deleteSubject = new Subject<any>();
addSubject = new Subject<any[]>();

objects$ = this.myService.getObjects().pipe(
  switchMap(x => merge(
    of(x),
    this.deleteSubject.pipe(map(y => this.deleteAll(y, x))),
    this.addSubject.pipe(map(y => { x.push(...y); return x; }))
  )),
  shareReplay(1)
);
constructor(private myService: MyService){ }

deleteAll(o: any, v: any[]) {
  for (let i = v.length - 1; i >= 0; i--) {
    if (v[i] == o) {
      v.splice(i, 1);
    }
  }
  return v;
}


问:
CheckBox to Highlight Range Google Sheets Formula/ Google Sheets

I am trying to get the result in the image attached. If I check a checkBox in Column A, I want it to also to highlight the same SKU & Location Column H,I(in Bright Green). Conditional formatting or if script could do this?

答:
You could simply achieve this using conditional formatting. These are the steps to follow:

Select the cell that you want to highlight with the checkbox, right click on it.

Go to conditional formation

Under Conditional format rules -> Format rules select custom formula is under (format cells if) and below it =A2 (or the checkbox cell basically)

Choose the color and press done and you will be ready!

Hope this has helped you, let me know if you need anything else (like an Apps Script implementation of this) or if you did not understand anything.


问:
Text from column cut off- HTML & CSS
I have 3 columns on a page. They all have text in them but not the same amount. My background color for the columns only covers the columns up until the text and not all the way down to the page. I want the background color to be displayed from where the text starts to the bottom of the page stopping just above my footer. I tried playing around with my padding and margin but I'm having trouble fixing it. I can't insert a picture since I just made my account but to paint a picture for you the columns are side by side but different heights, they are not aligned. Can someone please help me out, here is my code:

Thanks!

```<code>
/* Create three equal columns that floats next to each other */
.column {
  align-content: center;
  float: left;
  width: 33.33%;
  height: auto;
  background-color: lightgray;
}

/*Headings in columns*/
h2 {
  text-align: center;
  font-family: sans-serif;
  font-size: 25px;
  color: darkslateblue;
  margin: 10px;
}

/*All text in columns*/
#columntext {
  padding: 1px;
  margin: 10px;
  text-align: justify-all;
  font-family: sans-serif;
  font-size: 16px;
  color: darkslateblue;
}

/*Centers all columns with margin*/
#allcolumns {
  align-content: center;
  margin: 20px;
}
</code>```

答:
I'm not entirely sure what you're asking - I'd recommend including your HTML if possible?

If you're using an id it should only apply to one item on the page, I assume that #columntext is being used for each instance of column text? In which case make this a class instead, same for #allcolumns.

You mention they each float left and are different heights, are these three separate entire tables with a single column? If you're wanting them all to be the same height just make them inside of a single table:

```<code><table>
  <tr>
    <th><h2>Lorem ipsum</h2></th>
    <th><h2>Lorem ipsum</h2></th>
    <th><h2>Lorem ipsum</h2></th>
  </tr>
  <tr>
    <td>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent
    </td>
    <td>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent
    </td>
    <td>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent
    </td>
  </tr>
</table>
</code>```

If you include your HTML it'll be much easier to see what you are trying to do

P.S. I'd recommend using flexbox above floats if this is an option as floats are being phased out!

Title: Text from column cut off- HTML & CSS

Body:
I have 3 columns on a page. They all have text in them but not the same amount. My background color for the columns only covers the columns up until the text and not all the way down to the page. I want the background color to be displayed from where the text starts to the bottom of the page stopping just above my footer. I tried playing around with my padding and margin but I'm having trouble fixing it. I can't insert a picture since I just made my account but to paint a picture for you the columns are side by side but different heights, they are not aligned. Can someone please help me out, here is my code:

Thanks!

/* Create three equal columns that floats next to each other */
.column {
  align-content: center;
  float: left;
  width: 33.33%;
  height: auto;
  background-color: lightgray;
}

/*Headings in columns*/
h2 {
  text-align: center;
  font-family: sans-serif;
  font-size: 25px;
  color: darkslateblue;
  margin: 10px;
}

/*All text in columns*/
#columntext {
  padding: 1px;
  margin: 10px;
  text-align: justify-all;
  font-family: sans-serif;
  font-size: 16px;
  color: darkslateblue;
}

/*Centers all columns with margin*/
#allcolumns {
  align-content: center;
  margin: 20px;
}

Body:
I'm not entirely sure what you're asking - I'd recommend including your HTML if possible?

If you're using an id it should only apply to one item on the page, I assume that #columntext is being used for each instance of column text? In which case make this a class instead, same for #allcolumns.

You mention they each float left and are different heights, are these three separate entire tables with a single column? If you're wanting them all to be the same height just make them inside of a single table:

<table>
  <tr>
    <th><h2>Lorem ipsum</h2></th>
    <th><h2>Lorem ipsum</h2></th>
    <th><h2>Lorem ipsum</h2></th>
  </tr>
  <tr>
    <td>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent
    </td>
    <td>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent
    </td>
    <td>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent
    </td>
  </tr>
</table>

If you include your HTML it'll be much easier to see what you are trying to do

P.S. I'd recommend using flexbox above floats if this is an option as floats are being phased out!


问:
STM32F103C8T6 board not flashing with Keil 5
I have the following problem. Once i generate Keil project using ST CubeMX and write project into STM32F103C8 MCU, everything goes well; However, after this first flashing i'am not able to flash it anymore as it throws the following error:

```<code>Error: Flash Download failed  -  Target DLL has been cancelled
</code>```

I have pulled Boot0 pin, activated it, and erased MCU. This procedure helps only for one time flashing; however, if i flash MCU with bare metal or CMSIS code (which was not generated by CubeMX) it works fine and i can flash as many times as i want without errors.
Could you please advice, what could be wrong and how can i fix this?

答: Problem was in default configuration of STM CubeMx. In System core -> Sys Debug was switched off by default. After i changed it to Serial Wire it worked.

Body:
I have the following problem. Once i generate Keil project using ST CubeMX and write project into STM32F103C8 MCU, everything goes well; However, after this first flashing i'am not able to flash it anymore as it throws the following error:

Error: Flash Download failed  -  Target DLL has been cancelled

I have pulled Boot0 pin, activated it, and erased MCU. This procedure helps only for one time flashing; however, if i flash MCU with bare metal or CMSIS code (which was not generated by CubeMX) it works fine and i can flash as many times as i want without errors.
Could you please advice, what could be wrong and how can i fix this?


问:
How to import into jenkins Msbuild result
I use build on with the following chain to build several dotnet solution:

```<code>Jenkins -> batch (cmd) -> MsBuild
</code>```

How to retrieve build result and failure on MsBuild compilation into jenkins and/or Rational team concert build result ?

I have found jenkins plugin to import trx files (tests results) of MSTest.

I expect to find some think equivalent for MSBuild but i don't want to have to define each solution into jenkins.

答:
The warnings ng plugin will do it for you.  Install the plugin and then use the following in your publish step :

```<code>recordIssues enabledForFailure: true, tools:[msBuild()]
</code>```

https://github.com/jenkinsci/warnings-ng-plugin/blob/master/doc/Documentation.md

Body:
I use build on with the following chain to build several dotnet solution:

Jenkins -> batch (cmd) -> MsBuild

How to retrieve build result and failure on MsBuild compilation into jenkins and/or Rational team concert build result ?

I have found jenkins plugin to import trx files (tests results) of MSTest.

I expect to find some think equivalent for MSBuild but i don't want to have to define each solution into jenkins.

Body:
The warnings ng plugin will do it for you.  Install the plugin and then use the following in your publish step :

recordIssues enabledForFailure: true, tools:[msBuild()]

https://github.com/jenkinsci/warnings-ng-plugin/blob/master/doc/Documentation.md


问:
How to capture external command progress in PowerShell?
I'm using a PowerShell script to synchronize files between network directories. Robocopy is running in the background.

To capture the output and give statistics to the user, currently I'm doing something like:

```<code>$out = (robocopy $src $dst $options)
</code>```

Once that is done, a custom windows form is presented with a multi-line text box containing the output string.

However, doing this way halts the script execution until file copy is done. Since all the other input screen are presented to the user as graphical dialogues, I would like to give user progress output in a graphical way.

Is there a way to capture the stdout from robocopy, on the fly ?

Then the next question would be:

How to pipe that output into a form with a text box?

答:
You can run the robocopy job in the background and keep checking on the progress.

Start-Job will start the process in the background

Receive-Job will give you all the data that has been printed so far.

```<code>$job = Start-Job -scriptBlock { robocopy $using:src $using:dst $using:options }

$out = ""
while( ($job | Get-Job).HasMoreData -or ($job | Get-Job).State -eq "Running") {
    $out += (Receive-job $job)
    Write-output $out
    Start-Sleep 1
}

Remove-Job $job
</code>```

Body:
I'm using a PowerShell script to synchronize files between network directories. Robocopy is running in the background.

To capture the output and give statistics to the user, currently I'm doing something like:

$out = (robocopy $src $dst $options)

Once that is done, a custom windows form is presented with a multi-line text box containing the output string.

However, doing this way halts the script execution until file copy is done. Since all the other input screen are presented to the user as graphical dialogues, I would like to give user progress output in a graphical way.

Is there a way to capture the stdout from robocopy, on the fly ?

Then the next question would be:

How to pipe that output into a form with a text box?

Body:
You can run the robocopy job in the background and keep checking on the progress.

Start-Job will start the process in the background

Receive-Job will give you all the data that has been printed so far.

$job = Start-Job -scriptBlock { robocopy $using:src $using:dst $using:options }

$out = ""
while( ($job | Get-Job).HasMoreData -or ($job | Get-Job).State -eq "Running") {
    $out += (Receive-job $job)
    Write-output $out
    Start-Sleep 1
}

Remove-Job $job


问:
How do I rate limit the beta HTTP Api from AWS API Gateway
How do I rate limit the beta HTTP Api from AWS API Gateway</p>

答:
According to this, Usage plans and API keys are not supported for HTTP APIs. That probably indicates that setting throttle and burst limits is also not possible with HTTP APIs.

To verify this, I tried to update the stage of my HTTP API using update-stage AWS CLI command as below -

```<code>$ aws apigatewayv2 update-stage --api-id $API_ID --stage-name $STAGE_NAME --default-route-settings ThrottlingRateLimit=1000

An error occurred (BadRequestException) when calling the UpdateStage operation: Route-level throttling settings are not supported on protocolType HTTP
</code>```

Like you already know, HTTP APIs are in beta and have very limited features at this moment; the goal of using them is lower cost and performance optimization.

UPDATE: Information on account and route-level throttling for HTTP APIs can be found here.

Body:
According to this, Usage plans and API keys are not supported for HTTP APIs. That probably indicates that setting throttle and burst limits is also not possible with HTTP APIs.

To verify this, I tried to update the stage of my HTTP API using update-stage AWS CLI command as below -

$ aws apigatewayv2 update-stage --api-id $API_ID --stage-name $STAGE_NAME --default-route-settings ThrottlingRateLimit=1000

An error occurred (BadRequestException) when calling the UpdateStage operation: Route-level throttling settings are not supported on protocolType HTTP

Like you already know, HTTP APIs are in beta and have very limited features at this moment; the goal of using them is lower cost and performance optimization.

UPDATE: Information on account and route-level throttling for HTTP APIs can be found here.


问:
Data preparation for association rules algorithm (apriori)
I need help with my data preparation for a project I am working on.
I have 2 columns csv file, one contains the Order number, the second contains the items purchased.

Here's a sample of what I have:

```<code>1 A
1 B
1 C
2 A
2 D
3 F
3 G
3 K
</code>```

I need to transform it to:

```<code>1 A B C
2 A D
3 F G K
</code>```

(this is just a sample I made.. I have 70k rows)
Any help would be amazing. SQL / Python / excel are the tools I know how to work with. So if it possible, the answer within one of them would be the best.
Thanks!

答:
This is spectacularly simple with Python and collections.defaultdict:

```<code>import collections
order_to_products = collections.defaultdict(list)
with open('input.csv') as inp:
   for l in inp:
      order_id, *products = l.split()
      order_to_products[order_id].extend(products)
for order_id, products in order_to_products.items():
   print(order_id, ' '.join(products))
</code>```

(As an added bonus, this actually supports input lines with multiple products.)

E.g.

```<code>$ cat > input.csv
1 A
1 B
1 C
2 A
2 D
3 F
3 G
3 K
$ python3
>>> import collections
>>> order_to_products = collections.defaultdict(list)
>>> with open('input.csv') as inp:
...    for l in inp:
...       order_id, *products = l.split()
...       order_to_products[order_id].extend(products)
...
>>> for order_id, products in order_to_products.items():
...    print(order_id, ' '.join(products))
...
1 A B C
2 A D
3 F G K
</code>```

Body:
I need help with my data preparation for a project I am working on.
I have 2 columns csv file, one contains the Order number, the second contains the items purchased.

Here's a sample of what I have:

1 A
1 B
1 C
2 A
2 D
3 F
3 G
3 K

I need to transform it to:

1 A B C
2 A D
3 F G K

(this is just a sample I made.. I have 70k rows)
Any help would be amazing. SQL / Python / excel are the tools I know how to work with. So if it possible, the answer within one of them would be the best.
Thanks!

Body:
This is spectacularly simple with Python and collections.defaultdict:

import collections
order_to_products = collections.defaultdict(list)
with open('input.csv') as inp:
   for l in inp:
      order_id, *products = l.split()
      order_to_products[order_id].extend(products)
for order_id, products in order_to_products.items():
   print(order_id, ' '.join(products))

(As an added bonus, this actually supports input lines with multiple products.)

E.g.

$ cat > input.csv
1 A
1 B
1 C
2 A
2 D
3 F
3 G
3 K
$ python3
>>> import collections
>>> order_to_products = collections.defaultdict(list)
>>> with open('input.csv') as inp:
...    for l in inp:
...       order_id, *products = l.split()
...       order_to_products[order_id].extend(products)
...
>>> for order_id, products in order_to_products.items():
...    print(order_id, ' '.join(products))
...
1 A B C
2 A D
3 F G K


问:
Sharing operator subtask state using side outputs
I am implementing a streaming application and one of the stateful operators is trying to capture a “owner has items” relationship. The state, keyed per owner consists of details about the owner and each of the items. Ownership of an item can change and I would like to be able associate each item to its correct owner. Since operator state for different owners could be in different subtasks and these subtasks are intended to operate independently, I want to know what’s the best way to share state. One solution that I was able to think of was to create a keyed datastream from the side output of a subtask and have it sent to the correct owner and clear the state from the original owner. Essentially:

Subtask1 with state about OldOwner that has Item1, Item2, … , ItemN

Subtask1 writes to a message to side output (OldOwner, NewOwner, List[ItemsToTransfer])

(Optional) Clear state about List[ItemsToTransfer] from state about OldOwner.

Create a datastream from the side output and send it back to the same operator, but potentially different subtask that has state about NewOwner.

Update the state of NewOwner by adding the new set of items

Since side outputs are intended for a very different purpose (logging, etc.), I want to know whether this will work. Do the same fault tolerance guarantees apply to side outputs as to regular data streams? Is there a limit to how many side output messages can be buffered in a subtask?

An alternative approach might be to take the output of the first subtask and feed it back to the same operator. Both these approaches, in theory violate the property that a flink job is a DAG, although for my use case, there would never be a cyclic data transfer.

答:
Your proposal will create a cycle in the topology because you need to send the events from the side output back to the same/different subtask of the same operator.

What you effectively want is support for multi-key/multi-state transactions in Flink. Flink itself does not come with out-of-the-box support for it. However, Flink provides all the tools necessary to build such a feature on top of it. In fact, the streaming ledger does exactly this. It allows you to do multi-state transactions with exactly once processing guarantees on top of Flink.


问:
What will the code below output to the console and what is the reason?
This is an interview question and I'm very curious about the answer.</p>

```<code>var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();
</code>```

答:
Console logs:

```<code>outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar
</code>```

Because in javascript this refers to the caller's context:

In the call of the func function, this (the context) refers to the caller object, hence the function has visibility of the caller fields and can access them trough this.

In the second function call, this will refer to the global object(window in browsers), (the function func) that does not have a field called foo, hence it will evaluate as undefined. Instead, it has access on self(due to closure), that's why self.foo is accessible.

Body:
This is an interview question and I'm very curious about the answer.

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();

Body:
Console logs:

outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar

Because in javascript this refers to the caller's context:

In the call of the func function, this (the context) refers to the caller object, hence the function has visibility of the caller fields and can access them trough this.

In the second function call, this will refer to the global object(window in browsers), (the function func) that does not have a field called foo, hence it will evaluate as undefined. Instead, it has access on self(due to closure), that's why self.foo is accessible.


问:
Configuring Rails App to handle multiple subdomains and multiple cookies
I have a rails app which supports multiple domains and each domain may have multiple subdomains.

Users visiting mydomain1.com do not receive the same experience as mydomain2.com (although the base behaviour of the apps is the same)

Therefore, if a user is logged in to mydomain1.com, it shouldn't then be logged in to mydomain2.com

If a user is logged in to france.mydomain1.com, it should then be logged in to germany.mydomain1.com

Previously, I've handled this by setting the domain in the session store configs:

```<code>MyApp::Application.config.session_store :cookie_store, :key => '_MyApp_session', :domain => APP_CONFIG[:domain]
</code>```

I'm trying to work out the best way to handle this with multiple domains?

I've tried hacking around ActionDispatch::Callback but the request is not available from within there.

Can anybody suggest a good way of supporting multiple cookies from within one app?

Ideally I'd like to create a fresh cookie for each subdomain.

答:
It shouldn't be an issue as cookies are only valid per domain. You can have a _MyApp_session for example1.com and one for example2.com. The cookies are managed by the browser and only sent to the host if the domain matches.

Say you visit example1.com and log in and you will get a cookie with the value abcdef123. Then you log into example2.com and you will get another cookie with a random string uvwxyz890.

If you return to example1.com later, the browser will only send the cookies that are valid for this domain to your app. Your app won't have to manage anything and you don't have to hack anything.

Body:
I have a rails app which supports multiple domains and each domain may have multiple subdomains.

Users visiting mydomain1.com do not receive the same experience as mydomain2.com (although the base behaviour of the apps is the same)

Therefore, if a user is logged in to mydomain1.com, it shouldn't then be logged in to mydomain2.com

If a user is logged in to france.mydomain1.com, it should then be logged in to germany.mydomain1.com

Previously, I've handled this by setting the domain in the session store configs:

MyApp::Application.config.session_store :cookie_store, :key => '_MyApp_session', :domain => APP_CONFIG[:domain]

I'm trying to work out the best way to handle this with multiple domains?

I've tried hacking around ActionDispatch::Callback but the request is not available from within there.

Can anybody suggest a good way of supporting multiple cookies from within one app?

Ideally I'd like to create a fresh cookie for each subdomain.


问:
Why introduce a new array in a method? Why not reuse the parameter?
In the method normalize I input an array say, {1, 2, 3, 4}, and the return is a normalized array, {0.1, 0.2, 0.3, 0.4}.
I know I should introduce a new array in the method (b in the following), but why actually?

```<code>public static double[] normalize(double[] a) {
    double[] b = new double[a.length];
    double sum = 0;
        for (int i = 0; i < b.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < b.length; i++) {
            b[i] = a[i]/sum;
        }
    return b;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4
</code>```

Why is the following wrong:

```<code>public static double[] normalize(double[] a) {
    double sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < a.length; i++) {
            a[i] = a[i]/sum;
        }
    return a;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4
</code>```

答:
Explaining the byte code behavior, and the difference of creating a new array or reusing the same input is not what you are asking for I think. Because it is really easy to see the difference.

What I think you are looking for, is a conceptual analysis of the difference. From my perspective, "functions" in any language should be treated as math functions. You give X and Y, and the function returns Z. Imagine you have a rectangle which height = a and width = b. If you want the area of it, you pass a and b and you get A . If you want the perimeter, you pass a and b and you get P.

This makes your code more readable, reusable, more cohesive, more testable.

Body:
In the method normalize I input an array say, {1, 2, 3, 4}, and the return is a normalized array, {0.1, 0.2, 0.3, 0.4}.
I know I should introduce a new array in the method (b in the following), but why actually?

public static double[] normalize(double[] a) {
    double[] b = new double[a.length];
    double sum = 0;
        for (int i = 0; i < b.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < b.length; i++) {
            b[i] = a[i]/sum;
        }
    return b;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4

Why is the following wrong:

public static double[] normalize(double[] a) {
    double sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < a.length; i++) {
            a[i] = a[i]/sum;
        }
    return a;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4


问:
How to use a conditional decorator in python?
In trying to understand a conditional decorator in python I came upon this example. The accepted answer for that question explains how to define a conditional decorator, but not how to use it.

The example code is as follows:

```<code>class conditional_decorator(object):
    def __init__(self, dec, condition):
        self.decorator = dec
        self.condition = condition

    def __call__(self, func):
        if not self.condition:
            # Return the function unchanged, not decorated.
            return func
        return self.decorator(func)

@conditional_decorator(timeit, doing_performance_analysis)
def foo():
    time.sleep(2)
</code>```

But how to use it? I tried the following calls of foo like this:

```<code>doing_performance_analysis=False
foo()

doing_performance_analysis=True
foo()
</code>```

but I got the following errors:

```<code>Traceback (most recent call last):
  File "tester.py", line 18, in <module>
    @conditional_decorator(timeit, doing_performance_analysis)
NameError: name 'doing_performance_analysis' is not defined
</code>```

So how does it work correctly?

答:
If you use the python 3 wrapt module you can set an enabled flag to switch your decorator on or off. For debug reasons i try to paste a specific parameter given to a function to the clipboard (using pandas). This is done by the following decorator.

```<code>CLIPTRACE = True

def traceClipboard(fieldname):
    """ give fieldname of the functions formal parameter
        to get value dumped to clipboard
        also use wrapt parameter to disable if cliptrace is not set
    """
    @wrapt.decorator(enabled=CLIPTRACE)
    def wrapper(wrapped, instance, args, kwargs):
        args_list = inspect.getfullargspec(wrapped)[0]
        if "self" in args_list:
            args_list.pop(0)
        if fieldname in args_list:
            pyperclip.copy(args[args_list.index(fieldname)])

        if fieldname in kwargs.keys():
            pyperclip.copy(kwargs.get(fieldname))
        return wrapped(*args, **kwargs)
    return wrapper
</code>```

then use it for decorating a function of my session class:

```<code> @traceClipboard("url")
 def _get(self, url, odata=None):
    """single _get request..."""
</code>```

as long as CLIPTRACE is True the value of the parameter "url" is copied to clipboard, in productive environment CLIPTRACE is False and no clipboard copy is performed.

Body:
In trying to understand a conditional decorator in python I came upon this example. The accepted answer for that question explains how to define a conditional decorator, but not how to use it.

The example code is as follows:

class conditional_decorator(object):
    def __init__(self, dec, condition):
        self.decorator = dec
        self.condition = condition

    def __call__(self, func):
        if not self.condition:
            # Return the function unchanged, not decorated.
            return func
        return self.decorator(func)

@conditional_decorator(timeit, doing_performance_analysis)
def foo():
    time.sleep(2)

But how to use it? I tried the following calls of foo like this:

doing_performance_analysis=False
foo()

doing_performance_analysis=True
foo()

but I got the following errors:

Traceback (most recent call last):
  File "tester.py", line 18, in <module>
    @conditional_decorator(timeit, doing_performance_analysis)
NameError: name 'doing_performance_analysis' is not defined

So how does it work correctly?

Body:
If you use the python 3 wrapt module you can set an enabled flag to switch your decorator on or off. For debug reasons i try to paste a specific parameter given to a function to the clipboard (using pandas). This is done by the following decorator.

CLIPTRACE = True

def traceClipboard(fieldname):
    """ give fieldname of the functions formal parameter
        to get value dumped to clipboard
        also use wrapt parameter to disable if cliptrace is not set
    """
    @wrapt.decorator(enabled=CLIPTRACE)
    def wrapper(wrapped, instance, args, kwargs):
        args_list = inspect.getfullargspec(wrapped)[0]
        if "self" in args_list:
            args_list.pop(0)
        if fieldname in args_list:
            pyperclip.copy(args[args_list.index(fieldname)])

        if fieldname in kwargs.keys():
            pyperclip.copy(kwargs.get(fieldname))
        return wrapped(*args, **kwargs)
    return wrapper

then use it for decorating a function of my session class:

 @traceClipboard("url")
 def _get(self, url, odata=None):
    """single _get request..."""

as long as CLIPTRACE is True the value of the parameter "url" is copied to clipboard, in productive environment CLIPTRACE is False and no clipboard copy is performed.