问:
Kotlin + Room : java.lang.IllegalArgumentException: void cannot be converted to an Element
I am trying to add Room in my project which is Java + Kotlin, but when I try to compile the project, it fails on :app:kaptDebugKotlin with following error:

```<code>    e: java.lang.IllegalStateException: failed to analyze: java.lang.IllegalArgumentException: void cannot be converted to an Element
    at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:138)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:154)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:58)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:103)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:386)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:889)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:916)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:888)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:385)
    at sun.reflect.GeneratedMethodAccessor88.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: void cannot be converted to an Element
    at com.google.auto.common.MoreTypes$AsElementVisitor.defaultAction(MoreTypes.java:532)
    at com.google.auto.common.MoreTypes$AsElementVisitor.defaultAction(MoreTypes.java:527)
    at javax.lang.model.util.SimpleTypeVisitor6.visitNoType(SimpleTypeVisitor6.java:226)
    at com.sun.tools.javac.code.Type$JCVoidType.accept(Type.java:1736)
    at com.google.auto.common.MoreTypes.asElement(MoreTypes.java:524)
    at com.google.auto.common.MoreTypes.asTypeElement(MoreTypes.java:553)
</code>```

Here are the versions I am using:

```<code>kotlin_version = '1.1.51'
room library version = '1.0.0'
android build tool = '3.0.1'
</code>```

below things I have added in my gradle for Room:

```<code>kapt "com.android.databinding:compiler:3.0.1"

//Room
implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"
implementation "android.arch.persistence.room:rxjava2:1.0.0"
</code>```

I have also added apply plugin: 'kotlin-kapt' in my build.gradle.

Here's how I have implemented Room Library:

```<code>RoomDatabase.kt

@Database(entities = arrayOf(ProductTest::class), version = CartDatabase.DATABASE_VERSION)
abstract class CartDatabase : RoomDatabase() {

    companion object {
        const val DATABASE_VERSION = 1
        const val DATABASE_NAME = "sall_customer_db"
    }

    abstract var cartRepositoryImpl: CartRepositoryImpl
}

ProductTest.kt
@Entity
data class ProductTest(
        @PrimaryKey
        @ColumnInfo(name = "id")
        var productId: Int,
        @ColumnInfo(name = "name")
        var productName: String
)

CartRepositoryImpl.kt
@Dao
interface CartRepositoryImpl : CartRepository {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    override fun addToCart(product: ProductTest): Long
}
</code>```

I have just coded this without using it anywhere & tried to compile, but it fails. It compiles fine if I comment out the Room stuff from gradle & code but fails with just the above code.

Have already tried cleaning the project but it didn't help. Am I missing something here? Please help me out here.

Edit I created the new demo project to check & I am also facing the same compilation error there. The Room related code is same as above, here I am adding the full build.gradle from my demo:

Project level gradle:

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

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

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

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

// Versions
ext {
    support_library_version = '27.0.0'
    play_services_version = '11.6.2'
    retrofit_version = '2.3.0'
    arch_components_version = '1.0.0'
}

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

app module's gradle

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

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.abc.kotlinroomdemo"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    // RxJava2
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.5'

    //Room
    implementation "android.arch.persistence.room:runtime:$arch_components_version"
    implementation "android.arch.persistence.room:rxjava2:$arch_components_version"
    kapt "android.arch.persistence.room:compiler:$arch_components_version"

    //Dagger 2
    //compile 'com.google.dagger:dagger-android:2.10'
    //kapt 'com.google.dagger:dagger-android-processor:2.10'
    //compileOnly 'com.google.dagger:dagger:2.10'
    //implementation 'com.google.dagger:dagger:2.13'
    //kapt 'com.google.dagger:dagger-compiler:2.13'
    //provided 'javax.annotation:jsr250-api:1.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

答:
Maaan! What a silly mistake! In abstract RoomDatabase class, we need to declare the abstract fun returning the Dao object but I had defined abstract var there.

So changing

```<code>abstract var cartRepositoryImpl: CartRepositoryImpl
</code>```

to:

```<code>abstract fun cartRepositoryImpl(): CartRepositoryImpl
</code>```

fixed the compilation error! I overlooked this while following the stuff from a blog I admit, but still the better compile time error wouldn't have hurt!

Body:
I am trying to add Room in my project which is Java + Kotlin, but when I try to compile the project, it fails on :app:kaptDebugKotlin with following error:

    e: java.lang.IllegalStateException: failed to analyze: java.lang.IllegalArgumentException: void cannot be converted to an Element
    at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:138)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:154)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:58)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:103)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:386)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:889)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:916)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:888)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:385)
    at sun.reflect.GeneratedMethodAccessor88.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: void cannot be converted to an Element
    at com.google.auto.common.MoreTypes$AsElementVisitor.defaultAction(MoreTypes.java:532)
    at com.google.auto.common.MoreTypes$AsElementVisitor.defaultAction(MoreTypes.java:527)
    at javax.lang.model.util.SimpleTypeVisitor6.visitNoType(SimpleTypeVisitor6.java:226)
    at com.sun.tools.javac.code.Type$JCVoidType.accept(Type.java:1736)
    at com.google.auto.common.MoreTypes.asElement(MoreTypes.java:524)
    at com.google.auto.common.MoreTypes.asTypeElement(MoreTypes.java:553)

Here are the versions I am using:

kotlin_version = '1.1.51'
room library version = '1.0.0'
android build tool = '3.0.1'

below things I have added in my gradle for Room:

kapt "com.android.databinding:compiler:3.0.1"

//Room
implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"
implementation "android.arch.persistence.room:rxjava2:1.0.0"

I have also added apply plugin: 'kotlin-kapt' in my build.gradle.

Here's how I have implemented Room Library:

RoomDatabase.kt

@Database(entities = arrayOf(ProductTest::class), version = CartDatabase.DATABASE_VERSION)
abstract class CartDatabase : RoomDatabase() {

    companion object {
        const val DATABASE_VERSION = 1
        const val DATABASE_NAME = "sall_customer_db"
    }

    abstract var cartRepositoryImpl: CartRepositoryImpl
}

ProductTest.kt
@Entity
data class ProductTest(
        @PrimaryKey
        @ColumnInfo(name = "id")
        var productId: Int,
        @ColumnInfo(name = "name")
        var productName: String
)

CartRepositoryImpl.kt
@Dao
interface CartRepositoryImpl : CartRepository {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    override fun addToCart(product: ProductTest): Long
}

I have just coded this without using it anywhere & tried to compile, but it fails. It compiles fine if I comment out the Room stuff from gradle & code but fails with just the above code.

Have already tried cleaning the project but it didn't help. Am I missing something here? Please help me out here.

Edit I created the new demo project to check & I am also facing the same compilation error there. The Room related code is same as above, here I am adding the full build.gradle from my demo:

Project level gradle:

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

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

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

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

// Versions
ext {
    support_library_version = '27.0.0'
    play_services_version = '11.6.2'
    retrofit_version = '2.3.0'
    arch_components_version = '1.0.0'
}

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

app module's gradle

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.abc.kotlinroomdemo"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    // RxJava2
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.5'

    //Room
    implementation "android.arch.persistence.room:runtime:$arch_components_version"
    implementation "android.arch.persistence.room:rxjava2:$arch_components_version"
    kapt "android.arch.persistence.room:compiler:$arch_components_version"

    //Dagger 2
    //compile 'com.google.dagger:dagger-android:2.10'
    //kapt 'com.google.dagger:dagger-android-processor:2.10'
    //compileOnly 'com.google.dagger:dagger:2.10'
    //implementation 'com.google.dagger:dagger:2.13'
    //kapt 'com.google.dagger:dagger-compiler:2.13'
    //provided 'javax.annotation:jsr250-api:1.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Body:
Maaan! What a silly mistake! In abstract RoomDatabase class, we need to declare the abstract fun returning the Dao object but I had defined abstract var there.

So changing

abstract var cartRepositoryImpl: CartRepositoryImpl

to:

abstract fun cartRepositoryImpl(): CartRepositoryImpl

fixed the compilation error! I overlooked this while following the stuff from a blog I admit, but still the better compile time error wouldn't have hurt!


来源: stackexchange

问:
Check if string contains a 3 character long substring of another string
I need a regex pattern to check whether characters present in a string consecutively repeats 3 character in another string. Eg:

```<code>var string1 = "HelloWorld";
var string2 = "Work";
</code>```

Here the letters "Wor" in string1 repeats in string2, so it should return true.

Any help on this

答:
Another idea would be to concatenate the two strings, lowercase them and then apply this regular expression:

```<code>(\w{3}).+(\1)
</code>```

function repetitions(s1, s2) {
  const s = s1.toLowerCase() + s2.toLowerCase()
  const r = /(\w{3}).+(\1)/
  const res = r.exec(s)
  return res !== null ? res[1] : "";
}

console.log(repetitions("HelloWorld", "Work"));
console.log(repetitions("HelloWo", "Work"));```
</div>
</div>
</p>

<p>Here is a more robust version which prevents finding the string repetition in either of the input strings:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function repetitions(s1, s2) {
  const replaceRegex = /(\w{3})(.*)(\1)/;
  const s = s1.toLowerCase().replace(replaceRegex, "$1") + " " + s2.toLowerCase().replace(replaceRegex, "$1");
  const r = /(\w{3}).+?(\1)/;
  const res = r.exec(s);
  return res !== null ? res[1] : "";
}

console.log(repetitions("HelloWorld", "Work"));
console.log(repetitions("HelloWo", "Work"));
console.log(repetitions("HelloWoHello", "Work"));
console.log(repetitions("HelloWoHello", "WorkWork"));
console.log(repetitions("HelloWo", "HelloWork"));</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need a regex pattern to check whether characters present in a string consecutively repeats 3 character in another string. Eg:

var string1 = "HelloWorld";
var string2 = "Work";

Here the letters "Wor" in string1 repeats in string2, so it should return true.

Any help on this

Body:
Another idea would be to concatenate the two strings, lowercase them and then apply this regular expression:

(\w{3}).+(\1)

function repetitions(s1, s2) {
  const s = s1.toLowerCase() + s2.toLowerCase()
  const r = /(\w{3}).+(\1)/
  const res = r.exec(s)
  return res !== null ? res[1] : "";
}

console.log(repetitions("HelloWorld", "Work"));
console.log(repetitions("HelloWo", "Work"));

Here is a more robust version which prevents finding the string repetition in either of the input strings:

function repetitions(s1, s2) {
  const replaceRegex = /(\w{3})(.*)(\1)/;
  const s = s1.toLowerCase().replace(replaceRegex, "$1") + " " + s2.toLowerCase().replace(replaceRegex, "$1");
  const r = /(\w{3}).+?(\1)/;
  const res = r.exec(s);
  return res !== null ? res[1] : "";
}

console.log(repetitions("HelloWorld", "Work"));
console.log(repetitions("HelloWo", "Work"));
console.log(repetitions("HelloWoHello", "Work"));
console.log(repetitions("HelloWoHello", "WorkWork"));
console.log(repetitions("HelloWo", "HelloWork"));

ContentLicense: CC BY-SA 3.0


问:
handle Http Request in exception case
I have an application the backend is spring MVC and the front end is angular.the server side sends data to the client side. My question is if something wrong happens in the server side what is the best way to handle it.
I think about 2 solutions :
the first one is to create new model which contains 3 attributes like this

public class Response{
       boolean hasError;
       Object data;
       Exception ex}

and send this object to the client side then in the client side check if the hasError equals false check the data object otherwise check the exception object.
this solution grants that in all case the http response status will be 200 from the server side,

the second solution is to create custom status code for the http response then in the front end use this status code to detect exception type.

The question is what is the best practice of these 2 solutions ?
Or is there is a solution better than these 2 solutions ?

答: If you are using micro services based architecture,  why not give the Netflix hystrix fault tolerance lib a try.  It uses the circuit breaker  pattern and allows the microservice to operate when a related service fails.  </p>

Title: handle Http Request in exception case


答:
Use split, substring and includes

```<code>var fn = function( string1, string2, matchChars ) {
   return !!string2.split("").find( function(item, index){
       if (index + matchChars <= string2.length )
       {
          return string1.includes( string2.substring( index, index +  matchChars ) ); //check after each turn if the substring from index is included in string1 or not
       }
       return false;
   });
}

console.log( fn("HelloWorld", "Work", 3) );
</code>```

var fn = function(string1, string2, matchChars) {
  return !!string2.split("").find(function(item, index) {
    if (index + matchChars <= string2.length) {
      return string1.includes(string2.substring(index, matchChars));
    }
    return false;
  });
}

console.log(fn("HelloWorld", "Work", 3));
console.log(fn("HelloWorld", "Wod", 3));```

Title: Check if string contains a 3 character long substring of another string

Body:
Use split, substring and includes

var fn = function( string1, string2, matchChars ) {
   return !!string2.split("").find( function(item, index){
       if (index + matchChars <= string2.length )
       {
          return string1.includes( string2.substring( index, index +  matchChars ) ); //check after each turn if the substring from index is included in string1 or not
       }
       return false;
   });
}

console.log( fn("HelloWorld", "Work", 3) );

var fn = function(string1, string2, matchChars) {
  return !!string2.split("").find(function(item, index) {
    if (index + matchChars <= string2.length) {
      return string1.includes(string2.substring(index, matchChars));
    }
    return false;
  });
}

console.log(fn("HelloWorld", "Work", 3));
console.log(fn("HelloWorld", "Wod", 3));


问:
linq if statement problem
```<code>public IEnumerable<string> References { get; private set; }

References = hrefs.
                Select(href => href.Attributes["href"].Value).
                Distinct().
                ToArray();
</code>```

I'm trying to make it behave so that if href.Attributes["onclick"] exists then I will add onclick value to References otherwise href value. How can I check this inside linq? now I always add href value.

EDIT:

and how if class exist go to next element and don't add anything. i forget about this.

答:
maybe...

```<code>References = href
                .Select(href =>
                   href.Attributes["onclick"] != null ?
                      href.Attributes["onclick"].Value
                    : href.Attributes["href"].Value)
                .Distinct().
                .ToArray();
</code>```

Edit:

To answer the question update, just add

```<code>.Where(href => href.Attributes["class"] == null)
</code>```

before the Select clause.

ContentLicense: CC BY-SA 2.5

Title: linq if statement problem

Body:
public IEnumerable<string> References { get; private set; }

References = hrefs.
                Select(href => href.Attributes["href"].Value).
                Distinct().
                ToArray();

I'm trying to make it behave so that if href.Attributes["onclick"] exists then I will add onclick value to References otherwise href value. How can I check this inside linq? now I always add href value.

EDIT:

and how if class exist go to next element and don't add anything. i forget about this.

Body:
maybe...

References = href
                .Select(href =>
                   href.Attributes["onclick"] != null ?
                      href.Attributes["onclick"].Value
                    : href.Attributes["href"].Value)
                .Distinct().
                .ToArray();

Edit:

To answer the question update, just add

.Where(href => href.Attributes["class"] == null)

before the Select clause.


问:
Autocomplete Material Angular 2 implementation Error
I have an error in regards with the angular 2 when I implement with autocomplete on material design and I have no idea why because it is my first time implementing it practicing with backend asp.net core. I tried installing some of the ng2 libraries but does not work at all.  Here is my code below:

import { Component } from '@angular/core';
import { WebServiceComponents } from '../WebService/web.service';
import { FormControl } from '@angular/forms';

import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';

@Component({
    selector: 'new-user-account',
    template: `
              <md-card class="card-margin">
                <md-card-content>
                    <md-input-container>
                        <input mdInput placeholder="Select Employee" [mdAutocomplete]="auto" [formControl]="UserAccountCtrl" />

                    </md-input-container>
                    <md-autocomplete #auto="mdAutocomplete">
                        <md-option *ngFor="let userAccount of filterUserAccount | async" [value]="userAccount">
                            {{userAccount.username}}
                        </md-option>
                    </md-autocomplete>
                    <md-input-container>
                        <input mdInput placeholder="Username" />

                    </md-input-container>
                </md-card-content>
              </md-card>
              `
})

export class NewUserAccountComponent{
    UserAccountCtrl: FormControl;
    filterUserAccount: any;

     async ngOnInit(){
        var response = await this.webService.getUserAccounts();
        this.userAccounts = response.json();
    }

    userAccounts = [];

    constructor(private webService : WebServiceComponents){
    this.UserAccountCtrl = new FormControl();
    this.filterUserAccount = this.UserAccountCtrl.valueChanges
        .startWith(null)
        .map(name => this.filterUserAccount(name));
    }

    filteredUserAccount(val: string) {
    return val ? this.userAccounts.filter(s => new RegExp(`^${val}`, 'gi').test(s))
               : this.userAccounts;
  }
}```
</div>
</div>
</p>

<p>And the error as follows below:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>zone.js:645 Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'formControl' since it isn't a known property of 'input'. ("ainer>
                        <input mdInput placeholder="Select Employee" [mdAutocomplete]="auto" [ERROR ->][formControl]="UserAccountCtrl" /><br />
                    </md-input-container>
                  "): ng:///AppModule/NewUserAccountComponent.html@4:93
Error: Template parse errors:
Can't bind to 'formControl' since it isn't a known property of 'input'. ("ainer>
                        <input mdInput placeholder="Select Employee" [mdAutocomplete]="auto" [ERROR ->][formControl]="UserAccountCtrl" /><br />
                    </md-input-container>
                  "): ng:///AppModule/NewUserAccountComponent.html@4:93
    at syntaxError (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:1513:34)
    at TemplateParser.parse (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:11951:19)
    at JitCompiler._compileTemplate (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25723:39)
    at eval (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25647:62)
    at Set.forEach (native)
    at JitCompiler._compileComponents (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25647:19)
    at createResult (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25532:19)
    at ZoneDelegate.invoke (http://localhost:3002/node_modules/zone.js/dist/zone.js:391:26)
    at Zone.run (http://localhost:3002/node_modules/zone.js/dist/zone.js:141:43)
    at http://localhost:3002/node_modules/zone.js/dist/zone.js:818:57
    at syntaxError (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:1513:34)
    at TemplateParser.parse (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:11951:19)
    at JitCompiler._compileTemplate (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25723:39)
    at eval (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25647:62)
    at Set.forEach (native)
    at JitCompiler._compileComponents (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25647:19)
    at createResult (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25532:19)
    at ZoneDelegate.invoke (http://localhost:3002/node_modules/zone.js/dist/zone.js:391:26)
    at Zone.run (http://localhost:3002/node_modules/zone.js/dist/zone.js:141:43)
    at http://localhost:3002/node_modules/zone.js/dist/zone.js:818:57
    at resolvePromise (http://localhost:3002/node_modules/zone.js/dist/zone.js:770:31)
    at resolvePromise (http://localhost:3002/node_modules/zone.js/dist/zone.js:741:17)
    at http://localhost:3002/node_modules/zone.js/dist/zone.js:818:17
    at ZoneDelegate.invokeTask (http://localhost:3002/node_modules/zone.js/dist/zone.js:424:31)
    at Zone.runTask (http://localhost:3002/node_modules/zone.js/dist/zone.js:191:47)
    at drainMicroTaskQueue (http://localhost:3002/node_modules/zone.js/dist/zone.js:584:35)
    at XMLHttpRequest.ZoneTask.invoke (http://localhost:3002/node_modules/zone.js/dist/zone.js:490:25)</code>```

I don't know whats going on but I followed the steps in angular material design autocomplete component but it seems not working to me.

Does anyone knows how to fix this issue?  And can someone help me with my code? I'm newbie working for fixing this issue for almost 3 hours right now.

Thanks and have a great day!

答:
import FormsModule, ReactiveFormsModule from @angular/forms like below

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Body:
I have an error in regards with the angular 2 when I implement with autocomplete on material design and I have no idea why because it is my first time implementing it practicing with backend asp.net core. I tried installing some of the ng2 libraries but does not work at all.  Here is my code below:

import { Component } from '@angular/core';
import { WebServiceComponents } from '../WebService/web.service';
import { FormControl } from '@angular/forms';

import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';

@Component({
    selector: 'new-user-account',
    template: `
              <md-card class="card-margin">
                <md-card-content>
                    <md-input-container>
                        <input mdInput placeholder="Select Employee" [mdAutocomplete]="auto" [formControl]="UserAccountCtrl" />

                    </md-input-container>
                    <md-autocomplete #auto="mdAutocomplete">
                        <md-option *ngFor="let userAccount of filterUserAccount | async" [value]="userAccount">
                            {{userAccount.username}}
                        </md-option>
                    </md-autocomplete>
                    <md-input-container>
                        <input mdInput placeholder="Username" />

                    </md-input-container>
                </md-card-content>
              </md-card>
              `
})

export class NewUserAccountComponent{
    UserAccountCtrl: FormControl;
    filterUserAccount: any;

     async ngOnInit(){
        var response = await this.webService.getUserAccounts();
        this.userAccounts = response.json();
    }

    userAccounts = [];

    constructor(private webService : WebServiceComponents){
    this.UserAccountCtrl = new FormControl();
    this.filterUserAccount = this.UserAccountCtrl.valueChanges
        .startWith(null)
        .map(name => this.filterUserAccount(name));
    }

    filteredUserAccount(val: string) {
    return val ? this.userAccounts.filter(s => new RegExp(`^${val}`, 'gi').test(s))
               : this.userAccounts;
  }
}

And the error as follows below:

zone.js:645 Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'formControl' since it isn't a known property of 'input'. ("ainer>
                        <input mdInput placeholder="Select Employee" [mdAutocomplete]="auto" [ERROR ->][formControl]="UserAccountCtrl" />

                    </md-input-container>
                  "): ng:///AppModule/NewUserAccountComponent.html@4:93
Error: Template parse errors:
Can't bind to 'formControl' since it isn't a known property of 'input'. ("ainer>
                        <input mdInput placeholder="Select Employee" [mdAutocomplete]="auto" [ERROR ->][formControl]="UserAccountCtrl" />

                    </md-input-container>
                  "): ng:///AppModule/NewUserAccountComponent.html@4:93
    at syntaxError (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:1513:34)
    at TemplateParser.parse (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:11951:19)
    at JitCompiler._compileTemplate (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25723:39)
    at eval (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25647:62)
    at Set.forEach (native)
    at JitCompiler._compileComponents (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25647:19)
    at createResult (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25532:19)
    at ZoneDelegate.invoke (http://localhost:3002/node_modules/zone.js/dist/zone.js:391:26)
    at Zone.run (http://localhost:3002/node_modules/zone.js/dist/zone.js:141:43)
    at http://localhost:3002/node_modules/zone.js/dist/zone.js:818:57
    at syntaxError (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:1513:34)
    at TemplateParser.parse (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:11951:19)
    at JitCompiler._compileTemplate (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25723:39)
    at eval (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25647:62)
    at Set.forEach (native)
    at JitCompiler._compileComponents (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25647:19)
    at createResult (http://localhost:3002/node_modules/@angular/compiler/bundles/compiler.umd.js:25532:19)
    at ZoneDelegate.invoke (http://localhost:3002/node_modules/zone.js/dist/zone.js:391:26)
    at Zone.run (http://localhost:3002/node_modules/zone.js/dist/zone.js:141:43)
    at http://localhost:3002/node_modules/zone.js/dist/zone.js:818:57
    at resolvePromise (http://localhost:3002/node_modules/zone.js/dist/zone.js:770:31)
    at resolvePromise (http://localhost:3002/node_modules/zone.js/dist/zone.js:741:17)
    at http://localhost:3002/node_modules/zone.js/dist/zone.js:818:17
    at ZoneDelegate.invokeTask (http://localhost:3002/node_modules/zone.js/dist/zone.js:424:31)
    at Zone.runTask (http://localhost:3002/node_modules/zone.js/dist/zone.js:191:47)
    at drainMicroTaskQueue (http://localhost:3002/node_modules/zone.js/dist/zone.js:584:35)
    at XMLHttpRequest.ZoneTask.invoke (http://localhost:3002/node_modules/zone.js/dist/zone.js:490:25)

I don't know whats going on but I followed the steps in angular material design autocomplete component but it seems not working to me.

Does anyone knows how to fix this issue?  And can someone help me with my code? I'm newbie working for fixing this issue for almost 3 hours right now.

Thanks and have a great day!

Body:
import FormsModule, ReactiveFormsModule from @angular/forms like below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Graphs not showing in Observium
I have installed observium which is suceessfully pulling all information from all devices but it is not showing graphs.

I can see files in /opt/observium/rrd

I do not see any error when I manually execute:

```<code>cd /opt/observium && ./discovery.php -h all && ./poller.php -h all
</code>```

I have tested in Chrome and Firefox.

This is my config.php

```<code><?php

## Check http://www.observium.org/docs/config_options/ for documentation of possible settings

// Database config ---  This MUST be configured
$config['db_extension'] = 'mysqli';
$config['db_host']      = '192.168.1.10';
$config['db_user']      = 'observium';
$config['db_pass']      = 'somepass';
$config['db_name']      = 'observium';

// Base directory
#$config['install_dir'] = "/opt/observium";

// Default community list to use when adding/discovering
$config['snmp']['community'] = array("public");

// Authentication Model
$config['auth_mechanism'] = "mysql";    // default, other options: ldap, http-auth, please see documentation for config help

// Enable alerter
// $config['poller-wrapper']['alerter'] = TRUE;

//$config['web_show_disabled'] = FALSE;    // Show or not disabled devices on major pages.

// Set up a default alerter (email to a single address)
$config['email']['default']        = "admin@mydomain.com";
$config['email']['from']           = "Observium <observium@mydomain.com>";
$config['email']['default_only']   = TRUE;

$config['enable_syslog']                = 1; // Enable Syslog

// End config.php
</code>```

If I can provide any other information which could solve this please let me know.

Seetings:

Device graph settings:

Nginx conf:

```<code>server {
  listen 80;
  server_name observium.mydomain.com;

  root /opt/observium/html;
  client_max_body_size 10m;
  client_body_buffer_size 8K;
  client_header_buffer_size 1k;
  large_client_header_buffers 4 8k;

  location / {
    index index.php index.html index.htm;
    autoindex on;
    try_files $uri $uri/ /index.php;

    location ~ \.php$ {
      fastcgi_split_path_info ^(.+\.php)(/.+)$;
      fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      include fastcgi_params;
    }
  }
}
</code>```

Thank you

答:
Found problem.
At the top of config.php file was empty line before <?php

Title: Graphs not showing in Observium

Body:
I have installed observium which is suceessfully pulling all information from all devices but it is not showing graphs.

I can see files in /opt/observium/rrd

I do not see any error when I manually execute:

cd /opt/observium && ./discovery.php -h all && ./poller.php -h all

I have tested in Chrome and Firefox.

This is my config.php

<?php

## Check http://www.observium.org/docs/config_options/ for documentation of possible settings

// Database config ---  This MUST be configured
$config['db_extension'] = 'mysqli';
$config['db_host']      = '192.168.1.10';
$config['db_user']      = 'observium';
$config['db_pass']      = 'somepass';
$config['db_name']      = 'observium';

// Base directory
#$config['install_dir'] = "/opt/observium";

// Default community list to use when adding/discovering
$config['snmp']['community'] = array("public");

// Authentication Model
$config['auth_mechanism'] = "mysql";    // default, other options: ldap, http-auth, please see documentation for config help

// Enable alerter
// $config['poller-wrapper']['alerter'] = TRUE;

//$config['web_show_disabled'] = FALSE;    // Show or not disabled devices on major pages.

// Set up a default alerter (email to a single address)
$config['email']['default']        = "admin@mydomain.com";
$config['email']['from']           = "Observium <observium@mydomain.com>";
$config['email']['default_only']   = TRUE;

$config['enable_syslog']                = 1; // Enable Syslog

// End config.php

If I can provide any other information which could solve this please let me know.

Seetings:

Device graph settings:

Nginx conf:

server {
  listen 80;
  server_name observium.mydomain.com;

  root /opt/observium/html;
  client_max_body_size 10m;
  client_body_buffer_size 8K;
  client_header_buffer_size 1k;
  large_client_header_buffers 4 8k;

  location / {
    index index.php index.html index.htm;
    autoindex on;
    try_files $uri $uri/ /index.php;

    location ~ \.php$ {
      fastcgi_split_path_info ^(.+\.php)(/.+)$;
      fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      include fastcgi_params;
    }
  }
}

Thank you


问:
Printing dictionary in a While Loop
I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.

```<code>newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
</code>```

I created this dict and I want to use a while loop to output it this way:

```<code>Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30
</code>```

I am able to do it with a for loop, just curious how it can be done with a while loop.

答:
You can do this with while loop.

```<code>newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
i = 0
while i < len(newDict):
    val = newDict.items()[i]
    print val[0], val[1]
    i += 1
</code>```

Title: Printing dictionary in a While Loop

Body:
I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}

I created this dict and I want to use a while loop to output it this way:

Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30

I am able to do it with a for loop, just curious how it can be done with a while loop.

Body:
You can do this with while loop.

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
i = 0
while i < len(newDict):
    val = newDict.items()[i]
    print val[0], val[1]
    i += 1


问:
Which scripting language is better for embedding in multi-threaded C/C++ application
Considering the following requirementes:

Must be supported on Windows.  Preferably works also on other platforms.

Must support multi threading.  By that I mean that the engine can work in parallel in multiple threads.

Readability is important.

License must be compatible with closed-source projects.

I like Python for its readablity.  I am also have more experience with Python than other scripting languages.  However CPython is not multi-threaded, and IronPython requires hosting the CLR and a compatible language (C++/CLI or C#).

答:
I've been in the same dilemma an choose Lua over Python and JScript.
The thing which Lua does best is the great interop with C/C++ code using libraries like luabridge and luabind. That is, you can call lua from C++ and have the script call back into C++ without a problem, access c++ data from the script and vice versa.

The problem with languages like Python and Lua is that the language is not really multi-threaded in the regular sense of the word: if one C++ thread it using the language scripting engine to run a script, you cannot use the same engine to run another script. Both languages has an engine-wide lock which can be used in those cases to make sure the engine integrity is maintained. However, both languages are multi-threaded in the sense that you can run function in the background and interact with any synchronization object you want (just like from C++). So I choose to have all threads created from C++ and scripting code only run in a dedicated threads (thread per engine) and interact with other threads in the application in the regular ways.

If you need to pass data and control from C++ to a script and vice versa, Lua is much better than Python. Beside that, I would not host the CLR in a C++ project. It's too messy.


问:
List all property indices in agens-graph
I am evaluating Agensgraph v1.2 for usage in my company. I am trying to use normal postgres shell commands in agens shell to get information about the indices, tables etc. I am not able to list indices with \di command.

Is there a way to list all the property indices that are currently in the db?

It will also be helpful if I can get a link to some documentation of the system tables used by Agensgraph, which I can query if the shell commands are not yet fully functional for the graph side.

答: I was able to list the indices using the describe graph vertices command (\dGv).</p>


问:
Changing the suffix of .pdf causes it not to be opened correctly in windows
My dilemma is that there is pdf file named 'P01111-AMFLIBL.pdf' , I want to append '.NOSUFFIX' after .pdf so the result will be like 'P01111-AMFLIBL.pdf.NOSUFFIX'.

I am trying to add by this line of code :

```<code>fileName = fileName + ".pdf" + ".NOSUFFIX";
</code>```

It's working, but the problem is that pdf file is not directly getting opened into my system

答: On Windows, the extension (i.e. suffix starting at last .) determines the file type (and associated program). If you append another suffix, this appended .NOSUFFIX will become the file extension, and the original .pdf will become just a part of the file name.

Body:
My dilemma is that there is pdf file named 'P01111-AMFLIBL.pdf' , I want to append '.NOSUFFIX' after .pdf so the result will be like 'P01111-AMFLIBL.pdf.NOSUFFIX'.

I am trying to add by this line of code :

fileName = fileName + ".pdf" + ".NOSUFFIX";

It's working, but the problem is that pdf file is not directly getting opened into my system


问:
Spliting a variable into multiple in SAS
I was wondering if it is possible to split a variable in to multiple variables. I have a big variable I would like to split into multiple columns.

```<code>"0060175052";"Three Chords and the Truth: Hope, Heartbreak, and Changing Fortunes in Nashville";"Laurence Leamer";"1997","Harpercollins"
</code>```

I would like to split it where the semicolons are. So:

```<code>v1 = "0060175052"
v2 = "Three Chords and the Truth: Hope, Heartbreak, and Changing Fortunes in
      Nashville"
v3 = "Laurence Leamer"
v4 = "1997"
v5 = "Harpercollins"
</code>```

答:
Sofie:

How you split the value depends on where it is coming from.

Reading a data file

For the case of reading a text file with an INPUT statement you indicate the delimiter in the INFILE statement, for example:

```<code>INFILE *input-file* DSD DLM=';';
</code>```

Parsing a data value

For the case of a variable in an existing data set the SCAN function can extract different parts of a string.

```<code>v1 = SCAN (big_variable, 1, ';');
...
v5 = SCAN (big_variable, 5, ';');
</code>```

If the big variable values can contain consecutive semi-colons that indicate a blank value you will need to use the M modifier in the modifiers argument. For example:

```<code>v1 = SCAN (big_variable, 1, ';', 'M');
</code>```

For only five parts you probably don't need to array-ify the process.  If the string has many parts to split, an array would by used to reduce coding repetition:

```<code>attrib v1-v20 length=$200;
array v v1-v20;
do index = 1 to dim(v);
  v(index) = SCAN (big_variable, index, ';');
end;
</code>```

More advanced scanning techniques would use Perl regular expressions as surfaced by the SAS PRX* call routines and functions -- such as PRXPARSE, PRXMATCH, PRXNEXT, etc...

Body:
I was wondering if it is possible to split a variable in to multiple variables. I have a big variable I would like to split into multiple columns.

"0060175052";"Three Chords and the Truth: Hope, Heartbreak, and Changing Fortunes in Nashville";"Laurence Leamer";"1997","Harpercollins"

I would like to split it where the semicolons are. So:

v1 = "0060175052"
v2 = "Three Chords and the Truth: Hope, Heartbreak, and Changing Fortunes in
      Nashville"
v3 = "Laurence Leamer"
v4 = "1997"
v5 = "Harpercollins"

Body:
Sofie:

How you split the value depends on where it is coming from.

Reading a data file

For the case of reading a text file with an INPUT statement you indicate the delimiter in the INFILE statement, for example:

INFILE *input-file* DSD DLM=';';

Parsing a data value

For the case of a variable in an existing data set the SCAN function can extract different parts of a string.

v1 = SCAN (big_variable, 1, ';');
...
v5 = SCAN (big_variable, 5, ';');

If the big variable values can contain consecutive semi-colons that indicate a blank value you will need to use the M modifier in the modifiers argument. For example:

v1 = SCAN (big_variable, 1, ';', 'M');

For only five parts you probably don't need to array-ify the process.  If the string has many parts to split, an array would by used to reduce coding repetition:

attrib v1-v20 length=$200;
array v v1-v20;
do index = 1 to dim(v);
  v(index) = SCAN (big_variable, index, ';');
end;

More advanced scanning techniques would use Perl regular expressions as surfaced by the SAS PRX* call routines and functions -- such as PRXPARSE, PRXMATCH, PRXNEXT, etc...


答:
You can make your dictionary an iterator calling iteritems (Python 2.x), or iter on the items() (Python 3.x)

```<code># Python 2.x
from __future__ import print_function
items = newDict.iteritems()

# Python 3.x
items = iter(newDict.items())

while True:
    try:
        item = next(items)
        print(*item)
    except StopIteration:
        break
</code>```

Note: We're importing print_function on Python 2.x because print would be a statement instead of a function, and hence the line print(*item) would actually fail

Title: Printing dictionary in a While Loop

Body:
You can make your dictionary an iterator calling iteritems (Python 2.x), or iter on the items() (Python 3.x)

# Python 2.x
from __future__ import print_function
items = newDict.iteritems()

# Python 3.x
items = iter(newDict.items())

while True:
    try:
        item = next(items)
        print(*item)
    except StopIteration:
        break

Note: We're importing print_function on Python 2.x because print would be a statement instead of a function, and hence the line print(*item) would actually fail


问:
how to prevent chrome follow any location headers
What plugin or settings to use in google chrome to prevent follow by any location header? Can't find any information about that.

答: I found extension for Chrome - "Tamper chrome". It allows to edit response headers.</p>


问:
MultiDict Error Django
Im using Django and trying to get a response by using AJAX. I have two forms, the first one works just fine. Though I use the same logic in my second form handling it does not work well.

models.py

```<code>class AskMe(models.Model):
    name = models.CharField(max_length=1000)
</code>```

views.py

```<code>def AskMeQ(request):
    if request.method == POST:
        name = request.POST['name']

        AskMe.objects.create(name=name)
</code>```

urls.py

```<code>url('r^askmeQ/$', views.AskMeQ)
</code>```

ajax logic

```<code>$('.former').on('submit', '.ajaxform', function(event) {
    event.preventDefault();
    $.ajax({
        url: '/askmeQ/',
        type: 'POST',
        data: {name: $('#name').val(),
                csrfmiddlewaretoken: csrftoken
        }
    })
    .done(function() {
        console.log("success");
        $('.formset').slideToggle(400)
        });
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });
});
</code>```

ERROR

```<code>Traceback:

File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__
  77.             list_ = super().__getitem__(key)

During handling of the above exception ('name'), another exception occurred:

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/pc/Django_Projects/vikas/vikas/views.py" in askmeQ
  40.         name = request.POST['name']

File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__
  79.             raise MultiValueDictKeyError(key)

Exception Type: MultiValueDictKeyError at /askmeQ/
Exception Value: 'name'
</code>```

The logic I use above used to work in all the previous forms, but here it throws me an error.
The SQLite3 table has been created as projectname_model.name.

How can I correct this?

答:
It seems that the name was not posted with the request. Due to which, you name = request.POST['name'] will throw an error since the key won't be part of the POST dict.

To correct this, alter your code to:

```<code>def AskMeQ(request):
    if request.method == POST:
        name = request.POST.get('name')
        if name:
            AskMe.objects.create(name=name)
        # else:
        #     error condition handling
</code>```

Title: MultiDict Error Django

Body:
Im using Django and trying to get a response by using AJAX. I have two forms, the first one works just fine. Though I use the same logic in my second form handling it does not work well.

models.py

class AskMe(models.Model):
    name = models.CharField(max_length=1000)

views.py

def AskMeQ(request):
    if request.method == POST:
        name = request.POST['name']

        AskMe.objects.create(name=name)

urls.py

url('r^askmeQ/$', views.AskMeQ)

ajax logic

$('.former').on('submit', '.ajaxform', function(event) {
    event.preventDefault();
    $.ajax({
        url: '/askmeQ/',
        type: 'POST',
        data: {name: $('#name').val(),
                csrfmiddlewaretoken: csrftoken
        }
    })
    .done(function() {
        console.log("success");
        $('.formset').slideToggle(400)
        });
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });
});

ERROR

Traceback:

File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__
  77.             list_ = super().__getitem__(key)

During handling of the above exception ('name'), another exception occurred:

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/pc/Django_Projects/vikas/vikas/views.py" in askmeQ
  40.         name = request.POST['name']

File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__
  79.             raise MultiValueDictKeyError(key)

Exception Type: MultiValueDictKeyError at /askmeQ/
Exception Value: 'name'

The logic I use above used to work in all the previous forms, but here it throws me an error.
The SQLite3 table has been created as projectname_model.name.

How can I correct this?

Body:
It seems that the name was not posted with the request. Due to which, you name = request.POST['name'] will throw an error since the key won't be part of the POST dict.

To correct this, alter your code to:

def AskMeQ(request):
    if request.method == POST:
        name = request.POST.get('name')
        if name:
            AskMe.objects.create(name=name)
        # else:
        #     error condition handling


问:
Center Text Larger than Container? (Without using separate child element)
Using CSS, it's easy to horizontally center text in a container using text-align:center;, but if any single word of that text is larger than the width of the container, the browser automatically "clips" to the left boundary of the container (as in, the over-sized word aligns with the left side of the too-small container, and without the CSS word-break:hyphenate; property setting (or similar) the over-sized word sticks out past the right edge of the container.

Any way to float this pic left of my text here to save vertical space? Oh well. Anyway...

Without using a child container element to hold the text, is there a way to center the over-sized word so that it hangs over both left and right sides of the container equally?

Again, I do not want to use a text container within the container. I could do this in 5 seconds by using a child
text to be centered
 with fixed width and negative margin-left, or with absolute positioning of a container element inside a relative div, but I'm looking for a CSS attribute that will center text even when the word is too long to fit the width. By default, text-align:center doesn't do this.

Thoughts? Thanks! -Slink

答:
I use this solution:</p>

```<code>.limited-string {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 90%;
}
</code>```

Body:
I use this solution:

.limited-string {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 90%;
}


问:
VBA not pulling through a format correctly
I have created a userform which when entering a reference will pull through all information within the line of that reference.

I have some data in that line that is formatted 00-00-00 much like a banking sort code. The issue I am finding is although the cell displays 00-00-00 when you view it, when I click the find button on my userform it would pull through blank.

Can someone please help me with this issue please? Below is a sample of my coding The lines referring to the code I am pulling through is VL1, VL2, and VL3. Any of these sequences = 0 it will not pull through.

```<code>Private Sub Find_Click()

Dim searchRange As Range
Dim foundCell As Range
Dim mysearch As String

mysearch = Search.Value

With Sheets("Master Data")
    Set searchRange = Sheets("Master Data").Range("A2", .Range("A" & .Rows.Count).End(xlUp))
End With

Set foundCell = searchRange.Find(what:=mysearch, Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not foundCell Is Nothing Then
    RDesc = foundCell.Offset(0, 4).Value
    BD.Value = foundCell.Offset(0, 6).Value
    Ml.Value = foundCell.Offset(0, 7).Value
    Es.Value = foundCell.Offset(0, 8).Value
    In.Value = foundCell.Offset(0, 9).Value
    Pr.Value = foundCell.Offset(0, 10).Value
    Qt.Value = foundCell.Offset(0, 11).Value
    RC.Value = foundCell.Offset(0, 12).Value
    ROC.Value = foundCell.Offset(0, 13).Value
    Tal.Value = foundCell.Offset(0, 5).Value
    Vu.Value = Me.Total.Value / 1.2
    VT.Value = Me.Total.Value - Me.Value.Value
    R.Value = foundCell.Offset(0, 17).Value
    Ap.Value = foundCell.Offset(0, 18).Value
    L1.Value = foundCell.Offset(0, 19).Value
    L2.Value = foundCell.Offset(0, 20).Value
    Cy.Value = foundCell.Offset(0, 21).Value
    P.Value = foundCell.Offset(0, 22).Value
    VL1.Value = Mid(foundCell.Offset(0, 23).Value, 1, 1) & Mid(foundCell.Offset(0, 23).Value, 2, 1)
    VL2.Value = Mid(foundCell.Offset(0, 23).Value, 3, 1) & Mid(foundCell.Offset(0, 23).Value, 4, 1)
    VL3.Value = Mid(foundCell.Offset(0, 23).Value, 5, 1) & Mid(foundCell.Offset(0, 23).Value, 6, 1)
    Ar.Value = foundCell.Offset(0, 24).Value
    Processed.Value = foundCell.Offset(0, 25).Value
    EntryDate.Value = foundCell.Offset(0, 1).Value
    RDat.Value = foundCell.Offset(0, 27).Value
    StartDate.Value = foundCell.Offset(0, 26).Value

Else
     MsgBox "Uh oh, things have gone a little sideways and the reference number " & Search.Value & " cannot be located. Please try another reference!"
End If

End Sub
</code>```

答:
You could replace this:

```<code> VL1.Value = Mid(foundCell.Offset(0, 23).Value, 1, 1) & Mid(foundCell.Offset(0, 23).Value, 2, 1)
 VL2.Value = Mid(foundCell.Offset(0, 23).Value, 3, 1) & Mid(foundCell.Offset(0, 23).Value, 4, 1)
 VL3.Value = Mid(foundCell.Offset(0, 23).Value, 5, 1) & Mid(foundCell.Offset(0, 23).Value, 6, 1)
</code>```

To this:

```<code> Dim NewValue as String
 NewValue =Format(foundCell.Offset(0, 23).Value, "00-00-00")
 VL1.Value = Mid(NewValue , 1, 2)
 VL2.Value = Mid(NewValue , 4, 2)
 VL3.Value = Mid(NewValue , 7, 2)
</code>```

Body:
I have created a userform which when entering a reference will pull through all information within the line of that reference.

I have some data in that line that is formatted 00-00-00 much like a banking sort code. The issue I am finding is although the cell displays 00-00-00 when you view it, when I click the find button on my userform it would pull through blank.

Can someone please help me with this issue please? Below is a sample of my coding The lines referring to the code I am pulling through is VL1, VL2, and VL3. Any of these sequences = 0 it will not pull through.

Private Sub Find_Click()

Dim searchRange As Range
Dim foundCell As Range
Dim mysearch As String

mysearch = Search.Value

With Sheets("Master Data")
    Set searchRange = Sheets("Master Data").Range("A2", .Range("A" & .Rows.Count).End(xlUp))
End With

Set foundCell = searchRange.Find(what:=mysearch, Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not foundCell Is Nothing Then
    RDesc = foundCell.Offset(0, 4).Value
    BD.Value = foundCell.Offset(0, 6).Value
    Ml.Value = foundCell.Offset(0, 7).Value
    Es.Value = foundCell.Offset(0, 8).Value
    In.Value = foundCell.Offset(0, 9).Value
    Pr.Value = foundCell.Offset(0, 10).Value
    Qt.Value = foundCell.Offset(0, 11).Value
    RC.Value = foundCell.Offset(0, 12).Value
    ROC.Value = foundCell.Offset(0, 13).Value
    Tal.Value = foundCell.Offset(0, 5).Value
    Vu.Value = Me.Total.Value / 1.2
    VT.Value = Me.Total.Value - Me.Value.Value
    R.Value = foundCell.Offset(0, 17).Value
    Ap.Value = foundCell.Offset(0, 18).Value
    L1.Value = foundCell.Offset(0, 19).Value
    L2.Value = foundCell.Offset(0, 20).Value
    Cy.Value = foundCell.Offset(0, 21).Value
    P.Value = foundCell.Offset(0, 22).Value
    VL1.Value = Mid(foundCell.Offset(0, 23).Value, 1, 1) & Mid(foundCell.Offset(0, 23).Value, 2, 1)
    VL2.Value = Mid(foundCell.Offset(0, 23).Value, 3, 1) & Mid(foundCell.Offset(0, 23).Value, 4, 1)
    VL3.Value = Mid(foundCell.Offset(0, 23).Value, 5, 1) & Mid(foundCell.Offset(0, 23).Value, 6, 1)
    Ar.Value = foundCell.Offset(0, 24).Value
    Processed.Value = foundCell.Offset(0, 25).Value
    EntryDate.Value = foundCell.Offset(0, 1).Value
    RDat.Value = foundCell.Offset(0, 27).Value
    StartDate.Value = foundCell.Offset(0, 26).Value

Else
     MsgBox "Uh oh, things have gone a little sideways and the reference number " & Search.Value & " cannot be located. Please try another reference!"
End If

End Sub

Body:
You could replace this:

 VL1.Value = Mid(foundCell.Offset(0, 23).Value, 1, 1) & Mid(foundCell.Offset(0, 23).Value, 2, 1)
 VL2.Value = Mid(foundCell.Offset(0, 23).Value, 3, 1) & Mid(foundCell.Offset(0, 23).Value, 4, 1)
 VL3.Value = Mid(foundCell.Offset(0, 23).Value, 5, 1) & Mid(foundCell.Offset(0, 23).Value, 6, 1)

To this:

 Dim NewValue as String
 NewValue =Format(foundCell.Offset(0, 23).Value, "00-00-00")
 VL1.Value = Mid(NewValue , 1, 2)
 VL2.Value = Mid(NewValue , 4, 2)
 VL3.Value = Mid(NewValue , 7, 2)


问:
C++ inlining class methods causes undefined reference
I'm getting a compiler error when I try to inline a method of one of my classes. It works when I take away the "inline" keyword.

Here's a simplified example:

main.cpp:

```<code>#include "my_class.h"

int main() {
  MyClass c;
  c.TestMethod();

  return 0;
}
</code>```

my_class.h:

```<code>class MyClass {
 public:
  void TestMethod();
};
</code>```

my_class.cpp:

```<code>#include "my_class.h"

inline void MyClass::TestMethod() {
}
</code>```

I try compiling with:

```<code>g++ main.cpp my_class.cpp
</code>```

I get the error:

```<code>main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'
</code>```

Everything is fine if I take away the "inline". What's causing this problem? (and how should I inline class methods? Is it possible?)

Thanks.

答: The body of an inline function needs to be in the header so that the compiler can actually substitute it wherever required. See this: How do you tell the compiler to make a member function inline?</p>

Body:
I'm getting a compiler error when I try to inline a method of one of my classes. It works when I take away the "inline" keyword.

Here's a simplified example:

main.cpp:

#include "my_class.h"

int main() {
  MyClass c;
  c.TestMethod();

  return 0;
}

my_class.h:

class MyClass {
 public:
  void TestMethod();
};

my_class.cpp:

#include "my_class.h"

inline void MyClass::TestMethod() {
}

I try compiling with:

g++ main.cpp my_class.cpp

I get the error:

main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'

Everything is fine if I take away the "inline". What's causing this problem? (and how should I inline class methods? Is it possible?)

Thanks.


问:
Split command in Excel VBA adding a space between every character in array
I am reading a text file and splitting the data string at each space using the following code.

```<code> L = f.ReadLine
        If L = "" Then GoTo errorpoint:
            On Error GoTo errorpoint:
            sl = Split(L, " ", -1)
</code>```

However, the array I get back takes, for example, the word "Contact" in the text file and turns it into " C o n t a c t " in a single cell of my array (see below) and I'm not sure why.

Data Output in VBA Watch Window:

I have tried using

```<code>For i = 0 To UBound(sl)
     sl(i) = Replace(sl(i), " ", "")
Next
</code>```

Afterwards to remove the spaces, but that doesn't appear to be removing the spaces from my data. Any ideas how I can prevent the code from adding a space between every character in the first place?

I then need to check whether sl(1) and sl(2) contain the words "Contact" and "Stress" respectively, but that condition cannot be met currently, the cells contain " C o n t a c t " and " S t r e s s ", so I changed the if loop to reflect that, but the condition is still not met.

In addition, I cannot convert my data from String > Double because of the unusual formatting, it seems.

答:
As @LocEngineer pointed out in the comments, during the update of the external software that produces the text file I was reading, the text encoding had been changed to UTF-16 and the additional characters between my data were chr(0) Null values from the ASCII table, not spaces (chr(32) in ASCII). </p>

```<code>For i = 0 To UBound(sl)
     sl(i) = Replace(sl(i), Chr(0), "")
Next
</code>```

<p>This snippet solved the problem. </p>

Body:
I am reading a text file and splitting the data string at each space using the following code.

 L = f.ReadLine
        If L = "" Then GoTo errorpoint:
            On Error GoTo errorpoint:
            sl = Split(L, " ", -1)

However, the array I get back takes, for example, the word "Contact" in the text file and turns it into " C o n t a c t " in a single cell of my array (see below) and I'm not sure why.

Data Output in VBA Watch Window:

I have tried using

For i = 0 To UBound(sl)
     sl(i) = Replace(sl(i), " ", "")
Next

Afterwards to remove the spaces, but that doesn't appear to be removing the spaces from my data. Any ideas how I can prevent the code from adding a space between every character in the first place?

I then need to check whether sl(1) and sl(2) contain the words "Contact" and "Stress" respectively, but that condition cannot be met currently, the cells contain " C o n t a c t " and " S t r e s s ", so I changed the if loop to reflect that, but the condition is still not met.

In addition, I cannot convert my data from String > Double because of the unusual formatting, it seems.

Body:
As @LocEngineer pointed out in the comments, during the update of the external software that produces the text file I was reading, the text encoding had been changed to UTF-16 and the additional characters between my data were chr(0) Null values from the ASCII table, not spaces (chr(32) in ASCII).

For i = 0 To UBound(sl)
     sl(i) = Replace(sl(i), Chr(0), "")
Next

This snippet solved the problem.


问:
Is there any way I can pass dynamic data to a component in Angular?

I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.

ParentComponent.ts

```<code>results: any[];
ngOnInit() {
this.http.get('url').subscribe(data => this.results = data);
}
</code>```

ParentComponent.html

```<code><app-childComponent [dataNeeded]=results></app-childComponent>
</code>```

ChildComponent.ts

```<code>@Input('dataNeeded') dataNeeded: any[];
ngOnInit() {
 console.log(dataNeeded); //Always undefiend
}
</code>```

So as expected, it doesn't wait for the asynchronous call and returns me undefined. How do i pass the dynamic data to the component?

答:
The problem is that the UI thread will render the child component before the subscribe from the observable finished.

you need to do it like this:

```<code>import { ChangeDetectorRef } from '@angular/core';

constructor(private ref: ChangeDetectorRef) {}
ngOnInit() {
   this.http.get('url').subscribe(data => {
     this.results = data;
     this.ref.markForCheck();
   });
}
</code>```

and in the HTML you have to test the value first.

```<code><ng-container *ngIf="results != null">
    <app-childComponent [dataNeeded]=results></app-childComponent>
</ng-container>
</code>```

A little description, the .markForCheck() will refresh the result after the subscribe and will inform all the components which are using this "value" to update its value, including the ng-container. The container would allow rendering the child component now, which will guarantee that the results are not null when the child will be going through its life cycle.

Body:
I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.

ParentComponent.ts

results: any[];
ngOnInit() {
this.http.get('url').subscribe(data => this.results = data);
}

ParentComponent.html

<app-childComponent [dataNeeded]=results></app-childComponent>

ChildComponent.ts

@Input('dataNeeded') dataNeeded: any[];
ngOnInit() {
 console.log(dataNeeded); //Always undefiend
}

So as expected, it doesn't wait for the asynchronous call and returns me undefined. How do i pass the dynamic data to the component?

Body:
The problem is that the UI thread will render the child component before the subscribe from the observable finished.

you need to do it like this:

import { ChangeDetectorRef } from '@angular/core';

constructor(private ref: ChangeDetectorRef) {}
ngOnInit() {
   this.http.get('url').subscribe(data => {
     this.results = data;
     this.ref.markForCheck();
   });
}

and in the HTML you have to test the value first.

<ng-container *ngIf="results != null">
    <app-childComponent [dataNeeded]=results></app-childComponent>
</ng-container>

A little description, the .markForCheck() will refresh the result after the subscribe and will inform all the components which are using this "value" to update its value, including the ng-container. The container would allow rendering the child component now, which will guarantee that the results are not null when the child will be going through its life cycle.


问:
What does "-" do in Powershell
I'm new to powershell and I'm still trying to understand the syntax.
In a command like this

```<code>Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt$','.log' }
</code>```

What does - actually do?
Sometimes it is there, sometimes not, and I just don't understand what purpose it has xD

答:
-LiteralPath is what the meaning of using -. It's for paramters.

From your example, -NewName is treated as a parameter and -Replace is the operator

EDIT: As Peter rightly pointed out; amended the answer

Title: What does "-" do in Powershell

Body:
I'm new to powershell and I'm still trying to understand the syntax.
In a command like this

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt$','.log' }

What does - actually do?
Sometimes it is there, sometimes not, and I just don't understand what purpose it has xD


问:
Select Particular Date using Python Selenium (Rollover dates)
All,

We are trying to automate the date picking process  for reference Click here! . Please refer date of birth  and Appointment date fields. The way we select date is is different. I am not able to get any idea about selecting the dates for both the fields. Could you please help me?

I have tried my best and it's working with below code except date fields

Python version : 2.7
Selenium 3.8.0
Chrome : 48X

```<code>    import selenium
    import sys
    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.chrome.options import Options
    #profile = webdriver.FirefoxProfile()
    #profile.accept_untrusted_certs = True
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    chrome_options = Options()
    chrome_options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=chrome_options)

    driver.get('https://reentryvisa.inis.gov.ie/website/INISOA/IOA.nsf/AppointmentSelection?OpenForm');

    wait = WebDriverWait(driver, 10)
    driver.find_element_by_id('btCom').click()

    username = driver.find_element_by_id('GivenName')
    username.send_keys("First name here ")

    username = driver.find_element_by_id('Surname')
    username.send_keys("Surname here")

    username = driver.find_element_by_id('DOB')
    username.click()
 ActionChains(driver).move_to_element(username).click().send_keys('01/01/2011').perform()

    username = driver.find_element_by_id('Appdate')
    username.send_keys("12345")
</code>```

I tried seeing the html for id names etc but I dint find anything specific to year date or month. All I got was below code

```<code>    <script src="/website/INISOA/IOA.nsf/bootstrap-datepicker.js"></script>
    <link href="/website/INISOA/IOA.nsf/datepicker3.css" rel="stylesheet">

    <div class="form-group">
    <label class="control-label col-sm-3 col-md-3 col-lg-2" for="DOB">* Date    of Birth:</label>
    <div class="col-sm-3 col-md-3 col-lg-3">
    <div class="input-group date dobdate">

    <input name="DOB" value="" id="DOB" class="form-control readonlywhite"  placeholder="Date of birth" readonly>
    <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
    </div>
    </div>
</code>```

Please help me show away to select  the dates in both the fields (Date of birth and Appointment date)

答:
html for date/month/year popup is not under 'DOB input'. you can select the  popups using below selectors</p>

```<code>datePopup = driver.find_element_by_class('datepicker-days')
monthPopup = driver.find_element_by_class('datepicker-month')
yearPopup = driver.find_element_by_class('datepicker-years')
</code>```

Body:
All,

We are trying to automate the date picking process  for reference Click here! . Please refer date of birth  and Appointment date fields. The way we select date is is different. I am not able to get any idea about selecting the dates for both the fields. Could you please help me?

I have tried my best and it's working with below code except date fields

Python version : 2.7
Selenium 3.8.0
Chrome : 48X

    import selenium
    import sys
    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.chrome.options import Options
    #profile = webdriver.FirefoxProfile()
    #profile.accept_untrusted_certs = True
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    chrome_options = Options()
    chrome_options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=chrome_options)

    driver.get('https://reentryvisa.inis.gov.ie/website/INISOA/IOA.nsf/AppointmentSelection?OpenForm');

    wait = WebDriverWait(driver, 10)
    driver.find_element_by_id('btCom').click()

    username = driver.find_element_by_id('GivenName')
    username.send_keys("First name here ")

    username = driver.find_element_by_id('Surname')
    username.send_keys("Surname here")

    username = driver.find_element_by_id('DOB')
    username.click()
 ActionChains(driver).move_to_element(username).click().send_keys('01/01/2011').perform()

    username = driver.find_element_by_id('Appdate')
    username.send_keys("12345")

I tried seeing the html for id names etc but I dint find anything specific to year date or month. All I got was below code

    <link href="/website/INISOA/IOA.nsf/datepicker3.css" rel="stylesheet">

    * Date    of Birth:

    <input name="DOB" value="" id="DOB" class="form-control readonlywhite"  placeholder="Date of birth" readonly>

Please help me show away to select  the dates in both the fields (Date of birth and Appointment date)

Body:
html for date/month/year popup is not under 'DOB input'. you can select the  popups using below selectors

datePopup = driver.find_element_by_class('datepicker-days')
monthPopup = driver.find_element_by_class('datepicker-month')
yearPopup = driver.find_element_by_class('datepicker-years')


问:
Phoenix is ignoring csrf_token for an ajax request
I have this ajax request:

```<code>//..............
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
xhr.setRequestHeader("x-csrf-token", document.querySelector("meta[name=csrf]").content);
xhr.send(JSON.stringify(data));
</code>```

On a page there's a csrf token generated by Phoenix.

```<code><meta name="csrf" content="<%= Plug.CSRFProtection.get_csrf_token() %>" />
</code>```

It's sent on a server along with each ajax request I can see in Chrome. But my server always returns:

```<code>"403: invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid '_csrf_token' param or 'x-csrf-token' header"
</code>```

Why? How to fix this?

答:
I think the name should be "csrf-token" instead of just "csrf". This is what I use in app.html.eex (it's from the ex_turbolinks library readme.

```<code><meta name="csrf-token" content="<%= get_csrf_token() %>">
<meta name="csrf-param" content="_csrf_token">
</code>```

In order to use just get_csrf_token/0 in the view, however, you have to add get_csrf_token: 0 to the list of imports from Phoenix.Controller in the view function in my_app_web.ex. For example:

```<code>lib/my_app_web.ex

def view do
  quote do
  ...
  # Import convenience functions from controllers
  import Phoenix.Controller, only: [get_flash: 2, view_module: 1,
  get_csrf_token: 0]
  ...
  end
end
</code>```

Body:
I have this ajax request:

//..............
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
xhr.setRequestHeader("x-csrf-token", document.querySelector("meta[name=csrf]").content);
xhr.send(JSON.stringify(data));

On a page there's a csrf token generated by Phoenix.

<meta name="csrf" content="<%= Plug.CSRFProtection.get_csrf_token() %>" />

It's sent on a server along with each ajax request I can see in Chrome. But my server always returns:

"403: invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid '_csrf_token' param or 'x-csrf-token' header"

Why? How to fix this?

Body:
I think the name should be "csrf-token" instead of just "csrf". This is what I use in app.html.eex (it's from the ex_turbolinks library readme.

<meta name="csrf-token" content="<%= get_csrf_token() %>">
<meta name="csrf-param" content="_csrf_token">

In order to use just get_csrf_token/0 in the view, however, you have to add get_csrf_token: 0 to the list of imports from Phoenix.Controller in the view function in my_app_web.ex. For example:

lib/my_app_web.ex

def view do
  quote do
  ...
  # Import convenience functions from controllers
  import Phoenix.Controller, only: [get_flash: 2, view_module: 1,
  get_csrf_token: 0]
  ...
  end
end


答:
This is an absurd requirement, but here is one way to do it:

```<code>newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}

while newDict:
  x = next(x for x in newDict)
  print(x, newDict.pop(x))
</code>```

CAUTION:

After the while has finished executing, newDIct will be empty.

Title: Printing dictionary in a While Loop

Body:
I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}

I created this dict and I want to use a while loop to output it this way:

Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30

I am able to do it with a for loop, just curious how it can be done with a while loop.

Body:
This is an absurd requirement, but here is one way to do it:

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}

while newDict:
  x = next(x for x in newDict)
  print(x, newDict.pop(x))

CAUTION:

After the while has finished executing, newDIct will be empty.


问:
WP7 - Why are my bindings not firing when the windows back button is pressed?
Hopefully there is an obvious answer to this that my brain at 2am is not seeing (I'm basing this on the fact I can't find anyone else with the same problem).

When I press the "hardware/built in" back button on my windows phone 7 none of my bindings are re-evaluating. For example on my MainPage I have a button's "IsEnabled" bound to a bool property in my ViewModel that checks if a value is in isolated storage. In the emulator it starts as disabled (obviously).  I then navigate to another page and add the required value to isolated storage. When i press the hardware back button to return to the original page the binding does not get re-evaluated and my button remains disabled.

However if I go back to MainPage via code using the navigate method the binding gets re-evaluated and everything is good.

Any ideas as to why?

答:
The issue sounds like the RaisePropertyChanged method isn't being raised by your MVVM Light ViewModel - if you're binding Get{} accessor of your IsEnabled property on the viewmodel directly to a value in IsolatedStorage, then the ViewModel isn't going to know that that underlying value has necessarily changed.

When you write the value to IsolatedStorage, you can use the Messenger interface in MVVM to notify the ViewModel-in-question that it should fire the RaisePropertyChanged() event for your model, and that will re-bind that property in your view.


问:
Arc SVG Parameters
I've been trying to understand arc svg since it seems I need them in plotly -- my goal is to plot circle intersections.

My original idea was something like this:

for every intersection, to find the start and end coordinates as well as the height - but I am not very sure of where to go from here. It seems I am lacking the rotation and Large Arc Flag / Sweep parameters, and I am not sure how I would go about retrieving them. If anyone could point me into the right direction here, that would be great!

答:
Circles and intercepting points

MDN gives "A rx,ry xAxisRotate LargeArcFlag,SweepFlag x,y" as an arc in the path element. What are rx and ry? I would guess radius for x,y.

I am guessing you would use it as

```<code>// x,y start position
// rx,ry radius x and y
// x1,y1 end position
<path d="M x,y A rx, ry, 0 1 1 x1, y1"/>
</code>```

Below is the problem solved as javascript. I have Commented the part you need for the SVG. The two end points (intercepts)

There is a lot of redundancy but its not clear what you want so the code provides how to find other parts of two intersecting circles.

Law of Cosines

The math to solve the problem is called the law of cosines that is used to solve triangles.

In this case the triangle is created from 3 lengths. One each of the circle radius and one is the distance between circle centers. The image gives more details

With the angle c you can find the lengths GE, DE, and EF. If you want the angle for the other side at point f just swap B and C.

Example

Move mouse to check intercept.

const ctx = canvas.getContext("2d");
const m = {
  x: 0,
  y: 0
};
document.addEventListener("mousemove", e => {
  var b = canvas.getBoundingClientRect();
  m.x = e.pageX - b.left - scrollX;
  m.y = e.pageY - b.top - scrollY;
});
const PI = Math.PI;
const PI2 = Math.PI * 2;
const circles = [];

function circle(x, y, r, col, f = 0, t = PI2, w = 2) {
  var c;
  circles.push(c = { x, y,r, col, f, t, w});
  return c;
};

function drawCircle(A) {
  ctx.strokeStyle = A.col;
  ctx.lineWidth = A.w;
  ctx.beginPath();
  ctx.arc(A.x, A.y, A.r, A.f, A.t);
  ctx.stroke();
}

function mark(x, y, r, c) {
  ctx.strokeStyle = c;
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.arc(x, y, r, 0, PI2);
  ctx.stroke();
}

function line(A, B, c) {
  ctx.strokeStyle = c;
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.lineTo(A.x, A.y);
  ctx.lineTo(B.x, B.y);
  ctx.stroke();
}

// note I am sharing calc results between function

function circleIntercept(A, B) {
  var vx, vy, dist, c, d, x, y, x1, y1, x2, y2, dir, a1, a2;
  // Vec from A to B
  vx = B.x - A.x;
  vy = B.y - A.y;
  // Distance between
  dist = Math.sqrt(vx * vx + vy * vy);
  // Are the intercepting
  if (dist  B.r - A.r) {
    c = (B.r * B.r - (dist * dist + A.r * A.r)) / (-2 * dist);

    // Find mid point on cord
    x = A.x + vx * (c / dist);
    y = A.y + vy * (c / dist);
    mark(x, y, 5, "blue");

    // Find circumference intercepts

    //#################################################################
    //=================================================================
    // SVG path
    // Use x1,y1 and x2,y2 as the start and end angles of the ArcTo SVG
    d = Math.sqrt(A.r * A.r - c * c);
    x1 = x - vy * (d / dist);
    y1 = y + vx * (d / dist);
    x2 = x + vy * (d / dist);
    y2 = y - vx * (d / dist);
    // SVG path from above coords
    // d = `M ${x1}, ${y1} A ${A.r}, ${A,r1} 0, 1, 1, ${x2}, ${y2}`;
    //=================================================================

    // draw the chord
    line({x: x1,y: y1}, {x: x2,y: y2}, "red");

    // mark the intercepts
    mark(x1, y1, 5, "Green");
    mark(x2, y2, 5, "Orange");

    // Get direction from A to B
    dir = Math.atan2(vy, vx);

    // Get half inside sweep
    a1 = Math.acos(c / A.r);

    // Draw arc for A
    A.col = "black";
    A.w = 4;
    A.f = dir - a1;
    A.t = dir + a1;
    drawCircle(A);
    A.col = "#aaa";
    A.w = 2;
    A.f = 0;
    A.t = PI2;

    // inside sweep for B
    a2 = Math.asin(d / B.r);

    // Draw arc for B
    B.col = "black";
    B.w = 4;
    if (dist < c) {
      B.t = dir - a2;
      B.f = dir + a2;
    } else {

      B.f = dir + PI - a2;
      B.t = dir + PI + a2;
    }
    drawCircle(B);
    B.col = "#aaa";
    B.w = 2;
    B.f = 0;
    B.t = PI2;

  }

}

var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
var C1 = circle(cw, ch, ch * 0.5, "#aaa");
var C2 = circle(cw, ch, ch * 0.8, "#aaa");

function update(timer) {
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.globalAlpha = 1;
  if (w !== innerWidth || h !== innerHeight) {
    cw = (w = canvas.width = innerWidth) / 2;
    ch = (h = canvas.height = innerHeight) / 2;
    C1.x = cw;
    C1.y = ch;
    C1.r = ch * 0.5;
    ctx.lineCap = "round";
  }
  C2.x = m.x;
  C2.y = m.y;
  ctx.clearRect(0, 0, w, h);

  drawCircle(C1);
  drawCircle(C2);
  circleIntercept(C1, C2);

  requestAnimationFrame(update);
}
requestAnimationFrame(update);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  position: absolute;
  top: 0px;
  left: 0px;
}</code>```

<canvas id="canvas"></canvas>```

Title: Arc SVG Parameters

Body:
Circles and intercepting points

MDN gives "A rx,ry xAxisRotate LargeArcFlag,SweepFlag x,y" as an arc in the path element. What are rx and ry? I would guess radius for x,y.

I am guessing you would use it as

// x,y start position
// rx,ry radius x and y
// x1,y1 end position
<path d="M x,y A rx, ry, 0 1 1 x1, y1"/>

Below is the problem solved as javascript. I have Commented the part you need for the SVG. The two end points (intercepts)

There is a lot of redundancy but its not clear what you want so the code provides how to find other parts of two intersecting circles.

Law of Cosines

The math to solve the problem is called the law of cosines that is used to solve triangles.

In this case the triangle is created from 3 lengths. One each of the circle radius and one is the distance between circle centers. The image gives more details

With the angle c you can find the lengths GE, DE, and EF. If you want the angle for the other side at point f just swap B and C.

Example

Move mouse to check intercept.

const ctx = canvas.getContext("2d");
const m = {
  x: 0,
  y: 0
};
document.addEventListener("mousemove", e => {
  var b = canvas.getBoundingClientRect();
  m.x = e.pageX - b.left - scrollX;
  m.y = e.pageY - b.top - scrollY;
});
const PI = Math.PI;
const PI2 = Math.PI * 2;
const circles = [];

function circle(x, y, r, col, f = 0, t = PI2, w = 2) {
  var c;
  circles.push(c = { x, y,r, col, f, t, w});
  return c;
};

function drawCircle(A) {
  ctx.strokeStyle = A.col;
  ctx.lineWidth = A.w;
  ctx.beginPath();
  ctx.arc(A.x, A.y, A.r, A.f, A.t);
  ctx.stroke();
}

function mark(x, y, r, c) {
  ctx.strokeStyle = c;
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.arc(x, y, r, 0, PI2);
  ctx.stroke();
}

function line(A, B, c) {
  ctx.strokeStyle = c;
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.lineTo(A.x, A.y);
  ctx.lineTo(B.x, B.y);
  ctx.stroke();
}

// note I am sharing calc results between function

function circleIntercept(A, B) {
  var vx, vy, dist, c, d, x, y, x1, y1, x2, y2, dir, a1, a2;
  // Vec from A to B
  vx = B.x - A.x;
  vy = B.y - A.y;
  // Distance between
  dist = Math.sqrt(vx * vx + vy * vy);
  // Are the intercepting
  if (dist < A.r + B.r && dist > B.r - A.r) {
    c = (B.r * B.r - (dist * dist + A.r * A.r)) / (-2 * dist);

    // Find mid point on cord
    x = A.x + vx * (c / dist);
    y = A.y + vy * (c / dist);
    mark(x, y, 5, "blue");

    // Find circumference intercepts

    //#################################################################
    //=================================================================
    // SVG path
    // Use x1,y1 and x2,y2 as the start and end angles of the ArcTo SVG
    d = Math.sqrt(A.r * A.r - c * c);
    x1 = x - vy * (d / dist);
    y1 = y + vx * (d / dist);
    x2 = x + vy * (d / dist);
    y2 = y - vx * (d / dist);
    // SVG path from above coords
    // d = `M ${x1}, ${y1} A ${A.r}, ${A,r1} 0, 1, 1, ${x2}, ${y2}`;
    //=================================================================

    // draw the chord
    line({x: x1,y: y1}, {x: x2,y: y2}, "red");

    // mark the intercepts
    mark(x1, y1, 5, "Green");
    mark(x2, y2, 5, "Orange");

    // Get direction from A to B
    dir = Math.atan2(vy, vx);

    // Get half inside sweep
    a1 = Math.acos(c / A.r);

    // Draw arc for A
    A.col = "black";
    A.w = 4;
    A.f = dir - a1;
    A.t = dir + a1;
    drawCircle(A);
    A.col = "#aaa";
    A.w = 2;
    A.f = 0;
    A.t = PI2;

    // inside sweep for B
    a2 = Math.asin(d / B.r);

    // Draw arc for B
    B.col = "black";
    B.w = 4;
    if (dist < c) {
      B.t = dir - a2;
      B.f = dir + a2;
    } else {

      B.f = dir + PI - a2;
      B.t = dir + PI + a2;
    }
    drawCircle(B);
    B.col = "#aaa";
    B.w = 2;
    B.f = 0;
    B.t = PI2;

  }

}

var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
var C1 = circle(cw, ch, ch * 0.5, "#aaa");
var C2 = circle(cw, ch, ch * 0.8, "#aaa");

function update(timer) {
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.globalAlpha = 1;
  if (w !== innerWidth || h !== innerHeight) {
    cw = (w = canvas.width = innerWidth) / 2;
    ch = (h = canvas.height = innerHeight) / 2;
    C1.x = cw;
    C1.y = ch;
    C1.r = ch * 0.5;
    ctx.lineCap = "round";
  }
  C2.x = m.x;
  C2.y = m.y;
  ctx.clearRect(0, 0, w, h);

  drawCircle(C1);
  drawCircle(C2);
  circleIntercept(C1, C2);

  requestAnimationFrame(update);
}
requestAnimationFrame(update);

canvas {
  position: absolute;
  top: 0px;
  left: 0px;
}

<canvas id="canvas"></canvas>


问:
Change type of list elements from numpy.int64 to int
```<code>{
    "key1" : <list of strings>,
    "key2" : <list of integeres> }
</code>```

I want to change type of 'key2' list to int.
I have already tried looping over and using

v = int(v)

I have also tried mapping int to whole list.

map(int, list)

Any other way I can accomplish this task?

Current Code:

```<code>integer_columns = ["col1","col2","col3","col4"]
for col in integer_columns:
    col_list = config_data[col]
    col_list = list(map(int, col_list))
</code>```

答:
What's wrong with map?

d['key2'] = map(int, d['key2']) or d['key2'] = list(map(int, d['key2'])) on Python 3:

```<code>d = {'key2': ['1', '2', '3']}
print(d)
d['key2'] = list(map(int, d['key2']))
print(d)
</code>```

Outputs

```<code>{'key2': ['1', '2', '3']}
{'key2': [1, 2, 3]}
</code>```

Edit after OP updated the question

```<code>for col in integer_columns:
    col_list = config_data[col]          # col_list references to config_data[col]

    col_list = list(map(int, col_list))  # now col_list references to an entire
                                         # new list of ints, that has nothing to do
                                         # with config_data[col]
</code>```

col_list is being modified, but this change is not reflected back to config_data[col]. Instead, do something similar to what I showed in my original answer above:

```<code>for col in integer_columns:
    config_data[col] = list(map(int, config_data[col]))
</code>```

Body:
{
    "key1" : <list of strings>,
    "key2" : <list of integeres> }

I want to change type of 'key2' list to int.
I have already tried looping over and using

v = int(v)

I have also tried mapping int to whole list.

map(int, list)

Any other way I can accomplish this task?

Current Code:

integer_columns = ["col1","col2","col3","col4"]
for col in integer_columns:
    col_list = config_data[col]
    col_list = list(map(int, col_list))

Body:
What's wrong with map?

d['key2'] = map(int, d['key2']) or d['key2'] = list(map(int, d['key2'])) on Python 3:

d = {'key2': ['1', '2', '3']}
print(d)
d['key2'] = list(map(int, d['key2']))
print(d)

Outputs

{'key2': ['1', '2', '3']}
{'key2': [1, 2, 3]}

Edit after OP updated the question

for col in integer_columns:
    col_list = config_data[col]          # col_list references to config_data[col]

    col_list = list(map(int, col_list))  # now col_list references to an entire
                                         # new list of ints, that has nothing to do
                                         # with config_data[col]

col_list is being modified, but this change is not reflected back to config_data[col]. Instead, do something similar to what I showed in my original answer above:

for col in integer_columns:
    config_data[col] = list(map(int, config_data[col]))