问:
How to convert int to String(?) in JNI?
I had got a int[ ] array, and I want to convert each element of it into String(?) in JNI, and finally concatenate them as a String(?) (include the comma).

For example:

```<code>// java code
int testIntArray = new int[]{1, 2, 3};
String arrayString = "";

jni.constructArrayString(testIntArray, arrayString);

// the print content should like this: 1,2,3
System.out.println("ArrayString: " + arrayString);
</code>```

```<code>// jni code
JNIEXPORT void JNICALL constructArrayString (JNIEnv *env, jobject obj, jintArray jArr, jstring jstr) {
    // to do sth.
    // code maybe like the follow

    jint *arr = env -> GetIntArrayElements(jArr, 0);
    int len = env -> GetArrayLength(jArr);
    char *c_str = env -> GetStringUTFChars(jstr, 0);

    if(c_str == NULL) {
        return;
    }

    for(int i = 0; i < len; i++){
        // how to concatenate the arr[i], arr[i+1] and the comma ','
        // and finally make the arrayString like the string: 1,2,3 ?
    }
}
</code>```

I know that, there's no a direct way which just can convert the int-type into string-type data or something else but should be operable in JNI, and concatenate them as a String at last!

If it is hard to do with the void return-type, just change it! Thanx, in advance!

===========================================================================
New problem:

First, thanks @Jorn Vernee answer so much, it's seems the good way I should take. However, when I'm trying this way, there's comes an intractable problem about the std::stringstream. Well, even instantiating it will crash the application. And, sadly I'm new to JNI, have no experience in debugging a crash problem with JVM runtime error. And I had checked @Moe Bataineh question which really seems like me, however it's applying on Windows with MiniGW or Cygwin something I don't know, so it's hlepless for me.

Code in JNI like this:

```<code>#include "utils_JniInterface.h"
#include <android/log.h>
#include <string.h>
#include <iostream>
#include <sstream>

using namespace std;

#define TAG "JNI-Log"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)

JNIEXPORT jstring JNICALL Java_utils_JniInterface_constructRGBArrayString (JNIEnv *env, jobject obj, jintArray jArr){
    jint *arr = env -> GetIntArrayElements(jArr, 0);
    int len = env -> GetArrayLength(jArr);

    std::stringstream result;

    for(int i = 0; i < len; i++) {
        result << arr[i];

        if(i < len - 1) {
            result << ',';
        }
    }

    env -> ReleaseIntArrayElements(jArr, arr, 0);

    return env -> NewStringUTF(result.str().data());
}

// int[] a = {1,2,3} ⇒ String b = "1,2,3"
</code>```

Any good ideas or suggestions about this problem?

答:
helpful link: Issue regarding iostream in android NDK

 When utilizing std::stringstream ,I also got the following error;

fatal error: 'sstream' file not found

```<code>#include <sstream>
</code>```

^ 1 error generated.

Solution that helped me was creating a file called "Application.mk" (Note: case-sensitive). The only line you need to add is:

APP_STL := stlport_static

Put the "Application.mk" file in your "jni" folder this is same location your "Android.mk" file is. This worked for me in eclipse, and I can assume it works for android studio too.

Here's a link with alternatives: Android ndk-build iostream: No such file or directory

Hope this helps @frank jorsn

Title: How to convert int to String(?) in JNI?

Body:
I had got a int[ ] array, and I want to convert each element of it into String(?) in JNI, and finally concatenate them as a String(?) (include the comma).

For example:

// java code
int testIntArray = new int[]{1, 2, 3};
String arrayString = "";

jni.constructArrayString(testIntArray, arrayString);

// the print content should like this: 1,2,3
System.out.println("ArrayString: " + arrayString);

// jni code
JNIEXPORT void JNICALL constructArrayString (JNIEnv *env, jobject obj, jintArray jArr, jstring jstr) {
    // to do sth.
    // code maybe like the follow

    jint *arr = env -> GetIntArrayElements(jArr, 0);
    int len = env -> GetArrayLength(jArr);
    char *c_str = env -> GetStringUTFChars(jstr, 0);

    if(c_str == NULL) {
        return;
    }

    for(int i = 0; i < len; i++){
        // how to concatenate the arr[i], arr[i+1] and the comma ','
        // and finally make the arrayString like the string: 1,2,3 ?
    }
}

I know that, there's no a direct way which just can convert the int-type into string-type data or something else but should be operable in JNI, and concatenate them as a String at last!

If it is hard to do with the void return-type, just change it! Thanx, in advance!

===========================================================================
New problem:

First, thanks @Jorn Vernee answer so much, it's seems the good way I should take. However, when I'm trying this way, there's comes an intractable problem about the std::stringstream. Well, even instantiating it will crash the application. And, sadly I'm new to JNI, have no experience in debugging a crash problem with JVM runtime error. And I had checked @Moe Bataineh question which really seems like me, however it's applying on Windows with MiniGW or Cygwin something I don't know, so it's hlepless for me.

Code in JNI like this:

#include "utils_JniInterface.h"
#include <android/log.h>
#include <string.h>
#include <iostream>
#include <sstream>

using namespace std;

#define TAG "JNI-Log"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)

JNIEXPORT jstring JNICALL Java_utils_JniInterface_constructRGBArrayString (JNIEnv *env, jobject obj, jintArray jArr){
    jint *arr = env -> GetIntArrayElements(jArr, 0);
    int len = env -> GetArrayLength(jArr);

    std::stringstream result;

    for(int i = 0; i < len; i++) {
        result << arr[i];

        if(i < len - 1) {
            result << ',';
        }
    }

    env -> ReleaseIntArrayElements(jArr, arr, 0);

    return env -> NewStringUTF(result.str().data());
}

// int[] a = {1,2,3} ⇒ String b = "1,2,3"

Any good ideas or suggestions about this problem?

Body:
helpful link: Issue regarding iostream in android NDK

 When utilizing std::stringstream ,I also got the following error;

fatal error: 'sstream' file not found

#include <sstream>

^ 1 error generated.

Solution that helped me was creating a file called "Application.mk" (Note: case-sensitive). The only line you need to add is:

APP_STL := stlport_static

Put the "Application.mk" file in your "jni" folder this is same location your "Android.mk" file is. This worked for me in eclipse, and I can assume it works for android studio too.

Here's a link with alternatives: Android ndk-build iostream: No such file or directory

Hope this helps @frank jorsn


来源: stackexchange

问:
Is it possible to rotate a (Surface)UserControl by 180 degree?
Is there a simple method that allows to rotate a UI element like for example a UserControl resp. a SurfaceUserControl by 180 degree?</p>

答: You can set RotateTransform.

OwnerDisplayName: anon

ContentLicense: CC BY-SA 2.5

Body: You can set RotateTransform.


问:
looking for code which validate javascript variable name
I need to get some javascript variable names from user. And user can enter only valid variable names. For instance:

```<code>"test1" - valid input,
"test 1" - not valid input.
"_a" - valid.
</code>```

Now I am looking for php code which can validate user input with javascript variable naming standards.

答:
If you are not expecting any unicode values, here is a regex you can try:

```<code>if(preg_match('/^[a-zA-Z_$][0-9a-zA-Z_$]*$/', $jsVar, $matches)){
     var_dump($matches);
}
</code>```

Regex Demo, PHP Demo

ContentLicense: CC BY-SA 3.0

Body:
I need to get some javascript variable names from user. And user can enter only valid variable names. For instance:

"test1" - valid input,
"test 1" - not valid input.
"_a" - valid.

Now I am looking for php code which can validate user input with javascript variable naming standards.

Body:
If you are not expecting any unicode values, here is a regex you can try:

if(preg_match('/^[a-zA-Z_$][0-9a-zA-Z_$]*$/', $jsVar, $matches)){
     var_dump($matches);
}

Regex Demo, PHP Demo


问:
Where does raw geoip data come from?
This question is a general version of a more specific question asked here.  However, those answers were unusable.

Question: What is the raw source for geoIP data?

Many websites will tell me where my IP is, but they all appear to be using databases from fewer than 5 companies (most are using a database from MaxMind).  These companies offer limited free versions of their databases, but I'm trying to determine what they're using for their source data?

I've tried using Linux/Unix commands such as ping, traceroute, dig, whois, etc., but they don't provide predictably accurate information.

答:
Preamble: I believe this is actually a very valid question for SO website as understanding how such things work is important to understanding how such datasets can be used in software. However the answer to this question is rather complex and full of historical remarks.

First - it is worth mentioning that there is NO unified raw geoip data. Such thing just does not exist. Second - the data for this comes from multiple resources and often is not reliable and/or outdated.

To understand how that comes to be one need to know how Internet came into existence and spread around the world. Short summary is below:

IANA is a global [non-profit] organization which manages assignment of IP blocks to regional organizations: https://www.iana.org/numbers This happens upon request and regional organization requests specified block size

Regional organizations may assign those IP blocks to either ISP directly or to country level sub-organizations (who would assign that to ISP then).

ISP assigns IP addresses to local branches etc.

From above you can easily see that:

There is no single body which is responsible for IP block assignment to this or that location

Decisions how to (and whether to) release information about which IP belongs to which location are not taken uniformly and instead each organizations decides how to (and whether do it at all) release that information

All of above creates a whole lot of mess. It takes a lot of dedication and long time to obtain, aggregate and sort this data. And this is why most up-to-date and detailed geoip datasets are commercial commodity.

Whoever takes on a challenge of building their own dataset should be able to obtain this information directly from end users (ISPs), because higher level organizations do not know to which location each IP address will be assigned. Higher level organizations only distribute IP blocks among applicants (and keep some reserve for faster processing) and it is a lowest level organizations who decide which location gets which IP address and they are not obligated to release this information publicly.

UPD:
To start building your own dataset you can begin with this list of blocks and how they are assigned

ContentLicense: CC BY-SA 4.0

Title: Where does raw geoip data come from?


问:
How to save ACF data to a unique post and user combination
On a Wordpress site I have authors who can submit content and editors who can evaluate and comment on it. Submitted content uses it's own post type and evaluation is done showing a ACF 5 form with text and star rating fields.

My problem is a conceptual one, namely where to save evaluation data to:

I can't save it to the post as there have to be evaluations of different editors.

I can't save it to the user (neither author nor editor) as authors can submit various contents and editors can evaluate different contents.

So I would need to save the evaluations neither to submitted content (post_1, post_2, ...) nor to evaluators (user_1, user_2, ...) but to a unique post and user combination (evaluation_1_1, evaluation_1_2, ...):

How is the common way to do so? Do I have to create a new content type "evaluation" with references to submitted content and to evaluating editor and make queries on each evaluation to know if content already has been evaluated?

Or is there an easier way to go? I think of something like a custom $post_id:

```<code>'post_id' => "post_".$post_id."_".$uid,
</code>```

答:
Thanks to the help at ACF forum I could resolve this issue. The trick is to save evaluation data as array.

I implemented this using a standard ACF form group loaded from the single.php template and adding the following hooks:

Hook into acf/update_value and retrieve value:

$value = get_post_meta( $post_id, $field['name']);

In the same hook overwrite $value as an array:

$value[get_current_user_id()] = $value;

Hook into acf/load_field and retrieve value:

$value = get_post_meta(get_the_ID(), $field['name']);

In the same hook extract value from array:

$field['value'] = $value[0][get_current_user_id()];

Body:
On a Wordpress site I have authors who can submit content and editors who can evaluate and comment on it. Submitted content uses it's own post type and evaluation is done showing a ACF 5 form with text and star rating fields.

My problem is a conceptual one, namely where to save evaluation data to:

I can't save it to the post as there have to be evaluations of different editors.

I can't save it to the user (neither author nor editor) as authors can submit various contents and editors can evaluate different contents.

So I would need to save the evaluations neither to submitted content (post_1, post_2, ...) nor to evaluators (user_1, user_2, ...) but to a unique post and user combination (evaluation_1_1, evaluation_1_2, ...):

How is the common way to do so? Do I have to create a new content type "evaluation" with references to submitted content and to evaluating editor and make queries on each evaluation to know if content already has been evaluated?

Or is there an easier way to go? I think of something like a custom $post_id:

'post_id' => "post_".$post_id."_".$uid,


问:
DexArchiveMergerException with Android Studio 3.0
Having compilation error with the following build.gradle details :

Top-Level build.gradle

```<code>buildscript {
repositories {
    google()
    jcenter()
    mavenCentral()
 }
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
 }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://maven.google.com' }
    }
}

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

App-Level build.gradle

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

    android {
        compileSdkVersion 27
        defaultConfig {
            applicationId "com.abc"
            minSdkVersion 15
            targetSdkVersion 27
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            multiDexEnabled true

            dataBinding {
                enabled true
            }

            dexOptions {
                javaMaxHeapSize "4g"
            }
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

        // Android
        implementation 'com.android.support:appcompat-v7:27.+'
        implementation 'com.android.support:support-v4:27.+'
        implementation 'com.android.support:support-annotations:27.+'

        // RxJava & RxAndroid
        implementation 'io.reactivex.rxjava2:rxandroid:2.+'
        implementation 'io.reactivex.rxjava2:rxjava:2.+'
        implementation 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.4@aar'

        //Glide for images
        implementation 'com.github.bumptech.glide:glide:4.+'
        annotationProcessor 'com.github.bumptech.glide:compiler:4.+'

        // Retrofit : Network
        implementation 'com.squareup.retrofit2:retrofit:2.+'
        implementation 'com.squareup.retrofit2:converter-jackson:2.+'
        implementation 'com.google.code.gson:gson:2.+'

        // Multidex
        implementation 'com.android.support:multidex:1.+'

    }
</code>```

This is the error

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  com.android.builder.dexing.DexArchiveMergerException: com.android.tools.r8.errors.CompilationError: Program type already present: android.support.v4.app.ActionBarDrawerToggle$DelegateProvider

答:
first, try this

clean your project

then rebuild

if the problem still remains

invalidate catch and restart from the file menu.

and at last if still problem remains try this

delete

\build

.idea

.gradle

app\build

then rebuild. hope this help;).

Body:
Having compilation error with the following build.gradle details :

Top-Level build.gradle

buildscript {
repositories {
    google()
    jcenter()
    mavenCentral()
 }
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
 }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://maven.google.com' }
    }
}

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

App-Level build.gradle

    apply plugin: 'com.android.application'

    android {
        compileSdkVersion 27
        defaultConfig {
            applicationId "com.abc"
            minSdkVersion 15
            targetSdkVersion 27
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            multiDexEnabled true

            dataBinding {
                enabled true
            }

            dexOptions {
                javaMaxHeapSize "4g"
            }
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

        // Android
        implementation 'com.android.support:appcompat-v7:27.+'
        implementation 'com.android.support:support-v4:27.+'
        implementation 'com.android.support:support-annotations:27.+'

        // RxJava & RxAndroid
        implementation 'io.reactivex.rxjava2:rxandroid:2.+'
        implementation 'io.reactivex.rxjava2:rxjava:2.+'
        implementation 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.4@aar'

        //Glide for images
        implementation 'com.github.bumptech.glide:glide:4.+'
        annotationProcessor 'com.github.bumptech.glide:compiler:4.+'

        // Retrofit : Network
        implementation 'com.squareup.retrofit2:retrofit:2.+'
        implementation 'com.squareup.retrofit2:converter-jackson:2.+'
        implementation 'com.google.code.gson:gson:2.+'

        // Multidex
        implementation 'com.android.support:multidex:1.+'

    }

This is the error

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  com.android.builder.dexing.DexArchiveMergerException: com.android.tools.r8.errors.CompilationError: Program type already present: android.support.v4.app.ActionBarDrawerToggle$DelegateProvider


问:
Generalizing integer calculator example from PLY to floating number
I am reading the first example from

https://github.com/dabeaz/ply

It is a basic calculator allowing for only expression involving '(',')','+','-','*','/', integers and assignement (for instance x=3) and throwing the evaluation of the expression (even it it's result is not an integer, for instance '3/4').

I would like to allow for floating numbers, so that I basically modified the code from the example as follows but it doesn't work :

```<code># -----------------------------------------------------------------------------
# calc.py
#
# A simple calculator with variables.
# -----------------------------------------------------------------------------

tokens = (
    'NAME','INTEGER', 'FLOAT',
    'PLUS','MINUS','TIMES','DIVIDE','EQUALS',
    'LPAREN','RPAREN',
    )

# Tokens

t_PLUS    = r'\+'
t_MINUS   = r'-'
t_TIMES   = r'\*'
t_DIVIDE  = r'/'
t_EQUALS  = r'='
t_LPAREN  = r'\('
t_RPAREN  = r'\)'
t_NAME    = r'[a-zA-Z_][a-zA-Z0-9_]*'

def t_INTEGER(t):
    r'\d+'
    t.value = int(t.value)
    return t

def t_FLOAT(t):
    r'/^(?!0\d)\d*(\.\d+)?$/mg'
    t.value = float(t.value)
    return t

# Ignored characters
t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex
lex.lex()

# Precedence rules for the arithmetic operators
precedence = (
    ('left','PLUS','MINUS'),
    ('left','TIMES','DIVIDE'),
    ('right','UMINUS'),
    )

# dictionary of names (for storing variables)
names = { }

def p_statement_assign(p):
    'statement : NAME EQUALS expression'
    names[p[1]] = p[3]

def p_statement_expr(p):
    'statement : expression'
    print(p[1])

def p_expression_binop(p):
    '''expression : expression PLUS expression
                  | expression MINUS expression
                  | expression TIMES expression
                  | expression DIVIDE expression'''
    if p[2] == '+'  : p[0] = p[1] + p[3]
    elif p[2] == '-': p[0] = p[1] - p[3]
    elif p[2] == '*': p[0] = p[1] * p[3]
    elif p[2] == '/': p[0] = p[1] / p[3]

def p_expression_uminus(p):
    'expression : MINUS expression %prec UMINUS'
    p[0] = -p[2]

def p_expression_group(p):
    'expression : LPAREN expression RPAREN'
    p[0] = p[2]

def p_expression_integer(p):
    'expression : INTEGER'
    p[0] = p[1]

def p_expression_float(p):
    'expression : FLOAT'
    p[0] = p[1]

def p_expression_name(p):
    'expression : NAME'
    try:
        p[0] = names[p[1]]
    except LookupError:
        print("Undefined name '%s'" % p[1])
        p[0] = 0

def p_error(p):
    print("Syntax error at '%s'" % p.value)

import ply.yacc as yacc
yacc.yacc()

while True:
    try:
        s = input('calc > ')
    except EOFError:
        break
    yacc.parse(s)
</code>```

I have error :

```<code>calc > 3.14+1
Illegal character '.'
Syntax error at '14'
</code>```

答:
You have two problems in your lex file. First is the token order as explained by Jean-François: the longer tokens must be defined first in lex (ref from ply doc.):

When building the master regular expression, rules are added in the following order:

All tokens defined by functions are added in the same order as they appear in the lexer file.

Tokens defined by strings are added next by sorting them in order of decreasing regular expression length (longer expressions are added first).

But the string defining the token shall be a re compatible string. Your FLOAT definition is awfully broken here. If we define a float as composed of exactly one dot, and optional digits before or after the dot and not a dot alone, an acceptable definition could be:

```<code>r'(\d*\.\d+)|(\d+\.\d*)'
</code>```

In particular, the shlashes / shall not be included in the string...

Body:
I am reading the first example from

https://github.com/dabeaz/ply

It is a basic calculator allowing for only expression involving '(',')','+','-','*','/', integers and assignement (for instance x=3) and throwing the evaluation of the expression (even it it's result is not an integer, for instance '3/4').

I would like to allow for floating numbers, so that I basically modified the code from the example as follows but it doesn't work :

# -----------------------------------------------------------------------------
# calc.py
#
# A simple calculator with variables.
# -----------------------------------------------------------------------------

tokens = (
    'NAME','INTEGER', 'FLOAT',
    'PLUS','MINUS','TIMES','DIVIDE','EQUALS',
    'LPAREN','RPAREN',
    )

# Tokens

t_PLUS    = r'\+'
t_MINUS   = r'-'
t_TIMES   = r'\*'
t_DIVIDE  = r'/'
t_EQUALS  = r'='
t_LPAREN  = r'\('
t_RPAREN  = r'\)'
t_NAME    = r'[a-zA-Z_][a-zA-Z0-9_]*'

def t_INTEGER(t):
    r'\d+'
    t.value = int(t.value)
    return t

def t_FLOAT(t):
    r'/^(?!0\d)\d*(\.\d+)?$/mg'
    t.value = float(t.value)
    return t

# Ignored characters
t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex
lex.lex()

# Precedence rules for the arithmetic operators
precedence = (
    ('left','PLUS','MINUS'),
    ('left','TIMES','DIVIDE'),
    ('right','UMINUS'),
    )

# dictionary of names (for storing variables)
names = { }

def p_statement_assign(p):
    'statement : NAME EQUALS expression'
    names[p[1]] = p[3]

def p_statement_expr(p):
    'statement : expression'
    print(p[1])

def p_expression_binop(p):
    '''expression : expression PLUS expression
                  | expression MINUS expression
                  | expression TIMES expression
                  | expression DIVIDE expression'''
    if p[2] == '+'  : p[0] = p[1] + p[3]
    elif p[2] == '-': p[0] = p[1] - p[3]
    elif p[2] == '*': p[0] = p[1] * p[3]
    elif p[2] == '/': p[0] = p[1] / p[3]

def p_expression_uminus(p):
    'expression : MINUS expression %prec UMINUS'
    p[0] = -p[2]

def p_expression_group(p):
    'expression : LPAREN expression RPAREN'
    p[0] = p[2]

def p_expression_integer(p):
    'expression : INTEGER'
    p[0] = p[1]

def p_expression_float(p):
    'expression : FLOAT'
    p[0] = p[1]

def p_expression_name(p):
    'expression : NAME'
    try:
        p[0] = names[p[1]]
    except LookupError:
        print("Undefined name '%s'" % p[1])
        p[0] = 0

def p_error(p):
    print("Syntax error at '%s'" % p.value)

import ply.yacc as yacc
yacc.yacc()

while True:
    try:
        s = input('calc > ')
    except EOFError:
        break
    yacc.parse(s)

I have error :

calc > 3.14+1
Illegal character '.'
Syntax error at '14'

Body:
You have two problems in your lex file. First is the token order as explained by Jean-François: the longer tokens must be defined first in lex (ref from ply doc.):

When building the master regular expression, rules are added in the following order:

All tokens defined by functions are added in the same order as they appear in the lexer file.

Tokens defined by strings are added next by sorting them in order of decreasing regular expression length (longer expressions are added first).

But the string defining the token shall be a re compatible string. Your FLOAT definition is awfully broken here. If we define a float as composed of exactly one dot, and optional digits before or after the dot and not a dot alone, an acceptable definition could be:

r'(\d*\.\d+)|(\d+\.\d*)'

In particular, the shlashes / shall not be included in the string...


答: Apply a rotate Transform.</p>

Title: Is it possible to rotate a (Surface)UserControl by 180 degree?

Body: Is there a simple method that allows to rotate a UI element like for example a UserControl resp. a SurfaceUserControl by 180 degree?

Body: Apply a rotate Transform.


问:
Consider marking one of the beans as @Primary
In my Java spring application, I have

```<code>public class BinarySearchImpl {

    @Autowired
    @Qualifier("Quick")
    SortAlgorithem sorter;

    Log log=LogFactory.getLog(BinarySearchImpl.class);

    public BinarySearchImpl(SortAlgorithem sorter) {
        log.info("Binary Search Bean is created");
        this.sorter=sorter;
    }
</code>```

SortAlgorithem is an interface which makes my application loosely coupled:

```<code>public interface SortAlgorithem {

    public int[] sort(int[] arrayNumbers);

}
</code>```

And then there are 2 implementations for this interface. One is BubbleSort:

```<code>@Component
@Qualifier("Bubble")
public class BubbleSort implements SortAlgorithem {

    Log log=LogFactory.getLog(BubbleSort.class);

    public int[] sort(int[] numbers) {
        log.info("Bubble sort is called");
        return numbers;
    }
}
</code>```

and the other is QuickSort:

```<code>@Component
@Qualifier("Quick")
//@Primary
public class QuickSort implements SortAlgorithem{

    Log log= LogFactory.getLog(QuickSort.class);

    public int[] sort(int[] numbers) {
        log.info("Quick Sort is called");
        return numbers;
    }

}
</code>```

At the end, when I call my app it complains with this message:

```<code>Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
</code>```

I am wondering... Why @Qualifier annotation does not work?

答:
You have to declare your components like this:

```<code>@Component("Bubble")
public class BubbleSort implements SortAlgorithem {

    Log log=LogFactory.getLog(BubbleSort.class);

    public int[] sort(int[] numbers) {
        log.info("Bubble sort is called");
        return numbers;
    }
}
</code>```

and

```<code>@Component("Quick")
public class QuickSort implements SortAlgorithem{

    Log log= LogFactory.getLog(QuickSort.class);

    public int[] sort(int[] numbers) {
        log.info("Quick Sort is called");
        return numbers;
    }

}
</code>```

This should solve your issue.

Body:
In my Java spring application, I have

public class BinarySearchImpl {

    @Autowired
    @Qualifier("Quick")
    SortAlgorithem sorter;

    Log log=LogFactory.getLog(BinarySearchImpl.class);

    public BinarySearchImpl(SortAlgorithem sorter) {
        log.info("Binary Search Bean is created");
        this.sorter=sorter;
    }

SortAlgorithem is an interface which makes my application loosely coupled:

public interface SortAlgorithem {

    public int[] sort(int[] arrayNumbers);

}

And then there are 2 implementations for this interface. One is BubbleSort:

@Component
@Qualifier("Bubble")
public class BubbleSort implements SortAlgorithem {

    Log log=LogFactory.getLog(BubbleSort.class);

    public int[] sort(int[] numbers) {
        log.info("Bubble sort is called");
        return numbers;
    }
}

and the other is QuickSort:

@Component
@Qualifier("Quick")
//@Primary
public class QuickSort implements SortAlgorithem{

    Log log= LogFactory.getLog(QuickSort.class);

    public int[] sort(int[] numbers) {
        log.info("Quick Sort is called");
        return numbers;
    }

}

At the end, when I call my app it complains with this message:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

I am wondering... Why @Qualifier annotation does not work?

Body:
You have to declare your components like this:

@Component("Bubble")
public class BubbleSort implements SortAlgorithem {

    Log log=LogFactory.getLog(BubbleSort.class);

    public int[] sort(int[] numbers) {
        log.info("Bubble sort is called");
        return numbers;
    }
}

and

@Component("Quick")
public class QuickSort implements SortAlgorithem{

    Log log= LogFactory.getLog(QuickSort.class);

    public int[] sort(int[] numbers) {
        log.info("Quick Sort is called");
        return numbers;
    }

}

This should solve your issue.


问:
Need Help in Integrating Javascript with Wordpress
I have wordpress account for blogging. Recently I have opted for PopUpAds. I have the javascript code with me which I received from PopUpAds.

Can any one please tell me how to integrate this code into wordpress??

Any informative links will also be very helpful.

Thank You In advance.

答:
It might be the safest ( but not the best ) way to install the plugin which allows you to add inline javascript code.
I.e. something like this - https://wordpress.org/plugins/tc-custom-javascript/

Also, if you can edit functions.php file within your active theme, the quickest way is to add a patch of code there:

```<code><?php //add opening php tag only if there is closing tag at the end of functions.php file
function pop_up_ads_script() {
?>
<script type="text/javascript">
 //your script from PopUpAds goes here
 //check if PopUpAds code includes also script tags, then avoid adding duplicate tags
</script>
<?php
}
add_action( 'wp_footer', 'pop_up_ads_script' );
</code>```

For this approach, be careful when editing and saving functions.php, since you might cause error due to bad syntax or typo, so first check if php tags. I
would suggest to do this via FTP access, rather  than through built-in WordPress file editor.

Body:
It might be the safest ( but not the best ) way to install the plugin which allows you to add inline javascript code.
I.e. something like this - https://wordpress.org/plugins/tc-custom-javascript/

Also, if you can edit functions.php file within your active theme, the quickest way is to add a patch of code there:

<?php //add opening php tag only if there is closing tag at the end of functions.php file
function pop_up_ads_script() {
?>
<script type="text/javascript">
 //your script from PopUpAds goes here
 //check if PopUpAds code includes also script tags, then avoid adding duplicate tags
</script>
<?php
}
add_action( 'wp_footer', 'pop_up_ads_script' );

For this approach, be careful when editing and saving functions.php, since you might cause error due to bad syntax or typo, so first check if php tags. I
would suggest to do this via FTP access, rather  than through built-in WordPress file editor.


问:
Button not appearing in tkinter. (python)
I am stating to develop a program in which you click a button with the text "open" on it, and it will bring up a file selection window using filedialog.askopenfilename, but the button won't appear, and it will automatically bring up the window without the button needing to be pressed. Here is the code:

```<code>from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Snake converter")
sim = filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))
openbutton = Button(root, text = "Open", width = 10, command = sim)
</code>```

答:
Nowhere in your code you're calling a geometry manager(pack, grid, place etc.) so your button isn't shown. Also filedialog.askopenfilename runs immediately even if it's assigned to an object. I am also unsure that you can call an object as button function. Try the following:

```<code>def sim():
    filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))

openbutton = Button(root, text = "Open", width = 10, command=sim)

openbutton.pack()
root.mainloop()
</code>```

also your code should look like:

```<code>from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Snake converter")

def sim():
    filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))

openbutton = Button(root, text = "Open", width = 10, command=sim)

openbutton.pack()
root.mainloop()
</code>```

I'd also check frequent questions as a newcomer to tkinter.

Body:
I am stating to develop a program in which you click a button with the text "open" on it, and it will bring up a file selection window using filedialog.askopenfilename, but the button won't appear, and it will automatically bring up the window without the button needing to be pressed. Here is the code:

from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Snake converter")
sim = filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))
openbutton = Button(root, text = "Open", width = 10, command = sim)

Body:
Nowhere in your code you're calling a geometry manager(pack, grid, place etc.) so your button isn't shown. Also filedialog.askopenfilename runs immediately even if it's assigned to an object. I am also unsure that you can call an object as button function. Try the following:

def sim():
    filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))

openbutton = Button(root, text = "Open", width = 10, command=sim)

openbutton.pack()
root.mainloop()

also your code should look like:

from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Snake converter")

def sim():
    filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))

openbutton = Button(root, text = "Open", width = 10, command=sim)

openbutton.pack()
root.mainloop()

I'd also check frequent questions as a newcomer to tkinter.


问:
How to get the coordinates of mouse click on a slice of pie-chart : Amcharts
I'm trying to get the coordinates of the mouse click on the amcharts pie-chart's slice. It is working for the whole page except the slices. event.pageX and event.clientX are not working, returning undefined. I want the coordinates with respect to the page.

```<code>{
    "event": "pullOutSlice",
    "method": function (event) {
                var relX = event.pageX;
                var relY = event.pageY;
   }
}
</code>```

JSFIDDLE

答:
Is this what you are looking for ?
https://jsfiddle.net/6w78zmo9/1/

Try this:

```<code> var relX = event.chart.mouseX;
 var relY = event.chart.mouseY;
</code>```

Body:
I'm trying to get the coordinates of the mouse click on the amcharts pie-chart's slice. It is working for the whole page except the slices. event.pageX and event.clientX are not working, returning undefined. I want the coordinates with respect to the page.

{
    "event": "pullOutSlice",
    "method": function (event) {
                var relX = event.pageX;
                var relY = event.pageY;
   }
}

JSFIDDLE

Body:
Is this what you are looking for ?
https://jsfiddle.net/6w78zmo9/1/

Try this:

 var relX = event.chart.mouseX;
 var relY = event.chart.mouseY;


问:
How to update the dropdownlist in Javascript
I tried to update the drop down list by using ajax call to web method in asp.net as given below:

<asp:DropDownList ID="ddlCustomers" runat="server" multiple="multiple"></asp:DropDownList>

```<code>   $('#btnSelected').click(function(){
        var name= $("#<%=ddldistrict.ClientID %>").val();

        $.ajax({
            type: "POST",
            url: "reportutil.aspx/LoadMandals",
            data: '{name: "' + name + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }

         });
    });

    });
    function OnSuccess(response) {
        var ddlCustomers = $("[id*=ddlCustomers]");
        ddlCustomers.html("");

        $.each(response.d, function () {

                ddlCustomers.append($("<option optgroup= " + this['option'] + " > </option>").val(this['Value']).html(this['Text']));

        });
        $('[id*=ddlCustomers]').multiselect({
            enableClickableOptGroups: true,
            enableCollapsibleOptGroups: true,
            includeSelectAllOption: true,
            enableFiltering: true

        });

   var name = $("#<%=ddldistrict.ClientID %>").val();

        alert(name[0]);

    };

    $(function () {
        $("#<%=ddlCustomers.ClientID %>").change(function () {

            alert($("#<%=ddlCustomers.ClientID %>").val());

        });

     });
</code>```

Here the data is coming and binding first time only. If I changed the option and send to the web method, from that method I'm getting the result but that data is not binding to drop down list, but if I remove multi select  from Javascript then it is binding. Please help me out.

答:
```<code>$('#btnSelected').click(function () {
    var name = $("#<%=ddldistrict.ClientID %>").val();

    $.ajax({
        type: 'post',
        contentType: "application/json; charset=utf-8",
        url: "reportutil.aspx/LoadMandals",
        data: JSON.stringify({ name: name }),
        async: false,
        success: function (response) {
            $("[id*=ddlCustomers]").empty();
            var appendData = "<option value=''>--Select--</option>";
            for (var i = 0; i < response.d.length; i++) {
                if (response.d[i].Name != "") {
                    appendData += "<option value ='" + response.d[i].ValueFieldName + "'>" + response.d[i].TextFieldName + "</option>";
                }
            }
            $("[id*=ddlCustomers]").append(appenddata1);
        },
        error: function () { alert("error"); }
    });
});
</code>```

Body:
I tried to update the drop down list by using ajax call to web method in asp.net as given below:

<asp:DropDownList ID="ddlCustomers" runat="server" multiple="multiple"></asp:DropDownList>

   $('#btnSelected').click(function(){
        var name= $("#<%=ddldistrict.ClientID %>").val();

        $.ajax({
            type: "POST",
            url: "reportutil.aspx/LoadMandals",
            data: '{name: "' + name + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }

         });
    });

    });
    function OnSuccess(response) {
        var ddlCustomers = $("[id*=ddlCustomers]");
        ddlCustomers.html("");

        $.each(response.d, function () {

                ddlCustomers.append($("<option optgroup= " + this['option'] + " > </option>").val(this['Value']).html(this['Text']));

        });
        $('[id*=ddlCustomers]').multiselect({
            enableClickableOptGroups: true,
            enableCollapsibleOptGroups: true,
            includeSelectAllOption: true,
            enableFiltering: true

        });

   var name = $("#<%=ddldistrict.ClientID %>").val();

        alert(name[0]);

    };

    $(function () {
        $("#<%=ddlCustomers.ClientID %>").change(function () {

            alert($("#<%=ddlCustomers.ClientID %>").val());

        });

     });

Here the data is coming and binding first time only. If I changed the option and send to the web method, from that method I'm getting the result but that data is not binding to drop down list, but if I remove multi select  from Javascript then it is binding. Please help me out.


问:
Smallest range of substring in string
I have a string S (with words indexed from 0) and a substring Q. I wish to find the smallest range [L, R] in S which contains all words in Q. There are no duplicate words in Q. How do I approach this ?

For example,

Input:
S: what about the lazy brown fox that jumped over the other brown one which lazy dog ate the food of the fox
Q: lazy brown dog

Output: [11,15]

My code:

```<code>S = raw_input().strip().split(' ')
Q = raw_input().strip().split(' ')

count = [0 for x in range(len(Q))]
smallest_index = [0 for x in range(len(Q))]
largest_index = [0 for x in range(len(Q))]

for i in range(len(S)):
    for j in range(len(Q)):
        if S[i] == Q[j]:
            count[j] += 1
            if count[j] <= 1:
                smallest_index[j] = i
                largest_index[j] = i
            if count[j] > 1:
                largest_index[j] = i

largest_index.sort()
print "[%d," % largest_index[0],
print "%d]" % largest_index[len(Q)-1]
</code>```

答:
This is a slightly more efficient version of PM 2Ring's solution, replacing the call to product with a loop:

```<code>from itertools import product

def words_range(src, query):
    query = set(query)

    # Create a dict to store the word positions in src of each query word
    pos = {s: [] for s in query}
    for i, s in enumerate(src):
        if s in pos:
            pos[s].append(i)

    # Find all the ranges that hold all the query word
    # We'll iterate over the input string and keep track of
    # where each word appeared last
    last_pos = {}
    ranges = []
    for i, word in enumerate(src):
        if word in query:
            last_pos[word] = i
            if len(last_pos) == len(query):
                ranges.append( (min(last_pos.values()), i) )

    # Find the smallest range
    return min(ranges, key=lambda t:t[1] - t[0])
</code>```

It's not quite linear time (because of the min(last_pos.values()) in the loop), but it's a step in the right direction. There's probably a way to get rid of the min call (that I can't think of right now), which would make this linear.

Title: Smallest range of substring in string

Body:
I have a string S (with words indexed from 0) and a substring Q. I wish to find the smallest range [L, R] in S which contains all words in Q. There are no duplicate words in Q. How do I approach this ?

For example,

Input:
S: what about the lazy brown fox that jumped over the other brown one which lazy dog ate the food of the fox
Q: lazy brown dog

Output: [11,15]

My code:

S = raw_input().strip().split(' ')
Q = raw_input().strip().split(' ')

count = [0 for x in range(len(Q))]
smallest_index = [0 for x in range(len(Q))]
largest_index = [0 for x in range(len(Q))]

for i in range(len(S)):
    for j in range(len(Q)):
        if S[i] == Q[j]:
            count[j] += 1
            if count[j] <= 1:
                smallest_index[j] = i
                largest_index[j] = i
            if count[j] > 1:
                largest_index[j] = i

largest_index.sort()
print "[%d," % largest_index[0],
print "%d]" % largest_index[len(Q)-1]

Body:
This is a slightly more efficient version of PM 2Ring's solution, replacing the call to product with a loop:

from itertools import product

def words_range(src, query):
    query = set(query)

    # Create a dict to store the word positions in src of each query word
    pos = {s: [] for s in query}
    for i, s in enumerate(src):
        if s in pos:
            pos[s].append(i)

    # Find all the ranges that hold all the query word
    # We'll iterate over the input string and keep track of
    # where each word appeared last
    last_pos = {}
    ranges = []
    for i, word in enumerate(src):
        if word in query:
            last_pos[word] = i
            if len(last_pos) == len(query):
                ranges.append( (min(last_pos.values()), i) )

    # Find the smallest range
    return min(ranges, key=lambda t:t[1] - t[0])

It's not quite linear time (because of the min(last_pos.values()) in the loop), but it's a step in the right direction. There's probably a way to get rid of the min call (that I can't think of right now), which would make this linear.


问:
Ruby String class multiple methods and efficiency
I was looking through the Ruby source code and I can't seem to find a answer to my question:

If I call multiple methods on a string (str.upcase.reverse), does Ruby optimize this query? The code for upcase basically loops over the string and coverts each letter to its uppercase value and the reverse reverses the string. Does Ruby combine these (or any other combinable combinations) so that it will reverse AND capitalize at the same time O(n) instead of looping over each character in the string twice?

答:
No, there is no optimization like you describe, but feel free to write a method that performs a reverse+capitalize in one loop.

Definitely check out the Benchmark standard library.  When writing optimizations, always benchmark, never assume :)

PS: reverse.upcase is still O(n).  Big O notation disregards constants.


问:
How to Generate CSV File from PHP Form?
Aware this has been asked before but the solutions I found didn't help.

Currently I receive an email when a user completes the form on my website to download the brochure. I would like to have these details; Name, telephone, email and city store in a CSV file, which I can then manually add to Mailchimp or other site.

PHP:

```<code><?php
  $name    = $_POST['fname'];
  $email   = $_POST['email_from'];
  $phone   = $_POST['phone'];
  $city    = $_POST['city'];
  $content = $_POST['comments'];
  $to      = 'C.PAN@email.com';
  $subject = 'Enquiry';

  $headers = "From: " . strip_tags($email) . "\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

  $message = '<html><body>';
  $message .= '<table rules="all"  cellpadding="10">';
  $message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . $name . "</td></tr>";
  $message .= "<tr style='background: #eee;' ><td><strong>Email:</strong> </td><td>" . $email . "</td></tr>";
  $message .= "<tr style='background: #eee;'><td><strong>Phone:</strong> </td><td>" . $phone . "</td></tr>";
  $message .= "<tr style='background: #eee;'><td><strong>City:</strong> </td><td>" . $city . "</td></tr>";
  $message .= "<tr style='background: #eee;'><td><strong>Message:</strong> </td><td>" . $content . "</td></tr>";
  $message .= "</table>";
  $message .= "</body></html>";

            //Creates the csv file.
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=downloadcsv.csv');

            $dataRow = [
            'first_name' => $name,
            'email' => $email,
            'phone' => $phone,
            'city' => $city,
            'comments' => $comments,
            ];
            $fp = fopen($downloadcsv, 'w');
            fputcsv($fp, $dataRow);
            fclose($fp);

      if (mail($to, $subject, $message, $headers))
      {
      header('brochure.pdf');
      }
?>
</code>```

HTML:

```<code><form name="myForm" action="amail_brochure.php" method="post" onsubmit="return validateForm()" class="sidebar-form" accept-charset="ISO-8859-1">
  <div class="main-form">
    <div>
      <input type="text" class="form-control" name="fname" placeholder="Vollständiger Name" required="required"/>
    </div>
    <div>
      <input type="email" class="form-control" name="email_from" id="email_from" placeholder="Email" required="required" />
    </div>
    <div>
      <input type="text" class="form-control" name="phone" placeholder="Telefon" required="required"/>
    </div>
    <div>
      <input type="text" class="form-control" name="city" placeholder="Deine Stadt" required="required" />
    </div>
    <textarea name="comments" id="" rows="6" class="form-control" placeholder="Comments:"></textarea>
    <div class="button-container" style="display: inline-block;">
      <button class="btn cta-button pull-right form-submit" type="submit" formtarget="_blank">Download</button>
    </div>
  </div>
</form>
</code>```

Any help to implement exporting the users information into a CSV file would be greatly appreciated.

With thanks,

答:
To answer your question you can easily transform an array data structure into a CSV file. This has been asked here: Export to CSV via PHP

In this case you could use your POST array (although you should do some checking first to avoid harmful injections of code).

However mailchimp also has an API that lets you add those details directly. If you do not need any manual steps in between you could add your users directly to the mailing list using this API: http://developer.mailchimp.com/documentation/mailchimp/guides/manage-subscribers-with-the-mailchimp-api/

Title: How to Generate CSV File from PHP Form?

Body:
Aware this has been asked before but the solutions I found didn't help.

Currently I receive an email when a user completes the form on my website to download the brochure. I would like to have these details; Name, telephone, email and city store in a CSV file, which I can then manually add to Mailchimp or other site.

PHP:

<?php
  $name    = $_POST['fname'];
  $email   = $_POST['email_from'];
  $phone   = $_POST['phone'];
  $city    = $_POST['city'];
  $content = $_POST['comments'];
  $to      = 'C.PAN@email.com';
  $subject = 'Enquiry';

  $headers = "From: " . strip_tags($email) . "\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

  $message = '';
  $message .= '
';
  $message .= "
Name: 	" . $name . "
";
  $message .= "
Email: 	" . $email . "
";
  $message .= "
Phone: 	" . $phone . "
";
  $message .= "
City: 	" . $city . "
";
  $message .= "
Message: 	" . $content . "
";
  $message .= "
";
  $message .= "";

            //Creates the csv file.
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=downloadcsv.csv');

            $dataRow = [
            'first_name' => $name,
            'email' => $email,
            'phone' => $phone,
            'city' => $city,
            'comments' => $comments,
            ];
            $fp = fopen($downloadcsv, 'w');
            fputcsv($fp, $dataRow);
            fclose($fp);

      if (mail($to, $subject, $message, $headers))
      {
      header('brochure.pdf');
      }
?>

HTML:

<form name="myForm" action="amail_brochure.php" method="post" onsubmit="return validateForm()" class="sidebar-form" accept-charset="ISO-8859-1">

      <input type="text" class="form-control" name="fname" placeholder="Vollständiger Name" required="required"/>

      <input type="email" class="form-control" name="email_from" id="email_from" placeholder="Email" required="required" />

      <input type="text" class="form-control" name="phone" placeholder="Telefon" required="required"/>

      <input type="text" class="form-control" name="city" placeholder="Deine Stadt" required="required" />

    <textarea name="comments" id="" rows="6" class="form-control" placeholder="Comments:"></textarea>

      <button class="btn cta-button pull-right form-submit" type="submit" formtarget="_blank">Download</button>

</form>

Any help to implement exporting the users information into a CSV file would be greatly appreciated.

With thanks,


问:
Match multiple words in any order via one regex
as stated in heading I want regex which will give me results in order based on my 'query'.

```<code>line='VERSION="OTHER" POWER="LOW" FREQ="OFF" MAXTUN="BLER"'**
</code>```

Example 1:

```<code>re.findall(r'FREQ="(.*?)"|VERSION="(.*?)"', line, re.MULTILINE)
</code>```

Output is:

```<code>[('', 'OTHER'), ('OFF', '')]
</code>```

And desired output I prefer is something like:

```<code>['OFF', 'OTHER']
</code>```

Example 2:

```<code>re.findall(r'VERSION="(.*?)"|FREQ="(.*?)"', line, re.MULTILINE)
</code>```

Output is the same:

```<code>[('', 'OTHER'), ('OFF', '')]
</code>```

And desired output I prefer is something like:

```<code>['OTHER', 'OFF']
</code>```

Any suggestion?

P.S.
Please don't ask me what I want to achieve and tell me that there is maybe better way, only if you have some question regarding this.

Thank you!

答: I'm afraid there is no way to match in the order you want using regex: you could execute the part before | first, and then the part after |. Or order the result afterwards.</p>

Body:
as stated in heading I want regex which will give me results in order based on my 'query'.

line='VERSION="OTHER" POWER="LOW" FREQ="OFF" MAXTUN="BLER"'**

Example 1:

re.findall(r'FREQ="(.*?)"|VERSION="(.*?)"', line, re.MULTILINE)

Output is:

[('', 'OTHER'), ('OFF', '')]

And desired output I prefer is something like:

['OFF', 'OTHER']

Example 2:

re.findall(r'VERSION="(.*?)"|FREQ="(.*?)"', line, re.MULTILINE)

Output is the same:

[('', 'OTHER'), ('OFF', '')]

And desired output I prefer is something like:

['OTHER', 'OFF']

Any suggestion?

P.S.
Please don't ask me what I want to achieve and tell me that there is maybe better way, only if you have some question regarding this.

Thank you!


问:
Send data to Realm object server from app
I am creating an Android application in which I am using the Realm database to store data, and I am using the Realm object server to login and register user. I am able to log a user in using SyncUser and I am able to see that my login user has been stored in the Realm object server.

But now I have additional fields that I want to store - for instance, mail and age. I know how I'd store it in a different database but I don't know how to do this in Realm.

答: If you are talking about storing metadata about a user. That is not supported yet, but will be added soon. You can follow https://github.com/realm/realm-java/issues/4645. For now the workaround would be to save them in your own custom User Object.</p>


问:
Detecting word between specific words with PHP
for example,

```<code><form method="post">
    <textarea name="content" id="editor"></textarea>
    <input type="submit" value="submit" name="alltext">
<form>
</code>```

Then I type: Humans have ==brain== and it helps them learn things.
After that, I want this thing to find the word between == and ==.

```<code>$all_text = $_POST["alltext"];
if (a word is between '==' and '==') {
    $special_word = the word between '==' and '==';
} else {
    do nothing
}
</code>```

and the output I desire is the variable $special_word is set to brain.

It is more like stackoverflow.com where words between # and # is heading 1 and words between ## and ## is heading 2.

Please help me solve this puzzle.

答:
You should use preg_match to get the sub-string:

```<code>$str = 'Humans have ==brain== and it helps them learn things';
preg_match('/==(.*?)==/', $str, $match);
$special_word = $match[1];
</code>```

Body:
for example,

<form method="post">
    <textarea name="content" id="editor"></textarea>
    <input type="submit" value="submit" name="alltext">
<form>

Then I type: Humans have ==brain== and it helps them learn things.
After that, I want this thing to find the word between == and ==.

$all_text = $_POST["alltext"];
if (a word is between '==' and '==') {
    $special_word = the word between '==' and '==';
} else {
    do nothing
}

and the output I desire is the variable $special_word is set to brain.

It is more like stackoverflow.com where words between # and # is heading 1 and words between ## and ## is heading 2.

Please help me solve this puzzle.

Body:
You should use preg_match to get the sub-string:

$str = 'Humans have ==brain== and it helps them learn things';
preg_match('/==(.*?)==/', $str, $match);
$special_word = $match[1];


问:
Ionic Angular 2 - Return Observable from Nested Promises
I have function in which I want to return an Observable as my query result. I am making a SQLite Query and I want to return the result in an Observable. I tried putting the Observable.of outside at the first Promise function but it did not work. This is my code.

```<code>GetCustomers(FilterOptions: any): Observable<any> {

            return Observable.of(this.platform.ready().then(() => { //WRONG CODE

                 this.SQLObj.executeSql("select * from customers, {}).then((res) => {
                    console.log(res);
                });

            })).map(cust => {
                // MODIFY THE RESULT AND CREATE NEW OBJECT.
                return JSON.stringify(cust);
            })

        }
</code>```

Basically I want to return an Observable with nested promises but before that I want to modify and customize the resulted data of the SQL Query. What is the best way to do it.

答:
I think this should work as you want.</p>

```<code>Observable.fromPromise(this.platform.ready())
.switchMap(() => Observable.fromPromise(this.SQLObj.executeSql("select * from customers", {})))
.map((cust) => JSON.stringify(cust));
</code>```

Body:
I have function in which I want to return an Observable as my query result. I am making a SQLite Query and I want to return the result in an Observable. I tried putting the Observable.of outside at the first Promise function but it did not work. This is my code.

GetCustomers(FilterOptions: any): Observable<any> {

            return Observable.of(this.platform.ready().then(() => { //WRONG CODE

                 this.SQLObj.executeSql("select * from customers, {}).then((res) => {
                    console.log(res);
                });

            })).map(cust => {
                // MODIFY THE RESULT AND CREATE NEW OBJECT.
                return JSON.stringify(cust);
            })

        }

Basically I want to return an Observable with nested promises but before that I want to modify and customize the resulted data of the SQL Query. What is the best way to do it.

Body:
I think this should work as you want.

Observable.fromPromise(this.platform.ready())
.switchMap(() => Observable.fromPromise(this.SQLObj.executeSql("select * from customers", {})))
.map((cust) => JSON.stringify(cust));


问:
What stages would be involved in compiling Assembly language to Machine Code
I'm trying to write a compiler to take an assembler file which will output raw machine code instructions.

I've found lots of tutorials on how to write a compiler, but I'm wondering if all the stages are relevant to assembler mnemonics. For instance, is lexical analysis necessary at all given the simplified stage-by-stage format of assembler, or will it still be necessary but in a simpler format?

答: A lexical analyzer is still required:  you must have something that will break the text into individual tokens (words, numbers, punctuation, etc.).  You still need a parser, too, although a much simplified one.  There is a grammar, after all.


问:
How to select a row having a column with max value with a group by
I have a table with the next columns

```<code>MSG_ID          NOT NULL NUMBER(10)
CREATION_DATE            DATE
PORT                     VARCHAR2(50)
MESSAGE                  VARCHAR2(1024)
IP_ADDRESS               VARCHAR2(50)
PARSED                   NUMBER(1)
PARSED_ON                DATE
</code>```

Where parse time is parsed_on -  creation_date.

I would like to know if it is possible in 1 single query extract for each hour the message that take longer to parse, getting the HOUR, PORT, MSG_ID MINUTES...I am blocked here

```<code>select TO_CHAR(CREATION_DATE, 'HH24') || ':mm' HOUR, PORT, MSG_ID, ROUND(MAX(parsed_on -  creation_date)) * 24*60 MINUTES
        from T_INCOME_CALLS
         where TO_CHAR(CREATION_DATE, 'dd/mm/yyyy') = TO_CHAR(SYSDATE, 'dd/mm/yyyy')
        group by TO_CHAR(CREATION_DATE, 'HH24'), PORT, MSG_ID
         order by TO_CHAR(CREATION_DATE, 'HH24') ;
</code>```

答:
You can get it also without a sub-query when you use FIRST function:</p>

```<code>SELECT TO_CHAR(CREATION_DATE, 'HH24') || ':mm' HOUR, PORT, MSG_ID,
    MAX(MESSAGE) KEEP (DENSE_RANK FIRST ORDER BY (parsed_on - creation_date) desc, CREATION_DATE)
FROM T_INCOME_CALLS
WHERE CREATION_DATE >= TRUNC(SYSDATE) AND CREATION_DATE < TRUNC(SYSDATE) + 1
GROUP BY TO_CHAR(CREATION_DATE, 'HH24'), PORT, MSG_ID
ORDER BY TO_CHAR(CREATION_DATE, 'HH24');
</code>```

Body:
I have a table with the next columns

MSG_ID          NOT NULL NUMBER(10)
CREATION_DATE            DATE
PORT                     VARCHAR2(50)
MESSAGE                  VARCHAR2(1024)
IP_ADDRESS               VARCHAR2(50)
PARSED                   NUMBER(1)
PARSED_ON                DATE

Where parse time is parsed_on -  creation_date.

I would like to know if it is possible in 1 single query extract for each hour the message that take longer to parse, getting the HOUR, PORT, MSG_ID MINUTES...I am blocked here

select TO_CHAR(CREATION_DATE, 'HH24') || ':mm' HOUR, PORT, MSG_ID, ROUND(MAX(parsed_on -  creation_date)) * 24*60 MINUTES
        from T_INCOME_CALLS
         where TO_CHAR(CREATION_DATE, 'dd/mm/yyyy') = TO_CHAR(SYSDATE, 'dd/mm/yyyy')
        group by TO_CHAR(CREATION_DATE, 'HH24'), PORT, MSG_ID
         order by TO_CHAR(CREATION_DATE, 'HH24') ;

Body:
You can get it also without a sub-query when you use FIRST function:

SELECT TO_CHAR(CREATION_DATE, 'HH24') || ':mm' HOUR, PORT, MSG_ID,
    MAX(MESSAGE) KEEP (DENSE_RANK FIRST ORDER BY (parsed_on - creation_date) desc, CREATION_DATE)
FROM T_INCOME_CALLS
WHERE CREATION_DATE >= TRUNC(SYSDATE) AND CREATION_DATE < TRUNC(SYSDATE) + 1
GROUP BY TO_CHAR(CREATION_DATE, 'HH24'), PORT, MSG_ID
ORDER BY TO_CHAR(CREATION_DATE, 'HH24');


问:
"Stack is empty" in Microsoft Bot Framework
I am writing a bot using the Microsoft Bot Framework. It consists of a MessagesController that calls a LuisDialog using await Conversation.SendAsync....

Some scenarios trigger an exception with this message:

Stack is empty

I found the place in the source code of the Bot Framework where it is triggered:

```<code>  134         public static T Peek<T>(this IList<T> stack)
  135         {
  136             if (stack.Count == 0)
  137             {
  138                 throw new InvalidOperationException("Stack is empty");
  139             }
  140
  141             return stack[stack.Count - 1];
  142         }
</code>```

However, I cannot figure out how exactly it is triggered. When debugging line by line, the code seems to work fine (there's a lot of code, and it goes through all of it).

When just letting it run without breakpoints, it crashes with this exception.

My await Conversation.SendAsync is wrapped into a try/catch and this is how I catch the exception.

I couldn't figure out more about which part of code exactly causes the exception.

Do you have any idea what could cause the "Stack is empty" message?

Later update:

Some time later, I started getting the Stack is Empty exceptions in another piece of code, and I made sure everything is asynced and awaited:

```<code>public async Task StartAsync(IDialogContext context)
{
    context.Wait(UserProfileStep1);
}

public async Task UserProfileStep1(IDialogContext context, IAwaitable<object> original)
{
    string originalMessage = (string)await original; // <== the exception occurs here
</code>```

Turns out that in that particular case, it was because I used context.Forward and tried to pass a string object into it, while it only supports IMessageActivity objects.

答:
context.Done<object>(null);

Use this in the last of StartAsync.

Body:
I am writing a bot using the Microsoft Bot Framework. It consists of a MessagesController that calls a LuisDialog using await Conversation.SendAsync....

Some scenarios trigger an exception with this message:

Stack is empty

I found the place in the source code of the Bot Framework where it is triggered:

  134         public static T Peek<T>(this IList<T> stack)
  135         {
  136             if (stack.Count == 0)
  137             {
  138                 throw new InvalidOperationException("Stack is empty");
  139             }
  140
  141             return stack[stack.Count - 1];
  142         }

However, I cannot figure out how exactly it is triggered. When debugging line by line, the code seems to work fine (there's a lot of code, and it goes through all of it).

When just letting it run without breakpoints, it crashes with this exception.

My await Conversation.SendAsync is wrapped into a try/catch and this is how I catch the exception.

I couldn't figure out more about which part of code exactly causes the exception.

Do you have any idea what could cause the "Stack is empty" message?

Later update:

Some time later, I started getting the Stack is Empty exceptions in another piece of code, and I made sure everything is asynced and awaited:

public async Task StartAsync(IDialogContext context)
{
    context.Wait(UserProfileStep1);
}

public async Task UserProfileStep1(IDialogContext context, IAwaitable<object> original)
{
    string originalMessage = (string)await original; // <== the exception occurs here

Turns out that in that particular case, it was because I used context.Forward and tried to pass a string object into it, while it only supports IMessageActivity objects.


问:
Copying of an array of objects to another Array without object reference in javascript(Deep copy)
I have a scenario where i need to copy the array of Objects(Main array) to another Temp array which should not have object reference basically if i make any modification to  Main array it should not reflect in the Temp array so that i will preserve the copy independently.

I have used one of the code snippet from stack overflow this one does partially like if i delete all objects from the Main array the temp array still hold the value but when i do some modifications in main array and click cancel button iam removing all objects from the main array using array.Removeall(); but the modification still exist in Temp array so which means that object having a reference.

```<code>clone: function (existingArray) {
  var newObj = (existingArray instanceof Array) ? [] : {};
  console.debug('newObj value is ' + newObj);
  for (i in existingArray) {
    console.debug('i value is' + i);
    if (i == 'clone') continue;
    console.debug('existingArray[i] value ' + existingArray[i]);
    if (existingArray[i] && typeof existingArray[i] == "object") {

      newObj[i] = this.clone(existingArray[i]);
    } else {
      console.debug('in else part ' + existingArray[i]);
      newObj[i] = existingArray[i];
    }
  }
  return newObj;
}
</code>```

my object structure is like

iam using knockout framework.

```<code>newObjectCreation = function (localIp, RemoteIp, areaId) {
  this.localIP = ko.observable(localIp);
  this.remoteIP = ko.observable(RemoteIp);
  this.areaId = ko.observable(areaId);
};

template.ProtocolArray.push(new newObjectCreation('', '', '')); // to create default row
</code>```

答:
To copy the values of an array without copying the reference of the array, you can simply do:

```<code>const tempArray = [...mainArray];
</code>```

This is the recommended solution for AirBnb's JS Style Guide: https://github.com/airbnb/javascript#arrays

However, this will not create new referenes for the objects inside the array. To create a new reference for the array and the objects inside, you can do:

```<code>JSON.parse(JSON.stringify(mainArray));
</code>```

Body:
I have a scenario where i need to copy the array of Objects(Main array) to another Temp array which should not have object reference basically if i make any modification to  Main array it should not reflect in the Temp array so that i will preserve the copy independently.

I have used one of the code snippet from stack overflow this one does partially like if i delete all objects from the Main array the temp array still hold the value but when i do some modifications in main array and click cancel button iam removing all objects from the main array using array.Removeall(); but the modification still exist in Temp array so which means that object having a reference.

clone: function (existingArray) {
  var newObj = (existingArray instanceof Array) ? [] : {};
  console.debug('newObj value is ' + newObj);
  for (i in existingArray) {
    console.debug('i value is' + i);
    if (i == 'clone') continue;
    console.debug('existingArray[i] value ' + existingArray[i]);
    if (existingArray[i] && typeof existingArray[i] == "object") {

      newObj[i] = this.clone(existingArray[i]);
    } else {
      console.debug('in else part ' + existingArray[i]);
      newObj[i] = existingArray[i];
    }
  }
  return newObj;
}

my object structure is like

iam using knockout framework.

newObjectCreation = function (localIp, RemoteIp, areaId) {
  this.localIP = ko.observable(localIp);
  this.remoteIP = ko.observable(RemoteIp);
  this.areaId = ko.observable(areaId);
};

template.ProtocolArray.push(new newObjectCreation('', '', '')); // to create default row

Body:
To copy the values of an array without copying the reference of the array, you can simply do:

const tempArray = [...mainArray];

This is the recommended solution for AirBnb's JS Style Guide: https://github.com/airbnb/javascript#arrays

However, this will not create new referenes for the objects inside the array. To create a new reference for the array and the objects inside, you can do:

JSON.parse(JSON.stringify(mainArray));


问:
Avoid array loops sonar issue: system.arraycopy
I would like to use SysteM.arraycopy to make the below method faster. But as of my knowledge, Arraycopy cannot involve any such complicated logic.

```<code>for (int c = 0; c < newRow.length && c < target[r].length; ++c)
{
    target[r][c] = newRow[c];
}
</code>```

So any help would be welcome. Thanks in advance.

答:
You can rewrite that using System.arraycopy.
This about it this way:

You want to copy starting from index 0 of newRow

You want to copy starting from index 0 into target[r]

You want to copy at most newRow.length or target[r].length elements, whichever is smaller

Like this:

```<code>System.arraycopy(newRow, 0, target[r], 0, Math.min(newRow.length, target[r].length));
</code>```

Body:
I would like to use SysteM.arraycopy to make the below method faster. But as of my knowledge, Arraycopy cannot involve any such complicated logic.

for (int c = 0; c < newRow.length && c < target[r].length; ++c)
{
    target[r][c] = newRow[c];
}

So any help would be welcome. Thanks in advance.

Body:
You can rewrite that using System.arraycopy.
This about it this way:

You want to copy starting from index 0 of newRow

You want to copy starting from index 0 into target[r]

You want to copy at most newRow.length or target[r].length elements, whichever is smaller

Like this:

System.arraycopy(newRow, 0, target[r], 0, Math.min(newRow.length, target[r].length));


问:
Create LinkedIn user using Graph API
Is it possible to create LinkedIn user in Azure AD B2C using Graph API?

I can see that when I create LinkedIn user using hosted pages, the following user is created in directory

But when I query users endpoint, I don't see any properties on the user object that would say, that he is a LinkedIn user.

答:
It is not a LinkedIn user. It is a user who created an account in your Azure AD B2C using LinkedIn as an identity provider.

For you, as the Azure AD B2C administrator, it does not matter where the user has authenticated. You can not create a user account with a fixed identity provider.

Title: Create LinkedIn user using Graph API


问:
Distinct count of users grouped by a column and distributed across bins
I have several users that each have a department they belong to and a integer which denotes (in days) when they last logged in.
A user can have several departments.

I am trying to group the users by department, vertically distribute them across three bins depending on when they logged in, and then uniquely count them.
If a user belongs to several departments i only want to count them once, it dosen't matter under which department they are being counted.

In my current solution a user with several departments gets counted once for
each department, which, given my solution, makes sense, but is not what I want.
If i try a distinct count it returns the same as each row is unique.

I'm using the MsSql Fiddle example except that I have added a DaysSinceLastLogin (int) column that denotes when the user last logged in.
Uncomment the first sql block to see the 6 users and which departments they belong to.
Fiddle here

答:
As variant you can use a subquery

```<code>SELECT
  MaxDepartment,
  COUNT(case when MaxDaysSinceLastLogin < 10 then 1 end) as 'Last Login within 10 days',
  COUNT(case when MaxDaysSinceLastLogin > 10 and  MaxDaysSinceLastLogin <= 20 then 1 end) as 'Last Login within 10-20 days',
  COUNT(case when MaxDaysSinceLastLogin > 20 then 1 end) 'Last Login more then 20 days'
FROM
  (
    SELECT
      [User],
      -- any department
      MAX([Department]) MaxDepartment,
      -- max of days
      MAX([DaysSinceLastLogin]) MaxDaysSinceLastLogin
    FROM yourtable
    GROUP BY [User]
  ) q
GROUP BY MaxDepartment
</code>```

I hope I understood you correctly.

Body:
As variant you can use a subquery

SELECT
  MaxDepartment,
  COUNT(case when MaxDaysSinceLastLogin < 10 then 1 end) as 'Last Login within 10 days',
  COUNT(case when MaxDaysSinceLastLogin > 10 and  MaxDaysSinceLastLogin <= 20 then 1 end) as 'Last Login within 10-20 days',
  COUNT(case when MaxDaysSinceLastLogin > 20 then 1 end) 'Last Login more then 20 days'
FROM
  (
    SELECT
      [User],
      -- any department
      MAX([Department]) MaxDepartment,
      -- max of days
      MAX([DaysSinceLastLogin]) MaxDaysSinceLastLogin
    FROM yourtable
    GROUP BY [User]
  ) q
GROUP BY MaxDepartment

I hope I understood you correctly.


问:
Google Closure Compile REST Api suddenly Throws Error 405 "Method not allowed"
I've been using Closure as part of y application to compress Javascript for a while now, but just started getting an error 405 - Method not allowed

My code as below was working for a couple of years, but has now stopped.

NOTE: this is not called frequently, just when ever any changes are detected in the Javascript files in my application.

I get no further error information from the Closure app than this.

Obviously this code performs a POST operation. If I use the form found here https://closure-compiler.appspot.com/home, it works, but if I either browser to the URL or use my code I get Error 405, it's almost as if my code is trying a GET method... but it's not...

Any ideas?

```<code>Public Class Closure

    Property OriginalCode As String
    Property CompiledCode As String
    Property Errors As ArrayList
    Property Warnings As ArrayList
    Property Statistics As Dictionary(Of String, Object)

    Public Sub New(Input As String, Optional CompliationLevel As String = "SIMPLE_OPTIMIZATIONS")

        Dim _HttpWebRequest As HttpWebRequest
        Dim _Result As StringBuilder
        Dim ClosureWebServiceURL As String = "http://closure-compiler.appspot.com/compile?"
        Dim ClosureWebServicePOSTData As String = "output_format=json&output_info=compiled_code" &
                                                                        "&output_info=warnings" &
                                                                        "&output_info=errors" &
                                                                        "&output_info=statistics" &
                                                                        "&compilation_level=" & CompliationLevel & "" &
                                                                        "&warning_level=default" &
                                                                        "&js_code={0}"

        '// Create the POST data
        Dim Data = String.Format(ClosureWebServicePOSTData, HttpUtility.UrlEncode(Input))

        _Result = New StringBuilder
        _HttpWebRequest = DirectCast(WebRequest.Create(ClosureWebServiceURL), HttpWebRequest)
        _HttpWebRequest.Method = "POST"
        _HttpWebRequest.ContentType = "application/x-www-form-urlencoded"
        '//Set the content length to the length of the data. This might need to change if you're using characters that take more than 256 bytes
        _HttpWebRequest.ContentLength = Data.Length
        '//Write the request stream
        Using SW As New StreamWriter(_HttpWebRequest.GetRequestStream())
            SW.Write(Data)
        End Using

        Try

            Dim response As WebResponse = _HttpWebRequest.GetResponse()

            Using responseStream As Stream = response.GetResponseStream
                Dim encoding As Encoding = System.Text.Encoding.GetEncoding("utf-8")
                Using readStream As New StreamReader(responseStream, encoding)
                    Dim read(256) As Char
                    Dim count As Integer = readStream.Read(read, 0, 256)
                    While count > 0
                        Dim str As New String(read, 0, count)
                        _Result.Append(str)
                        count = readStream.Read(read, 0, 256)
                    End While
                End Using
            End Using

            Dim js As New JavaScriptSerializer
            js.MaxJsonLength = Int32.MaxValue

            Dim d As Dictionary(Of String, Object) = js.Deserialize(Of Dictionary(Of String, Object))(_Result.ToString())
            Me.CompiledCode = d.NullKey("compiledCode")
            Me.Warnings = TryCast(d.NullKey("warnings"), ArrayList)
            Me.Errors = TryCast(d.NullKey("errors"), ArrayList)
            Me.Statistics = TryCast(d.NullKey("statistics"), Dictionary(Of String, Object))

        Catch ex As Exception
            Me.CompiledCode = ""
            If Me.Errors Is Nothing Then
                Dim er As New List(Of String)
                er.Add(ex.ToString())
                Me.Errors = New ArrayList(er)
            Else
                Me.Errors.Add(ex.ToString())
            End If
        End Try

        Me.OriginalCode = Input

    End Sub

End Class
</code>```

答: Closure REST api is redirecting to https, you may want to try to POST to "https://closure-compiler.appspot.com/compile" directly in order to avoid redirection.</p>

Body:
I've been using Closure as part of y application to compress Javascript for a while now, but just started getting an error 405 - Method not allowed

My code as below was working for a couple of years, but has now stopped.

NOTE: this is not called frequently, just when ever any changes are detected in the Javascript files in my application.

I get no further error information from the Closure app than this.

Obviously this code performs a POST operation. If I use the form found here https://closure-compiler.appspot.com/home, it works, but if I either browser to the URL or use my code I get Error 405, it's almost as if my code is trying a GET method... but it's not...

Any ideas?

Public Class Closure

    Property OriginalCode As String
    Property CompiledCode As String
    Property Errors As ArrayList
    Property Warnings As ArrayList
    Property Statistics As Dictionary(Of String, Object)

    Public Sub New(Input As String, Optional CompliationLevel As String = "SIMPLE_OPTIMIZATIONS")

        Dim _HttpWebRequest As HttpWebRequest
        Dim _Result As StringBuilder
        Dim ClosureWebServiceURL As String = "http://closure-compiler.appspot.com/compile?"
        Dim ClosureWebServicePOSTData As String = "output_format=json&output_info=compiled_code" &
                                                                        "&output_info=warnings" &
                                                                        "&output_info=errors" &
                                                                        "&output_info=statistics" &
                                                                        "&compilation_level=" & CompliationLevel & "" &
                                                                        "&warning_level=default" &
                                                                        "&js_code={0}"

        '// Create the POST data
        Dim Data = String.Format(ClosureWebServicePOSTData, HttpUtility.UrlEncode(Input))

        _Result = New StringBuilder
        _HttpWebRequest = DirectCast(WebRequest.Create(ClosureWebServiceURL), HttpWebRequest)
        _HttpWebRequest.Method = "POST"
        _HttpWebRequest.ContentType = "application/x-www-form-urlencoded"
        '//Set the content length to the length of the data. This might need to change if you're using characters that take more than 256 bytes
        _HttpWebRequest.ContentLength = Data.Length
        '//Write the request stream
        Using SW As New StreamWriter(_HttpWebRequest.GetRequestStream())
            SW.Write(Data)
        End Using

        Try

            Dim response As WebResponse = _HttpWebRequest.GetResponse()

            Using responseStream As Stream = response.GetResponseStream
                Dim encoding As Encoding = System.Text.Encoding.GetEncoding("utf-8")
                Using readStream As New StreamReader(responseStream, encoding)
                    Dim read(256) As Char
                    Dim count As Integer = readStream.Read(read, 0, 256)
                    While count > 0
                        Dim str As New String(read, 0, count)
                        _Result.Append(str)
                        count = readStream.Read(read, 0, 256)
                    End While
                End Using
            End Using

            Dim js As New JavaScriptSerializer
            js.MaxJsonLength = Int32.MaxValue

            Dim d As Dictionary(Of String, Object) = js.Deserialize(Of Dictionary(Of String, Object))(_Result.ToString())
            Me.CompiledCode = d.NullKey("compiledCode")
            Me.Warnings = TryCast(d.NullKey("warnings"), ArrayList)
            Me.Errors = TryCast(d.NullKey("errors"), ArrayList)
            Me.Statistics = TryCast(d.NullKey("statistics"), Dictionary(Of String, Object))

        Catch ex As Exception
            Me.CompiledCode = ""
            If Me.Errors Is Nothing Then
                Dim er As New List(Of String)
                er.Add(ex.ToString())
                Me.Errors = New ArrayList(er)
            Else
                Me.Errors.Add(ex.ToString())
            End If
        End Try

        Me.OriginalCode = Input

    End Sub

End Class


问:
Salesforce custom objects accessing using selenium webdriver with java
Each time SalesForce does a new release, most of the ID's of the elements on the salesforce webpage change(I use the ID property of the element to locate it with my automation code). This breaks my automation scripts.

In my case one text box named as "Question Name" i want to enter a value in this text box.

recent html:

```<code><label class="label inputLabel uiLabel-left form-element__label uiLabel" for="7:1781;a" data-aura-rendered-by="1040:0" data-aura-class="uiLabel">
<span class="" data-aura-rendered-by="1041:0">Question Name</span>
<span class="required " data-aura-rendered-by="8:1781;a">*</span>
</label>
<input id="7:1781;a" class=" input" maxlength="80" aria-describedby="" placeholder="" required="" data-aura-rendered-by="11:1781;a"
data-interactive-lib-uid="5" aria-required="true" type="text">
</code>```

my existing xpath :

```<code>driver.findElement(By.xpath("//input[@id='6:2634;a']")).sendKeys("test");
</code>```

Salesforce application all ID's are dynamically changed for every new release, my test script failed with the above xpath with Id, so please suggest me alternate solution.

how should i get the input id value in runtime? or let me know is there any other possible.

答:
You can use the following:

```<code>driver.findElement(By.xpath("//label[contains(., 'Question Name')]/following-sibling::input")).sendKeys("test");
</code>```

This will search for a label containing the text 'Question Name' and then selects the following input sibling

Body:
Each time SalesForce does a new release, most of the ID's of the elements on the salesforce webpage change(I use the ID property of the element to locate it with my automation code). This breaks my automation scripts.

In my case one text box named as "Question Name" i want to enter a value in this text box.

recent html:

Question Name
*

<input id="7:1781;a" class=" input" maxlength="80" aria-describedby="" placeholder="" required="" data-aura-rendered-by="11:1781;a"
data-interactive-lib-uid="5" aria-required="true" type="text">

my existing xpath :

driver.findElement(By.xpath("//input[@id='6:2634;a']")).sendKeys("test");

Salesforce application all ID's are dynamically changed for every new release, my test script failed with the above xpath with Id, so please suggest me alternate solution.

how should i get the input id value in runtime? or let me know is there any other possible.

Body:
You can use the following:

driver.findElement(By.xpath("//label[contains(., 'Question Name')]/following-sibling::input")).sendKeys("test");

This will search for a label containing the text 'Question Name' and then selects the following input sibling


问:
How to run two methods in Gradle in parallel mode?
I got a Gradle task which calls two methods. The methods are independent of each other so I want to start them parallel. What is the best way to achieve this?

Example:

```<code>task cucumber(dependsOn: 'testClasses') {
    doLast {
        // ...
        // I want to call the next 2 methods in parallel
        runSequentialTests(testEnvironment, tags)
        runParallelTests(testEnvironment, tags)
    }
}

def runSequentialTests(testEnvironment, tags) {
    // execute cucumber tests via javaexec
}

def runParallelTests(testEnvironment, tags) {
    // execute cucumber tests via exec sh script for each feature file (parallelism is done via GParsPool.withPool(5) {...}
}
</code>```

答:
Worth researching groovy parallel systems library gpars

```<code>GParsPool.withPool {
    GParsPool.executeAsyncAndWait({runSequentialTests(testEnvironment, tags)}, {runParallelTests(testEnvironment, tags)})
}
</code>```

Or maybe create a @ParallelizableTask

But I'm not sure what version of gradle you are using. And parallel is/was an incubating feature.

And needs to run build with --parallel if those have no dependencies between themselves Gradle should run them independently.

Alternatively, you can specify a property in your gradle.properties

C:\Users\<user>\.gradle\gradle.properties
org.gradle.parallel=true

Body:
I got a Gradle task which calls two methods. The methods are independent of each other so I want to start them parallel. What is the best way to achieve this?

Example:

task cucumber(dependsOn: 'testClasses') {
    doLast {
        // ...
        // I want to call the next 2 methods in parallel
        runSequentialTests(testEnvironment, tags)
        runParallelTests(testEnvironment, tags)
    }
}

def runSequentialTests(testEnvironment, tags) {
    // execute cucumber tests via javaexec
}

def runParallelTests(testEnvironment, tags) {
    // execute cucumber tests via exec sh script for each feature file (parallelism is done via GParsPool.withPool(5) {...}
}

Body:
Worth researching groovy parallel systems library gpars

GParsPool.withPool {
    GParsPool.executeAsyncAndWait({runSequentialTests(testEnvironment, tags)}, {runParallelTests(testEnvironment, tags)})
}

Or maybe create a @ParallelizableTask

But I'm not sure what version of gradle you are using. And parallel is/was an incubating feature.

And needs to run build with --parallel if those have no dependencies between themselves Gradle should run them independently.

Alternatively, you can specify a property in your gradle.properties

C:\Users\<user>\.gradle\gradle.properties
org.gradle.parallel=true


问:
CRC 4 implementation for C#
Solved by this code -> https://gist.github.com/Sbreitzke/b26107798eee74e39ff85800abf71fb1

I searched the web for a CRC 4 implementation in C# because I have to calculate a checksum  by

Changing the numbers of the barcode into Hex representation, then to bytes and then to bits and then calculate a CRC4 checksum on the bit stream.

I already found this question from 8 years ago without an answer
CRC-4 implementation in C#.

I tried changing the CRC 8 and 16 implementations to CRC 4 but they don't quite get the result I require.

0130E0928270FFFFFFF should evaluate to 7.

I found two C implementation but was unable to convert them to C#. For example this one:

```<code> short[] crc4_tab = {
 0x0, 0x7, 0xe, 0x9, 0xb, 0xc, 0x5, 0x2,
 0x1, 0x6, 0xf, 0x8, 0xa, 0xd, 0x4, 0x3,
};

/**
* crc4 - calculate the 4-bit crc of a value.
* @crc:  starting crc4
* @x:    value to checksum
* @bits: number of bits in @x to checksum
*
* Returns the crc4 value of @x, using polynomial 0b10111.
*
* The @x value is treated as left-aligned, and bits above @bits are ignored
* in the crc calculations.
*/
short crc4(uint8_t c, uint64_t x, int bits)
{
    int i;

    /* mask off anything above the top bit */
    x &= (1ull << bits) -1;

    /* Align to 4-bits */
    bits = (bits + 3) & ~0x3;

    /* Calculate crc4 over four-bit nibbles, starting at the MSbit */
    for (i = bits - 4; i >= 0; i -= 4)
    c = crc4_tab[c ^ ((x >> i) & 0xf)];

    return c;
}
</code>```

My current generation code (unit test) looks like this:

```<code>[TestMethod]
public void x()
{
    var ordnungskennzeichen = 01;
    var kundennummer = 51251496;
    var einlieferungsbel = 9999;
    var sendungsnr = 16777215;

    var hex_ordnungskennzeichen = ordnungskennzeichen.ToString("x2");
    var hex_kundennummer = kundennummer.ToString("x2");
    var hex_einlieferungsbel = einlieferungsbel.ToString("x2");
    var hex_sendungsnr = sendungsnr.ToString("x2");

    var complete = hex_ordnungskennzeichen + hex_kundennummer + hex_einlieferungsbel + hex_sendungsnr;

    var bytes = Encoding.ASCII.GetBytes(complete);

    //var computeChecksum = crc4(???);
    //   Console.WriteLine(computeChecksum);

}

short[] crc4_tab = {
    0x0, 0x7, 0xe, 0x9, 0xb, 0xc, 0x5, 0x2,
    0x1, 0x6, 0xf, 0x8, 0xa, 0xd, 0x4, 0x3,
};

/**
* crc4 - calculate the 4-bit crc of a value.
* @crc:  starting crc4
* @x:    value to checksum
* @bits: number of bits in @x to checksum
*
* Returns the crc4 value of @x, using polynomial 0b10111.
*
* The @x value is treated as left-aligned, and bits above @bits are ignored
* in the crc calculations.
*/

short crc4(byte c, ulong x, int bits)
{
    int i;

    /* mask off anything above the top bit */
    x &= ((ulong)1 << bits) -1;

    /* Align to 4-bits */
    bits = (bits + 3) & ~0x3;

    /* Calculate crc4 over four-bit nibbles, starting at the MSbit */
    for (i = bits - 4; i >= 0; i -= 4)
        c = (byte) crc4_tab[c ^ ((x >> i) & 0xf)];

    return c;
}
</code>```

答:
After further testing and communication with the Deutsche Post AG we made a correct implementation (for the purpose of Deutsche Post at least):

https://gist.github.com/Sbreitzke/b26107798eee74e39ff85800abf71fb1

Title: CRC 4 implementation for C#

Body:
Solved by this code -> https://gist.github.com/Sbreitzke/b26107798eee74e39ff85800abf71fb1

I searched the web for a CRC 4 implementation in C# because I have to calculate a checksum  by

Changing the numbers of the barcode into Hex representation, then to bytes and then to bits and then calculate a CRC4 checksum on the bit stream.

I already found this question from 8 years ago without an answer
CRC-4 implementation in C#.

I tried changing the CRC 8 and 16 implementations to CRC 4 but they don't quite get the result I require.

0130E0928270FFFFFFF should evaluate to 7.

I found two C implementation but was unable to convert them to C#. For example this one:

 short[] crc4_tab = {
 0x0, 0x7, 0xe, 0x9, 0xb, 0xc, 0x5, 0x2,
 0x1, 0x6, 0xf, 0x8, 0xa, 0xd, 0x4, 0x3,
};

/**
* crc4 - calculate the 4-bit crc of a value.
* @crc:  starting crc4
* @x:    value to checksum
* @bits: number of bits in @x to checksum
*
* Returns the crc4 value of @x, using polynomial 0b10111.
*
* The @x value is treated as left-aligned, and bits above @bits are ignored
* in the crc calculations.
*/
short crc4(uint8_t c, uint64_t x, int bits)
{
    int i;

    /* mask off anything above the top bit */
    x &= (1ull << bits) -1;

    /* Align to 4-bits */
    bits = (bits + 3) & ~0x3;

    /* Calculate crc4 over four-bit nibbles, starting at the MSbit */
    for (i = bits - 4; i >= 0; i -= 4)
    c = crc4_tab[c ^ ((x >> i) & 0xf)];

    return c;
}

My current generation code (unit test) looks like this:

[TestMethod]
public void x()
{
    var ordnungskennzeichen = 01;
    var kundennummer = 51251496;
    var einlieferungsbel = 9999;
    var sendungsnr = 16777215;

    var hex_ordnungskennzeichen = ordnungskennzeichen.ToString("x2");
    var hex_kundennummer = kundennummer.ToString("x2");
    var hex_einlieferungsbel = einlieferungsbel.ToString("x2");
    var hex_sendungsnr = sendungsnr.ToString("x2");

    var complete = hex_ordnungskennzeichen + hex_kundennummer + hex_einlieferungsbel + hex_sendungsnr;

    var bytes = Encoding.ASCII.GetBytes(complete);

    //var computeChecksum = crc4(???);
    //   Console.WriteLine(computeChecksum);

}

short[] crc4_tab = {
    0x0, 0x7, 0xe, 0x9, 0xb, 0xc, 0x5, 0x2,
    0x1, 0x6, 0xf, 0x8, 0xa, 0xd, 0x4, 0x3,
};

/**
* crc4 - calculate the 4-bit crc of a value.
* @crc:  starting crc4
* @x:    value to checksum
* @bits: number of bits in @x to checksum
*
* Returns the crc4 value of @x, using polynomial 0b10111.
*
* The @x value is treated as left-aligned, and bits above @bits are ignored
* in the crc calculations.
*/

short crc4(byte c, ulong x, int bits)
{
    int i;

    /* mask off anything above the top bit */
    x &= ((ulong)1 << bits) -1;

    /* Align to 4-bits */
    bits = (bits + 3) & ~0x3;

    /* Calculate crc4 over four-bit nibbles, starting at the MSbit */
    for (i = bits - 4; i >= 0; i -= 4)
        c = (byte) crc4_tab[c ^ ((x >> i) & 0xf)];

    return c;
}


问:
Aligning the divs in a single line
I am trying to align two divs inside one div in a single line . I have tried with the following code:

```<code><div style="width:100%">
 <div id="id1" style="width:40%;float:left;background-color:green;position:relative">
   float-left
 </div>
 <div id="id2" style="width:60%;float:right;background-color:yellow;position:relative">
 float-right
   <div id="id3" style="position:relative;left:0px">
   button1
   </div>
    <div id="id4" style="position:absolute;right:0px">
   button2
   </div>
 </div>
</div>
</code>```

I need divs with id3 and id4 in the same line similar to span but I dont want to use a span tag , within id2 div?

I tried using position as both absolute and relative and combinations but it is not aligning within same line. What is it that I am missing?

答:
Just put display:inline-block

   float-left

   button1

   button2

```

Title: Aligning the divs in a single line

Body:
I am trying to align two divs inside one div in a single line . I have tried with the following code:

   float-left

 float-right

   button1

   button2

I need divs with id3 and id4 in the same line similar to span but I dont want to use a span tag , within id2 div?

I tried using position as both absolute and relative and combinations but it is not aligning within same line. What is it that I am missing?

Body:
Just put display:inline-block

<div style="width:100%">
 <div id="id1" style="width:40%;float:left;background-color:green;position:relative">
   float-left
 </div>
 <div id="id2" style="width:60%;float:right;background-color:yellow;position:relative">
   <div id="id3" style="display:inline-block;">
   button1
   </div>
    <div id="id4" style="display:inline-block;">
   button2
   </div>
 </div>
</div>