问:
run HelloAndroid from gradle?
There are an overwhelming number and variety of gradle tasks:

```<code>thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ gradle clean run

FAILURE: Build failed with an exception.

* What went wrong:
Task 'run' not found in root project 'HelloAndroid'.

* Try:
Run gradle tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 0s
thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ gradle tasks --all

> Task :tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Android tasks
-------------
app:androidDependencies - Displays the Android dependencies of the project.
app:signingReport - Displays the signing info for each variant.
app:sourceSets - Prints out all the source sets defined in this project.

Build tasks
-----------
app:assemble - Assembles all variants of all applications and secondary packages.
app:assembleAndroidTest - Assembles all the Test applications.
app:assembleDebug - Assembles all Debug builds.
app:assembleRelease - Assembles all Release builds.
app:build - Assembles and tests this project.
app:buildDependents - Assembles and tests this project and all projects that depend on it.
app:buildNeeded - Assembles and tests this project and all projects it depends on.
app:clean - Deletes the build directory.
app:cleanBuildCache - Deletes the build cache directory.
app:compileDebugAndroidTestSources
app:compileDebugSources
app:compileDebugUnitTestSources
app:compileReleaseSources
app:compileReleaseUnitTestSources
app:mockableAndroidJar - Creates a version of android.jar that's suitable for unit tests.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'HelloAndroid'.
app:buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
components - Displays the components produced by root project 'HelloAndroid'. [incubating]
app:components - Displays the components produced by project ':app'. [incubating]
dependencies - Displays all dependencies declared in root project 'HelloAndroid'.
app:dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in root project 'HelloAndroid'.
app:dependencyInsight - Displays the insight into a specific dependency in project ':app'.
dependentComponents - Displays the dependent components of components in root project 'HelloAndroid'. [incubating]
app:dependentComponents - Displays the dependent components of components in project ':app'. [incubating]
help - Displays a help message.
app:help - Displays a help message.
model - Displays the configuration model of root project 'HelloAndroid'. [incubating]
app:model - Displays the configuration model of project ':app'. [incubating]
projects - Displays the sub-projects of root project 'HelloAndroid'.
app:projects - Displays the sub-projects of project ':app'.
properties - Displays the properties of root project 'HelloAndroid'.
app:properties - Displays the properties of project ':app'.
tasks - Displays the tasks runnable from root project 'HelloAndroid' (some of the displayed tasks may belong to subprojects).
app:tasks - Displays the tasks runnable from project ':app'.

Install tasks
-------------
app:installDebug - Installs the Debug build.
app:installDebugAndroidTest - Installs the android (on device) tests for the Debug build.
app:uninstallAll - Uninstall all applications.
app:uninstallDebug - Uninstalls the Debug build.
app:uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Debug build.
app:uninstallRelease - Uninstalls the Release build.

Verification tasks
------------------
app:check - Runs all checks.
app:connectedAndroidTest - Installs and runs instrumentation tests for all flavors on connected devices.
app:connectedCheck - Runs all device checks on currently connected devices.
app:connectedDebugAndroidTest - Installs and runs the tests for debug on connected devices.
app:deviceAndroidTest - Installs and runs instrumentation tests using all Device Providers.
app:deviceCheck - Runs all device checks using Device Providers and Test Servers.
app:lint - Runs lint on all variants.
app:lintDebug - Runs lint on the Debug build.
app:lintRelease - Runs lint on the Release build.
app:lintVitalRelease - Runs lint on just the fatal issues in the release build.
app:test - Run unit tests for all variants.
app:testDebugUnitTest - Run unit tests for the debug build.
app:testReleaseUnitTest - Run unit tests for the release build.

Other tasks
-----------
app:assembleDebugAndroidTest
app:assembleDebugUnitTest
app:assembleReleaseUnitTest
app:bundleAppClassesDebug
app:bundleAppClassesDebugAndroidTest
app:bundleAppClassesDebugUnitTest
app:bundleAppClassesRelease
app:bundleAppClassesReleaseUnitTest
app:checkDebugManifest
app:checkReleaseManifest
clean
app:compileDebugAidl
app:compileDebugAndroidTestAidl
app:compileDebugAndroidTestJavaWithJavac
app:compileDebugAndroidTestKotlin - Compiles the debugAndroidTest kotlin.
app:compileDebugAndroidTestNdk
app:compileDebugAndroidTestRenderscript
app:compileDebugAndroidTestShaders
app:compileDebugJavaWithJavac
app:compileDebugKotlin - Compiles the debug kotlin.
app:compileDebugNdk
app:compileDebugRenderscript
app:compileDebugShaders
app:compileDebugUnitTestJavaWithJavac
app:compileDebugUnitTestKotlin - Compiles the debugUnitTest kotlin.
app:compileLint
app:compileReleaseAidl
app:compileReleaseJavaWithJavac
app:compileReleaseKotlin - Compiles the release kotlin.
app:compileReleaseNdk
app:compileReleaseRenderscript
app:compileReleaseShaders
app:compileReleaseUnitTestJavaWithJavac
app:compileReleaseUnitTestKotlin - Compiles the releaseUnitTest kotlin.
app:consumeConfigAttr
app:createDebugCompatibleScreenManifests
app:createReleaseCompatibleScreenManifests
app:extractProguardFiles
app:generateDebugAndroidTestAssets
app:generateDebugAndroidTestBuildConfig
app:generateDebugAndroidTestResources
app:generateDebugAndroidTestResValues
app:generateDebugAndroidTestSources
app:generateDebugAssets
app:generateDebugBuildConfig
app:generateDebugResources
app:generateDebugResValues
app:generateDebugSources
app:generateReleaseAssets
app:generateReleaseBuildConfig
app:generateReleaseResources
app:generateReleaseResValues
app:generateReleaseSources
app:javaPreCompileDebug
app:javaPreCompileDebugAndroidTest
app:javaPreCompileDebugUnitTest
app:javaPreCompileRelease
app:javaPreCompileReleaseUnitTest
app:mergeDebugAndroidTestAssets
app:mergeDebugAndroidTestJniLibFolders
app:mergeDebugAndroidTestResources
app:mergeDebugAndroidTestShaders
app:mergeDebugAssets
app:mergeDebugJniLibFolders
app:mergeDebugResources
app:mergeDebugShaders
app:mergeReleaseAssets
app:mergeReleaseJniLibFolders
app:mergeReleaseResources
app:mergeReleaseShaders
app:packageDebug
app:packageDebugAndroidTest
app:packageRelease
app:platformAttrExtractor
app:preBuild
app:preDebugAndroidTestBuild
app:preDebugBuild
app:preDebugUnitTestBuild
app:prepareLintJar
app:preReleaseBuild
app:preReleaseUnitTestBuild
app:processDebugAndroidTestJavaRes
app:processDebugAndroidTestManifest
app:processDebugAndroidTestResources
app:processDebugJavaRes
app:processDebugManifest
app:processDebugResources
app:processDebugUnitTestJavaRes
app:processReleaseJavaRes
app:processReleaseManifest
app:processReleaseResources
app:processReleaseUnitTestJavaRes
app:resolveConfigAttr
app:splitsDiscoveryTaskDebug
app:splitsDiscoveryTaskDebugAndroidTest
app:splitsDiscoveryTaskRelease
app:transformClassesWithDexBuilderForDebug
app:transformClassesWithDexBuilderForDebugAndroidTest
app:transformClassesWithPreDexForRelease
app:transformDexArchiveWithDexMergerForDebug
app:transformDexArchiveWithDexMergerForDebugAndroidTest
app:transformDexArchiveWithExternalLibsDexMergerForDebug
app:transformDexArchiveWithExternalLibsDexMergerForDebugAndroidTest
app:transformDexWithDexForRelease
app:transformNativeLibsWithMergeJniLibsForDebug
app:transformNativeLibsWithMergeJniLibsForDebugAndroidTest
app:transformNativeLibsWithMergeJniLibsForRelease
app:transformResourcesWithMergeJavaResForDebug
app:transformResourcesWithMergeJavaResForDebugAndroidTest
app:transformResourcesWithMergeJavaResForDebugUnitTest
app:transformResourcesWithMergeJavaResForRelease
app:transformResourcesWithMergeJavaResForReleaseUnitTest
app:validateSigningDebug
app:validateSigningDebugAndroidTest
app:writeDebugApplicationId
app:writeReleaseApplicationId

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed
thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ gradle clean

BUILD SUCCESSFUL in 0s
2 actionable tasks: 1 executed, 1 up-to-date
thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ tree
.
├── app
│   ├── build.gradle
│   ├── libs
│   ├── proguard-rules.pro
│   └── src
│       ├── androidTest
│       │   └── java
│       │       └── android
│       │           └── kotlin
│       │               └── dur
│       │                   └── bounceme
│       │                       └── net
│       │                           └── helloandroid
│       │                               └── ExampleInstrumentedTest.kt
│       ├── main
│       │   ├── AndroidManifest.xml
│       │   ├── java
│       │   │   └── android
│       │   │       └── kotlin
│       │   │           └── dur
│       │   │               └── bounceme
│       │   │                   └── net
│       │   │                       └── helloandroid
│       │   │                           └── MainActivity.kt
│       │   └── res
│       │       ├── drawable
│       │       │   ├── ic_dashboard_black_24dp.xml
│       │       │   ├── ic_home_black_24dp.xml
│       │       │   ├── ic_launcher_background.xml
│       │       │   └── ic_notifications_black_24dp.xml
│       │       ├── drawable-v24
│       │       │   └── ic_launcher_foreground.xml
│       │       ├── layout
│       │       │   └── activity_main.xml
│       │       ├── menu
│       │       │   └── navigation.xml
│       │       ├── mipmap-anydpi-v26
│       │       │   ├── ic_launcher_round.xml
│       │       │   └── ic_launcher.xml
│       │       ├── mipmap-hdpi
│       │       │   ├── ic_launcher.png
│       │       │   └── ic_launcher_round.png
│       │       ├── mipmap-mdpi
│       │       │   ├── ic_launcher.png
│       │       │   └── ic_launcher_round.png
│       │       ├── mipmap-xhdpi
│       │       │   ├── ic_launcher.png
│       │       │   └── ic_launcher_round.png
│       │       ├── mipmap-xxhdpi
│       │       │   ├── ic_launcher.png
│       │       │   └── ic_launcher_round.png
│       │       ├── mipmap-xxxhdpi
│       │       │   ├── ic_launcher.png
│       │       │   └── ic_launcher_round.png
│       │       └── values
│       │           ├── colors.xml
│       │           ├── dimens.xml
│       │           ├── strings.xml
│       │           └── styles.xml
│       └── test
│           └── java
│               └── android
│                   └── kotlin
│                       └── dur
│                           └── bounceme
│                               └── net
│                                   └── helloandroid
│                                       └── ExampleUnitTest.kt
├── build
│   ├── android-profile
│   │   ├── profile-2017-11-05-17-50-01-533.json
│   │   └── profile-2017-11-05-17-50-01-533.rawproto
│   └── kotlin-build
│       └── version.txt
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── HelloAndroid.iml
├── local.properties
└── settings.gradle

44 directories, 41 files
thufir@dur:~/AndroidStudioProjects/HelloAndroid$
</code>```

From Android Studio:

Simplest possible "run" is what I'm after.  Something analogous to runShadow?

Generated code and build file:

```<code>thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ cat build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.51'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // 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
}
thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ cat app/src/main/java/android/kotlin/dur/bounceme/net/helloandroid/MainActivity.kt
package android.kotlin.dur.bounceme.net.helloandroid

import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_home -> {
                message.setText(R.string.title_home)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_dashboard -> {
                message.setText(R.string.title_dashboard)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                message.setText(R.string.title_notifications)
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    }
}
thufir@dur:~/AndroidStudioProjects/HelloAndroid$
</code>```

答:
You can see

```<code>gradle installDebug
</code>```

which installs the app onto the device. You still need to run it as described by @moxi: $ adb shell am start -n "android.kotlin.dur.bounceme.net.helloandroid/android.kotlin.dur.bounceme.net.helloandroid.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER If you have some tests, you could also use

```<code>gradle connectedAndroidTest
</code>```

which starts the app to run the tests.

Title: run HelloAndroid from gradle?

Body:
There are an overwhelming number and variety of gradle tasks:

thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ gradle clean run

FAILURE: Build failed with an exception.

* What went wrong:
Task 'run' not found in root project 'HelloAndroid'.

* Try:
Run gradle tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 0s
thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ gradle tasks --all

> Task :tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Android tasks
-------------
app:androidDependencies - Displays the Android dependencies of the project.
app:signingReport - Displays the signing info for each variant.
app:sourceSets - Prints out all the source sets defined in this project.

Build tasks
-----------
app:assemble - Assembles all variants of all applications and secondary packages.
app:assembleAndroidTest - Assembles all the Test applications.
app:assembleDebug - Assembles all Debug builds.
app:assembleRelease - Assembles all Release builds.
app:build - Assembles and tests this project.
app:buildDependents - Assembles and tests this project and all projects that depend on it.
app:buildNeeded - Assembles and tests this project and all projects it depends on.
app:clean - Deletes the build directory.
app:cleanBuildCache - Deletes the build cache directory.
app:compileDebugAndroidTestSources
app:compileDebugSources
app:compileDebugUnitTestSources
app:compileReleaseSources
app:compileReleaseUnitTestSources
app:mockableAndroidJar - Creates a version of android.jar that's suitable for unit tests.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'HelloAndroid'.
app:buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
components - Displays the components produced by root project 'HelloAndroid'. [incubating]
app:components - Displays the components produced by project ':app'. [incubating]
dependencies - Displays all dependencies declared in root project 'HelloAndroid'.
app:dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in root project 'HelloAndroid'.
app:dependencyInsight - Displays the insight into a specific dependency in project ':app'.
dependentComponents - Displays the dependent components of components in root project 'HelloAndroid'. [incubating]
app:dependentComponents - Displays the dependent components of components in project ':app'. [incubating]
help - Displays a help message.
app:help - Displays a help message.
model - Displays the configuration model of root project 'HelloAndroid'. [incubating]
app:model - Displays the configuration model of project ':app'. [incubating]
projects - Displays the sub-projects of root project 'HelloAndroid'.
app:projects - Displays the sub-projects of project ':app'.
properties - Displays the properties of root project 'HelloAndroid'.
app:properties - Displays the properties of project ':app'.
tasks - Displays the tasks runnable from root project 'HelloAndroid' (some of the displayed tasks may belong to subprojects).
app:tasks - Displays the tasks runnable from project ':app'.

Install tasks
-------------
app:installDebug - Installs the Debug build.
app:installDebugAndroidTest - Installs the android (on device) tests for the Debug build.
app:uninstallAll - Uninstall all applications.
app:uninstallDebug - Uninstalls the Debug build.
app:uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Debug build.
app:uninstallRelease - Uninstalls the Release build.

Verification tasks
------------------
app:check - Runs all checks.
app:connectedAndroidTest - Installs and runs instrumentation tests for all flavors on connected devices.
app:connectedCheck - Runs all device checks on currently connected devices.
app:connectedDebugAndroidTest - Installs and runs the tests for debug on connected devices.
app:deviceAndroidTest - Installs and runs instrumentation tests using all Device Providers.
app:deviceCheck - Runs all device checks using Device Providers and Test Servers.
app:lint - Runs lint on all variants.
app:lintDebug - Runs lint on the Debug build.
app:lintRelease - Runs lint on the Release build.
app:lintVitalRelease - Runs lint on just the fatal issues in the release build.
app:test - Run unit tests for all variants.
app:testDebugUnitTest - Run unit tests for the debug build.
app:testReleaseUnitTest - Run unit tests for the release build.

Other tasks
-----------
app:assembleDebugAndroidTest
app:assembleDebugUnitTest
app:assembleReleaseUnitTest
app:bundleAppClassesDebug
app:bundleAppClassesDebugAndroidTest
app:bundleAppClassesDebugUnitTest
app:bundleAppClassesRelease
app:bundleAppClassesReleaseUnitTest
app:checkDebugManifest
app:checkReleaseManifest
clean
app:compileDebugAidl
app:compileDebugAndroidTestAidl
app:compileDebugAndroidTestJavaWithJavac
app:compileDebugAndroidTestKotlin - Compiles the debugAndroidTest kotlin.
app:compileDebugAndroidTestNdk
app:compileDebugAndroidTestRenderscript
app:compileDebugAndroidTestShaders
app:compileDebugJavaWithJavac
app:compileDebugKotlin - Compiles the debug kotlin.
app:compileDebugNdk
app:compileDebugRenderscript
app:compileDebugShaders
app:compileDebugUnitTestJavaWithJavac
app:compileDebugUnitTestKotlin - Compiles the debugUnitTest kotlin.
app:compileLint
app:compileReleaseAidl
app:compileReleaseJavaWithJavac
app:compileReleaseKotlin - Compiles the release kotlin.
app:compileReleaseNdk
app:compileReleaseRenderscript
app:compileReleaseShaders
app:compileReleaseUnitTestJavaWithJavac
app:compileReleaseUnitTestKotlin - Compiles the releaseUnitTest kotlin.
app:consumeConfigAttr
app:createDebugCompatibleScreenManifests
app:createReleaseCompatibleScreenManifests
app:extractProguardFiles
app:generateDebugAndroidTestAssets
app:generateDebugAndroidTestBuildConfig
app:generateDebugAndroidTestResources
app:generateDebugAndroidTestResValues
app:generateDebugAndroidTestSources
app:generateDebugAssets
app:generateDebugBuildConfig
app:generateDebugResources
app:generateDebugResValues
app:generateDebugSources
app:generateReleaseAssets
app:generateReleaseBuildConfig
app:generateReleaseResources
app:generateReleaseResValues
app:generateReleaseSources
app:javaPreCompileDebug
app:javaPreCompileDebugAndroidTest
app:javaPreCompileDebugUnitTest
app:javaPreCompileRelease
app:javaPreCompileReleaseUnitTest
app:mergeDebugAndroidTestAssets
app:mergeDebugAndroidTestJniLibFolders
app:mergeDebugAndroidTestResources
app:mergeDebugAndroidTestShaders
app:mergeDebugAssets
app:mergeDebugJniLibFolders
app:mergeDebugResources
app:mergeDebugShaders
app:mergeReleaseAssets
app:mergeReleaseJniLibFolders
app:mergeReleaseResources
app:mergeReleaseShaders
app:packageDebug
app:packageDebugAndroidTest
app:packageRelease
app:platformAttrExtractor
app:preBuild
app:preDebugAndroidTestBuild
app:preDebugBuild
app:preDebugUnitTestBuild
app:prepareLintJar
app:preReleaseBuild
app:preReleaseUnitTestBuild
app:processDebugAndroidTestJavaRes
app:processDebugAndroidTestManifest
app:processDebugAndroidTestResources
app:processDebugJavaRes
app:processDebugManifest
app:processDebugResources
app:processDebugUnitTestJavaRes
app:processReleaseJavaRes
app:processReleaseManifest
app:processReleaseResources
app:processReleaseUnitTestJavaRes
app:resolveConfigAttr
app:splitsDiscoveryTaskDebug
app:splitsDiscoveryTaskDebugAndroidTest
app:splitsDiscoveryTaskRelease
app:transformClassesWithDexBuilderForDebug
app:transformClassesWithDexBuilderForDebugAndroidTest
app:transformClassesWithPreDexForRelease
app:transformDexArchiveWithDexMergerForDebug
app:transformDexArchiveWithDexMergerForDebugAndroidTest
app:transformDexArchiveWithExternalLibsDexMergerForDebug
app:transformDexArchiveWithExternalLibsDexMergerForDebugAndroidTest
app:transformDexWithDexForRelease
app:transformNativeLibsWithMergeJniLibsForDebug
app:transformNativeLibsWithMergeJniLibsForDebugAndroidTest
app:transformNativeLibsWithMergeJniLibsForRelease
app:transformResourcesWithMergeJavaResForDebug
app:transformResourcesWithMergeJavaResForDebugAndroidTest
app:transformResourcesWithMergeJavaResForDebugUnitTest
app:transformResourcesWithMergeJavaResForRelease
app:transformResourcesWithMergeJavaResForReleaseUnitTest
app:validateSigningDebug
app:validateSigningDebugAndroidTest
app:writeDebugApplicationId
app:writeReleaseApplicationId

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed
thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ gradle clean

BUILD SUCCESSFUL in 0s
2 actionable tasks: 1 executed, 1 up-to-date
thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ tree
.
├── app
│   ├── build.gradle
│   ├── libs
│   ├── proguard-rules.pro
│   └── src
│       ├── androidTest
│       │   └── java
│       │       └── android
│       │           └── kotlin
│       │               └── dur
│       │                   └── bounceme
│       │                       └── net
│       │                           └── helloandroid
│       │                               └── ExampleInstrumentedTest.kt
│       ├── main
│       │   ├── AndroidManifest.xml
│       │   ├── java
│       │   │   └── android
│       │   │       └── kotlin
│       │   │           └── dur
│       │   │               └── bounceme
│       │   │                   └── net
│       │   │                       └── helloandroid
│       │   │                           └── MainActivity.kt
│       │   └── res
│       │       ├── drawable
│       │       │   ├── ic_dashboard_black_24dp.xml
│       │       │   ├── ic_home_black_24dp.xml
│       │       │   ├── ic_launcher_background.xml
│       │       │   └── ic_notifications_black_24dp.xml
│       │       ├── drawable-v24
│       │       │   └── ic_launcher_foreground.xml
│       │       ├── layout
│       │       │   └── activity_main.xml
│       │       ├── menu
│       │       │   └── navigation.xml
│       │       ├── mipmap-anydpi-v26
│       │       │   ├── ic_launcher_round.xml
│       │       │   └── ic_launcher.xml
│       │       ├── mipmap-hdpi
│       │       │   ├── ic_launcher.png
│       │       │   └── ic_launcher_round.png
│       │       ├── mipmap-mdpi
│       │       │   ├── ic_launcher.png
│       │       │   └── ic_launcher_round.png
│       │       ├── mipmap-xhdpi
│       │       │   ├── ic_launcher.png
│       │       │   └── ic_launcher_round.png
│       │       ├── mipmap-xxhdpi
│       │       │   ├── ic_launcher.png
│       │       │   └── ic_launcher_round.png
│       │       ├── mipmap-xxxhdpi
│       │       │   ├── ic_launcher.png
│       │       │   └── ic_launcher_round.png
│       │       └── values
│       │           ├── colors.xml
│       │           ├── dimens.xml
│       │           ├── strings.xml
│       │           └── styles.xml
│       └── test
│           └── java
│               └── android
│                   └── kotlin
│                       └── dur
│                           └── bounceme
│                               └── net
│                                   └── helloandroid
│                                       └── ExampleUnitTest.kt
├── build
│   ├── android-profile
│   │   ├── profile-2017-11-05-17-50-01-533.json
│   │   └── profile-2017-11-05-17-50-01-533.rawproto
│   └── kotlin-build
│       └── version.txt
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── HelloAndroid.iml
├── local.properties
└── settings.gradle

44 directories, 41 files
thufir@dur:~/AndroidStudioProjects/HelloAndroid$

From Android Studio:

Simplest possible "run" is what I'm after.  Something analogous to runShadow?

Generated code and build file:

thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ cat build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.51'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // 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
}
thufir@dur:~/AndroidStudioProjects/HelloAndroid$
thufir@dur:~/AndroidStudioProjects/HelloAndroid$ cat app/src/main/java/android/kotlin/dur/bounceme/net/helloandroid/MainActivity.kt
package android.kotlin.dur.bounceme.net.helloandroid

import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_home -> {
                message.setText(R.string.title_home)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_dashboard -> {
                message.setText(R.string.title_dashboard)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                message.setText(R.string.title_notifications)
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    }
}
thufir@dur:~/AndroidStudioProjects/HelloAndroid$

Body:
You can see

gradle installDebug

which installs the app onto the device. You still need to run it as described by @moxi: $ adb shell am start -n "android.kotlin.dur.bounceme.net.helloandroid/android.kotlin.dur.bounceme.net.helloandroid.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER If you have some tests, you could also use

gradle connectedAndroidTest

which starts the app to run the tests.


来源: stackexchange

问:
grepl for any string allowed
I am building a grepl command is fed by a function parameter. I'd like to skip the grep command if it's not needed. I could do this with control statements, but I would like to pass a value that returns all strings.

```<code>some_sub <- function(data, descr="*.*"){
     return(data %>% filter(grepl(descr, description)))
}
</code>```

I'd like to have the following working:

```<code>some_sub(data, "Cabbage")
some_sub(data) # returns everything
</code>```

where data

```<code>data <- structure(list(description = structure(c(1L, 1L, 2L, 1L),
                                   .Label = c("Cabbage","Carrot"),
                                   class = "factor"),
           weight = c(12L, 9L, 7L, 15L)),
      class = "data.frame",
      row.names = c(NA,-4L))
</code>```

答:
An option would be to just use . (as it is a metacharacter for any character) as the default match for descr parameter

Added one more paramet colNm to generalize a bit more

If there are blanks ("") and want to match those, it may be better to have * as the default

```<code>some_sub <- function(data, colNm, descr="."){
 colNm <- enquo(colNm)
 data %>%
      filter(grepl(descr, !!colNm))
}

some_sub(iris, Species, "setosa")
some_sub(iris, Species)
</code>```

Using OP' data

```<code>some_sub(data, description, "Cabbage")
#  description weight
#1     Cabbage     12
#2     Cabbage      9
#3     Cabbage     15

some_sub(data, description)
#  description weight
#1     Cabbage     12
#2     Cabbage      9
#3      Carrot      7
#4     Cabbage     15
</code>```

ContentLicense: CC BY-SA 4.0

Title: grepl for any string allowed

Body:
I am building a grepl command is fed by a function parameter. I'd like to skip the grep command if it's not needed. I could do this with control statements, but I would like to pass a value that returns all strings.

some_sub <- function(data, descr="*.*"){
     return(data %>% filter(grepl(descr, description)))
}

I'd like to have the following working:

some_sub(data, "Cabbage")
some_sub(data) # returns everything

where data

data <- structure(list(description = structure(c(1L, 1L, 2L, 1L),
                                   .Label = c("Cabbage","Carrot"),
                                   class = "factor"),
           weight = c(12L, 9L, 7L, 15L)),
      class = "data.frame",
      row.names = c(NA,-4L))

Body:
An option would be to just use . (as it is a metacharacter for any character) as the default match for descr parameter

Added one more paramet colNm to generalize a bit more

If there are blanks ("") and want to match those, it may be better to have * as the default

some_sub <- function(data, colNm, descr="."){
 colNm <- enquo(colNm)
 data %>%
      filter(grepl(descr, !!colNm))
}

some_sub(iris, Species, "setosa")
some_sub(iris, Species)

Using OP' data

some_sub(data, description, "Cabbage")
#  description weight
#1     Cabbage     12
#2     Cabbage      9
#3     Cabbage     15

some_sub(data, description)
#  description weight
#1     Cabbage     12
#2     Cabbage      9
#3      Carrot      7
#4     Cabbage     15


问:
Overload resolution in case of templates and inheritance in unique_ptr
I have two classes:

```<code>class Base {};
class Derived : public Base {};
</code>```

And two overloaded functions:

```<code>void call(std::unique_ptr<Base> op)
{
    std::cout << "First overloading" << std::endl;
}

template<class F>
void call(F f)
{
    std::cout << "Second overloading" << std::endl;
}
</code>```

Let's call it with unique_ptr of Derived

```<code>call(std::make_unique<Derived>());
</code>```

I expect calling first function, however second is called instead.
Why compiler choose generic function instead of specific one? Overload resolution does not support inheritance and polymorphism?
If so, how I can fix it and call first function?

答:
Both of your overloads are valid candidates. If you remove either, the remaining one is still a valid overload. In such a case, broadly speaking, the overload that will be chosen will be the one that most closely matches the arguments provided.

You provided std::unique_ptr<Derived>. In the first case, it expects std::unique_ptr<Base>. There exists an implicit conversion from std::unique_ptr<Derived> to std::unique_ptr<Base>, so this overload is legal, but it does require a conversion.

In the second case, F is simply deduced to be std::unique_ptr<Derived>. It does not require a conversion and is a closer match to the argument provided. Therefore, it is preferred.

Edit : It seems I missed the part about a fix.

You can make the overload that accepts a unique_ptr a function template instead. This way, you can get an exact match with the first overload, eliminating the need for a conversion. You can use std::enable_if to disable that overload for unique_ptrs of incompatible types :

```<code>#include <memory>
#include <type_traits>

class Base {};
class Derived : public Base {};

template<class T>
std::enable_if_t<std::is_base_of<Base, T>::value>>
call(std::unique_ptr<T>);

template<class T>
void call(T);
</code>```

Body:
I have two classes:

class Base {};
class Derived : public Base {};

And two overloaded functions:

void call(std::unique_ptr<Base> op)
{
    std::cout << "First overloading" << std::endl;
}

template<class F>
void call(F f)
{
    std::cout << "Second overloading" << std::endl;
}

Let's call it with unique_ptr of Derived

call(std::make_unique<Derived>());

I expect calling first function, however second is called instead.
Why compiler choose generic function instead of specific one? Overload resolution does not support inheritance and polymorphism?
If so, how I can fix it and call first function?

Body:
Both of your overloads are valid candidates. If you remove either, the remaining one is still a valid overload. In such a case, broadly speaking, the overload that will be chosen will be the one that most closely matches the arguments provided.

You provided std::unique_ptr<Derived>. In the first case, it expects std::unique_ptr<Base>. There exists an implicit conversion from std::unique_ptr<Derived> to std::unique_ptr<Base>, so this overload is legal, but it does require a conversion.

In the second case, F is simply deduced to be std::unique_ptr<Derived>. It does not require a conversion and is a closer match to the argument provided. Therefore, it is preferred.

Edit : It seems I missed the part about a fix.

You can make the overload that accepts a unique_ptr a function template instead. This way, you can get an exact match with the first overload, eliminating the need for a conversion. You can use std::enable_if to disable that overload for unique_ptrs of incompatible types :

#include <memory>
#include <type_traits>

class Base {};
class Derived : public Base {};

template<class T>
std::enable_if_t<std::is_base_of<Base, T>::value>>
call(std::unique_ptr<T>);

template<class T>
void call(T);


问:
Network is Unreachable error from Compute Engine (but fine from local machine)
I am getting an error for my Java-based test code snippet when I run it from a GCE instance (whereas it works fine from my local machine, with the right credentials).

I used to be able to run Pub/Sub code from GCE instances just a few months ago, but seems like no longer. Not sure if this is an ipv4/ipv6 issue, but I can't find any information out there on how to properly configure GCE instances now to work with Pub/Sub.

Not sure if this is the issue, but it seems like i can reach pubsub.googleapis.com with ping, but not ping6:

```<code>ping pubsub.googleapis.com
PING pubsub.googleapis.com (173.194.196.95) 56(84) bytes of data.
</code>```

vs.

```<code>ping6 pubsub.googleapis.com
connect: Network is unreachable
</code>```

For what it's worth, here's the full Java stack trace:

```<code>Exception in thread "main" java.util.concurrent.ExecutionException: com.google.api.gax.rpc.UnavailableException: io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
    at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:552)
    at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:533)
    at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:90)
    at com.google.common.util.concurrent.ForwardingFuture.get(ForwardingFuture.java:62)
    at PSPublish.main(PSPublish.java:149)
Caused by: com.google.api.gax.rpc.UnavailableException: io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
    at com.google.api.gax.rpc.ApiExceptionFactory.createException(ApiExceptionFactory.java:69)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:72)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:60)
    at com.google.api.gax.grpc.GrpcExceptionCallable$ExceptionTransformingFuture.onFailure(GrpcExceptionCallable.java:97)
    at com.google.api.core.ApiFutures$1.onFailure(ApiFutures.java:68)
    at com.google.common.util.concurrent.Futures$CallbackListener.run(Futures.java:1070)
    at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
    at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1138)
    at com.google.common.util.concurrent.AbstractFuture.addListener(AbstractFuture.java:707)
    at com.google.common.util.concurrent.ForwardingListenableFuture.addListener(ForwardingListenableFuture.java:45)
    at com.google.api.core.ApiFutureToListenableFuture.addListener(ApiFutureToListenableFuture.java:52)
    at com.google.common.util.concurrent.Futures.addCallback(Futures.java:1051)
    at com.google.api.core.ApiFutures.addCallback(ApiFutures.java:63)
    at com.google.api.gax.grpc.GrpcExceptionCallable.futureCall(GrpcExceptionCallable.java:67)
    at com.google.api.gax.rpc.AttemptCallable.call(AttemptCallable.java:86)
    at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:125)
    at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:69)
    at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:78)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
    at io.grpc.Status.asRuntimeException(Status.java:532)
    at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:482)
    at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
    at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23)
    at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40)
    at io.grpc.internal.CensusStatsModule$StatsClientInterceptor$1$1.onClose(CensusStatsModule.java:699)
    at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
    at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23)
    at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40)
    at io.grpc.internal.CensusTracingModule$TracingClientInterceptor$1$1.onClose(CensusTracingModule.java:397)
    at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:459)
    at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:63)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:546)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$600(ClientCallImpl.java:467)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:584)
    at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
    ... 6 more
Caused by: io.grpc.netty.shaded.io.netty.channel.AbstractChannel$AnnotatedSocketException: Network is unreachable: pubsub.googleapis.com/2607:f8b0:4001:c03:0:0:0:5f:443
    at java.base/sun.nio.ch.Net.connect0(Native Method)
    at java.base/sun.nio.ch.Net.connect(Net.java:482)
    at java.base/sun.nio.ch.Net.connect(Net.java:474)
    at java.base/sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:694)
    at io.grpc.netty.shaded.io.netty.util.internal.SocketUtils$3.run(SocketUtils.java:83)
    at io.grpc.netty.shaded.io.netty.util.internal.SocketUtils$3.run(SocketUtils.java:80)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at io.grpc.netty.shaded.io.netty.util.internal.SocketUtils.connect(SocketUtils.java:80)
    at io.grpc.netty.shaded.io.netty.channel.socket.nio.NioSocketChannel.doConnect(NioSocketChannel.java:312)
    at io.grpc.netty.shaded.io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.connect(AbstractNioChannel.java:254)
    at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline$HeadContext.connect(DefaultChannelPipeline.java:1366)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeConnect(AbstractChannelHandlerContext.java:545)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChannelHandlerContext.java:530)
    at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.connect(SslHandler.java:716)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeConnect(AbstractChannelHandlerContext.java:545)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChannelHandlerContext.java:530)
    at io.grpc.netty.shaded.io.netty.channel.ChannelDuplexHandler.connect(ChannelDuplexHandler.java:50)
    at io.grpc.netty.shaded.io.grpc.netty.ProtocolNegotiators$AbstractBufferingHandler.connect(ProtocolNegotiators.java:491)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeConnect(AbstractChannelHandlerContext.java:545)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChannelHandlerContext.java:530)
    at io.grpc.netty.shaded.io.netty.channel.ChannelDuplexHandler.connect(ChannelDuplexHandler.java:50)
    at io.grpc.netty.shaded.io.grpc.netty.WriteBufferingAndExceptionHandler.connect(WriteBufferingAndExceptionHandler.java:136)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeConnect(AbstractChannelHandlerContext.java:545)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.access$1000(AbstractChannelHandlerContext.java:38)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext$11.run(AbstractChannelHandlerContext.java:535)
    at io.grpc.netty.shaded.io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
    at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:474)
    at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:909)
    at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    ... 1 more
Caused by: java.net.SocketException: Network is unreachable
</code>```

答:
I can't find any information out there on how to properly configure GCE instances now to work with Pub/Sub.

There is no Pub/Sub-specific configuration necessary for GCE VMs to talk to the Pub/Sub service. This seems like a networking issue outside the scope of the Pub/Sub service.

Body:
I am getting an error for my Java-based test code snippet when I run it from a GCE instance (whereas it works fine from my local machine, with the right credentials).

I used to be able to run Pub/Sub code from GCE instances just a few months ago, but seems like no longer. Not sure if this is an ipv4/ipv6 issue, but I can't find any information out there on how to properly configure GCE instances now to work with Pub/Sub.

Not sure if this is the issue, but it seems like i can reach pubsub.googleapis.com with ping, but not ping6:

ping pubsub.googleapis.com
PING pubsub.googleapis.com (173.194.196.95) 56(84) bytes of data.

vs.

ping6 pubsub.googleapis.com
connect: Network is unreachable

For what it's worth, here's the full Java stack trace:

Exception in thread "main" java.util.concurrent.ExecutionException: com.google.api.gax.rpc.UnavailableException: io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
    at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:552)
    at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:533)
    at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:90)
    at com.google.common.util.concurrent.ForwardingFuture.get(ForwardingFuture.java:62)
    at PSPublish.main(PSPublish.java:149)
Caused by: com.google.api.gax.rpc.UnavailableException: io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
    at com.google.api.gax.rpc.ApiExceptionFactory.createException(ApiExceptionFactory.java:69)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:72)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:60)
    at com.google.api.gax.grpc.GrpcExceptionCallable$ExceptionTransformingFuture.onFailure(GrpcExceptionCallable.java:97)
    at com.google.api.core.ApiFutures$1.onFailure(ApiFutures.java:68)
    at com.google.common.util.concurrent.Futures$CallbackListener.run(Futures.java:1070)
    at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
    at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1138)
    at com.google.common.util.concurrent.AbstractFuture.addListener(AbstractFuture.java:707)
    at com.google.common.util.concurrent.ForwardingListenableFuture.addListener(ForwardingListenableFuture.java:45)
    at com.google.api.core.ApiFutureToListenableFuture.addListener(ApiFutureToListenableFuture.java:52)
    at com.google.common.util.concurrent.Futures.addCallback(Futures.java:1051)
    at com.google.api.core.ApiFutures.addCallback(ApiFutures.java:63)
    at com.google.api.gax.grpc.GrpcExceptionCallable.futureCall(GrpcExceptionCallable.java:67)
    at com.google.api.gax.rpc.AttemptCallable.call(AttemptCallable.java:86)
    at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:125)
    at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:69)
    at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:78)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
    at io.grpc.Status.asRuntimeException(Status.java:532)
    at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:482)
    at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
    at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23)
    at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40)
    at io.grpc.internal.CensusStatsModule$StatsClientInterceptor$1$1.onClose(CensusStatsModule.java:699)
    at io.grpc.PartialForwardingClientCallListener.onClose(PartialForwardingClientCallListener.java:39)
    at io.grpc.ForwardingClientCallListener.onClose(ForwardingClientCallListener.java:23)
    at io.grpc.ForwardingClientCallListener$SimpleForwardingClientCallListener.onClose(ForwardingClientCallListener.java:40)
    at io.grpc.internal.CensusTracingModule$TracingClientInterceptor$1$1.onClose(CensusTracingModule.java:397)
    at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:459)
    at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:63)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:546)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$600(ClientCallImpl.java:467)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:584)
    at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
    ... 6 more
Caused by: io.grpc.netty.shaded.io.netty.channel.AbstractChannel$AnnotatedSocketException: Network is unreachable: pubsub.googleapis.com/2607:f8b0:4001:c03:0:0:0:5f:443
    at java.base/sun.nio.ch.Net.connect0(Native Method)
    at java.base/sun.nio.ch.Net.connect(Net.java:482)
    at java.base/sun.nio.ch.Net.connect(Net.java:474)
    at java.base/sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:694)
    at io.grpc.netty.shaded.io.netty.util.internal.SocketUtils$3.run(SocketUtils.java:83)
    at io.grpc.netty.shaded.io.netty.util.internal.SocketUtils$3.run(SocketUtils.java:80)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at io.grpc.netty.shaded.io.netty.util.internal.SocketUtils.connect(SocketUtils.java:80)
    at io.grpc.netty.shaded.io.netty.channel.socket.nio.NioSocketChannel.doConnect(NioSocketChannel.java:312)
    at io.grpc.netty.shaded.io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.connect(AbstractNioChannel.java:254)
    at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline$HeadContext.connect(DefaultChannelPipeline.java:1366)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeConnect(AbstractChannelHandlerContext.java:545)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChannelHandlerContext.java:530)
    at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.connect(SslHandler.java:716)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeConnect(AbstractChannelHandlerContext.java:545)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChannelHandlerContext.java:530)
    at io.grpc.netty.shaded.io.netty.channel.ChannelDuplexHandler.connect(ChannelDuplexHandler.java:50)
    at io.grpc.netty.shaded.io.grpc.netty.ProtocolNegotiators$AbstractBufferingHandler.connect(ProtocolNegotiators.java:491)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeConnect(AbstractChannelHandlerContext.java:545)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.connect(AbstractChannelHandlerContext.java:530)
    at io.grpc.netty.shaded.io.netty.channel.ChannelDuplexHandler.connect(ChannelDuplexHandler.java:50)
    at io.grpc.netty.shaded.io.grpc.netty.WriteBufferingAndExceptionHandler.connect(WriteBufferingAndExceptionHandler.java:136)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeConnect(AbstractChannelHandlerContext.java:545)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.access$1000(AbstractChannelHandlerContext.java:38)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext$11.run(AbstractChannelHandlerContext.java:535)
    at io.grpc.netty.shaded.io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
    at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:474)
    at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:909)
    at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    ... 1 more
Caused by: java.net.SocketException: Network is unreachable


问:
Copy trigger from one database to another
Is it possible, in a script executed in MS SQL Server 2005, to copy a trigger from one database to another?

I've been asked to write a test script for a trigger my project is using. Our test structure is to create an empty database containing only the object under test, then execute a script on that database that creates all the other objects needed for the test, fills them, runs whatever tests are needed, compares the results against expected results, and then drops everything except the object under test.

I can't just create a database that is empty except for the trigger, because the trigger depends on several tables. My test script currently runs the CREATE TRIGGER after all the required tables are created, but this won't do because the test script isn't allowed to contain the object under test.

What's been suggested is that, instead of running a CREATE TRIGGER, I somehow copy the trigger at that point in the script from the live database to the test database. I've had a quick Google and haven't found a way to do this. Thus my question - is this even possible, and if so, how can I do it?

答:
I have a stored procedure that copies a bunch of tables to a test database. To make it less prone to mistakes that could potentially change the wrong database, I want to avoid using USE and instead explicitly specify per statement which database the trigger is copied from and to.

With the help of this answer, I came up with this solution:

```<code>DECLARE @sql NVARCHAR(MAX);
EXEC SourceDB.sys.sp_executesql
    N'SELECT @output = (SELECT OBJECT_DEFINITION(OBJECT_ID(''TriggerName'')))',
    N'@output VARCHAR(MAX) OUTPUT',
    @output = @sql OUTPUT;
EXEC DestDB.sys.sp_executesql @sql;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a stored procedure that copies a bunch of tables to a test database. To make it less prone to mistakes that could potentially change the wrong database, I want to avoid using USE and instead explicitly specify per statement which database the trigger is copied from and to.

With the help of this answer, I came up with this solution:

DECLARE @sql NVARCHAR(MAX);
EXEC SourceDB.sys.sp_executesql
    N'SELECT @output = (SELECT OBJECT_DEFINITION(OBJECT_ID(''TriggerName'')))',
    N'@output VARCHAR(MAX) OUTPUT',
    @output = @sql OUTPUT;
EXEC DestDB.sys.sp_executesql @sql;


问:
Python Repo Cleanup
I have a script that I have almost 100% complete however there is just one more step that I can not figure out. My script currently checks the destination to see if the file already exists and if it does then the file from the source location is not moved over. The problem I am running into is that the code doesn't check all of the subdirectories as well just the root directory.

I am using os.walk to go through all of the files in the source folder but am not sure how to os.walk the destination folder and the source folder in conjunction with each other.

```<code>import time
import sys
import logging
import logging.config

def main():
    purge_files

def move_files(src_file):

    try:
        #Attempt to move files to dest
        shutil.move(src_file, dest)
        #making use of the OSError exception instead of FileExistsError due to older version of python not contaning that exception
    except OSError as e:
        #Log the files that have not been moved to the console
        logging.info(f'Files File already exists: {src_file}')
        print(f'File already exists: {src_file}')
        #os.remove to delete files that are already in dest repo
        os.remove(src_file)
        logging.warning(f'Deleting: {src_file}')

def file_loop(files, root):

    for file in files:
        #src_file is used to get the full path of everyfile
        src_file = os.path.join(root,file)

        #The two variables below are used to get the files creation date
        t = os.stat(src_file)
        c = t.st_ctime
        #If the file is older then cutoff code within the if statement executes

        if c<cutoff:

            move_files(src_file)
        #Log the file names that are not older then the cutoff and continue loop
        else:
            logging.info(f'File is not older than 14 days: {src_file}')
            continue

def purge_files():

    logging.info('invoke purge_files method')
    #Walk through root directory and all subdirectories
       for root, subdirs, files in os.walk(source):
          dst_dir = root.replace(source, dest)

           #Loop through files to grab every file
           file_loop(files, root)

       return files, root, subdirs

files, root, subdirs = purge_files()
</code>```

I expected the output to move all files from source to dest. Before the files are moved I expected to check all files in the dest location including subdir of dest if any of them are the same file as the source then they wont be moved to the dest. I do not want the folders that are in source. I just want all the files to be moved to the root directory.

答:
I can see that you have written a large part of the code already, but as it is currently posted it contains quite some errors:

The code is incorrectly indented, making it invalid Python code.

Some import statements are missing (e.g. for shutil).

You are referring to undefined variables (e.g. source).

If I copy-paste your code into my IDE, I get 26 errors from pep8 and pylint, and after fixing the indentation error I get 49 errors. It makes me wonder if this is your actual code or if you made copy-paste errors. Anyway, using an IDE will definitely help you validate your code and catch errors earlier. Try it!

Since I cannot run your code, I can't exactly tell why it's not working, but I can give you some pointers.

One thing that raises much questions is the following line:

dst_dir = root.replace(source, dest)
```

<p>Apart from the bad indentation, the variable <code>dst_dir</code> is not used anywhere. So what's the point of this statement? Also note that this replaces <em>all</em> occurences of <code>source</code> in <code>root</code>. For trivial cases this will be no problem, but it's not very robust in all circumstances. So use path operations from the standard library when possible and try to avoid performing manual string operations on paths. In Python 3.4 the <code>Pathlib</code> module was introduced. I recommend using that.</p>

<p>Using <code>os.walk()</code> can be quite convenient in some cases, but may not be the best solution for your use case. Maybe using <code>os.listdir()</code> recursively will be much easier, especially since the destination directory will be flat (i.e. a fixed directory without sub directories).</p>

<p>A possible implementation (using <code>pathlib</code> and <code>os.listdir()</code>) could be as follows:</p>

<pre class="lang-py prettyprint-override"><code>import logging
import os
import pathlib
import shutil
import time

SOURCE_DIR_PATH = pathlib.Path('C:\\Temp')
DESTINATION_DIR_PATH = pathlib.Path('D:\\archive')

CUTOFF_DAYS = 14
CUTOFF_TIME = time.time() - CUTOFF_DAYS * 24 * 3600  # two weeks

def move_file(src_file_path, dst_dir_path):
    logging.debug('Moving file %s to directory %s', src_file_path,
                  dst_dir_path)
    return  # REMOVE THIS LINE TO ACTUALLY PERFORM FILE OPERATIONS
    try:
        shutil.move(str(src_file_path), str(dst_dir_path))
    except OSError:
        logging.info('File already exists in destination directory: %s',
                     src_file_path)
        logging.warning('Deleting file %s', src_file_path)
        src_file_path.unlink()

def move_files(src_file_paths, dst_dir_path):
    for src_file_path in src_file_paths:
        if src_file_path.stat().st_ctime < CUTOFF_TIME:
            logging.info('Moving file older than %d days: %s', CUTOFF_DAYS,
                         src_file_path)
            move_file(src_file_path, dst_dir_path)
        else:
            logging.info('Not moving file less than %d days old: %s',
                         CUTOFF_DAYS, src_file_path)

def purge_files(src_dir_path, dst_dir_path):
    logging.info('Scanning directory %s', src_dir_path)
    names = os.listdir(src_dir_path)
    paths = [src_dir_path.joinpath(name) for name in names]
    file_paths = [path for path in paths if path.is_file()]
    dir_paths = [path for path in paths if path.is_dir()]
    # Cleanup files
    move_files(file_paths, dst_dir_path)
    # Cleanup directories, recursively.
    for dir_path in dir_paths:
        purge_files(dir_path, dst_dir_path)

def main():
    logging.basicConfig(format='%(message)s', level=logging.DEBUG)
    purge_files(SOURCE_DIR_PATH, DESTINATION_DIR_PATH)

if __name__ == '__main__':
    main()
</code>```

I tested this code and it worked.

Note that I used the same error handling for move_file as in your example. However, I don't think it's quite robust. What if two files with the same name exist in the source directory (in different subdirectories, or during different times)? Than the second file will be deleted without backup. Also, in case of other errors (such as "disk full" or "network error"), the code just assumes that the file was already backed up and the original is deleted. I don't know your use case, but I would seriously consider rewriting this function.

However, I hope these suggestions and example code will get you on the right track.

Title: Python Repo Cleanup

Body:
I have a script that I have almost 100% complete however there is just one more step that I can not figure out. My script currently checks the destination to see if the file already exists and if it does then the file from the source location is not moved over. The problem I am running into is that the code doesn't check all of the subdirectories as well just the root directory.

I am using os.walk to go through all of the files in the source folder but am not sure how to os.walk the destination folder and the source folder in conjunction with each other.

import time
import sys
import logging
import logging.config

def main():
    purge_files

def move_files(src_file):

    try:
        #Attempt to move files to dest
        shutil.move(src_file, dest)
        #making use of the OSError exception instead of FileExistsError due to older version of python not contaning that exception
    except OSError as e:
        #Log the files that have not been moved to the console
        logging.info(f'Files File already exists: {src_file}')
        print(f'File already exists: {src_file}')
        #os.remove to delete files that are already in dest repo
        os.remove(src_file)
        logging.warning(f'Deleting: {src_file}')

def file_loop(files, root):

    for file in files:
        #src_file is used to get the full path of everyfile
        src_file = os.path.join(root,file)

        #The two variables below are used to get the files creation date
        t = os.stat(src_file)
        c = t.st_ctime
        #If the file is older then cutoff code within the if statement executes

        if c<cutoff:

            move_files(src_file)
        #Log the file names that are not older then the cutoff and continue loop
        else:
            logging.info(f'File is not older than 14 days: {src_file}')
            continue

def purge_files():

    logging.info('invoke purge_files method')
    #Walk through root directory and all subdirectories
       for root, subdirs, files in os.walk(source):
          dst_dir = root.replace(source, dest)

           #Loop through files to grab every file
           file_loop(files, root)

       return files, root, subdirs

files, root, subdirs = purge_files()

I expected the output to move all files from source to dest. Before the files are moved I expected to check all files in the dest location including subdir of dest if any of them are the same file as the source then they wont be moved to the dest. I do not want the folders that are in source. I just want all the files to be moved to the root directory.

Body:
I can see that you have written a large part of the code already, but as it is currently posted it contains quite some errors:

The code is incorrectly indented, making it invalid Python code.

Some import statements are missing (e.g. for shutil).

You are referring to undefined variables (e.g. source).

If I copy-paste your code into my IDE, I get 26 errors from pep8 and pylint, and after fixing the indentation error I get 49 errors. It makes me wonder if this is your actual code or if you made copy-paste errors. Anyway, using an IDE will definitely help you validate your code and catch errors earlier. Try it!

Since I cannot run your code, I can't exactly tell why it's not working, but I can give you some pointers.

One thing that raises much questions is the following line:

dst_dir = root.replace(source, dest)

Apart from the bad indentation, the variable dst_dir is not used anywhere. So what's the point of this statement? Also note that this replaces all occurences of source in root. For trivial cases this will be no problem, but it's not very robust in all circumstances. So use path operations from the standard library when possible and try to avoid performing manual string operations on paths. In Python 3.4 the Pathlib module was introduced. I recommend using that.

Using os.walk() can be quite convenient in some cases, but may not be the best solution for your use case. Maybe using os.listdir() recursively will be much easier, especially since the destination directory will be flat (i.e. a fixed directory without sub directories).

A possible implementation (using pathlib and os.listdir()) could be as follows:

import logging
import os
import pathlib
import shutil
import time

SOURCE_DIR_PATH = pathlib.Path('C:\\Temp')
DESTINATION_DIR_PATH = pathlib.Path('D:\\archive')

CUTOFF_DAYS = 14
CUTOFF_TIME = time.time() - CUTOFF_DAYS * 24 * 3600  # two weeks

def move_file(src_file_path, dst_dir_path):
    logging.debug('Moving file %s to directory %s', src_file_path,
                  dst_dir_path)
    return  # REMOVE THIS LINE TO ACTUALLY PERFORM FILE OPERATIONS
    try:
        shutil.move(str(src_file_path), str(dst_dir_path))
    except OSError:
        logging.info('File already exists in destination directory: %s',
                     src_file_path)
        logging.warning('Deleting file %s', src_file_path)
        src_file_path.unlink()

def move_files(src_file_paths, dst_dir_path):
    for src_file_path in src_file_paths:
        if src_file_path.stat().st_ctime < CUTOFF_TIME:
            logging.info('Moving file older than %d days: %s', CUTOFF_DAYS,
                         src_file_path)
            move_file(src_file_path, dst_dir_path)
        else:
            logging.info('Not moving file less than %d days old: %s',
                         CUTOFF_DAYS, src_file_path)

def purge_files(src_dir_path, dst_dir_path):
    logging.info('Scanning directory %s', src_dir_path)
    names = os.listdir(src_dir_path)
    paths = [src_dir_path.joinpath(name) for name in names]
    file_paths = [path for path in paths if path.is_file()]
    dir_paths = [path for path in paths if path.is_dir()]
    # Cleanup files
    move_files(file_paths, dst_dir_path)
    # Cleanup directories, recursively.
    for dir_path in dir_paths:
        purge_files(dir_path, dst_dir_path)

def main():
    logging.basicConfig(format='%(message)s', level=logging.DEBUG)
    purge_files(SOURCE_DIR_PATH, DESTINATION_DIR_PATH)

if __name__ == '__main__':
    main()

I tested this code and it worked.

Note that I used the same error handling for move_file as in your example. However, I don't think it's quite robust. What if two files with the same name exist in the source directory (in different subdirectories, or during different times)? Than the second file will be deleted without backup. Also, in case of other errors (such as "disk full" or "network error"), the code just assumes that the file was already backed up and the original is deleted. I don't know your use case, but I would seriously consider rewriting this function.

However, I hope these suggestions and example code will get you on the right track.


问:
Java - Remotely Connect to a Server using PowerShell and bypass the password prompt
I need help connecting to a remote server using PowerShell in JAVA. I want the connection to be done in the background, without having a prompt for the password and navigate to the desired location on the server (C:\Events\rootdir\), where I will upload a directory from my local machine.

Currently, I am using the following query:

```<code> String command = "powershell.exe Invoke-Command -Credential myusername -ComputerName 192.x.x.x -FilePath C:\\Events\\rootdir\\
 Process powerShellProcess = Runtime.getRuntime().exec(command);
 powerShellProcess.getOutputStream().close();
</code>```

However, by doing this I am getting a prompt for the password:

What do I need to do to include the password call in the command string, so that I connect directly to C:\Events\rootdir\, bypassing this password prompt?

答:
Here is the working code:</p>

```<code>public class PowerShellSession {
    private static String subModule = "PowerShellSession";
    String targetIpAddress;
    String username;
    String password;

    public static Object connectPShellLock = new Object();

    public PowerShellSession() {}

    public void exec(String cmd, String credentials)  {

        String ex = credentials +" Invoke-Command -ScriptBlock {" + cmd + "} -ComputerName " + targetIpAddress +" -Credential $mycred";

        String[] args = new String[] { "powershell", ex};
        try {
            execRemote(args);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        String command = "Exit-PSSession";
        String[] args = new String[] { "powershell", command};
        try {
            execRemote(args);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String getCredentials(String domain, String userName,
            String password) throws IOException {
        String creds = "$Username = '"+userName+"';$PlainPassword ='" + password
                + "'; $SecurePassword = ConvertTo-SecureString -AsPlainText $PlainPassword -Force;"
                + "$mycred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword;";
        //creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";

        String[] args = new String[] { "powershell", creds};
        execRemote(args);
        return creds;
    }

    private void execRemote(String[] arguments) throws IOException {
        ProcessBuilder builder = new ProcessBuilder(arguments);
        builder.redirectErrorStream(true);
        Process process = builder.start();
        doProcessIO(process);
    }

    // Do the IO for a passed process
    private void doProcessIO(Process p) throws IOException {
        p.getOutputStream().close();
        String line;
        System.out.println("Output:");
        BufferedReader stdout = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        while ((line = stdout.readLine()) != null) {
            System.out.println(line);
        }
        stdout.close();
        System.out.println("Error:");
        BufferedReader stderr = new BufferedReader(new InputStreamReader(
                p.getErrorStream()));
        while ((line = stderr.readLine()) != null) {
            System.out.println(line);
        }
        stderr.close();
        System.out.println("Done");
    }

    public static void main(String[] args) throws IOException {
        PropertiesFileReader propReader = new PropertiesFileReader(System.getProperty("user.dir")+"/cred.properties");

        String user = propReader.getPropertyData("user");
        String pass = propReader.getPropertyData("pass");
        String ip_add = propReader.getPropertyData("ip");

        PowerShellSession psSession = new PowerShellSession();
        String credentials = psSession.getCredentials(ip_add, user, pass);
        psSession.targetIpAddress = ip_add;//;

        String cmdd = propReader.getPropertyData("command");//"Get-Culture";
        if(!credentials.equals("")) {

            psSession.exec(cmdd, credentials);

            System.out.println("Finished PowerShell remote session.");

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

ContentLicense: CC BY-SA 3.0

Body:
I need help connecting to a remote server using PowerShell in JAVA. I want the connection to be done in the background, without having a prompt for the password and navigate to the desired location on the server (C:\Events\rootdir\), where I will upload a directory from my local machine.

Currently, I am using the following query:

 String command = "powershell.exe Invoke-Command -Credential myusername -ComputerName 192.x.x.x -FilePath C:\\Events\\rootdir\\
 Process powerShellProcess = Runtime.getRuntime().exec(command);
 powerShellProcess.getOutputStream().close();

However, by doing this I am getting a prompt for the password:

What do I need to do to include the password call in the command string, so that I connect directly to C:\Events\rootdir\, bypassing this password prompt?

Body:
Here is the working code:

public class PowerShellSession {
    private static String subModule = "PowerShellSession";
    String targetIpAddress;
    String username;
    String password;

    public static Object connectPShellLock = new Object();

    public PowerShellSession() {}

    public void exec(String cmd, String credentials)  {

        String ex = credentials +" Invoke-Command -ScriptBlock {" + cmd + "} -ComputerName " + targetIpAddress +" -Credential $mycred";

        String[] args = new String[] { "powershell", ex};
        try {
            execRemote(args);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        String command = "Exit-PSSession";
        String[] args = new String[] { "powershell", command};
        try {
            execRemote(args);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String getCredentials(String domain, String userName,
            String password) throws IOException {
        String creds = "$Username = '"+userName+"';$PlainPassword ='" + password
                + "'; $SecurePassword = ConvertTo-SecureString -AsPlainText $PlainPassword -Force;"
                + "$mycred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword;";
        //creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";

        String[] args = new String[] { "powershell", creds};
        execRemote(args);
        return creds;
    }

    private void execRemote(String[] arguments) throws IOException {
        ProcessBuilder builder = new ProcessBuilder(arguments);
        builder.redirectErrorStream(true);
        Process process = builder.start();
        doProcessIO(process);
    }

    // Do the IO for a passed process
    private void doProcessIO(Process p) throws IOException {
        p.getOutputStream().close();
        String line;
        System.out.println("Output:");
        BufferedReader stdout = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        while ((line = stdout.readLine()) != null) {
            System.out.println(line);
        }
        stdout.close();
        System.out.println("Error:");
        BufferedReader stderr = new BufferedReader(new InputStreamReader(
                p.getErrorStream()));
        while ((line = stderr.readLine()) != null) {
            System.out.println(line);
        }
        stderr.close();
        System.out.println("Done");
    }

    public static void main(String[] args) throws IOException {
        PropertiesFileReader propReader = new PropertiesFileReader(System.getProperty("user.dir")+"/cred.properties");

        String user = propReader.getPropertyData("user");
        String pass = propReader.getPropertyData("pass");
        String ip_add = propReader.getPropertyData("ip");

        PowerShellSession psSession = new PowerShellSession();
        String credentials = psSession.getCredentials(ip_add, user, pass);
        psSession.targetIpAddress = ip_add;//;

        String cmdd = propReader.getPropertyData("command");//"Get-Culture";
        if(!credentials.equals("")) {

            psSession.exec(cmdd, credentials);

            System.out.println("Finished PowerShell remote session.");

        }
        psSession.close();
    }
}


问:
My test stage in GitLab CI won't get picked up by the pipeline
I'm trying to have 2 types of tests run depending on why the pipeline is being run. On commits I'd like to run my build stage, and on merge requests I'd like to run my build and test stages. When I do a commit it runs only build but it also only runs build on Merge Requests.

I've tried specifying only:merge_requests in my .gitlab-ci.yml but it still won't register the stage.

```<code>stages:
  - build
  - deploy
  - test
  - deploy_prod

build:
  image: "python:3.6.1"
  stage: build
  variables:
    GIT_SUBMODULE_STRATEGY: 'recursive'
  script:
    - pip install --upgrade pip
    - pip install -r lender_v2/requirements.txt
    - pip install -r lender_v2/reggora_models/requirements.txt
    - export FLASK_CONFIG=localhost
    - cd lender_v2/smoke_tests && python3 -m unittest discover -p "smoke_*.py" -q --failfast

test:
  image: "python:3.6.1"
  stage: test
  variables:
    GIT_SUBMODULE_STRATEGY: 'recursive'
  script:
    - pip install --upgrade pip
    - pip install -r lender_v2/requirements.txt
    - pip install -r lender_v2/reggora_models/requirements.txt
    - export FLASK_CONFIG=localhost
    - cd lender_v2/test_project && python3 -m unittest discover ../test_project -p "test_*.py" -q --failfast
  only:
    - merge_requests
</code>```

I thought this should run the test stage on merge_requests but it won't run at any time.

答:
Which GitLab and GitLab runner versions are you using?

only: merge_requests was introduced in Gitlab 11.6.

Also, note the information from the Docs:

As of GitLab 11.10, pipelines for merge requests require GitLab Runner
  11.9 or higher due to the recent refspecs changes. Anything lower will cause the pipeline to fail.

Body:
I'm trying to have 2 types of tests run depending on why the pipeline is being run. On commits I'd like to run my build stage, and on merge requests I'd like to run my build and test stages. When I do a commit it runs only build but it also only runs build on Merge Requests.

I've tried specifying only:merge_requests in my .gitlab-ci.yml but it still won't register the stage.

stages:
  - build
  - deploy
  - test
  - deploy_prod

build:
  image: "python:3.6.1"
  stage: build
  variables:
    GIT_SUBMODULE_STRATEGY: 'recursive'
  script:
    - pip install --upgrade pip
    - pip install -r lender_v2/requirements.txt
    - pip install -r lender_v2/reggora_models/requirements.txt
    - export FLASK_CONFIG=localhost
    - cd lender_v2/smoke_tests && python3 -m unittest discover -p "smoke_*.py" -q --failfast

test:
  image: "python:3.6.1"
  stage: test
  variables:
    GIT_SUBMODULE_STRATEGY: 'recursive'
  script:
    - pip install --upgrade pip
    - pip install -r lender_v2/requirements.txt
    - pip install -r lender_v2/reggora_models/requirements.txt
    - export FLASK_CONFIG=localhost
    - cd lender_v2/test_project && python3 -m unittest discover ../test_project -p "test_*.py" -q --failfast
  only:
    - merge_requests

I thought this should run the test stage on merge_requests but it won't run at any time.


问:
Encoding Desktop Duplication API ID3D11Texture2D frame using NvPipe
I'm trying to capture the desktop frames using Desktop Duplication API, and encode them right away with NvPipe without going through CPU access to pixels.

Is there any way to have the ID3D11Texture2D data as an input for NvPipe, or some other efficient way of doing it? I'm working on a VR solution that requires as low latency as possible, so even a 1ms saved is a big deal.

Edit: After following recommendations from @Soonts, I've ended up with this code which doesn't seem to work:

```<code>    cudaArray *array;
    m_DeviceContext->CopySubresourceRegion(CopyBuffer, 0, 0, 0, 0, m_SharedSurf, 0, Box);
    cudaError_t err = cudaGraphicsD3D11RegisterResource(&_cudaResource, CopyBuffer, cudaGraphicsRegisterFlagsNone);
    err = cudaGraphicsResourceSetMapFlags(_cudaResource, cudaGraphicsMapFlagsReadOnly);
    cudaStream_t cuda_stream;
    cudaStreamCreate(&cuda_stream);
    err = cudaGraphicsMapResources(1, &_cudaResource, cuda_stream);
    err = cudaGraphicsSubResourceGetMappedArray(&array, _cudaResource, 0, 0);
    uint64_t compressedSize = NvPipe_Encode(encoder, array, dataPitch, buffer.data(), buffer.size(), width, height, false);
</code>```

The NvPipe_Encode results in a memory access violation and does nothing. I don't know which step I'm messing up, as I can't seem to find any documentation about any of the functions or variables/structures online, and putting watches on variables shows no valuable information other than their address in memory.

答:
I have not tried but I think should be doable with CUDA interop.

Call cudaGraphicsD3D11RegisterResource to register a texture for CUDA interop. Not sure you can register the DWM-owned texture you get from DD. If you can't, make another one (in a default pool), register that one, and update each frame with ID3D11DeviceContext::CopyResource.

Call cudaGraphicsResourceSetMapFlags to specify you want read-only access from CUDA side of the interop.

Call cudaGraphicsMapResources to allow CUDA to access the texture.

Call cudaGraphicsSubResourceGetMappedArray. Now you have a device pointer with the frame data you can give to NvPipe.

P.S. Other option is using media foundation instead of NvPipe. Will work on all GPUs not just nVidia, on most systems MF also uses hardware encoders. I’m not sure about latency, never used MF for anything too sensitive to it, and never used NvPipe at all, have no idea how they compare.

Body:
I'm trying to capture the desktop frames using Desktop Duplication API, and encode them right away with NvPipe without going through CPU access to pixels.

Is there any way to have the ID3D11Texture2D data as an input for NvPipe, or some other efficient way of doing it? I'm working on a VR solution that requires as low latency as possible, so even a 1ms saved is a big deal.

Edit: After following recommendations from @Soonts, I've ended up with this code which doesn't seem to work:

    cudaArray *array;
    m_DeviceContext->CopySubresourceRegion(CopyBuffer, 0, 0, 0, 0, m_SharedSurf, 0, Box);
    cudaError_t err = cudaGraphicsD3D11RegisterResource(&_cudaResource, CopyBuffer, cudaGraphicsRegisterFlagsNone);
    err = cudaGraphicsResourceSetMapFlags(_cudaResource, cudaGraphicsMapFlagsReadOnly);
    cudaStream_t cuda_stream;
    cudaStreamCreate(&cuda_stream);
    err = cudaGraphicsMapResources(1, &_cudaResource, cuda_stream);
    err = cudaGraphicsSubResourceGetMappedArray(&array, _cudaResource, 0, 0);
    uint64_t compressedSize = NvPipe_Encode(encoder, array, dataPitch, buffer.data(), buffer.size(), width, height, false);

The NvPipe_Encode results in a memory access violation and does nothing. I don't know which step I'm messing up, as I can't seem to find any documentation about any of the functions or variables/structures online, and putting watches on variables shows no valuable information other than their address in memory.


问:
How to Identify if the rate of an event (moving average) exceeds a threshold
EDIT Added information

Originally this was just about a general algorithm and language/platform agnostic. However I'm going to answer this question myself and the answer is in fact specific to the tools in use.

This is for event detection on an IBM mainframe under z/OS , using the Ops/MVS automation tool running a REXX script.

So the answers posted may be applicable in Python, Perl, bash, Java etc; it's just that the product being used in this particular case has a specific function that does the trick.

End of added information

My question is very similar to this:

How to calculate continuous smooth event rate based on event times?

and this would be an answer:

This can be implemented with a moving average. Take your last N events
  where N is the size of your averaging window. Compute the time
  difference between the first and the last of these N events. If you
  are measuring in seconds and want the rate in event per minute you
  would then divide 60 seconds by your time difference expressed in
  seconds and you multiply by N-1.

except I'd like to avoid storing information about previous events. I'm also only interested if the moving average exceeds a threshold, so I'm not interested in keeping a trend of  rate.

So for example, I want to know if I get more than 3 events/min. This was my first approach:

When the first event comes in, I create a count of 1 and log the
start time.

When another event comes in, I increment the count and calculate the
rate from the count and the elapsed time

If rate exceed permitted value, generate alert.

I realised this wouldn’t work because if you had an event a week ago and then nothing until 10 events in the last minute, the average ‘rate’ is 11 in a week i.e. 3.6/day, rather than the current rate of 10/min.

So I'm thinking of trying the following:

When the first event comes in, I create a count of 1 and log the
start time.

When another event comes in, if the time since the previous event exceeds the interval over which I want to measure the rate (1 min in my example), I effectively discard the previous event and record a count of 1 and the current time as the new start time (because if it's been over 1 min since the previous event, the rate can't exceed x/min right?).

If the time since the previous event hasn't exceeded the monitoring
interval, increment the count and calculate the rate from the count
and the elapsed time

If rate exceed permitted value, generate alert.

This seems simple but other posts on SO (specifically this question: Estimating rate of occurrence of an event with exponential smoothing and irregular events and it's accepted answer: https://stackoverflow.com/a/23617678/1430420) seem to imply that there's a lot more to it than I think.

答:
Ops/MVS has this functionality built in via the 'OPSTHRSH' function:

https://docops.ca.com/ca-opsmvs/13-5/en/reference-information/command-and-function-reference/ops-rexx-built-in-functions/opsthrsh-function

for this particular scenario, we can invoke it as follows:

```<code>if OPSTHRSH('A',60) > 3 then do something...
</code>```

OPSTHRESH('A',60) will return a count of how many times the current event has triggered for the current address space (task) within a 60 second period. If this value exceeds my trigger level, then take action. 60 seconds after the first event is received, the event count is reset.

Body:
Ops/MVS has this functionality built in via the 'OPSTHRSH' function:

https://docops.ca.com/ca-opsmvs/13-5/en/reference-information/command-and-function-reference/ops-rexx-built-in-functions/opsthrsh-function

for this particular scenario, we can invoke it as follows:

if OPSTHRSH('A',60) > 3 then do something...

OPSTHRESH('A',60) will return a count of how many times the current event has triggered for the current address space (task) within a 60 second period. If this value exceeds my trigger level, then take action. 60 seconds after the first event is received, the event count is reset.


问:
How to add a validation error message next to a field using jQuery
Hi have a form with a few fields. Amongst them:

```<code><div>
    <label for="phoneNumber" class="label">Phone Number</label>
    <input name="phoneNumber" type="text" id="phoneNumber" size="13"  style="float:left;margin-right:10px;">
</div>
<div>
    <input type="checkbox" name="activePN" id="activePN" checked >
    <label for="activePN">Active</label>
</div>
</code>```

The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:

```<code>$('#submit').click(function () {
    var proceed = true;
    var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
    if (strippedPN.length !== 10) {
        $('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
        proceed = false;
    }
...
...
...
});
</code>```

I was hopping that adding those

 tags would do it. But they don't...
Note: I also tried with html() instead of text() and with activePN instead of phoneNumber.

答:
Its best to use jqueryvalidation plugin.

But in some scenario may be you need to show validation message using custom code, then below may help.

Code

```<code>var errorSeen = false;

$('#txtname').keyup(function (e) {

var validInput = false; // TODO set your validation here

if (!validInput) {

  var errorMessageVisible = $(".validationMessage").is(":visible");

  if (errorSeen === false && errorMessageVisible === false) {

      $('#txtname').style.borderColor = "red";

        $('#txtname').after("<span class='validationMessage' style='color:red;'>
                            Name is required.</span>");

        errorSeen = true;
    }

  }
   else {

   $('#txtname').style.borderColor = "";

     var errorMessageVisible = $(".validationMessage").is(":visible");

     if (errorMessageVisible)
        $(".validationMessage").remove();

        errorSeen = false;
  }

});
</code>```

Body:
Hi have a form with a few fields. Amongst them:

    Phone Number
    <input name="phoneNumber" type="text" id="phoneNumber" size="13"  style="float:left;margin-right:10px;">

    <input type="checkbox" name="activePN" id="activePN" checked >
    Active

The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:

$('#submit').click(function () {
    var proceed = true;
    var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
    if (strippedPN.length !== 10) {
        $('#phoneNumber').text('
Phone number has to be 10 digits long.
')
        proceed = false;
    }
...
...
...
});

I was hopping that adding those

 tags would do it. But they don't...
Note: I also tried with html() instead of text() and with activePN instead of phoneNumber.

Body:
Its best to use jqueryvalidation plugin.

But in some scenario may be you need to show validation message using custom code, then below may help.

Code

var errorSeen = false;

$('#txtname').keyup(function (e) {

var validInput = false; // TODO set your validation here

if (!validInput) {

  var errorMessageVisible = $(".validationMessage").is(":visible");

  if (errorSeen === false && errorMessageVisible === false) {

      $('#txtname').style.borderColor = "red";

        $('#txtname').after("<span class='validationMessage' style='color:red;'>
                            Name is required.</span>");

        errorSeen = true;
    }

  }
   else {

   $('#txtname').style.borderColor = "";

     var errorMessageVisible = $(".validationMessage").is(":visible");

     if (errorMessageVisible)
        $(".validationMessage").remove();

        errorSeen = false;
  }

});


问:
Comparing two List<string> for equality
Other than stepping through the elements one by one, how do I compare two lists of strings for equality (in .NET 3.0):

This fails:

```<code>// Expected result.
List<string> expected = new List<string>();
expected.Add( "a" );
expected.Add( "b" );
expected.Add( "c" );

// Actual result
actual = new List<string>();
actual.Add( "a" );
actual.Add( "b" );
actual.Add( "c" );

// Verdict
Assert.IsTrue( actual == expected );
</code>```

答:
It might be used with not regular way but without implementation  IEquatable for Custom types

```<code>JsonConvert.SerializeObject( myList1) == JsonConvert.SerializeObject( myList2)
</code>```

But in general case you could use SequenceEqual as was mentioned in comments https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal?view=netframework-4.8

Also do not forget to implement IEquatable interface for custom types (not necessary for strings type or other structure)

Title: Comparing two List<string> for equality

Body:
Other than stepping through the elements one by one, how do I compare two lists of strings for equality (in .NET 3.0):

This fails:

// Expected result.
List<string> expected = new List<string>();
expected.Add( "a" );
expected.Add( "b" );
expected.Add( "c" );

// Actual result
actual = new List<string>();
actual.Add( "a" );
actual.Add( "b" );
actual.Add( "c" );

// Verdict
Assert.IsTrue( actual == expected );

Body:
It might be used with not regular way but without implementation  IEquatable for Custom types

JsonConvert.SerializeObject( myList1) == JsonConvert.SerializeObject( myList2)

But in general case you could use SequenceEqual as was mentioned in comments https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal?view=netframework-4.8

Also do not forget to implement IEquatable interface for custom types (not necessary for strings type or other structure)