问:
NullPointer while generate signed APK
I generated several times signed APK before added okhttp , dexter and other server side libraries.

Exception:

```<code>java.lang.NullPointerException
    at com.android.tools.r8.naming.ClassNameMinifier.a(:81)
    at com.android.tools.r8.naming.ClassNameMinifier.a(:25)
    at com.android.tools.r8.naming.ClassNameMinifier.a(:2)
    at com.android.tools.r8.naming.Minifier.run(:15)
    at com.android.tools.r8.R8.a(:493)
    at com.android.tools.r8.R8.c(:1)
    at com.android.tools.r8.R8.b(:1)
    at com.android.tools.r8.utils.t.a(:23)
    at com.android.tools.r8.R8.runForTesting(:3)
    at com.android.tools.r8.R8.run(:3)
    at com.android.builder.dexing.R8Tool.runR8(r8Tool.kt:195)
    at com.android.build.gradle.internal.transforms.R8Transform.transform(R8Transform.kt:261)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:239)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:235)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:106)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:230)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:103)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskInputsTaskAction.doExecute(IncrementalTaskInputsTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:41)
    at org.gradle.api.internal.project.taskfactory.AbstractIncrementalTaskAction.execute(AbstractIncrementalTaskAction.java:25)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:28)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$5.run(ExecuteActionsTaskExecuter.java:404)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:393)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:376)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$200(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:213)
    at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$0(ExecuteStep.java:32)
    at java.util.Optional.map(Optional.java:215)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:32)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:26)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:58)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:35)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:48)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:33)
    at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:39)
    at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:73)
    at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:54)
    at org.gradle.internal.execution.steps.CatchExceptionStep.execute(CatchExceptionStep.java:35)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:45)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:31)
    at org.gradle.internal.execution.steps.CacheStep.executeWithoutCache(CacheStep.java:201)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:70)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:45)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:49)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:43)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:32)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:38)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:24)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:96)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:89)
    at java.util.Optional.map(Optional.java:215)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:54)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:38)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:77)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:37)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:36)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:26)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:90)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:48)
    at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:33)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:120)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java:75)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
    at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:94)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:49)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Any solution? I think this problem happened because of okhttp

build.gradle (Module:app)

```<code>/*TODO:-> Retrofit*/
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'org.apache.httpcomponents:httpclient-android:4.3.3'
    implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.13.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.13.0'
</code>```

what is happening? when I run from android studio, it works fine. I tried several solution from stack overflow and other sites but it is not working.

EDIT:

```<code>build.gradle (project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0-beta01'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

build.gradle (app)

```<code>apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        // These docs use an open ended version so that our plugin
        // can be updated quickly in response to Android tooling updates

        // We recommend changing it to the latest version from our changelog:
        // https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
        classpath 'io.fabric.tools:gradle:1.+'
    }
}

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.tekitsolutions.remindme"
        minSdkVersion 19
        targetSdkVersion 28
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        android.defaultConfig.vectorDrawables.useSupportLibrary = true

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        customDebugType {
            debuggable true
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha04'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'

    /*TODO:-> For showing Database on Google Chrome*/
    implementation 'com.facebook.stetho:stetho:1.5.0'

    implementation('com.crashlytics.sdk.android:crashlytics:2.9.8@aar') {
        transitive = true
    }

    /*TODO:-> For View binding*/
    implementation 'com.jakewharton:butterknife:10.1.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'

    /*TODO:-> Number Picker*/
    implementation 'com.github.travijuu:numberpicker:1.0.7'

    /*TODO:-> Circle ImageView*/
    implementation 'de.hdodenhof:circleimageview:2.2.0'

    /*TODO:-> Remove before development*/
    implementation 'com.ajts.androidmads.SQLite2Excel:library:1.0.4'

    /*TODO:-> Dexter runtime permissions*/
    implementation 'com.karumi:dexter:5.0.0'

    /*TODO:-> Retrofit*/
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'org.apache.httpcomponents:httpclient-android:4.3.3'
    implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.13.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.13.0'

}
</code>```

答:
This is a duplicate of a bug report on R8: https://b.corp.google.com/issues/131210377

The bug is fixed in a later version and you should be able to use it by adding the following to your build.gradle file:

```<code>buildscript {

    repositories {
        maven {
            url 'http://storage.googleapis.com/r8-releases/raw'
        }
    }

    dependencies {
        classpath 'com.android.tools:r8:1.5.24'          // Must be before the Gradle Plugin for Android.
        classpath 'com.android.tools.build:gradle:X.Y.Z' // Your current AGP version.
     }
}
</code>```

If that does not work I think you should file a bug on the R8 bug tracker.

Title: NullPointer while generate signed APK

Body:
I generated several times signed APK before added okhttp , dexter and other server side libraries.

Exception:

java.lang.NullPointerException
    at com.android.tools.r8.naming.ClassNameMinifier.a(:81)
    at com.android.tools.r8.naming.ClassNameMinifier.a(:25)
    at com.android.tools.r8.naming.ClassNameMinifier.a(:2)
    at com.android.tools.r8.naming.Minifier.run(:15)
    at com.android.tools.r8.R8.a(:493)
    at com.android.tools.r8.R8.c(:1)
    at com.android.tools.r8.R8.b(:1)
    at com.android.tools.r8.utils.t.a(:23)
    at com.android.tools.r8.R8.runForTesting(:3)
    at com.android.tools.r8.R8.run(:3)
    at com.android.builder.dexing.R8Tool.runR8(r8Tool.kt:195)
    at com.android.build.gradle.internal.transforms.R8Transform.transform(R8Transform.kt:261)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:239)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:235)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:106)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:230)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:103)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskInputsTaskAction.doExecute(IncrementalTaskInputsTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:41)
    at org.gradle.api.internal.project.taskfactory.AbstractIncrementalTaskAction.execute(AbstractIncrementalTaskAction.java:25)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:28)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$5.run(ExecuteActionsTaskExecuter.java:404)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:393)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:376)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$200(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:213)
    at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$0(ExecuteStep.java:32)
    at java.util.Optional.map(Optional.java:215)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:32)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:26)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:58)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:35)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:48)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:33)
    at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:39)
    at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:73)
    at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:54)
    at org.gradle.internal.execution.steps.CatchExceptionStep.execute(CatchExceptionStep.java:35)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:45)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:31)
    at org.gradle.internal.execution.steps.CacheStep.executeWithoutCache(CacheStep.java:201)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:70)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:45)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:49)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:43)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:32)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:38)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:24)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:96)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:89)
    at java.util.Optional.map(Optional.java:215)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:54)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:38)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:77)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:37)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:36)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:26)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:90)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:48)
    at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:33)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:120)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java:75)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
    at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:94)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:49)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)

Any solution? I think this problem happened because of okhttp

build.gradle (Module:app)

/*TODO:-> Retrofit*/
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'org.apache.httpcomponents:httpclient-android:4.3.3'
    implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.13.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.13.0'

what is happening? when I run from android studio, it works fine. I tried several solution from stack overflow and other sites but it is not working.

EDIT:

build.gradle (project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0-beta01'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle (app)

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        // These docs use an open ended version so that our plugin
        // can be updated quickly in response to Android tooling updates

        // We recommend changing it to the latest version from our changelog:
        // https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
        classpath 'io.fabric.tools:gradle:1.+'
    }
}

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.tekitsolutions.remindme"
        minSdkVersion 19
        targetSdkVersion 28
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        android.defaultConfig.vectorDrawables.useSupportLibrary = true

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        customDebugType {
            debuggable true
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha04'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'

    /*TODO:-> For showing Database on Google Chrome*/
    implementation 'com.facebook.stetho:stetho:1.5.0'

    implementation('com.crashlytics.sdk.android:crashlytics:2.9.8@aar') {
        transitive = true
    }

    /*TODO:-> For View binding*/
    implementation 'com.jakewharton:butterknife:10.1.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'

    /*TODO:-> Number Picker*/
    implementation 'com.github.travijuu:numberpicker:1.0.7'

    /*TODO:-> Circle ImageView*/
    implementation 'de.hdodenhof:circleimageview:2.2.0'

    /*TODO:-> Remove before development*/
    implementation 'com.ajts.androidmads.SQLite2Excel:library:1.0.4'

    /*TODO:-> Dexter runtime permissions*/
    implementation 'com.karumi:dexter:5.0.0'

    /*TODO:-> Retrofit*/
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'org.apache.httpcomponents:httpclient-android:4.3.3'
    implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.13.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.13.0'

}

Body:
This is a duplicate of a bug report on R8: https://b.corp.google.com/issues/131210377

The bug is fixed in a later version and you should be able to use it by adding the following to your build.gradle file:

buildscript {

    repositories {
        maven {
            url 'http://storage.googleapis.com/r8-releases/raw'
        }
    }

    dependencies {
        classpath 'com.android.tools:r8:1.5.24'          // Must be before the Gradle Plugin for Android.
        classpath 'com.android.tools.build:gradle:X.Y.Z' // Your current AGP version.
     }
}

If that does not work I think you should file a bug on the R8 bug tracker.


来源: stackexchange

问:
Why can't I access the 2nd element in this array, while loop issue
I have this while loops and an embedded if statement which places a hyperlink in the appropriate table cell. When I press edit the URL reflects what I want to see (which is the current word to be edited) but the text field the word is suppose to populate is only ever the first entry in the database table.

I have tried Using PHP variables inside HTML tags?
which I think does not work because mine is an internal link, not another website.

I have also tried to store $row['yourword'] in another var, so when the while loop encounters that if statement which puts the edit in the right cell, it also would save the correct yourword, but it just results in an error.

Here is the while loop

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['uname'] . "	";
echo "" . $row['clickrate'] . "	";
if($row['uname'] == $logedInUsername)
{
    echo "" . $row['yourword'] . " edit	";
}
else
{
    echo "" . $row['yourword'] . "	";
}
echo "
";
}
echo "
";
?>
```

<p>And here is the destination</p>

<pre class="lang-php prettyprint-override"><code><form action="edityourword.php" method="POST">
    word: <input type="text" name="newName" value="<?php echo $row[yourword]; ?>"><br><br>
    <input type="submit" value="Update">
</form>
</code>```

The expected result should be the 2nd word showing up in the text field on the next page, instead of the first one each time, editing the word still works, but the text field is just populated with wrong one each time if it is not the user which is the first on the table.

PS. If visualising helps: table

答:
You should get the value of 'edit' in your destination with : $_GET['edit'] since you are sending it as parameter in the link

```<code><a href='edityourword.php?edit=$row[yourword]'> edit</a>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this while loops and an embedded if statement which places a hyperlink in the appropriate table cell. When I press edit the URL reflects what I want to see (which is the current word to be edited) but the text field the word is suppose to populate is only ever the first entry in the database table.

I have tried Using PHP variables inside HTML tags?
which I think does not work because mine is an internal link, not another website.

I have also tried to store $row['yourword'] in another var, so when the while loop encounters that if statement which puts the edit in the right cell, it also would save the correct yourword, but it just results in an error.

Here is the while loop

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['uname'] . "	";
echo "" . $row['clickrate'] . "	";
if($row['uname'] == $logedInUsername)
{
    echo "" . $row['yourword'] . " edit	";
}
else
{
    echo "" . $row['yourword'] . "	";
}
echo "
";
}
echo "
";
?>

And here is the destination

<form action="edityourword.php" method="POST">
    word: <input type="text" name="newName" value="<?php echo $row[yourword]; ?>">

    <input type="submit" value="Update">
</form>

The expected result should be the 2nd word showing up in the text field on the next page, instead of the first one each time, editing the word still works, but the text field is just populated with wrong one each time if it is not the user which is the first on the table.

PS. If visualising helps: table

Body:
You should get the value of 'edit' in your destination with : $_GET['edit'] since you are sending it as parameter in the link

<a href='edityourword.php?edit=$row[yourword]'> edit</a>


问:
Why I'm unable to debug my code in TestNG
I am running automation tests using TestNG and Java.

Here is part of my code:

```<code>private void testConnection(String URL1) throws IOException {

    try {
        URL url = new URL(URL1);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.connect();

        assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
    } catch (IOException e) {
        ConsoleLogger.error("*******************************");
        ConsoleLogger.error("Could NOT connect to the server");
        ConsoleLogger.error("Entire test is aborted!!!");
        ConsoleLogger.error("Please check port and IP again!");
        ConsoleLogger.error("*******************************");
        throw e;
    }
}
</code>```

Now, my test fails because I am getting an exception from the URL.
I can see in the console the error message/s.
This method is being called in a method with the annotation @BeforeSuite.

Why can’t I debug this method (not the try block nor the catch block)?

答: Since you can print out the error message, definitely you have chance to debug. You can try to set break point at that printing error message. If it still fail. Means your workspace is not update with your code. Just refresh or restart your IDE. Good luck.</p>

Body:
I am running automation tests using TestNG and Java.

Here is part of my code:

private void testConnection(String URL1) throws IOException {

    try {
        URL url = new URL(URL1);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.connect();

        assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
    } catch (IOException e) {
        ConsoleLogger.error("*******************************");
        ConsoleLogger.error("Could NOT connect to the server");
        ConsoleLogger.error("Entire test is aborted!!!");
        ConsoleLogger.error("Please check port and IP again!");
        ConsoleLogger.error("*******************************");
        throw e;
    }
}

Now, my test fails because I am getting an exception from the URL.
I can see in the console the error message/s.
This method is being called in a method with the annotation @BeforeSuite.

Why can’t I debug this method (not the try block nor the catch block)?


问:
pyomo creating constraints via a loop
I am adding a series of constraints like this, one for each node (Node_A, Node_B, ... Node_L):

```<code>def NodeA(model):
    k = sum(
        model.ArcVar[i] * node_arc_matrix[i,0]
        for i in model.ArcVar
            )
    return k ==  2*model.NodeVar[1]
model.NodeAConstraint=Constraint(rule=NodeA)
</code>```

Where the 0-index in node_arc_matrix refers to the column corresponding to Node_A, and model.NodeVar[1] refers to Node-A as well.  Instead of creating a constraint for each node manually can I create constraints across both i (arcs) and j (nodes)?

答:
No need to add a loop.

When you have elements in your constraint that are a "for all element in ...", Pyomo simply requires you to add the Sets that you want to iterate over in the Constraint construction line.

```<code>model.NodeAConstraint=Constraint(model.set_of_arcs_A, model.set_of_node_N, rule=NodeA)
</code>```

And your rule must include a and n as parameters (i seems to already be used in your function).

```<code>def NodeA(model, a, n):
    k = sum(
        model.ArcVar[i] * node_arc_matrix[i,a]
        for i in model.ArcVar
    )
    return k ==  2 * model.NodeVar[n]
</code>```

Notice where I put a and n in the previous code. It also needs to be parameters for your function. I tried replacing every 0 by a and every 1 by n, if I understood your needs correctly.

Link to documentation here: https://pyomo.readthedocs.io/en/stable/pyomo_modeling_components/Constraints.html

Title: pyomo creating constraints via a loop

Body:
I am adding a series of constraints like this, one for each node (Node_A, Node_B, ... Node_L):

def NodeA(model):
    k = sum(
        model.ArcVar[i] * node_arc_matrix[i,0]
        for i in model.ArcVar
            )
    return k ==  2*model.NodeVar[1]
model.NodeAConstraint=Constraint(rule=NodeA)

Where the 0-index in node_arc_matrix refers to the column corresponding to Node_A, and model.NodeVar[1] refers to Node-A as well.  Instead of creating a constraint for each node manually can I create constraints across both i (arcs) and j (nodes)?

Body:
No need to add a loop.

When you have elements in your constraint that are a "for all element in ...", Pyomo simply requires you to add the Sets that you want to iterate over in the Constraint construction line.

model.NodeAConstraint=Constraint(model.set_of_arcs_A, model.set_of_node_N, rule=NodeA)

And your rule must include a and n as parameters (i seems to already be used in your function).

def NodeA(model, a, n):
    k = sum(
        model.ArcVar[i] * node_arc_matrix[i,a]
        for i in model.ArcVar
    )
    return k ==  2 * model.NodeVar[n]

Notice where I put a and n in the previous code. It also needs to be parameters for your function. I tried replacing every 0 by a and every 1 by n, if I understood your needs correctly.

Link to documentation here: https://pyomo.readthedocs.io/en/stable/pyomo_modeling_components/Constraints.html


问:
Julia: Flux.jl: "function gradient does not accept keyword arguments"
I'm trying to use Flux.jl v"0.6.10 (which I freshly installed and which looks like an awesome package) with Julia Version 1.1.0 and copied the following code from the "basic" section of the documation of flux.jl

```<code>using Flux.Tracker
f(x) = 3x^2 + 2x + 1;
df(x) = Tracker.gradient(f, x; nest = true)[1];
df(2)
</code>```

However I got this error message:

```<code>ERROR: function gradient does not accept keyword arguments
Stacktrace:
 [1] kwfunc(::Any) at ./boot.jl:330
 [2] df(::Int64) at ./REPL[3]:1
 [3] top-level scope at none:0
</code>```

What am I doing wrong?

答: Well I just found that the version that I installed and update is the v"0.6.10 (although I just ran (v1.1) pkg> update Flux). However in the documentation, the code above is df(x) = Tracker.gradient(f, x)[1] for the definition of the gradient (and not df(x) = Tracker.gradient(f, x; nest = true)[1];, which is valid for the version v"0.8.3)

Body:
I'm trying to use Flux.jl v"0.6.10 (which I freshly installed and which looks like an awesome package) with Julia Version 1.1.0 and copied the following code from the "basic" section of the documation of flux.jl

using Flux.Tracker
f(x) = 3x^2 + 2x + 1;
df(x) = Tracker.gradient(f, x; nest = true)[1];
df(2)

However I got this error message:

ERROR: function gradient does not accept keyword arguments
Stacktrace:
 [1] kwfunc(::Any) at ./boot.jl:330
 [2] df(::Int64) at ./REPL[3]:1
 [3] top-level scope at none:0

What am I doing wrong?


问:
Capybara and Javascript onbefoureunload
I have an 'ask_a_question' page with an onbeforeunload function to alert the user before leaving something unsaved (hey! like SO :P). I'm testing it using cucumber with capybara and webdriver, adding the @javascript tag because it uses a lot of javascript. A cucumber feature might look like this:

```<code>@javascript
Scenario: add a question
    Given I login as "Mauricio"
    And I go to the create question page
    Then I should see "Ask a Question" within "header"
</code>```

But once the test pases, Capybara (or WebDriver, I dunno) tries to reuse the same browser window for other tests then the onbeforeunload alert is displayed screwing the following test.

As my feature is not closing or exiting the page per se. I don't think it might be good idea  to add something to accept the alert. But honestly I'm quite lost.

How can I tell capybara to use a new browser window for each @javascript test or automatically close the onbeforeunload alert?

Thanx

答:
you can use page.driver.browser.switch_to.alert.dismiss (docs here) to get rid of the alert.

You could put this in a cucumber after hook

```<code>After "@javascript" do
  page.driver.browser.switch_to.alert.dismiss
  # or accept it if that is what you prefer
  page.driver.browser.switch_to.alert.accept
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: Capybara and Javascript onbefoureunload

Body:
I have an 'ask_a_question' page with an onbeforeunload function to alert the user before leaving something unsaved (hey! like SO :P). I'm testing it using cucumber with capybara and webdriver, adding the @javascript tag because it uses a lot of javascript. A cucumber feature might look like this:

@javascript
Scenario: add a question
    Given I login as "Mauricio"
    And I go to the create question page
    Then I should see "Ask a Question" within "header"

But once the test pases, Capybara (or WebDriver, I dunno) tries to reuse the same browser window for other tests then the onbeforeunload alert is displayed screwing the following test.

As my feature is not closing or exiting the page per se. I don't think it might be good idea  to add something to accept the alert. But honestly I'm quite lost.

How can I tell capybara to use a new browser window for each @javascript test or automatically close the onbeforeunload alert?

Thanx

Body:
you can use page.driver.browser.switch_to.alert.dismiss (docs here) to get rid of the alert.

You could put this in a cucumber after hook

After "@javascript" do
  page.driver.browser.switch_to.alert.dismiss
  # or accept it if that is what you prefer
  page.driver.browser.switch_to.alert.accept
end

ContentLicense: CC BY-SA 3.0


问:
Do firestore batch writes get re-run automatically on failure?
While going through the official documentation I found out that transactions are automatically re-run a finite number of times by the SDK on failure, however in case of Batch Writes it is not explicitly mentioned.

The documentation does mention that batch writes are atomic just like transactions but that does not necessarily implies that they get re-run also on failure.

答:
Batch writes are not retried if there is a failure.  The entire thing is just rolled back, and you have to figure out for yourself if you want to retry.

Transactions are retried because they are explicitly trying to make a change based on the contents of existing document.  Since those documents could change between the round trip between the client and server, the retry is necessary to automatically handle that case, if it happens.  Batch writes don't have this problem, since they are atomic, but not really transactional in nature.


问:
AccessDenied for ListObjectsV2 operation for S3 bucket
During GitlabCi I got:
"fatal error: An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied"

My bucket policy :

```<code>{
"Version": "2008-10-17",
"Statement": [
    {
        "Sid": "AllowPublicRead",
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": "s3:*",
        "Resource": "arn:aws:s3:::BUCKET-NAME/*"
    }
]
</code>```

}

In gitlabCI settings set:

AWS_ACCESS_KEY_ID: YOUR-AWS-ACCESS-KEY-ID

AWS_SECRET_ACCESS_KEY: YOUR-AWS-SECRET-ACCESS-KEY

S3_BUCKET_NAME: YOUR-S3-BUCKET-NAME

DISTRIBUTION_ID: CLOUDFRONT-DISTRIBUTION-ID

My .gitlab-ci.yml

```<code>image: docker:latest

stages:
  - build
  - deploy

build:
  stage: build
  image: node:8.11.3
script:
  - export API_URL="d144iew37xsh40.cloudfront.net"
  - npm install
  - npm run build
  - echo "BUILD SUCCESSFULLY"
artifacts:
   paths:
    - public/
expire_in: 20 mins
environment:
name: production
only:
   - master
deploy:
  stage: deploy
  image: python:3.5
dependencies:
   - build
script:
  - export AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID
  - export AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY
  - export S3_BUCKET_NAME=$S3_BUCKET_NAME
  - export DISTRIBUTION_ID=$DISTRIBUTION_ID
  - pip install awscli --upgrade --user
  - export PATH=~/.local/bin:$PATH
  - aws s3 sync --acl public-read --delete public $S3_BUCKET_NAME
  - aws cloudfront create-invalidation --distribution-id
$DISTRIBUTION_ID --paths '/*'
  - echo "DEPLOYED SUCCESSFULLY"

environment:
   name: production
only:
  - master
</code>```

答:
Try to update your bucket policy to:

```<code>{
"Version": "version_id",
"Statement": [
    {
        "Sid": "AllowPublicRead",
        "Effect": "Allow",
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::BUCKET-NAME",
            "arn:aws:s3:::BUCKET-NAME/*"
        ]
    }
] }
</code>```

I hope you understand this is very insecure.

Body:
During GitlabCi I got:
"fatal error: An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied"

My bucket policy :

{
"Version": "2008-10-17",
"Statement": [
    {
        "Sid": "AllowPublicRead",
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": "s3:*",
        "Resource": "arn:aws:s3:::BUCKET-NAME/*"
    }
]

}

In gitlabCI settings set:

AWS_ACCESS_KEY_ID: YOUR-AWS-ACCESS-KEY-ID

AWS_SECRET_ACCESS_KEY: YOUR-AWS-SECRET-ACCESS-KEY

S3_BUCKET_NAME: YOUR-S3-BUCKET-NAME

DISTRIBUTION_ID: CLOUDFRONT-DISTRIBUTION-ID

My .gitlab-ci.yml

image: docker:latest

stages:
  - build
  - deploy

build:
  stage: build
  image: node:8.11.3
script:
  - export API_URL="d144iew37xsh40.cloudfront.net"
  - npm install
  - npm run build
  - echo "BUILD SUCCESSFULLY"
artifacts:
   paths:
    - public/
expire_in: 20 mins
environment:
name: production
only:
   - master
deploy:
  stage: deploy
  image: python:3.5
dependencies:
   - build
script:
  - export AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID
  - export AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY
  - export S3_BUCKET_NAME=$S3_BUCKET_NAME
  - export DISTRIBUTION_ID=$DISTRIBUTION_ID
  - pip install awscli --upgrade --user
  - export PATH=~/.local/bin:$PATH
  - aws s3 sync --acl public-read --delete public $S3_BUCKET_NAME
  - aws cloudfront create-invalidation --distribution-id
$DISTRIBUTION_ID --paths '/*'
  - echo "DEPLOYED SUCCESSFULLY"

environment:
   name: production
only:
  - master

Body:
Try to update your bucket policy to:

{
"Version": "version_id",
"Statement": [
    {
        "Sid": "AllowPublicRead",
        "Effect": "Allow",
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::BUCKET-NAME",
            "arn:aws:s3:::BUCKET-NAME/*"
        ]
    }
] }

I hope you understand this is very insecure.


问:
I could not cast initialViewController
I would like to instantiate a ViewController once after the launching of the app. So I instantiate the controller but than I get a weird error

Could not cast value of type 'erkeb.HomeVC' (0x100bd8738) to 'erkeb.ContainerVC' (0x100bd8990)

Can someone tell me how to resolve this issue please?

```<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    fileprivate var containerVC = ContainerVC()

    var MenuContainerVC: ContainerVC{
        return containerVC
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()

        containerVC = ContainerVC()

        window = UIWindow(frame: UIScreen.main.bounds)

        let sb = UIStoryboard(name: "Main", bundle: nil)
        var intialViewController = sb.instantiateViewController(withIdentifier: "WelkomVC")

        let userDefaults = UserDefaults.standard

        if userDefaults.bool(forKey: "WelkomIntroIsOk"){
            intialViewController = sb.instantiateInitialViewController() as! ContainerVC
        }

        window?.rootViewController = intialViewController
        window?.makeKeyAndVisible()

        //normaal juist onder lijn 28 maar menu schuift niet open
//        window?.rootViewController = containerVC
//        window?.makeKeyAndVisible()

        return true
    }
</code>```

答:
You don't need to cast sb.instantiateInitialViewController() as ContainerVC. If the UserDefaults value is true, create ContainerVC instance programmatically and assign in intialViewController. ContainerVC will be assigned as root view controller.

```<code>if userDefaults.bool(forKey: "WelkomIntroIsOk") {
    intialViewController = ContainerVC()
}
</code>```

Title: I could not cast initialViewController

Body:
I would like to instantiate a ViewController once after the launching of the app. So I instantiate the controller but than I get a weird error

Could not cast value of type 'erkeb.HomeVC' (0x100bd8738) to 'erkeb.ContainerVC' (0x100bd8990)

Can someone tell me how to resolve this issue please?

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    fileprivate var containerVC = ContainerVC()

    var MenuContainerVC: ContainerVC{
        return containerVC
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()

        containerVC = ContainerVC()

        window = UIWindow(frame: UIScreen.main.bounds)

        let sb = UIStoryboard(name: "Main", bundle: nil)
        var intialViewController = sb.instantiateViewController(withIdentifier: "WelkomVC")

        let userDefaults = UserDefaults.standard

        if userDefaults.bool(forKey: "WelkomIntroIsOk"){
            intialViewController = sb.instantiateInitialViewController() as! ContainerVC
        }

        window?.rootViewController = intialViewController
        window?.makeKeyAndVisible()

        //normaal juist onder lijn 28 maar menu schuift niet open
//        window?.rootViewController = containerVC
//        window?.makeKeyAndVisible()

        return true
    }

Body:
You don't need to cast sb.instantiateInitialViewController() as ContainerVC. If the UserDefaults value is true, create ContainerVC instance programmatically and assign in intialViewController. ContainerVC will be assigned as root view controller.

if userDefaults.bool(forKey: "WelkomIntroIsOk") {
    intialViewController = ContainerVC()
}


问:
Saving list data in python
I am wondering how I can save whatever I added to a list when I close a python file. For example, in this "my contact" program that I wrote below, if I add information about 'Jane Doe', what could I do so that next time I open up the same file, Jane Doe still exists.  </p>

```<code>def main():
    myBook = Book([{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}])
class Book:
    def __init__(self, peoples):
        self.peoples = peoples
        self.main_menu()
    def main_menu(self):
        print('Main Menu')
        print('1. Display Contact Names')
        print('2. Search For Contacts')
        print('3. Edit Contact')
        print('4. New Contact')
        print('5. Remove Contact')
        print('6. Exit')
        self.selection = input('Enter a # form the menu: ')
        if (self.selection == "1"):
            self.display_names()
        if (self.selection == "2"):
            self.search()
        if (self.selection == "3"):
            self.edit()
        if (self.selection == "4"):
            self.new()
        if (self.selection == "5"):
            self.delete()
        if (self.selection == "6"):
            self.end()
    def display_names(self):
        for people in self.peoples:
                print("Name: " + people["name"])
        self.main_menu()
    def search(self):
        searchname = input('What is the name of your contact: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                print("Name: " + self.peoples[index]["name"])
                print("Address: " + self.peoples[index]["address"])
                print("Phone: " + self.peoples[index]["phone"])
        self.main_menu()
    def edit(self):
        searchname = input('What is the name of the contact that you want to edit: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)
                name = input('What is your name: ')
                address = input('What is your address: ')
                phone = input('What is your phone number: ')
                self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def new(self):
        name = input('What is your name: ')
        address = input('What is your address: ')
        phone = input('What is your phone number: ')
        self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def delete(self):
        searchname = input('What is the name of the contact that you want to delete: ')
        for index in reversed(range(len(self.peoples))):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)

            print(searchname, 'has been removed')
        self.main_menu()
    def end(self):
        print('Thank you for using the contact book, have a nice day')
        print('Copyright Carson147 2019©, All Rights Reserved')

main()
</code>```

答:
You just convert your list to array inside in function .

```<code>np.save('path/to/save', np.array(your_list))
</code>```

to load :

```<code>arr=np.load(''path/to/save.npy').tolist()
</code>```

I hope it will be helpful

Title: Saving list data in python

Body:
I am wondering how I can save whatever I added to a list when I close a python file. For example, in this "my contact" program that I wrote below, if I add information about 'Jane Doe', what could I do so that next time I open up the same file, Jane Doe still exists.

def main():
    myBook = Book([{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}])
class Book:
    def __init__(self, peoples):
        self.peoples = peoples
        self.main_menu()
    def main_menu(self):
        print('Main Menu')
        print('1. Display Contact Names')
        print('2. Search For Contacts')
        print('3. Edit Contact')
        print('4. New Contact')
        print('5. Remove Contact')
        print('6. Exit')
        self.selection = input('Enter a # form the menu: ')
        if (self.selection == "1"):
            self.display_names()
        if (self.selection == "2"):
            self.search()
        if (self.selection == "3"):
            self.edit()
        if (self.selection == "4"):
            self.new()
        if (self.selection == "5"):
            self.delete()
        if (self.selection == "6"):
            self.end()
    def display_names(self):
        for people in self.peoples:
                print("Name: " + people["name"])
        self.main_menu()
    def search(self):
        searchname = input('What is the name of your contact: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                print("Name: " + self.peoples[index]["name"])
                print("Address: " + self.peoples[index]["address"])
                print("Phone: " + self.peoples[index]["phone"])
        self.main_menu()
    def edit(self):
        searchname = input('What is the name of the contact that you want to edit: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)
                name = input('What is your name: ')
                address = input('What is your address: ')
                phone = input('What is your phone number: ')
                self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def new(self):
        name = input('What is your name: ')
        address = input('What is your address: ')
        phone = input('What is your phone number: ')
        self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def delete(self):
        searchname = input('What is the name of the contact that you want to delete: ')
        for index in reversed(range(len(self.peoples))):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)

            print(searchname, 'has been removed')
        self.main_menu()
    def end(self):
        print('Thank you for using the contact book, have a nice day')
        print('Copyright Carson147 2019©, All Rights Reserved')

main()

Body:
You just convert your list to array inside in function .

np.save('path/to/save', np.array(your_list))

to load :

arr=np.load(''path/to/save.npy').tolist()

I hope it will be helpful


问:
401. That’s an error. Error: invalid_client The OAuth client was not found
I am working with Google Drive File Picker by following this Google Drive File Picker Example demo project. I have generated API Key and Client Id. But when I run the project I am getting following error

That’s an error.

Error: invalid_client

The OAuth client was not found.

I have also checked This Google Drive File Picker Example Link but it does not work, Please help me to solve my issue.

invalid_client in google oauth2.

答: Your client_id is not correct, re-check pls


问:
Ember JS : How to reuse ember data while calling?
I have two models to call. In the first model I include somedate like this.

```<code>this.store.query('comment',{
   include : 'person,address'
});
</code>```

And in the second call I include the same details that already stored in the store.

```<code>this.store.query('post',{
   include : 'person,address'
});
</code>```

So, the API call takes a lot of time to resolve. Is there any way I can use the first API include data in the second API call to create a relationship between those two models(person, address).
This would save a lot of time for me.

Note: Examples are testing purpose only.

答:
You are using the query() method of Ember Data's store. It expects two arguments: the model name as first argument and the query as a second argument. Last one is directly passed to your backend as part of the request. The responsible code is quite simple: https://github.com/emberjs/data/blob/v3.10.0/addon/adapters/rest.js#L535-L560

If you are using default JSONAPIAdapter the requests executed by your method calls look like this:

```<code>this.store.query('comment', { include: 'person,address' });
=> GET /comments?include=person,address

this.store.query('post', { include: 'person,address' });
=> GET /posts?include=person,address
</code>```

The API does not know from that request that the client already has some of the person and address records cached locally. Ember Data does not include that information by default. You could customize your Adapter two do it but I wouldn't recommend so - especially cause that may blow up the request size and reduce the cache hit rate by a fair amount. Also you may want to reload the locally cached records.

If you expect two have most of the related records already cached locally, you may simply not want to ask the server to include them? In that case it might be cheaper to load them afterwards in a coalesced request.

Body:
I have two models to call. In the first model I include somedate like this.

this.store.query('comment',{
   include : 'person,address'
});

And in the second call I include the same details that already stored in the store.

this.store.query('post',{
   include : 'person,address'
});

So, the API call takes a lot of time to resolve. Is there any way I can use the first API include data in the second API call to create a relationship between those two models(person, address).
This would save a lot of time for me.

Note: Examples are testing purpose only.

Body:
You are using the query() method of Ember Data's store. It expects two arguments: the model name as first argument and the query as a second argument. Last one is directly passed to your backend as part of the request. The responsible code is quite simple: https://github.com/emberjs/data/blob/v3.10.0/addon/adapters/rest.js#L535-L560

If you are using default JSONAPIAdapter the requests executed by your method calls look like this:

this.store.query('comment', { include: 'person,address' });
=> GET /comments?include=person,address

this.store.query('post', { include: 'person,address' });
=> GET /posts?include=person,address

The API does not know from that request that the client already has some of the person and address records cached locally. Ember Data does not include that information by default. You could customize your Adapter two do it but I wouldn't recommend so - especially cause that may blow up the request size and reduce the cache hit rate by a fair amount. Also you may want to reload the locally cached records.

If you expect two have most of the related records already cached locally, you may simply not want to ask the server to include them? In that case it might be cheaper to load them afterwards in a coalesced request.


问:
Java 8 application on EC2
I was wondering if anyone knows if it will be possible for me to install Java 8 on an EC2 instance. My application is packed as a fat jar with embedded jetty, so the Java 8 runtime alone should be sufficient.

I'm not too familiar with Linux, and I saw that they only had Java 7 support on the default AMI. Is there a simple command I can run to update to Java 8?

答:
Donwload Linux version of JRE from below link to your windows machine as it has browser. Note that if you are using this EC2 instance as server you just need JRE and not complete JDK.
https://www.oracle.com/technetwork/java/javase/downloads/server-jre8-downloads-2133154.html

Tranfer downloaded .tar.gz file using winscp to your EC2 instance.

Run "tar zxvf jre-8uversion-linux-i586.tar.gz" on your EC2 instance.  For more info https://docs.oracle.com/javase/8/docs/technotes/guides/install/linux_jre.html#CFHBHAGI

Title: Java 8 application on EC2


答:
I would use apply with with a custom function return a series from pd.date_range

```<code>def create_range(x):
    s = pd.Series(pd.date_range(start=x['start date'], end=x['end date'])).dt.strftime('%m/%d/%Y')
    return s
</code>```

Using the custom function above to apply, stack, reset_index and join with df

```<code>df[['start date', 'end date']].apply(create_range, axis=1).stack().reset_index(level=-1, drop=True).to_frame('date').join(df)

Out[1742]:
         date  col1   end date start date
0  01/03/2019     1   1/5/2019   1/3/2019
0  01/04/2019     1   1/5/2019   1/3/2019
0  01/05/2019     1   1/5/2019   1/3/2019
1  01/10/2019     2  1/12/2019  1/10/2019
1  01/11/2019     2  1/12/2019  1/10/2019
1  01/12/2019     2  1/12/2019  1/10/2019
</code>```

Title: How can I melt the dataframe getting all dates between a range?

Body:
I have a dataset like this:

    import pandas as pd
    pd.DataFrame({'col1': [1, 2], 'start date': ['1/3/2019', '1/10/2019'],
                                  'end date':['1/5/2019','1/12/2019']} )

I want to get a row for each of the values between Start Date and End Date.

    pd.DataFrame({'col1': [1,1,1,2,2,2],
                  'date': ['1/3/2019','1/4/2019','1/5/2019',
                           '1/10/2019', '1/11/2019', '1/12/2019'],

                  'start date': ['1/3/2019', '1/3/2019', '1/3/2019',
                           '1/10/2019', '1/10/2019', '1/10/2019'],

                  'end date':['1/5/2019','1/5/2019','1/5/2019',
                           '1/12/2019','1/12/2019','1/12/2019']} )

Edit: Range overlap is allowed.

I am trying to use melt but I can't get what I want.

Body:
I would use apply with with a custom function return a series from pd.date_range

def create_range(x):
    s = pd.Series(pd.date_range(start=x['start date'], end=x['end date'])).dt.strftime('%m/%d/%Y')
    return s

Using the custom function above to apply, stack, reset_index and join with df

df[['start date', 'end date']].apply(create_range, axis=1).stack().reset_index(level=-1, drop=True).to_frame('date').join(df)

Out[1742]:
         date  col1   end date start date
0  01/03/2019     1   1/5/2019   1/3/2019
0  01/04/2019     1   1/5/2019   1/3/2019
0  01/05/2019     1   1/5/2019   1/3/2019
1  01/10/2019     2  1/12/2019  1/10/2019
1  01/11/2019     2  1/12/2019  1/10/2019
1  01/12/2019     2  1/12/2019  1/10/2019


问:
Bash script behaves unexpected / Strange
First I want to apologize for being an absolute noob at programming, writing scripts, etc.
I'm running a FreeNAS Server and a Raspberry Pi which I'd like to include a sh-Script which should check if 8 clients (IP addresses) are online. If yes they should stop but if all IP's are offline, it should perform another task / script.

Here's my problem: On the internet (src: https://www.tech-blogger.net/freenas-automatisch-bei-nicht-benutzung-abschalten/) I found a script which checks specific IP's and if they're offline it should shutdown automatically. When I ping those addresses I get 100% package lost which indicates that they are offline. But the script echos me that at least one client is offline. Because I'm not THAT dumb I assume that it has something to do with my code. Does anyone know what goes wrong with my Script?:

```<code>HOST1=192.168.1.32
HOST2=192.168.1.33
HOST3=192.168.1.34
HOST4=192.168.1.35
HOST5=192.168.1.36

_exit () {
case $1 in
1) echo „No Shutdown – At least one PC is online“ ;;
2) echo „No PC is online – Shutdown“ ; shutdown -p now ;;
esac
exit $1;
}

#Check if IPs are online
if [ `ping -c 1 -i 1 $HOST1 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST2 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST3 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST4 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST5 | grep -wc 100.0%` -eq 0 ] ; then _exit 1;

#All Clients are offline, shutdown
else
_exit 2
fi
fi
</code>```

答:
As William Pursell said in a comment, when ping doesn't reach the requested IP, it returns a non-zero exit code indicating failure. The if statement in shells like Bash can use that exit code directly without having to use bracketed conditional expressions.

I would recommend a loop instead of a long conditional. This will be easier to read and maintain and scales more readily if the number of hosts change.

# create an array of IPs
host_ips=(
    192.168.1.32
    192.168.1.33
    192.168.1.34
    192.168.1.35
    192.168.1.36
)

for ip in "${host_ips[@]}"
do
    if ping -c 1 -i 1 "$ip"
    then
        _exit 1
        # no need to break since _exit doesn't return
    fi
done
# if we made it this far, none are online
_exit 2
```

Body:
First I want to apologize for being an absolute noob at programming, writing scripts, etc.
I'm running a FreeNAS Server and a Raspberry Pi which I'd like to include a sh-Script which should check if 8 clients (IP addresses) are online. If yes they should stop but if all IP's are offline, it should perform another task / script.

Here's my problem: On the internet (src: https://www.tech-blogger.net/freenas-automatisch-bei-nicht-benutzung-abschalten/) I found a script which checks specific IP's and if they're offline it should shutdown automatically. When I ping those addresses I get 100% package lost which indicates that they are offline. But the script echos me that at least one client is offline. Because I'm not THAT dumb I assume that it has something to do with my code. Does anyone know what goes wrong with my Script?:

HOST1=192.168.1.32
HOST2=192.168.1.33
HOST3=192.168.1.34
HOST4=192.168.1.35
HOST5=192.168.1.36

_exit () {
case $1 in
1) echo „No Shutdown – At least one PC is online“ ;;
2) echo „No PC is online – Shutdown“ ; shutdown -p now ;;
esac
exit $1;
}

#Check if IPs are online
if [ `ping -c 1 -i 1 $HOST1 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST2 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST3 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST4 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST5 | grep -wc 100.0%` -eq 0 ] ; then _exit 1;

#All Clients are offline, shutdown
else
_exit 2
fi
fi


问:
Split worksheet in multiple workbooks based on unique values in range
It's been asked before but I haven't found a solution for unique values, I'm trying to split a large worksheet into workbooks based on the unique supervisors of T column, which contains the one in charge (one to many relationship / multiple employees for a supervisor).

My code currently scans the T column and runs the second code block to store and paste the rows associated to this person, the problem is that the loops runs for each row, no matter if the supervisor repeats itself 1000+ times, meaning that for each supervisor the file it's created n times.

```<code>emp       sup
-------------------
john doe  jane q public 'specific file for this supervisor
clint     jane q public 'it should be in the same file as the prev record
jenny doe jonny cage 'in separate file
</code>```

Here's my code based on multiple answers on SO:

```<code>Option Explicit
'Split resp data into separate columns based on the names defined in
'a RESP on the FIRST sheet.
Sub splitRespVP()
    Dim wb As Workbook
    Dim p As Range

    'Application.ScreenUpdating = False

    Application.DisplayAlerts = False
    Application.EnableEvents = False

    For Each p In Sheets(1).Range("T2:T2201")
        Workbooks.Add
        Set wb = ActiveWorkbook
        ThisWorkbook.Activate

        WritePersonToWorkbook wb, p.Value

        wb.SaveAs ThisWorkbook.Path & "\sdoRespVP_" & p.Value
        wb.Close
    Next p
    'Application.ScreenUpdating = True
    Set wb = Nothing

    Application.DisplayAlerts = True
    Application.EnableEvents = True

End Sub
</code>```

Second code loop, where the file it's recreated multiple times for each duplicated supervisor:

```<code>'Writes all the sales data rows belonging to a Person
'to the first sheet in the named respWB.
Sub WritePersonToWorkbook(ByVal respWB As Workbook, _
                          ByVal Person As String)
    Dim rw As Range
    Dim personRows As Range     'Stores all of the rows found
    Dim firstRW As Range        'containing Person in column 1
    For Each rw In UsedRange.Rows
        If Person = rw.Cells(2, 20) Then
            If personRows Is Nothing Then
                Set personRows = rw
                'Set personRows = Union(personRows, rw)
            Else
                Set personRows = Union(personRows, rw)
            End If
        End If
    Next rw

    personRows.Copy respWB.Sheets(1).Cells(1, 1) ' ACA ESTÀ EL ERROR
    Set personRows = Nothing
End Sub
</code>```

I'm looking to avoid looping each row and work on unique values.

答:
Used a dictionary and using each unique value I iterate the code and so far it worked fast:</p>

```<code>Option Explicit
'Split resp data into separate columns baed on the names defined in
'a RESP on the FIRST sheet.
Sub splitRespVP()
    Dim wb As Workbook
    Dim p As Range

    Application.ScreenUpdating = False

    '''''''''''
    Dim key As Variant
    Dim d As Object, i As Long, lr As Long
    Set d = CreateObject("Scripting.Dictionary")
    lr = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 2 To lr
      d.Item(Range("T" & i).Value) = 1
    Next i
    '''''''''''

    Application.DisplayAlerts = False
    Application.EnableEvents = False

    For Each key In d.Keys()
        Workbooks.Add
        Set wb = ActiveWorkbook
        ThisWorkbook.Activate

        WritePersonToWorkbook wb, key 'd.Item

        wb.SaveAs ThisWorkbook.Path & "\sdoRespVP_" & key
        wb.Close
    Next key
    Application.ScreenUpdating = True
    Set wb = Nothing

    Application.DisplayAlerts = True
    Application.EnableEvents = True

End Sub

'Writes all the sales data rows belonging to a Person
'to the first sheet in the named respWB.
Sub WritePersonToWorkbook(ByVal respWB As Workbook, _
                          ByVal Person As String)
    Dim rw As Range
    Dim personRows As Range     'Stores all of the rows found
    Dim firstRW As Range        'containing Person in column 1
    For Each rw In UsedRange.Rows
        If Person = rw.Cells(2, 20) Then
            If personRows Is Nothing Then
                Set personRows = rw
                'Set personRows = Union(personRows, rw)
            Else
                Set personRows = Union(personRows, rw)
            End If
        End If
    Next rw

    personRows.Copy respWB.Sheets(1).Cells(1, 1) ' ACA ESTÀ EL ERROR
    Set personRows = Nothing
End Sub
</code>```

Body:
It's been asked before but I haven't found a solution for unique values, I'm trying to split a large worksheet into workbooks based on the unique supervisors of T column, which contains the one in charge (one to many relationship / multiple employees for a supervisor).

My code currently scans the T column and runs the second code block to store and paste the rows associated to this person, the problem is that the loops runs for each row, no matter if the supervisor repeats itself 1000+ times, meaning that for each supervisor the file it's created n times.

emp       sup
-------------------
john doe  jane q public 'specific file for this supervisor
clint     jane q public 'it should be in the same file as the prev record
jenny doe jonny cage 'in separate file

Here's my code based on multiple answers on SO:

Option Explicit
'Split resp data into separate columns based on the names defined in
'a RESP on the FIRST sheet.
Sub splitRespVP()
    Dim wb As Workbook
    Dim p As Range

    'Application.ScreenUpdating = False

    Application.DisplayAlerts = False
    Application.EnableEvents = False

    For Each p In Sheets(1).Range("T2:T2201")
        Workbooks.Add
        Set wb = ActiveWorkbook
        ThisWorkbook.Activate

        WritePersonToWorkbook wb, p.Value

        wb.SaveAs ThisWorkbook.Path & "\sdoRespVP_" & p.Value
        wb.Close
    Next p
    'Application.ScreenUpdating = True
    Set wb = Nothing

    Application.DisplayAlerts = True
    Application.EnableEvents = True

End Sub

Second code loop, where the file it's recreated multiple times for each duplicated supervisor:

'Writes all the sales data rows belonging to a Person
'to the first sheet in the named respWB.
Sub WritePersonToWorkbook(ByVal respWB As Workbook, _
                          ByVal Person As String)
    Dim rw As Range
    Dim personRows As Range     'Stores all of the rows found
    Dim firstRW As Range        'containing Person in column 1
    For Each rw In UsedRange.Rows
        If Person = rw.Cells(2, 20) Then
            If personRows Is Nothing Then
                Set personRows = rw
                'Set personRows = Union(personRows, rw)
            Else
                Set personRows = Union(personRows, rw)
            End If
        End If
    Next rw

    personRows.Copy respWB.Sheets(1).Cells(1, 1) ' ACA ESTÀ EL ERROR
    Set personRows = Nothing
End Sub

I'm looking to avoid looping each row and work on unique values.

Body:
Used a dictionary and using each unique value I iterate the code and so far it worked fast:

Option Explicit
'Split resp data into separate columns baed on the names defined in
'a RESP on the FIRST sheet.
Sub splitRespVP()
    Dim wb As Workbook
    Dim p As Range

    Application.ScreenUpdating = False

    '''''''''''
    Dim key As Variant
    Dim d As Object, i As Long, lr As Long
    Set d = CreateObject("Scripting.Dictionary")
    lr = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 2 To lr
      d.Item(Range("T" & i).Value) = 1
    Next i
    '''''''''''

    Application.DisplayAlerts = False
    Application.EnableEvents = False

    For Each key In d.Keys()
        Workbooks.Add
        Set wb = ActiveWorkbook
        ThisWorkbook.Activate

        WritePersonToWorkbook wb, key 'd.Item

        wb.SaveAs ThisWorkbook.Path & "\sdoRespVP_" & key
        wb.Close
    Next key
    Application.ScreenUpdating = True
    Set wb = Nothing

    Application.DisplayAlerts = True
    Application.EnableEvents = True

End Sub

'Writes all the sales data rows belonging to a Person
'to the first sheet in the named respWB.
Sub WritePersonToWorkbook(ByVal respWB As Workbook, _
                          ByVal Person As String)
    Dim rw As Range
    Dim personRows As Range     'Stores all of the rows found
    Dim firstRW As Range        'containing Person in column 1
    For Each rw In UsedRange.Rows
        If Person = rw.Cells(2, 20) Then
            If personRows Is Nothing Then
                Set personRows = rw
                'Set personRows = Union(personRows, rw)
            Else
                Set personRows = Union(personRows, rw)
            End If
        End If
    Next rw

    personRows.Copy respWB.Sheets(1).Cells(1, 1) ' ACA ESTÀ EL ERROR
    Set personRows = Nothing
End Sub


问:
Can Someone Explain How the ball went forward from the camera?

private void Update()
{
    Ball.transform.position = PlayerCamera.transform.position +
                              PlayerCamera.transform.forward * DistanceBall;
}
```

答:
You should have a look at some basic API pages like Update, Transform, Transform.position and Transform.forawrd.

For the calculation itself a look at Vector3 * operator would also be helpful.

// This method is automatically called by Unity every frame
private void Update()
{
    Ball.transform.position =
        // This is the PlayerCamera's position
        PlayerCamera.transform.position
        // This is the PlayerCamera's forward vector with magnitude 1
        // so this would move the ball 1 Unity Unit in front of the camera
        + PlayerCamera.transform.forward
        // This finally moves the desired distance in front of the camera instead of 1 Unit
        * DistanceBall;
}
```

The transform.forward is a Vector3 that always points in the positive local Z axis. It is the local forward vector but returned in World space coordinates.

I general I would actually always recommend to use LateUpdate isntead if the camera is moved by any user input. This way you can handle all user input in Update and make the moving of the ball rather the latest step before rendering.

In general I would recommend to go through some basic Unity Tutorials like e.g. Update and FixedUpdate and Vector Maths before touching code ;)

Body:
You should have a look at some basic API pages like Update, Transform, Transform.position and Transform.forawrd.

For the calculation itself a look at Vector3 * operator would also be helpful.

// This method is automatically called by Unity every frame
private void Update()
{
    Ball.transform.position =
        // This is the PlayerCamera's position
        PlayerCamera.transform.position
        // This is the PlayerCamera's forward vector with magnitude 1
        // so this would move the ball 1 Unity Unit in front of the camera
        + PlayerCamera.transform.forward
        // This finally moves the desired distance in front of the camera instead of 1 Unit
        * DistanceBall;
}

The transform.forward is a Vector3 that always points in the positive local Z axis. It is the local forward vector but returned in World space coordinates.

I general I would actually always recommend to use LateUpdate isntead if the camera is moved by any user input. This way you can handle all user input in Update and make the moving of the ball rather the latest step before rendering.

In general I would recommend to go through some basic Unity Tutorials like e.g. Update and FixedUpdate and Vector Maths before touching code ;)


问:
Is there an implicit default constructor in C++?
In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?</p>

答:
The default constructor created for a class will not initialize built-in types, but it will call the default constructor on all user-defined members:</p>

```<code>class Foo
{
public:
     int x;
     Foo() : x(1) {}
};

class Bar
{
public:
     int y;
     Foo f;
     Foo *fp;
};

int main()
{

    Bar b1;
    ASSERT(b1.f.x == 1);
    // We know nothing about what b1.y is set to, or what b1.fp is set to.

    // The class members' initialization parallels normal stack initialization.
    int y;
    Foo f;
    Foo *fp;
    ASSERT(f.x == 1);
    // We know nothing about what y is set to, or what fp is set to.

}
</code>```

OwnerDisplayName: Skilldrick

Body:
The default constructor created for a class will not initialize built-in types, but it will call the default constructor on all user-defined members:

class Foo
{
public:
     int x;
     Foo() : x(1) {}
};

class Bar
{
public:
     int y;
     Foo f;
     Foo *fp;
};

int main()
{

    Bar b1;
    ASSERT(b1.f.x == 1);
    // We know nothing about what b1.y is set to, or what b1.fp is set to.

    // The class members' initialization parallels normal stack initialization.
    int y;
    Foo f;
    Foo *fp;
    ASSERT(f.x == 1);
    // We know nothing about what y is set to, or what fp is set to.

}

OwnerDisplayName: Josh

LastEditorDisplayName: Josh


问:
Complex data-driven web application in Java - Decision on technologies
Dear Stack Overflow Community,

I am a Java programmer in front of a task of building a complex, data-driven, web application (SaaS) and I'm searching for technologies to use. I have already made some decisions and I believe I'm proficient enough to build the appliaction using just the technologies I have decided for (I'm definitely not saying it would be perfect, just that it would be working). However, I'd like to make my task easier and that's why I need your help.

Brief description of the project

Back-end

The application will be heavily data-driven, meaning that everything will be stored in a self-descripting database. This means the database itself will be entirely described with metadata and the application will not know what data it reads and writes. There won't probably be any regular entities (in terms of JPA @Entity) because the application won't know the structure of the data; it will obtain it from the metadata. Only the metadata will have a pre-determined structure. To put it simply, the metadata is the alpha-omega of the application because it will tell the application WHEN and WHAT to display and HOW to display it.

The application will probably utilize stored procedures to perform some low-level tasks on the data, such as automatical auditing, logging and translating to user's language, thus most likely eliminating any possibility to use ORM frameworks because there won't be just simple CRUD operations. Therefore, JDBC seems like my only option (doesn't it?).

Front-end

The UI will be "dumb" in terms that it will not know what data it is displaying (to some extent, of course). It will just know how to display it based on the metadata which it will obtain from the database. All UI controls (like menu items, buttons, etc) will be created based on current application's state and the UI will NOT know what the controls do. This means that clicking a menu item or a button will just send an identifier of associated action to the back-end and the server will decide what to do.

My goals

My main goal is to have the application as lightweight as possible with as least dependencies as possible. Because the application will be very complex, I'd like to avoid any heavy framework(s) because there is a very high probability that I'd need to customize a lot of its functionality.

What I have already decided for

Please object to the following decisions only if you think they're absolutely non-viable for my application, as I have already implemented some core functionality using these technologies:

Servlets on Tomcat, Guice DI, AOP (AspectJ)

I believe all of these technologies are lightweight enough and I don't need to learn J2EE.

GWT with GIN-jection on the front-end

Seems like the best option for me because I'm very familiar with Java and Swing and don't want to write any Javascript, PHP or learn a new language. GIN is a little brother of Guice and I will be using the same syntax and principles on both the client and server.

MSSQL RDBMS

This is actually a requirement from company management as I'd much rather like to go with an open-source solution. Too bad for me..

Maven 2

I think no-one can object to this :)

What I need help with

DB communication

I think that ORM is ruled out (is it?) so I need to use JDBC. Do you think Spring JDBC is lightweight and flexible enough for my use? I would often need to "blindly" read data from database, mapping it to some generic entity (because I won't assume any pre-determined structure), and then send the data using some generic DTO to the client along with the metadata telling it what data it is and how to display it. Or do you know any alternatives? Or should I do this myself?

Client/Server communication

GWT and its GWT-RPC mechanism seems not very suited for sending the generic data I need. Although I'm convinced that it's doable using GWT-RPC, are there any alternatives? But I definitely want to use GWT.

Security

Do you know any security libraries / frameworks that would help me? I'm aware of the existence of Spring-security; do you think it's flexible enough for my use or I'd be better off implementing that myself? Also, is Spring's IoC an integral part of the Spring framework, or would I be able to continue to use Guice?

Anything else that you think might be useful?

I really appreciate any advice and suggestions because I wouldn't dare to try to make such decisions myself. Please ask me if you need more information.

Thank you in advance!
eQui

答:
I think you are over-engineering the solution. Take a look at

http://thedailywtf.com/Articles/Programming-Sucks!-Or-At-Least,-It-Ought-To-.aspx

If everything is driven by the DB, you are going to have immense difficulty making things happen in the UI, and you aren't going to be able to use many of the tools that make UI development easier.

I also suggest you take a look at Spring Roo, if your application is mainly just updating data in a database.


问:
How to transform a DataFrame into a dictionary taking just the mapped values?
I need to reset some values in a DataFrame of objects

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})

def test(ar):
    if ar == ['']:
        return False
    else:
        return True

df.applymap(test)
</code>```

The applymap returns this:

I just need to take the columns and cells with True into a structure like the following:

```<code>d = {
    'x': [(0, [''])],
    'y': [(0, ['']), (1, ['']),]
    'z': [(0, ['']), (1, ['']),]
}
</code>```

Which is the fastest method to achieve this? There has to be a simple way to solve it.

答:
I'm not sure how effective this is, but you can try:

```<code>new_df = df.applymap(test).stack()

# replace True with the empty string
new_df = new_df[new_df].replace({True:''}).reset_index(level=0)

# get the tuples
s = new_df.apply(lambda x: tuple(x), axis=1)

# group the tuples by (original) column names and return dict
d = s.groupby(s.index).apply(lambda x: x.tolist()).to_dict()
</code>```

Output:

```<code>{'x': [(0, '')], 'y': [(0, ''), (1, '')], 'z': [(0, ''), (1, '')]}
</code>```

Optimized algorythm by the asker. The replacement step is not needed if I return the right object in the applymap directly

```<code>df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'q': [[''], ['']],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})
new_df = df.applymap(lambda x: None if x == [''] else [''])
new_df = new_df.stack().reset_index(level=0)
s = new_df.apply(lambda x: tuple(x), axis=1)
d = s.groupby(s.index).apply(lambda x: x.tolist()).to_dict()
d
</code>```

Body:
I need to reset some values in a DataFrame of objects

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})

def test(ar):
    if ar == ['']:
        return False
    else:
        return True

df.applymap(test)

The applymap returns this:

I just need to take the columns and cells with True into a structure like the following:

d = {
    'x': [(0, [''])],
    'y': [(0, ['']), (1, ['']),]
    'z': [(0, ['']), (1, ['']),]
}

Which is the fastest method to achieve this? There has to be a simple way to solve it.

Body:
I'm not sure how effective this is, but you can try:

new_df = df.applymap(test).stack()

# replace True with the empty string
new_df = new_df[new_df].replace({True:''}).reset_index(level=0)

# get the tuples
s = new_df.apply(lambda x: tuple(x), axis=1)

# group the tuples by (original) column names and return dict
d = s.groupby(s.index).apply(lambda x: x.tolist()).to_dict()

Output:

{'x': [(0, '')], 'y': [(0, ''), (1, '')], 'z': [(0, ''), (1, '')]}

Optimized algorythm by the asker. The replacement step is not needed if I return the right object in the applymap directly

df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'q': [[''], ['']],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})
new_df = df.applymap(lambda x: None if x == [''] else [''])
new_df = new_df.stack().reset_index(level=0)
s = new_df.apply(lambda x: tuple(x), axis=1)
d = s.groupby(s.index).apply(lambda x: x.tolist()).to_dict()
d


问:
How to get the io_context from a strand in Boost 1.68?
I have a boost::asio::strand<boost::asio::io_context::executor_type> object and need to get its io_context. I thought that I could use get_io_context() but that has been deprecated. Then I thought that I could use context() but that one returns a boost::asio::execution_context.

I cannot see how I can convert this into an instance of io_context instead...

So, how can I get a strand's io_context in boost 1.68?

答:
Call get_inner_executor on strand instance then context on executor:

```<code>#include <boost/asio.hpp>
int main() {
    boost::asio::io_context io;
    boost::asio::strand<boost::asio::io_context::executor_type> strand{io.get_executor()};

    boost::asio::io_context::executor_type executor = strand.get_inner_executor();
    boost::asio::io_context& refIO = executor.context();
}
</code>```

Body:
Call get_inner_executor on strand instance then context on executor:

#include <boost/asio.hpp>
int main() {
    boost::asio::io_context io;
    boost::asio::strand<boost::asio::io_context::executor_type> strand{io.get_executor()};

    boost::asio::io_context::executor_type executor = strand.get_inner_executor();
    boost::asio::io_context& refIO = executor.context();
}


问:
TypeError: str.trim is not a function (Request-Promise/Tough-Cookie)
I am having similar problem as discussed here:
https://github.com/request/request-promise/issues/183

I am using Request-Promise@4.2.2 and Tough-Cookie@2.3.4

And getting the same error:

TypeError: str.trim is not a function

I also played around with npm-dedupe

Any clue,

My code looks like this:

```<code>let cookie = new tough.Cookie({domain: '.companyName.ninja',
  httpOnly: true,
  name: '_application_session',
  path: '/',
  secure: false,
  value: 'f044888d39e2d19126716d9f54028700' })
let cookieJar = request.jar()
cookieJar.setCookie(cookie, 'http://application.companyName.ninja/')
options.jar = cookieJar
</code>```

答:
Change line

```<code>cookieJar.setCookie(cookie, 'http://application.companyName.ninja/')
</code>```

to

```<code>cookieJar.setCookie(cookie.toString(), 'http://application.companyName.ninja/')
</code>```

(use toString() method).

Body:
I am having similar problem as discussed here:
https://github.com/request/request-promise/issues/183

I am using Request-Promise@4.2.2 and Tough-Cookie@2.3.4

And getting the same error:

TypeError: str.trim is not a function

I also played around with npm-dedupe

Any clue,

My code looks like this:

let cookie = new tough.Cookie({domain: '.companyName.ninja',
  httpOnly: true,
  name: '_application_session',
  path: '/',
  secure: false,
  value: 'f044888d39e2d19126716d9f54028700' })
let cookieJar = request.jar()
cookieJar.setCookie(cookie, 'http://application.companyName.ninja/')
options.jar = cookieJar

Body:
Change line

cookieJar.setCookie(cookie, 'http://application.companyName.ninja/')

to

cookieJar.setCookie(cookie.toString(), 'http://application.companyName.ninja/')

(use toString() method).