问:
Android Gradle Plugin 1.1.0 - getNdkFolder() not found anymore, any replacement?
I just updated android Gradle plugin to 1.1.0 from 1.0.0, and I got this error:

No signature of method:
  com.android.build.gradle.LibraryPlugin.getNdkFolder() is applicable
  for argument types: () values: []

I tried to find diff of gradle plugin 1.0.0 to 1.1.0 but couldn't find anywhere online.

Seems like getNdkFolder method has been either changed or removed.

Is there a replacement ? Or any other way to get NdkFolder ?

I'm using that method like this,

def ndkDir = project.plugins.findPlugin ( 'com.android.library'
  ).getNdkFolder ()

I have also filed an issue against tools team in Android issue tracker: https://code.google.com/p/android/issues/detail?id=152810

Thank you !

答:
I am using gradle 2.2.3 version. The think that worked for me:

def ndkDir = project.android.ndkDirectory

Ref. Link: https://code.google.com/p/android/issues/detail?id=152810


来源: stackexchange

问:
Compute weighted sums on rolling window with pandas dataframes of different length
I have a large dataframe > 5000000 rows that I am performing a rolling calculation on.

```<code>df = pd.DataFrame(np.randn(10000,1), columns = ['rand'])
sum_abs = df.rolling(5).sum()
</code>```

I would like to do the same calculations but add in a weighted sum.

```<code>df2 = pd.DataFrame(pd.Series([1,2,3,4,5]), name ='weight'))
df3 = df.mul(df2.set_index(df.index)).rolling(5).sum()
</code>```

However, I am getting a Length Mismatch expected axis has 5 elements error.
I know I could do something like [a *b for a, b in zip(L, weight)] if I converted everything to a list but I would like to keep it in a dataframe if possible. Is there a way to multiply against different size frames or do I need to repeat the set of numbers the length of the dataset I'm multiplying against?

答:
Easy way to do this is

```<code>w = np.arange(1, 6)
df.rolling(5).apply(lambda x: (x * w).sum())
</code>```

A less easy way using strides

```<code>from numpy.lib.stride_tricks import as_strided as strided

v = df.values
n, m = v.shape
s1, s2 = v.strides
k = 5
w = np.arange(1, 6).reshape(1, 1, k)
pd.DataFrame(
    (strided(v, (n - k + 1, m, k), (s1, s2, s1)) * w).sum(-1),
    df.index[k - 1:], df.columns)
</code>```

naive time test

ContentLicense: CC BY-SA 3.0

Body:
I have a large dataframe > 5000000 rows that I am performing a rolling calculation on.

df = pd.DataFrame(np.randn(10000,1), columns = ['rand'])
sum_abs = df.rolling(5).sum()

I would like to do the same calculations but add in a weighted sum.

df2 = pd.DataFrame(pd.Series([1,2,3,4,5]), name ='weight'))
df3 = df.mul(df2.set_index(df.index)).rolling(5).sum()

However, I am getting a Length Mismatch expected axis has 5 elements error.
I know I could do something like [a *b for a, b in zip(L, weight)] if I converted everything to a list but I would like to keep it in a dataframe if possible. Is there a way to multiply against different size frames or do I need to repeat the set of numbers the length of the dataset I'm multiplying against?

Body:
Easy way to do this is

w = np.arange(1, 6)
df.rolling(5).apply(lambda x: (x * w).sum())

A less easy way using strides

from numpy.lib.stride_tricks import as_strided as strided

v = df.values
n, m = v.shape
s1, s2 = v.strides
k = 5
w = np.arange(1, 6).reshape(1, 1, k)
pd.DataFrame(
    (strided(v, (n - k + 1, m, k), (s1, s2, s1)) * w).sum(-1),
    df.index[k - 1:], df.columns)

naive time test


问:
arrays in arrays weird thing? Java
I have a variable B that stores how many user objects have been added in the array userarr. I'm using one line of code that adds a note that the user types in to the B element user object in the userarr array. Here it is:

```<code>userarr[login].notes[b] = tempnote;
</code>```

tempnote is a string variable that temporarily holds the note the user types in, and login stores the user number that you are logged in to. So it assigns the string variable tempnote to the login value user object in the user array, and in element b element in the notes array for that user.

But for some reason there is a problem with this line of code.
I know it is that line of code, because it happens right after you confirm you want to add that note, and there is a println right next to it that never appears.

Here is the method for the whole note thing:

```<code> public static void loggedin() {
     System.out.println("welcome, " + userarr[login].username + "!");
     do{
         System.out.println("type 'notes' to list current notes, type 'new' to add notes, type 'delete' to delete a note, or type 'exit' to exit the program.");
         switch(scan.nextLine()){
             case "exit":
                 System.out.println("exiting");
                 login = -1;
                 break;
              case "delete":

                 break;
              case "new":
                 System.out.println("\n\nType the note.");
                 String tempnote = scan.nextLine();
                 System.out.println("note is is now " + tempnote + ". is this what you want? type 'yes' to proceed, or 'no' to enter note again.");
                 String ch5 = scan.nextLine();
                 if (ch5.equals("no")) {
                     break;
                 } else {
                    userarr[login].notes[b] = tempnote;
                    System.out.println("note created!");
                    b += 1;
                 }
                 break;
             case "notes":
                 for (int i=0;i<b;i++) {
                     System.out.println("Note " + i + ":");
                     System.out.println(userarr[login].notes[i] + "\n");
                 }
                 break;
             default:
                 System.out.println("restarting.");

         };
     }while(login != -1);
}
</code>```

Here is the user object thing:

```<code> static class user extends TextGame {
     String username;
     int password;
     String[] notes;

     public user(String username, int password) {
        this.username = username;
        this.password = password;
     }

 }
 static user[] userarr = new user[10];
 static int a = 0;
 static int b = 0;
 static int login = -1;
</code>```

There is no error before i run it. when i get to the part that has the problem it says:

```<code>Exception in thread "main" java.lang.NullPointerException
at text.game.TextGame.loggedin(TextGame.java:80)
at text.game.TextGame.login(TextGame.java:53)
at text.game.TextGame.main(TextGame.java:135)
</code>```

anyone know the problem?

EDIT: It seems necessary to show the whole class, because there is apparently a lot more information people need to know. So here is the whole thing for you to have all the information you need:

```<code>package text.game;
import java.util.Scanner;

public class TextGame {

    static Scanner scan = new Scanner(System.in);
    static class user extends TextGame {
        String username;
        int password;
        String[] notes;

        public user(String username, int password) {
            this.username = username;
            this.password = password;
        }

     }
     static user[] userarr = new user[10];
     static int a = 0;
     static int b = 0;
     static int login = -1;

     public static void newuser() {
         System.out.println("\n\nType the username for this user.");
         String usernameA = scan.nextLine();
         System.out.println("Username is now " + usernameA + ". is this what you want? type 'yes' to proceed, or 'no' to enter username again.");
         if (scan.nextLine().equals("no")) {
             newuser();
         } else {
             System.out.println("\n\n type the password for this user. (numbers only.)");
             int passwordA = scan.nextInt();
             System.out.println("user is " + usernameA + " and password is " + passwordA + ". creating user.");
             userarr[a] = new user(usernameA, passwordA);
             System.out.println("user created!");
             a += 1;
         }
     }

     public static void login() {
         System.out.println("which account do you want to log into? type the name of a user, or type 'list' to view the users signed in.");
         String ch2 = scan.nextLine();
         if (ch2.equals("list")){
             for (int i=0;i<a;i++) {
                 System.out.println(userarr[i].username);
             }
         } else {
             for (int i=0;i<a;i++) {if ((userarr[i].username).equals(ch2)){
                  System.out.println("type the password for this account (USE NUMBERS ONLY).");
                  int ch4 = scan.nextInt();
                  if (ch4==userarr[i].password) {
                      System.out.println("logged in!"); login = i; loggedin();
                  }else{
                      System.out.print("incorrect password!");
                  }
             }
         }
     }
 }

 public static void loggedin() {
     System.out.println("welcome, " + userarr[login].username + "!");
     do{
         System.out.println("type 'notes' to list current notes, type 'new' to add notes, type 'delete' to delete a note, or type 'exit' to exit the program.");
         switch(scan.nextLine()){
             case "exit":
                 System.out.println("exiting");
                 login = -1;
                 break;
             case "delete":

                 break;
             case "new":
                 System.out.println("\n\nType the note.");
                 String tempnote = scan.nextLine();
                 System.out.println("note is is now " + tempnote + ". is this what you want? type 'yes' to proceed, or 'no' to enter note again.");
                String ch5 = scan.nextLine();
                if (ch5.equals("no")) {
                    break;
                } else {
                    userarr[login].notes[b] = tempnote;
                    System.out.println("note created!");
                    b += 1;
                }
                break;
            case "notes":
                for (int i=0;i<b;i++) {
                    System.out.println("Note " + i + ":");
                    System.out.println(userarr[login].notes[i] + "\n");
                }
                break;
            default:
                System.out.println("restarting.");

        };
    }while(login != -1);
}

 public static void main(String[] args) {
     do {
         System.out.println("Welcome to LINCOLN COMP console OS. Type 'new' to create a new user, type 'log' to log in to an existing user, or type 'exit' to leave.\nif you are asked a yes or no question, if you type something other than yes or no, it will default to yes.");
         String ch1 = scan.nextLine();
         switch (ch1) {
             case "new":
                 if (a==2) {
                     System.out.println("maximum users have been created. type a username to delete that user, type list to list users, or type back to return.");
                     String ch3 = scan.nextLine();
                     if (ch3.equals("list")) {
                         for (int i=0;i<a;i++) {
                              if (userarr[i].username==null) {
                                  System.out.println("undefined");
                              }else{
                                  System.out.println("\n" + userarr[i].username);
                              };
                          }
                     } else if (ch3.equals("back")) {
                         break;
                     } else {
                          for (int i=0;i<a;i++) {
                              if ((userarr[i].username).equals(ch3)){
                                  System.out.println("type the password for this account (USE NUMBERS ONLY).");
                                  int ch4 = scan.nextInt();
                                  if (ch4==userarr[i].password) {
                                      a --;
                                      userarr[i] = null;
                                      System.out.println("user deleted!");
                                      break;
                                  }else{
                                      System.out.println("incorrect password.");
                                      break;
                                  }

                              }else if (i==a-1) {
                                  System.out.println("user not found.");
                                  break;
                              }

                          }

                     }
                 }else {
                     System.out.println("Initializing user creation method:");
                     newuser();
                 }
                 break;
             case "log":
                 login();
                 break;
             case "exit":
                 System.out.println("Goodbye!");
                 System.exit(0);
                 break;
             case "debug":
                 for (int i=0;i<userarr.length;i++) {
                     System.out.println(userarr[i]);
                 }
                 break;
             default:
                 System.out.println("restarting.");
         }

     } while (true);
 }

}//Note from other user - Extra bracket?
</code>```

答:
I noticed that you don't appear to be checking if there are next lines/ints whenever you use your scanner's next functions.

Take these two lines from your code for example...

```<code>String ch2 = scan.nextLine();

int ch4 = scan.nextInt();
</code>```

You can check if there is indeed a next int, or next line by using the hasNext functions...

```<code>String ch2; //Declared outside of the if-statement for scope reasons
if(scan.hasNextLine()){
    //the hasNext functions return true if there is a next line (or int for hasNextInt).
    ch2 = scan.nextLine();
}else{
    //if something needs to be done in the event that there is no nextLine, do it here
}

int ch4;
if(scan.hasNextInt()){
    ch4 = scan.hasNextInt();
}else{
    //if something needs to be done in the event that there is no nextInt, do it here
}
</code>```

This might not solve your issue; however, this at least can prevent many potential issues later. You should always be sure there is more content to get before you get it, and using the hasNext functions make it very easy.

See more at https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Title: arrays in arrays weird thing? Java

Body:
I have a variable B that stores how many user objects have been added in the array userarr. I'm using one line of code that adds a note that the user types in to the B element user object in the userarr array. Here it is:

userarr[login].notes[b] = tempnote;

tempnote is a string variable that temporarily holds the note the user types in, and login stores the user number that you are logged in to. So it assigns the string variable tempnote to the login value user object in the user array, and in element b element in the notes array for that user.

But for some reason there is a problem with this line of code.
I know it is that line of code, because it happens right after you confirm you want to add that note, and there is a println right next to it that never appears.

Here is the method for the whole note thing:

 public static void loggedin() {
     System.out.println("welcome, " + userarr[login].username + "!");
     do{
         System.out.println("type 'notes' to list current notes, type 'new' to add notes, type 'delete' to delete a note, or type 'exit' to exit the program.");
         switch(scan.nextLine()){
             case "exit":
                 System.out.println("exiting");
                 login = -1;
                 break;
              case "delete":

                 break;
              case "new":
                 System.out.println("\n\nType the note.");
                 String tempnote = scan.nextLine();
                 System.out.println("note is is now " + tempnote + ". is this what you want? type 'yes' to proceed, or 'no' to enter note again.");
                 String ch5 = scan.nextLine();
                 if (ch5.equals("no")) {
                     break;
                 } else {
                    userarr[login].notes[b] = tempnote;
                    System.out.println("note created!");
                    b += 1;
                 }
                 break;
             case "notes":
                 for (int i=0;i<b;i++) {
                     System.out.println("Note " + i + ":");
                     System.out.println(userarr[login].notes[i] + "\n");
                 }
                 break;
             default:
                 System.out.println("restarting.");

         };
     }while(login != -1);
}

Here is the user object thing:

 static class user extends TextGame {
     String username;
     int password;
     String[] notes;

     public user(String username, int password) {
        this.username = username;
        this.password = password;
     }

 }
 static user[] userarr = new user[10];
 static int a = 0;
 static int b = 0;
 static int login = -1;

There is no error before i run it. when i get to the part that has the problem it says:

Exception in thread "main" java.lang.NullPointerException
at text.game.TextGame.loggedin(TextGame.java:80)
at text.game.TextGame.login(TextGame.java:53)
at text.game.TextGame.main(TextGame.java:135)

anyone know the problem?

EDIT: It seems necessary to show the whole class, because there is apparently a lot more information people need to know. So here is the whole thing for you to have all the information you need:

package text.game;
import java.util.Scanner;

public class TextGame {

    static Scanner scan = new Scanner(System.in);
    static class user extends TextGame {
        String username;
        int password;
        String[] notes;

        public user(String username, int password) {
            this.username = username;
            this.password = password;
        }

     }
     static user[] userarr = new user[10];
     static int a = 0;
     static int b = 0;
     static int login = -1;

     public static void newuser() {
         System.out.println("\n\nType the username for this user.");
         String usernameA = scan.nextLine();
         System.out.println("Username is now " + usernameA + ". is this what you want? type 'yes' to proceed, or 'no' to enter username again.");
         if (scan.nextLine().equals("no")) {
             newuser();
         } else {
             System.out.println("\n\n type the password for this user. (numbers only.)");
             int passwordA = scan.nextInt();
             System.out.println("user is " + usernameA + " and password is " + passwordA + ". creating user.");
             userarr[a] = new user(usernameA, passwordA);
             System.out.println("user created!");
             a += 1;
         }
     }

     public static void login() {
         System.out.println("which account do you want to log into? type the name of a user, or type 'list' to view the users signed in.");
         String ch2 = scan.nextLine();
         if (ch2.equals("list")){
             for (int i=0;i<a;i++) {
                 System.out.println(userarr[i].username);
             }
         } else {
             for (int i=0;i<a;i++) {if ((userarr[i].username).equals(ch2)){
                  System.out.println("type the password for this account (USE NUMBERS ONLY).");
                  int ch4 = scan.nextInt();
                  if (ch4==userarr[i].password) {
                      System.out.println("logged in!"); login = i; loggedin();
                  }else{
                      System.out.print("incorrect password!");
                  }
             }
         }
     }
 }

 public static void loggedin() {
     System.out.println("welcome, " + userarr[login].username + "!");
     do{
         System.out.println("type 'notes' to list current notes, type 'new' to add notes, type 'delete' to delete a note, or type 'exit' to exit the program.");
         switch(scan.nextLine()){
             case "exit":
                 System.out.println("exiting");
                 login = -1;
                 break;
             case "delete":

                 break;
             case "new":
                 System.out.println("\n\nType the note.");
                 String tempnote = scan.nextLine();
                 System.out.println("note is is now " + tempnote + ". is this what you want? type 'yes' to proceed, or 'no' to enter note again.");
                String ch5 = scan.nextLine();
                if (ch5.equals("no")) {
                    break;
                } else {
                    userarr[login].notes[b] = tempnote;
                    System.out.println("note created!");
                    b += 1;
                }
                break;
            case "notes":
                for (int i=0;i<b;i++) {
                    System.out.println("Note " + i + ":");
                    System.out.println(userarr[login].notes[i] + "\n");
                }
                break;
            default:
                System.out.println("restarting.");

        };
    }while(login != -1);
}

 public static void main(String[] args) {
     do {
         System.out.println("Welcome to LINCOLN COMP console OS. Type 'new' to create a new user, type 'log' to log in to an existing user, or type 'exit' to leave.\nif you are asked a yes or no question, if you type something other than yes or no, it will default to yes.");
         String ch1 = scan.nextLine();
         switch (ch1) {
             case "new":
                 if (a==2) {
                     System.out.println("maximum users have been created. type a username to delete that user, type list to list users, or type back to return.");
                     String ch3 = scan.nextLine();
                     if (ch3.equals("list")) {
                         for (int i=0;i<a;i++) {
                              if (userarr[i].username==null) {
                                  System.out.println("undefined");
                              }else{
                                  System.out.println("\n" + userarr[i].username);
                              };
                          }
                     } else if (ch3.equals("back")) {
                         break;
                     } else {
                          for (int i=0;i<a;i++) {
                              if ((userarr[i].username).equals(ch3)){
                                  System.out.println("type the password for this account (USE NUMBERS ONLY).");
                                  int ch4 = scan.nextInt();
                                  if (ch4==userarr[i].password) {
                                      a --;
                                      userarr[i] = null;
                                      System.out.println("user deleted!");
                                      break;
                                  }else{
                                      System.out.println("incorrect password.");
                                      break;
                                  }

                              }else if (i==a-1) {
                                  System.out.println("user not found.");
                                  break;
                              }

                          }

                     }
                 }else {
                     System.out.println("Initializing user creation method:");
                     newuser();
                 }
                 break;
             case "log":
                 login();
                 break;
             case "exit":
                 System.out.println("Goodbye!");
                 System.exit(0);
                 break;
             case "debug":
                 for (int i=0;i<userarr.length;i++) {
                     System.out.println(userarr[i]);
                 }
                 break;
             default:
                 System.out.println("restarting.");
         }

     } while (true);
 }

}//Note from other user - Extra bracket?

Body:
I noticed that you don't appear to be checking if there are next lines/ints whenever you use your scanner's next functions.

Take these two lines from your code for example...

String ch2 = scan.nextLine();

int ch4 = scan.nextInt();

You can check if there is indeed a next int, or next line by using the hasNext functions...

String ch2; //Declared outside of the if-statement for scope reasons
if(scan.hasNextLine()){
    //the hasNext functions return true if there is a next line (or int for hasNextInt).
    ch2 = scan.nextLine();
}else{
    //if something needs to be done in the event that there is no nextLine, do it here
}

int ch4;
if(scan.hasNextInt()){
    ch4 = scan.hasNextInt();
}else{
    //if something needs to be done in the event that there is no nextInt, do it here
}

This might not solve your issue; however, this at least can prevent many potential issues later. You should always be sure there is more content to get before you get it, and using the hasNext functions make it very easy.

See more at https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html


问:
How to get Display Name Attribute using PropertyDescriptor C# ASP.NET MVC 4
I am using property descriptor to generically iterate over the properties and print their attribute names as table header. It works fine printing the property name, but not for the [Display(Name = "Test")]

Class:

```<code>public class Transaction
{
    [Display(Name = "Test")]
    public string DELETE { get; set; }
    public string PARTNO { get; set; } //Part Number
</code>```

Markup:

```<code>    @foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(Model[0]))
    {
       <th onclick="tableColumnSort(this)" class="tableSortHeaderBtnStyle">@descriptor.DisplayName;</th>
    }
</code>```

Just prints the "DELETE" name rather than "Test".  The descriptor has a Name, and DisplayName option and both are set to "DELETE"

What am I doing wrong?

答: Use [DisplayName("Test")] in place of [Display(Name = "Test")]

Body:
I am using property descriptor to generically iterate over the properties and print their attribute names as table header. It works fine printing the property name, but not for the [Display(Name = "Test")]

Class:

public class Transaction
{
    [Display(Name = "Test")]
    public string DELETE { get; set; }
    public string PARTNO { get; set; } //Part Number

Markup:

    @foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(Model[0]))
    {
       @descriptor.DisplayName;
    }

Just prints the "DELETE" name rather than "Test".  The descriptor has a Name, and DisplayName option and both are set to "DELETE"

What am I doing wrong?


问:
Using 'Lock' in web applications
A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.

I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

```<code>lock(HitCounter)
{
   // Bla...
}
</code>```

However after some discussion he said, lock is good but never use it in web applications!

What is the basis behind his statement? Why shouldnt I use lock in web applications?

答:
lock is only intended to be used for multithreaded applications where multiple threads require access to the same shared variable, thus a lock is exclusively acquired by the requesting thread and all pending threads will block and wait until the lock is released.

in web applications, user requests are isolated so there is no need for locking by default

ContentLicense: CC BY-SA 2.5

Title: Using 'Lock' in web applications

Body:
A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.

I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

lock(HitCounter)
{
   // Bla...
}

However after some discussion he said, lock is good but never use it in web applications!

What is the basis behind his statement? Why shouldnt I use lock in web applications?


问:
Write random Python data to CSV file
I have a small python script that uses a library to generate random dates(mm/dd/yyyy) and random time based on a 12 hour clock..

```<code>def randomPhone():
    n ='0000000000'
    while '0' in n[3:6] or n[3:6]=='000':
    n = str(random.randint(10**9, 10**10-1))
    return n[:3] + '-' + n[3:6] + '-' + n[6:]
    randomPhone ()

def strTimeProp(start, end, format, prop):
    stime = time.mktime(time.strptime(start, format))
    etime = time.mktime(time.strptime(end, format))
    ptime = stime + prop * (etime - stime)
    return time.strftime(format, time.localtime(ptime))

def randomDate(start, end, prop):
    return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop)

print randomDate("1/1/2016 12:00 AM", "1/1/2017 12:00 AM", random.random())
</code>```

I have code to generate other random data, like names, and phone numbers. But first I want to write the date and time to a CSV file and make sure the formatting is correct. So the date and time are correctly displayed in a nicely formatted table, however when I try to add in the phoneNumber() argument I run into problems. The table displays when only the Date/Time argument is passed, and how I want it to looks, but with another section added onto the end for a Phone#, etc.

```<code>f = open("CDR.csv", 'wt')
try:
    writer = csv.writer(f)
    writer.writerow( ('Date/Time', 'Phone#') )
    for i in range(1):
        writer.writerow( (randomDate("1/1/2016 12:00 AM", "1/1/2017 12:00 AM", random.random())), randomPhone() )
finally:
    f.close()

print open("CDR.csv", 'rt').read()
</code>```

However I'm getting a typeError, `writerow() takes exactly one argument and two are given'

I'm following CSV Writing as an example.

答:
You've got your parentheses in the wrong place, causing you to pass two arguments to .writerow() instead of a single tuple.

Try separating your tuple creation from the function call. This should make the code easier to read.

```<code>row = (
    randomDate("1/1/2016 12:00 AM", "1/1/2017 12:00 AM", random.random()),
    randomPhone(),
)
writer.writerow(row)
</code>```

Title: Write random Python data to CSV file

Body:
I have a small python script that uses a library to generate random dates(mm/dd/yyyy) and random time based on a 12 hour clock..

def randomPhone():
    n ='0000000000'
    while '0' in n[3:6] or n[3:6]=='000':
    n = str(random.randint(10**9, 10**10-1))
    return n[:3] + '-' + n[3:6] + '-' + n[6:]
    randomPhone ()

def strTimeProp(start, end, format, prop):
    stime = time.mktime(time.strptime(start, format))
    etime = time.mktime(time.strptime(end, format))
    ptime = stime + prop * (etime - stime)
    return time.strftime(format, time.localtime(ptime))

def randomDate(start, end, prop):
    return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop)

print randomDate("1/1/2016 12:00 AM", "1/1/2017 12:00 AM", random.random())

I have code to generate other random data, like names, and phone numbers. But first I want to write the date and time to a CSV file and make sure the formatting is correct. So the date and time are correctly displayed in a nicely formatted table, however when I try to add in the phoneNumber() argument I run into problems. The table displays when only the Date/Time argument is passed, and how I want it to looks, but with another section added onto the end for a Phone#, etc.

f = open("CDR.csv", 'wt')
try:
    writer = csv.writer(f)
    writer.writerow( ('Date/Time', 'Phone#') )
    for i in range(1):
        writer.writerow( (randomDate("1/1/2016 12:00 AM", "1/1/2017 12:00 AM", random.random())), randomPhone() )
finally:
    f.close()

print open("CDR.csv", 'rt').read()

However I'm getting a typeError, `writerow() takes exactly one argument and two are given'

I'm following CSV Writing as an example.

Body:
You've got your parentheses in the wrong place, causing you to pass two arguments to .writerow() instead of a single tuple.

Try separating your tuple creation from the function call. This should make the code easier to read.

row = (
    randomDate("1/1/2016 12:00 AM", "1/1/2017 12:00 AM", random.random()),
    randomPhone(),
)
writer.writerow(row)


问:
How to disable <input "text"> if there is a value in column (inside moda)
Hi GoodMorning(here in philippines) :)

```<code>    I want to disable the <input ="text"> if there is a value in the dedicated column

        <?php
    $stmt = $db_con->prepare("SELECT * FROM userinfo WHERE role='student' AND gradelvl='7' AND sectionname='studid' ORDER BY lrnno ASC");
    $stmt->execute();
    $row=$stmt->fetch(PDO::FETCH_ASSOC)
    ?>
    <form action="71stgmodalaction.php" method="POST" class="form-horizontal">
        <div id="1stgrade7" class="modal fade">
        <div class="modal-dialog">
        <div class="modal-content">
        <div class="modal-header">
        <div class="form-group">

    <input type='text' name='id' value='studid'; ?>' />
            <h2 class="modal-title"><div align="center">Please Fill Correctly</div></h2>

    <div class="modal-header">
            <h4 class="modal-title"><div align="center">1st Grading Result</div></h4>
              </div>

    <div class="modal-body"><div align="left">
        <b>Filipino:</b><input type="text" class="resizedTextbox" name="c71stgfilipino" >
    </div>
    <div class="modal-footer">
        <button type="submit" name="submit71st"  class="btn btn-success">Save changes</button>
    </div>
    </div>
    </div>
    </div>
    </div>

    </form>
</code>```

Here is my action to update column

```<code> <?php

    if($_POST)
    {

    $id = $_POST['id'];
    $c7finalgfilipino = $_POST['c7finalgfilipino'];

    $stmt = $db_con->prepare("UPDATE userinfo SET c7finalgfilipino=:qc7finalgfilipino WHERE id=:id");
    $stmt->bindParam(":qc7finalgfilipino", $c7finalgfilipino);

    $stmt->bindParam(":id", $id);

    if($stmt->execute())
    {
        echo "Successfully updated";

    }
    else{
        echo "Query Problem";
    }
}

?>
</code>```

How can I disable the input type="text" name="c71sthfilipino" if the is a value in that text ?

hope that will understand what Im saying, Im sorry for my english grammar :)
Thanks in advance

答:
You disable it like this</p>

```<code><input type="text"
        class="resizedTextbox"
        name="c71stgfilipino"
<?php echo isset($row['column']) ? 'disabled' : '' ?> >
</code>```

Body:
Hi GoodMorning(here in philippines) :)

    I want to disable the <input ="text"> if there is a value in the dedicated column

        <?php
    $stmt = $db_con->prepare("SELECT * FROM userinfo WHERE role='student' AND gradelvl='7' AND sectionname='studid' ORDER BY lrnno ASC");
    $stmt->execute();
    $row=$stmt->fetch(PDO::FETCH_ASSOC)
    ?>
    <form action="71stgmodalaction.php" method="POST" class="form-horizontal">

    <input type='text' name='id' value='studid'; ?>' />

Please Fill Correctly

1st Grading Result

        Filipino:<input type="text" class="resizedTextbox" name="c71stgfilipino" >

        <button type="submit" name="submit71st"  class="btn btn-success">Save changes</button>

    </form>

Here is my action to update column

 <?php

    if($_POST)
    {

    $id = $_POST['id'];
    $c7finalgfilipino = $_POST['c7finalgfilipino'];

    $stmt = $db_con->prepare("UPDATE userinfo SET c7finalgfilipino=:qc7finalgfilipino WHERE id=:id");
    $stmt->bindParam(":qc7finalgfilipino", $c7finalgfilipino);

    $stmt->bindParam(":id", $id);

    if($stmt->execute())
    {
        echo "Successfully updated";

    }
    else{
        echo "Query Problem";
    }
}

?>

How can I disable the input type="text" name="c71sthfilipino" if the is a value in that text ?

hope that will understand what Im saying, Im sorry for my english grammar :)
Thanks in advance

Body:
You disable it like this

<input type="text"
        class="resizedTextbox"
        name="c71stgfilipino"
<?php echo isset($row['column']) ? 'disabled' : '' ?> >


问:
Out-Of-Browser Service Access problem using Silverlight 4
I have a Silverlight 4 application that access a couple of WCF Data Services.

There are no problems accessing the service through the browser.

I set the program to run out-of-browser with elevated trust.  Then I can see the calls to the WCF Service via fiddler, but nothing ever comes back.

If I debug then I get the following error:

```<code>$exception  {System.UnauthorizedAccessException: Invalid cross-thread access.
   at MS.Internal.XcpImports.CheckThread()
   at System.Windows.Controls.ItemCollection.GetValueInternal(DependencyProperty dp)
   at System.Windows.PresentationFrameworkCollection`1.get_CountImpl()
   at System.Windows.PresentationFrameworkCollection`1.get_Count()
   at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IItemContainerGenerator.RemoveAll()
   at System.Windows.Controls.ItemContainerGenerator.RemoveAll()
   at System.Windows.Controls.ItemContainerGenerator.OnRefresh()
   at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.ICollectionChangedListener.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   at System.Windows.Controls.WeakCollectionChangedListener.SourceCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.ItemCollection.NotifyCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.ItemCollection.System.Windows.Controls.ICollectionChangedListener.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.WeakCollectionChangedListener.SourceCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.ClearItems()
   at System.Collections.ObjectModel.Collection`1.Clear()
   at ClientFolderExplorer.ViewModels.DocumentExplorerViewModel.clientCatalog_ClientsLoadingComplete(Object sender, ClientLoadingEventArgs e)
   at ClientFolderExplorer.Catalogs.ClientCatalog.<>c__DisplayClass3.<ExecuteClientQuery>b__2(IAsyncResult a)}  System.Exception {System.UnauthorizedAccessException}
</code>```

Not sure where to start troubleshooting.  I have crossdomain.xml and clientaccesspolicy.xml files in place in the root of the webserver, but I cannot even see these files being requested (in fiddler).

Any Ideas?

答:
Yes - you suppose the problem is related to cross-site access, while in reality it's related to cross-thread access (first line of error indicates this clearly).

I'm assuming you're trying to set some UI element's data bound (or not, doesn't matter) property directly from the callback handling the service call. (edit) Forgot to clarify - where the callback is running on a thread different from the UI thread. Silverlight like most other frameworks disallows modifying UI except from the UI thread.

If so, take a look at how to use Dispatcher in order to switch back to the UI thread.

Body:
I have a Silverlight 4 application that access a couple of WCF Data Services.

There are no problems accessing the service through the browser.

I set the program to run out-of-browser with elevated trust.  Then I can see the calls to the WCF Service via fiddler, but nothing ever comes back.

If I debug then I get the following error:

$exception  {System.UnauthorizedAccessException: Invalid cross-thread access.
   at MS.Internal.XcpImports.CheckThread()
   at System.Windows.Controls.ItemCollection.GetValueInternal(DependencyProperty dp)
   at System.Windows.PresentationFrameworkCollection`1.get_CountImpl()
   at System.Windows.PresentationFrameworkCollection`1.get_Count()
   at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IItemContainerGenerator.RemoveAll()
   at System.Windows.Controls.ItemContainerGenerator.RemoveAll()
   at System.Windows.Controls.ItemContainerGenerator.OnRefresh()
   at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.ICollectionChangedListener.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   at System.Windows.Controls.WeakCollectionChangedListener.SourceCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.ItemCollection.NotifyCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.ItemCollection.System.Windows.Controls.ICollectionChangedListener.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.WeakCollectionChangedListener.SourceCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.ClearItems()
   at System.Collections.ObjectModel.Collection`1.Clear()
   at ClientFolderExplorer.ViewModels.DocumentExplorerViewModel.clientCatalog_ClientsLoadingComplete(Object sender, ClientLoadingEventArgs e)
   at ClientFolderExplorer.Catalogs.ClientCatalog.<>c__DisplayClass3.<ExecuteClientQuery>b__2(IAsyncResult a)}  System.Exception {System.UnauthorizedAccessException}

Not sure where to start troubleshooting.  I have crossdomain.xml and clientaccesspolicy.xml files in place in the root of the webserver, but I cannot even see these files being requested (in fiddler).

Any Ideas?


问:
Get the extension of a file contained in an NSString
I have an NSMutable dictionary that contains file IDs and their filename+extension in the simple form of fileone.doc or filetwo.pdf. I need to determine what type of file it is to correctly display a related icon in my UITableView. Here is what I have done so far.

```<code>NSString *docInfo = [NSString stringWithFormat:@"%d", indexPath.row]; //Determine what cell we are formatting
NSString *fileType = [contentFiles objectForKey:docInfo]; //Store the file name in a string
</code>```

I wrote two regex to determine what type of file I'm looking at, but they never return a positive result. I haven't used regex in iOS programming before, so I'm not entirely sure if I'm doing it right, but I basically copied the code from the Class Description page.

```<code>    NSError *error = NULL;
NSRegularExpression *regexPDF = [NSRegularExpression regularExpressionWithPattern:@"/^.*\\.pdf$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSRegularExpression *regexDOC = [NSRegularExpression regularExpressionWithPattern:@"/^.*\\.(doc|docx)$/" options:NSRegularExpressionCaseInsensitive error:&error];
    NSUInteger numMatch = [regexPDF numberOfMatchesInString:fileType options:0 range:NSMakeRange(0, [fileType length])];
    NSLog(@"How many matches were found? %@", numMatch);
</code>```

My questions would be, is there an easier way to do this? If not, are my regex incorrect? And finally if I have to use this, is it costly in run time? I don't know what the average amount of files a user will have will be.

Thank you.

答:
Try this, it works for me.

```<code>NSString *fileName = @"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
</code>```

Documentation here for NSString pathExtension

Body:
I have an NSMutable dictionary that contains file IDs and their filename+extension in the simple form of fileone.doc or filetwo.pdf. I need to determine what type of file it is to correctly display a related icon in my UITableView. Here is what I have done so far.

NSString *docInfo = [NSString stringWithFormat:@"%d", indexPath.row]; //Determine what cell we are formatting
NSString *fileType = [contentFiles objectForKey:docInfo]; //Store the file name in a string

I wrote two regex to determine what type of file I'm looking at, but they never return a positive result. I haven't used regex in iOS programming before, so I'm not entirely sure if I'm doing it right, but I basically copied the code from the Class Description page.

    NSError *error = NULL;
NSRegularExpression *regexPDF = [NSRegularExpression regularExpressionWithPattern:@"/^.*\\.pdf$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSRegularExpression *regexDOC = [NSRegularExpression regularExpressionWithPattern:@"/^.*\\.(doc|docx)$/" options:NSRegularExpressionCaseInsensitive error:&error];
    NSUInteger numMatch = [regexPDF numberOfMatchesInString:fileType options:0 range:NSMakeRange(0, [fileType length])];
    NSLog(@"How many matches were found? %@", numMatch);

My questions would be, is there an easier way to do this? If not, are my regex incorrect? And finally if I have to use this, is it costly in run time? I don't know what the average amount of files a user will have will be.

Thank you.

Body:
Try this, it works for me.

NSString *fileName = @"yourFileName.pdf";
NSString *ext = [fileName pathExtension];

Documentation here for NSString pathExtension


问:
TYPO3 Styling of selection Flexform
I have the following selection flexform

```<code><config>
    <type>select</type>
    <items type='array'>
        <numIndex index='0' type='array'>
            <numIndex index='0'>freie Plätze</numIndex>
            <numIndex index='1'>freie Plätze</numIndex>
        </numIndex>
        <numIndex index='1' type='array'>
            <numIndex index='0'>ausgebucht</numIndex>
            <numIndex index='1'>ausgebucht</numIndex>
        </numIndex>
    </items>
    (...)
</config>`
</code>```

I want to style the different answers with different colors in the FE

```<code>numIndex index='0' = green
numIndex index='1' = red
</code>```

but I don't find any solution so I can't offer any idea. Sorry for that.

I use TYPO3 7.6.16 with DCE and a fluid template with a responsive table

```<code><f:for each="{field.kurs}" as="kurs">
<tr>
    <td>(...)</td>
    <td data-label="Status">{kurs.kursStatus}</td>
    <td>(...)</td>
</tr>
(...)
</code>```

答:
Your select is in Flexform? Try this:

```<code><settings.offer>
    <TCEforms>
        <label>Offer</label>
        <config>
            <type>select</type>
            <renderType>selectSingle</renderType>
            <items>
                <numIndex index="1">
                    <numIndex index="0">freie Plätze</numIndex>
                    <numIndex index="1">free</numIndex>
                </numIndex>
                <numIndex index="2">
                    <numIndex index="0">ausgebucht</numIndex>
                    <numIndex index="1">booked-up</numIndex>
                </numIndex>
            </items>
        </config>
    </TCEforms>
</settings.offer>
</code>```

In template add css classes:

```<code><f:for each="{field.kurs}" as="kurs">
    <ul>
        <li>(...)</li>
        <li class="{f:if(condition: {settings.offer} == 'free', then: 'green', else 'red') }"></li>
        <li>(...)</li>
    </ul>
(...)
</code>```

Title: TYPO3 Styling of selection Flexform

Body:
I have the following selection flexform

<config>
    <type>select</type>
    <items type='array'>
        <numIndex index='0' type='array'>
            <numIndex index='0'>freie Plätze</numIndex>
            <numIndex index='1'>freie Plätze</numIndex>
        </numIndex>
        <numIndex index='1' type='array'>
            <numIndex index='0'>ausgebucht</numIndex>
            <numIndex index='1'>ausgebucht</numIndex>
        </numIndex>
    </items>
    (...)
</config>`

I want to style the different answers with different colors in the FE

numIndex index='0' = green
numIndex index='1' = red

but I don't find any solution so I can't offer any idea. Sorry for that.

I use TYPO3 7.6.16 with DCE and a fluid template with a responsive table

<f:for each="{field.kurs}" as="kurs">

    (...)
    {kurs.kursStatus}
    (...)

(...)

Body:
Your select is in Flexform? Try this:

<settings.offer>
    <TCEforms>
        <label>Offer</label>
        <config>
            <type>select</type>
            <renderType>selectSingle</renderType>
            <items>
                <numIndex index="1">
                    <numIndex index="0">freie Plätze</numIndex>
                    <numIndex index="1">free</numIndex>
                </numIndex>
                <numIndex index="2">
                    <numIndex index="0">ausgebucht</numIndex>
                    <numIndex index="1">booked-up</numIndex>
                </numIndex>
            </items>
        </config>
    </TCEforms>
</settings.offer>

In template add css classes:

<f:for each="{field.kurs}" as="kurs">
    <ul>
        <li>(...)</li>
        <li class="{f:if(condition: {settings.offer} == 'free', then: 'green', else 'red') }"></li>
        <li>(...)</li>
    </ul>
(...)


问:
Trouble with JQuery in Rails 5
I have used JQuery in Rails 5 before and understand the issue with turbolinks. I want my #title object to change color via .animate() when it gets hovered over. Here is my js file:

```<code>//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .

$(document).on('turbolinks:load', function(){
$('#title').hover(
    function(){
        $('#title').animate({'color': '#404a87'},400);
    },
    function(){
        $('#title').animate({'color': '#393939'},400);
    }
);
});
</code>```

Here is the object I am attempting to alter:

```<code><p id="title">SEABOLT DESIGN</p>
</code>```

I can't get anything to work on this object. I think the JQuery just isn't working. Can someone help? Thank you!

答:
Aggred to the official documentation of jquery.turbolinks

Turbolinks then needs to be at the end because it has to be the last to install the click handler, so not to interfere with other scripts.

you have to organize your file like this:

```<code>//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//
//= require_tree .
//
//= require turbolinks
</code>```

And place your Javascript in a new file in app/assets/javascripts/ path.

Title: Trouble with JQuery in Rails 5

Body:
I have used JQuery in Rails 5 before and understand the issue with turbolinks. I want my #title object to change color via .animate() when it gets hovered over. Here is my js file:

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .

$(document).on('turbolinks:load', function(){
$('#title').hover(
    function(){
        $('#title').animate({'color': '#404a87'},400);
    },
    function(){
        $('#title').animate({'color': '#393939'},400);
    }
);
});

Here is the object I am attempting to alter:

SEABOLT DESIGN

I can't get anything to work on this object. I think the JQuery just isn't working. Can someone help? Thank you!

Body:
Aggred to the official documentation of jquery.turbolinks

Turbolinks then needs to be at the end because it has to be the last to install the click handler, so not to interfere with other scripts.

you have to organize your file like this:

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//
//= require_tree .
//
//= require turbolinks

And place your Javascript in a new file in app/assets/javascripts/ path.


问:
The best implementation of a tableview in Model View Controller
What is the best implementation of a tableview in Model View Controller?
 I'm developing my app without storyboard, all programmatically .

Is it possible to implement a TableView in a UIView? I tried it, but If I implement the TableView in a view, when the controller recives a button action, I can't modify or access to the tableView of the View...

After that, I tried to implement the tableView in a ViewController and it works perfectly, but I don't know if this is a good implementation because I found the same problem when I wanted to implement a TextView/TextField with a Piker, for example.

My goal was to had a clean code of viewController with a views and controllers (of buttons etc) and now I find myself with a uiviewController with the view and multiples components when I wanted the components were in the corresponding views.

Thank you very much!

答:
It is all possible, and the problems you are running into are not because of it being something that you should not do, but that it is something that inherently works slightly differently than before. To answer your question directly, I would implement the tableView as the modal view controller directly, either as a UITableViewController or a UIViewController that inherits the table views delegate and datasource (this method being chosen if you don't want the table view to use up the entirety of the modal view controller's space).

TableViews are simple to use, but understanding every detail of how they work will make you far stronger and able to use them in any of these scenarios. I am not going to write you a guide on their use, butcontinue studying them before you declare that anything "can not be done".

Knowing what classes to implement the delegate methods becomes very important during these different scenarios. It is often easiest to use textfields delegate's implementation in UITableViewCell's subclass rather than in the UIViewController they are in. This allows for a more modular creation.

I find that working with the storyboard allows for a much quicker learning curve, and also a time saver. The one excuse I will give you for working without a storyboard is if you have an extremely slow computer.


问:
How to remove resize option present at the right bottom-corner of the textarea?
I'm trying to remove dots in a textarea which are present at the bottom-right corner.

Here's an example of what I mean (from Chrome):

How to remove those diagonal lines?

答:
html

sass

```<code>textarea {
  position: relative;
  z-index: 1;
  min-width: 1141px;
  min-height: 58px;
}

.resizer {
  position: relative;
  display: inline-block;
  &:after {
    content: "";
    border-top: 8px solid #1c87c7;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    -webkit-transform: rotate(-45deg);
    z-index: 1;
    opacity: 0.5;
    position: absolute;
    bottom: 1px;
    right: -3px;
    pointer-events: none;
  }
}
.arrow-resizer-textarea {
  height: 0;
  width: 0;
  border-top: 8px solid #1c87c7;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  -webkit-transform: rotate(-45deg);
  position: absolute;
  bottom: 1px;
  right: -3px;
  pointer-events: none;
  z-index: 2;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
html

sass

textarea {
  position: relative;
  z-index: 1;
  min-width: 1141px;
  min-height: 58px;
}

.resizer {
  position: relative;
  display: inline-block;
  &:after {
    content: "";
    border-top: 8px solid #1c87c7;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    -webkit-transform: rotate(-45deg);
    z-index: 1;
    opacity: 0.5;
    position: absolute;
    bottom: 1px;
    right: -3px;
    pointer-events: none;
  }
}
.arrow-resizer-textarea {
  height: 0;
  width: 0;
  border-top: 8px solid #1c87c7;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  -webkit-transform: rotate(-45deg);
  position: absolute;
  bottom: 1px;
  right: -3px;
  pointer-events: none;
  z-index: 2;
}


问:
How to make a live HTML preview textarea safe against HTML/Script Injection
I'm turning here as a last resort. I've scoured google and I'm having troubles coming to a solution. I have a form with a textarea element that allows you to type html in the area and it will render the HTML markup live as you type if you have the preview mode active. Not too different from the way StackOverflow shows the preview below a new post.

However, I have recently discovered that my functionality has a vulnerability. All I got to do is type something like:

```<code></textarea>
     <script>alert("Hello World!");</script>
<textarea style="display: none;">
</code>```

And not only does this run from within the textarea live, if you save the form and reload said data on a different page this code still executes within the textarea on said different page but unbeknownst to the user; to them all the see is a textarea (if there is no alert obviously).

I found this post; Live preview of textarea input with javascript html, and attempted to refactor my JS to the accepted answer there, because I noticed I couldn't write a script tag in the JSFiddle example, though maybe that's some JSFiddle blocking that behaviour, but I couldn't get it working within my JS file.

These few lines is what I use to live render HTML markup:

```<code>$(".main").on("keyup", "#actualTextArea", function () {
    $('#previewTextArea').html($('#actualTextArea').val());
});

$(".main").on("keydown", "#actualTextArea", function () {
    $('#previewTextArea').html($('#actualTextArea').val());
});
</code>```

Is there a way this can be refactored so it's safe? My only idea at the moment is to wipe the live preview and use a toggle on/off and encode it, but I really think this is a cool feature and would like to keep it live instead of toggle. Is there a way to "live encode" it or escape certain tags or something?

答:
In order to sanitise your text area preview simply replace all the < and > with their html character code equivalents:

function showPreview()
{
  var value = $('#writer').val().trim();
  value = value.replace("<", "<");
  value = value.replace(">", ">");
  $('#preview').html(value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="writer" onInput="showPreview();">
</textarea>
<br/>
<hr/>
<div id="preview">
</div></code>```

Body:
I'm turning here as a last resort. I've scoured google and I'm having troubles coming to a solution. I have a form with a textarea element that allows you to type html in the area and it will render the HTML markup live as you type if you have the preview mode active. Not too different from the way StackOverflow shows the preview below a new post.

However, I have recently discovered that my functionality has a vulnerability. All I got to do is type something like:

</textarea>

<textarea style="display: none;">

And not only does this run from within the textarea live, if you save the form and reload said data on a different page this code still executes within the textarea on said different page but unbeknownst to the user; to them all the see is a textarea (if there is no alert obviously).

I found this post; Live preview of textarea input with javascript html, and attempted to refactor my JS to the accepted answer there, because I noticed I couldn't write a script tag in the JSFiddle example, though maybe that's some JSFiddle blocking that behaviour, but I couldn't get it working within my JS file.

These few lines is what I use to live render HTML markup:

$(".main").on("keyup", "#actualTextArea", function () {
    $('#previewTextArea').html($('#actualTextArea').val());
});

$(".main").on("keydown", "#actualTextArea", function () {
    $('#previewTextArea').html($('#actualTextArea').val());
});

Is there a way this can be refactored so it's safe? My only idea at the moment is to wipe the live preview and use a toggle on/off and encode it, but I really think this is a cool feature and would like to keep it live instead of toggle. Is there a way to "live encode" it or escape certain tags or something?

Body:
In order to sanitise your text area preview simply replace all the < and > with their html character code equivalents:

function showPreview()
{
  var value = $('#writer').val().trim();
  value = value.replace("<", "&lt;");
  value = value.replace(">", "&gt;");
  $('#preview').html(value);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="writer" onInput="showPreview();">
</textarea>
<br/>
<hr/>
<div id="preview">
</div>


问:
HTMLCollection memory leak in Chrome
EDIT: See https://bugs.chromium.org/p/chromium/issues/detail?id=707544 for relevant issue and information about the bug.

Not necessary to answer this question from now on but retain the question for reference.

Element.getElementsByTagName return HTMLCollection in Chrome.

It stops GC from collecting the Element which called by or referenced from.

Although nothing found in Detached DOM tree, Nodes count (and probably heap size) increased unexpectedly.

The following demonstrates the result of clicking the button in the page which the code is provided below and forcing GC alternatively. (Heap size are dropped after Major GC/DOM GC but not Nodes counts)

And memory information after the first allocation and forced GC.

In my opinion, those HTMLCollection maybe act as a cache/placeholder. Since its parent is a temporary element, unnecessary amount of copy of HTMLCollection remains even when those elements were removed and collected.

Observed on Chrome 57.0.2987.133 and Chromium 59.0.3058.0 in Win10.

Reproducible code:

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div id="content"></div>
    <input type="button" id="button">
    <script type="application/javascript">
        var button = document.getElementById('button');
        button.addEventListener('click', function() {
            var content = document.getElementById('content');
            for (var i = 0; i < 2000; i++) {
                var el = document.createElement("div");
                //var no_leak = el.querySelectorAll('SPAN'); // NodeList
                var leak = el.getElementsByTagName('SPAN'); // HTMLCollection
                content.appendChild(el);
                el.remove();
            }
        });
    </script>
</body>
</html>
</code>```

答: Try using Allocation Timelines. See Identify JS heap memory leaks with Allocation Timelines. It's a kind of realtime visualization of memory allocations.</p>

Title: HTMLCollection memory leak in Chrome

Body:
EDIT: See https://bugs.chromium.org/p/chromium/issues/detail?id=707544 for relevant issue and information about the bug.

Not necessary to answer this question from now on but retain the question for reference.

Element.getElementsByTagName return HTMLCollection in Chrome.

It stops GC from collecting the Element which called by or referenced from.

Although nothing found in Detached DOM tree, Nodes count (and probably heap size) increased unexpectedly.

The following demonstrates the result of clicking the button in the page which the code is provided below and forcing GC alternatively. (Heap size are dropped after Major GC/DOM GC but not Nodes counts)

And memory information after the first allocation and forced GC.

In my opinion, those HTMLCollection maybe act as a cache/placeholder. Since its parent is a temporary element, unnecessary amount of copy of HTMLCollection remains even when those elements were removed and collected.

Observed on Chrome 57.0.2987.133 and Chromium 59.0.3058.0 in Win10.

Reproducible code:

<!DOCTYPE html>

    <input type="button" id="button">


问:
Converting seconds in mm:ss in running JavaScript Timer
I'm just trying to update a friend's timer, which we did for an event a while ago. The timer works perfectly and already does everything it should (see and run Snippet). However, now I would like to display the format mm:ss instead of only seconds (eg. 180 -> 3:00). This must of course be able to count down further. Different approaches I googled have failed. Has anyone an idea how to solve my problem elegantly?

Edit: You can start and stop the timer by pressing 'Space'

<!DOCTYPE html>

  <title></title>

    <svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
      <g>
        <title>Layer 1</title>
        <circle id="circle" r="65.85699" cy="81" cx="81" stroke-width="15" stroke="#ffffff" fill="none"/>
        <circle id="circle" class="circle_animation" r="65.85699" cy="81" cx="81" stroke-width="16" stroke="#333" fill="none"/>
      </g>
    </svg>

180

```

答:
Here is the important part:

```<code> var seconds = time - runtime,
      mins = ("0" + Math.floor(seconds / 60)).substr(-2),
      secs = ("0" + (seconds % 60)).substr(-2);
    $('h1').text(mins + ":" + secs);
</code>```

Basically split up each part by minutes and seconds and concatenate them. The substring is to enforce double digit padding (ie: 02:03 instead of 2:3)

<!DOCTYPE html>

  <title></title>

    <svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
      <g>
        <title>Layer 1</title>
        <circle id="circle" r="65.85699" cy="81" cx="81" stroke-width="15" stroke="#ffffff" fill="none"/>
        <circle id="circle" class="circle_animation" r="65.85699" cy="81" cx="81" stroke-width="16" stroke="#333" fill="none"/>
      </g>
    </svg>

180

```

Cool animation btw.

Body:
Here is the important part:

 var seconds = time - runtime,
      mins = ("0" + Math.floor(seconds / 60)).substr(-2),
      secs = ("0" + (seconds % 60)).substr(-2);
    $('h1').text(mins + ":" + secs);

Basically split up each part by minutes and seconds and concatenate them. The substring is to enforce double digit padding (ie: 02:03 instead of 2:3)

<!DOCTYPE html>
<html>

<head>
  <title></title>

  <style type="text/css">
    body {
      background-color: #333;
      font-family: sans-serif;
    }

    .item {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%) scale(3.0);
    }

    .item h1 {
      text-align: center;
      position: absolute;
      width: 100%;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-110%);
      color: #ffffff;
      font-size: 3em;
    }

    .item h2 {
      text-align: center;
      position: absolute;
      width: 50%;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-110%);
      color: #ffffff;
      font-size: 1.5em;
      line-height: 0.9;
    }

    svg {
      -webkit-transform: rotate(-90deg);
      transform: rotate(-90deg);
    }

    .circle_animation {
      stroke-dasharray: 440;
      /* this value is the pixel circumference of the circle */
      stroke-dashoffset: 440;
      transition: all 1s linear;
    }
  </style>

  <script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>

  <script type="text/javascript">
    var running = false;

    var time = 180;
    var initialOffset = '440';
    var runtime = 0;

    $(document).keydown(function(e) {

      switch (e.which) {
        case 32:
          setTimeout(function() {
            if (running === false) {
              running = true;
            } else {
              running = false;
            };
          }, 1);
          break;
      }
    });

    $(document).ready(function() {

      console.log("ready!");
      $('#start').click(function() {
        running = true;
      });

      var interval = setInterval(function() {
        $('.circle_animation').css('stroke-dashoffset', initialOffset - (runtime * (initialOffset / (time + 10.5))));
        var seconds = time - runtime,
          mins = ("0" + Math.floor(seconds / 60)).substr(-2),
          secs = ("0" + (seconds % 60)).substr(-2);
        $('h1').text(mins + ":" + secs);
        if (runtime == 420) {
          audioElement1.play();
        }
        if (runtime == time) {
          clearInterval(interval);
          $('.circle_animation').css('stroke-dashoffset', 880);
          $('h1').text('');
          $('h2').text('Time is up!');
        }
        if (running) {
          runtime++;
        };
      }, 1000);

    });
  </script>

</head>

<body>

  <div class="item html">
    <svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
      <g>
        <title>Layer 1</title>
        <circle id="circle" r="65.85699" cy="81" cx="81" stroke-width="15" stroke="#ffffff" fill="none"/>
        <circle id="circle" class="circle_animation" r="65.85699" cy="81" cx="81" stroke-width="16" stroke="#333" fill="none"/>
      </g>
    </svg>
    <h1>180</h1>
    <h2></h2>
  </div>

</body>

</html>

Cool animation btw.


答:
I believe what you are trying to do is JavaScript (JQuery for making it easier). </p>

```<code>$(function(){
   var elem = $('input[name="c71sthfilipino"]');
   if ( !$(elem).val() ){
      elem.prop('disabled', true);
   }
})
</code>```

Title: How to disable <input "text"> if there is a value in column (inside moda)

Body:
I believe what you are trying to do is JavaScript (JQuery for making it easier).

$(function(){
   var elem = $('input[name="c71sthfilipino"]');
   if ( !$(elem).val() ){
      elem.prop('disabled', true);
   }
})


问:
How to automatically set a large number of external variables to a given value?
I have an interesting problem which has me stumped quite a bit. Many thanks in advance for any assistance.

The basic situation is as follows. I'm writing a general script file, general.js, for use with a large number of web pages, each of which has its own associated script file pageN.js. Each of these pageN files contains a large number of variables t1,...,tn, with n different for each page. (Usually n will be between 50 and 100.)

In general.js I have a "lightswitch" function:

```<code>function onOff(t,binaryDigit){
   if ( binaryDigit == 0 ) { // hide graphic element associated with t
   }
   else { // show graphic element associated with t
   }
}
</code>```

and also a function that applies onOff to an arbitrary number of  ordered pairs [tk,binaryDigit]:

```<code>function myFunction() {
    for (var i = 0; i < arguments.length; i++) {
        onOff(arguments[i][0],arguments[i][1])
    }
}
</code>```

Since I'm going to call myFunction often, and each time most binaryDigits will have to be set to 0, I would like to build a helperFunction in which I only need to specify the tk for which I want binaryDigit to be 1 and which sets the other binary digits to 0. So, for example, if n = 50, then calling helperFunction(t1,t2,t3) should execute myFunction([t1,1],[t2,1],[t3,1],[t4,0],...,[t50,0]).

My question is: how should I do this? I have only limited experience with advanced JavaScript, so I haven't got a clue, to be honest.`

答:
Solved it by myself, after giving it some further thought (on the toilet). My solution is to generate for each pageN.js file an array, called variableArray, that is essentially a list of all the variables in that file. Next, I define my helperFunction in general.js as follows:

```<code>var helperFunction = function() {
    var argArray = Array.prototype.slice.call(arguments);
    var varArray = argArray[argArray.length-1];
    var elementsOff = $(varArray).not($(argArray)).get();
    for (var i = 0; i < arguments.length; i++) {
        onOff(arguments[i],1);
    }
    for (var i = 0; i < elementsOff.length; i++) {
    onOff(elementsOff[i],0);
   }
};
</code>```

The functions gets called like this: helperFunction(t1,t2,t3,variableArray).

Body:
I have an interesting problem which has me stumped quite a bit. Many thanks in advance for any assistance.

The basic situation is as follows. I'm writing a general script file, general.js, for use with a large number of web pages, each of which has its own associated script file pageN.js. Each of these pageN files contains a large number of variables t1,...,tn, with n different for each page. (Usually n will be between 50 and 100.)

In general.js I have a "lightswitch" function:

function onOff(t,binaryDigit){
   if ( binaryDigit == 0 ) { // hide graphic element associated with t
   }
   else { // show graphic element associated with t
   }
}

and also a function that applies onOff to an arbitrary number of  ordered pairs [tk,binaryDigit]:

function myFunction() {
    for (var i = 0; i < arguments.length; i++) {
        onOff(arguments[i][0],arguments[i][1])
    }
}

Since I'm going to call myFunction often, and each time most binaryDigits will have to be set to 0, I would like to build a helperFunction in which I only need to specify the tk for which I want binaryDigit to be 1 and which sets the other binary digits to 0. So, for example, if n = 50, then calling helperFunction(t1,t2,t3) should execute myFunction([t1,1],[t2,1],[t3,1],[t4,0],...,[t50,0]).

My question is: how should I do this? I have only limited experience with advanced JavaScript, so I haven't got a clue, to be honest.`

Body:
Solved it by myself, after giving it some further thought (on the toilet). My solution is to generate for each pageN.js file an array, called variableArray, that is essentially a list of all the variables in that file. Next, I define my helperFunction in general.js as follows:

var helperFunction = function() {
    var argArray = Array.prototype.slice.call(arguments);
    var varArray = argArray[argArray.length-1];
    var elementsOff = $(varArray).not($(argArray)).get();
    for (var i = 0; i < arguments.length; i++) {
        onOff(arguments[i],1);
    }
    for (var i = 0; i < elementsOff.length; i++) {
    onOff(elementsOff[i],0);
   }
};

The functions gets called like this: helperFunction(t1,t2,t3,variableArray).


问:
What is the maximum number of clients that a grpc-java managedchannelbuilder can handle?
When we create a managedChannelBuilder and use this to call a grpc-java service call, how many clients can we serve with this? Doesn't this channel be shutdown after individual service call?
Say I have a REST interface which accepts REST calls from a browser
and from within these REST Service methods, I am making grpc client calls to an independent grpc server. Also I can expect client connections in the range of [4000-5000] concurrently.
 How well can I make use of this managedChannelBuilder. Do I need just one? Or do I need to pool multiple channelbuilders?</p>

答:
Generally, I'd suggest using a single ManagedChannel per endpoint when your code can be easily structured to share it. ManagedChannel multiplexes RPCs and is thread-safe, so it can handle multiple RPCs concurrently.

In rarer cases of high very high throughput, it may make sense to use more than one ManagedChannel. Eventually ManagedChannel (or, maybe Channel) should have support for doing this natively.


问:
Javascript generating anchors quote issue
I'm new to this site and new to Javascript, however I'm been coding in C for some years, and I ran into a problem that totally blows my mind.

I want to make a tool for myself (a very simple code generating tool). I want to generate html code and in a displayable manner, because the final product would be a static page (no javascript). So I tried to solve it with basic string manipulation.

The task and the code is so simple I'll just post it here.
Javascript with it's corresponding tags:

```
</div>
</div>
</p>

<p>The input:</p>

<blockquote>
  <p>https://drive.google.com/uc?id=0B3ju3vX1o4OuY0RaaDJKWnlRN1U + title +
  desc https://drive.google.com/uc?id=0B3ju3vX1o4OuSC1hNFQwUV9IWlE +
  title2 + desc2</p>
</blockquote>

<p>And the output after running the script:</p>

```
```

<p>It's like something automatically put quotes around the links. Sorry, I have tried so many things I can't remember now, but as I remember this "auto-quoting" thing only happens with links and it causes all sorts of problem in the resulting code (for example the '/' slips inside the quotes). And all other problems were caused by this behavior (I can't assign title and other attributes inside the img tag).</p>

<p>Additional html:</p>

```    <form>
    <textarea id="gallery_generator_input" style = "width:800px;"></textarea></form>

    <textarea id="gallery_generator_result" style = "width:800px;"></textarea>

Convert!

```

Thank you for any hints in advance!

EDIT: removed the misleading WOW thing.
The desired result is simply a valid html image code.

答:
Change this line

```<code>result.innerHTML += '<img src=' + link + '!!WOW>';
</code>```

to this

```<code>result.innerHTML += '<img src="' + link + '!!WOW"/>';
</code>```

also you can urlencode the exclamation marks if they are a problem:

```<code>result.innerHTML += '<img src="' + link + '%21%21WOW"/>';
</code>```

Body:
I'm new to this site and new to Javascript, however I'm been coding in C for some years, and I ran into a problem that totally blows my mind.

I want to make a tool for myself (a very simple code generating tool). I want to generate html code and in a displayable manner, because the final product would be a static page (no javascript). So I tried to solve it with basic string manipulation.

The task and the code is so simple I'll just post it here.
Javascript with it's corresponding tags:

The input:

https://drive.google.com/uc?id=0B3ju3vX1o4OuY0RaaDJKWnlRN1U + title +
  desc https://drive.google.com/uc?id=0B3ju3vX1o4OuSC1hNFQwUV9IWlE +
  title2 + desc2

And the output after running the script:

It's like something automatically put quotes around the links. Sorry, I have tried so many things I can't remember now, but as I remember this "auto-quoting" thing only happens with links and it causes all sorts of problem in the resulting code (for example the '/' slips inside the quotes). And all other problems were caused by this behavior (I can't assign title and other attributes inside the img tag).

Additional html:

    <form>
    <textarea id="gallery_generator_input" style = "width:800px;"></textarea></form>

    <textarea id="gallery_generator_result" style = "width:800px;"></textarea>

Convert!

Thank you for any hints in advance!

EDIT: removed the misleading WOW thing.
The desired result is simply a valid html image code.

Body:
Change this line

result.innerHTML += '<img src=' + link + '!!WOW>';

to this

result.innerHTML += '<img src="' + link + '!!WOW"/>';

also you can urlencode the exclamation marks if they are a problem:

result.innerHTML += '<img src="' + link + '%21%21WOW"/>';


问:
q.allSettled with nested async forEach
I'm in a situation in which I have to wait for all promises in a forEach loop to be settled before I proceed. It would have been a walk in the park if the nesting level was just one deep. In my case, I have to wait for even the promise inside a promise and only then move to q.allSettled. A rough code is given below:

```<code>        return q.Promise(function (resolve, reject) {
        mydata.forEach(function (item) {
            products.forEach(function (product) {
                    var attributeSetNode = item.Products.Product.AttributeSets;
                        var promise = somePromise(), rankNode;
                        matchingPromises.push(promise);
                        debug("matchingpromise length before grab category: "+ matchingPromises.length);
                        //async function inside loop needs to be passed references
                        (function (product, rankNode, attributeSetNode) {
                            promise.then(function (grabbed) {
                                debug('Grabbed Category', grabbed);
-------------------- Problem Line --------------------
                                (function (product) {
                                    var dimsAndFeePromise = somePromise();
                                    matchingPromises.push(dimsAndFeePromise);
                                    debug("matchingpromise length after grab category: "+ matchingPromises.length);
                                    dimsAndFeePromise.then(function () {
                                        //Some future logic here. Once streamlined, this is actually supposed to return the calculations
                                        //here and not play with the reference itself inside the function call:(
                                        debug('Done with ASIN: ' + product.ASIN);
                                    });
                                })(product);
                            }).catch(function (err) {
                                debug(err);
                            })
                        })(product, rankNode, attributeSetNode);
            });
        });
        debug("Going to resolve allSettled matchingPromises with length: "+ matchingPromises.length);

------------------ Problem Line 2 -----------------------
        q.allSettled(matchingPromises).then(function (result) {
            resolve();
        });
    });
</code>```

I'm just not sure how to wait for the above for loop so that Problem Line 2 is only called after Problem Line 1 has executed

答:
I believe that you need to enchain the inner promise with the outer promise, in this case, the dimsAndFeePromise needs to be enchained with the matchingPromises.

The below code should get you in the right direction:

```<code>return q.Promise(function (resolve, reject) {
    mydata.forEach(function (item) {
        products.forEach(function (product) {
            var attributeSetNode = item.Products.Product.AttributeSets;
            var promise = somePromise(),
                rankNode,
                enchainedPromise;

            debug("matchingpromise length before grab category: "+ matchingPromises.length);
            //async function inside loop needs to be passed references
            (function (product, rankNode, attributeSetNode) {
                enchainedPromise = promise.then(function (grabbed) {
                    debug('Grabbed Category', grabbed);
-------------------- Problem Line --------------------
                    return (function (product) {
                        var dimsAndFeePromise = somePromise();
                        // matchingPromises.push(dimsAndFeePromise);
                        debug("matchingpromise length after grab category: "+ matchingPromises.length);
                        return dimsAndFeePromise.then(function () {
                            //Some future logic here. Once streamlined, this is actually supposed to return the calculations
                            //here and not play with the reference itself inside the function call:(
                            debug('Done with ASIN: ' + product.ASIN);
                        });
                    })(product);
                }).catch(function (err) {
                    debug(err);
                })
            })(product, rankNode, attributeSetNode);
            matchingPromises.push(enchainedPromise);
        });
    });
    debug("Going to resolve allSettled matchingPromises with length: "+ matchingPromises.length);

------------------ Problem Line 2 -----------------------
    q.allSettled(matchingPromises).then(function (result) {
        resolve();
    });
});
</code>```

I think that the code could also be factorized into the following:

```<code>return q.allSettled(mydata.map(function (item) {
    return products.map(function (product) {
        var attributeSetNode = item.Products.Product.AttributeSets;
        var promise = somePromise(),
            rankNode;

            return promise.then(function (grabbed) {
                return somePromise().then(function () {
                    //Some future logic here. Once streamlined, this is actually supposed to return the calculations
                    //here and not play with the reference itself inside the function call:(
                    debug('Done with ASIN: ' + product.ASIN);
                });
            });
    });
}));
</code>```

Title: q.allSettled with nested async forEach

Body:
I'm in a situation in which I have to wait for all promises in a forEach loop to be settled before I proceed. It would have been a walk in the park if the nesting level was just one deep. In my case, I have to wait for even the promise inside a promise and only then move to q.allSettled. A rough code is given below:

        return q.Promise(function (resolve, reject) {
        mydata.forEach(function (item) {
            products.forEach(function (product) {
                    var attributeSetNode = item.Products.Product.AttributeSets;
                        var promise = somePromise(), rankNode;
                        matchingPromises.push(promise);
                        debug("matchingpromise length before grab category: "+ matchingPromises.length);
                        //async function inside loop needs to be passed references
                        (function (product, rankNode, attributeSetNode) {
                            promise.then(function (grabbed) {
                                debug('Grabbed Category', grabbed);
-------------------- Problem Line --------------------
                                (function (product) {
                                    var dimsAndFeePromise = somePromise();
                                    matchingPromises.push(dimsAndFeePromise);
                                    debug("matchingpromise length after grab category: "+ matchingPromises.length);
                                    dimsAndFeePromise.then(function () {
                                        //Some future logic here. Once streamlined, this is actually supposed to return the calculations
                                        //here and not play with the reference itself inside the function call:(
                                        debug('Done with ASIN: ' + product.ASIN);
                                    });
                                })(product);
                            }).catch(function (err) {
                                debug(err);
                            })
                        })(product, rankNode, attributeSetNode);
            });
        });
        debug("Going to resolve allSettled matchingPromises with length: "+ matchingPromises.length);

------------------ Problem Line 2 -----------------------
        q.allSettled(matchingPromises).then(function (result) {
            resolve();
        });
    });

I'm just not sure how to wait for the above for loop so that Problem Line 2 is only called after Problem Line 1 has executed

Body:
I believe that you need to enchain the inner promise with the outer promise, in this case, the dimsAndFeePromise needs to be enchained with the matchingPromises.

The below code should get you in the right direction:

return q.Promise(function (resolve, reject) {
    mydata.forEach(function (item) {
        products.forEach(function (product) {
            var attributeSetNode = item.Products.Product.AttributeSets;
            var promise = somePromise(),
                rankNode,
                enchainedPromise;

            debug("matchingpromise length before grab category: "+ matchingPromises.length);
            //async function inside loop needs to be passed references
            (function (product, rankNode, attributeSetNode) {
                enchainedPromise = promise.then(function (grabbed) {
                    debug('Grabbed Category', grabbed);
-------------------- Problem Line --------------------
                    return (function (product) {
                        var dimsAndFeePromise = somePromise();
                        // matchingPromises.push(dimsAndFeePromise);
                        debug("matchingpromise length after grab category: "+ matchingPromises.length);
                        return dimsAndFeePromise.then(function () {
                            //Some future logic here. Once streamlined, this is actually supposed to return the calculations
                            //here and not play with the reference itself inside the function call:(
                            debug('Done with ASIN: ' + product.ASIN);
                        });
                    })(product);
                }).catch(function (err) {
                    debug(err);
                })
            })(product, rankNode, attributeSetNode);
            matchingPromises.push(enchainedPromise);
        });
    });
    debug("Going to resolve allSettled matchingPromises with length: "+ matchingPromises.length);

------------------ Problem Line 2 -----------------------
    q.allSettled(matchingPromises).then(function (result) {
        resolve();
    });
});

I think that the code could also be factorized into the following:

return q.allSettled(mydata.map(function (item) {
    return products.map(function (product) {
        var attributeSetNode = item.Products.Product.AttributeSets;
        var promise = somePromise(),
            rankNode;

            return promise.then(function (grabbed) {
                return somePromise().then(function () {
                    //Some future logic here. Once streamlined, this is actually supposed to return the calculations
                    //here and not play with the reference itself inside the function call:(
                    debug('Done with ASIN: ' + product.ASIN);
                });
            });
    });
}));


问:
Changed Int to uniqueidentifier in a Database Project
I would like to change a primary key column from int to uniqueidentifier in a database project. I tried to change the type but got predictable error because SQL Server can't convert int to guid. (Original Image):

```<code>+ ------------ + -------------- + ----------- + ------- +
| Name         | Data_Type      | Allow Nulls | Default |
+ ------------ + -------------- + ----------- + ------- +
| OrderImageId | int            | No          |         |
| OrderId      | int            | No          |         |
| Image        | varbinary(MAX) | Yes         |         |
| FileName     | nvarchar(Max)  | Yes         |         |
+ ------------ + -------------- + ----------- + ------- +

create table [dbo].[OrderImages]
(
    [OrderImageId] int not null primary key identity,
    [OrderId] int not null
        Constraint [FK_OrderImages_Orders] foreign key (OrderId) references [Orders]([OrderId]),
    [Image] varbinary(Max) null,
    [FileName] nvarchar(max) null
)
</code>```

I know how to do it in SQL Server Management Studio (create a separate guid column, fill it, delete PK, set PK for guid column etc), but is it possible to do it in a database project? And what if my PK column has FKs?

答:
To do this you will need to create a new table and migrate the data, substituting the guids that you want to use to replace the existing integer data.

That being said, using a uniqueidentifier here is not a good idea.  It is 128 bits of essentially random data that will cause fragmentation.  If you expect to have more than 4 billion images with possibly multiple images per order, you can use a bigint.

If there will be no more than one image per order, you can use the OrderID as the primary key (without the identity constraint) and avoid needing to add a nonclustered index on OrderID.

Body:
I would like to change a primary key column from int to uniqueidentifier in a database project. I tried to change the type but got predictable error because SQL Server can't convert int to guid. (Original Image):

+ ------------ + -------------- + ----------- + ------- +
| Name         | Data_Type      | Allow Nulls | Default |
+ ------------ + -------------- + ----------- + ------- +
| OrderImageId | int            | No          |         |
| OrderId      | int            | No          |         |
| Image        | varbinary(MAX) | Yes         |         |
| FileName     | nvarchar(Max)  | Yes         |         |
+ ------------ + -------------- + ----------- + ------- +

create table [dbo].[OrderImages]
(
    [OrderImageId] int not null primary key identity,
    [OrderId] int not null
        Constraint [FK_OrderImages_Orders] foreign key (OrderId) references [Orders]([OrderId]),
    [Image] varbinary(Max) null,
    [FileName] nvarchar(max) null
)

I know how to do it in SQL Server Management Studio (create a separate guid column, fill it, delete PK, set PK for guid column etc), but is it possible to do it in a database project? And what if my PK column has FKs?