问:
JOIN table onto itself with parent id until no more rows
I have a table describing changes that has been made to an end_customers table. When someone changes and end_customer we create a new row in the end_customers table and add a row to end_customer_history table where end_customer_parent_id is the ID of the old end_customer, and end_customer_child_id is the ID of the new end_customer.

End Customer Table:

```<code>CREATE TABLE `end_customers` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `reference_person` varchar(255) DEFAULT NULL,
  `phone_number` varchar(255) NOT NULL,
  `email` varchar(255) DEFAULT NULL,
  `social_security_number` varchar(255) DEFAULT NULL,
  `comment` longtext,
  `token` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101107 DEFAULT CHARSET=utf8;
</code>```

End Customer History Table:

```<code>CREATE TABLE `end_customer_history` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `end_customer_parent_id` bigint(20) NOT NULL,
  `end_customer_child_id` bigint(20) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `date` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_end_customer_parent` (`end_customer_parent_id`),
  KEY `FK_end_customer_child` (`end_customer_child_id`),
  KEY `FK_user` (`user_id`),
  CONSTRAINT `end_customer_history_old_ibfk_1` FOREIGN KEY (`end_customer_parent_id`) REFERENCES `end_customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `end_customer_history_old_ibfk_2` FOREIGN KEY (`end_customer_child_id`) REFERENCES `end_customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `end_customer_history_old_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8;
</code>```

We are now refactoring the schema so that changes made to end_customers table directly edits the row instead of creating a new row, and puts a copy of the old data in a end_customer_history_new table that has the same schema as end_customers.

I need to migrate all old data to this new table.
So for each end_customer I have, I need to check if it has an entry in end_customer_history as a end_customer_child_id (it has been modified), and then check if that entrys parent is also present in end_customer_history as a child, and then check if that entrys parent is also present in end_customer_history as a child, and so forth until there are no more rows.

How do I do this in one migration SQL script?

答:
Unlike Oracle, MySQL does not provide the functionality to recursively query parent-child hierarchy. You can write a self join query (or inner queries) if you know the level beforehand. If not, you have to perform a single query and handle resursiveness in the application or stored procedure.

Here is an example of querying a parent child hierarchy if you know the level already, and here is an example of how to do it in Oracle (for your reference).

Body:
I have a table describing changes that has been made to an end_customers table. When someone changes and end_customer we create a new row in the end_customers table and add a row to end_customer_history table where end_customer_parent_id is the ID of the old end_customer, and end_customer_child_id is the ID of the new end_customer.

End Customer Table:

CREATE TABLE `end_customers` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `reference_person` varchar(255) DEFAULT NULL,
  `phone_number` varchar(255) NOT NULL,
  `email` varchar(255) DEFAULT NULL,
  `social_security_number` varchar(255) DEFAULT NULL,
  `comment` longtext,
  `token` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101107 DEFAULT CHARSET=utf8;

End Customer History Table:

CREATE TABLE `end_customer_history` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `end_customer_parent_id` bigint(20) NOT NULL,
  `end_customer_child_id` bigint(20) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `date` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_end_customer_parent` (`end_customer_parent_id`),
  KEY `FK_end_customer_child` (`end_customer_child_id`),
  KEY `FK_user` (`user_id`),
  CONSTRAINT `end_customer_history_old_ibfk_1` FOREIGN KEY (`end_customer_parent_id`) REFERENCES `end_customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `end_customer_history_old_ibfk_2` FOREIGN KEY (`end_customer_child_id`) REFERENCES `end_customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `end_customer_history_old_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8;

We are now refactoring the schema so that changes made to end_customers table directly edits the row instead of creating a new row, and puts a copy of the old data in a end_customer_history_new table that has the same schema as end_customers.

I need to migrate all old data to this new table.
So for each end_customer I have, I need to check if it has an entry in end_customer_history as a end_customer_child_id (it has been modified), and then check if that entrys parent is also present in end_customer_history as a child, and then check if that entrys parent is also present in end_customer_history as a child, and so forth until there are no more rows.

How do I do this in one migration SQL script?


来源: stackexchange

问:
Trigger function on number input
I have a text input where users are able to write addresses, I want to trigger a javascript function when a number is typed in the text input, how can I achieve it?

EDIT: What I need is to know when a number has been typed, onkeyup via jquery works like a charm, this is what I did:

```<code>$("#q").keyup((e) => {

        var value = $("#q").val();

        var regex = new RegExp("[a-zA-Z0-9_ ]\\d+");

        var succeded = regex.test(value);

        ...
</code>```

答:
This will do your job:

```<code>$('#tbInput').keypress(function(event){

if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
}
else
{
//Your function that you want to trigger.
alert("You pressed a numberic key: " + event.which);
}});
</code>```

You can test it here:
JSFIDDLE DEMO

ContentLicense: CC BY-SA 3.0

Title: Trigger function on number input

Body:
I have a text input where users are able to write addresses, I want to trigger a javascript function when a number is typed in the text input, how can I achieve it?

EDIT: What I need is to know when a number has been typed, onkeyup via jquery works like a charm, this is what I did:

$("#q").keyup((e) => {

        var value = $("#q").val();

        var regex = new RegExp("[a-zA-Z0-9_ ]\\d+");

        var succeded = regex.test(value);

        ...

Body:
This will do your job:

$('#tbInput').keypress(function(event){

if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
}
else
{
//Your function that you want to trigger.
alert("You pressed a numberic key: " + event.which);
}});

You can test it here:
JSFIDDLE DEMO


答:
You can simply do:

```<code>$("input").keyup(function(){
    $("input").css("background-color", "pink");
});
</code>```

Source

Title: Trigger function on number input

Body:
You can simply do:

$("input").keyup(function(){
    $("input").css("background-color", "pink");
});

Source


问:
can't build android project it shows error
project gradle

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

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        classpath 'com.google.gms:google-services:3.0.0'

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

allprojects {
    repositories {
        jcenter()
    }
}

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

App Gradle

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.arun4fms.efix"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        packagingOptions {
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE-FIREBASE.txt'
            exclude 'META-INF/NOTICE'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.chabbal:slidingdotsplash:1.0.2'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Error:A problem occurred configuring root project 'webapp'.

Could not resolve all dependencies for configuration ':classpath'.
  Could not find com.android.tools.build:gradle:3.0.0-alpha3.
       Searched in the following locations:
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
       Required by:
           project :

答:
Use this.. This may work because this worked in my case:

```<code>dependencies {
classpath 'com.android.tools.build:gradle:2.0.0-alpha3'
classpath 'com.google.gms:google-services:2.0.0-alpha3'
}
</code>```

and put this at the end of the app-level build.gradle file (after the dependencies).

```<code> apply plugin: 'com.google.gms.google-services'
</code>```

I have no clue why putting this at the end (and not at the beginning ) solves the error.

Ok… So trying to put an end to all problems you guys have faced with my solution

This is my final app level gradle

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

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "your-app-name"
    minSdkVersion 16
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    }
    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
        'proguard-rules.pro'
    }
    }
     }

   repositories {
    jcenter()
    }

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.android.support:design:23.1.1'
compile 'com.mcxiaoke.volley:library:1.0.6@aar'
}

 apply plugin: 'com.google.gms.google-services'
</code>```

and this is my final project level gradle

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

```<code>   buildscript {
   repositories {
    jcenter()
     }
    dependencies {
    classpath 'com.android.tools.build:gradle:2.0.0-alpha3'
    classpath 'com.google.gms:google-services:2.0.0-alpha3'

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

   allprojects {
   repositories {
    jcenter()
   }
   }
</code>```

Compare this with your own gradle files, and add or modify any values which are different from what I've written.

Body:
project gradle

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

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        classpath 'com.google.gms:google-services:3.0.0'

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

allprojects {
    repositories {
        jcenter()
    }
}

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

App Gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.arun4fms.efix"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        packagingOptions {
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE-FIREBASE.txt'
            exclude 'META-INF/NOTICE'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.chabbal:slidingdotsplash:1.0.2'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Error:A problem occurred configuring root project 'webapp'.

Could not resolve all dependencies for configuration ':classpath'.
  Could not find com.android.tools.build:gradle:3.0.0-alpha3.
       Searched in the following locations:
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
       Required by:
           project :

Body:
Use this.. This may work because this worked in my case:

dependencies {
classpath 'com.android.tools.build:gradle:2.0.0-alpha3'
classpath 'com.google.gms:google-services:2.0.0-alpha3'
}

and put this at the end of the app-level build.gradle file (after the dependencies).

 apply plugin: 'com.google.gms.google-services'

I have no clue why putting this at the end (and not at the beginning ) solves the error.

Ok… So trying to put an end to all problems you guys have faced with my solution

This is my final app level gradle

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "your-app-name"
    minSdkVersion 16
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    }
    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
        'proguard-rules.pro'
    }
    }
     }

   repositories {
    jcenter()
    }

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.android.support:design:23.1.1'
compile 'com.mcxiaoke.volley:library:1.0.6@aar'
}

 apply plugin: 'com.google.gms.google-services'

and this is my final project level gradle

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

   buildscript {
   repositories {
    jcenter()
     }
    dependencies {
    classpath 'com.android.tools.build:gradle:2.0.0-alpha3'
    classpath 'com.google.gms:google-services:2.0.0-alpha3'

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

   allprojects {
   repositories {
    jcenter()
   }
   }

Compare this with your own gradle files, and add or modify any values which are different from what I've written.


问:
How to implement tuple unpacking for function parameters in Java?
I have created some tuple classes, and put them into Java collection. But I don't want to use tuple as function parameters directly when iterating collection.So I implemented tuple unpacking as the following code.

Basically it works, but the problem is that a type casting is needed:

map((Func2<Long, Long, Long>) (a, b) -> a + b)

Is there any way to remove the type casting here?

edit:

Maybe I didn't make it clear, not only tuple2, but also tuple3, tuple4... should be supported. @Flown's answer works greatly for Tuple2, but doesn't work for tuple2, tuple3, tuple4 in the meantime

```<code>package test;

import com.google.common.collect.Iterables;

import java.util.Arrays;
import java.util.function.Function;

import static test.TupleIterable.Tuple.tuple;

public interface TupleIterable<T> {

    Iterable<T> apply();

    static <E> TupleIterable<E> from(Iterable<E> iterable) {
        return () -> iterable;
    }

    default <E> TupleIterable<E> map(Function<? super T, ? extends E> op) {
        return () -> Iterables.transform(TupleIterable.this.apply(), op::apply);
    }

    interface Func2<T1, T2, R> extends Function<Tuple.Tuple2<T1, T2>, R> {

        R apply(T1 t1, T2 t2);

        @Override
        default R apply(Tuple.Tuple2<T1, T2> t) {
            return apply(t.t1, t.t2);
        }
    }

    interface Func3<T1, T2, T3, R> extends Function<Tuple.Tuple3<T1, T2, T3>, R> {

        R apply(T1 t1, T2 t2, T3 t3);

        @Override
        default R apply(Tuple.Tuple3<T1, T2, T3> t) {
            return apply(t.t1, t.t2, t.t3);
        }
    }

    interface Tuple {

        static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
            return new Tuple2<>(t1, t2);
        }

        static <T1, T2, T3> Tuple3<T1, T2, T3> tuple(T1 t1, T2 t2, T3 t3) {
            return new Tuple3<>(t1, t2, t3);
        }

        class Tuple2<T1, T2> implements Tuple {

            public T1 t1;

            public T2 t2;

            public Tuple2(T1 t1, T2 t2) {
                this.t1 = t1;
                this.t2 = t2;
            }
        }

        class Tuple3<T1, T2, T3> implements Tuple {

            public T1 t1;

            public T2 t2;

            public T3 t3;

            public Tuple3(T1 t1, T2 t2, T3 t3) {
                this.t1 = t1;
                this.t2 = t2;
                this.t3 = t3;
            }
        }
    }

    public static void main(String[] args) {
        TupleIterable.from(Arrays.asList(1L, 2L))
                .map(x -> tuple(x, x)) // map long to tuple2
                .map((Func2<Long, Long, Tuple.Tuple3<Long, Long, Long>>) (a, b) -> tuple(a, b, a + b)) // map tuple2 to tuple3
                .map((Func3<Long, Long, Long, Long>) (a, b, c) -> a + b + c) // map tuple3 to Long
                .apply()
                .forEach(System.out::println);
    }
}
</code>```

答:
You can do the same trick as the JDK developer did for the Stream specializations of primitive types. Introduce mapToTuple and unwrap in different interfaces.

I rewrote some of your code and used some existing FunctionalInterfaces.

```<code>import java.util.Arrays;
import java.util.Iterator;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

public class Test {

  public static void main(String... args) {
    MyIterable.from(Arrays.asList(1L, 2L)).mapToTuple(l -> Tuple2.tuple(l, l + 1L)).unwrap((a, b) -> a + b).get()
        .forEach(System.out::println);
  }
}

final class Tuple2<T1, T2> {

  public static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
    return new Tuple2<>(t1, t2);
  }

  public final T1 t1;
  public final T2 t2;

  private Tuple2(T1 t1, T2 t2) {
    this.t1 = t1;
    this.t2 = t2;
  }
}

@FunctionalInterface
interface TupleIterable<T1, T2> extends Supplier<Iterable<Tuple2<T1, T2>>> {

  default <E> MyIterable<E> unwrap(BiFunction<T1, T2, E> func) {
    return () -> Iterables.transform(get(), t -> func.apply(t.t1, t.t2));
  }
}

@FunctionalInterface
interface MyIterable<T> extends Supplier<Iterable<T>> {

  static <E> MyIterable<E> from(Iterable<E> iterable) {
    return () -> iterable;
  }

  default <E> MyIterable<E> map(Function<? super T, ? extends E> mapper) {
    return () -> Iterables.transform(get(), mapper::apply);
  }

  default <T1, T2> TupleIterable<T1, T2> mapToTuple(Function<? super T, ? extends Tuple2<T1, T2>> tupleMapper) {
    return () -> Iterables.transform(get(), tupleMapper::apply);
  }
}

final class Iterables {
  public static <T, E> Iterable<E> transform(Iterable<T> iterable, Function<? super T, ? extends E> mapper) {
    return () -> new Iterator<E>() {

      private final Iterator<T> iter = iterable.iterator();

      @Override
      public boolean hasNext() {
        return iter.hasNext();
      }

      @Override
      public E next() {
        return mapper.apply(iter.next());
      }
    };
  }
}
</code>```

Body:
I have created some tuple classes, and put them into Java collection. But I don't want to use tuple as function parameters directly when iterating collection.So I implemented tuple unpacking as the following code.

Basically it works, but the problem is that a type casting is needed:

map((Func2<Long, Long, Long>) (a, b) -> a + b)

Is there any way to remove the type casting here?

edit:

Maybe I didn't make it clear, not only tuple2, but also tuple3, tuple4... should be supported. @Flown's answer works greatly for Tuple2, but doesn't work for tuple2, tuple3, tuple4 in the meantime

package test;

import com.google.common.collect.Iterables;

import java.util.Arrays;
import java.util.function.Function;

import static test.TupleIterable.Tuple.tuple;

public interface TupleIterable<T> {

    Iterable<T> apply();

    static <E> TupleIterable<E> from(Iterable<E> iterable) {
        return () -> iterable;
    }

    default <E> TupleIterable<E> map(Function<? super T, ? extends E> op) {
        return () -> Iterables.transform(TupleIterable.this.apply(), op::apply);
    }

    interface Func2<T1, T2, R> extends Function<Tuple.Tuple2<T1, T2>, R> {

        R apply(T1 t1, T2 t2);

        @Override
        default R apply(Tuple.Tuple2<T1, T2> t) {
            return apply(t.t1, t.t2);
        }
    }

    interface Func3<T1, T2, T3, R> extends Function<Tuple.Tuple3<T1, T2, T3>, R> {

        R apply(T1 t1, T2 t2, T3 t3);

        @Override
        default R apply(Tuple.Tuple3<T1, T2, T3> t) {
            return apply(t.t1, t.t2, t.t3);
        }
    }

    interface Tuple {

        static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
            return new Tuple2<>(t1, t2);
        }

        static <T1, T2, T3> Tuple3<T1, T2, T3> tuple(T1 t1, T2 t2, T3 t3) {
            return new Tuple3<>(t1, t2, t3);
        }

        class Tuple2<T1, T2> implements Tuple {

            public T1 t1;

            public T2 t2;

            public Tuple2(T1 t1, T2 t2) {
                this.t1 = t1;
                this.t2 = t2;
            }
        }

        class Tuple3<T1, T2, T3> implements Tuple {

            public T1 t1;

            public T2 t2;

            public T3 t3;

            public Tuple3(T1 t1, T2 t2, T3 t3) {
                this.t1 = t1;
                this.t2 = t2;
                this.t3 = t3;
            }
        }
    }

    public static void main(String[] args) {
        TupleIterable.from(Arrays.asList(1L, 2L))
                .map(x -> tuple(x, x)) // map long to tuple2
                .map((Func2<Long, Long, Tuple.Tuple3<Long, Long, Long>>) (a, b) -> tuple(a, b, a + b)) // map tuple2 to tuple3
                .map((Func3<Long, Long, Long, Long>) (a, b, c) -> a + b + c) // map tuple3 to Long
                .apply()
                .forEach(System.out::println);
    }
}

Body:
You can do the same trick as the JDK developer did for the Stream specializations of primitive types. Introduce mapToTuple and unwrap in different interfaces.

I rewrote some of your code and used some existing FunctionalInterfaces.

import java.util.Arrays;
import java.util.Iterator;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

public class Test {

  public static void main(String... args) {
    MyIterable.from(Arrays.asList(1L, 2L)).mapToTuple(l -> Tuple2.tuple(l, l + 1L)).unwrap((a, b) -> a + b).get()
        .forEach(System.out::println);
  }
}

final class Tuple2<T1, T2> {

  public static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
    return new Tuple2<>(t1, t2);
  }

  public final T1 t1;
  public final T2 t2;

  private Tuple2(T1 t1, T2 t2) {
    this.t1 = t1;
    this.t2 = t2;
  }
}

@FunctionalInterface
interface TupleIterable<T1, T2> extends Supplier<Iterable<Tuple2<T1, T2>>> {

  default <E> MyIterable<E> unwrap(BiFunction<T1, T2, E> func) {
    return () -> Iterables.transform(get(), t -> func.apply(t.t1, t.t2));
  }
}

@FunctionalInterface
interface MyIterable<T> extends Supplier<Iterable<T>> {

  static <E> MyIterable<E> from(Iterable<E> iterable) {
    return () -> iterable;
  }

  default <E> MyIterable<E> map(Function<? super T, ? extends E> mapper) {
    return () -> Iterables.transform(get(), mapper::apply);
  }

  default <T1, T2> TupleIterable<T1, T2> mapToTuple(Function<? super T, ? extends Tuple2<T1, T2>> tupleMapper) {
    return () -> Iterables.transform(get(), tupleMapper::apply);
  }
}

final class Iterables {
  public static <T, E> Iterable<E> transform(Iterable<T> iterable, Function<? super T, ? extends E> mapper) {
    return () -> new Iterator<E>() {

      private final Iterator<T> iter = iterable.iterator();

      @Override
      public boolean hasNext() {
        return iter.hasNext();
      }

      @Override
      public E next() {
        return mapper.apply(iter.next());
      }
    };
  }
}


问:
JSON only allows one top level value?
I have the following Java Object:

```<code>public class PersonDetails {
    private Person person;
    private List<Relative> relatives;

    public PersonDetails() {};

    //getters and setters

    }
</code>```

I am trying to create Stub JSON for this so that I can parse it to a Java Object using GSON.

When I try to use the below JSON, but I get the error:

```<code>JSON only allows one top level value
</code>```

How can I alter my JSON to make it valid?

My Current JSON:

```<code>{
    "Person": {

        "id": "123",
        "name: "stubName"
    },
    [
     "Relative": {

        "name": "relative1",
        "relation: "mother"

     }

    ]
}
</code>```

答:
'Relatives' could be your field name and the list will be a javascript array with the element you need, like this:</p>

```<code>{
    "Person": {

        "id": "123",
        "name: "stubName"
    },

    "Relatives": [{

            "name": "relative1",
            "relation: "mother"

         } ]
 }
</code>```

Title: JSON only allows one top level value?

Body:
I have the following Java Object:

public class PersonDetails {
    private Person person;
    private List<Relative> relatives;

    public PersonDetails() {};

    //getters and setters

    }

I am trying to create Stub JSON for this so that I can parse it to a Java Object using GSON.

When I try to use the below JSON, but I get the error:

JSON only allows one top level value

How can I alter my JSON to make it valid?

My Current JSON:

{
    "Person": {

        "id": "123",
        "name: "stubName"
    },
    [
     "Relative": {

        "name": "relative1",
        "relation: "mother"

     }

    ]
}

Body:
'Relatives' could be your field name and the list will be a javascript array with the element you need, like this:

{
    "Person": {

        "id": "123",
        "name: "stubName"
    },

    "Relatives": [{

            "name": "relative1",
            "relation: "mother"

         } ]
 }


问:
Replacing text in one CSV column using FasterCSV
Being relatively new to Ruby, I am trying to figure out how to do the following using FasterCSV:
Open a CSV file, pick a column by its header, in this column only replace all occurrences of string x with y, write out the new file to STDOUT.
The following code almost works:

```<code>filename = ARGV[0]
csv = FCSV.read(filename, :headers => true, :header_converters => :symbol, :return_headers => true, :encoding => 'u')
mycol = csv[:mycol]
# construct a mycol_new by iterating over mycol and doing some string replacement
puts csv[:mycol][0] # produces "MyCol" as expected
puts mycol_new[0] # produces "MyCol" as expected
csv[:mycol] = mycol_new
puts csv[:mycol][0] # produces "mycol" while "MyCol" is expected
csv.each do |r|
  puts r.to_csv(:force_quotes => true)
end
</code>```

The only problem is that there is a header conversion where I do not expect it. If the header of the chosen column is "MyCol" before the substitution of the columns in the csv table it is "mycol" afterwards (see comments in the code). Why does this happen? And how to avoid it? Thanks.

答:
There's a couple of things you can change in the initialization line that will help. Change:

```<code>csv = FCSV.read(filename, :headers => true, :return_headers => true, :encoding => 'u')
</code>```

to:

```<code>csv = FCSV.read(filename, :headers => true, :encoding => 'u')
</code>```

I'm using CSV, which is FasterCSV only it's part of Ruby 1.9. This will create a CSV file in the current directory called "temp.csv" with a modified 'FName' field:

```<code>require 'csv'

data = "ID,FName,LName\n1,mickey,mouse\n2,minnie,mouse\n3,donald,duck\n"

# read and parse the data
csv_in = CSV.new(data, :headers => true)

# open the temp file
CSV.open('./temp.csv', 'w') do |csv_out|

  # output the headers embedded in the object, then rewind to the start of the list
  csv_out << csv_in.first.headers
  csv_in.rewind

  # loop over the rows
  csv_in.each do |row|

    # munge the first name
    if (row['FName']['mi'])
      row['FName'] = row['FName'][1 .. -1] << '-' << row['FName'][0] << 'ay'
    end

    # output the record
    csv_out << row.fields
  end
end
</code>```

The output looks like:

```<code>ID,FName,LName
1,ickey-may,mouse
2,innie-may,mouse
3,donald,duck
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Being relatively new to Ruby, I am trying to figure out how to do the following using FasterCSV:
Open a CSV file, pick a column by its header, in this column only replace all occurrences of string x with y, write out the new file to STDOUT.
The following code almost works:

filename = ARGV[0]
csv = FCSV.read(filename, :headers => true, :header_converters => :symbol, :return_headers => true, :encoding => 'u')
mycol = csv[:mycol]
# construct a mycol_new by iterating over mycol and doing some string replacement
puts csv[:mycol][0] # produces "MyCol" as expected
puts mycol_new[0] # produces "MyCol" as expected
csv[:mycol] = mycol_new
puts csv[:mycol][0] # produces "mycol" while "MyCol" is expected
csv.each do |r|
  puts r.to_csv(:force_quotes => true)
end

The only problem is that there is a header conversion where I do not expect it. If the header of the chosen column is "MyCol" before the substitution of the columns in the csv table it is "mycol" afterwards (see comments in the code). Why does this happen? And how to avoid it? Thanks.

Body:
There's a couple of things you can change in the initialization line that will help. Change:

csv = FCSV.read(filename, :headers => true, :return_headers => true, :encoding => 'u')

to:

csv = FCSV.read(filename, :headers => true, :encoding => 'u')

I'm using CSV, which is FasterCSV only it's part of Ruby 1.9. This will create a CSV file in the current directory called "temp.csv" with a modified 'FName' field:

require 'csv'

data = "ID,FName,LName\n1,mickey,mouse\n2,minnie,mouse\n3,donald,duck\n"

# read and parse the data
csv_in = CSV.new(data, :headers => true)

# open the temp file
CSV.open('./temp.csv', 'w') do |csv_out|

  # output the headers embedded in the object, then rewind to the start of the list
  csv_out << csv_in.first.headers
  csv_in.rewind

  # loop over the rows
  csv_in.each do |row|

    # munge the first name
    if (row['FName']['mi'])
      row['FName'] = row['FName'][1 .. -1] << '-' << row['FName'][0] << 'ay'
    end

    # output the record
    csv_out << row.fields
  end
end

The output looks like:

ID,FName,LName
1,ickey-may,mouse
2,innie-may,mouse
3,donald,duck


问:
Trying to center 2 groups of 2 divs each at the middle of a wrapper
I have four divs(all same sizes) i have grouped them into to blocks of 2 with classes blocka both contained in an inner container body-content float all the blocks to the left so when my page width changes,these the blocks(of 2) aligned under each other.
I am trying to get now is that those divs sit right at the middle of the main container.

Everything response well. All i need it the class body content sit at the middle of main while blocka all center themselves in the middle of body-content

.main {
  max-width: 100%;
  margin-left: 240px;
  background-color: ;
}

.body-content {
  background-color: white;
  margin: 0 auto;
  width: 95%;
  padding: 15px;
  border: 1px solid grey;
  height: 100px;
}

.blocka {
  float: left;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">

  <div class="body-content">
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
  </div>
</div></code>```

答:
Have you considered flexbox?

body {
  margin: 0;
}

.body-content {
  display: flex;
  min-height: 100vh;
  justify-content: center;
  align-items: center;
}

.blocka {
  display: flex;
  flex-direction: column;
}

.body-content-items {
  min-width: 35vw;
  min-height: 35vh;
  margin: 5px;
  background-color: #f5f5f5;
  padding: 1rem;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="body-content">
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
  </div></code>```

Feel free to set fixed sizes for items (instead of 35vw/35vh). I was just showing you it's possible. Changing their size will keep them centered.

Body:
I have four divs(all same sizes) i have grouped them into to blocks of 2 with classes blocka both contained in an inner container body-content float all the blocks to the left so when my page width changes,these the blocks(of 2) aligned under each other.
I am trying to get now is that those divs sit right at the middle of the main container.

Everything response well. All i need it the class body content sit at the middle of main while blocka all center themselves in the middle of body-content

.main {
  max-width: 100%;
  margin-left: 240px;
  background-color: ;
}

.body-content {
  background-color: white;
  margin: 0 auto;
  width: 95%;
  padding: 15px;
  border: 1px solid grey;
  height: 100px;
}

.blocka {
  float: left;
  margin: 0 auto;
}

Add All

Add All

Add All

Add All

Body:
Have you considered flexbox?

body {
  margin: 0;
}

.body-content {
  display: flex;
  min-height: 100vh;
  justify-content: center;
  align-items: center;
}

.blocka {
  display: flex;
  flex-direction: column;
}

.body-content-items {
  min-width: 35vw;
  min-height: 35vh;
  margin: 5px;
  background-color: #f5f5f5;
  padding: 1rem;
  box-sizing: border-box;
}

<div class="main">
  <div class="body-content">
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
  </div>

Feel free to set fixed sizes for items (instead of 35vw/35vh). I was just showing you it's possible. Changing their size will keep them centered.


问:
Why I do not see all of the folders in Eclipse package Explorer that I see in File Explorer
I created a Maven modul in Eclipse, and there I have a folder called 'target'. That on I see in package explorer in Eclipse. If I open it there are several folder. If I open it in File Explorer on Windows I see even more folder, e.g. one of them called classes/META-INF/services/* which I created using annotations before some classes in the modul. Why I only see those in the Windows File Explorer and not in the Eclipse Package Explorer and how to change that?</p>

答:
This is because you are looking in the "Project Explorer", which understands a project layout, and knows the difference between source files, generated files, project files, resource directories and so on. It doesn't necessarily present you the files in the same tree structure as the they appear in the filesystem.

If you want to see the the actual file layout, you need the "File explorer". Other views can be opened in the "Window -> Show View -> " menu.


问:
How to set axis to start from corner in Matplotlib
this is a graph that I plotted:

```<code># MatPlotlib
import matplotlib.pyplot as plt
# Scientific libraries
import numpy as np

plt.figure(1)

points = np.array([(100, 6.09),
                   (111, 8.42),
                   (119, 10.6),
                   (129, 12.5),
                   (139, 14.9),
                   (149, 17.2),
                   (200, 28.9),
                   (250, 40.9),
                   (299, 52.4),
                   (349, 64.7),
                   (400, 76.9)])

# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'bo', x_new, y_new)

plt.show()
</code>```

I find that all the graphs I plot do not have their axes starting from the corner of the box, could anyone tell me how I can correct this? Aside from setting limits in the graph

答:
By default, matplotlib adds a 5% margin on all sides of the axes.
To get rid of that margin, you can use plt.margins(0).

```<code>import matplotlib.pyplot as plt

plt.plot([1,2,3],[1,2,3], marker="o")
plt.margins(0)
plt.show()
</code>```

To change the margins for the complete script, you may use

```<code>plt.rcParams['axes.xmargin'] = 0
plt.rcParams['axes.ymargin'] = 0
</code>```

Or you may change your rc file to include those settings.

Body:
this is a graph that I plotted:

# MatPlotlib
import matplotlib.pyplot as plt
# Scientific libraries
import numpy as np

plt.figure(1)

points = np.array([(100, 6.09),
                   (111, 8.42),
                   (119, 10.6),
                   (129, 12.5),
                   (139, 14.9),
                   (149, 17.2),
                   (200, 28.9),
                   (250, 40.9),
                   (299, 52.4),
                   (349, 64.7),
                   (400, 76.9)])

# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'bo', x_new, y_new)

plt.show()

I find that all the graphs I plot do not have their axes starting from the corner of the box, could anyone tell me how I can correct this? Aside from setting limits in the graph

Body:
By default, matplotlib adds a 5% margin on all sides of the axes.
To get rid of that margin, you can use plt.margins(0).

import matplotlib.pyplot as plt

plt.plot([1,2,3],[1,2,3], marker="o")
plt.margins(0)
plt.show()

To change the margins for the complete script, you may use

plt.rcParams['axes.xmargin'] = 0
plt.rcParams['axes.ymargin'] = 0

Or you may change your rc file to include those settings.


问:
Highcharts series data array not working
From the servlet I am getting back 3 arrays activeArray,inActiveArray and rejectedArray. I would like to pick these arrays in the java script and come up with a high charts that plots the categories as the blood group names like A+, A- etc.
The series names will be Active, Inactive and rejected.
The series data will have to be the arrays mentioned above.
I was able to achieve only the categories but the series data does not get plotted. I have included the script code below.

```<code><script>
var nameArray ="${nameArray}";

var bloodNames = [
<c:forEach items="${nameArray}" var="name">
    '<c:out value="${name}" />',
</c:forEach>
];

var  activeValue = new Array();
activeValue = [
<c:forEach items="${activeArray}" var="data">
    '<c:out value="${data}" />',
</c:forEach>
];

var seriesData = [
    {
        name: 'Active',
        data:activeValue
    },{
        name:'InActive',
        data:[3, 01, 03,0,0,0]
    },
    {
        name:'Rejected',
        data:[4, 01, 03,0,2,0]
    }
]
$(function () {
var myChart = Highcharts.chart('container', {
chart: {
    type: 'column'
},
title: {
    text: 'Donar Status Report'
},
subtitle: {
    text: 'Blood Name Wise'
},
xAxis: {
    categories:
       bloodNames
    ,
    crosshair: true
},
yAxis: {
    min: 0,
    title: {
        text: 'Person (in Counts)'
    }
},
tooltip: {
    headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
    pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
        '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
    footerFormat: '</table>',
    shared: true,
    useHTML: true
},
plotOptions: {
    column: {
        pointPadding: 0.2,
        borderWidth: 0
    }
},
series: seriesData
});
</code>```

});

答: The quotes around the data in the active is the problem. The column chart expecting an integer as data.</p>


问:
puppet not able to run shell script from master to client
I am new to puppet. I want to run a shell script call crfs.sh located under /myscripts on a RHEL linux puppet master server.

How do I execute this script on a client or target server?

答:
What you want can be solved using the file and the exec modules of puppet. </p>

```<code>class mymodule::myclass {
  file { 'my_bash_script':
    ensure => 'file',
    source => 'puppet:///modules/mymodule/my_bash_script.sh',
    path   => '/usr/local/bin/my_bash_script.sh',
    owner  => 'root'
    group  => 'root'
    mode   => '0744', # Use 0700 if it is sensitive
    notify => Exec['run_my_script'],
  }

  exec { 'run_my_script':
    command     => '/usr/local/bin/my_bash_script.sh',
    refreshonly => true,
  }
}
</code>```

Body:
What you want can be solved using the file and the exec modules of puppet.

class mymodule::myclass {
  file { 'my_bash_script':
    ensure => 'file',
    source => 'puppet:///modules/mymodule/my_bash_script.sh',
    path   => '/usr/local/bin/my_bash_script.sh',
    owner  => 'root'
    group  => 'root'
    mode   => '0744', # Use 0700 if it is sensitive
    notify => Exec['run_my_script'],
  }

  exec { 'run_my_script':
    command     => '/usr/local/bin/my_bash_script.sh',
    refreshonly => true,
  }
}


问:
How to pass options value to a function in react?
How to pass option's value to a function on select ?</p>

```<code>submit = (selectedOption) => {
  console.log('Selected value:',selectedOption);
}

render(){
    return
       <select onChange={this.submit}>
          <option value="Bangalore">Bangalore</option>
          <option value="Delhi">Delhi</option>
          <option value="Mumbai">Mumbai</option>
       </select>
}
</code>```

答:
The callback for onChange receives an event object as parameter. To access the selected value, use event.target.value. E.g.

```<code><select onChange={(event) => this.submit(event.target.value)}>
</code>```

Body:
How to pass option's value to a function on select ?

submit = (selectedOption) => {
  console.log('Selected value:',selectedOption);
}

render(){
    return
       <select onChange={this.submit}>
          <option value="Bangalore">Bangalore</option>
          <option value="Delhi">Delhi</option>
          <option value="Mumbai">Mumbai</option>
       </select>
}

Body:
The callback for onChange receives an event object as parameter. To access the selected value, use event.target.value. E.g.

<select onChange={(event) => this.submit(event.target.value)}>


答:
You don't need to pass the value manually, you can access the selected value by event object: event.target.value

Write it like this:

```<code>submit = (event) => {
  console.log('Selected value:', event.target.value);
}

render(){
   return(
      <select onChange={this.submit}>
         <option value="Bangalore">Bangalore</option>
         <option value="Delhi">Delhi</option>
         <option value="Mumbai">Mumbai</option>
     </select>
   )
}
</code>```

Title: How to pass options value to a function in react?

Body:
You don't need to pass the value manually, you can access the selected value by event object: event.target.value

Write it like this:

submit = (event) => {
  console.log('Selected value:', event.target.value);
}

render(){
   return(
      <select onChange={this.submit}>
         <option value="Bangalore">Bangalore</option>
         <option value="Delhi">Delhi</option>
         <option value="Mumbai">Mumbai</option>
     </select>
   )
}


问:
HTML - Writing HTML codes in textarea
I would like to run HTML codes in textarea but it doesn't work. I get data from databese and I'm printing in a variable but codes It looks like it is, not work. How can I run HTML Codes in textarea? My Codes :

```<code>echo "<div id='ilkyaz'> <textarea class='metin_yazisi' id='yep' onkeypress='silyaz(event);'  readonly> $metin  </textarea> </div>";
</code>```

$metin's contain is  Hello

答:
Use CK editor Jquery Library for that .
Visit http://ckeditor.com/features for details</p>

Title: HTML - Writing HTML codes in textarea

Body:
I would like to run HTML codes in textarea but it doesn't work. I get data from databese and I'm printing in a variable but codes It looks like it is, not work. How can I run HTML Codes in textarea? My Codes :

echo "
 <textarea class='metin_yazisi' id='yep' onkeypress='silyaz(event);'  readonly> $metin  </textarea>
";

$metin's contain is  Hello


答:
I think your JSON structure is incorrect, GSON is expecting something like:

```<code>{
  "person": {
      // Person object
  },
  "relatives": [ // Mind the plural!
      {
           //Relative object
      },
      {
           //another Relative object
      }
  ]
}
</code>```

Rationale: In general any JSON library will examine your beans looking for  public setters. If you have a setter like setPerson(Person p), then it will remove the "set" prefix and then will switch the case of the next letter ("P" becomes "p"), so it will try to create a Person object and then insert it in a person attribute.

But then again I think there is something else wrong: that error complains that you have a JSON string like: "{....},{....}", so you have 2 or more top level (aka root) objects, which is not allowed in the JSON standard notation.

Title: JSON only allows one top level value?

Body:
I think your JSON structure is incorrect, GSON is expecting something like:

{
  "person": {
      // Person object
  },
  "relatives": [ // Mind the plural!
      {
           //Relative object
      },
      {
           //another Relative object
      }
  ]
}

Rationale: In general any JSON library will examine your beans looking for  public setters. If you have a setter like setPerson(Person p), then it will remove the "set" prefix and then will switch the case of the next letter ("P" becomes "p"), so it will try to create a Person object and then insert it in a person attribute.

But then again I think there is something else wrong: that error complains that you have a JSON string like: "{....},{....}", so you have 2 or more top level (aka root) objects, which is not allowed in the JSON standard notation.


问:
Can the X++ language be used for the following development?
I'm interested in developing primarily games and websites. Is X++ a suitable language for this?</p>

答:
In terms of your "Can it be used?" title, possibly, but it seems to be targeted to business oriented applications:

X++ is an object-oriented language with similarities to C#. X++ is part of the MorphX development platform that you use to construct accounting and business management systems. (a)

That means, in terms of your "Is it suitable?" in the body of your question, almost certainly not.

In the sense that you could also write accounting applications in BCPL, or web servers in COBOL-85, then yes, it's probably doable. Whether it's a good idea, that's a different matter.

(a) See http://msdn.microsoft.com/en-us/library/aa867122.aspx.

ContentLicense: CC BY-SA 4.0


问:
Passing an array between pages in ionic 2
I'm new in Ionic 2 and I'm having troubles with passing data between pages. In my Home.ts file  I have a global array that contains some numbers I calculated and i want to pass it to my Table.ts file, to show it in a HTML table with the *ngFor method.

this is the Function in Home.ts where i fill the array and try to push (i will skip the calculations, becacause i know they are correct).

```<code>`import { Component } from '@angular/core';
 import { AlertController } from 'ionic-angular';
 import { IonicPage,NavController, NavParams} from 'ionic-angular';
 import {Table} from '../table/table';

 export class HomePage {

 averagesList: Array <number> =[];

 constructor(public alerCtrl: AlertController,
             public navCtrl: NavController,
             public navParams: NavParams)
             {}

 Calculate(){

 var Averages=[];

 //Calculations on the 'Averages' Array

 this.averagesList = Averages;

this.navCtrl.push(Table,this.averagesList);
 }

}
</code>```

So I try to print it in my Table.ts file but it gives me undefined result

```<code>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {HomePage} from '../home/home';
@IonicPage()
@Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class Table{

constructor(public navCtrl: NavController, public navParams: NavParams) {

}

ionViewDidLoad() {

console.log(this.navParams.get('averagesList'));
}
}
</code>```

I've tried to pass a let variable and it worked, so why doesn't it work with arrays?

答:
you can use services to do so. Just like in angular2 you can import your service within the constructor and use the property like this.</p>

```<code>import {OnInit} from '@angular/core';
import {someService} from ./somepath;
 ...
 export class someClass implements OnInit{
let myTmpVar; //we will capture the shared data in this variable
constructor (private smService: someService){ ... }
ngOnInit{
   this.myTmpVar = this.smService.SharedServiceData;
}
...
}
</code>```

Body:
I'm new in Ionic 2 and I'm having troubles with passing data between pages. In my Home.ts file  I have a global array that contains some numbers I calculated and i want to pass it to my Table.ts file, to show it in a HTML table with the *ngFor method.

this is the Function in Home.ts where i fill the array and try to push (i will skip the calculations, becacause i know they are correct).

`import { Component } from '@angular/core';
 import { AlertController } from 'ionic-angular';
 import { IonicPage,NavController, NavParams} from 'ionic-angular';
 import {Table} from '../table/table';

 export class HomePage {

 averagesList: Array <number> =[];

 constructor(public alerCtrl: AlertController,
             public navCtrl: NavController,
             public navParams: NavParams)
             {}

 Calculate(){

 var Averages=[];

 //Calculations on the 'Averages' Array

 this.averagesList = Averages;

this.navCtrl.push(Table,this.averagesList);
 }

}

So I try to print it in my Table.ts file but it gives me undefined result

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {HomePage} from '../home/home';
@IonicPage()
@Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class Table{

constructor(public navCtrl: NavController, public navParams: NavParams) {

}

ionViewDidLoad() {

console.log(this.navParams.get('averagesList'));
}
}

I've tried to pass a let variable and it worked, so why doesn't it work with arrays?

Body:
you can use services to do so. Just like in angular2 you can import your service within the constructor and use the property like this.

import {OnInit} from '@angular/core';
import {someService} from ./somepath;
 ...
 export class someClass implements OnInit{
let myTmpVar; //we will capture the shared data in this variable
constructor (private smService: someService){ ... }
ngOnInit{
   this.myTmpVar = this.smService.SharedServiceData;
}
...
}


答:
You could make use of htmlentities

e.g.

```<code>echo "<div id='ilkyaz'> <textarea class='metin_yazisi' id='yep' onkeypress='silyaz(event);'  readonly>".htmlentities($metin)."</textarea> </div>";
</code>```

Title: HTML - Writing HTML codes in textarea

Body:
You could make use of htmlentities

e.g.

echo "<div id='ilkyaz'> <textarea class='metin_yazisi' id='yep' onkeypress='silyaz(event);'  readonly>".htmlentities($metin)."</textarea> </div>";


问:
A last part in query is not working
I have some code, but $query_last is not working, previous  identica part $query  -without problems.

I Don't understand what the problem is.

```<code><?php
    if ($_SERVER["REQUEST_METHOD"]=="POST"){
        require 'connect_k.php';
        createMessage();
    }

    function createMessage(){
        global $connect;
        $email = $_POST["email"];
        $price_main = $_POST["price_main"];
        $date = $_POST["date"];
        $order_number = $_POST["order_number"];
        $query="INSERT INTO final(email,name,size,quantity,price)SELECT email,name,size,quantity,price FROM items_cart WHERE email like ('$email');";
        $query_del="DELETE FROM items_cart WHERE email like ('$email');";
        $query_upd="UPDATE final SET price_main='$price_main',order_number='$order_number',date='$date' WHERE email like ('$email');";
----problem is here----
        $query_last="INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date)SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
        mysqli_query ($connect,$query)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_del)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_upd)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_last)or die (mysqli_error($connect));
        mysqli_close($connect);
    }
?>
</code>```

答:
```<code>"INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date)SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
</code>```

Syntax error due to using a reserved word as a table or column name in MySQL

order is a reserved keyword, and needs to be backticked or renamed.

Title: A last part in query is not working

Body:
I have some code, but $query_last is not working, previous  identica part $query  -without problems.

I Don't understand what the problem is.

<?php
    if ($_SERVER["REQUEST_METHOD"]=="POST"){
        require 'connect_k.php';
        createMessage();
    }

    function createMessage(){
        global $connect;
        $email = $_POST["email"];
        $price_main = $_POST["price_main"];
        $date = $_POST["date"];
        $order_number = $_POST["order_number"];
        $query="INSERT INTO final(email,name,size,quantity,price)SELECT email,name,size,quantity,price FROM items_cart WHERE email like ('$email');";
        $query_del="DELETE FROM items_cart WHERE email like ('$email');";
        $query_upd="UPDATE final SET price_main='$price_main',order_number='$order_number',date='$date' WHERE email like ('$email');";
----problem is here----
        $query_last="INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date)SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
        mysqli_query ($connect,$query)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_del)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_upd)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_last)or die (mysqli_error($connect));
        mysqli_close($connect);
    }
?>

Body:
"INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date)SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";

Syntax error due to using a reserved word as a table or column name in MySQL

order is a reserved keyword, and needs to be backticked or renamed.


问:
SSIS error: delimiter for column "columnX" is not found
This question was asked here before but the solutions proposed don't seem to be working for me.

I'm trying to import a text file pipe delimited text qualifier ". The SSIS package is returning the error message

delimiter for column "columnX" is not found

where column X is the last field in the file.

In the connection manager advanced tab, I have set up the column delimiter for columnX to {LF} while all the other fields are set to vertical |.

I have verified the file and there are no missing fields. There are some null values but all the fields are there.

I can't point out what is causing this. Your help would be greatly appreciated.

答:
I suggest to delete the flat file connection manager, and recreate it so it will automatically set all options. Just select the column delimiter to |

If it doesn't works you have to verify that flat file does not contains bad rows.

Check these solutions they may helps:

SSIS ragged file not recognized CRLF

SSIS reading LF as terminator when its set as CRLF

Import CSV File Error : Column Value containing column delimiter

Or if you have installed sql server try importibg this fla file to an sql server table using import and export wizard and check the data after importing it may helps detecting the lines containning errors.


问:
[Django rest framework]: Serialize a list of strings
I am working with django and djando rest framework

I have created a new endpoint installedapps. When making GET requests to it, I want to return the data contained as a list of strings (list of installed apps)

The list of strings looks something like this:

installed_apps = ['django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_js_reverse', 'djcelery', 'bootstrap3', 'foo', 'bar', 'apirest']
```

<p>Until now I have only worked with model serializers, and everything was pretty easy. But now i dont know how to return this list of strings</p>

<p>This is what I have tried so far:</p>

<pre class="lang-python prettyprint-override"><code>class InstalledAppsViewSet(viewsets.ViewSet):
    serializer_class = serializers.InstalledAppsSerializer

    def list(self, request):
        from credits.views import GetInstalledApps

        installed_apps = GetInstalledApps.get_installed_apps()

        serializer = serializers.InstalledAppsSerializer(
            instance=installed_apps, many=True)

        return Response(serializer.data)

class InstalledAppsSerializer(serializers.ListField):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps_field = serializers.SerializerMethodField(
        'get_installed_apps')
</code>```

I am always getting all kind of errors. Any help on how to return the content of the list of strings?

Update

I have tried @e4c5 code, leaving it like this:

class InstalledAppsViewSet(viewsets.ViewSet):
    serializer_class = serializers.InstalledAppsSerializer

    def list(self, request):

        serializer = serializers.InstalledAppsSerializer

class InstalledAppsSerializer(serializers.Serializer):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps = serializers.SerializerMethodField('get_the_installed_apps')

    def get_the_installed_apps(self):
        from credits.views import GetInstalledApps
        installed_apps = GetInstalledApps.get_installed_apps()

        return installed_apps
```

And I'm still getting errors. But I don't get the error message anywhere. Any help?

答:
The 'all kinds of errors' would probably go away if you based your serializer on a serializer, rather than a serializer field

ListField

A field class that validates a list of objects.

You might want to use it when one of the members of your class is a list. But you don't want to ListField as a serializer, because it isn't one

```<code>class InstalledAppsSerializer(serializers.Serializer):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps_field = serializers.SerializerMethodField(
        'get_installed_apps')
</code>```

Body:
I am working with django and djando rest framework

I have created a new endpoint installedapps. When making GET requests to it, I want to return the data contained as a list of strings (list of installed apps)

The list of strings looks something like this:

installed_apps = ['django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_js_reverse', 'djcelery', 'bootstrap3', 'foo', 'bar', 'apirest']

Until now I have only worked with model serializers, and everything was pretty easy. But now i dont know how to return this list of strings

This is what I have tried so far:

class InstalledAppsViewSet(viewsets.ViewSet):
    serializer_class = serializers.InstalledAppsSerializer

    def list(self, request):
        from credits.views import GetInstalledApps

        installed_apps = GetInstalledApps.get_installed_apps()

        serializer = serializers.InstalledAppsSerializer(
            instance=installed_apps, many=True)

        return Response(serializer.data)

class InstalledAppsSerializer(serializers.ListField):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps_field = serializers.SerializerMethodField(
        'get_installed_apps')

I am always getting all kind of errors. Any help on how to return the content of the list of strings?

Update

I have tried @e4c5 code, leaving it like this:

class InstalledAppsViewSet(viewsets.ViewSet):
    serializer_class = serializers.InstalledAppsSerializer

    def list(self, request):

        serializer = serializers.InstalledAppsSerializer

class InstalledAppsSerializer(serializers.Serializer):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps = serializers.SerializerMethodField('get_the_installed_apps')

    def get_the_installed_apps(self):
        from credits.views import GetInstalledApps
        installed_apps = GetInstalledApps.get_installed_apps()

        return installed_apps

And I'm still getting errors. But I don't get the error message anywhere. Any help?

Body:
The 'all kinds of errors' would probably go away if you based your serializer on a serializer, rather than a serializer field

ListField

A field class that validates a list of objects.

You might want to use it when one of the members of your class is a list. But you don't want to ListField as a serializer, because it isn't one

class InstalledAppsSerializer(serializers.Serializer):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps_field = serializers.SerializerMethodField(
        'get_installed_apps')


问:
Calculates b/w two row
Can any one Help me Please I want to Calculate 2 or more row Record see Below Query.

```<code>SELECT docs_DocCode, SUM(invd_Qty) AS Total_IN
FROM   dbo.SI_InventoryDetail

WHERE  (docs_DocCode = 'D.C') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'STO') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SAO') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'IOB') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'GRN') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'STI') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SAI') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SRN') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'PRN') AND (itm_ItemCode = '0101050000083')
GROUP BY docs_DocCode
</code>```

ABove Query Give me Result as below

```<code>dics_doccode   Total
D.C            328.00000000
GRN            205.00000000
IOB             96.00000000
SAI             66.00000000
SAO             51.00000000
SRN             14.00000000
STI            150.00000000
STO            150.00000000
</code>```

Now i want To ADD (D.C+STI+SAI) - (GRN+STI+SAI+IOB) = One Value

And i am using SQL SERVER 2000

Thankx

答:
I resolved My problem thankx to  "Zerkms" Below is My Query and It Result

SELECT Itm_itemcode,

```<code>    SUM(CASE WHEN docs_DocCode IN ('D.C', 'STO', 'SAO','PRN') THEN INVD_QTY END ) -
    SUM(CASE WHEN docs_DocCode IN ('GRN', 'STI', 'SAI','SRN','IOB') THEN invd_Qty END) AS Qty
</code>```

From SI_InventoryDetail

Where Itm_itemcode = '0101050000083'

group by Itm_itemcode

Result

Item_code           Qty

0101050000083   -2.00000000

Thankx
Brave ali khatri

Title: Calculates b/w two row

Body:
Can any one Help me Please I want to Calculate 2 or more row Record see Below Query.

SELECT docs_DocCode, SUM(invd_Qty) AS Total_IN
FROM   dbo.SI_InventoryDetail

WHERE  (docs_DocCode = 'D.C') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'STO') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SAO') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'IOB') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'GRN') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'STI') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SAI') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SRN') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'PRN') AND (itm_ItemCode = '0101050000083')
GROUP BY docs_DocCode

ABove Query Give me Result as below

dics_doccode   Total
D.C            328.00000000
GRN            205.00000000
IOB             96.00000000
SAI             66.00000000
SAO             51.00000000
SRN             14.00000000
STI            150.00000000
STO            150.00000000

Now i want To ADD (D.C+STI+SAI) - (GRN+STI+SAI+IOB) = One Value

And i am using SQL SERVER 2000

Thankx

Body:
I resolved My problem thankx to  "Zerkms" Below is My Query and It Result

SELECT Itm_itemcode,

    SUM(CASE WHEN docs_DocCode IN ('D.C', 'STO', 'SAO','PRN') THEN INVD_QTY END ) -
    SUM(CASE WHEN docs_DocCode IN ('GRN', 'STI', 'SAI','SRN','IOB') THEN invd_Qty END) AS Qty

From SI_InventoryDetail

Where Itm_itemcode = '0101050000083'

group by Itm_itemcode

Result

Item_code           Qty

0101050000083   -2.00000000

Thankx
Brave ali khatri


问:
Upload Block Blob to Azure Storage via SDK - Server failed to authenticate the request
From my ASP.Net Core app, I try to upload a block blob to Azure Storage Service.
I took the example from Microsoft:

```<code>    var accountName = "accountname";
    var accountKey = "key";
    //var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("myconnectionstring");

    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference(Container);

    // Retrieve reference to a blob named "test".
    CloudBlockBlob blockBlob = container.GetBlockBlobReference("test");

    // Create or overwrite the "test" blob with contents from a local file.
    using (var fileStream = System.IO.File.OpenRead(@"E:\Drone\N_01004619000008.jpg"))
    {
        await blockBlob.UploadFromStreamAsync(fileStream);
    }
</code>```

This results in the following error:

StorageException: Server failed to authenticate the request. Make sure
  the value of Authorization header is formed correctly including the
  signature.

Using fiddler I could also see this additional error info:

The MAC signature found in the HTTP request 'blankedOutKey' is not the
  same as any computed signature. Server used following string to sign:
  'PUT'

...whereas the 'blankedOutKey' is not the key I actually used for authentication. Not sure where it comes from.
As you can see in my Code Snippet, I tried both using my accountName and accountKey as well as the ConnectionString.

What am I doing wrong?

Edit:
I tried this here:
https://github.com/Azure-Samples/storage-dotnet-sas-getting-started

With the exact same connection string, it worked in the solution from github but when I took over the complete code to my ASP.Net Core 1.1 app, I again faced the issue mentioned. So I double checked the differences. It turns out that the project from github uses the 6.2.0 version of "Microsoft.WindowsAzure.Storage" while my ASP.Net Core app uses the 8.1.3 version.

Furthermore, I double checked the HTTP requests from both solutions in fiddler.
Here is the one from the older SDK which works:

User-Agent: WA-Storage/6.2.0 (.NET CLR 4.0.30319.42000; Win32NT
  6.2.9200.0) x-ms-version: 2015-04-05 x-ms-client-request-id: c1aea889-73f8-4b6b-9a1f-2f2f9e021846 x-ms-date: Sun, 04 Jun 2017
  12:23:37 GMT Authorization: SharedKey
  mystoragename:F5yhOOh2taUBfUE+3wii1cYb0D7L+jZGVfs1xTgTme0=
  Host: mystoragename.blob.core.windows.net Content-Length: 0

The request submitted through the newer SDK which fails:

Connection: Keep-Alive Authorization: SharedKey
  mystoragenamee:IxtXuZFIcPjeKnqjktxvfcQMRLkfHM5SVN9zvQZmBJc=
  User-Agent: Azure-Storage/8.1.3 (.NET Core) x-ms-client-request-id:
  d890d2e0-07af-4695-af1f-8020c9476774 x-ms-version: 2016-05-31
  x-ms-date: Sun, 04 Jun 2017 12:24:49 GMT x-ms-request-root-id:
  428e8e6279f1ff9d-4237b4f7 x-ms-request-id:
  |428e8e6279f1ff9d-4237b4f7.1. Request-Id:
  |428e8e6279f1ff9d-4237b4f7.1. Content-Length: 0 Host:
  mystoragename.blob.core.windows.net

答:
Thanks to @Tom Sun - MSFT I have been sent to the right direction.
I now compared all dependencies between the new ASP.Net Core app which I started from scratch and my actual solution.

The problem was the following package:

Microsoft.ApplicationInsights.AspNetCore

If I used the 2.1.0-beta I was faced with the error.
Switching to the last stable 2.0.0 solved my problem

Body:
From my ASP.Net Core app, I try to upload a block blob to Azure Storage Service.
I took the example from Microsoft:

    var accountName = "accountname";
    var accountKey = "key";
    //var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("myconnectionstring");

    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference(Container);

    // Retrieve reference to a blob named "test".
    CloudBlockBlob blockBlob = container.GetBlockBlobReference("test");

    // Create or overwrite the "test" blob with contents from a local file.
    using (var fileStream = System.IO.File.OpenRead(@"E:\Drone\N_01004619000008.jpg"))
    {
        await blockBlob.UploadFromStreamAsync(fileStream);
    }

This results in the following error:

StorageException: Server failed to authenticate the request. Make sure
  the value of Authorization header is formed correctly including the
  signature.

Using fiddler I could also see this additional error info:

The MAC signature found in the HTTP request 'blankedOutKey' is not the
  same as any computed signature. Server used following string to sign:
  'PUT'

...whereas the 'blankedOutKey' is not the key I actually used for authentication. Not sure where it comes from.
As you can see in my Code Snippet, I tried both using my accountName and accountKey as well as the ConnectionString.

What am I doing wrong?

Edit:
I tried this here:
https://github.com/Azure-Samples/storage-dotnet-sas-getting-started

With the exact same connection string, it worked in the solution from github but when I took over the complete code to my ASP.Net Core 1.1 app, I again faced the issue mentioned. So I double checked the differences. It turns out that the project from github uses the 6.2.0 version of "Microsoft.WindowsAzure.Storage" while my ASP.Net Core app uses the 8.1.3 version.

Furthermore, I double checked the HTTP requests from both solutions in fiddler.
Here is the one from the older SDK which works:

User-Agent: WA-Storage/6.2.0 (.NET CLR 4.0.30319.42000; Win32NT
  6.2.9200.0) x-ms-version: 2015-04-05 x-ms-client-request-id: c1aea889-73f8-4b6b-9a1f-2f2f9e021846 x-ms-date: Sun, 04 Jun 2017
  12:23:37 GMT Authorization: SharedKey
  mystoragename:F5yhOOh2taUBfUE+3wii1cYb0D7L+jZGVfs1xTgTme0=
  Host: mystoragename.blob.core.windows.net Content-Length: 0

The request submitted through the newer SDK which fails:

Connection: Keep-Alive Authorization: SharedKey
  mystoragenamee:IxtXuZFIcPjeKnqjktxvfcQMRLkfHM5SVN9zvQZmBJc=
  User-Agent: Azure-Storage/8.1.3 (.NET Core) x-ms-client-request-id:
  d890d2e0-07af-4695-af1f-8020c9476774 x-ms-version: 2016-05-31
  x-ms-date: Sun, 04 Jun 2017 12:24:49 GMT x-ms-request-root-id:
  428e8e6279f1ff9d-4237b4f7 x-ms-request-id:
  |428e8e6279f1ff9d-4237b4f7.1. Request-Id:
  |428e8e6279f1ff9d-4237b4f7.1. Content-Length: 0 Host:
  mystoragename.blob.core.windows.net


问:
Link within label in Swift
I would like to do that in my app :

The label is like : username comment

I don't know how to add the "button" within the label; I found this library but I'm not sure it will work? https://github.com/optonaut/ActiveLabel.swift

Maybe use it by creating a regex for the first word? What do you think?

答:
You can use TTTAttributedLabel to make a particular part or word tappable in a UILabel.

For example

```<code>label.text = @"Fork me on GitHub! (https://github.com/mattt/TTTAttributedLabel/)"; // Repository URL will be automatically detected and linked
NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range];
</code>```

In addition to hyperlinks you can add custom links also to a particular part or word and that word becomes tappable and on tapping that word delegate method didSelectLinkWithURL gets called and you can check for that link inside that function

```<code>(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    NSLog(@"link %@", [url absoluteString]);
    NSLog(@"whole label %@", label);
}
</code>```

Title: Link within label in Swift

Body:
You can use TTTAttributedLabel to make a particular part or word tappable in a UILabel.

For example

label.text = @"Fork me on GitHub! (https://github.com/mattt/TTTAttributedLabel/)"; // Repository URL will be automatically detected and linked
NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range];

In addition to hyperlinks you can add custom links also to a particular part or word and that word becomes tappable and on tapping that word delegate method didSelectLinkWithURL gets called and you can check for that link inside that function

(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    NSLog(@"link %@", [url absoluteString]);
    NSLog(@"whole label %@", label);
}


问:
SVG line animation with anime.js
I'm modifying a pen to create an SVG animation. I would like the green element to exactly follow the line path but it is not. Also it is not looping the 8 path correctly in one line but bounceing at the crossroad of the loop. Any advice how to achieve this would be appreciated since I haven't been able to find a solution

```<code>var path = anime.path('path');

anime({
  targets: 'div',
  translateX: path,
  translateY: path,
  rotate: path,
  duration: 6000,
  loop: true,
  easing: 'linear'
});
</code>```

Here's the codepen: https://codepen.io/anon/pen/VWYKwB

答:
A few days ago I told you that your path has a problem.
You have to rebuild your path ...

  <!doctype html>

    <meta charset="UTF-8">
    <title>Document</title>

    <button onclick="dashAni(myPath, 50, 3500)">start</button>
    <svg id="mySVG"  width="200" height="200" viewBox="0 0 500 500">
        <path id="myPath" d="M 50,250 c 0 -100   150 -100   200 0
                                      c 50 100   200 100   200 0
                                      c -0 -100   -150 -100   -200 0
                                      c -50 100   -200 100   -200 0
                                      z"
        stroke="#eee"
        stroke-width="5" fill="none" />
    </svg>

  ```

Title: SVG line animation with anime.js

Body:
I'm modifying a pen to create an SVG animation. I would like the green element to exactly follow the line path but it is not. Also it is not looping the 8 path correctly in one line but bounceing at the crossroad of the loop. Any advice how to achieve this would be appreciated since I haven't been able to find a solution

var path = anime.path('path');

anime({
  targets: 'div',
  translateX: path,
  translateY: path,
  rotate: path,
  duration: 6000,
  loop: true,
  easing: 'linear'
});

Here's the codepen: https://codepen.io/anon/pen/VWYKwB

Body:
A few days ago I told you that your path has a problem.
You have to rebuild your path ...

  <!doctype html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>
  <body>
    <button onclick="dashAni(myPath, 50, 3500)">start</button>
    <svg id="mySVG"  width="200" height="200" viewBox="0 0 500 500">
        <path id="myPath" d="M 50,250 c 0 -100   150 -100   200 0
                                      c 50 100   200 100   200 0
                                      c -0 -100   -150 -100   -200 0
                                      c -50 100   -200 100   -200 0
                                      z"
        stroke="#eee"
        stroke-width="5" fill="none" />
    </svg>
    <script>
      var dashAni = function(path, length, duration){
        var dashPath = path.cloneNode(true);
        mySVG.appendChild(dashPath);
        var pathLen=path.getTotalLength();
        var aktPos=0
        var sumSteps = duration / (1000/60) // 60 pics per second
        var step=0;
        var pathAnim;
        dashPath.setAttribute('stroke-dasharray', length + ' ' + (pathLen - length));
        dashPath.setAttribute('stroke', "red");
        dashPath.setAttribute('stroke-dashoffset', aktPos);

        var anim=function(){
           aktPos = pathLen/sumSteps*step*-1;
            //aktLen = easeInOutQuad(step/sumSteps)*len;
           dashPath.setAttribute('stroke-dasharray', length + ' ' + pathLen);
           dashPath.setAttribute('stroke-dashoffset', aktPos);

           if (step <= (sumSteps)){
            step++;
            pathAnim = setTimeout(anim, 1000/60) //1000/60 pics/second
            } else {
              mySVG.removeChild(dashPath);
              clearTimeout(pathAnim);
            }
        }
       anim();
      }
    </script>
  </body>
  </html>


答:
You could use the serializers.ListField,

ListField is a field class that validates a list of objects.

The ListField class also supports a declarative style that allows you to write reusable list field classes.

You could write a custom field for serializer inheriting from ListField form the drf serializers which accepts list of strings. Maybe like this, this example is already shown in the DRF docs.

```<code>class StringListField(serializers.ListField):
    child = serializers.CharField()
</code>```

We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it.

These are from the docs, I haven't tried it yet. But hope you get what you looking for.

You could use the custom field in your serializer like,

```<code>class InstalledAppsSerializer(serializers.Serializer):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps_field = StringListField()
</code>```

Title: [Django rest framework]: Serialize a list of strings

Body:
You could use the serializers.ListField,

ListField is a field class that validates a list of objects.

The ListField class also supports a declarative style that allows you to write reusable list field classes.

You could write a custom field for serializer inheriting from ListField form the drf serializers which accepts list of strings. Maybe like this, this example is already shown in the DRF docs.

class StringListField(serializers.ListField):
    child = serializers.CharField()

We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it.

These are from the docs, I haven't tried it yet. But hope you get what you looking for.

You could use the custom field in your serializer like,

class InstalledAppsSerializer(serializers.Serializer):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps_field = StringListField()


问:
Decision Trees with SKlearn and Visualization
working on the Kaggle Titanic data set. I'm trying to understand decision trees better, I've worked with linear regressions a good bit but never decision trees. I'm trying to create a visualization in python for my tree. Something isn't working though. Check my code below.

```<code>import pandas as pd
from sklearn import tree
from sklearn.datasets import load_iris
import numpy as np

train_file='.......\RUN.csv'
train=pd.read_csv(train_file)

#impute number values and missing values
train["Sex"][train["Sex"] == "male"] = 0
train["Sex"][train["Sex"] == "female"] = 1
train["Embarked"] = train["Embarked"].fillna("S")
train["Embarked"][train["Embarked"] == "S"]= 0
train["Embarked"][train["Embarked"] == "C"]= 1
train["Embarked"][train["Embarked"] == "Q"]= 2
train["Age"] = train["Age"].fillna(train["Age"].median())
train["Pclass"] = train["Pclass"].fillna(train["Pclass"].median())
train["Fare"] = train["Fare"].fillna(train["Fare"].median())

target = train["Survived"].values
features_one = train[["Pclass", "Sex", "Age", "Fare","SibSp","Parch","Embarked"]].values

# Fit your first decision tree: my_tree_one
my_tree_one = tree.DecisionTreeClassifier(max_depth = 10, min_samples_split = 5, random_state = 1)

iris=load_iris()

my_tree_one = my_tree_one.fit(features_one, target)

tree.export_graphviz(my_tree_one, out_file='tree.dot')
</code>```

How do I actually see the decision tree? Trying to visualize it.

Help appreciated!

答:
I made a visualization using bar plots. The first plot indicates the distribution of the classes. The first title represents the first split criterium. All data satisfying this criterium result in the left underlying subplot. If not, the right plot is the result. Thus, all titles indicate the split criterium for the next split.

The percentages are the values from the initial distribution. Therefore, by looking at the precentages one can easily obtain how much from the inititial amount of data is left after a few splits.

Note, if you set max_depth high that this will entail a lot of subplot (max_depth, 2^depth)

Tree visualization using bar plots

Code:

```<code>def give_nodes(nodes,amount_of_branches,left,right):
    amount_of_branches*=2
    nodes_splits=[]
    for node in nodes:
        nodes_splits.append(left[node])
        nodes_splits.append(right[node])
    return (nodes_splits,amount_of_branches)

def plot_tree(tree, feature_names):
    from matplotlib import gridspec
    import matplotlib.pyplot as plt
    from matplotlib import rc
    import pylab

    color = plt.cm.coolwarm(np.linspace(1,0,len(feature_names)))

    plt.rc('text', usetex=True)
    plt.rc('font', family='sans-serif')
    plt.rc('font', size=14)

    params = {'legend.fontsize': 20,
             'axes.labelsize': 20,
             'axes.titlesize':25,
             'xtick.labelsize':20,
             'ytick.labelsize':20}
    plt.rcParams.update(params)

    max_depth=tree.max_depth
    left      = tree.tree_.children_left
    right     = tree.tree_.children_right
    threshold = tree.tree_.threshold
    features  = [feature_names[i] for i in tree.tree_.feature]
    value = tree.tree_.value

    fig = plt.figure(figsize=(3*2**max_depth,2*2**max_depth))
    gs = gridspec.GridSpec(max_depth, 2**max_depth)
    plt.subplots_adjust(hspace = 0.6, wspace=0.8)

    # All data
    amount_of_branches=1
    nodes=[0]
    normalize=np.sum(value[0][0])

    for i,node in enumerate(nodes):
        ax=fig.add_subplot(gs[0,(2**max_depth*i)/amount_of_branches:(2**max_depth*(i+1))/amount_of_branches])
        ax.set_title( features[node]+"$<= "+str(threshold[node])+"$")
        if( i==0): ax.set_ylabel(r'$\%$')
        ind=np.arange(1,len(value[node][0])+1,1)
        width=0.2
        bars= (np.array(value[node][0])/normalize)*100
        plt.bar(ind-width/2, bars, width,color=color,alpha=1,linewidth=0)
        plt.xticks(ind, [int(i) for i in ind-1])
        pylab.ticklabel_format(axis='y',style='sci',scilimits=(0,2))

    # Splits
    for j in range(1,max_depth):
        nodes,amount_of_branches=give_nodes(nodes,amount_of_branches,left,right)
        for i,node in enumerate(nodes):
            ax=fig.add_subplot(gs[j,(2**max_depth*i)/amount_of_branches:(2**max_depth*(i+1))/amount_of_branches])
            ax.set_title( features[node]+"$<= "+str(threshold[node])+"$")
            if( i==0): ax.set_ylabel(r'$\%$')
            ind=np.arange(1,len(value[node][0])+1,1)
            width=0.2
            bars= (np.array(value[node][0])/normalize)*100
            plt.bar(ind-width/2, bars, width,color=color,alpha=1,linewidth=0)
            plt.xticks(ind, [int(i) for i in ind-1])
            pylab.ticklabel_format(axis='y',style='sci',scilimits=(0,2))

    plt.tight_layout()
    return fig
</code>```

Example:

```<code>X=[]
Y=[]
amount_of_labels=5
feature_names=[ '$x_1$','$x_2$','$x_3$','$x_4$','$x_5$']
for i in range(200):
    X.append([np.random.normal(),np.random.randint(0,100),np.random.uniform(200,500) ])
    Y.append(np.random.randint(0,amount_of_labels))

clf = tree.DecisionTreeClassifier(criterion='entropy',max_depth=4)
clf = clf.fit(X,Y )
fig=plot_tree(clf, feature_names)
</code>```

Body:
working on the Kaggle Titanic data set. I'm trying to understand decision trees better, I've worked with linear regressions a good bit but never decision trees. I'm trying to create a visualization in python for my tree. Something isn't working though. Check my code below.

import pandas as pd
from sklearn import tree
from sklearn.datasets import load_iris
import numpy as np

train_file='.......\RUN.csv'
train=pd.read_csv(train_file)

#impute number values and missing values
train["Sex"][train["Sex"] == "male"] = 0
train["Sex"][train["Sex"] == "female"] = 1
train["Embarked"] = train["Embarked"].fillna("S")
train["Embarked"][train["Embarked"] == "S"]= 0
train["Embarked"][train["Embarked"] == "C"]= 1
train["Embarked"][train["Embarked"] == "Q"]= 2
train["Age"] = train["Age"].fillna(train["Age"].median())
train["Pclass"] = train["Pclass"].fillna(train["Pclass"].median())
train["Fare"] = train["Fare"].fillna(train["Fare"].median())

target = train["Survived"].values
features_one = train[["Pclass", "Sex", "Age", "Fare","SibSp","Parch","Embarked"]].values

# Fit your first decision tree: my_tree_one
my_tree_one = tree.DecisionTreeClassifier(max_depth = 10, min_samples_split = 5, random_state = 1)

iris=load_iris()

my_tree_one = my_tree_one.fit(features_one, target)

tree.export_graphviz(my_tree_one, out_file='tree.dot')

How do I actually see the decision tree? Trying to visualize it.

Help appreciated!

Body:
I made a visualization using bar plots. The first plot indicates the distribution of the classes. The first title represents the first split criterium. All data satisfying this criterium result in the left underlying subplot. If not, the right plot is the result. Thus, all titles indicate the split criterium for the next split.

The percentages are the values from the initial distribution. Therefore, by looking at the precentages one can easily obtain how much from the inititial amount of data is left after a few splits.

Note, if you set max_depth high that this will entail a lot of subplot (max_depth, 2^depth)

Tree visualization using bar plots

Code:

def give_nodes(nodes,amount_of_branches,left,right):
    amount_of_branches*=2
    nodes_splits=[]
    for node in nodes:
        nodes_splits.append(left[node])
        nodes_splits.append(right[node])
    return (nodes_splits,amount_of_branches)

def plot_tree(tree, feature_names):
    from matplotlib import gridspec
    import matplotlib.pyplot as plt
    from matplotlib import rc
    import pylab

    color = plt.cm.coolwarm(np.linspace(1,0,len(feature_names)))

    plt.rc('text', usetex=True)
    plt.rc('font', family='sans-serif')
    plt.rc('font', size=14)

    params = {'legend.fontsize': 20,
             'axes.labelsize': 20,
             'axes.titlesize':25,
             'xtick.labelsize':20,
             'ytick.labelsize':20}
    plt.rcParams.update(params)

    max_depth=tree.max_depth
    left      = tree.tree_.children_left
    right     = tree.tree_.children_right
    threshold = tree.tree_.threshold
    features  = [feature_names[i] for i in tree.tree_.feature]
    value = tree.tree_.value

    fig = plt.figure(figsize=(3*2**max_depth,2*2**max_depth))
    gs = gridspec.GridSpec(max_depth, 2**max_depth)
    plt.subplots_adjust(hspace = 0.6, wspace=0.8)

    # All data
    amount_of_branches=1
    nodes=[0]
    normalize=np.sum(value[0][0])

    for i,node in enumerate(nodes):
        ax=fig.add_subplot(gs[0,(2**max_depth*i)/amount_of_branches:(2**max_depth*(i+1))/amount_of_branches])
        ax.set_title( features[node]+"$<= "+str(threshold[node])+"$")
        if( i==0): ax.set_ylabel(r'$\%$')
        ind=np.arange(1,len(value[node][0])+1,1)
        width=0.2
        bars= (np.array(value[node][0])/normalize)*100
        plt.bar(ind-width/2, bars, width,color=color,alpha=1,linewidth=0)
        plt.xticks(ind, [int(i) for i in ind-1])
        pylab.ticklabel_format(axis='y',style='sci',scilimits=(0,2))

    # Splits
    for j in range(1,max_depth):
        nodes,amount_of_branches=give_nodes(nodes,amount_of_branches,left,right)
        for i,node in enumerate(nodes):
            ax=fig.add_subplot(gs[j,(2**max_depth*i)/amount_of_branches:(2**max_depth*(i+1))/amount_of_branches])
            ax.set_title( features[node]+"$<= "+str(threshold[node])+"$")
            if( i==0): ax.set_ylabel(r'$\%$')
            ind=np.arange(1,len(value[node][0])+1,1)
            width=0.2
            bars= (np.array(value[node][0])/normalize)*100
            plt.bar(ind-width/2, bars, width,color=color,alpha=1,linewidth=0)
            plt.xticks(ind, [int(i) for i in ind-1])
            pylab.ticklabel_format(axis='y',style='sci',scilimits=(0,2))

    plt.tight_layout()
    return fig

Example:

X=[]
Y=[]
amount_of_labels=5
feature_names=[ '$x_1$','$x_2$','$x_3$','$x_4$','$x_5$']
for i in range(200):
    X.append([np.random.normal(),np.random.randint(0,100),np.random.uniform(200,500) ])
    Y.append(np.random.randint(0,amount_of_labels))

clf = tree.DecisionTreeClassifier(criterion='entropy',max_depth=4)
clf = clf.fit(X,Y )
fig=plot_tree(clf, feature_names)


问:
Trying to center 2 groups of 2 divs each at the middle of a wrapper
I have four divs(all same sizes) i have grouped them into to blocks of 2 with classes blocka both contained in an inner container body-content float all the blocks to the left so when my page width changes,these the blocks(of 2) aligned under each other.
I am trying to get now is that those divs sit right at the middle of the main container.

Everything response well. All i need it the class body content sit at the middle of main while blocka all center themselves in the middle of body-content

.main {
  max-width: 100%;
  margin-left: 240px;
  background-color: ;
}

.body-content {
  background-color: white;
  margin: 0 auto;
  width: 95%;
  padding: 15px;
  border: 1px solid grey;
  height: 100px;
}

.blocka {
  float: left;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">

  <div class="body-content">
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
  </div>
</div></code>```

答:
I don't really understand so please clarify.

Here you go, the body-content is sitting in the middle of main, while blocka is sitting in the middle of body-content. You didn't said where will the main be position so I left it in the right-side.

Colors are for visualization and I reduced the body-content's width to see the main behind it

.main {
  max-width: 80%;
  margin: 0 auto;
  background-color: red;
}

.body-content {
  background-color: blue;
  margin: 0 auto;
  width: 50%;
  padding: 15px;
  border: 1px solid grey;
  height: 100px;
  text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">

  <div class="body-content">
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
  </div>
</div></code>```

Body:
I have four divs(all same sizes) i have grouped them into to blocks of 2 with classes blocka both contained in an inner container body-content float all the blocks to the left so when my page width changes,these the blocks(of 2) aligned under each other.
I am trying to get now is that those divs sit right at the middle of the main container.

Everything response well. All i need it the class body content sit at the middle of main while blocka all center themselves in the middle of body-content

.main {
  max-width: 100%;
  margin-left: 240px;
  background-color: ;
}

.body-content {
  background-color: white;
  margin: 0 auto;
  width: 95%;
  padding: 15px;
  border: 1px solid grey;
  height: 100px;
}

.blocka {
  float: left;
  margin: 0 auto;
}

Add All

Add All

Add All

Add All

Body:
I don't really understand so please clarify.

Here you go, the body-content is sitting in the middle of main, while blocka is sitting in the middle of body-content. You didn't said where will the main be position so I left it in the right-side.

Colors are for visualization and I reduced the body-content's width to see the main behind it

.main {
  max-width: 80%;
  margin: 0 auto;
  background-color: red;
}

.body-content {
  background-color: blue;
  margin: 0 auto;
  width: 50%;
  padding: 15px;
  border: 1px solid grey;
  height: 100px;
  text-align:center;
}

<div class="main">

  <div class="body-content">
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
  </div>
</div>


问:
How Web broswer's ssl works
When a user selects using the ssl of web browser, for example,
a user selects the option of using ssl in FireFox, how the Web browser sets the ssl connection? Does the browser has a public key ?</p>

答: When a user selects the option of using ssl in firefox,it allows the the browser to establish connection with ssl enabled websites.The browser has a set of root certificate authorities like verisign which are well known around the world.So when a website gives a certificate signed by these CAs then our browser automatically recognizes the identity of the website.However,if that certificate is signed by a unknown authority ,then the browser gives a pop-up of unknown certificate and it depends on the user to trust it or not.If you trust it then it gets installed in your browser and that pop up does not come up the next time you connect to that website.Similarly,some websites require client certificates in order to recognize the client.In that case,you need to install your certificate(generally provided by them to a set of users) in the browser so that those websites can identify you.You can say that it is a two communication and involves exchange of certificates from both server and client.</p>

Title: How Web broswer's ssl works