问:
TypeError: list indices must be integers, not float
I have a python 3.x program that is producing an error:

```<code>def main():
    names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter',
             'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle',
             'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']

    entered = input('Enter the name of whom you would you like to search for:')
    binary_search(names, entered)

    if position == -1:
        print("Sorry the name entered is not part of the list.")
    else:
        print(entered, " is part of the list and is number ", position, " on the list.")
    input('Press<enter>')

def binary_search(names, entered):
    first = 0
    last = len(names) - 1
    position = -1
    found = False

    while not found and first <= last:
        middle = (first + last) / 2

        if names[middle] == entered:
            found = True
            position = middle
        elif names[middle] > entered:
            last = middle - 1
        else:
            first = middle + 1

    return position

main()
</code>```

Error is:

```<code>TypeError: list indices must be integers, not float
</code>```

I am having trouble understanding what this error message means.

答:
I can be wrong but this line:

```<code>binary_search(names, entered)
</code>```

would not be

```<code>position = binary_search(names, entered)
</code>```

Body:
I have a python 3.x program that is producing an error:

def main():
    names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter',
             'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle',
             'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']

    entered = input('Enter the name of whom you would you like to search for:')
    binary_search(names, entered)

    if position == -1:
        print("Sorry the name entered is not part of the list.")
    else:
        print(entered, " is part of the list and is number ", position, " on the list.")
    input('Press<enter>')

def binary_search(names, entered):
    first = 0
    last = len(names) - 1
    position = -1
    found = False

    while not found and first <= last:
        middle = (first + last) / 2

        if names[middle] == entered:
            found = True
            position = middle
        elif names[middle] > entered:
            last = middle - 1
        else:
            first = middle + 1

    return position

main()

Error is:

TypeError: list indices must be integers, not float

I am having trouble understanding what this error message means.

Body:
I can be wrong but this line:

binary_search(names, entered)

would not be

position = binary_search(names, entered)


来源: stackexchange

问:
Android Studio shows warning: Element merge is not allowed here
I create custom view based on LinearLayout. Class extends the LinearLayout class, in layout I have:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <merge>
        some staff here
    </merge>
</layout>
</code>```

Android Studio shows the the warning Element merge is not allowed here, but app works.

What's wrong?

答:
I believe it's just a glitch in Android studio. Even the official documentation has merge as a direct child of layout: https://developer.android.com/topic/libraries/data-binding/index.html

Edit: I filed a bug there: https://code.google.com/p/android/issues/detail?id=286406&thanks=286406&ts=1490873944

Edit2: Bug is fixed \o/ in AS 3.5 Canary 12

ContentLicense: CC BY-SA 3.0

Body:
I create custom view based on LinearLayout. Class extends the LinearLayout class, in layout I have:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <merge>
        some staff here
    </merge>
</layout>

Android Studio shows the the warning Element merge is not allowed here, but app works.

What's wrong?

ContentLicense: CC BY-SA 4.0


问:
Exporting data from SQL Server Express to CSV (need quoting and escaping)
I've spent 2 days trying to export a 75,000 row table containing a large text field of user input data from a SQL server installation.  This data contains every plain ascii character, tabs, and newlines.  I need to export CSV where every field is quoted, and quotes within the quoted columns are properly escaped ("").

Here is what I've tried so far:
- Right clicking on the database from Management Studio and exporting to Excel: fails due to the field being too long.
- Data Export from Management Studio to flat file with " text separator and comma separation - completely useless, does not escape quotes within a field making the file completely ambiguous.
- BCP from command line - also does not support quoting fields.

I need to import with the FasterCSV ruby library.  It does not allow the quote delimiter to be a non-standard ascii character or more than one character.  It also does not allow \n or \r in unquoted columns.

Any help is greatly appreciated.

答:
The simplest solution Ive found is to add double quotes in your query;

```<code>SELECT '"'+MYCHARACTERDATA+'"' FROM MYTABLE
</code>```

If your spreadsheet allows you to use a custom text qualifier then you can use a more exotic character like | to avoid double quotes in the text.

Daft..SSMS should export as proper CSV with quoted text fields and properly escaped quotes in those fields.

Body:
The simplest solution Ive found is to add double quotes in your query;

SELECT '"'+MYCHARACTERDATA+'"' FROM MYTABLE

If your spreadsheet allows you to use a custom text qualifier then you can use a more exotic character like | to avoid double quotes in the text.

Daft..SSMS should export as proper CSV with quoted text fields and properly escaped quotes in those fields.


问:
In Java Lambda's why is getClass() called on a captured variable
If you look at the byte code for

```<code>Consumer<String> println = System.out::println;
</code>```

the byte code generates by Java 8 update 121 is

```<code>GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
DUP
INVOKEVIRTUAL java/lang/Object.getClass ()Ljava/lang/Class;
POP
INVOKEDYNAMIC accept(Ljava/io/PrintStream;)Ljava/util/function/Consumer; [
  // handle kind 0x6 : INVOKESTATIC
  java/lang/invoke/LambdaMetafactory.metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;
  // arguments:
  (Ljava/lang/Object;)V,
  // handle kind 0x5 : INVOKEVIRTUAL
  java/io/PrintStream.println(Ljava/lang/String;)V,
  (Ljava/lang/String;)V
]
ASTORE 1
</code>```

The getClass() method is being called on the System.out and the result is ignored.

Is this an indirect null reference check?

Certainly if you run

```<code>PrintStream out = null;
Consumer<String> println = out::println;
</code>```

This triggers a NullPointerException.

答:
Yes, calling getClass() has become a canonical “test for null” idiom, as getClass() is expected to be a cheap intrinsic operation and, I suppose, HotSpot might be capable of detecting this pattern and reduce the operation to an intrinsic null-check operation, if the result of getClass() is not used.

Another example is creating an inner class instance with an outer instance that is not this:

```<code>public class ImplicitNullChecks {
    class Inner {}
    void createInner(ImplicitNullChecks obj) {
        obj.new Inner();
    }

    void lambda(Object o) {
        Supplier<String> s=o::toString;
    }
}
</code>```

compiles to

```<code>Compiled from "ImplicitNullChecks.java"
public class bytecodetests.ImplicitNullChecks {
  public bytecodetests.ImplicitNullChecks();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  void createInner(bytecodetests.ImplicitNullChecks);
    Code:
       0: new           #23                 // class bytecodetests/ImplicitNullChecks$Inner
       3: dup
       4: aload_1
       5: dup
       6: invokevirtual #24                 // Method java/lang/Object.getClass:()Ljava/lang/Class;
       9: pop
      10: invokespecial #25                 // Method bytecodetests/ImplicitNullChecks$Inner."<init>":(Lbytecodetests/ImplicitNullChecks;)V
      13: pop
      14: return

  void lambda(java.lang.Object);
    Code:
       0: aload_1
       1: dup
       2: invokevirtual #24                 // Method java/lang/Object.getClass:()Ljava/lang/Class;
       5: pop
       6: invokedynamic #26,  0             // InvokeDynamic #0:get:(Ljava/lang/Object;)Ljava/util/function/Supplier;
      11: astore_2
      12: return
}
</code>```

See also JDK-8073550:

A few places in our class library use the weird trick of using object.getClass() to check for nullity.
  While this make seem a smart move, it actually confuses people into believing this is an approved
  practice of null checking.

With JDK 7, we have Objects.requireNonNull that provide the proper null checking, and declare the
  intent properly.

It might be debatable whether this should apply to programming language intrinsic checks as well, as using Objects.requireNonNull for that purpose would create a dependency to a class outside the java.lang package not visible in the source code. And in this specific case, the trick is only visible to those who look at the byte code. But it has been decided to change the behavior with Java 9.

This is how jdk1.9.0b160 compiles the same test class:

```<code>Compiled from "ImplicitNullChecks.java"
public class bytecodetests.ImplicitNullChecks {
  public bytecodetests.ImplicitNullChecks();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  void createInner(bytecodetests.ImplicitNullChecks);
    Code:
       0: new           #26                 // class bytecodetests/ImplicitNullChecks$Inner
       3: dup
       4: aload_1
       5: dup
       6: invokestatic  #27                 // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)Ljava/lang/Object;
       9: pop
      10: invokespecial #28                 // Method bytecodetests/ImplicitNullChecks$Inner."<init>":(Lbytecodetests/ImplicitNullChecks;)V
      13: pop
      14: return

  void lambda(java.lang.Object);
    Code:
       0: aload_1
       1: dup
       2: invokestatic  #27                 // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)Ljava/lang/Object;
       5: pop
       6: invokedynamic #29,  0             // InvokeDynamic #0:get:(Ljava/lang/Object;)Ljava/util/function/Supplier;
      11: astore_2
      12: return
}
</code>```

Body:
If you look at the byte code for

Consumer<String> println = System.out::println;

the byte code generates by Java 8 update 121 is

GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
DUP
INVOKEVIRTUAL java/lang/Object.getClass ()Ljava/lang/Class;
POP
INVOKEDYNAMIC accept(Ljava/io/PrintStream;)Ljava/util/function/Consumer; [
  // handle kind 0x6 : INVOKESTATIC
  java/lang/invoke/LambdaMetafactory.metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;
  // arguments:
  (Ljava/lang/Object;)V,
  // handle kind 0x5 : INVOKEVIRTUAL
  java/io/PrintStream.println(Ljava/lang/String;)V,
  (Ljava/lang/String;)V
]
ASTORE 1

The getClass() method is being called on the System.out and the result is ignored.

Is this an indirect null reference check?

Certainly if you run

PrintStream out = null;
Consumer<String> println = out::println;

This triggers a NullPointerException.

Body:
Yes, calling getClass() has become a canonical “test for null” idiom, as getClass() is expected to be a cheap intrinsic operation and, I suppose, HotSpot might be capable of detecting this pattern and reduce the operation to an intrinsic null-check operation, if the result of getClass() is not used.

Another example is creating an inner class instance with an outer instance that is not this:

public class ImplicitNullChecks {
    class Inner {}
    void createInner(ImplicitNullChecks obj) {
        obj.new Inner();
    }

    void lambda(Object o) {
        Supplier<String> s=o::toString;
    }
}

compiles to

Compiled from "ImplicitNullChecks.java"
public class bytecodetests.ImplicitNullChecks {
  public bytecodetests.ImplicitNullChecks();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  void createInner(bytecodetests.ImplicitNullChecks);
    Code:
       0: new           #23                 // class bytecodetests/ImplicitNullChecks$Inner
       3: dup
       4: aload_1
       5: dup
       6: invokevirtual #24                 // Method java/lang/Object.getClass:()Ljava/lang/Class;
       9: pop
      10: invokespecial #25                 // Method bytecodetests/ImplicitNullChecks$Inner."<init>":(Lbytecodetests/ImplicitNullChecks;)V
      13: pop
      14: return

  void lambda(java.lang.Object);
    Code:
       0: aload_1
       1: dup
       2: invokevirtual #24                 // Method java/lang/Object.getClass:()Ljava/lang/Class;
       5: pop
       6: invokedynamic #26,  0             // InvokeDynamic #0:get:(Ljava/lang/Object;)Ljava/util/function/Supplier;
      11: astore_2
      12: return
}

See also JDK-8073550:

A few places in our class library use the weird trick of using object.getClass() to check for nullity.
  While this make seem a smart move, it actually confuses people into believing this is an approved
  practice of null checking.

With JDK 7, we have Objects.requireNonNull that provide the proper null checking, and declare the
  intent properly.

It might be debatable whether this should apply to programming language intrinsic checks as well, as using Objects.requireNonNull for that purpose would create a dependency to a class outside the java.lang package not visible in the source code. And in this specific case, the trick is only visible to those who look at the byte code. But it has been decided to change the behavior with Java 9.

This is how jdk1.9.0b160 compiles the same test class:

Compiled from "ImplicitNullChecks.java"
public class bytecodetests.ImplicitNullChecks {
  public bytecodetests.ImplicitNullChecks();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  void createInner(bytecodetests.ImplicitNullChecks);
    Code:
       0: new           #26                 // class bytecodetests/ImplicitNullChecks$Inner
       3: dup
       4: aload_1
       5: dup
       6: invokestatic  #27                 // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)Ljava/lang/Object;
       9: pop
      10: invokespecial #28                 // Method bytecodetests/ImplicitNullChecks$Inner."<init>":(Lbytecodetests/ImplicitNullChecks;)V
      13: pop
      14: return

  void lambda(java.lang.Object);
    Code:
       0: aload_1
       1: dup
       2: invokestatic  #27                 // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)Ljava/lang/Object;
       5: pop
       6: invokedynamic #29,  0             // InvokeDynamic #0:get:(Ljava/lang/Object;)Ljava/util/function/Supplier;
      11: astore_2
      12: return
}


问:
Bootstrap Validator?
I'm using Bootstraps frameworks to build a website and I would like to know if some kind of "validator" tool exist. (kind of like html 4 validator form W3C)</p>

答: This is the one I could find: http://1000hz.github.io/bootstrap-validator/#validator-overview</p>

Title: Bootstrap Validator?


问:
Sorting csv file by one field
Trying to write a program that sorts a csv file with 5 "fields" using compareTo, and I've got the code working to import the csv file into an arrayList, among a couple of other things.
That said, I'm completely stuck on what code I need to actually sort the populated arrayList.

Here is my code:

```<code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class Student implements Comparable<Student>{

public static final String CSV_PATH = "unsortedList.csv";
public static int studentID, mark;
public static String fName, lName, grade;
public static boolean append = true;
public static ArrayList<String> aList = new ArrayList<String>();

public static void main(String[] args) throws IOException {

    readAllLinesFromFile(CSV_PATH);
}

public static ArrayList<String> readAllLinesFromFile(String path) throws IOException{

    FileReader fileReader = new FileReader(path);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line = null;
    while( (line = bufferedReader.readLine()) != null){
        aList.add(line);
    }
    bufferedReader.close();
    System.out.print(aList);

    return aList;

}

public static void writeAllLinesToFile(String path, ArrayList<String> aList) throws IOException {
    //ArrayList<String> aList = new ArrayList<String>();
    FileWriter fileWriter = new FileWriter(path, append);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    for (String line : aList){
        printWriter.printf("%s" + "%n", line);
    }
    printWriter.close();
}

public Student(int studentID, String fName, String lName, int mark, String grade) {
    super();
    this.studentID = studentID;
    this.fName = fName;
    this.lName = lName;
    this.mark = mark;
    this.grade = grade;
}

public int getStudentID() {
    return studentID;
}

public String getfName() {
    return fName;
}

public String getlName() {
    return lName;
}

public int getMark() {
    return mark;
}

public String getGrade() {
    return grade;
}

public int compareTo (Student s) {

    if (this.mark == s.mark) {
        return this.fName.compareTo(s.fName);
    } else {
        return (s.mark - this.mark) > 0 ? 1 : -1;
    }
}
}
</code>```

And here is an example of the contents of the CSV:

```<code>StudentID,FirstName,LastName,FinalMark,FinalGrade
123464,John,Guest,77,P
123456,Dianne,Smith,76,P
122364,Stacey,Hobbs,58,P
123472,Laura,Taylor,67,P
123461,Lazarus,Wonton,42,F
123468,Nola,Emirate,50,P
</code>```

Any help is greatly appreciated!

答:
Take a look at this post: How to sort an ArrayList in Java

The way I see it, you should override the compare function, and then call the sort function on your arraylist.

EDIT: tried it for myself.

```<code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main {

public static final String CSV_PATH = "unsortedList.csv";
public static boolean append = true;
public static ArrayList<String> aList = new ArrayList<String>();

public static void main(String[] args) throws IOException {

    readAllLinesFromFile(CSV_PATH);
    System.out.println("Unsorted:\n");
    for(String aStudentString: aList){
        System.out.println(aStudentString +"\n");
    }

    ArrayList<Student> students = convertToStudents(aList);
    System.out.println("SORTED:\n");
    for(Student student : students){
        System.out.println(student.toString());
    }
}

public static ArrayList<String> readAllLinesFromFile(String path) throws IOException{

    FileReader fileReader = new FileReader(path);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line = null;
    while( (line = bufferedReader.readLine()) != null){
        aList.add(line);
    }
    bufferedReader.close();

    return aList;

}

public static ArrayList<Student> convertToStudents(ArrayList<String> studentsStrings) {
    ArrayList<Student> students = new ArrayList<>();
    studentsStrings.remove(0);
    for(String studentString : studentsStrings) {
        String[] parts = studentString.split(",");
        int studentID = Integer.valueOf(parts[0]);
        String fName = parts[1];
        String lName = parts[2];
        int mark = Integer.valueOf(parts[3]);
        String grade = parts[4];
        students.add(new Student(studentID, fName, lName, mark, grade));
    }

    Collections.sort(students, new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.compareTo(o2);
        }
    });
    return students;
}
public static void writeAllLinesToFile(String path, ArrayList<String> aList) throws IOException {
    //ArrayList<String> aList = new ArrayList<String>();
    FileWriter fileWriter = new FileWriter(path, append);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    for (String line : aList){
        printWriter.printf("%s" + "%n", line);
    }
    printWriter.close();
}
}
</code>```

And the student class:

```<code>public class Student implements Comparable<Student>{

public int studentID, mark;
public String fName, lName, grade;

public Student(int studentID, String fName, String lName, int mark, String grade) {
    super();
    this.studentID = studentID;
    this.fName = fName;
    this.lName = lName;
    this.mark = mark;
    this.grade = grade;
}

public int getStudentID() {
    return studentID;
}

public String getfName() {
    return fName;
}

public String getlName() {
    return lName;
}

public int getMark() {
    return mark;
}

public String getGrade() {
    return grade;
}

@Override
public int compareTo (Student s) {

    if (this.mark == s.mark) {
        return this.fName.compareTo(s.fName);
    } else {
        return (s.mark - this.mark) > 0 ? 1 : -1;
    }
}

@Override
public String toString() {
    return "Student{" + "studentID=" + studentID + ", mark=" + mark + ", fName=" + fName + ", lName=" + lName + ", grade=" + grade + '}';
}

}
</code>```

Title: Sorting csv file by one field

Body:
Trying to write a program that sorts a csv file with 5 "fields" using compareTo, and I've got the code working to import the csv file into an arrayList, among a couple of other things.
That said, I'm completely stuck on what code I need to actually sort the populated arrayList.

Here is my code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class Student implements Comparable<Student>{

public static final String CSV_PATH = "unsortedList.csv";
public static int studentID, mark;
public static String fName, lName, grade;
public static boolean append = true;
public static ArrayList<String> aList = new ArrayList<String>();

public static void main(String[] args) throws IOException {

    readAllLinesFromFile(CSV_PATH);
}

public static ArrayList<String> readAllLinesFromFile(String path) throws IOException{

    FileReader fileReader = new FileReader(path);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line = null;
    while( (line = bufferedReader.readLine()) != null){
        aList.add(line);
    }
    bufferedReader.close();
    System.out.print(aList);

    return aList;

}

public static void writeAllLinesToFile(String path, ArrayList<String> aList) throws IOException {
    //ArrayList<String> aList = new ArrayList<String>();
    FileWriter fileWriter = new FileWriter(path, append);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    for (String line : aList){
        printWriter.printf("%s" + "%n", line);
    }
    printWriter.close();
}

public Student(int studentID, String fName, String lName, int mark, String grade) {
    super();
    this.studentID = studentID;
    this.fName = fName;
    this.lName = lName;
    this.mark = mark;
    this.grade = grade;
}

public int getStudentID() {
    return studentID;
}

public String getfName() {
    return fName;
}

public String getlName() {
    return lName;
}

public int getMark() {
    return mark;
}

public String getGrade() {
    return grade;
}

public int compareTo (Student s) {

    if (this.mark == s.mark) {
        return this.fName.compareTo(s.fName);
    } else {
        return (s.mark - this.mark) > 0 ? 1 : -1;
    }
}
}

And here is an example of the contents of the CSV:

StudentID,FirstName,LastName,FinalMark,FinalGrade
123464,John,Guest,77,P
123456,Dianne,Smith,76,P
122364,Stacey,Hobbs,58,P
123472,Laura,Taylor,67,P
123461,Lazarus,Wonton,42,F
123468,Nola,Emirate,50,P

Any help is greatly appreciated!

Body:
Take a look at this post: How to sort an ArrayList in Java

The way I see it, you should override the compare function, and then call the sort function on your arraylist.

EDIT: tried it for myself.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main {

public static final String CSV_PATH = "unsortedList.csv";
public static boolean append = true;
public static ArrayList<String> aList = new ArrayList<String>();

public static void main(String[] args) throws IOException {

    readAllLinesFromFile(CSV_PATH);
    System.out.println("Unsorted:\n");
    for(String aStudentString: aList){
        System.out.println(aStudentString +"\n");
    }

    ArrayList<Student> students = convertToStudents(aList);
    System.out.println("SORTED:\n");
    for(Student student : students){
        System.out.println(student.toString());
    }
}

public static ArrayList<String> readAllLinesFromFile(String path) throws IOException{

    FileReader fileReader = new FileReader(path);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line = null;
    while( (line = bufferedReader.readLine()) != null){
        aList.add(line);
    }
    bufferedReader.close();

    return aList;

}

public static ArrayList<Student> convertToStudents(ArrayList<String> studentsStrings) {
    ArrayList<Student> students = new ArrayList<>();
    studentsStrings.remove(0);
    for(String studentString : studentsStrings) {
        String[] parts = studentString.split(",");
        int studentID = Integer.valueOf(parts[0]);
        String fName = parts[1];
        String lName = parts[2];
        int mark = Integer.valueOf(parts[3]);
        String grade = parts[4];
        students.add(new Student(studentID, fName, lName, mark, grade));
    }

    Collections.sort(students, new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.compareTo(o2);
        }
    });
    return students;
}
public static void writeAllLinesToFile(String path, ArrayList<String> aList) throws IOException {
    //ArrayList<String> aList = new ArrayList<String>();
    FileWriter fileWriter = new FileWriter(path, append);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    for (String line : aList){
        printWriter.printf("%s" + "%n", line);
    }
    printWriter.close();
}
}

And the student class:

public class Student implements Comparable<Student>{

public int studentID, mark;
public String fName, lName, grade;

public Student(int studentID, String fName, String lName, int mark, String grade) {
    super();
    this.studentID = studentID;
    this.fName = fName;
    this.lName = lName;
    this.mark = mark;
    this.grade = grade;
}

public int getStudentID() {
    return studentID;
}

public String getfName() {
    return fName;
}

public String getlName() {
    return lName;
}

public int getMark() {
    return mark;
}

public String getGrade() {
    return grade;
}

@Override
public int compareTo (Student s) {

    if (this.mark == s.mark) {
        return this.fName.compareTo(s.fName);
    } else {
        return (s.mark - this.mark) > 0 ? 1 : -1;
    }
}

@Override
public String toString() {
    return "Student{" + "studentID=" + studentID + ", mark=" + mark + ", fName=" + fName + ", lName=" + lName + ", grade=" + grade + '}';
}

}


问:
adding two values using react native and display the result
I'm developing simple calculator using react native, just for addition of two numbers. How can I store values to variable and display them using TextInput? And how to add those variables?

答:
```<code>render() {
    return (
        <View>
             <TextInput />
             <TextInput />
        </View>
    );
}
</code>```


问:
I need 2 formats needed in an excel spreadsheet column
I am not using .NET only excel.
1. I have a column of values from 1 - 10.
examples:

```<code>2,00
2,34
6,30
7,00
</code>```

(Comas because I live in Spain)
2. I don't want the whole numbers to show decimal points.
ie: I need

```<code>2
2,34
6,30
7
</code>```

答:
You could do this with conditional formatting. Set the cell format to General and then set the conditional format to override that formatting if the cell is not a whole number:

Create a rule that has the formula (assuming the top left cell in question is A1)

```<code>=IF(A1<>INT(A1),TRUE,FALSE)
</code>```

With that rule, set the conditional format to Number with 2 decimal places.

Body:
I am not using .NET only excel.
1. I have a column of values from 1 - 10.
examples:

2,00
2,34
6,30
7,00

(Comas because I live in Spain)
2. I don't want the whole numbers to show decimal points.
ie: I need

2
2,34
6,30
7

Body:
You could do this with conditional formatting. Set the cell format to General and then set the conditional format to override that formatting if the cell is not a whole number:

Create a rule that has the formula (assuming the top left cell in question is A1)

=IF(A1<>INT(A1),TRUE,FALSE)

With that rule, set the conditional format to Number with 2 decimal places.


问:
Using 'with sexp' on a type generates "Warning 4: this pattern-matching is fragile"
I've just started using the with sexp syntax extension (described here and here) on my custom types.  However, I've noticed that when I do, I get the following warning about my type:

Warning 4: this pattern-matching is fragile. It will remain exhaustive when constructors are added to type Sexplib.Type.t.

I'm assuming this is because the sexp converters that are generated by the with sexp syntax only handle the type constructors defined for Sexp (Sexp.List and Sexp.Atom).

I generally try to fix any warnings in my compilation; is there a way to make the compiler happy here (short of having it suppress the warning entirely for all cases)?

EDIT: for markdown formatting.

Update: Providing example code from hit.ml.

```<code>open Core.Std
open Option.Monad_infix

open Battey.Kernel

type hit = (sentence * int) with sexp
</code>```

Generates this warning:

File "hit.ml", line 6, characters 5-27:
Warning 4: this pattern-matching is fragile.
It will remain exhaustive when constructors are added to type Sexplib.Type.t.

Other info: I'm using version 4.02.3 of ocamlc (as installed via opam) on a macbook (Yosemite) and am using version 113.00.00 of core and core_kernel.  I'm also using -w A for my cflags.

Apologies for the delay in updating; the holidays kept me away from my laptop/internet connection.

Thanks for the feedback!

答:
I believe this is caused by using something like

```<code>match t with
| A -> 0
| B -> 1
| _ -> 2
</code>```

This looks fine if type t = A | B | C. But when later a constructor D is added the _ will just match it and usually that is not what you want. Doesn't look like there is anything you can do but ignore the warning though.

Body:
I've just started using the with sexp syntax extension (described here and here) on my custom types.  However, I've noticed that when I do, I get the following warning about my type:

Warning 4: this pattern-matching is fragile. It will remain exhaustive when constructors are added to type Sexplib.Type.t.

I'm assuming this is because the sexp converters that are generated by the with sexp syntax only handle the type constructors defined for Sexp (Sexp.List and Sexp.Atom).

I generally try to fix any warnings in my compilation; is there a way to make the compiler happy here (short of having it suppress the warning entirely for all cases)?

EDIT: for markdown formatting.

Update: Providing example code from hit.ml.

open Core.Std
open Option.Monad_infix

open Battey.Kernel

type hit = (sentence * int) with sexp

Generates this warning:

File "hit.ml", line 6, characters 5-27:
Warning 4: this pattern-matching is fragile.
It will remain exhaustive when constructors are added to type Sexplib.Type.t.

Other info: I'm using version 4.02.3 of ocamlc (as installed via opam) on a macbook (Yosemite) and am using version 113.00.00 of core and core_kernel.  I'm also using -w A for my cflags.

Apologies for the delay in updating; the holidays kept me away from my laptop/internet connection.

Thanks for the feedback!

Body:
I believe this is caused by using something like

match t with
| A -> 0
| B -> 1
| _ -> 2

This looks fine if type t = A | B | C. But when later a constructor D is added the _ will just match it and usually that is not what you want. Doesn't look like there is anything you can do but ignore the warning though.


问:
Eigen matrix library coefficient-wise modulo operation
In one of the functions in the project I am working on, I need to find the remainder of each element of my eigen library matrix when divided by a given number. Here is the Matlab equivalent to what I want to do:

```<code>mod(X,num)
</code>```

where X is the dividend matrix and num is the divisor.

What is the easiest way to achieve this?

答:
For completeness, another solution would be to:

transform X to an eigen array (for coeffwise operations),

Apply the modulo formula a%b = a - (b * int(a/b))

C++ code that return an eigen array:

```<code>auto mod_array = X.array() - (num * (X.array()/num));
</code>```

C++ code to get a matrix:

```<code>auto mod_matrix = (X.array() - (num * (X.array()/num))).matrix();
</code>```

Note that, parentheses are important especially in (X.array()/num) as eigen will optimize (num * X.array()/num) to X.array() which is not what we expect.

The first version with eigen array is faster than version with unaryExpr.
The second version with matrix takes about the same time as version with unaryExpr.

If X contains float numbers, you will need to cast X.array() in (X.array()/num) to int

Body:
In one of the functions in the project I am working on, I need to find the remainder of each element of my eigen library matrix when divided by a given number. Here is the Matlab equivalent to what I want to do:

mod(X,num)

where X is the dividend matrix and num is the divisor.

What is the easiest way to achieve this?

Body:
For completeness, another solution would be to:

transform X to an eigen array (for coeffwise operations),

Apply the modulo formula a%b = a - (b * int(a/b))

C++ code that return an eigen array:

auto mod_array = X.array() - (num * (X.array()/num));

C++ code to get a matrix:

auto mod_matrix = (X.array() - (num * (X.array()/num))).matrix();

Note that, parentheses are important especially in (X.array()/num) as eigen will optimize (num * X.array()/num) to X.array() which is not what we expect.

The first version with eigen array is faster than version with unaryExpr.
The second version with matrix takes about the same time as version with unaryExpr.

If X contains float numbers, you will need to cast X.array() in (X.array()/num) to int


问:
Displaying custom checkout billing field on email notifications
In WooCommerce, I want to add some custom fields on checkout which will be displayed under the billing section on the e-mail confirmation.
My custom fields and their values, shown on the checkout form and on the order page on back end (WooCommerce -> Orders). So far everything works great.

The problem is that the e-mail that i receive does not contain the custom fields and their values.

Code shown below:

```<code>    add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
    function custom_override_checkout_fields( $fields ) {
        $fields['billing']['billing_field_testing'] = array(
            'label'     => __('TestingField', 'woocommerce'),
            'placeholder'   => _x('TestingField', 'placeholder', 'woocommerce'),
            'required'  => false,
            'class'     => array('form-row-wide'),
            'clear'     => true
             );
        return $fields;
    }

    add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
    function my_custom_checkout_field_display_admin_order_meta($order)
    {
        echo '<p><strong>'.__('TestingField').':</strong> ' . get_post_meta( $order->id, '_billing_field_testing', true ) . '</p>';
    }
</code>```

Please help.

Thanks in advance

答:
You will need to customize email templates under woocommerce/templates/emails/ to your-theme/woocommerce/emails/

Youc an override whatever template you want end add custom field there.

Alternatively, you can also add them using hook from following code:

```<code>add_filter( 'woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3 );

function custom_woocommerce_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
    $fields['meta_key'] = array(
        'label' => __( 'Label' ),
        'value' => get_post_meta( $order->id, 'meta_key', true ),
    );
    return $fields;
}
</code>```

Body:
In WooCommerce, I want to add some custom fields on checkout which will be displayed under the billing section on the e-mail confirmation.
My custom fields and their values, shown on the checkout form and on the order page on back end (WooCommerce -> Orders). So far everything works great.

The problem is that the e-mail that i receive does not contain the custom fields and their values.

Code shown below:

    add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
    function custom_override_checkout_fields( $fields ) {
        $fields['billing']['billing_field_testing'] = array(
            'label'     => __('TestingField', 'woocommerce'),
            'placeholder'   => _x('TestingField', 'placeholder', 'woocommerce'),
            'required'  => false,
            'class'     => array('form-row-wide'),
            'clear'     => true
             );
        return $fields;
    }

    add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
    function my_custom_checkout_field_display_admin_order_meta($order)
    {
        echo '
'.__('TestingField').': ' . get_post_meta( $order->id, '_billing_field_testing', true ) . '
';
    }

Please help.

Thanks in advance

Body:
You will need to customize email templates under woocommerce/templates/emails/ to your-theme/woocommerce/emails/

Youc an override whatever template you want end add custom field there.

Alternatively, you can also add them using hook from following code:

add_filter( 'woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3 );

function custom_woocommerce_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
    $fields['meta_key'] = array(
        'label' => __( 'Label' ),
        'value' => get_post_meta( $order->id, 'meta_key', true ),
    );
    return $fields;
}


问:
Sort a List of users based on statistics from a seperate Table
I have a table of friends where I can get userIds. I also have a table of Stats where the Key is userId.

I want to create a highscore (List) of friends sorted by the score in the stats-table, what would be the best way to sort this list?

I can fill an Array of friends stats like this:

```<code>List<Player> friendsList = getFriends(playerID, limit);
List<Stats> stats = new ArrayList<Stats>();

        for(Player player: friendsList){
            stats.add(ofy().load().type(Stats.class).filter("player", player).first().now());
        }
</code>```

Now I want to sort it and return a List of friends (Player) + score sorted by the highest score.

答:
The solution can be made more elegant if you use a HashMap for your friendsList or use SQL to sort with. But I decided to answer based on the information you provided, such that you do not have to refactor a lot. I can provide you with a lot more elegant solution, if you want that, just ask.

Solution to your problem

```<code>class Main{

    public static void main(String[] args) {

        List<Player> friendsList = new ArrayList<Player>();
        friendsList.add(new Player(1));
        friendsList.add(new Player(2));
        friendsList.add(new Player(3));

        List<Stats> stats = new ArrayList<Stats>();
        stats.add(new Stats(1,100));
        stats.add(new Stats(2, 300));
        stats.add(new Stats(3,200));

        Collections.sort(stats,
                (Stats s1, Stats s2)->s1.getScore().compareTo(s2.getScore())
                );

        List<Player> highscore = new ArrayList<Player>();
        for(Stats s : stats){
            for(int i = 0; i < stats.size(); i++){
                if(friendsList.get(i).id == s.getUserId()){
                    highscore.add(friendsList.get(i));
                }
            }
        }

        Collections.reverse(highscore);

        for(Player p : highscore){
            System.out.println(p.getId());
        }

    }
}
</code>```

Output:

```<code>2
3
1
</code>```

Additional classes for the purpose of testing:

```<code>class Player{
    Integer id;
    Player(Integer id){
        this.id = id;
    }
    Integer getId(){
        return id;
    }
}

class Stats{
    Integer userId;
    Integer score;
    Stats(Integer userId, Integer score){
        this.userId = userId;
        this.score = score;
    }
    Integer getScore(){
        return score;
    }
    Integer getUserId(){
        return userId;
    }
}
</code>```

Body:
I have a table of friends where I can get userIds. I also have a table of Stats where the Key is userId.

I want to create a highscore (List) of friends sorted by the score in the stats-table, what would be the best way to sort this list?

I can fill an Array of friends stats like this:

List<Player> friendsList = getFriends(playerID, limit);
List<Stats> stats = new ArrayList<Stats>();

        for(Player player: friendsList){
            stats.add(ofy().load().type(Stats.class).filter("player", player).first().now());
        }

Now I want to sort it and return a List of friends (Player) + score sorted by the highest score.

Body:
The solution can be made more elegant if you use a HashMap for your friendsList or use SQL to sort with. But I decided to answer based on the information you provided, such that you do not have to refactor a lot. I can provide you with a lot more elegant solution, if you want that, just ask.

Solution to your problem

class Main{

    public static void main(String[] args) {

        List<Player> friendsList = new ArrayList<Player>();
        friendsList.add(new Player(1));
        friendsList.add(new Player(2));
        friendsList.add(new Player(3));

        List<Stats> stats = new ArrayList<Stats>();
        stats.add(new Stats(1,100));
        stats.add(new Stats(2, 300));
        stats.add(new Stats(3,200));

        Collections.sort(stats,
                (Stats s1, Stats s2)->s1.getScore().compareTo(s2.getScore())
                );

        List<Player> highscore = new ArrayList<Player>();
        for(Stats s : stats){
            for(int i = 0; i < stats.size(); i++){
                if(friendsList.get(i).id == s.getUserId()){
                    highscore.add(friendsList.get(i));
                }
            }
        }

        Collections.reverse(highscore);

        for(Player p : highscore){
            System.out.println(p.getId());
        }

    }
}

Output:

2
3
1

Additional classes for the purpose of testing:

class Player{
    Integer id;
    Player(Integer id){
        this.id = id;
    }
    Integer getId(){
        return id;
    }
}

class Stats{
    Integer userId;
    Integer score;
    Stats(Integer userId, Integer score){
        this.userId = userId;
        this.score = score;
    }
    Integer getScore(){
        return score;
    }
    Integer getUserId(){
        return userId;
    }
}


问:
Memory warning and crash when creating PDF
When genrating a large PDF, my app recives a memory a warning, then crashes during the generation process of the PDF.  The PDF is drawn into a web view, when the pages get above a certain amount (depending on device) I run out of memory

My research into this matter so far leads me to understand I need to:

change UIGraphicsBeginPDFContextToData to IGraphicsBeginPDFContextToFile

Create a reasonable path to a temporary file,

Give that to the function,

Give the file to the webview to load.

Delete the file when done.

Problem is, while I think I grasp it (just) in pricipal, I dont know how to go about acheiving this, or fully understand it so as to impliment it within my code.  Advice in this matter very much appricated

Im also open to any other ideas to stop the memory crash

```<code>@interface ICPDFPreviewController ()
@property (nonatomic, strong) Certificate *certificate;
@property (nonatomic, strong) NSData *pdfData;
@property (nonatomic) BOOL viewHasUnloaded;
- (void)generatePdf;
- (void)pdfDone:(NSData *)data;
- (NSData *)createPdfWithPages:(NSArray *)pages;
@end

@implementation ICPDFPreviewController
@synthesize certificate=_certificate;
@synthesize scrollView=_scrollView;
@synthesize webView=_webView;
@synthesize pdfData=_pdfData;
@synthesize viewHasUnloaded=_viewHasUnloaded;

- (void)generatePdf
 {
 NSMutableArray *pagesArray = [NSMutableArray array];

 if ([self.certificate.certificateType.title isEqualToString:@"Minor Works"]) {
[pagesArray addObject:[[ICPDFMinorWorksPage1 alloc] initWithCertificate:self.certificate]];
 [pagesArray addObject:[[ICPDFMinorWorksPage2 alloc] initWithCertificate:self.certificate]];

 } else if ([self.certificate.certificateType.title isEqualToString:@"EIC"]) {
[pagesArray addObject:[[ICPDFEICPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage4 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage5 alloc] initWithCertificate:self.certificate]];
[self addDistributionBoardsToPagesArray:pagesArray];
ICPDFEICPageFinal *pageFinal = [[ICPDFEICPageFinal alloc]        initWithCertificate:self.certificate];
 pageFinal.pageNumber.text = [NSString stringWithFormat:@"%d", pagesArray.count+1];
[pagesArray addObject:pageFinal];

} else if ([self.certificate.certificateType.title isEqualToString:@"Domestic EIC"]) {
[pagesArray addObject:[[ICPDFDomesticEICPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage4 alloc] initWithCertificate:self.certificate]];
[self addDistributionBoardsToPagesArray:pagesArray];
[pagesArray addObject:[[ICPDFDomesticEICPageFinal alloc] initWithCertificate:self.certificate]];

} else if ([self.certificate.certificateType.title isEqualToString:@"EICR"]) {
[pagesArray addObject:[[ICPDFEICRPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRPage2 alloc] initWithCertificate:self.certificate]];
[self addObservationsToPagesArray:pagesArray];
[self addDistributionBoardsToPagesArray:pagesArray];
[pagesArray addObject:[[ICPDFEICRInspection alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRPageFinal alloc] initWithCertificate:self.certificate]];
 }

// Set page count on all pages
int pageNumber = 0;
for (ICCertificateComponent *page in pagesArray) {
page.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageNumber];
page.pageCount.text = [NSString stringWithFormat:@"%d", pagesArray.count];
}

 NSData *pdfData = [self createPdfWithPages:pagesArray];
[self performSelectorOnMainThread:@selector(pdfDone:) withObject:pdfData waitUntilDone:YES];

 }

- (void)pdfDone:(NSData *)data
 {
 self.pdfData = data;
[self.webView loadData:self.pdfData MIMEType:@"application/pdf" textEncodingName:@"utf-8"      baseURL:nil];
 [ICUtils removeProgressView];
 }

 - (NSData *)createPdfWithPages:(NSArray *)pages
  {
 // Creates a mutable data object for updating with binary data, like a byte array
 NSMutableData *pdfData = [NSMutableData data];

 ICCertificateComponent *firstPage = [pages objectAtIndex:0];

UIGraphicsBeginPDFContextToData(pdfData, firstPage.contentView.bounds, nil);

 for (int i = 0; i < pages.count; i++) {
 ICCertificateComponent *thisPage = [pages objectAtIndex:i];
 UIGraphicsBeginPDFPageWithInfo(thisPage.contentView.bounds, nil);

 CGContextRef pdfContext = UIGraphicsGetCurrentContext();
 [thisPage.contentView.layer renderInContext:pdfContext];
 }

 UIGraphicsEndPDFContext();

 return pdfData;
}

- (void)addDistributionBoardsToPagesArray:(NSMutableArray *)pagesArray
{
int pageCount = pagesArray.count;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt"       ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
NSArray *boards = [self.certificate.distributionBoards      sortedArrayUsingDescriptors:sortDescriptors];
 for (DistributionBoard *thisBoard in boards) {
DebugLog(@"Creating a board page");
ICPDFDistributionBoard *boardPage = [[ICPDFDistributionBoard alloc]        initWithDistributionBoard:thisBoard];
boardPage.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageCount];
DebugLog(@"Page number is %d", pageCount);
[pagesArray addObject:boardPage];

NSSortDescriptor *circuitDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt"     ascending:YES];
NSArray *circuitDescriptors = [[NSArray alloc] initWithObjects:circuitDescriptor, nil];
NSArray *circuits = [thisBoard.circuits sortedArrayUsingDescriptors:circuitDescriptors];

 //int circuitCount = circuits.count;
 ICPDFCircuitDetails *circuitDetails = boardPage.circuitDetails;

int circuitCount = 0;
for (Circuit *thisCircuit in circuits) {
circuitCount++;
if (circuitCount > 16) {
    // Add an extension page
    DebugLog(@"Adding an extension sheet");
    circuitCount = 1;
    ICPDFDistributionBoardExtension *boardExtension = [[ICPDFDistributionBoardExtension  alloc]   initWithDistributionBoard:thisBoard];
    [pagesArray addObject:boardExtension];
    boardExtension.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageCount];
    circuitDetails = boardExtension.circuitDetails;
   }
    NSString *key = [NSString stringWithFormat:@"circuitRow%d", circuitCount];
   ICCircuitRow *circuitRow = [circuitDetails valueForKey:key];
   [circuitRow populateFromCircuit:thisCircuit];
  }
 }
}
</code>```

debug console warnings are a load of these, then crash

```<code> 2013-02-08 10:38:35.475 iCertifi[5772:907] Received memory warning.
 2013-02-08 10:38:35.477 iCertifi[5772:907] <ICPDFPreviewController: 0x1eb28930>   didReceiveMemoryWarning
</code>```

答:
Try to use @autoreleasepool in your for cycle</p>

```<code>for (int i = 0; i < pages.count; i++) {

// notice this line
     @autureleasepool
     {
       ICCertificateComponent *thisPage = [pages objectAtIndex:i];
       UIGraphicsBeginPDFPageWithInfo(thisPage.contentView.bounds, nil);

       CGContextRef pdfContext = UIGraphicsGetCurrentContext();
       [thisPage.contentView.layer renderInContext:pdfContext];
     }
 }
</code>```

Body:
When genrating a large PDF, my app recives a memory a warning, then crashes during the generation process of the PDF.  The PDF is drawn into a web view, when the pages get above a certain amount (depending on device) I run out of memory

My research into this matter so far leads me to understand I need to:

change UIGraphicsBeginPDFContextToData to IGraphicsBeginPDFContextToFile

Create a reasonable path to a temporary file,

Give that to the function,

Give the file to the webview to load.

Delete the file when done.

Problem is, while I think I grasp it (just) in pricipal, I dont know how to go about acheiving this, or fully understand it so as to impliment it within my code.  Advice in this matter very much appricated

Im also open to any other ideas to stop the memory crash

@interface ICPDFPreviewController ()
@property (nonatomic, strong) Certificate *certificate;
@property (nonatomic, strong) NSData *pdfData;
@property (nonatomic) BOOL viewHasUnloaded;
- (void)generatePdf;
- (void)pdfDone:(NSData *)data;
- (NSData *)createPdfWithPages:(NSArray *)pages;
@end

@implementation ICPDFPreviewController
@synthesize certificate=_certificate;
@synthesize scrollView=_scrollView;
@synthesize webView=_webView;
@synthesize pdfData=_pdfData;
@synthesize viewHasUnloaded=_viewHasUnloaded;

- (void)generatePdf
 {
 NSMutableArray *pagesArray = [NSMutableArray array];

 if ([self.certificate.certificateType.title isEqualToString:@"Minor Works"]) {
[pagesArray addObject:[[ICPDFMinorWorksPage1 alloc] initWithCertificate:self.certificate]];
 [pagesArray addObject:[[ICPDFMinorWorksPage2 alloc] initWithCertificate:self.certificate]];

 } else if ([self.certificate.certificateType.title isEqualToString:@"EIC"]) {
[pagesArray addObject:[[ICPDFEICPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage4 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage5 alloc] initWithCertificate:self.certificate]];
[self addDistributionBoardsToPagesArray:pagesArray];
ICPDFEICPageFinal *pageFinal = [[ICPDFEICPageFinal alloc]        initWithCertificate:self.certificate];
 pageFinal.pageNumber.text = [NSString stringWithFormat:@"%d", pagesArray.count+1];
[pagesArray addObject:pageFinal];

} else if ([self.certificate.certificateType.title isEqualToString:@"Domestic EIC"]) {
[pagesArray addObject:[[ICPDFDomesticEICPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage4 alloc] initWithCertificate:self.certificate]];
[self addDistributionBoardsToPagesArray:pagesArray];
[pagesArray addObject:[[ICPDFDomesticEICPageFinal alloc] initWithCertificate:self.certificate]];

} else if ([self.certificate.certificateType.title isEqualToString:@"EICR"]) {
[pagesArray addObject:[[ICPDFEICRPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRPage2 alloc] initWithCertificate:self.certificate]];
[self addObservationsToPagesArray:pagesArray];
[self addDistributionBoardsToPagesArray:pagesArray];
[pagesArray addObject:[[ICPDFEICRInspection alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRPageFinal alloc] initWithCertificate:self.certificate]];
 }

// Set page count on all pages
int pageNumber = 0;
for (ICCertificateComponent *page in pagesArray) {
page.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageNumber];
page.pageCount.text = [NSString stringWithFormat:@"%d", pagesArray.count];
}

 NSData *pdfData = [self createPdfWithPages:pagesArray];
[self performSelectorOnMainThread:@selector(pdfDone:) withObject:pdfData waitUntilDone:YES];

 }

- (void)pdfDone:(NSData *)data
 {
 self.pdfData = data;
[self.webView loadData:self.pdfData MIMEType:@"application/pdf" textEncodingName:@"utf-8"      baseURL:nil];
 [ICUtils removeProgressView];
 }

 - (NSData *)createPdfWithPages:(NSArray *)pages
  {
 // Creates a mutable data object for updating with binary data, like a byte array
 NSMutableData *pdfData = [NSMutableData data];

 ICCertificateComponent *firstPage = [pages objectAtIndex:0];

UIGraphicsBeginPDFContextToData(pdfData, firstPage.contentView.bounds, nil);

 for (int i = 0; i < pages.count; i++) {
 ICCertificateComponent *thisPage = [pages objectAtIndex:i];
 UIGraphicsBeginPDFPageWithInfo(thisPage.contentView.bounds, nil);

 CGContextRef pdfContext = UIGraphicsGetCurrentContext();
 [thisPage.contentView.layer renderInContext:pdfContext];
 }

 UIGraphicsEndPDFContext();

 return pdfData;
}

- (void)addDistributionBoardsToPagesArray:(NSMutableArray *)pagesArray
{
int pageCount = pagesArray.count;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt"       ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
NSArray *boards = [self.certificate.distributionBoards      sortedArrayUsingDescriptors:sortDescriptors];
 for (DistributionBoard *thisBoard in boards) {
DebugLog(@"Creating a board page");
ICPDFDistributionBoard *boardPage = [[ICPDFDistributionBoard alloc]        initWithDistributionBoard:thisBoard];
boardPage.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageCount];
DebugLog(@"Page number is %d", pageCount);
[pagesArray addObject:boardPage];

NSSortDescriptor *circuitDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt"     ascending:YES];
NSArray *circuitDescriptors = [[NSArray alloc] initWithObjects:circuitDescriptor, nil];
NSArray *circuits = [thisBoard.circuits sortedArrayUsingDescriptors:circuitDescriptors];

 //int circuitCount = circuits.count;
 ICPDFCircuitDetails *circuitDetails = boardPage.circuitDetails;

int circuitCount = 0;
for (Circuit *thisCircuit in circuits) {
circuitCount++;
if (circuitCount > 16) {
    // Add an extension page
    DebugLog(@"Adding an extension sheet");
    circuitCount = 1;
    ICPDFDistributionBoardExtension *boardExtension = [[ICPDFDistributionBoardExtension  alloc]   initWithDistributionBoard:thisBoard];
    [pagesArray addObject:boardExtension];
    boardExtension.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageCount];
    circuitDetails = boardExtension.circuitDetails;
   }
    NSString *key = [NSString stringWithFormat:@"circuitRow%d", circuitCount];
   ICCircuitRow *circuitRow = [circuitDetails valueForKey:key];
   [circuitRow populateFromCircuit:thisCircuit];
  }
 }
}

debug console warnings are a load of these, then crash

 2013-02-08 10:38:35.475 iCertifi[5772:907] Received memory warning.
 2013-02-08 10:38:35.477 iCertifi[5772:907] <ICPDFPreviewController: 0x1eb28930>   didReceiveMemoryWarning

Body:
Try to use @autoreleasepool in your for cycle

for (int i = 0; i < pages.count; i++) {

// notice this line
     @autureleasepool
     {
       ICCertificateComponent *thisPage = [pages objectAtIndex:i];
       UIGraphicsBeginPDFPageWithInfo(thisPage.contentView.bounds, nil);

       CGContextRef pdfContext = UIGraphicsGetCurrentContext();
       [thisPage.contentView.layer renderInContext:pdfContext];
     }
 }


问:
Python Selenium how to locate element
How can I click via selenium and python on such element:

```<code>      <a href="#create" class="btn toolbarBtn">
          <i class="fa fa-plus-circle"></i> Create
        </a>
</code>```

When I Copy Xpath this element from Chrome i got this:

//*[@id="page"]/div/div/div/div[1]/div[1]/a/i

But when I use it in my code:

driver.find_element_by_xpath('//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()

I got error that:

```<code>Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()"}
</code>```

When I tried to use find_element_by_link_text and partial_link_text I got same error that selenium was unable to find such element.

答:
Try to wait until element becomes clickable:

```<code>from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href='#create']"))).click()
</code>```

If this also doesn't work check whether your link located inside . If so, you need to switch to that frame before clicking link:

```<code>driver.switch_to.frame("Put frameID here")
</code>```

Title: Python Selenium how to locate element

Body:
How can I click via selenium and python on such element:

           Create

When I Copy Xpath this element from Chrome i got this:

//*[@id="page"]/div/div/div/div[1]/div[1]/a/i

But when I use it in my code:

driver.find_element_by_xpath('//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()

I got error that:

Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()"}

When I tried to use find_element_by_link_text and partial_link_text I got same error that selenium was unable to find such element.

Body:
Try to wait until element becomes clickable:

from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href='#create']"))).click()

If this also doesn't work check whether your link located inside <iframe>. If so, you need to switch to that frame before clicking link:

driver.switch_to.frame("Put frameID here")


问:
Android - when ever my app is installed, by default "No permission allowed" is set?
My app when-ever is installed via Google Play or USB
(which use microphone, camera just like all other general app), by default the app gets "No permission allowed".

As a result it never works after the installation as fresh install.

Unless someone manually go in the app settings and change it.

What am i doing wrong? why its causing default into permission denied mode?

AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
</code>```

EDIT:

```<code>C:\cordova\tpt>cordova plugin add cordova.plugins.diagnostic
Fetching plugin "cordova.plugins.diagnostic" via npm
Installing "cordova.plugins.diagnostic" for android
ANDROID_HOME=C:\Users\tpt\AppData\Local\Android\sdk
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_121
Subproject Path: CordovaLib
null
org.xwalk:xwalk_core_library:23+
Incremental java compilation is an incubating feature.
:clean FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':clean'.
> Unable to delete directory: C:\cordova\tpt\platforms\android\build\outputs\apk

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 3.83 secs
Failed to install 'cordova.plugins.diagnostic':Error: cmd: Command failed with exit code 1
    at ChildProcess.whenDone (C:\cordova\tpt\platforms\android\cordova\node_modules\cordova-common\src\superspawn.js:169:23)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:886:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
Error: cmd: Command failed with exit code 1
</code>```

答:
Starting from Android Marshmallow (6.0), you have to request the permissions at run-time. This way the user can manually accept or deny each permission you need.

For help on implementing permissions see the Android documentation.

This prevents apps from 'secretly' using private device and user information without their consent.

Body:
My app when-ever is installed via Google Play or USB
(which use microphone, camera just like all other general app), by default the app gets "No permission allowed".

As a result it never works after the installation as fresh install.

Unless someone manually go in the app settings and change it.

What am i doing wrong? why its causing default into permission denied mode?

AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CAMERA" />

EDIT:

C:\cordova\tpt>cordova plugin add cordova.plugins.diagnostic
Fetching plugin "cordova.plugins.diagnostic" via npm
Installing "cordova.plugins.diagnostic" for android
ANDROID_HOME=C:\Users\tpt\AppData\Local\Android\sdk
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_121
Subproject Path: CordovaLib
null
org.xwalk:xwalk_core_library:23+
Incremental java compilation is an incubating feature.
:clean FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':clean'.
> Unable to delete directory: C:\cordova\tpt\platforms\android\build\outputs\apk

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 3.83 secs
Failed to install 'cordova.plugins.diagnostic':Error: cmd: Command failed with exit code 1
    at ChildProcess.whenDone (C:\cordova\tpt\platforms\android\cordova\node_modules\cordova-common\src\superspawn.js:169:23)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:886:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
Error: cmd: Command failed with exit code 1


问:
NHibernate: Error when saving Bag with NOT-Nullable Constraint
Given are tables Item and ItemTranslation where the latter has a NOT-Nullable foreign key on Item.

ItemTranslation.hbm.xml only has its properties Text and LanguageCode, it does NOT map Item.

Item.hbm.xml:

```<code><bag name="Translations" cascade="all-delete-orphan">
  <key column="ItemID" />
  <one-to-many class="ItemTranslation, SomeNamespace" />
</bag>
</code>```

Now when I do the following:

```<code>Item item = new Item();
item.Translations.Add( new ItemTranslation { LanguageCode = "DE", Text = "Test DE" } );
item.Translations.Add( new ItemTranslation { LanguageCode = "EN", Text = "Test EN" } );
item.Save();
</code>```

NHibernate throws the following exception:

```<code>System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'ItemID', table 'someDb.dbo.ItemTranslation'; column does not allow nulls. INSERT fails.
Cannot insert the value NULL into column 'ItemID', table 'someDb.dbo.ItemTranslation'; column does not allow nulls.
</code>```

I could fix it either by mapping ItemID as many-to-one in IssuedItemTranslation.hbm.xml or making the column NULLable.

But both ways are kind of ugly.

Is there any other possibility? Maybe with some change in the bag-mapping?

Thank you in advance.

答:
If we do not want to use inverse mapping (see below) .. we must left the column in DB nullable.

That is how it works. NHibernate will

insert children (or parent)

insert parent   (or children) read more here 9.6. Flush

update children with parent id

Another way: Inverse mapping

There is nothing bad on explicit Item back reference mapping on ItemTranslatin. I do that always. And If we really do not like it.. it could be protected property.

But then, we would need inverse mapping.

```<code><bag name="Translations" cascade="all-delete-orphan" inverse="true">
</code>```

And also set the reference on both sides.

```<code>Item item = new Item();
var tr1 = new ItemTranslation {
  LanguageCode = "DE",
  Text = "Test DE"
  Item = item } ;
item.Translations.Add(tr1);
...
</code>```

This solution does not require item column to be nullable...

That would be the way I suggest. Read more here:

Minimal and correct way to map one-to-many with NHibernate

Body:
Given are tables Item and ItemTranslation where the latter has a NOT-Nullable foreign key on Item.

ItemTranslation.hbm.xml only has its properties Text and LanguageCode, it does NOT map Item.

Item.hbm.xml:

<bag name="Translations" cascade="all-delete-orphan">
  <key column="ItemID" />
  <one-to-many class="ItemTranslation, SomeNamespace" />
</bag>

Now when I do the following:

Item item = new Item();
item.Translations.Add( new ItemTranslation { LanguageCode = "DE", Text = "Test DE" } );
item.Translations.Add( new ItemTranslation { LanguageCode = "EN", Text = "Test EN" } );
item.Save();

NHibernate throws the following exception:

System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'ItemID', table 'someDb.dbo.ItemTranslation'; column does not allow nulls. INSERT fails.
Cannot insert the value NULL into column 'ItemID', table 'someDb.dbo.ItemTranslation'; column does not allow nulls.

I could fix it either by mapping ItemID as many-to-one in IssuedItemTranslation.hbm.xml or making the column NULLable.

But both ways are kind of ugly.

Is there any other possibility? Maybe with some change in the bag-mapping?

Thank you in advance.

Body:
If we do not want to use inverse mapping (see below) .. we must left the column in DB nullable.

That is how it works. NHibernate will

insert children (or parent)

insert parent   (or children) read more here 9.6. Flush

update children with parent id

Another way: Inverse mapping

There is nothing bad on explicit Item back reference mapping on ItemTranslatin. I do that always. And If we really do not like it.. it could be protected property.

But then, we would need inverse mapping.

<bag name="Translations" cascade="all-delete-orphan" inverse="true">

And also set the reference on both sides.

Item item = new Item();
var tr1 = new ItemTranslation {
  LanguageCode = "DE",
  Text = "Test DE"
  Item = item } ;
item.Translations.Add(tr1);
...

This solution does not require item column to be nullable...

That would be the way I suggest. Read more here:

Minimal and correct way to map one-to-many with NHibernate


问:
Getting HTML form elements to be in line
I am using some bootstrap elements along with some buttons and have issues getting them all to show up in one line! I have something like:

```<code><span><input class="form-control" id="filename" value="Select a ZIP file to upload..." disabled style="display: inline" ></span>
<span><input type="button" id="get_file" class="btn btn-primary" value="Browse" style="display: inline"></span>
<span><input type="button" id="get_file" class="btn btn-success" value="Upload" style="display: inline"></span>
<input type="file" id="my_file" accept=".zip" style="display: none">
</code>```

This should basically show a text field with two buttons and I get an output like:

What i would like is for the two buttons to be on the same row as well...

答:
Have a look to the Bootstrap Documentation :
http://getbootstrap.com/components/#input-groups-buttons

```<code>  <div class="input-group">
    <input type="text" class="form-control" placeholder="Search for...">
    <span class="input-group-btn">
      <button class="btn btn-default" type="button">Go!</button>
    </span>
  </div>
</code>```

Body:
I am using some bootstrap elements along with some buttons and have issues getting them all to show up in one line! I have something like:

<input class="form-control" id="filename" value="Select a ZIP file to upload..." disabled style="display: inline" >
<input type="button" id="get_file" class="btn btn-primary" value="Browse" style="display: inline">
<input type="button" id="get_file" class="btn btn-success" value="Upload" style="display: inline">
<input type="file" id="my_file" accept=".zip" style="display: none">

This should basically show a text field with two buttons and I get an output like:

What i would like is for the two buttons to be on the same row as well...

Body:
Have a look to the Bootstrap Documentation :
http://getbootstrap.com/components/#input-groups-buttons

  <div class="input-group">
    <input type="text" class="form-control" placeholder="Search for...">
    <span class="input-group-btn">
      <button class="btn btn-default" type="button">Go!</button>
    </span>
  </div>


问:
How to configure a WCF service for a load balancer
How to configure a WCF service for a load balancer and specific the end points</p>

答:
You could try writing a custom service host factory which will use the load balancer's url as base address:</p>

```<code>public class CustomServiceHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(
        Type serviceType, Uri[] baseAddresses)
    {
        Uri uri = null;
        if (baseAddresses.Length < 2)
        {
            uri = baseAddresses[0];
        }
        else
        {
            // TODO: You need to choose the load balancer's url here:
            uri = baseAddresses[????];
        }
        return base.CreateServiceHost(serviceType, new Uri[] { uri });
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You could try writing a custom service host factory which will use the load balancer's url as base address:

public class CustomServiceHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(
        Type serviceType, Uri[] baseAddresses)
    {
        Uri uri = null;
        if (baseAddresses.Length < 2)
        {
            uri = baseAddresses[0];
        }
        else
        {
            // TODO: You need to choose the load balancer's url here:
            uri = baseAddresses[????];
        }
        return base.CreateServiceHost(serviceType, new Uri[] { uri });
    }
}


问:
Speeding up rowwise comparison
I have a data.frame like the following:

```<code>id year  x y         v1
 1 2006 12 1  0.8510703
 1 2007 12 1  0.5954527
 1 2008 12 2 -1.9312854
 1 2009 12 1  0.1558393
 1 2010  8 1  0.9051487
 2 2001 12 2 -0.5480566
 2 2002 12 2 -0.7607420
 2 2003  3 2 -0.8094283
 2 2004  3 2 -0.1732794
</code>```

I would like to sum up (grouped by id) v1 of consecutive years (so 2010 and 2009, 2009 and 2008 and so on) only if x and y match. Expected output:

```<code>id year        res
 1 2010         NA
 1 2009         NA
 1 2008         NA
 1 2007  1.4465230
 2 2004 -0.9827077
 2 2003         NA
 2 2002 -1.3087987
</code>```

The oldest year per id is removed, as there is no preceding year.

I have a slow lapply solution in place but would like to speed things up, as my data is rather large.

Data:

```<code>set.seed(1)
dat <- data.frame(id = c(rep(1,5),rep(2,4)),year = c(2006:2010,2001:2004),
                x = c(12,12,12,12,8,12,12,3,3), y = c(1,1,2,1,1,2,2,2,2),
                v1 = rnorm(9))
</code>```

Current Solution:

```<code>require(dplyr)

myfun <- function(dat) { do.call(rbind,lapply(rev(unique(dat$year)[-1]),
            function(z) inner_join(dat[dat$year==z,2:5],
            dat[dat$year==z-1,2:5],
            by=c("x","y")) %>%
            summarise(year = z, res = ifelse(nrow(.) < 1,NA,sum(v1.x,v1.y)))))
        }

dat %>% group_by(id) %>% do(myfun(.))
</code>```

答:
Here is a data.table solution, I think.

```<code>datNew <- setDT(dat)[, .(year=year, res=(v1+shift(v1)) * NA^(x != shift(x) | y != shift(y))),
                     by=id][-1, .SD, by=id][]
   id year        res
1:  1 2007 -0.4428105
2:  1 2008         NA
3:  1 2009         NA
4:  1 2010         NA
5:  2 2001         NA
6:  2 2002 -0.3330393
7:  2 2003         NA
8:  2 2004  1.3141061
</code>```

Here, the j statement contains a list with two elements, the year and a function. This function sums values with the lagged value, using shift, but is multiplied by NA or 1 depending on whether the x and y match with their lagged values. This calculation is performed by id. The output is fed to a second chain, which drops the first observation of each id which is all NA.

You can adjust the order efficiently using setorder if desired.

```<code>setorder(datNew, id, -year)

datNew
   id year        res
1:  1 2010         NA
2:  1 2009         NA
3:  1 2008         NA
4:  1 2007 -0.4428105
5:  2 2004  1.3141061
6:  2 2003         NA
7:  2 2002 -0.3330393
8:  2 2001         NA
</code>```

Title: Speeding up rowwise comparison

Body:
I have a data.frame like the following:

id year  x y         v1
 1 2006 12 1  0.8510703
 1 2007 12 1  0.5954527
 1 2008 12 2 -1.9312854
 1 2009 12 1  0.1558393
 1 2010  8 1  0.9051487
 2 2001 12 2 -0.5480566
 2 2002 12 2 -0.7607420
 2 2003  3 2 -0.8094283
 2 2004  3 2 -0.1732794

I would like to sum up (grouped by id) v1 of consecutive years (so 2010 and 2009, 2009 and 2008 and so on) only if x and y match. Expected output:

id year        res
 1 2010         NA
 1 2009         NA
 1 2008         NA
 1 2007  1.4465230
 2 2004 -0.9827077
 2 2003         NA
 2 2002 -1.3087987

The oldest year per id is removed, as there is no preceding year.

I have a slow lapply solution in place but would like to speed things up, as my data is rather large.

Data:

set.seed(1)
dat <- data.frame(id = c(rep(1,5),rep(2,4)),year = c(2006:2010,2001:2004),
                x = c(12,12,12,12,8,12,12,3,3), y = c(1,1,2,1,1,2,2,2,2),
                v1 = rnorm(9))

Current Solution:

require(dplyr)

myfun <- function(dat) { do.call(rbind,lapply(rev(unique(dat$year)[-1]),
            function(z) inner_join(dat[dat$year==z,2:5],
            dat[dat$year==z-1,2:5],
            by=c("x","y")) %>%
            summarise(year = z, res = ifelse(nrow(.) < 1,NA,sum(v1.x,v1.y)))))
        }

dat %>% group_by(id) %>% do(myfun(.))

Body:
Here is a data.table solution, I think.

datNew <- setDT(dat)[, .(year=year, res=(v1+shift(v1)) * NA^(x != shift(x) | y != shift(y))),
                     by=id][-1, .SD, by=id][]
   id year        res
1:  1 2007 -0.4428105
2:  1 2008         NA
3:  1 2009         NA
4:  1 2010         NA
5:  2 2001         NA
6:  2 2002 -0.3330393
7:  2 2003         NA
8:  2 2004  1.3141061

Here, the j statement contains a list with two elements, the year and a function. This function sums values with the lagged value, using shift, but is multiplied by NA or 1 depending on whether the x and y match with their lagged values. This calculation is performed by id. The output is fed to a second chain, which drops the first observation of each id which is all NA.

You can adjust the order efficiently using setorder if desired.

setorder(datNew, id, -year)

datNew
   id year        res
1:  1 2010         NA
2:  1 2009         NA
3:  1 2008         NA
4:  1 2007 -0.4428105
5:  2 2004  1.3141061
6:  2 2003         NA
7:  2 2002 -0.3330393
8:  2 2001         NA


问:
How to latebind COM event without interface
I need to late bind to a 3rd party VB6 COM object in a 3.5 C# application (to avoid version dependencies that we currently have). The dll that was provided is not consumable in most non-latebound ways due to some bug that causes errors when we try to consume it normally. Currently, we are using a custom VB6 wrapper that makes things VERY version specific, however I have found that I can use late-binding to access properties and methods. Now, I am trying to late-bind to events, however everything I have read says that I need to inherit from the COM wrapper's interface to create the event sinks that are needed. Here is one such article.

So, my question is whether it is possible to perform late-bound event handling without having any reference to the dll at compile time?

UPDATE

Here are the errors I have with the VB6 wrapper (Which is still being actively updated).

In OleViewer, I get

Could not decompile selected item Error loading type library/DLL.
  TYPE_E_CANTLOADLIBRARY ($80029C4A)

In Visual Studio I get:

Could not determine the dependencies of the COM reference
  "3rdPartyDLL". Error loading type library/DLL. (Exception from
  HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))

答:
From here:

I found that the problem is caused when the IDL contains an importlib
  to another project's .tlb typelib.

This seems to create a dependency between one dll and the other.

If dependant dll is missing OLEView refuses to display the dependent
  dll, which also manifests itself by not allowing #import from C++
  code.

Therefore I would look carefully at the COM dependencies of the DLL in question and make sure they are all registered as well.

It also goes on to add:

...because both dlls are co-dependent,
  components from each interact (via interface declarations on method
  signatures) and use #import from each others typelib.

Therefore, unless both target dlls are present, neither can be
  rebuilt. As you can imagine, this causes a terrible problem when you
  try to completely rebuild the project's from scratch.

I've experimented with separating the interface definitions into
  smaller IDL files...

Edit: here's a recent example of this problem coming about (I believe). I had a C# library exported to COM. Modifications to that library were made which changed the interface of several classes, but the library GUID was not changed. Also see here about risks of AutoDual which was in use.

Here's the odd part - the VB6 DLL was rebuilt referencing the modified C# DLL. It compiled fine. no errors. But its typelib was corrupt - OleView couldn't open it, failing with TYPE_E_CANTLOADLIBRARY. Changing the C# DLL GUID was necessary to get the VB6 DLL recompiled successfully.

Clearly a pitfall of VB6 / C# interop.


问:
Short Circuit a controller action with xhr for rails
Is there a way to short-circuit an action with a method and ensure that other methods aren't called afterwards in Rails?

```<code>def update
   return head(:unauthorized) unless available_user_settings?
   if setting.update....
   ...
end
</code>```

I would like to do something more like:

```<code>def update
   ensure_settings_modifiable!
   if setting.update....
   ...
end
</code>```

But I don't know of a good way to render head and stop the rest of the action if the settings should not be updated.

答:
You could have:</p>

```<code>def update
  # stop action if `false` is returned. Otherwise continue
  settings_modifiable? or return
  ...
end
</code>```

Body:
Is there a way to short-circuit an action with a method and ensure that other methods aren't called afterwards in Rails?

def update
   return head(:unauthorized) unless available_user_settings?
   if setting.update....
   ...
end

I would like to do something more like:

def update
   ensure_settings_modifiable!
   if setting.update....
   ...
end

But I don't know of a good way to render head and stop the rest of the action if the settings should not be updated.

Body:
You could have:

def update
  # stop action if `false` is returned. Otherwise continue
  settings_modifiable? or return
  ...
end


问:
unity C# bool and to set false by time....?
this is My Code:

```<code>if ( run && Input.GetKeyDown (KeyCode.K)) {
    anim.SetInteger ("State", 4);
    slide = true;
}

if (Input.GetKeyUp (KeyCode.K)) {
    slide = false;
    anim.SetInteger ("State", 0);
}
</code>```

My problem: if I hold the (KeyCode.K) than slide is still true which I don´t want.

I need set slide to true just once, or to false after 2 seconds only.

I hope you all understand what I want.

答:
I would suggest making slide a property which will set your integer :

```<code>public bool Slide
{
    get { return slide; }
    set
    {
        if ( value == slide ) return;

        slide = value;

        if( slide ) anim.SetInteger("State", 4);
        else anim.SetInteger("State", 0);
    }
}
</code>```

One of the many possible options would be to create a Coroutine that just resets the flag back to false :

```<code>IEnumerator StartSlide()
{
    const float MAX_TIME = 2.0f; // time to wait before resetting the flag
    Slide = true;
    float timeNow = 0.0f;
    while ( timeNow < MAX_TIME && Slide )
    {
       timeNow += Time.deltaTime;
       yield return new WaitForEndOfFrame();
    }
    Slide = false;
}
</code>```

And to use this you can call :

```<code>if ( run && Input.GetKeyDown(KeyCode.K) && !Slide )
{
     StartCoroutine(StartSlide());
}
</code>```

You can also use this with GetKeyUp method :

```<code>if ( Input.GetKeyUp(KeyCode.K) && Slide )
{
    Slide = false;
}
</code>```

Body:
this is My Code:

if ( run && Input.GetKeyDown (KeyCode.K)) {
    anim.SetInteger ("State", 4);
    slide = true;
}

if (Input.GetKeyUp (KeyCode.K)) {
    slide = false;
    anim.SetInteger ("State", 0);
}

My problem: if I hold the (KeyCode.K) than slide is still true which I don´t want.

I need set slide to true just once, or to false after 2 seconds only.

I hope you all understand what I want.

Body:
I would suggest making slide a property which will set your integer :

public bool Slide
{
    get { return slide; }
    set
    {
        if ( value == slide ) return;

        slide = value;

        if( slide ) anim.SetInteger("State", 4);
        else anim.SetInteger("State", 0);
    }
}

One of the many possible options would be to create a Coroutine that just resets the flag back to false :

IEnumerator StartSlide()
{
    const float MAX_TIME = 2.0f; // time to wait before resetting the flag
    Slide = true;
    float timeNow = 0.0f;
    while ( timeNow < MAX_TIME && Slide )
    {
       timeNow += Time.deltaTime;
       yield return new WaitForEndOfFrame();
    }
    Slide = false;
}

And to use this you can call :

if ( run && Input.GetKeyDown(KeyCode.K) && !Slide )
{
     StartCoroutine(StartSlide());
}

You can also use this with GetKeyUp method :

if ( Input.GetKeyUp(KeyCode.K) && Slide )
{
    Slide = false;
}


问:
Login to website from WinForms
How can I make a winform application which enables me to log in to a website from my desktop?</p>

答:
Many ways

1- Use WebBrowser Control and Navigate to your website , and do login into your web site.

2- Use HttpWebRequest class and use Credentials property

easiest way is option no 1

Title: Login to website from WinForms


问:
How do I use the access token in Loopback?
I am trying to use Loopback as a mobile backend.

I am also following this example: http://docs.strongloop.com/display/public/LB/Introducing+the+Coffee+Shop+Reviews+app

After I login on my iOS device, I receive an access token. All good.
Now I want to call an endpoint that requires authentication. Just calling the endpoint gets me the message "AUTHENTICATION REQUIRED".

So I try to attach the access token to the request parameters as {"access_token":"1241341234513..."}. However, nothing happens.

What I'm confused by is that on the web application, there's no need to directly send the access token. How can I make this work on my mobile client?

答: You would need to make sure you send access_token in header of request every time or you can send access_token='value' as query string in url.</p>


问:
What are sessions? How do they work?
I am just beginning to start learning web application development, using python. I am coming across the terms 'cookies' and 'sessions'. I understand cookies in that they store some info in a key value pair on the browser. But I have a little confusion regarding sessions, in a session too we store data in a cookie on the user's browser.

For example - I login using username='rasmus' and password='default'. In such a case the data will be posted to the server which is supposed to check and log me in if authenticated. However during the entire process the server also generates a session ID which will be stored in a cookie on my browser. Now the server also stores this session ID in its file system or datastore.

But based on just the session ID, how would it be able to know my username during my subsequent traversal through the site? Does it store the data on the server as a dict where the key would be a session ID and details like username, email etc. be the values?

I am getting quite confused here. Need help.

答:
Think of HTTP as a person(A) who has SHORT TERM MEMORY LOSS and forgets every person as soon as that person goes out of sight.

Now, to remember different persons, A takes a photo of that person and keeps it. Each Person's pic has an ID number. When that person comes again in sight, that person tells it's ID number to A and A finds their picture by ID number.
And voila !!, A knows who is that person.

Same is with HTTP. It is suffering from SHORT TERM MEMORY LOSS. It uses Sessions to record everything you did while using a website, and then, when you come again, it identifies you with the help of Cookies(Cookie is like a token).
Picture is the Session here, and ID is the Cookie here.

Title: What are sessions? How do they work?


问:
How to store table with particular column should stored in array and retrieve it in Angularjs (Mean Stack)
all

Iam using Mean stack angularjs and mongodb now i have form like get the person information it's stored normal like table.my need is i have fields like this

Html code

```<code><!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>

    <script src="Controller/MongooseCrud.js"></script>
<title>Page Title</title>
</head>
<body>

    Name <input type="text" ng-model="user.name" > </br></br>
    Details</br></br>

    age:<input type="text"  ng-model="user.age"> </br></br>
     address:   <input type="text"  ng-model="user.address"> </br></br>
     Contact no:<input type="text" ng-model="user.number" > </br></br>

     <input type=button value=submit ng-click="Add()">

</body>
</html>
</code>```

Controller Code

```<code>   $scope.Add = function () {
        $http.post('/AddNewuser', $scope.user).success(function (response) {
            refresh();
        });
    };
</code>```

Server Code

```<code>app.post('/AddNewuser', function (req, res) {

    console.log(req.body);
    db.Users.insert(req.body, function (err, docs) {

        res.json(docs);
    });
});
</code>```

it's store like table value's i want stored array inside the column

答:
If you have no schema then you can try it

```<code>app.post('/AddNewuser', function (req, res) {

    console.log(req.body);
    var newUser = {
            name: req.body.name,
            details:{
                age: req.body.age,
                address: req.body.address,
                contactNo: req.body.contactNo
            }
       };
    db.Users.save(newUser , function (err, doc) {
        if(err) {
            console.log(err);
            return res.status(500).send('Error occurred');
        }
        return res.status(200).json(doc);
    });
});
</code>```

N.B: Here I created details as a object instead of array

Body:
all

Iam using Mean stack angularjs and mongodb now i have form like get the person information it's stored normal like table.my need is i have fields like this

Html code

<!DOCTYPE html>

<title>Page Title</title>

    Name <input type="text" ng-model="user.name" >

    Details

    age:<input type="text"  ng-model="user.age">

     address:   <input type="text"  ng-model="user.address">

     Contact no:<input type="text" ng-model="user.number" >

     <input type=button value=submit ng-click="Add()">

Controller Code

   $scope.Add = function () {
        $http.post('/AddNewuser', $scope.user).success(function (response) {
            refresh();
        });
    };

Server Code

app.post('/AddNewuser', function (req, res) {

    console.log(req.body);
    db.Users.insert(req.body, function (err, docs) {

        res.json(docs);
    });
});

it's store like table value's i want stored array inside the column

Body:
If you have no schema then you can try it

app.post('/AddNewuser', function (req, res) {

    console.log(req.body);
    var newUser = {
            name: req.body.name,
            details:{
                age: req.body.age,
                address: req.body.address,
                contactNo: req.body.contactNo
            }
       };
    db.Users.save(newUser , function (err, doc) {
        if(err) {
            console.log(err);
            return res.status(500).send('Error occurred');
        }
        return res.status(200).json(doc);
    });
});

N.B: Here I created details as a object instead of array


问:
Is it possible to process the push notification data in Windows Phone 7
i have a question for my student project.

I am currently using push notification an the Windows Phone 7 and wanted to ask if it is possible - like as it is in Android - to process the delivered data in background, creating a wakelock or something.

Here the scenerio how it works in Android:
1. I send a notification to the device (more precise to the C2DM Server, but that doesn't matters now).
2. The App receives my notification while it is closed, shows a tile on the screens and saves the data in a database so i can work with them later.

Is it possible to store the data received by a push notification in a database/isolated storage in Windows Phone 7 while the Application is not running?

答: This capability isn't exposed directly by the API at the moment. However, there is nothing stopping you calling back to your web service after the user taps your toast notification to query for any data that needs to be passed along.</p>