问:
Text after table in Word using VBA codes
I create a Word document using VBA codes and transfer data from Excel to a table I create in the Word document.

I get an error starting a new line/paragraph after the table.

My code selects the whole table but does not start new text after the table, so later content is being added to cell(1,1) in the table.

I am just showing you the structure of my codes and I get an error at the Selection.Collapse line of code.

run time error 438, object doesn't support this property or method.

```<code>Sub Word_Report()
    Dim objWord As Object
    Dim objDoc As Object
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Add()
    With objWord.Selection
        Set myTable = objDoc.Tables.Add(Range:=objWord.Selection.Range, NumRows:=7, NumColumns:=3)
        myTable.Borders.Enable = True

        ''' my table contents'''
    end with

    'start new line after table
    objDoc.Range.InsertAfter Chr(13) & "Hello"
    .Font.Size = 11
    .BoldRun

End sub
</code>```

答:
Edited

Try the following:

```<code>   Sub Word_Report()
    Dim objWord As Object
    Dim objDoc As Object
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Add()

     With objWord.Selection
    Set myTable = objDoc.Tables.Add(Range:=objWord.Selection.Range, NumRows:=7, NumColumns:=3)
      myTable.Borders.Enable = True

    ''' my table contents'''
    End With

    'start new line after table
    objDoc.Range.InsertAfter Chr(13) & "Hello"

    End Sub
</code>```

Use .Range instead of Selection

Body:
I create a Word document using VBA codes and transfer data from Excel to a table I create in the Word document.

I get an error starting a new line/paragraph after the table.

My code selects the whole table but does not start new text after the table, so later content is being added to cell(1,1) in the table.

I am just showing you the structure of my codes and I get an error at the Selection.Collapse line of code.

run time error 438, object doesn't support this property or method.

Sub Word_Report()
    Dim objWord As Object
    Dim objDoc As Object
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Add()
    With objWord.Selection
        Set myTable = objDoc.Tables.Add(Range:=objWord.Selection.Range, NumRows:=7, NumColumns:=3)
        myTable.Borders.Enable = True

        ''' my table contents'''
    end with

    'start new line after table
    objDoc.Range.InsertAfter Chr(13) & "Hello"
    .Font.Size = 11
    .BoldRun

End sub

Body:
Edited

Try the following:

   Sub Word_Report()
    Dim objWord As Object
    Dim objDoc As Object
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Add()

     With objWord.Selection
    Set myTable = objDoc.Tables.Add(Range:=objWord.Selection.Range, NumRows:=7, NumColumns:=3)
      myTable.Borders.Enable = True

    ''' my table contents'''
    End With

    'start new line after table
    objDoc.Range.InsertAfter Chr(13) & "Hello"

    End Sub

Use .Range instead of Selection


来源: stackexchange

问:
Eclipse Autocomplete for PHP Extensions?
I just downloaded and installed the Gearman extension for PHP, and would really like to have autocomplete work for this in Eclipse.

I've been searching through preferences and googling for hours but I haven't been able to come up with anything. I've tried restarting Eclipse as well as adding the php.net manual for Gearman. Nothing seems to make to enable autocomplete or tooltips for Gearman.

Anyone have the same problem?

答: You can view http://www.php-editors.com/review/anjuta.htm its best suited for Web Development Purpose. Also its Eclipse Based. Might Fulfill your requirement.</p>

ContentLicense: CC BY-SA 2.5


问:
DexArchiveBuilderException on compilation after migrating to Gradle Plugin 3.0
I've recently upgraded our android application's gradle plugin from 2.3.3 to 3.0.0. After resolving most of the compilation issues, I'm still plagued with the following exception:

```<code>com.android.build.api.transform.TransformException:
com.android.builder.dexing.DexArchiveBuilderException:
com.android.builder.dexing.DexArchiveBuilderException:
Failed to process /Users/{user}/SourceCode/Android/{project_path}/build/intermediates/transforms/profilers-transform/debug/113.jar
</code>```

The {user} and {project_path} fields are placeholders for the actual values.

I'm not entirely sure exactly what's happening but from the looks of the stacktrace the build is failing to dex one of our third party sdks (Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing com/outbrain/OBSDK/HttpClient/OBHttpClient.class). The odd thing about this though is the fact that the build works as expected if I build the project internally or if I build and generate the apks for both debug and release. Its only when I attempt to deploy the app on the emulator that I receive this error.

Any insight into why this error is occurring would be greatly appreciated.

Note: I've referred to the Google Doc (https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html) and I don't see anything regarding this issue.

Here's the output of the relevant stacktrace:

```<code>Caused by: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /Users/{user}/SourceCode/Android/{project_path}/build/intermediates/transforms/profilers-transform/debug/113.jar
at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:550)
at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.lambda$convertToDexArchive$1(DexArchiveBuilderTransform.java:488)
at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing com/outbrain/OBSDK/HttpClient/OBHttpClient.class

at com.android.builder.dexing.DxDexArchiveBuilder.getExceptionToRethrow(DxDexArchiveBuilder.java:143)
at com.android.builder.dexing.DxDexArchiveBuilder.convert(DxDexArchiveBuilder.java:89)
at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:545)
... 6 more

Caused by: com.android.dx.cf.code.SimException: stack: underflow
at com.android.dx.cf.code.ExecutionStack.throwSimException(ExecutionStack.java:341)
at com.android.dx.cf.code.ExecutionStack.peek(ExecutionStack.java:206)
at com.android.dx.cf.code.ExecutionStack.peekType(ExecutionStack.java:241)
at com.android.dx.cf.code.Simulator$SimVisitor.visitNoArgs(Simulator.java:427)
at com.android.dx.cf.code.BytecodeArray.parseInstruction(BytecodeArray.java:584)
at com.android.dx.cf.code.Simulator.simulate(Simulator.java:103)
at com.android.dx.cf.code.Ropper.processBlock(Ropper.java:790)
at com.android.dx.cf.code.Ropper.doit(Ropper.java:745)
at com.android.dx.cf.code.Ropper.convert(Ropper.java:350)
at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:309)
at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:150)
at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:102)
at com.android.builder.dexing.DxDexArchiveBuilder.dex(DxDexArchiveBuilder.java:107)
at com.android.builder.dexing.DxDexArchiveBuilder.convert(DxDexArchiveBuilder.java:86)
... 7 more
</code>```

Edit: Added project build.gradle to question. Note: Added placeholders for sensitive information:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
allprojects {
    repositories {
        jcenter()
        maven {
            url 'http://dl.bintray.com/optimizely/optimizely'
        }
    }
}

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // The Fabric Gradle plugin uses an open ended version to
        // react quickly to Android tooling updates
        classpath 'io.fabric.tools:gradle:1.+'

        classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'

        // Kotlin Support
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.51'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.jakewharton.hugo'
apply plugin: 'kotlin-android'

repositories {
    jcenter()
    maven {
        url 'https://maven.fabric.io/public'
    }
    maven {
        url "http://appboy.github.io/appboy-android-sdk/sdk"
    }
    maven {
        url  "http://dl.bintray.com/teads/TeadsSDK-android"
    }
    maven {
        url "https://jitpack.io"
    }
    flatDir {
        dirs 'libs'
    }
    google()
}

// Test Dependencies
dependencies {
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:1.10.19'
    testCompile 'org.robolectric:robolectric:3.0'
    testCompile 'org.robolectric:shadows-multidex:3.0'
    testCompile 'org.robolectric:shadows-play-services:3.0'
    testCompile 'org.easytesting:fest-assert-core:2.0M10'
    // testCompile 'org.easytesting:fest-assert:1.4'
    testCompile 'org.powermock:powermock-module-junit4:1.6.4'
    testCompile 'org.powermock:powermock-module-junit4-rule:1.6.4'
    testCompile 'org.powermock:powermock-api-mockito:1.6.4'
    testCompile 'org.powermock:powermock-classloading-xstream:1.6.4'
}

dependencies {

    def appCompatVersion = "25.3.1"
    def playServicesVersion = "11.0.4"

    compile project(':BRShared')
    compile project(':CastCompanionLibrary-android')
    wearApp project(':wear')

    compile fileTree(dir: 'libs', include: '*.jar')

    compile(name: 'sharethrough-android-sdk-v4.4.0', ext: 'aar')
    compile('com.optimizely:optimizely:+@aar') {
        transitive = true
    }

    compile 'com.android.volley:volley:1.0.0'
    compile "com.google.android.gms:play-services:$playServicesVersion"

    compile "com.android.support:support-v4:$appCompatVersion"
    compile "com.android.support:appcompat-v7:$appCompatVersion"
    compile "com.android.support:design:$appCompatVersion"
    compile "com.android.support:cardview-v7:$appCompatVersion"
    compile "com.android.support:recyclerview-v7:$appCompatVersion"
    compile "com.android.support:customtabs:$appCompatVersion"
    compile 'com.android.support:support-v4:19.1.0'
    compile 'com.android.support:multidex:1.0.1'

    compile('com.twitter.sdk.android:tweet-ui:2.3.1@aar') {
        transitive = true;
    }
    compile('com.twitter.sdk.android:twitter-core:2.3.0@aar') {
        transitive = true;
    }

    compile 'com.squareup.okhttp3:okhttp:3.4.2'
    compile 'com.squareup.picasso:picasso:2.5.2'

    compile 'com.appboy:android-sdk-ui:1.19.0'

    // Facebook
    compile 'com.facebook.stetho:stetho:1.3.0'
    compile 'com.facebook.android:audience-network-sdk:4.26.0'
    compile 'com.facebook.android:facebook-android-sdk:4.27.0'

    // Inneractive SDK
    compile(name: 'ia-mraid-kit-release-7.0.5', ext: 'aar')
    compile(name: 'ia-native-kit-release-7.0.5', ext: 'aar')
    compile(name: 'ia-sdk-core-full-release-7.0.5', ext: 'aar')
    compile(name: 'ia-video-kit-release-7.0.5', ext: 'aar')

    compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:crashlytics-ndk:1.1.2@aar') {
        transitive = true;
    }

    compile 'com.jakewharton:butterknife:7.0.1'

    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.outbrain.obsdk:obsdk:2.1.1'
    compile 'org.jetbrains.kotlin:kotlin-stdlib:1.1.3'
    compile files('libs/bluekai.jar')

    // Reactive
    compile 'io.reactivex:rxjava:1.3.0'
    compile 'io.reactivex:rxandroid:1.2.1'

    // ExoPlayer
    compile 'com.google.android.exoplayer:exoplayer:r2.4.0'

    // AdobePass
    compile files('libs/novacorps-adobepass-client-1.1.0.jar')
    compile files('libs/nebula-config-1.3.0.jar')

    // Needed in libs directory to avoid missing MVPD model compile error
    compile files('libs/android_accessenabler-1.9.1.jar')

    // Android Spin Kit UI
    compile 'com.github.ybq:Android-SpinKit:1.1.0'

    // Teads SDK
    compile ('tv.teads.sdk:androidsdk:2.4.14:fullRelease@aar') {
        transitive = true;
    }

    // Material Ripple Layout
    compile 'com.balysv:material-ripple:1.0.2'

    compile 'org.aspectj:aspectjrt:1.8.1'

    // Moshi - JSON Object Mapping
    compile 'com.squareup.moshi:moshi:1.5.0'

    // GIF Image Library - For Animations
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.8'
}

android {
    compileSdkVersion project.compile_sdk_version.toInteger()
    buildToolsVersion project.build_tools_version
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId {application_id}
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        versionCode 31500100
        versionName {version_name}
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        minSdkVersion 19

        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath true
            }
        }
    }
    signingConfigs {
        release {
            keyAlias {key_alias}
            keyPassword {key_password}
            storeFile file({file_name})
            storePassword {store_password}
        }
    }

buildTypes {
        debug {
            minifyEnabled false
            applicationIdSuffix '.debug'
            versionNameSuffix '-DEBUG'
            debuggable true

            buildConfigField "boolean", "DEBUG_FORCE_UNICORN_OFF", "false"
            buildConfigField "boolean", "DEBUG_STETHO", "true"

            // These are the values for the authorities and account types.
            resValue "string", "account_type", "{application_id}.debug.accounttype"
            resValue "string", "authority", "{application_id}.debug"

            resValue "string", "about_version_build", defaultConfig.versionName
            resValue "string", "about_version_suffix", "debug"
            resValue "string", "outbrain_test_mode", "true"
            resValue "bool", "enable_view_server", "true"
            resValue "bool", "hockey_app_auto_upload", "false"

            resValue "string", "base_feed_url", {base_feed_url}
            resValue "string", "path_config", "xmldata/configuration-androidtest"

            resValue "string", "google_now_check_credentials_url", "{google_check_credentials_url}"
            resValue "string", "google_now_add_credentials_url", "{google_add_credentials_url}"
            resValue "string", "google_now_add_activity_url", "{google_add_activity_url}"

            resValue "string", "com_appboy_push_gcm_sender_id", "{sender_id}"
            resValue "string", "com_appboy_api_key", "{api_key}"
        }
        release {
            ext.enableCrashlytics = true
            minifyEnabled false
            debuggable false
            signingConfig signingConfigs.release

            buildConfigField "boolean", "DEBUG_FORCE_UNICORN_OFF", "false"
            buildConfigField "boolean", "DEBUG_STETHO", "false"

            // Reference them again so they get overwritten by the flavor.
            resValue "string", "account_type", "{application_id}.accounttype"
            resValue "string", "authority", "{application_id}"

            resValue "string", "about_version_build", defaultConfig.versionName
            resValue "string", "about_version_suffix", "release"
            resValue "string", "outbrain_test_mode", "false"
            resValue "bool", "enable_view_server", "false"
            resValue "bool", "hockey_app_auto_upload", "true"

            resValue "string", "base_feed_url", "{base_feed_url}"
            resValue "string", "path_config", "xmldata/configuration-androidv4"
            resValue "string", "google_now_check_credentials_url", "{google_check_credentials_url}"
            resValue "string", "google_now_add_credentials_url", "{google_add_credentials_url}"
            resValue "string", "google_now_add_activity_url", "{google_add_activity_url}"

            resValue "string", "com_appboy_push_gcm_sender_id", "{sender_id}"
            resValue "string", "com_appboy_api_key", "{api_key}"
        }
        livesim {
            ext.enableCrashlytics = true
            versionNameSuffix '-LIVE-SIM'
            minifyEnabled false
            debuggable false
            signingConfig signingConfigs.release

            buildConfigField "boolean", "DEBUG_FORCE_UNICORN_OFF", "false"
            buildConfigField "boolean", "DEBUG_STETHO", "false"

            // Reference them again so they get overwritten by the flavor.
            resValue "string", "account_type", "{application_id}.accounttype"
            resValue "string", "authority", "{application_id}"

            resValue "string", "about_version_build", defaultConfig.versionName
            resValue "string", "about_version_suffix", "release"
            resValue "string", "outbrain_test_mode", "false"
            resValue "bool", "enable_view_server", "false"
            resValue "bool", "hockey_app_auto_upload", "true"

            resValue "string", "base_feed_url", "{base_feed_url}"
            resValue "string", "path_config", "xmldata/configuration-androidv4"
            resValue "string", "google_now_check_credentials_url", "{google_check_credentials_url}"
            resValue "string", "google_now_add_credentials_url", "{google_add_credentials_url}"
            resValue "string", "google_now_add_activity_url", "{google_add_activity_url}"

            resValue "string", "com_appboy_push_gcm_sender_id", "{sender_id}"
            resValue "string", "com_appboy_api_key", "{api_key}"

            // Fallback for sub projects
            matchingFallbacks = ['release']
        }
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src/main']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        instrumentTest.setRoot('tests')

        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
        livesim.setRoot('build-types/livesim')
    }
    dexOptions {
        jumboMode true
        preDexLibraries = false
        javaMaxHeapSize "6g"
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
    testOptions {
        unitTests.returnDefaultValues = true
    }
}

android.applicationVariants.all { variant ->
    variant.outputs.all { output ->
        def buildType = variant.variantData.variantConfiguration.buildType.name
        outputFileName = "{Application_Name}-" + (buildType == "release" || buildType == "livesim" ? "release-" : "") + "${variant.versionName}.apk"
    }
}

dependencies {
    compile 'com.android.support.constraint:constraint-layout:+'
}
</code>```

答:
I've found the answer to my question but in case anyone is still searching for an answer, I'll post my solution here:

It turns out the issue was installing the debug build on the emulator/physical device with the Advanced Profiling field enabled. This is a feature that was enabled in Android Studio 3.0 that allows developers to get more precise and detailed information from whats output from the Android Profiler.

The description for the requirements are a little misleading imho. It identifies that its required for API versions less than ver. 26 but that's not the case (at least for me it wasn't). It seems to build successfully only on API versions greater than ver. 26 if you choose to enable it. It may have something to do with the updated Multi-Dex support library where it hasn't flushed out all the methods by the time the Advanced Profiler requires them but there doesn't seem to be any details on whats going on.

If you're running your build on a device less than ver. 26 (i.e. Android O), try disabling the field in your run configurations (its located under the Profiling tab within the Edit Run Configurations window).

Advanced Profiling Field in Run Configurations

Hope that helps!

ContentLicense: CC BY-SA 3.0

Body:
I've recently upgraded our android application's gradle plugin from 2.3.3 to 3.0.0. After resolving most of the compilation issues, I'm still plagued with the following exception:

com.android.build.api.transform.TransformException:
com.android.builder.dexing.DexArchiveBuilderException:
com.android.builder.dexing.DexArchiveBuilderException:
Failed to process /Users/{user}/SourceCode/Android/{project_path}/build/intermediates/transforms/profilers-transform/debug/113.jar

The {user} and {project_path} fields are placeholders for the actual values.

I'm not entirely sure exactly what's happening but from the looks of the stacktrace the build is failing to dex one of our third party sdks (Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing com/outbrain/OBSDK/HttpClient/OBHttpClient.class). The odd thing about this though is the fact that the build works as expected if I build the project internally or if I build and generate the apks for both debug and release. Its only when I attempt to deploy the app on the emulator that I receive this error.

Any insight into why this error is occurring would be greatly appreciated.

Note: I've referred to the Google Doc (https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html) and I don't see anything regarding this issue.

Here's the output of the relevant stacktrace:

Caused by: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /Users/{user}/SourceCode/Android/{project_path}/build/intermediates/transforms/profilers-transform/debug/113.jar
at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:550)
at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.lambda$convertToDexArchive$1(DexArchiveBuilderTransform.java:488)
at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing com/outbrain/OBSDK/HttpClient/OBHttpClient.class

at com.android.builder.dexing.DxDexArchiveBuilder.getExceptionToRethrow(DxDexArchiveBuilder.java:143)
at com.android.builder.dexing.DxDexArchiveBuilder.convert(DxDexArchiveBuilder.java:89)
at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:545)
... 6 more

Caused by: com.android.dx.cf.code.SimException: stack: underflow
at com.android.dx.cf.code.ExecutionStack.throwSimException(ExecutionStack.java:341)
at com.android.dx.cf.code.ExecutionStack.peek(ExecutionStack.java:206)
at com.android.dx.cf.code.ExecutionStack.peekType(ExecutionStack.java:241)
at com.android.dx.cf.code.Simulator$SimVisitor.visitNoArgs(Simulator.java:427)
at com.android.dx.cf.code.BytecodeArray.parseInstruction(BytecodeArray.java:584)
at com.android.dx.cf.code.Simulator.simulate(Simulator.java:103)
at com.android.dx.cf.code.Ropper.processBlock(Ropper.java:790)
at com.android.dx.cf.code.Ropper.doit(Ropper.java:745)
at com.android.dx.cf.code.Ropper.convert(Ropper.java:350)
at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:309)
at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:150)
at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:102)
at com.android.builder.dexing.DxDexArchiveBuilder.dex(DxDexArchiveBuilder.java:107)
at com.android.builder.dexing.DxDexArchiveBuilder.convert(DxDexArchiveBuilder.java:86)
... 7 more

Edit: Added project build.gradle to question. Note: Added placeholders for sensitive information:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
allprojects {
    repositories {
        jcenter()
        maven {
            url 'http://dl.bintray.com/optimizely/optimizely'
        }
    }
}

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // The Fabric Gradle plugin uses an open ended version to
        // react quickly to Android tooling updates
        classpath 'io.fabric.tools:gradle:1.+'

        classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'

        // Kotlin Support
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.51'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.jakewharton.hugo'
apply plugin: 'kotlin-android'

repositories {
    jcenter()
    maven {
        url 'https://maven.fabric.io/public'
    }
    maven {
        url "http://appboy.github.io/appboy-android-sdk/sdk"
    }
    maven {
        url  "http://dl.bintray.com/teads/TeadsSDK-android"
    }
    maven {
        url "https://jitpack.io"
    }
    flatDir {
        dirs 'libs'
    }
    google()
}

// Test Dependencies
dependencies {
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:1.10.19'
    testCompile 'org.robolectric:robolectric:3.0'
    testCompile 'org.robolectric:shadows-multidex:3.0'
    testCompile 'org.robolectric:shadows-play-services:3.0'
    testCompile 'org.easytesting:fest-assert-core:2.0M10'
    // testCompile 'org.easytesting:fest-assert:1.4'
    testCompile 'org.powermock:powermock-module-junit4:1.6.4'
    testCompile 'org.powermock:powermock-module-junit4-rule:1.6.4'
    testCompile 'org.powermock:powermock-api-mockito:1.6.4'
    testCompile 'org.powermock:powermock-classloading-xstream:1.6.4'
}

dependencies {

    def appCompatVersion = "25.3.1"
    def playServicesVersion = "11.0.4"

    compile project(':BRShared')
    compile project(':CastCompanionLibrary-android')
    wearApp project(':wear')

    compile fileTree(dir: 'libs', include: '*.jar')

    compile(name: 'sharethrough-android-sdk-v4.4.0', ext: 'aar')
    compile('com.optimizely:optimizely:+@aar') {
        transitive = true
    }

    compile 'com.android.volley:volley:1.0.0'
    compile "com.google.android.gms:play-services:$playServicesVersion"

    compile "com.android.support:support-v4:$appCompatVersion"
    compile "com.android.support:appcompat-v7:$appCompatVersion"
    compile "com.android.support:design:$appCompatVersion"
    compile "com.android.support:cardview-v7:$appCompatVersion"
    compile "com.android.support:recyclerview-v7:$appCompatVersion"
    compile "com.android.support:customtabs:$appCompatVersion"
    compile 'com.android.support:support-v4:19.1.0'
    compile 'com.android.support:multidex:1.0.1'

    compile('com.twitter.sdk.android:tweet-ui:2.3.1@aar') {
        transitive = true;
    }
    compile('com.twitter.sdk.android:twitter-core:2.3.0@aar') {
        transitive = true;
    }

    compile 'com.squareup.okhttp3:okhttp:3.4.2'
    compile 'com.squareup.picasso:picasso:2.5.2'

    compile 'com.appboy:android-sdk-ui:1.19.0'

    // Facebook
    compile 'com.facebook.stetho:stetho:1.3.0'
    compile 'com.facebook.android:audience-network-sdk:4.26.0'
    compile 'com.facebook.android:facebook-android-sdk:4.27.0'

    // Inneractive SDK
    compile(name: 'ia-mraid-kit-release-7.0.5', ext: 'aar')
    compile(name: 'ia-native-kit-release-7.0.5', ext: 'aar')
    compile(name: 'ia-sdk-core-full-release-7.0.5', ext: 'aar')
    compile(name: 'ia-video-kit-release-7.0.5', ext: 'aar')

    compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:crashlytics-ndk:1.1.2@aar') {
        transitive = true;
    }

    compile 'com.jakewharton:butterknife:7.0.1'

    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.outbrain.obsdk:obsdk:2.1.1'
    compile 'org.jetbrains.kotlin:kotlin-stdlib:1.1.3'
    compile files('libs/bluekai.jar')

    // Reactive
    compile 'io.reactivex:rxjava:1.3.0'
    compile 'io.reactivex:rxandroid:1.2.1'

    // ExoPlayer
    compile 'com.google.android.exoplayer:exoplayer:r2.4.0'

    // AdobePass
    compile files('libs/novacorps-adobepass-client-1.1.0.jar')
    compile files('libs/nebula-config-1.3.0.jar')

    // Needed in libs directory to avoid missing MVPD model compile error
    compile files('libs/android_accessenabler-1.9.1.jar')

    // Android Spin Kit UI
    compile 'com.github.ybq:Android-SpinKit:1.1.0'

    // Teads SDK
    compile ('tv.teads.sdk:androidsdk:2.4.14:fullRelease@aar') {
        transitive = true;
    }

    // Material Ripple Layout
    compile 'com.balysv:material-ripple:1.0.2'

    compile 'org.aspectj:aspectjrt:1.8.1'

    // Moshi - JSON Object Mapping
    compile 'com.squareup.moshi:moshi:1.5.0'

    // GIF Image Library - For Animations
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.8'
}

android {
    compileSdkVersion project.compile_sdk_version.toInteger()
    buildToolsVersion project.build_tools_version
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId {application_id}
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        versionCode 31500100
        versionName {version_name}
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        minSdkVersion 19

        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath true
            }
        }
    }
    signingConfigs {
        release {
            keyAlias {key_alias}
            keyPassword {key_password}
            storeFile file({file_name})
            storePassword {store_password}
        }
    }

buildTypes {
        debug {
            minifyEnabled false
            applicationIdSuffix '.debug'
            versionNameSuffix '-DEBUG'
            debuggable true

            buildConfigField "boolean", "DEBUG_FORCE_UNICORN_OFF", "false"
            buildConfigField "boolean", "DEBUG_STETHO", "true"

            // These are the values for the authorities and account types.
            resValue "string", "account_type", "{application_id}.debug.accounttype"
            resValue "string", "authority", "{application_id}.debug"

            resValue "string", "about_version_build", defaultConfig.versionName
            resValue "string", "about_version_suffix", "debug"
            resValue "string", "outbrain_test_mode", "true"
            resValue "bool", "enable_view_server", "true"
            resValue "bool", "hockey_app_auto_upload", "false"

            resValue "string", "base_feed_url", {base_feed_url}
            resValue "string", "path_config", "xmldata/configuration-androidtest"

            resValue "string", "google_now_check_credentials_url", "{google_check_credentials_url}"
            resValue "string", "google_now_add_credentials_url", "{google_add_credentials_url}"
            resValue "string", "google_now_add_activity_url", "{google_add_activity_url}"

            resValue "string", "com_appboy_push_gcm_sender_id", "{sender_id}"
            resValue "string", "com_appboy_api_key", "{api_key}"
        }
        release {
            ext.enableCrashlytics = true
            minifyEnabled false
            debuggable false
            signingConfig signingConfigs.release

            buildConfigField "boolean", "DEBUG_FORCE_UNICORN_OFF", "false"
            buildConfigField "boolean", "DEBUG_STETHO", "false"

            // Reference them again so they get overwritten by the flavor.
            resValue "string", "account_type", "{application_id}.accounttype"
            resValue "string", "authority", "{application_id}"

            resValue "string", "about_version_build", defaultConfig.versionName
            resValue "string", "about_version_suffix", "release"
            resValue "string", "outbrain_test_mode", "false"
            resValue "bool", "enable_view_server", "false"
            resValue "bool", "hockey_app_auto_upload", "true"

            resValue "string", "base_feed_url", "{base_feed_url}"
            resValue "string", "path_config", "xmldata/configuration-androidv4"
            resValue "string", "google_now_check_credentials_url", "{google_check_credentials_url}"
            resValue "string", "google_now_add_credentials_url", "{google_add_credentials_url}"
            resValue "string", "google_now_add_activity_url", "{google_add_activity_url}"

            resValue "string", "com_appboy_push_gcm_sender_id", "{sender_id}"
            resValue "string", "com_appboy_api_key", "{api_key}"
        }
        livesim {
            ext.enableCrashlytics = true
            versionNameSuffix '-LIVE-SIM'
            minifyEnabled false
            debuggable false
            signingConfig signingConfigs.release

            buildConfigField "boolean", "DEBUG_FORCE_UNICORN_OFF", "false"
            buildConfigField "boolean", "DEBUG_STETHO", "false"

            // Reference them again so they get overwritten by the flavor.
            resValue "string", "account_type", "{application_id}.accounttype"
            resValue "string", "authority", "{application_id}"

            resValue "string", "about_version_build", defaultConfig.versionName
            resValue "string", "about_version_suffix", "release"
            resValue "string", "outbrain_test_mode", "false"
            resValue "bool", "enable_view_server", "false"
            resValue "bool", "hockey_app_auto_upload", "true"

            resValue "string", "base_feed_url", "{base_feed_url}"
            resValue "string", "path_config", "xmldata/configuration-androidv4"
            resValue "string", "google_now_check_credentials_url", "{google_check_credentials_url}"
            resValue "string", "google_now_add_credentials_url", "{google_add_credentials_url}"
            resValue "string", "google_now_add_activity_url", "{google_add_activity_url}"

            resValue "string", "com_appboy_push_gcm_sender_id", "{sender_id}"
            resValue "string", "com_appboy_api_key", "{api_key}"

            // Fallback for sub projects
            matchingFallbacks = ['release']
        }
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src/main']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        instrumentTest.setRoot('tests')

        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
        livesim.setRoot('build-types/livesim')
    }
    dexOptions {
        jumboMode true
        preDexLibraries = false
        javaMaxHeapSize "6g"
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
    testOptions {
        unitTests.returnDefaultValues = true
    }
}

android.applicationVariants.all { variant ->
    variant.outputs.all { output ->
        def buildType = variant.variantData.variantConfiguration.buildType.name
        outputFileName = "{Application_Name}-" + (buildType == "release" || buildType == "livesim" ? "release-" : "") + "${variant.versionName}.apk"
    }
}

dependencies {
    compile 'com.android.support.constraint:constraint-layout:+'
}


问:
Restrict delete of master record if it has children
How can I restrict delete of a master record if it has children in a Firebird database.</p>

答:
You need to add a foreign key from the child table to the parent table. The default behavior of a foreign key will prevent deletion of records from the parent table if there are child records.

For example

```<code>create table parent (
    id integer generated by default as identity primary key
);

create table child (
    id integer generated by default as identity primary key,
    parent_id integer references parent(id)
);
</code>```

This will also prevent you from adding records to child with parent_id values (other than null) that do not exist in parent. You can further modify the behavior of the foreign key constraint using on update and on delete clauses. See the Firebird language reference on constraints. For example using on delete cascade will delete rows from the child table if the parent record is deleted.

A foreign key can only point to a primary key or a unique key.

The above code is intentionally short, you should consider using named constraints for both primary and foreign key constraints, as it will simplify future maintenance, check the language reference for details.

Body:
You need to add a foreign key from the child table to the parent table. The default behavior of a foreign key will prevent deletion of records from the parent table if there are child records.

For example

create table parent (
    id integer generated by default as identity primary key
);

create table child (
    id integer generated by default as identity primary key,
    parent_id integer references parent(id)
);

This will also prevent you from adding records to child with parent_id values (other than null) that do not exist in parent. You can further modify the behavior of the foreign key constraint using on update and on delete clauses. See the Firebird language reference on constraints. For example using on delete cascade will delete rows from the child table if the parent record is deleted.

A foreign key can only point to a primary key or a unique key.

The above code is intentionally short, you should consider using named constraints for both primary and foreign key constraints, as it will simplify future maintenance, check the language reference for details.

ContentLicense: CC BY-SA 4.0


问:
Have image that needs to take up full width on all screen sizes. Zoom in on larger screen to prevent fill bars on sides
This is what I have so far

```<code><img style="height:auto; overflow-y:hidden; width:100%;"
src="/static/images/cover.jpg">
</code>```

This does not seems to solve the problem. I have tried to add

```<code> will-change: transform, top;
</code>```

Desired Output:

Since the image is not 1920px wide on the larger sized monitors it receives fill bars on the sides. I'd like this image to instead always go to the full width of the window. (even when zooming and out) And when the browser window becomes smaller the image will get cropped in. I'd also like to be able to control the image by having the bottom of the image visible in all cases. Aspect ratio should be maintained.

答:
It sounds like you’re wanting the imagine to go outside the bounds of the container. You have two options really;

a) take the image outside of the container that is restricting the image from being 100% width of the screen. Note: 100% width is merely 100% width of the container, not of the viewport

b) use JavaScript to detect the distance from either side of the image to the edge of the window and set a negative margin to ‘pull’ the image towards the edges of the window

Body:
This is what I have so far

This does not seems to solve the problem. I have tried to add

 will-change: transform, top;

Desired Output:

Since the image is not 1920px wide on the larger sized monitors it receives fill bars on the sides. I'd like this image to instead always go to the full width of the window. (even when zooming and out) And when the browser window becomes smaller the image will get cropped in. I'd also like to be able to control the image by having the bottom of the image visible in all cases. Aspect ratio should be maintained.


问:
How do I get these SVG fonts to work?
I need to dynamically make an SVG in my web app and to do so I'm making an SVG in Corel and modifying that template file in Node.js as needed. This works except for fonts. For this project I need my text as text, not curves, because I need to modify it. I'm using Century Gothic. I was using embedded fonts, but apparently those are no longer supported by Chrome and Edge. However, if I used linked fonts the file renders improperly if the user doesn't have the font installed. In either of these error cases the browser defaults to Times New Roman. What can I do to get Century Gothic to render in all browsers in an SVG?</p>

答: You'll need a web font. Century Gothic is not freely available, so you have to either buy a license, or use an open source alternative. Muli seems to be considered as a good alternative. For how to use an external font provider, see this.</p>

Title: How do I get these SVG fonts to work?


问:
AWS CloudWatch alert on every change in metric
Can you set up CloudWatch to fire an event (which can lead to a Lambda function being called) on every change to a metric? I can see how to fire an even when it meets a boundary via alerts, but I'd like an event on every change.</p>

答:
No.

A CloudWatch Alarm is triggered when a calculated metric goes outside a given bound over a desired time period. It is always a calculated value (eg average, sum, min, max) and is not based upon an individual metric.

That said, if you have very sparse metrics (that don't trigger very often), using COUNT or SUM might be sufficient but it isn't specifically what you are requesting.


问:
how can i convert from php curl to java
I am looking to try  convert curl to JAVA code. cURL code in php work perfect but in java theres porblem this is code php

```<code>$urlt="http://api.xxxxxxx/xxxxx";
        $apikey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        $camp="id";

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL,$urlt);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('apikey' => $apikey, 'apif' => 'ge', 'camp' => $camp));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $server_output = curl_exec ($ch);

            curl_close ($ch);
</code>```

and this is my convert to java

```<code>String apikey="xxxxxxx";
        String camp="17";
        URL url = new URL("http://xxxxxxx/xxxxxxxx");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setRequestMethod("POST");

        con.setInstanceFollowRedirects(true);

        String postData = "apikey"+apikey+"apif=ge"+"camp"+camp; // I need somthing like this
        con.setRequestProperty("Content-length", String.valueOf(postData.length()));

        con.setDoOutput(true);
        con.setDoInput(true);

        DataOutputStream output = new DataOutputStream(con.getOutputStream());
        output.writeBytes(postData);
        output.close();

        int code = con.getResponseCode(); // 200 = HTTP_OK
        System.out.println("Response    (Code):" + code);
        System.out.println("Response (Message):" + con.getResponseMessage());

        DataInputStream input = new DataInputStream(con.getInputStream());
        int c;
        StringBuilder resultBuf = new StringBuilder();
        while ( (c = input.read()) != -1) {
            resultBuf.append((char) c);
        }
        input.close();

        return resultBuf.toString();
</code>```

and this is the out put

Response    (Code):200
Response (Message):OK
API KEY REQUIRED

答:
You're not encoding your parameters correctly. You're missing an = and the & separators:

```<code>"apikey="+apikey+"&apif=ge"+"&camp="+camp
</code>```

If there's a way of having the library do the encoding for you, as you do in the CURL example using an array(...), that's usually a lot safer.

Title: how can i convert from php curl to java

Body:
I am looking to try  convert curl to JAVA code. cURL code in php work perfect but in java theres porblem this is code php

$urlt="http://api.xxxxxxx/xxxxx";
        $apikey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        $camp="id";

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL,$urlt);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('apikey' => $apikey, 'apif' => 'ge', 'camp' => $camp));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $server_output = curl_exec ($ch);

            curl_close ($ch);

and this is my convert to java

String apikey="xxxxxxx";
        String camp="17";
        URL url = new URL("http://xxxxxxx/xxxxxxxx");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setRequestMethod("POST");

        con.setInstanceFollowRedirects(true);

        String postData = "apikey"+apikey+"apif=ge"+"camp"+camp; // I need somthing like this
        con.setRequestProperty("Content-length", String.valueOf(postData.length()));

        con.setDoOutput(true);
        con.setDoInput(true);

        DataOutputStream output = new DataOutputStream(con.getOutputStream());
        output.writeBytes(postData);
        output.close();

        int code = con.getResponseCode(); // 200 = HTTP_OK
        System.out.println("Response    (Code):" + code);
        System.out.println("Response (Message):" + con.getResponseMessage());

        DataInputStream input = new DataInputStream(con.getInputStream());
        int c;
        StringBuilder resultBuf = new StringBuilder();
        while ( (c = input.read()) != -1) {
            resultBuf.append((char) c);
        }
        input.close();

        return resultBuf.toString();

and this is the out put

Response    (Code):200
Response (Message):OK
API KEY REQUIRED

Body:
You're not encoding your parameters correctly. You're missing an = and the & separators:

"apikey="+apikey+"&apif=ge"+"&camp="+camp

If there's a way of having the library do the encoding for you, as you do in the CURL example using an array(...), that's usually a lot safer.


答:
why not using background instead of ? See below:

div {
  height: 100vh;
  width: 100vw;
  background: url('http://imgsv.imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg') bottom no-repeat;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
</div></code>```

We set a background using background: url('img/path-to-image.png') (...);

We want to always see the bottom of the image so we use background: (...) bottom

The background will cover the entire div using background-size: cover;

Our div should fit the entire user screen, we do it thanks to: height: 100vh; width: 100vw;

vw, vh: Respectively these are 1/100th of the width of the viewport, and 1/100th of the height of the viewport. Again, these are not as widely supported as rems.
CSS units - MDN

Title: Have image that needs to take up full width on all screen sizes. Zoom in on larger screen to prevent fill bars on sides

Body:
why not using background instead of <img>? See below:

div {
  height: 100vh;
  width: 100vw;
  background: url('http://imgsv.imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg') bottom no-repeat;
  background-size: cover;
}

<div>
</div>

We set a background using background: url('img/path-to-image.png') (...);

We want to always see the bottom of the image so we use background: (...) bottom

The background will cover the entire div using background-size: cover;

Our div should fit the entire user screen, we do it thanks to: height: 100vh; width: 100vw;

vw, vh: Respectively these are 1/100th of the width of the viewport, and 1/100th of the height of the viewport. Again, these are not as widely supported as rems.
CSS units - MDN


问:
wkhtmltopdf Default Settings?
I am using laravel-snappy
as a wrapper for wkhtmltopdf for creating PDFs out of HTML.

While running the same code with the same configuration, I am getting different outputs:

CentOS output:  (centered correctly but with big margin at the bottom)

macOS output:  (right part is cropped, and also theres a big margin at the bottom)

Both environments are using wkhtmltopdf 0.12.4 (with patched qt), any ideas for this difference?

答:
Wkhtmltopdf relies on Qt Webkit to do the headless rendering of a PDF. Qt Webkit is cross-platform, but uses different APIs between CentOS and MacOS.

There is a Github issue that, while closed, still has people reporting similar problems in the 12.4 version when using an X11 version of Qt Webkit. The last comment is from someone who reported that solutions like @kerrin's do not work for them, so maybe you are having the same problem.

I am running an older version of Wkhtmltopdf on CentOS in production and MacOS locally, and have not noticed problems like this.

Try an older version like 0.12.1, and if you still notice the issue, then try to use the --dpi and --disable-smart-shrinking flags.

Title: wkhtmltopdf Default Settings?


问:
Haskell: Check for distinct value within three variables & count distinct variables
I'm new to Haskell and trying to figure out how I could realise the following two functions.

Input 3 integers and check if two of them are equal (e.g. 1,2,2 -> true and 1,2,3 -> false)

Input 3 integers and count different values (e.g. 1,1,2 -> 2)

Thank you very much.

答:
sort and group elements and count the equivalence classes, which will give you the count of distinct elements

```<code>distinct = length . group . sort
</code>```

use the above definition, if there are duplicates the number of distinct elements will be less than the number of elements.

```<code>dups = liftM2 (/=) length distinct
</code>```

this is a fancier way of writing it simply

```<code>dups x = length x /= distinct x
</code>```

Body:
sort and group elements and count the equivalence classes, which will give you the count of distinct elements

distinct = length . group . sort

use the above definition, if there are duplicates the number of distinct elements will be less than the number of elements.

dups = liftM2 (/=) length distinct

this is a fancier way of writing it simply

dups x = length x /= distinct x


问:
PHP SQL - Json like search
I'm sending json via dataloader like this:

```<code>{"person":{"name":[{"tag":"peter"},{"tag":"frank"},{"tag":"jeff"}]}}
</code>```

I have the below query and as of right now I filter by exact values. But how do I search 'like' for the values this example?

php:

```<code>...

$arr = json_decode($data,true);

$name = $arr['person']['name'];
foreach($name as $t=>$tag){
    $name[] = $tag['tag'];
}

$query = "SELECT name, id
          FROM accounts
          WHERE visible != '1'";
if ($name) {
    $query.=" AND name IN ('".implode("', '", $name)."')";
}
    $query.=" ORDER BY name DESC";

...
</code>```

答:
Theoretically and not recommended since it will not be very performant, you could use OR (not tested):

```<code>$name = $arr['person']['name'];

if ($name) {
  $arr = [];
  foreach($name as $t=>$tag){
    $n = $tag['tag'];
    $arr[] = “(name LIKE ‘%$n%’)”;
  }
  $query .= “ AND (“ . implode(“ OR “, $arr) . “)”;
}
</code>```

But I think you should re-structure your data to either use JSON column and then you could search the data (e.g. take a look at this SO question).

Or the other option (which complies more to a normalized db structure) is to put the names in their own table, join the table to the accounts table and search do a simple LIKE search.

Title: PHP SQL - Json like search

Body:
I'm sending json via dataloader like this:

{"person":{"name":[{"tag":"peter"},{"tag":"frank"},{"tag":"jeff"}]}}

I have the below query and as of right now I filter by exact values. But how do I search 'like' for the values this example?

php:

...

$arr = json_decode($data,true);

$name = $arr['person']['name'];
foreach($name as $t=>$tag){
    $name[] = $tag['tag'];
}

$query = "SELECT name, id
          FROM accounts
          WHERE visible != '1'";
if ($name) {
    $query.=" AND name IN ('".implode("', '", $name)."')";
}
    $query.=" ORDER BY name DESC";

...

Body:
Theoretically and not recommended since it will not be very performant, you could use OR (not tested):

$name = $arr['person']['name'];

if ($name) {
  $arr = [];
  foreach($name as $t=>$tag){
    $n = $tag['tag'];
    $arr[] = “(name LIKE ‘%$n%’)”;
  }
  $query .= “ AND (“ . implode(“ OR “, $arr) . “)”;
}

But I think you should re-structure your data to either use JSON column and then you could search the data (e.g. take a look at this SO question).

Or the other option (which complies more to a normalized db structure) is to put the names in their own table, join the table to the accounts table and search do a simple LIKE search.


问:
Opening sockets between 2 Android phones
Is it possible to open a socket between 2 Android phones?  How can this be done so the devices can communicate between each other?</p>

答:
Using Socket Programming with Android is a very good read on the topic, it explains how to do Socket Programming with Android and also lists some useful example.

Also, this discussion lists some very useful pointers for Socket Programming on Android Platform


问:
How to use map with list
So I have a population.csv file while looks like this:

```<code>country,population_size
Afghanistan,32758020
Albania,2889104
Algeria,39113313
American Samoa,55437
Andorra,79223
Angola,26920466
Antigua and Barbuda,98875
Argentina,42981515
</code>```

I separated them line by line using this

```<code>val file_population = "population.csv"
def get_csv_file(file: String) : List[String] =
{
    val body = scala.io.Source.fromFile(file_population).mkString
    body.split("\n").toList
}
</code>```

After that I need to split the strings according to the commas. This generate a Map from country names to population sizes.

I tried to do it and currently have the following:

```<code>def process_pops(lines: List[String]) : Map[String, Long] =
{
    val seperated = for ( line <- lines ) yield (line.split(",").toList(0), (line.split(",").toList(1)).toLong )
    for ( i <- seperated)
    {
        val map = Map(seperated(0) -> seperated(1))
    }

}
</code>```

Please note that  immutable map is only allowed
but I am sure that it is wrong. Please help

Thanks for your time

答:
You can do this all a little bit nicer using some built-in functions like .toMap and pattern matching:

```<code>def process_pops(lines: List[String]) : Map[String, Long] = {

  // Remove the first line that is the headers
  val withoutHeaders = lines.tail

  // Map over each line
  val tuples: List[(String, Long)] = withoutHeaders.map(line => {

    // Split the line on the commas into its two parts
    val Array(country, pop) = line.split(",")

    // Return a tuple of type Tuple2[String, Long]
    country -> pop.toLong
  })

  // Convert the List of Tuples to a Map
  tuples.toMap
}
</code>```

You could also do it with a fold, where we would start with an empty map, and for each line, add a new entry to the map:

```<code>def process_pops(lines: List[String]) : Map[String, Long] = {
  lines.tail.foldLeft(Map.empty[String, Long]) {
    case (map, line) =>
      val Array(country, pop) = line.split(",")
      map + (country -> pop.toLong)
  }
}
</code>```

Title: How to use map with list

Body:
So I have a population.csv file while looks like this:

country,population_size
Afghanistan,32758020
Albania,2889104
Algeria,39113313
American Samoa,55437
Andorra,79223
Angola,26920466
Antigua and Barbuda,98875
Argentina,42981515

I separated them line by line using this

val file_population = "population.csv"
def get_csv_file(file: String) : List[String] =
{
    val body = scala.io.Source.fromFile(file_population).mkString
    body.split("\n").toList
}

After that I need to split the strings according to the commas. This generate a Map from country names to population sizes.

I tried to do it and currently have the following:

def process_pops(lines: List[String]) : Map[String, Long] =
{
    val seperated = for ( line <- lines ) yield (line.split(",").toList(0), (line.split(",").toList(1)).toLong )
    for ( i <- seperated)
    {
        val map = Map(seperated(0) -> seperated(1))
    }

}

Please note that  immutable map is only allowed
but I am sure that it is wrong. Please help

Thanks for your time

Body:
You can do this all a little bit nicer using some built-in functions like .toMap and pattern matching:

def process_pops(lines: List[String]) : Map[String, Long] = {

  // Remove the first line that is the headers
  val withoutHeaders = lines.tail

  // Map over each line
  val tuples: List[(String, Long)] = withoutHeaders.map(line => {

    // Split the line on the commas into its two parts
    val Array(country, pop) = line.split(",")

    // Return a tuple of type Tuple2[String, Long]
    country -> pop.toLong
  })

  // Convert the List of Tuples to a Map
  tuples.toMap
}

You could also do it with a fold, where we would start with an empty map, and for each line, add a new entry to the map:

def process_pops(lines: List[String]) : Map[String, Long] = {
  lines.tail.foldLeft(Map.empty[String, Long]) {
    case (map, line) =>
      val Array(country, pop) = line.split(",")
      map + (country -> pop.toLong)
  }
}


问:
Python console keeps asking for user input more times than coded for
I am trying to learn functions and have created a little code def function to find out whether the measurements given will produce a right angled triangle. However whenever I try to run it, I am being asked the same question more than once.

The current code that I have produced is:

```<code>def is_rightangle():
    a=int(input("Enter a triangle length: "))
    b=int(input("Enter a triangle length: "))
    c=int(input("Enter a triangle length: "))

if (a*a + b*b == c*c or c*c + b*b == a*a or a*a + c*c == b*b):
    return True
else:
    return False

is_rightangle()
print (is_rightangle())
</code>```

The console returns Enter a triangle length: 6 times instead of 3, a value for a, b, and c.

From what I can see I have not asked Python to ask the question more than 3 times, which is why I am confused.

答:
When you write this:

```<code>is_rightangle()
print (is_rightangle())
</code>```

You are doing two things. First, you call is_rightangle(), and that evaluates to either True or False. But, that value doesn't have any effect, and since the line is over, it goes to the next line. In the print statement, you are trying to print the value of is_rightangle() (which is being called for a second time, which is why you get six inputs instead of three).

What I would do is just remove the first call to is_rightangle().

```<code>def is_rightangle():
    a=int(input("Enter a triangle length: "))
    b=int(input("Enter a triangle length: "))
    c=int(input("Enter a triangle length: "))

if (a*a + b*b == c*c or c*c + b*b == a*a or a*a + c*c == b*b):
    return True
else:
    return False

print (is_rightangle())
</code>```

Body:
I am trying to learn functions and have created a little code def function to find out whether the measurements given will produce a right angled triangle. However whenever I try to run it, I am being asked the same question more than once.

The current code that I have produced is:

def is_rightangle():
    a=int(input("Enter a triangle length: "))
    b=int(input("Enter a triangle length: "))
    c=int(input("Enter a triangle length: "))

if (a*a + b*b == c*c or c*c + b*b == a*a or a*a + c*c == b*b):
    return True
else:
    return False

is_rightangle()
print (is_rightangle())

The console returns Enter a triangle length: 6 times instead of 3, a value for a, b, and c.

From what I can see I have not asked Python to ask the question more than 3 times, which is why I am confused.

Body:
When you write this:

is_rightangle()
print (is_rightangle())

You are doing two things. First, you call is_rightangle(), and that evaluates to either True or False. But, that value doesn't have any effect, and since the line is over, it goes to the next line. In the print statement, you are trying to print the value of is_rightangle() (which is being called for a second time, which is why you get six inputs instead of three).

What I would do is just remove the first call to is_rightangle().

def is_rightangle():
    a=int(input("Enter a triangle length: "))
    b=int(input("Enter a triangle length: "))
    c=int(input("Enter a triangle length: "))

if (a*a + b*b == c*c or c*c + b*b == a*a or a*a + c*c == b*b):
    return True
else:
    return False

print (is_rightangle())


问:
@ExceptionHandler null pointer in console after spring-boot upgrade
Today, I was feeling a bit lucky, so I upgraded from Spring boot 1.5.1 to the latest. When I run my JAR file, everything seems fine at first.

However, when I make a call that is expected to return an error response (negative test - say "record not found"), it returns a properly formatted JSON response as expected.

However, I also notice a giant stack-trace in the console.

There is a WARN level log which mentions a null pointer somewhere.

```<code>WARN  o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver -
Failed to invoke @ExceptionHandler method: protected org.springframework.http.ResponseEntity<?>     com.sgb.AbstractBaseController.handle(com.sgb.panic.CustomSgbException,org.springframework.web.context.request.WebRequest)
java.lang.NullPointerException: null
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:384)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:59)
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136)
    at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:74)
    at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1218)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1030)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:664)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
</code>```

It was working perfectly fine before I upgraded to the latest spring boot 1.5.3.
When I switched back to 1.5.1, the stack trace goes away.
I switch to 1.5.3, it comes back.

What gives?
Appreciate any pointers.

EDIT:
When I change the logging level of spring framework to DEBUG, I see that immediately after the above stack trace is logged, it attempts to call the ExceptionHandler again and succeeds the second time - which explains why a valid error response was coming despite the stack trace.

The question then becomes why :

```<code> o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Invoking @ExceptionHandler method
</code>```

the first invocation to @ExceptionHandler method is failing.

EDIT:
This SO post also refers to this problem.

In my case, I have an AbstractBaseController class that all my controllers extend where all the exception handling occurs instead of having a separate ControllerAdvice for my Rest endpoint.

I attempted to create a separate ControllerAdvice for handling all exceptions. It works for all my custom exceptions, however when validation failure triggered by @Valid (JSR-303) occurs, it does not get seem to trigger my custom ExceptionHandler in my ControllerAdvice for MethodArgumentNotValidException. This results in an empty 400 with no error message when JSR 303 validations fail.

So I need to move all my exception handlers back into the superclass for the controllers which results in the original WARN message in the log. This is less than ideal.

答:
I was in the same problem with the 1.5.3-RELEASE version.

Upgrading to the 1.5.8-RELEASE solved the bug.

Body:
Today, I was feeling a bit lucky, so I upgraded from Spring boot 1.5.1 to the latest. When I run my JAR file, everything seems fine at first.

However, when I make a call that is expected to return an error response (negative test - say "record not found"), it returns a properly formatted JSON response as expected.

However, I also notice a giant stack-trace in the console.

There is a WARN level log which mentions a null pointer somewhere.

WARN  o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver -
Failed to invoke @ExceptionHandler method: protected org.springframework.http.ResponseEntity<?>     com.sgb.AbstractBaseController.handle(com.sgb.panic.CustomSgbException,org.springframework.web.context.request.WebRequest)
java.lang.NullPointerException: null
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:384)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:59)
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136)
    at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:74)
    at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1218)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1030)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:664)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

It was working perfectly fine before I upgraded to the latest spring boot 1.5.3.
When I switched back to 1.5.1, the stack trace goes away.
I switch to 1.5.3, it comes back.

What gives?
Appreciate any pointers.

EDIT:
When I change the logging level of spring framework to DEBUG, I see that immediately after the above stack trace is logged, it attempts to call the ExceptionHandler again and succeeds the second time - which explains why a valid error response was coming despite the stack trace.

The question then becomes why :

 o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Invoking @ExceptionHandler method

the first invocation to @ExceptionHandler method is failing.

EDIT:
This SO post also refers to this problem.

In my case, I have an AbstractBaseController class that all my controllers extend where all the exception handling occurs instead of having a separate ControllerAdvice for my Rest endpoint.

I attempted to create a separate ControllerAdvice for handling all exceptions. It works for all my custom exceptions, however when validation failure triggered by @Valid (JSR-303) occurs, it does not get seem to trigger my custom ExceptionHandler in my ControllerAdvice for MethodArgumentNotValidException. This results in an empty 400 with no error message when JSR 303 validations fail.

So I need to move all my exception handlers back into the superclass for the controllers which results in the original WARN message in the log. This is less than ideal.


问:
How can I hide my JavaScript functions so that nobody can steal them?

Possible Duplicate:

  How to prevent your JavaScript code from being stolen, copied, and viewed ?

I have a user form that has a submit button. Once clicked, a certain JS function is called and the code does something. I want to hide this so that nobody can see it. What is the best way to do this? I am not using any JS libraries, it is just code that I wrote myself.

Thanks!

答:
You can't entirely.

The best option is to obfuscate it, but then it is still delivered to the client's browser, and they can read it (albeit obfuscated).

There are other ways to obscure it such as serving it via a custom handler that requires some kind of authentication, but ultimately its security through obscurity which is no security at all.


问:
Numbers with leading zeroes, using vb6
How can I add leading zeroes to a number?
For example:

```<code>Dim stracctnumber as String
stracctnumber = 987654321
</code>```

If stracctnumber is less than 15 characters, then add leading zeroes to the account number.

The final number should be

```<code>stracctnumber = "000000987654321"
</code>```

Can anyone help me?

答:
B8 = Format((Format(B2, "###,###")), "@@@@@@@")

This is to add spaces to left.

WORKS GREAT in VBA Excel.....

Title: Numbers with leading zeroes, using vb6

Body:
How can I add leading zeroes to a number?
For example:

Dim stracctnumber as String
stracctnumber = 987654321

If stracctnumber is less than 15 characters, then add leading zeroes to the account number.

The final number should be

stracctnumber = "000000987654321"

Can anyone help me?


问:
Use of Python in web develpment
Right now i am learning python and i want to start doing web development with Python.

I wanted to know about the different types of things we can do with python in web development.

答:
I'd highly recommend learning HTML, JS, and CSS. It is essential for web development. It should be fairly straightforward though, especially compared to learning python. I expect you'll pick it up quickly.

I'm not sure you'd really understand the underpinnings of frameworks like Django without those first.

I'm sure you can learn it as you go though.

Good luck.

Title: Use of Python in web develpment


问:
cx_Oracle Setting large value for CLOB var fails with cx_Oracle.DatabaseError: ORA-03146: Invalid buffer length for TTC field
I'm attempting to set a very large value (>536MB) into a cx_oracle CLOB variable, but it appears to be failing around the 512MB mark.

```<code>conn = cx_Oracle.connect('foo/bar@baz')
cur = conn.cursor()
clob = cur.var(cx_Oracle.CLOB)

# The following is successful
clob.setvalue(0, 'A' * 1024 * 1024 * 511)

# The following fails
clob.setvalue(0, 'A' * 1024 * 1024 * 512)
</code>```

The second command (or any value greater than this) fails with:

```<code>cx_Oracle.DatabaseError: ORA-03146: Invalid buffer length for TTC field
</code>```

After making exactly three calls to the second command, the session itself appears to be disconnected (whereas this does not happen with the first command)

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cx_Oracle.OperationalError: ORA-03135: connection lost contact
Process ID: 17567
Session ID: 137 Serial number: 9226
</code>```

I've tested this on two environments with identical results: Python on my local environment connecting to my local Oracle; and python on a remote unix environment connecting to a different remote Oracle environment. Both of them fail at the exact same 1024 * 1024 * 512 line, which leads me to believe the issue may be with cx_Oracle.

Database version: Oracle 12CR1

Oracle Client version: 12.1.0.2.0

cx_Oracle version: Tested on 5.1.3 and 6.0.3 with identical results

Python version: 2.7.13

Everything is 64 bit.

My use case is that I need to call an PLSQL procedure to insert the CLOB into a database. Our project is following a specific ERP rule set and we are not allowed to do a direct DML. I have code similar to the following:

```<code>data = get_user_provided_data()

conn = cx_Oracle.connect('foo/bar@baz')
cur = conn.cursor()
clob = cur.var(cx_Oracle.CLOB)
clob.setvalue(0, data)

cur.callproc('xxfoo_bar_pkg.insert_one',
               keywordParameters={
                   'p_data_i': clob,
               })
</code>```

答:
Thanks to Anthony Tuininga for his response over at the github repo.

This apparently is a bug, but the following is an effective workaround, which involves changing the PLSQL to use an OUT param for the CLOB, and using Oracle's empty_clob to instantiate the value. This will return a LOB locator back to python, which is kind of like a pointer to the LOB value. You can write to the lob locator, followed by a commit, which will write the value to the DB. I'm not clear on the network implications of of this but the performance seems to be similar to

DDLs:

```<code>CREATE TABLE xxtest_cx_oracle (
    data CLOB
);

CREATE OR REPLACE PACKAGE xxtest_cx_oracle_pkg
IS
    -- Normal way; limited to ~ 511MB
    PROCEDURE insert_one(
        p_data_i IN CLOB
    );

    -- Workaround; supports > 511MB
    PROCEDURE insert_one_workaround(
        p_data_o OUT CLOB
    );
END;

CREATE OR REPLACE PACKAGE BODY xxtest_cx_oracle_pkg
IS
    -- Normal way; limited to ~ 511MB
    PROCEDURE insert_one(
        p_data_i IN CLOB
    )
    IS
    BEGIN
        INSERT INTO xxtest_cx_oracle (
            data
        ) VALUES (
            p_data_i
        );
    END;

    -- Workaround; supports > 511MB
    PROCEDURE insert_one_workaround(
        p_data_o OUT CLOB
    )
    IS
    BEGIN
        INSERT INTO xxtest_cx_oracle (
            data
        ) VALUES (
            empty_clob()
        ) RETURNING data INTO p_data_o;
    END;
END;
</code>```

Python:

```<code>import cx_Oracle
conn = cx_Oracle.connect('FOO/bar@BAZ')
cur = conn.cursor()

# Old way, using normal IN param; only supports ~511MB
data = cur.var(cx_Oracle.CLOB)
data.setvalue(0, 'A' * 1024 * 1024 * 511)
cur.callproc('xxtest_cx_oracle_pkg.insert_one', (data,))
conn.commit()

# New way using empty_clob and OUT param; supports > 511MB
data = cur.var(cx_Oracle.CLOB)
cur.callproc('xxtest_cx_oracle_pkg.insert_one_workaround', (data))
lob = data.getvalue()
lob.write('A' * 1024 * 1024 * 512)
conn.commit()
</code>```

One thing I noticed was that attempting to close the conn would fail:

```<code>>>> cursor.close()
>>> conn.close()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
cx_Oracle.DatabaseError: DPI-1054: connection cannot be closed when open statements or LOBs exist
</code>```

But you can either just del lob or let conn go out of scope to resolve this.

Body:
I'm attempting to set a very large value (>536MB) into a cx_oracle CLOB variable, but it appears to be failing around the 512MB mark.

conn = cx_Oracle.connect('foo/bar@baz')
cur = conn.cursor()
clob = cur.var(cx_Oracle.CLOB)

# The following is successful
clob.setvalue(0, 'A' * 1024 * 1024 * 511)

# The following fails
clob.setvalue(0, 'A' * 1024 * 1024 * 512)

The second command (or any value greater than this) fails with:

cx_Oracle.DatabaseError: ORA-03146: Invalid buffer length for TTC field

After making exactly three calls to the second command, the session itself appears to be disconnected (whereas this does not happen with the first command)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cx_Oracle.OperationalError: ORA-03135: connection lost contact
Process ID: 17567
Session ID: 137 Serial number: 9226

I've tested this on two environments with identical results: Python on my local environment connecting to my local Oracle; and python on a remote unix environment connecting to a different remote Oracle environment. Both of them fail at the exact same 1024 * 1024 * 512 line, which leads me to believe the issue may be with cx_Oracle.

Database version: Oracle 12CR1

Oracle Client version: 12.1.0.2.0

cx_Oracle version: Tested on 5.1.3 and 6.0.3 with identical results

Python version: 2.7.13

Everything is 64 bit.

My use case is that I need to call an PLSQL procedure to insert the CLOB into a database. Our project is following a specific ERP rule set and we are not allowed to do a direct DML. I have code similar to the following:

data = get_user_provided_data()

conn = cx_Oracle.connect('foo/bar@baz')
cur = conn.cursor()
clob = cur.var(cx_Oracle.CLOB)
clob.setvalue(0, data)

cur.callproc('xxfoo_bar_pkg.insert_one',
               keywordParameters={
                   'p_data_i': clob,
               })

Body:
Thanks to Anthony Tuininga for his response over at the github repo.

This apparently is a bug, but the following is an effective workaround, which involves changing the PLSQL to use an OUT param for the CLOB, and using Oracle's empty_clob to instantiate the value. This will return a LOB locator back to python, which is kind of like a pointer to the LOB value. You can write to the lob locator, followed by a commit, which will write the value to the DB. I'm not clear on the network implications of of this but the performance seems to be similar to

DDLs:

CREATE TABLE xxtest_cx_oracle (
    data CLOB
);

CREATE OR REPLACE PACKAGE xxtest_cx_oracle_pkg
IS
    -- Normal way; limited to ~ 511MB
    PROCEDURE insert_one(
        p_data_i IN CLOB
    );

    -- Workaround; supports > 511MB
    PROCEDURE insert_one_workaround(
        p_data_o OUT CLOB
    );
END;

CREATE OR REPLACE PACKAGE BODY xxtest_cx_oracle_pkg
IS
    -- Normal way; limited to ~ 511MB
    PROCEDURE insert_one(
        p_data_i IN CLOB
    )
    IS
    BEGIN
        INSERT INTO xxtest_cx_oracle (
            data
        ) VALUES (
            p_data_i
        );
    END;

    -- Workaround; supports > 511MB
    PROCEDURE insert_one_workaround(
        p_data_o OUT CLOB
    )
    IS
    BEGIN
        INSERT INTO xxtest_cx_oracle (
            data
        ) VALUES (
            empty_clob()
        ) RETURNING data INTO p_data_o;
    END;
END;

Python:

import cx_Oracle
conn = cx_Oracle.connect('FOO/bar@BAZ')
cur = conn.cursor()

# Old way, using normal IN param; only supports ~511MB
data = cur.var(cx_Oracle.CLOB)
data.setvalue(0, 'A' * 1024 * 1024 * 511)
cur.callproc('xxtest_cx_oracle_pkg.insert_one', (data,))
conn.commit()

# New way using empty_clob and OUT param; supports > 511MB
data = cur.var(cx_Oracle.CLOB)
cur.callproc('xxtest_cx_oracle_pkg.insert_one_workaround', (data))
lob = data.getvalue()
lob.write('A' * 1024 * 1024 * 512)
conn.commit()

One thing I noticed was that attempting to close the conn would fail:

>>> cursor.close()
>>> conn.close()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
cx_Oracle.DatabaseError: DPI-1054: connection cannot be closed when open statements or LOBs exist

But you can either just del lob or let conn go out of scope to resolve this.


问:
Gaussian convolution of data cube
I have a data cube called 'cube'. I need to convolve each 2d slice with a Gaussian kernel.

However using the following code this uses a normalised Gaussian kernel which dilutes the weaker pixels in each slice.

Is there a way to divide each pixel Gaussian by say 'max(Gaussian)' so that each pixel is convolved relative to the pixel strength?

```<code>import numpy as np
from astropy.convolution import convolve, Gaussian2DKernel

std = 2

gauss_kernel = Gaussian2DKernel(std)

for i in range(len(cube[:,0,0])):
        cube[i,:,:] = convolve(cube[i,:,:], gauss_kernel/np.max(gauss_kernel))
</code>```

答:
The solution you've posted already illustrates how to convolve with a peak-normalized Gaussian.  From your comment, it sounds like you want your "peaks" to be unaffected by surrounding data points.  Strictly, that's not possible - convolution means every pixel gets "spread out".

However, you might be talking about normalized convolution, which astropy implements (see http://docs.astropy.org/en/stable/convolution/index.html).  As long as the surrounding pixels are set to NAN, they will not contribute anything to their neighbors.  So if you have a sparsely populated array, with only a few pixels that you want to blur into surrounding "empty" pixels, just set the "empty" pixels to NaN.  See this example: http://docs.astropy.org/en/stable/convolution/index.html#using-astropy-s-convolution-to-replace-bad-data

Title: Gaussian convolution of data cube

Body:
I have a data cube called 'cube'. I need to convolve each 2d slice with a Gaussian kernel.

However using the following code this uses a normalised Gaussian kernel which dilutes the weaker pixels in each slice.

Is there a way to divide each pixel Gaussian by say 'max(Gaussian)' so that each pixel is convolved relative to the pixel strength?

import numpy as np
from astropy.convolution import convolve, Gaussian2DKernel

std = 2

gauss_kernel = Gaussian2DKernel(std)

for i in range(len(cube[:,0,0])):
        cube[i,:,:] = convolve(cube[i,:,:], gauss_kernel/np.max(gauss_kernel))


问:
Find largest sum of 3 numbers which is also divisable by 3
How to find largest sum of 3 numbers which is also divisable by 3?

Examples:

Input: [1, 15, 4, 7, 2]

Output: [15, 7, 2] (In that order)

Input: [1, 2, 4, 7]

Output: [1, 4, 7] (In that order)

I came up only with this:

```<code>function largestSum(arr) {
    let max = -1;
    let nums;

    for (let i = 0; i < arr.length; i++)
        for (let j = i + 1; j < arr.length; j++)
            for (let k = j + 1; k < arr.length; k++)
                if ((arr[i] + arr[j] + arr[k]) % 3 === 0 && arr[i] + arr[j] + arr[k] > max)
                    nums = [arr[i], arr[j], arr[k]], max = arr[i] + arr[j] + arr[k];

    return nums;
}
</code>```

But, isn't it better option here (with better efficiency)?

答:
This can be solved in linear time and constant space using modular arithmetic, no need to sort the input or enumerate its combinations.</p>

```<code>Save:
  the largest three elements congruent to 0 mod 3
  the largest three elements congruent to 1 mod 3
  the largest three elements congruent to 2 mod 3

Choose the largest of:
  1. the sum of the largest three elements congruent to 0 mod 3
  2. the sum of the largest three elements congruent to 1 mod 3
  3. the sum of the largest three elements congruent to 2 mod 3
  4. the sum of the largest element congruent to 0 mod 3
                and the largest element congruent to 1 mod 3
                and the largest element congruent to 2 mod 3
</code>```

Body:
How to find largest sum of 3 numbers which is also divisable by 3?

Examples:

Input: [1, 15, 4, 7, 2]

Output: [15, 7, 2] (In that order)

Input: [1, 2, 4, 7]

Output: [1, 4, 7] (In that order)

I came up only with this:

function largestSum(arr) {
    let max = -1;
    let nums;

    for (let i = 0; i < arr.length; i++)
        for (let j = i + 1; j < arr.length; j++)
            for (let k = j + 1; k < arr.length; k++)
                if ((arr[i] + arr[j] + arr[k]) % 3 === 0 && arr[i] + arr[j] + arr[k] > max)
                    nums = [arr[i], arr[j], arr[k]], max = arr[i] + arr[j] + arr[k];

    return nums;
}

But, isn't it better option here (with better efficiency)?

Body:
This can be solved in linear time and constant space using modular arithmetic, no need to sort the input or enumerate its combinations.

Save:
  the largest three elements congruent to 0 mod 3
  the largest three elements congruent to 1 mod 3
  the largest three elements congruent to 2 mod 3

Choose the largest of:
  1. the sum of the largest three elements congruent to 0 mod 3
  2. the sum of the largest three elements congruent to 1 mod 3
  3. the sum of the largest three elements congruent to 2 mod 3
  4. the sum of the largest element congruent to 0 mod 3
                and the largest element congruent to 1 mod 3
                and the largest element congruent to 2 mod 3


问:
Detecting and changing via screen width is not working
So, I checked out Do something if screen width is less than 960 px to see how to execute something if the screen size was less than 960 px. However, it did not work for me. Their answer was this:

```<code>if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}
</code>```

I tried it and it did work. I also already had an alert that told me the screen size;

```<code>var size = $(window).width();
alert(size);
</code>```

and this worked, but this did not:

```<code>if (size < 1200) {
    $("#mobileVersionDetected").css("display", "block");
}
else {
    $("#mobileVersionDetected").css("display", "none");
}
</code>```

Any ideas?

答:
Try this:</p>

```<code>if (size < 1200) {
    $('#mobileVersionDetected').attr("style", "display: block");
}
else {
    $('#mobileVersionDetected').attr("style", "display: none");
}
</code>```

Body:
So, I checked out Do something if screen width is less than 960 px to see how to execute something if the screen size was less than 960 px. However, it did not work for me. Their answer was this:

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}

I tried it and it did work. I also already had an alert that told me the screen size;

var size = $(window).width();
alert(size);

and this worked, but this did not:

if (size < 1200) {
    $("#mobileVersionDetected").css("display", "block");
}
else {
    $("#mobileVersionDetected").css("display", "none");
}

Any ideas?

Body:
Try this:

if (size < 1200) {
    $('#mobileVersionDetected').attr("style", "display: block");
}
else {
    $('#mobileVersionDetected').attr("style", "display: none");
}


问:
replacement for deprecated UiApp and UiInstance
To start off I would like to say I am nowhere near a knowledgeable person in coding and I just happen to be the person with most knowledge regarding this subject hence the reason why I get to look for help.

A while back I Frankensteined together a google script to put a time stamp on a page that would show last revision date and published date. However, recently I've noticed a "Deprecated" message on two lines. I struggled quite a bit to make the current script work so I'm here for some guidance.

```<code>function doGet(e){
  var app= UiApp.createApplication();
  var page = SitesApp.getActivePage();
  var updated = Utilities.formatDate(page.getLastUpdated(), "America/Chicago", "EEE, d MMM yyyy, hh:mm:ss a '('z')'");
  var published = Utilities.formatDate(page.getDatePublished(), "America/Chicago", "EEE, d MMM yyyy, hh:mm:ss a '('z')'");
  app.add(app.createHTML('Last revision: ' + updated));
  app.add(app.createHTML('Published: ' + published));
  return app;
}
</code>```

This is the current code and here is the error message I'm getting

UiApp API is deprecated.

  File: Code Line: 2

  The API has been marked as deprecated which means that the feature should be avoided and may be removed in the future. Consider using an alternative solution.

UiInstance API is deprecated.

  File: Code Line: 6

  The API has been marked as deprecated which means that the feature should be avoided and may be removed in the future. Consider using an alternative solution.

Any help or guidance would be greatly appreciated. I will keep on doing some research on my side to hopefully better understand this deprecated APIs

答:
After some perusing of https://developers.google.com/apps-script/reference/ui/ui-instance and https://developers.google.com/apps-script/reference/html/html-service it would seem like this is the way to do it. This is untested code.</p>

```<code>function doGet(e){
  var app= HtmlService.createHtmlOutput();
  var page = SitesApp.getActivePage();
  var updated = Utilities.formatDate(page.getLastUpdated(), "America/Chicago", "EEE, d MMM yyyy, hh:mm:ss a '('z')'");
  var published = Utilities.formatDate(page.getDatePublished(), "America/Chicago", "EEE, d MMM yyyy, hh:mm:ss a '('z')'");
  app.append('Last revision: ' + updated);
  app.append('Published: ' + published);
  return app;
}
</code>```

Body:
To start off I would like to say I am nowhere near a knowledgeable person in coding and I just happen to be the person with most knowledge regarding this subject hence the reason why I get to look for help.

A while back I Frankensteined together a google script to put a time stamp on a page that would show last revision date and published date. However, recently I've noticed a "Deprecated" message on two lines. I struggled quite a bit to make the current script work so I'm here for some guidance.

function doGet(e){
  var app= UiApp.createApplication();
  var page = SitesApp.getActivePage();
  var updated = Utilities.formatDate(page.getLastUpdated(), "America/Chicago", "EEE, d MMM yyyy, hh:mm:ss a '('z')'");
  var published = Utilities.formatDate(page.getDatePublished(), "America/Chicago", "EEE, d MMM yyyy, hh:mm:ss a '('z')'");
  app.add(app.createHTML('Last revision: ' + updated));
  app.add(app.createHTML('Published: ' + published));
  return app;
}

This is the current code and here is the error message I'm getting

UiApp API is deprecated.

  File: Code Line: 2

  The API has been marked as deprecated which means that the feature should be avoided and may be removed in the future. Consider using an alternative solution.

UiInstance API is deprecated.

  File: Code Line: 6

  The API has been marked as deprecated which means that the feature should be avoided and may be removed in the future. Consider using an alternative solution.

Any help or guidance would be greatly appreciated. I will keep on doing some research on my side to hopefully better understand this deprecated APIs

Body:
After some perusing of https://developers.google.com/apps-script/reference/ui/ui-instance and https://developers.google.com/apps-script/reference/html/html-service it would seem like this is the way to do it. This is untested code.

function doGet(e){
  var app= HtmlService.createHtmlOutput();
  var page = SitesApp.getActivePage();
  var updated = Utilities.formatDate(page.getLastUpdated(), "America/Chicago", "EEE, d MMM yyyy, hh:mm:ss a '('z')'");
  var published = Utilities.formatDate(page.getDatePublished(), "America/Chicago", "EEE, d MMM yyyy, hh:mm:ss a '('z')'");
  app.append('Last revision: ' + updated);
  app.append('Published: ' + published);
  return app;
}


答: If I add $(window).width() into the actual if function rather than using a variable it works.

Title: Detecting and changing via screen width is not working


问:
Possible to use Math.min to get second smallest number from array?
I am using Math.min to get the smallest number out of an array of numbers. However, I also need to get the second smallest number as well. Wondering if there is a way to do this using Math.min as well, otherwise looking for the best way to get this number.

Here's what I have:

var arr = [15, 37, 9, 21, 55];
var min = Math.min.apply(null, arr.filter(Boolean));
var secondMin; // Get second smallest number from array here

console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);```

答:
just to make that thread completed: the fastest way is to iterate all the elements just like you can do to find minimum. But up to your needs there will be two variables used: first minimum (candidate) and second one.

This logic is O(N) while sorting approach  is O(N lg(N)).

But maybe you shouldn't care if this is just for practice.

In case repeatition should be processed as independant value(just like it would be for .sort(...)[1]) then it should <= be used instead of <.

var arr = [15, 37, 9, 21, 55];
var min = Infinity, secondMin = Infinity;
for (var i= 0; i< arr.length; i++) {
    if (arr[i]< min) {
        secondMin = min;
        min = arr[i];
    } else if (arr[i]< secondMin) {
        secondMin = arr[i];
    }
}

console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);```


问:
How to add a shallow git submodule at a given tag
I want to include a large git repository as a submodule in my project. To reduce download times for developers in the project, I'd like to add the submodule so that when it is cloned, only one version is retrieved. Also, the version I need is an older version which is marked with a tag.

How do I achieve this when adding the module or when setting up a new clone?

答:
The tag is actually a human-readable version of a commit and when you add a submodule to a project, the project that you've added it to will store the state of the submodule at that commit hash.  It doesn't point at HEAD but rather the exact point in time commit when the submodule was added.

For example, game-music-emu @ 21a064e is at the exact commit of 21a064e, this is how submodules work by default.

If the commit exists in the default (e.g. master) branch, the --depth 1 should get you just the commit history from the tag you are looking for.  On the other hand, the default behavior is to bring with it all of the commit history from the default (e.g. master) branch, this is why the shallow, or --depth 1 is needed as part of the submodule command.  This is just how git repositories are cloned by default.

You can save the commit your submodule is currently on by using git add path/to/submodule.  Note, the submodule and the parent folder in which it lives are two separate repos!

Note... if the commit exists on another branch, git submodule add also supports the --branch option and the documentation states the .gitmodules file will contain an entry for branch = somebranchname, however in testing, git 1.9.1 does not seem to honor this and the default (e.g. master) branch is used regardless.

So to answer the question, to make this faster for your developers, write a helper script into your build system to pull in your submodules at a shallow depth automatically using the git submodule combined with the --depth parameter, or alternately update your documentation to specify --depth 1 so speed up clone times.

Lastly, git submodule also supports foreach [--recursive] <command> option which will allow custom commands on each submodule.

Here's an example I'm working on in cmake to lazy fetch at a shallow depth for an entire project.
 https://gist.github.com/tresf/263ea897036fa762674d489c8d457d68


问:
Is gprof suitable for analysis of long running programs? Why or why not?
I am aware there's a frequency of sample counts in gprof before it prints the flat profile. Based on the frequency of sample counts, my judgement would be longer the program runs, more is the sample collected for profiling and hence better is the data. But I am not really sure if this is true and whether long running programs are suitable for being profiled on gprof.

Any inputs will be really helpful.

答:
true, gprof has advantages (availability in any platform)
the disadvantages however make him unsuitable for more complex programs.
1)instrumentation adds function call overhead
2)cant profile code in shared libraries
3)profiles only the main thread
4)doesnt provide information about cache misses
5)doesnt give flops/s
6)doesnt analyse loops
etc</p>