答:
you can do it by this code if you using JQuery.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</code>```

//For ref add above script cdn

If you have to assign this on page load then use this code in onload / ready .

```<code>$("a.nav-link.active").parent('li').addClass('myclass');
</code>```

If you want to change this on click of a tab and page not get postback and click event is handled by a then.

```<code>$("this").parent('li').addClass('myclass');
</code>```

Title: Add class to parent when child get a new class?

Body:
How can I add class .myclass to li when its child (a.nav-link) get class .active?

       Home

       Profile

Body:
you can do it by this code if you using JQuery.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>

//For ref add above script cdn

If you have to assign this on page load then use this code in onload / ready .

$("a.nav-link.active").parent('li').addClass('myclass');

If you want to change this on click of a tab and page not get postback and click event is handled by a then.

$("this").parent('li').addClass('myclass');


来源: stackexchange

问:
Scala call length() on very long string throws exception: Maximum String literal length exceeded
I wrote a scala solution for HackerRank BigSorting ,
and got RuntimeException in some test case. I tested the input in scastie, it seems the problem is caused by calling length() on a very long string, but the same java solution has no problem, is this a bug?
my solution code is :

```<code>object Solution {
    def stringSort(x:String, y:String):Boolean = {
        var result = true

        if(x.length < y.length){
            result = true
        }else if(x.length > y.length){
            result = false
        }else{
            var founded = false
            var i = 0
            while(i < x.length && !founded){
                var xi = x.charAt(i)
                var yi = y.charAt(i)
                if(xi != yi){
                    result = xi < yi
                    founded = true
                }
                i += 1
            }
        }
        result
    }

    def bigSort(unsorted:Array[String]):Array[String] = {
        return unsorted.sortWith(stringSort)
    }

    def main(args: Array[String]) {
        val sc = new java.util.Scanner (System.in);
        var n = sc.nextInt();
        var unsorted = new Array[String](n);
        for(unsorted_i <- 0 to n-1) {
           unsorted(unsorted_i) = sc.next();
        }
        print(bigSort(unsorted).mkString("\n"))
        // your code goes here
    }
}
</code>```

the exception is

```<code>java.lang.IllegalArgumentException: Maximum String literal length exceeded
    at scala.tools.asm.ByteVector.putUTF8(ByteVector.java:213)
    at scala.tools.asm.ClassWriter.newUTF8(ClassWriter.java:1114)
    at scala.tools.asm.ClassWriter.newString(ClassWriter.java:1582)
    at scala.tools.asm.ClassWriter.newConstItem(ClassWriter.java:1064)
    at scala.tools.asm.MethodWriter.visitLdcInsn(MethodWriter.java:1187)
    at scala.tools.asm.tree.LdcInsnNode.accept(LdcInsnNode.java:71)
    at scala.tools.asm.tree.InsnList.accept(InsnList.java:162)
    at scala.tools.asm.tree.MethodNode.accept(MethodNode.java:820)
    at scala.tools.asm.tree.MethodNode.accept(MethodNode.java:730)
    at scala.tools.asm.tree.ClassNode.accept(ClassNode.java:412)
...
</code>```

java solution

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String[] unsorted = new String[n];
        for(int i = 0; i < n; i++) unsorted[i] = in.next();

        Arrays.sort(unsorted,new Comparator<String>() {
            @Override
            public int compare(String a, String b)
            {
                return StringAsIntegerCompare(a,b);
            }
        });

        StringBuilder output = new StringBuilder("");
        for(String num : unsorted)
            output.append(num+"\n");
        System.out.println(output);
    }

    static int StringAsIntegerCompare(String s1, String s2)
    {
        if(s1.length() > s2.length()) return 1;
        if(s1.length() < s2.length()) return -1;
        for(int i = 0; i < s1.length(); i++)
        {
            if((int)s1.charAt(i) > (int)s2.charAt(i)) return 1;
            if((int)s1.charAt(i) < (int)s2.charAt(i)) return -1;
        }
        return 0;
    }
}
</code>```

答:
It is curious that a java solution, asking each string for its length, works while the Scala solution does not.

For what it's worth, the challenge is solvable without invoking the length method on any String element. I came up with an accepted solution (21 lines of code) using isDefinedAt() to determine the relative lengths of the String elements.

As requested, here is the solution I came up with.

For those not familiar with HackerRank challenges, the very poor Scala code in the main() method is supplied code (i.e. not my fault!). I wrote the sortum() code.

```<code>def sortum(arr:Array[String],start:Int = 0, end:Int = 1000000):Array[String] =
  if (arr.length < 2) arr             //only one of this length, return it
  else if (end-start < 1) arr.sorted  //multiple of the same length, sort them
  else {                              //partition into two groups
    val mid = (end-start)/2 + start
    val (a,b) = arr.partition(_.isDefinedAt(mid))
    if      (a.isEmpty) sortum(b,start,mid)
    else if (b.isEmpty) sortum(a,mid+1,end)
    else sortum(b,start,mid) ++ sortum(a,mid+1,end)
  }

def main(args: Array[String]) {
  val sc = new java.util.Scanner (System.in);
  var n = sc.nextInt();
  var unsorted = new Array[String](n);
  for(unsorted_i <- 0 to n-1) {
    unsorted(unsorted_i) = sc.next();
  }
  sortum(unsorted).foreach(println)
}
</code>```

It's your basic binary search pattern used to segregate stings by their lengths.

Of course, now that we know that string .length isn't the source of the problem, a much simpler solution is available.

```<code>unsorted.map(_.length)
        .zipWithIndex
        .sortWith{case ((al,ax),(bl,bx)) =>
          al < bl || (al == bl && unsorted(ax) < unsorted(bx))
        }.foreach(x => println(unsorted(x._2)))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wrote a scala solution for HackerRank BigSorting ,
and got RuntimeException in some test case. I tested the input in scastie, it seems the problem is caused by calling length() on a very long string, but the same java solution has no problem, is this a bug?
my solution code is :

object Solution {
    def stringSort(x:String, y:String):Boolean = {
        var result = true

        if(x.length < y.length){
            result = true
        }else if(x.length > y.length){
            result = false
        }else{
            var founded = false
            var i = 0
            while(i < x.length && !founded){
                var xi = x.charAt(i)
                var yi = y.charAt(i)
                if(xi != yi){
                    result = xi < yi
                    founded = true
                }
                i += 1
            }
        }
        result
    }

    def bigSort(unsorted:Array[String]):Array[String] = {
        return unsorted.sortWith(stringSort)
    }

    def main(args: Array[String]) {
        val sc = new java.util.Scanner (System.in);
        var n = sc.nextInt();
        var unsorted = new Array[String](n);
        for(unsorted_i <- 0 to n-1) {
           unsorted(unsorted_i) = sc.next();
        }
        print(bigSort(unsorted).mkString("\n"))
        // your code goes here
    }
}

the exception is

java.lang.IllegalArgumentException: Maximum String literal length exceeded
    at scala.tools.asm.ByteVector.putUTF8(ByteVector.java:213)
    at scala.tools.asm.ClassWriter.newUTF8(ClassWriter.java:1114)
    at scala.tools.asm.ClassWriter.newString(ClassWriter.java:1582)
    at scala.tools.asm.ClassWriter.newConstItem(ClassWriter.java:1064)
    at scala.tools.asm.MethodWriter.visitLdcInsn(MethodWriter.java:1187)
    at scala.tools.asm.tree.LdcInsnNode.accept(LdcInsnNode.java:71)
    at scala.tools.asm.tree.InsnList.accept(InsnList.java:162)
    at scala.tools.asm.tree.MethodNode.accept(MethodNode.java:820)
    at scala.tools.asm.tree.MethodNode.accept(MethodNode.java:730)
    at scala.tools.asm.tree.ClassNode.accept(ClassNode.java:412)
...

java solution

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String[] unsorted = new String[n];
        for(int i = 0; i < n; i++) unsorted[i] = in.next();

        Arrays.sort(unsorted,new Comparator<String>() {
            @Override
            public int compare(String a, String b)
            {
                return StringAsIntegerCompare(a,b);
            }
        });

        StringBuilder output = new StringBuilder("");
        for(String num : unsorted)
            output.append(num+"\n");
        System.out.println(output);
    }

    static int StringAsIntegerCompare(String s1, String s2)
    {
        if(s1.length() > s2.length()) return 1;
        if(s1.length() < s2.length()) return -1;
        for(int i = 0; i < s1.length(); i++)
        {
            if((int)s1.charAt(i) > (int)s2.charAt(i)) return 1;
            if((int)s1.charAt(i) < (int)s2.charAt(i)) return -1;
        }
        return 0;
    }
}

Body:
It is curious that a java solution, asking each string for its length, works while the Scala solution does not.

For what it's worth, the challenge is solvable without invoking the length method on any String element. I came up with an accepted solution (21 lines of code) using isDefinedAt() to determine the relative lengths of the String elements.

As requested, here is the solution I came up with.

For those not familiar with HackerRank challenges, the very poor Scala code in the main() method is supplied code (i.e. not my fault!). I wrote the sortum() code.

def sortum(arr:Array[String],start:Int = 0, end:Int = 1000000):Array[String] =
  if (arr.length < 2) arr             //only one of this length, return it
  else if (end-start < 1) arr.sorted  //multiple of the same length, sort them
  else {                              //partition into two groups
    val mid = (end-start)/2 + start
    val (a,b) = arr.partition(_.isDefinedAt(mid))
    if      (a.isEmpty) sortum(b,start,mid)
    else if (b.isEmpty) sortum(a,mid+1,end)
    else sortum(b,start,mid) ++ sortum(a,mid+1,end)
  }

def main(args: Array[String]) {
  val sc = new java.util.Scanner (System.in);
  var n = sc.nextInt();
  var unsorted = new Array[String](n);
  for(unsorted_i <- 0 to n-1) {
    unsorted(unsorted_i) = sc.next();
  }
  sortum(unsorted).foreach(println)
}

It's your basic binary search pattern used to segregate stings by their lengths.

Of course, now that we know that string .length isn't the source of the problem, a much simpler solution is available.

unsorted.map(_.length)
        .zipWithIndex
        .sortWith{case ((al,ax),(bl,bx)) =>
          al < bl || (al == bl && unsorted(ax) < unsorted(bx))
        }.foreach(x => println(unsorted(x._2)))


问:
How to handle non-ascii column names in Spark SQL?
I have a table with Danish characters in some of its column names. I can create dataframes of these tables but I cant write the column names in the where clause without getting an error. For example:

jdbcDF.where("GÆLDER_FRA_DT > '2016-12-01'")

throws an error

```<code>== SQL ==
GÆLDER_FRA_DT > '2016-12-01' and ryk_type in ('52','551','651','751')
-^^^

StackTrace: extraneous input 'Æ' expecting {<EOF>, '(', '.', '[', 'SELECT', 'FROM', 'ADD', 'AS', 'ALL', 'DISTINCT', 'WHERE', 'GROUP', 'BY', 'GROUPING', 'SETS', 'CUBE', 'ROLLUP', 'ORDER', 'HAVING', 'LIMIT', 'AT', 'OR', 'AND', 'IN', NOT, 'NO', 'EXISTS', 'BETWEEN', 'LIKE', RLIKE, 'IS', 'NULL', 'TRUE', 'FALSE', 'NULLS', 'ASC', 'DESC', 'FOR', 'INTERVAL', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'JOIN', 'CROSS', 'OUTER', 'INNER', 'LEFT', 'SEMI', 'RIGHT', 'FULL', 'NATURAL', 'ON', 'LATERAL', 'WINDOW', 'OVER', 'PARTITION', 'RANGE', 'ROWS', 'UNBOUNDED', 'PRECEDING', 'FOLLOWING', 'CURRENT', 'FIRST', 'AFTER', 'LAST', 'ROW', 'WITH', 'VALUES', 'CREATE', 'TABLE', 'VIEW', 'REPLACE', 'INSERT', 'DELETE', 'INTO', 'DESCRIBE', 'EXPLAIN', 'FORMAT', 'LOGICAL', 'CODEGEN', 'COST', 'CAST', 'SHOW', 'TABLES', 'COLUMNS', 'COLUMN', 'USE', 'PARTITIONS', 'FUNCTIONS', 'DROP', 'UNION', 'EXCEPT', 'MINUS', 'INTERSECT', 'TO', 'TABLESAMPLE', 'STRATIFY', 'ALTER', 'RENAME', 'ARRAY', 'MAP', 'STRUCT', 'COMMENT', 'SET', 'RESET', 'DATA', 'START', 'TRANSACTION', 'COMMIT', 'ROLLBACK', 'MACRO', 'IGNORE', 'IF', EQ, '<=>', '<>', '!=', '<', LTE, '>', GTE, '+', '-', '*', '/', '%', 'DIV', '&', '|', '^', 'PERCENT', 'BUCKET', 'OUT', 'OF', 'SORT', 'CLUSTER', 'DISTRIBUTE', 'OVERWRITE', 'TRANSFORM', 'REDUCE', 'USING', 'SERDE', 'SERDEPROPERTIES', 'RECORDREADER', 'RECORDWRITER', 'DELIMITED', 'FIELDS', 'TERMINATED', 'COLLECTION', 'ITEMS', 'KEYS', 'ESCAPED', 'LINES', 'SEPARATED', 'FUNCTION', 'EXTENDED', 'REFRESH', 'CLEAR', 'CACHE', 'UNCACHE', 'LAZY', 'FORMATTED', 'GLOBAL', TEMPORARY, 'OPTIONS', 'UNSET', 'TBLPROPERTIES', 'DBPROPERTIES', 'BUCKETS', 'SKEWED', 'STORED', 'DIRECTORIES', 'LOCATION', 'EXCHANGE', 'ARCHIVE', 'UNARCHIVE', 'FILEFORMAT', 'TOUCH', 'COMPACT', 'CONCATENATE', 'CHANGE', 'CASCADE', 'RESTRICT', 'CLUSTERED', 'SORTED', 'PURGE', 'INPUTFORMAT', 'OUTPUTFORMAT', DATABASE, DATABASES, 'DFS', 'TRUNCATE', 'ANALYZE', 'COMPUTE', 'LIST', 'STATISTICS', 'PARTITIONED', 'EXTERNAL', 'DEFINED', 'REVOKE', 'GRANT', 'LOCK', 'UNLOCK', 'MSCK', 'REPAIR', 'RECOVER', 'EXPORT', 'IMPORT', 'LOAD', 'ROLE', 'ROLES', 'COMPACTIONS', 'PRINCIPALS', 'TRANSACTIONS', 'INDEX', 'INDEXES', 'LOCKS', 'OPTION', 'ANTI', 'LOCAL', 'INPATH', 'CURRENT_DATE', 'CURRENT_TIMESTAMP', IDENTIFIER, BACKQUOTED_IDENTIFIER}(line 1, pos 1)
== SQL ==
GÆLDER_FRA_DT > '2016-12-01' and ryk_type in ('52','551','651','751')
-^^^
  at org.apache.spark.sql.catalyst.parser.ParseException.withCommand(ParseDriver.scala:217)
  at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parse(ParseDriver.scala:114)
  at org.apache.spark.sql.execution.SparkSqlParser.parse(SparkSqlParser.scala:48)
  at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parseExpression(ParseDriver.scala:43)
  at org.apache.spark.sql.Dataset.where(Dataset.scala:1344)
</code>```

How do I handle this? Is there some way for me to say this is a unicode string?

答:
A single quote worked fine.

```<code>jdbcDF.where("'GÆLDER_FRA_DT' > '2016-12-01'")
</code>```

The backtick is probably the best way to deal with this situation though.

```<code>jdbcDF.where("`GÆLDER_FRA_DT` > '2016-12-01'")
</code>```

Body:
I have a table with Danish characters in some of its column names. I can create dataframes of these tables but I cant write the column names in the where clause without getting an error. For example:

jdbcDF.where("GÆLDER_FRA_DT > '2016-12-01'")

throws an error

== SQL ==
GÆLDER_FRA_DT > '2016-12-01' and ryk_type in ('52','551','651','751')
-^^^

StackTrace: extraneous input 'Æ' expecting {<EOF>, '(', '.', '[', 'SELECT', 'FROM', 'ADD', 'AS', 'ALL', 'DISTINCT', 'WHERE', 'GROUP', 'BY', 'GROUPING', 'SETS', 'CUBE', 'ROLLUP', 'ORDER', 'HAVING', 'LIMIT', 'AT', 'OR', 'AND', 'IN', NOT, 'NO', 'EXISTS', 'BETWEEN', 'LIKE', RLIKE, 'IS', 'NULL', 'TRUE', 'FALSE', 'NULLS', 'ASC', 'DESC', 'FOR', 'INTERVAL', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'JOIN', 'CROSS', 'OUTER', 'INNER', 'LEFT', 'SEMI', 'RIGHT', 'FULL', 'NATURAL', 'ON', 'LATERAL', 'WINDOW', 'OVER', 'PARTITION', 'RANGE', 'ROWS', 'UNBOUNDED', 'PRECEDING', 'FOLLOWING', 'CURRENT', 'FIRST', 'AFTER', 'LAST', 'ROW', 'WITH', 'VALUES', 'CREATE', 'TABLE', 'VIEW', 'REPLACE', 'INSERT', 'DELETE', 'INTO', 'DESCRIBE', 'EXPLAIN', 'FORMAT', 'LOGICAL', 'CODEGEN', 'COST', 'CAST', 'SHOW', 'TABLES', 'COLUMNS', 'COLUMN', 'USE', 'PARTITIONS', 'FUNCTIONS', 'DROP', 'UNION', 'EXCEPT', 'MINUS', 'INTERSECT', 'TO', 'TABLESAMPLE', 'STRATIFY', 'ALTER', 'RENAME', 'ARRAY', 'MAP', 'STRUCT', 'COMMENT', 'SET', 'RESET', 'DATA', 'START', 'TRANSACTION', 'COMMIT', 'ROLLBACK', 'MACRO', 'IGNORE', 'IF', EQ, '<=>', '<>', '!=', '<', LTE, '>', GTE, '+', '-', '*', '/', '%', 'DIV', '&', '|', '^', 'PERCENT', 'BUCKET', 'OUT', 'OF', 'SORT', 'CLUSTER', 'DISTRIBUTE', 'OVERWRITE', 'TRANSFORM', 'REDUCE', 'USING', 'SERDE', 'SERDEPROPERTIES', 'RECORDREADER', 'RECORDWRITER', 'DELIMITED', 'FIELDS', 'TERMINATED', 'COLLECTION', 'ITEMS', 'KEYS', 'ESCAPED', 'LINES', 'SEPARATED', 'FUNCTION', 'EXTENDED', 'REFRESH', 'CLEAR', 'CACHE', 'UNCACHE', 'LAZY', 'FORMATTED', 'GLOBAL', TEMPORARY, 'OPTIONS', 'UNSET', 'TBLPROPERTIES', 'DBPROPERTIES', 'BUCKETS', 'SKEWED', 'STORED', 'DIRECTORIES', 'LOCATION', 'EXCHANGE', 'ARCHIVE', 'UNARCHIVE', 'FILEFORMAT', 'TOUCH', 'COMPACT', 'CONCATENATE', 'CHANGE', 'CASCADE', 'RESTRICT', 'CLUSTERED', 'SORTED', 'PURGE', 'INPUTFORMAT', 'OUTPUTFORMAT', DATABASE, DATABASES, 'DFS', 'TRUNCATE', 'ANALYZE', 'COMPUTE', 'LIST', 'STATISTICS', 'PARTITIONED', 'EXTERNAL', 'DEFINED', 'REVOKE', 'GRANT', 'LOCK', 'UNLOCK', 'MSCK', 'REPAIR', 'RECOVER', 'EXPORT', 'IMPORT', 'LOAD', 'ROLE', 'ROLES', 'COMPACTIONS', 'PRINCIPALS', 'TRANSACTIONS', 'INDEX', 'INDEXES', 'LOCKS', 'OPTION', 'ANTI', 'LOCAL', 'INPATH', 'CURRENT_DATE', 'CURRENT_TIMESTAMP', IDENTIFIER, BACKQUOTED_IDENTIFIER}(line 1, pos 1)
== SQL ==
GÆLDER_FRA_DT > '2016-12-01' and ryk_type in ('52','551','651','751')
-^^^
  at org.apache.spark.sql.catalyst.parser.ParseException.withCommand(ParseDriver.scala:217)
  at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parse(ParseDriver.scala:114)
  at org.apache.spark.sql.execution.SparkSqlParser.parse(SparkSqlParser.scala:48)
  at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parseExpression(ParseDriver.scala:43)
  at org.apache.spark.sql.Dataset.where(Dataset.scala:1344)

How do I handle this? Is there some way for me to say this is a unicode string?

Body:
A single quote worked fine.

jdbcDF.where("'GÆLDER_FRA_DT' > '2016-12-01'")

The backtick is probably the best way to deal with this situation though.

jdbcDF.where("`GÆLDER_FRA_DT` > '2016-12-01'")

ContentLicense: CC BY-SA 4.0


问:
Null in API version Android Studio preview
I updated from Android Studio 2.3 to 3.0 and now none of the previews on the XML editors are shown.

I can see a null in the top bar in the API level selector and it does not give me any option to pick

Any possible solution for that?

I tried Invalidate cache and restart but it does not seem to help.

答:
Just press "Sync Project with gradle" and enjoy :)
Sync icon is present in the toolbar


问:
Join 2 arrays of objects based on grouping properties
With the following JSON API response:

```<code>{
   "default" : [
      {"val_a" : 5 , "val_b": 10, "key_a":"A", "key_b":"X"},
      {"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
      {"val_a" : 6 , "val_b": 12, "key_a":"B", "key_b":"Z"}
   ],
   "alt" : [
      {"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
      {"val_a" : 9 , "val_b": 10, "key_a":"A", "key_b":"X"}
   ]
}
</code>```

I'm trying to write a merging function that will give the following results:

```<code>[
 {"alt_val_a":9, "alt_val_b":10 ,"val_a" : 5 , "val_b": 10, "key_a":"A", "key_b":"X"},
 {"alt_val_a":15, "alt_val_b":11 ,"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
 {"val_a" : 6 , "val_b": 12, "key_a":"B", "key_b":"Z"}
]
</code>```

Explanation:

The results are merged based on 2 properties,"key_a" and "key_b" that produce a unique entry combination. The "alt" prefix is added to the other properties.

EDIT: The grouping keys (key_b , key_a) in the example above are dynamically changing based on the request to the api, so another API response could have another grouping key involved, for example key_c, therefore the function should be generic enough to accept the grouping keys as an array.

Edit 2 Just to make it clear, val_a and val_b are just an example of a specific response. On another response val_c could be present or val_a could be missing.

I'm thinking of a function that accepts the original JSON and an array of group by keys
like so:

```<code>function transformResults(results,groupings){
   //...
}
</code>```

Usage:

```<code>transformResults(originalJSON,["key_a","key_b"]);
</code>```

Any help is appreciated :)

答:
You can iterate over the original results and create a new Object based on the group keys like so:

```<code>{ AX:
   { val_a: 5,
     val_b: 10,
     key_a: 'A',
     key_b: 'X',
     alt_val_a: 9,
     alt_val_b: 10 },
  AY:
   { val_a: 15,
     val_b: 11,
     key_a: 'A',
     key_b: 'Y',
     alt_val_a: 15,
     alt_val_b: 11 },
  BZ: { val_a: 6, val_b: 12, key_a: 'B', key_b: 'Z' } }
</code>```

Then map the keys to the final array.

Here is my generic version:

function transformResults(results, groupings) {
  let reducedResults = Object.keys(results).reduce((modified, originalKey) => {
    //iterating over the original results
    results[originalKey].forEach((row) => {
      //creating a dynamic key based on the grouping key values
      let groupKey = groupings.reduce((resultKey, keyVal) => {
        resultKey = resultKey + row[keyVal];
        return resultKey;
      }, "");

      //iterating over each row values
      Object.keys(row).forEach((rowKey) => {
        //determine if a prefix should be added to the original row key
        let finalKey = (originalKey === 'default' || groupings.indexOf(rowKey) !== -1) ? rowKey : originalKey + "_" + rowKey;
        //creating a modified object where the key is the unique group value
        modified[groupKey] = modified[groupKey] || {};
        modified[groupKey][finalKey] = row[rowKey];
      });
    });
    return modified;
  }, {});

  //mapping the object results and modifying the results to an array
  return Object.keys(reducedResults).map((gKey) => {
    return reducedResults[gKey];
  });
}

let data = {
  "default": [
    {"val_a": 5, "val_b": 10, "key_a": "A", "key_b": "X"},
    {"val_a": 15, "val_b": 11, "key_a": "A", "key_b": "Y"},
    {"val_a": 6, "val_b": 12, "key_a": "B", "key_b": "Z"}
  ],
  "alt": [
    {"val_a": 15, "val_b": 11, "key_a": "A", "key_b": "Y"},
    {"val_a": 9, "val_b": 10, "key_a": "A", "key_b": "X"}
  ]
};

console.log(transformResults(data, ["key_a", "key_b"]));```

Body:
With the following JSON API response:

{
   "default" : [
      {"val_a" : 5 , "val_b": 10, "key_a":"A", "key_b":"X"},
      {"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
      {"val_a" : 6 , "val_b": 12, "key_a":"B", "key_b":"Z"}
   ],
   "alt" : [
      {"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
      {"val_a" : 9 , "val_b": 10, "key_a":"A", "key_b":"X"}
   ]
}

I'm trying to write a merging function that will give the following results:

[
 {"alt_val_a":9, "alt_val_b":10 ,"val_a" : 5 , "val_b": 10, "key_a":"A", "key_b":"X"},
 {"alt_val_a":15, "alt_val_b":11 ,"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
 {"val_a" : 6 , "val_b": 12, "key_a":"B", "key_b":"Z"}
]

Explanation:

The results are merged based on 2 properties,"key_a" and "key_b" that produce a unique entry combination. The "alt" prefix is added to the other properties.

EDIT: The grouping keys (key_b , key_a) in the example above are dynamically changing based on the request to the api, so another API response could have another grouping key involved, for example key_c, therefore the function should be generic enough to accept the grouping keys as an array.

Edit 2 Just to make it clear, val_a and val_b are just an example of a specific response. On another response val_c could be present or val_a could be missing.

I'm thinking of a function that accepts the original JSON and an array of group by keys
like so:

function transformResults(results,groupings){
   //...
}

Usage:

transformResults(originalJSON,["key_a","key_b"]);

Any help is appreciated :)

Body:
You can iterate over the original results and create a new Object based on the group keys like so:

{ AX:
   { val_a: 5,
     val_b: 10,
     key_a: 'A',
     key_b: 'X',
     alt_val_a: 9,
     alt_val_b: 10 },
  AY:
   { val_a: 15,
     val_b: 11,
     key_a: 'A',
     key_b: 'Y',
     alt_val_a: 15,
     alt_val_b: 11 },
  BZ: { val_a: 6, val_b: 12, key_a: 'B', key_b: 'Z' } }

Then map the keys to the final array.

Here is my generic version:

function transformResults(results, groupings) {
  let reducedResults = Object.keys(results).reduce((modified, originalKey) => {
    //iterating over the original results
    results[originalKey].forEach((row) => {
      //creating a dynamic key based on the grouping key values
      let groupKey = groupings.reduce((resultKey, keyVal) => {
        resultKey = resultKey + row[keyVal];
        return resultKey;
      }, "");

      //iterating over each row values
      Object.keys(row).forEach((rowKey) => {
        //determine if a prefix should be added to the original row key
        let finalKey = (originalKey === 'default' || groupings.indexOf(rowKey) !== -1) ? rowKey : originalKey + "_" + rowKey;
        //creating a modified object where the key is the unique group value
        modified[groupKey] = modified[groupKey] || {};
        modified[groupKey][finalKey] = row[rowKey];
      });
    });
    return modified;
  }, {});

  //mapping the object results and modifying the results to an array
  return Object.keys(reducedResults).map((gKey) => {
    return reducedResults[gKey];
  });
}

let data = {
  "default": [
    {"val_a": 5, "val_b": 10, "key_a": "A", "key_b": "X"},
    {"val_a": 15, "val_b": 11, "key_a": "A", "key_b": "Y"},
    {"val_a": 6, "val_b": 12, "key_a": "B", "key_b": "Z"}
  ],
  "alt": [
    {"val_a": 15, "val_b": 11, "key_a": "A", "key_b": "Y"},
    {"val_a": 9, "val_b": 10, "key_a": "A", "key_b": "X"}
  ]
};

console.log(transformResults(data, ["key_a", "key_b"]));


问:
Multiple index properties on a type?
Is it possible to have something like this in C#? I am not very sure:

```<code>class Library
{
    public string Books[string title]
    {
        get{return this.GetBookByName(string title);}
    }

    public DateTime PublishingDates[string title]
    {
        get{return this.GetBookByName(string title).PublishingDate;}
    }
}
</code>```

So it could be used as such:

```<code>myLibrary.Books["V For Vendetta"]
myLibrary.PublishingDates["V For Vendetta"] = ...
</code>```

So my complete member methods that I need to implement in my framework (by calling them) are:

```<code>GetCustomStringValue (key)
GetCustomIntValue (key)
GetCustomBoolValue (key)
GetCustomFloatValue (key)
SetCustomStringValue (key)
SetCustomIntValue (key)
SetCustomBoolValue (key)
SetCustomFloatValue (key)
</code>```

I want to implement them cleaner in my own type.

答:
Why not just use methods?</p>

```<code>class Library
{
    public string Books(string title)
    {
        return this.GetBookByName(title);
    }

    public DateTime PublishingDates(string title)
    {
        return this.GetBookByName(title).PublishingDate;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Multiple index properties on a type?

Body:
Is it possible to have something like this in C#? I am not very sure:

class Library
{
    public string Books[string title]
    {
        get{return this.GetBookByName(string title);}
    }

    public DateTime PublishingDates[string title]
    {
        get{return this.GetBookByName(string title).PublishingDate;}
    }
}

So it could be used as such:

myLibrary.Books["V For Vendetta"]
myLibrary.PublishingDates["V For Vendetta"] = ...

So my complete member methods that I need to implement in my framework (by calling them) are:

GetCustomStringValue (key)
GetCustomIntValue (key)
GetCustomBoolValue (key)
GetCustomFloatValue (key)
SetCustomStringValue (key)
SetCustomIntValue (key)
SetCustomBoolValue (key)
SetCustomFloatValue (key)

I want to implement them cleaner in my own type.

Body:
Why not just use methods?

class Library
{
    public string Books(string title)
    {
        return this.GetBookByName(title);
    }

    public DateTime PublishingDates(string title)
    {
        return this.GetBookByName(title).PublishingDate;
    }
}


问:
Return root to specific leaf from a nested dictionary tree
The nested dictionary tree is of the form,

```<code>categories = [{
    'name': 'Cat1',
    'children': [{
        'name': 'SubCat1',
        'children': [{
            'name': 'SubSubCat1',
            'children': []
         }]
     }]
}, {
    'name': 'Cat2',
    'children': []
}]
</code>```

The recursive function should return the path from root to a specific leaf.

Lets say, function(categories, 'SubCat1') should return a list containing ['Cat1', 'SubCat1']. Likewise for function(categories, 'Cat2') should return the ['Cat2'].

Progress made so far

```<code>def recurse_category(categories, to_find):
    def _recurse_category(categories, to_find, path=[]):
        for category in categories:
            path.append(category['name'])
            if len(category['children']) == 0 and category['name'] != to_find:
                return path, False

            if category['name'] == to_find:
                return path, True
            else:
                recurse_category(
                    category['children'], to_find, path
                )
    return _recurse_category(categories, to_find, path=[])
</code>```

答:
Don't pass along a list; it'll accumulate all searched paths, not just the one that matches. Build up the list as you recurse, by concatenating. You also need to process the result of the recursive call; your code ignores that result.

The following works, note that when we recurse (in if category['children']) the code has to check if a path was found in that subtree:

```<code>def recurse_category(categories, to_find):
    for category in categories:
        if category['name'] == to_find:
            return True, [category['name']]
        if category['children']:
            found, path = recurse_category(category['children'], to_find)
            if found:
                return True, [category['name']] + path
    return False, []
</code>```

This returns a boolean (true if found) and the path:

```<code>>>> recurse_category(categories, 'SubCat1')
(True, ['Cat1', 'SubCat1'])
>>> recurse_category(categories, 'Cat2')
(True, ['Cat2'])
>>> recurse_category(categories, 'Nonesuch')
(False, [])
</code>```

Body:
The nested dictionary tree is of the form,

categories = [{
    'name': 'Cat1',
    'children': [{
        'name': 'SubCat1',
        'children': [{
            'name': 'SubSubCat1',
            'children': []
         }]
     }]
}, {
    'name': 'Cat2',
    'children': []
}]

The recursive function should return the path from root to a specific leaf.

Lets say, function(categories, 'SubCat1') should return a list containing ['Cat1', 'SubCat1']. Likewise for function(categories, 'Cat2') should return the ['Cat2'].

Progress made so far

def recurse_category(categories, to_find):
    def _recurse_category(categories, to_find, path=[]):
        for category in categories:
            path.append(category['name'])
            if len(category['children']) == 0 and category['name'] != to_find:
                return path, False

            if category['name'] == to_find:
                return path, True
            else:
                recurse_category(
                    category['children'], to_find, path
                )
    return _recurse_category(categories, to_find, path=[])

Body:
Don't pass along a list; it'll accumulate all searched paths, not just the one that matches. Build up the list as you recurse, by concatenating. You also need to process the result of the recursive call; your code ignores that result.

The following works, note that when we recurse (in if category['children']) the code has to check if a path was found in that subtree:

def recurse_category(categories, to_find):
    for category in categories:
        if category['name'] == to_find:
            return True, [category['name']]
        if category['children']:
            found, path = recurse_category(category['children'], to_find)
            if found:
                return True, [category['name']] + path
    return False, []

This returns a boolean (true if found) and the path:

>>> recurse_category(categories, 'SubCat1')
(True, ['Cat1', 'SubCat1'])
>>> recurse_category(categories, 'Cat2')
(True, ['Cat2'])
>>> recurse_category(categories, 'Nonesuch')
(False, [])


问:
How to access Session variables and set them in javascript?
In code-behind I set Session with some data.

```<code>Session["usedData"] = "sample data";
</code>```

And the question is how can I get the Session value(in my example; "sample data") in javascript and set Session["usedData"] with a new value?

Body:
In code-behind I set Session with some data.

Session["usedData"] = "sample data";

And the question is how can I get the Session value(in my example; "sample data") in javascript and set Session["usedData"] with a new value?

Body:
If you want read Session value in javascript.This code help for you.

<script type='text/javascript'>
 var userID='@Session["userID"]';
</script>


问:
Restrict uploaded image size Camera plugin cordova ionic
I have fetched the image using Camera plugin in my ionic app. I want to restrict the user on the size of the image which user is choosing, lets say 200kb. I have added Camera as File plugin.

I have used below code:

```<code>/*Function to get image from gallery*/
$scope.getImageFromGallery = function(){
    var options = {
        quality: 100,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: false,
        targetWidth: 450,
        targetHeight: 450,
        encodingType: Camera.EncodingType.JPEG,
    };

    navigator.camera.getPicture(gallerySuccess, galleryError, options);

    function gallerySuccess(imageURI){
        getSize(imageURI);
    }

    function getSize(fileUri) {
        window.resolveLocalFileSystemURL(fileUri, function(fileEntry){

            fileEntry.getMetadata(function(metadata){
                console.log("size is "+metadata.size);
            }, resOnError);

            fileEntry.file(function(file) {

                var reader = new FileReader();
                reader.onloadend = function(evt) {

                    var imgData = evt.target.result;
                    var res = imgData.split(",");
                    $rootScope.imagebase64 = res[1];
                    var image = document.getElementById('preview-image1');
                    image.src = evt.target.result;
                    $('#preview-image').css('display','block');
                    $('#preview-image').css('background-image', "url("+res[1]+")").show();
                };

                reader.readAsDataURL(file);
            }, resOnError);
        },
        resOnError);
    }

    function resOnError(error) {
        console.log("error "+JSON.stringify(error));
    }

    function galleryError(error) {
    }
}
</code>```

But here, when I'm choosing image of 2.5MB, it is showing size 178908
and when I'm choosing image of size 8.9MB, it is showing size 88412.

As per my knowledge, the file size is in bytes, but the values which I'm getting are not correct.

答:
try this solution this is for 150kb for yours just change it to 200kb</p>

```<code>  window.resolveLocalFileSystemURI(newPath, function (fileEntry) {
                        fileEntry.file(function (fileObj) {
                            if (fileObj.size <= 153600) {
                                var reader = new FileReader();
                                reader.onload = function () {
                                    var dataURL = reader.result;
                                    //your stuff.....
                                };
                                reader.readAsDataURL(fileObj);
                            }
                            else {
                                //  alert("Please upload image less then 150KB");
                                alertPopup = $ionicPopup.alert({
                                    title: 'Upload image failed!',
                                    template: 'Please upload image less then 150KB!'
                                });
                            }

                            console.log("Size = " + fileObj.size);
                        });
                    });
</code>```

Body:
I have fetched the image using Camera plugin in my ionic app. I want to restrict the user on the size of the image which user is choosing, lets say 200kb. I have added Camera as File plugin.

I have used below code:

/*Function to get image from gallery*/
$scope.getImageFromGallery = function(){
    var options = {
        quality: 100,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: false,
        targetWidth: 450,
        targetHeight: 450,
        encodingType: Camera.EncodingType.JPEG,
    };

    navigator.camera.getPicture(gallerySuccess, galleryError, options);

    function gallerySuccess(imageURI){
        getSize(imageURI);
    }

    function getSize(fileUri) {
        window.resolveLocalFileSystemURL(fileUri, function(fileEntry){

            fileEntry.getMetadata(function(metadata){
                console.log("size is "+metadata.size);
            }, resOnError);

            fileEntry.file(function(file) {

                var reader = new FileReader();
                reader.onloadend = function(evt) {

                    var imgData = evt.target.result;
                    var res = imgData.split(",");
                    $rootScope.imagebase64 = res[1];
                    var image = document.getElementById('preview-image1');
                    image.src = evt.target.result;
                    $('#preview-image').css('display','block');
                    $('#preview-image').css('background-image', "url("+res[1]+")").show();
                };

                reader.readAsDataURL(file);
            }, resOnError);
        },
        resOnError);
    }

    function resOnError(error) {
        console.log("error "+JSON.stringify(error));
    }

    function galleryError(error) {
    }
}

But here, when I'm choosing image of 2.5MB, it is showing size 178908
and when I'm choosing image of size 8.9MB, it is showing size 88412.

As per my knowledge, the file size is in bytes, but the values which I'm getting are not correct.

Body:
try this solution this is for 150kb for yours just change it to 200kb

  window.resolveLocalFileSystemURI(newPath, function (fileEntry) {
                        fileEntry.file(function (fileObj) {
                            if (fileObj.size <= 153600) {
                                var reader = new FileReader();
                                reader.onload = function () {
                                    var dataURL = reader.result;
                                    //your stuff.....
                                };
                                reader.readAsDataURL(fileObj);
                            }
                            else {
                                //  alert("Please upload image less then 150KB");
                                alertPopup = $ionicPopup.alert({
                                    title: 'Upload image failed!',
                                    template: 'Please upload image less then 150KB!'
                                });
                            }

                            console.log("Size = " + fileObj.size);
                        });
                    });


问:
If you change a global variable in a vim plugin (python-mode) and reload it, isn’t it equivalent to just loading the .vimrc at startup?
Using Vim version: 7.4

In this line of the Python-mode documentation: https://github.com/python-mode/python-mode/blob/01c3131343aaa3c76f8cb656b5e9f54ac90ca04b/doc/pymode.txt#L234

it says that I can turn-on the variable (g:pymode_run) using

let g:pymode_run=1,

to run my python file using “:PymodeRun” or use it via ‘<leader>r’

If there is no modification to my Vimrc file, the default setting is:

```<code>let g:pymode_run=1
</code>```

However, if the default setting in your vimrc file is

let g:pymode_run=0,

you load your .vimrc, and attempt to then change the variable using
let pymode_run=1 or let g:pymode_run=1 (both of this is equivalent, as we are dealing with the global variable here),

:PymodeRun doesn’t work.

If you do “:so ~/.vimrc” after changing let g:pymode_run=1, it doesn’t work either.

The only solution to this, that I found, is to change to “let g:pymode_run=1” in your  ~/.vimrc, shutdown VIM and restart vim.
Then it works as expected.

Since pymode_run is a variable which determines whether :PymodeRun should run or not, shouldn’t changing the variable pymode_run from 0 to 1 in the current VIM session, also enable running :PymodeRun, withough having to reload VIM?

答:
g:pymode_run seems to be used here, which means that the variable is used to decide if the command :PymodeRun (and related bindings) should be defined or not in the first place. In other words, it isn't checked when calling :PymodeRun, but is checked on editing python files. This is why setting the value afterwards doesn't work. This is probably because changing the option while editing is not expected (I don't see much rationale either).

As this variable is checked in ftplugin, I believe reloading the file (:ed %) suffices for let g:pymode_run=1 to take effect.

Body:
Using Vim version: 7.4

In this line of the Python-mode documentation: https://github.com/python-mode/python-mode/blob/01c3131343aaa3c76f8cb656b5e9f54ac90ca04b/doc/pymode.txt#L234

it says that I can turn-on the variable (g:pymode_run) using

let g:pymode_run=1,

to run my python file using “:PymodeRun” or use it via ‘<leader>r’

If there is no modification to my Vimrc file, the default setting is:

let g:pymode_run=1

However, if the default setting in your vimrc file is

let g:pymode_run=0,

you load your .vimrc, and attempt to then change the variable using
let pymode_run=1 or let g:pymode_run=1 (both of this is equivalent, as we are dealing with the global variable here),

:PymodeRun doesn’t work.

If you do “:so ~/.vimrc” after changing let g:pymode_run=1, it doesn’t work either.

The only solution to this, that I found, is to change to “let g:pymode_run=1” in your  ~/.vimrc, shutdown VIM and restart vim.
Then it works as expected.

Since pymode_run is a variable which determines whether :PymodeRun should run or not, shouldn’t changing the variable pymode_run from 0 to 1 in the current VIM session, also enable running :PymodeRun, withough having to reload VIM?


问:
Add class to parent when child get a new class?
How can I add class .myclass to li when its child (a.nav-link) get class .active?

       Home

       Profile

```

答:
You can loop in anchor tag inside li and add your desire class in it's parent if it has class active.

$("ul li a").each(function(index) {
  if($(this).hasClass('active'))
  $(this).parent('li').addClass('myclass');
});```
<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>
<ul class="nav-tabs" id="myTab" role="tablist">
  <li class="nav-item">
    Home
  </li>
  <li class="nav-item">
    Profile
  </li>
</ul></code>```

Body:
You can loop in anchor tag inside li and add your desire class in it's parent if it has class active.

$("ul li a").each(function(index) {
  if($(this).hasClass('active'))
  $(this).parent('li').addClass('myclass');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav-tabs" id="myTab" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Profile</a>
  </li>
</ul>


问:
PHP & Ajax - can i use POST to retrieve form value without reload
I have a php file "Criteria" to display a bunch of html multi select dropdowns that can be used to create criteria for a query.

I have a php file "Results" which builds an SQL statement according to the selected options from various dropdowns, executes the query, and then displays the results of that query.

I would like to skip having to reload & echo all the html for each select dropdown, as they each contain hundreds of options.  Ajax was my solution for this.

For each dropdown, an onchange event calls my javascript, which executes an Ajax call to my "Results" page.  This "Results" page would then get the value of each select dropdown using $_POST['htmlSelectDropdownID'].

The problem, now that I have implemented Ajax, is that the selected value from the select dropdowns is not coming across to my Results file... and I can only assume this is because the HTML never reloaded...

Does anybody have a suggestion of how to resolve this issue?

Thanks,

------------------------ code --------------------------

My Javascript / Ajax

```<code> function AjaxPostback(){
/*if (str=="")
{
    document.getElementById("divTest").innerHTML="";
    return;
} */
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4)// && xmlhttp.status==200)
    {
        document.getElementById("divResults").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","Results.php", true); //?q="+str,true);
xmlhttp.send();}
</code>```

Just 1 of the dropdown on my page

```<code>Group By <select id="selGroupBy" name="selGroupBy" onchange="AjaxPostback()">
            <option value='Department' <?php if ($_POST['selGroupBy'] == 'Department') echo 'selected="selected"'; ?>>Department</option>
            <option value='Store' <?php if ($_POST['selGroupBy'] == 'Store') echo 'selected="selected"'; ?>>Store</option>
            <option value='Date' <?php if ($_POST['selGroupBy'] == 'Date') echo 'selected="selected"'; ?>>Date</option>
            <option value='Size' <?php if ($_POST['selGroupBy'] == 'Size') echo 'selected="selected"'; ?>>Size</option>
        </select>
</code>```

--
The html that builds the Criteria (dropdown html) and the div (divResults) who's innerHTML is filled with the javascript

```<code><div>
            <?php include ("Criteria.php"); ?>

            <div class="divResults" id="divResults">

            </div>
        </div>
</code>```

When called, my Results.php file simply checks to document for things like..
if (isset($_POST['selDepartment']) && ($_POST['selDepartment'] == "320 Socks") {
  $sqlSelect .= $_POST['selDepartment'];
}

I have also tried using $_GET instead of $_POST to retrieve the value, same result.. =\

答:
It seems that you never send any param to your Results page. Try to add this:

```<code>xmlhttp.open("GET","Results.php?selGroupBy="+document.getElementById("selGroupBy").value, true); //?q="+str,true);
</code>```

And get it on your php page with:

```<code>$val = $_GET['selGroupBy'];
</code>```

Well, I maybe not understand your prob.

Body:
I have a php file "Criteria" to display a bunch of html multi select dropdowns that can be used to create criteria for a query.

I have a php file "Results" which builds an SQL statement according to the selected options from various dropdowns, executes the query, and then displays the results of that query.

I would like to skip having to reload & echo all the html for each select dropdown, as they each contain hundreds of options.  Ajax was my solution for this.

For each dropdown, an onchange event calls my javascript, which executes an Ajax call to my "Results" page.  This "Results" page would then get the value of each select dropdown using $_POST['htmlSelectDropdownID'].

The problem, now that I have implemented Ajax, is that the selected value from the select dropdowns is not coming across to my Results file... and I can only assume this is because the HTML never reloaded...

Does anybody have a suggestion of how to resolve this issue?

Thanks,

------------------------ code --------------------------

My Javascript / Ajax

 function AjaxPostback(){
/*if (str=="")
{
    document.getElementById("divTest").innerHTML="";
    return;
} */
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4)// && xmlhttp.status==200)
    {
        document.getElementById("divResults").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","Results.php", true); //?q="+str,true);
xmlhttp.send();}

Just 1 of the dropdown on my page

Group By <select id="selGroupBy" name="selGroupBy" onchange="AjaxPostback()">
            <option value='Department' <?php if ($_POST['selGroupBy'] == 'Department') echo 'selected="selected"'; ?>>Department</option>
            <option value='Store' <?php if ($_POST['selGroupBy'] == 'Store') echo 'selected="selected"'; ?>>Store</option>
            <option value='Date' <?php if ($_POST['selGroupBy'] == 'Date') echo 'selected="selected"'; ?>>Date</option>
            <option value='Size' <?php if ($_POST['selGroupBy'] == 'Size') echo 'selected="selected"'; ?>>Size</option>
        </select>

--
The html that builds the Criteria (dropdown html) and the div (divResults) who's innerHTML is filled with the javascript

            <?php include ("Criteria.php"); ?>

When called, my Results.php file simply checks to document for things like..
if (isset($_POST['selDepartment']) && ($_POST['selDepartment'] == "320 Socks") {
  $sqlSelect .= $_POST['selDepartment'];
}

I have also tried using $_GET instead of $_POST to retrieve the value, same result.. =\

Body:
It seems that you never send any param to your Results page. Try to add this:

xmlhttp.open("GET","Results.php?selGroupBy="+document.getElementById("selGroupBy").value, true); //?q="+str,true);

And get it on your php page with:

$val = $_GET['selGroupBy'];

Well, I maybe not understand your prob.


问:
What are the benefits of css selector syntax with Selenium
When using css selectors to find elements, you can write them in several ways.  For example:

```<code>driver.FindElement(By.CssSelector("header.top-bar.js-top-bar._fixed"));
</code>```

vs

```<code>driver.FindElement(By.CssSelector("header[class='top-bar js-top-bar _fixed']"));
</code>```

and

```<code>driver.FindElement(By.CssSelector("form[id='search'][action='/search']"));
</code>```

vs

```<code>driver.FindElement(By.CssSelector("form#search[action='/search']"));
</code>```

For me it's just a personal preferences using one over the other, but I was wondering if there are any performance benefits in using for example:

header.top-bar.js-top-bar._fixed vs header[class='top-bar js-top-bar _fixed']

答:
You can use "CSS Test Creator" which lets you test the speed of different CSS selectors:

http://stevesouders.com/efws/css-selectors/csscreate.php

I tested both tag.class and tag[class='class'] using 10,000 rules and 10,000 anchors. Running each test 5 times, I got the following results:

```<code>+----------+-----------+----------+
|  Test #  | tag.class|tag[class|
+----------+-----------+----------+
|    1     |  226 ms  |  177 ms |
|    2     |  197 ms  |  211 ms |
|    3     |  228 ms  |  177 ms |
|    4     |  207 ms  |  200 ms |
|    5     |  209 ms  |  198 ms |
+----------+-----------+----------+
|  AVERAGE |  213 ms  |  192 ms |
+----------+-----------+----------+
</code>```

Based on the above inference its safe to say that tag[class='class'] has better performance than tag.class

Body:
When using css selectors to find elements, you can write them in several ways.  For example:

driver.FindElement(By.CssSelector("header.top-bar.js-top-bar._fixed"));

vs

driver.FindElement(By.CssSelector("header[class='top-bar js-top-bar _fixed']"));

and

driver.FindElement(By.CssSelector("form[id='search'][action='/search']"));

vs

driver.FindElement(By.CssSelector("form#search[action='/search']"));

For me it's just a personal preferences using one over the other, but I was wondering if there are any performance benefits in using for example:

header.top-bar.js-top-bar._fixed vs header[class='top-bar js-top-bar _fixed']

Body:
You can use "CSS Test Creator" which lets you test the speed of different CSS selectors:

http://stevesouders.com/efws/css-selectors/csscreate.php

I tested both tag.class and tag[class='class'] using 10,000 rules and 10,000 anchors. Running each test 5 times, I got the following results:

+----------+-----------+----------+
|  Test #  | tag.class|tag[class|
+----------+-----------+----------+
|    1     |  226 ms  |  177 ms |
|    2     |  197 ms  |  211 ms |
|    3     |  228 ms  |  177 ms |
|    4     |  207 ms  |  200 ms |
|    5     |  209 ms  |  198 ms |
+----------+-----------+----------+
|  AVERAGE |  213 ms  |  192 ms |
+----------+-----------+----------+

Based on the above inference its safe to say that tag[class='class'] has better performance than tag.class


问:
Promise-based functions for dialogflow's action map
Setting up a Google Assistant App via the NodeJS Google Actions SDK is done this way:

It seems that these are synchronous functions (per the documentation given on https://developers.google.com/actions/reference/nodejs/ActionsSdkApp#ActionsSdkApp

```<code>const app = new App({request: req, response: res});
function pickOption (app) {
   /*A bunch of steps here*/
}
function optionPicked (app) {
   /*Another bunch of steps here*/
}

const actionMap = new Map();
actionMap.set(app.StandardIntents.TEXT, pickOption);
actionMap.set(app.StandardIntents.OPTION, optionPicked);

app.handleRequest(actionMap);
</code>```

Is it possible for pickOption and optionPicked to be asynchronous functions? i.e., would it be correct to have pickOption be implemented as

```<code>function pickOption(){
   var pickOptionPromise = Q.defer();
   pickOptionPromise.resolve({
     /*Some results here*/
   });
   return pickOptionPromise.promise;
}
</code>```

答:
Yes, there are two functions you'll use most of the time to return a response to the Assistant. app.ask and app.tell. These wrap your response into a JSON object and return it to Google.

Your pickOption and optionPicked functions can be run asynchronously and run app.tell after your logic is completed.

Body:
Setting up a Google Assistant App via the NodeJS Google Actions SDK is done this way:

It seems that these are synchronous functions (per the documentation given on https://developers.google.com/actions/reference/nodejs/ActionsSdkApp#ActionsSdkApp

const app = new App({request: req, response: res});
function pickOption (app) {
   /*A bunch of steps here*/
}
function optionPicked (app) {
   /*Another bunch of steps here*/
}

const actionMap = new Map();
actionMap.set(app.StandardIntents.TEXT, pickOption);
actionMap.set(app.StandardIntents.OPTION, optionPicked);

app.handleRequest(actionMap);

Is it possible for pickOption and optionPicked to be asynchronous functions? i.e., would it be correct to have pickOption be implemented as

function pickOption(){
   var pickOptionPromise = Q.defer();
   pickOptionPromise.resolve({
     /*Some results here*/
   });
   return pickOptionPromise.promise;
}


问:
How Do I set a Teamcity Trigger on a Particular Folder for Git VCS trigger
I would like Teamcity to Trigger a build when there is a gerrit change on a specific branch on a specific folder. I'm unable to achieve the same, any suggestions from all you experienced users out there is greatly appreciated.

Following is how my Structure looks like, I want the build to be triggered of both the Branch dev & Staging, any change under New/Folder/My_Content only and not on any other foder , file content

```<code> - Branch dev
  --Repo
     * New/Folder/My_Content
     * Folder 2
     * Folder 3
     * File1.txt
     * File1.html
     * File1.log

 - Branch Staging
  --Repo
     * New/Folder/My_Content
     * Folder 2
     * Folder 3
     * File1.txt
     * File1.html
     * File1.log
</code>```

This is what I have tried

```<code>VCS root name: my_root

set on branches

+:refs/(changes/*)
+:refs/heads/dev
+:refs/heads/Staging

VCS Trigger rules:
+:root=my_root:New/Folder/My_Content/**
Branch filter:
+:changes/*
</code>```

The above rules always trigger builds on everything, on all the folders apart from the one I need.

And the second question I had was, Can I use parameters in the VCS Trigger rules.
Something as follows.

```<code>VCS Trigger rules:
+:root=my_root:New/Folder/%my_var%/**
Branch filter:
+:changes/*
</code>```

答:
You just need to add two VCS Roots for the branches dev and Staging you want to trigger and specify the file path you need to trigger.
Detail settings as below:

In Version Control Settings Tab, add two VCS roots separately:

First VCS root name is <repo URL>+:refs/heads/dev, default branch is refs/heads/dev.

Second VCS root name is <repo URL>+:refs/heads/Staging, default branch is refs/heads/Staging.

Below is an example VCS root configuration:

For VCS checkout mode, you can select Always checkout files on agent, and select Allow builds in the default branch.

In Triggers Tab, set the trigger rule as +:New/Folder/My_Content/**.

Body:
I would like Teamcity to Trigger a build when there is a gerrit change on a specific branch on a specific folder. I'm unable to achieve the same, any suggestions from all you experienced users out there is greatly appreciated.

Following is how my Structure looks like, I want the build to be triggered of both the Branch dev & Staging, any change under New/Folder/My_Content only and not on any other foder , file content

 - Branch dev
  --Repo
     * New/Folder/My_Content
     * Folder 2
     * Folder 3
     * File1.txt
     * File1.html
     * File1.log

 - Branch Staging
  --Repo
     * New/Folder/My_Content
     * Folder 2
     * Folder 3
     * File1.txt
     * File1.html
     * File1.log

This is what I have tried

VCS root name: my_root

set on branches

+:refs/(changes/*)
+:refs/heads/dev
+:refs/heads/Staging

VCS Trigger rules:
+:root=my_root:New/Folder/My_Content/**
Branch filter:
+:changes/*

The above rules always trigger builds on everything, on all the folders apart from the one I need.

And the second question I had was, Can I use parameters in the VCS Trigger rules.
Something as follows.

VCS Trigger rules:
+:root=my_root:New/Folder/%my_var%/**
Branch filter:
+:changes/*


问:
Read CSV data and add it into dictionary
This is an empty Dictionary

```<code>d = {}
</code>```

This is the csv file data

```<code>M, Max, Sporting, Football, Cricket
M, Jack, Sporting, Cricket, Tennis
M, Kevin, Sporting, Cricket, Basketball
M, Ben, Sporting, Football, Rugby
</code>```

I tried to use the following code to append data from the csv to dictionary.

```<code>with open('example.csv', "r") as csvfile:
        csv_reader = csv.reader(csvfile)
        for row in csv_reader:
            if row:
                d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
</code>```

But it gives me an error:

```<code>d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
IndexError: list index out of range
</code>```

It there any way, i can add data from csv to the dictionary, in the form:

```<code>d = {'M': {'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}}}
</code>```

I am new to this so help me.

答:
```<code>import csv

d={}
with open('JJ.csv', "r") as csvfile:
    csv_reader = csv.reader(csvfile)
    for row in csv_reader:
        if row:
            d.setdefault(row[0],{})[row[1]] = {row[2]: [row[3],row[4]]}
print(d)

{'M': {' Max': {' Sporting': [' Football', ' Cricket']}, ' Jack': {' Sporting': [' Cricket', ' Tennis']}, ' Kevin': {' Sporting': [' Cricket', ' Basketball']}, ' Ben': {' Sporting': [' Football', ' Rugby']}}}
</code>```

To remove all the leading/trailing spaces in the output, you can use the below line instead. There might be a better way which I'm not sure as of now.

```<code>d.setdefault(row[0],{})[row[1].strip()] = {row[2].strip(): [row[3].strip(),row[4].strip()]}
</code>```

Body:
This is an empty Dictionary

d = {}

This is the csv file data

M, Max, Sporting, Football, Cricket
M, Jack, Sporting, Cricket, Tennis
M, Kevin, Sporting, Cricket, Basketball
M, Ben, Sporting, Football, Rugby

I tried to use the following code to append data from the csv to dictionary.

with open('example.csv', "r") as csvfile:
        csv_reader = csv.reader(csvfile)
        for row in csv_reader:
            if row:
                d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}

But it gives me an error:

d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
IndexError: list index out of range

It there any way, i can add data from csv to the dictionary, in the form:

d = {'M': {'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}}}

I am new to this so help me.

Body:
import csv

d={}
with open('JJ.csv', "r") as csvfile:
    csv_reader = csv.reader(csvfile)
    for row in csv_reader:
        if row:
            d.setdefault(row[0],{})[row[1]] = {row[2]: [row[3],row[4]]}
print(d)

{'M': {' Max': {' Sporting': [' Football', ' Cricket']}, ' Jack': {' Sporting': [' Cricket', ' Tennis']}, ' Kevin': {' Sporting': [' Cricket', ' Basketball']}, ' Ben': {' Sporting': [' Football', ' Rugby']}}}

To remove all the leading/trailing spaces in the output, you can use the below line instead. There might be a better way which I'm not sure as of now.

d.setdefault(row[0],{})[row[1].strip()] = {row[2].strip(): [row[3].strip(),row[4].strip()]}


问:
prevent rounding off of timestamp in mysql
I have a MySQL table with a single field of type TIMESTAMP.
When I insert a timestamp into the table, it is getting rounded off.

For example - if I do a

```<code>insert into tablename (time) values ("2014-08-25 23:59:59.587");
</code>```

and then I do a

```<code>select * from tablename;
</code>```

I get

```<code>2014-08-26 00:00:00
</code>```

This is causing a bug in my code where I use the timestamp of the last record to determine where a new day has started.

How do I ensure that the fractional part gets stored as it is?
(or if it is getting stored correctly, then how do I retrieve it - (using Java))

I am using MySQL 5.6.16 and Java 8
(although the problem does not require java and can be verified from the command line)

When using Java,

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;

public class DBTest {

    public static void main(String[] args) {

           try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection dbConn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/demod?useUnicode=true&characterEncoding=utf8", "dawon","1111");
            Statement stmt = dbConn.createStatement();
            String sql = "SELECT TEST FROM TIME;";
            ResultSet rs = stmt.executeQuery(sql);
            rs.next();
            Timestamp ts = rs.getTimestamp("TEST");
            System.out.println("time" + ts.toString() + " " + rs.getTimestamp("TEST"));
            //both print out the rounded off value
           } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}
</code>```

答:
[Posting to save time for others]

I faced a similar problem with mysql/aurora.

I was trying to use new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createdOn) in the queries, but found out that SimpleDateFormat simply drops additional fields.

Hibernate's default mapping of Date fields to MySQL DateTime columns (using the annotation @Temporal(TemporalType.TIMESTAMP)) was rounding off the milliseconds.

In order to generate consistent queries i had to implement rounding off myself while using SimpleDateFormat.

Example round off code:

```<code>Calendar cal = Calendar.getInstance();
cal.setTime(this.getCreatedOn());
if (cal.get(Calendar.MILLISECOND) >= 500 ) {
  System.out.println("Round off milliseconds to seconds");
  cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + 1);
}
</code>```

Usage in queries:

createdOn = "'" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(roundedCreatedOn)+ "'"

Body:
I have a MySQL table with a single field of type TIMESTAMP.
When I insert a timestamp into the table, it is getting rounded off.

For example - if I do a

insert into tablename (time) values ("2014-08-25 23:59:59.587");

and then I do a

select * from tablename;

I get

2014-08-26 00:00:00

This is causing a bug in my code where I use the timestamp of the last record to determine where a new day has started.

How do I ensure that the fractional part gets stored as it is?
(or if it is getting stored correctly, then how do I retrieve it - (using Java))

I am using MySQL 5.6.16 and Java 8
(although the problem does not require java and can be verified from the command line)

When using Java,

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;

public class DBTest {

    public static void main(String[] args) {

           try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection dbConn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/demod?useUnicode=true&characterEncoding=utf8", "dawon","1111");
            Statement stmt = dbConn.createStatement();
            String sql = "SELECT TEST FROM TIME;";
            ResultSet rs = stmt.executeQuery(sql);
            rs.next();
            Timestamp ts = rs.getTimestamp("TEST");
            System.out.println("time" + ts.toString() + " " + rs.getTimestamp("TEST"));
            //both print out the rounded off value
           } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

Body:
[Posting to save time for others]

I faced a similar problem with mysql/aurora.

I was trying to use new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createdOn) in the queries, but found out that SimpleDateFormat simply drops additional fields.

Hibernate's default mapping of Date fields to MySQL DateTime columns (using the annotation @Temporal(TemporalType.TIMESTAMP)) was rounding off the milliseconds.

In order to generate consistent queries i had to implement rounding off myself while using SimpleDateFormat.

Example round off code:

Calendar cal = Calendar.getInstance();
cal.setTime(this.getCreatedOn());
if (cal.get(Calendar.MILLISECOND) >= 500 ) {
  System.out.println("Round off milliseconds to seconds");
  cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + 1);
}

Usage in queries:

createdOn = "'" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(roundedCreatedOn)+ "'"


问:
Why do lots of (old) programs use floor(0.5 + input) instead of round(input)?
The differences reside in the returned value giving inputs around tie-breaking I believe, such as this code:

```<code>int main()
{
    std::cout.precision(100);

    double input = std::nextafter(0.05, 0.0) / 0.1;
    double x1 = floor(0.5 + input);
    double x2 = round(input);

    std::cout << x1 << std::endl;
    std::cout << x2 << std::endl;
}
</code>```

which outputs:

```<code>1
0
</code>```

But they are just different results in the end, one chooses its preferred one. I see lots of "old" C/C++ programs using floor(0.5 + input) instead of round(input).

Is there any historic reason? Cheapest on the CPU?

答:
There is no historic reason whatsoever. This kind of deviance has been around since year dot. It's an abuse of floating point arithmetic, and many experienced professional programmers fall for it. Even the Java bods did up to version 1.7. Funny guys.

My conjecture is that a decent out-of-the-box rounding function was not formally available until C++11 (despite C getting theirs in C99), but that really is no excuse for adopting the so-called alternative.

Here's the thing: floor(0.5 + input) does not always recover the same result as the corresponding std::round call!

The reason is quite subtle: the cutoff point for rounding, a.5 for an integer a is a dyadic rational. As this can be represented exactly in an IEEE754 floating point up to the 52nd power of 2, and thereafter rounding is a no-op anyway, std::round always works properly. For other floating point schemes, consult the documentation.

But adding 0.5 to a double can introduce imprecision causing a slight under or overshoot for some values. If you think about it, adding two double values together - that are the inception of unwitting denary conversions - and applying a function that is a very strong function of the input (such as a rounding function), is bound to end in tears.

Don't do it.

Reference: Why does Math.round(0.49999999999999994) return 1?

Body:
The differences reside in the returned value giving inputs around tie-breaking I believe, such as this code:

int main()
{
    std::cout.precision(100);

    double input = std::nextafter(0.05, 0.0) / 0.1;
    double x1 = floor(0.5 + input);
    double x2 = round(input);

    std::cout << x1 << std::endl;
    std::cout << x2 << std::endl;
}

which outputs:

1
0

But they are just different results in the end, one chooses its preferred one. I see lots of "old" C/C++ programs using floor(0.5 + input) instead of round(input).

Is there any historic reason? Cheapest on the CPU?


答: std::round is introduced in C++11. Before that, only std::floor was available so programmers were using it.

Title: Why do lots of (old) programs use floor(0.5 + input) instead of round(input)?


问:
What indicates an Office Open XML Cell contains a Date/Time value?
I'm reading an .xlsx file using the Office Open XML SDK and am confused about reading Date/Time values.  One of my spreadsheets has this markup (generated by Excel 2010)

```<code><x:row r="2" spans="1:22" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <x:c r="A2" t="s">
    <x:v>56</x:v>
  </x:c>
  <x:c r="B2" t="s">
    <x:v>64</x:v>
  </x:c>
  .
  .
  .
  <x:c r="J2" s="9">
    <x:v>17145</x:v>
  </x:c>
</code>```

Cell J2 has a date serial value in it and a style attribute s="9".  However, the Office Open XML Specification says that 9 corresponds to a followed hyperlink.  This is a screen shot from page 4,999 of ECMA-376, Second Edition, Part 1 - Fundamentals And Markup Language Reference.pdf.

The presetCellStyles.xml file included with the spec also refers to builtinId 9 as a followed hyperlink.

```<code><followedHyperlink builtinId="9">
</code>```

All of the styles in the spec are simply visual formatting styles, not number styles.  Where are the number styles defined and how does one differentiate a style reference s="9" from indicating a cell formatting (visual) style vs a number style?

Obviously I'm looking in the wrong place to match styles on cells with their number formats.  Where's the right place to find this information?

答:
In styles.xml see if there is a numFmt node.  I think that will hold a numFmtId of "9" which will relate to the date format that's used.

I don't know where that is in the ECMA, but if you search for numFmt, you might find it.

Body:
I'm reading an .xlsx file using the Office Open XML SDK and am confused about reading Date/Time values.  One of my spreadsheets has this markup (generated by Excel 2010)

<x:row r="2" spans="1:22" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <x:c r="A2" t="s">
    <x:v>56</x:v>
  </x:c>
  <x:c r="B2" t="s">
    <x:v>64</x:v>
  </x:c>
  .
  .
  .
  <x:c r="J2" s="9">
    <x:v>17145</x:v>
  </x:c>

Cell J2 has a date serial value in it and a style attribute s="9".  However, the Office Open XML Specification says that 9 corresponds to a followed hyperlink.  This is a screen shot from page 4,999 of ECMA-376, Second Edition, Part 1 - Fundamentals And Markup Language Reference.pdf.

The presetCellStyles.xml file included with the spec also refers to builtinId 9 as a followed hyperlink.

<followedHyperlink builtinId="9">

All of the styles in the spec are simply visual formatting styles, not number styles.  Where are the number styles defined and how does one differentiate a style reference s="9" from indicating a cell formatting (visual) style vs a number style?

Obviously I'm looking in the wrong place to match styles on cells with their number formats.  Where's the right place to find this information?


问:
How to use IF with And and OR in Excell?
I am using a FIFA 8 dataset for a project. There are various fields like age, rating, value and wage. Now I want to make a column of whether the player should be bought or not. I want to make this in Excel. I want to use a condition such as:

```<code>IF(Age<30 & Rating >90 & Value>100) OR If (Age<25 & Rating >85 & Value >70 ) then buy
</code>```

How can I use this kind of different situations in one formula in Excel?

答:
Stackoverflow explains the correct method for IF - ELSE - IF Structure in Excel here

IF - ELSE IF - ELSE Structure in Excel

When FIND returns #VALUE!, it is an error, not a string, so you can't compare FIND(...) with "#VALUE!", you need to check if FIND returns an error with ISERROR. Also FIND can work on multiple characters.

So a simplified and working version of your formula would be:

Body:
I am using a FIFA 8 dataset for a project. There are various fields like age, rating, value and wage. Now I want to make a column of whether the player should be bought or not. I want to make this in Excel. I want to use a condition such as:

IF(Age<30 & Rating >90 & Value>100) OR If (Age<25 & Rating >85 & Value >70 ) then buy

How can I use this kind of different situations in one formula in Excel?


问:
Save hibernate object with foreign key without loading the dependent object
When we save an object in Hibernate then we save the dependent object not as an id but with loading that object and saving it.

Ex: Employee has a department foreign key, so if we need to save the employee object then we will do something like:

```<code>saveEmployee{
emp.setName(name);
Department department = session.find(Department.class,deptid);
emp.setDepartment(department);
}
</code>```

Now in case we import 1000 records and there we have deptid as a separate column in excel, then unnecessary 1000 times db will be called to fetch respective department.

Any better way to do this then
Is it possible to have foreign key enforced without object-to-object mapping?

答:
Use the load method instead of find:

```<code>Department department = session.load(Department.class,deptid);
</code>```

The persistence provider will only create a proxy at that point and assume that the entity physically exists on the database (there will be an error reaised if its not there to keep in mind).

Provided that all your operations are withing one transactinoal method, you will get N number of insertions without any selects.

Body:
When we save an object in Hibernate then we save the dependent object not as an id but with loading that object and saving it.

Ex: Employee has a department foreign key, so if we need to save the employee object then we will do something like:

saveEmployee{
emp.setName(name);
Department department = session.find(Department.class,deptid);
emp.setDepartment(department);
}

Now in case we import 1000 records and there we have deptid as a separate column in excel, then unnecessary 1000 times db will be called to fetch respective department.

Any better way to do this then
Is it possible to have foreign key enforced without object-to-object mapping?

Body:
Use the load method instead of find:

Department department = session.load(Department.class,deptid);

The persistence provider will only create a proxy at that point and assume that the entity physically exists on the database (there will be an error reaised if its not there to keep in mind).

Provided that all your operations are withing one transactinoal method, you will get N number of insertions without any selects.


问:
binned frequency from multiple variables in same column
Using R, I have melted my table into two columns, variable and value. There are multiple variables and values represent lengths. I would like to end up with three columns: variable, fixed pre-determined bins and frequency of each bin per variable.

Example Data:

original table/data frame:

```<code>Var Value
a   509
a   1000
b   251
b   330
...
</code>```

new table/data frame:

```<code>Var Bin       Count
a   0-250     50
a   251-500   30
a   501-1000  1
b   0-250     80
b   251-500   55
b   501-1000  30
...
</code>```

答:
To my surprise, I haven't found a duplicate question googling the question's title.

So, here are three possible solutions using cut() implemented in base R, dplyr, and data.table.

```<code># pre-define break points of bins
breaks <- seq(0L, 1000L, by = 250L)
</code>```

Note that cut() creates left open, right closed intervals by default, e.g,

250 < x <= 500.

For the first interval, the parameter include.lowest = TRUE forces a left closed interval as well, e.g.,

0 <= x <= 250

which seems to be in line with OP's expected output.

base R

```<code>with(DF, table(Var, cut(Value, breaks, include.lowest = TRUE)))
</code>```

```<code>Var [0,250] (250,500] (500,750] (750,1e+03]
  a       0         0         1           1
  b       1         2         0           0
</code>```

dpylr

```<code>library(dplyr)
DF %>%
  group_by(Var, Bin = cut(Value, breaks, include.lowest = TRUE)) %>%
  count()
</code>```

```<code># A tibble: 4 x 3
# Groups:   Var, Bin [4]
    Var         Bin     n
  <chr>      <fctr> <int>
1     a   (500,750]     1
2     a (750,1e+03]     1
3     b     [0,250]     1
4     b   (250,500]     2
</code>```

data.table

```<code>library(data.table)
setDT(DF)[, .N, by = .(Var, Bin = cut(Value, breaks, include.lowest = TRUE))]
</code>```

```<code>   Var         Bin N
1:   a   (500,750] 1
2:   a (750,1e+03] 1
3:   b     [0,250] 1
4:   b   (250,500] 2
</code>```

Data

```<code>library(data.table)
DF <- fread("Var Value
a   509
a   1000
b   0
b   251
b   330")
</code>```

Body:
Using R, I have melted my table into two columns, variable and value. There are multiple variables and values represent lengths. I would like to end up with three columns: variable, fixed pre-determined bins and frequency of each bin per variable.

Example Data:

original table/data frame:

Var Value
a   509
a   1000
b   251
b   330
...

new table/data frame:

Var Bin       Count
a   0-250     50
a   251-500   30
a   501-1000  1
b   0-250     80
b   251-500   55
b   501-1000  30
...

Body:
To my surprise, I haven't found a duplicate question googling the question's title.

So, here are three possible solutions using cut() implemented in base R, dplyr, and data.table.

# pre-define break points of bins
breaks <- seq(0L, 1000L, by = 250L)

Note that cut() creates left open, right closed intervals by default, e.g,

250 < x <= 500.

For the first interval, the parameter include.lowest = TRUE forces a left closed interval as well, e.g.,

0 <= x <= 250

which seems to be in line with OP's expected output.

base R

with(DF, table(Var, cut(Value, breaks, include.lowest = TRUE)))

Var [0,250] (250,500] (500,750] (750,1e+03]
  a       0         0         1           1
  b       1         2         0           0

dpylr

library(dplyr)
DF %>%
  group_by(Var, Bin = cut(Value, breaks, include.lowest = TRUE)) %>%
  count()

# A tibble: 4 x 3
# Groups:   Var, Bin [4]
    Var         Bin     n
  <chr>      <fctr> <int>
1     a   (500,750]     1
2     a (750,1e+03]     1
3     b     [0,250]     1
4     b   (250,500]     2

data.table

library(data.table)
setDT(DF)[, .N, by = .(Var, Bin = cut(Value, breaks, include.lowest = TRUE))]

   Var         Bin N
1:   a   (500,750] 1
2:   a (750,1e+03] 1
3:   b     [0,250] 1
4:   b   (250,500] 2

Data

library(data.table)
DF <- fread("Var Value
a   509
a   1000
b   0
b   251
b   330")


问:
Is it possible to manually destroy SurfaceView?
My SurfaceView is not getting destroyed even if onPause of the activity is called.

I am taking care of the thread in

```<code>public void surfaceCreated(SurfaceHolder holder) {
    if (mGameThread.getState() == Thread.State.TERMINATED) {
        createGameThread(getHolder(), getContext());
    }
    mGameThread.setRunning(true);
    mGameThread.start();
}

public void surfaceDestroyed(SurfaceHolder holder) {
    boolean retry = true;
    mGameThread.setRunning(false);
    while (retry) {
        try {
            mGameThread.join();
            retry = false;
        } catch (InterruptedException e) {
        }
    }
}
</code>```

As an hack I have to check the state of the thread in onResume and if the thread is already  terminated, I would finish the activity

```<code>protected void onResume() {
    Log.d(mLogTag, "onResume()");
    super.onResume();
    if (mGameThread != null) {
        if (mGameThread.getState() == Thread.State.TERMINATED) {
            finish();
        }
    }

}
</code>```

Unfortunately it is not possible to move the thread handling from surfaceDestroyed and surfaceCreated to onPause() and onResume() of the activity. Is it possible to manually destroy the SurfaceView in the onPause() and recreate it in onResume()?

答:
Yes possible.
First initialize Size

```<code>   Size currentSurfaceSize;

   cameraSurface.getHolder().addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(SurfaceHolder holder) {
                    if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(QR_Reader_Activity.this,
                                new String[]{Manifest.permission.CAMERA}, RequestCameraPermission);
                        permission = true;
                        return;
                    }
                    try {
                        cameraSource.start(cameraSurface.getHolder());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        currentSurfaceSize = new Size(width, height);
                    }
                }
                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    onPause();
                }
            });
</code>```

where do you want to destroy the surface, use this below code.

```<code>              if (currentSurfaceSize==null){
                    cameraSurface = (SurfaceView) cameraSurface.getHolder();
                    cameraSurface.removeCallbacks((Runnable) cameraSurface);
              }
</code>```

Body:
My SurfaceView is not getting destroyed even if onPause of the activity is called.

I am taking care of the thread in

public void surfaceCreated(SurfaceHolder holder) {
    if (mGameThread.getState() == Thread.State.TERMINATED) {
        createGameThread(getHolder(), getContext());
    }
    mGameThread.setRunning(true);
    mGameThread.start();
}

public void surfaceDestroyed(SurfaceHolder holder) {
    boolean retry = true;
    mGameThread.setRunning(false);
    while (retry) {
        try {
            mGameThread.join();
            retry = false;
        } catch (InterruptedException e) {
        }
    }
}

As an hack I have to check the state of the thread in onResume and if the thread is already  terminated, I would finish the activity

protected void onResume() {
    Log.d(mLogTag, "onResume()");
    super.onResume();
    if (mGameThread != null) {
        if (mGameThread.getState() == Thread.State.TERMINATED) {
            finish();
        }
    }

}

Unfortunately it is not possible to move the thread handling from surfaceDestroyed and surfaceCreated to onPause() and onResume() of the activity. Is it possible to manually destroy the SurfaceView in the onPause() and recreate it in onResume()?

Body:
Yes possible.
First initialize Size

   Size currentSurfaceSize;

   cameraSurface.getHolder().addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(SurfaceHolder holder) {
                    if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(QR_Reader_Activity.this,
                                new String[]{Manifest.permission.CAMERA}, RequestCameraPermission);
                        permission = true;
                        return;
                    }
                    try {
                        cameraSource.start(cameraSurface.getHolder());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        currentSurfaceSize = new Size(width, height);
                    }
                }
                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    onPause();
                }
            });

where do you want to destroy the surface, use this below code.

              if (currentSurfaceSize==null){
                    cameraSurface = (SurfaceView) cameraSurface.getHolder();
                    cameraSurface.removeCallbacks((Runnable) cameraSurface);
              }


问:
Get values from deeply nested object
I am working to get values from deeply nested object. The data and expected output are below. I got this data like below from request of API.

I have to use this script at Google Apps Script. So please note I cannot use ECMAScript6.

Object

```<code>var obj = {
  "key1": [
    {
      "key2": [
        {
          "key3": {
            "key4": {
              "key5": [
                {
                  "key6": "value6"
                },
                {},
                {
                  "key7": {
                    "key8": "value8"
                  }
                }
              ]
            }
          }
        },
        {
          "key3": {
            "key4": {
              "key5": [
                {
                  "key6": "value6"
                },
                {
                  "key7": {
                    "key8": "value8"
                  }
                },
                {}
              ]
            }
          }
        },
        {
          "key3": {
            "key5": "value5"
          }
        }
      ]
    },
    {
      "key2": [
        {
          "key3": {
            "key4": {
              "key5": [
                {
                  "key6": "value6"
                },
                {
                  "key7": {
                    "key8": "value8"
                  }
                }
              ]
            }
          }
        },
        {
          "key3": {
            "key4": {
              "key5": [
                {
                  "key6": "value6"
                },
                {},
                {
                  "key7": {
                    "key8": "value8"
                  }
                },
                {}
              ]
            }
          }
        },
        {
          "key3": {
            "key5": "value5"
          }
        }
      ]
    }
  ]
};
</code>```

Expected output

I want values of "key8".

```<code>value8
value8
value8
value8
</code>```

My current script

```<code>for (var i in obj.key1) {
  for (var j in obj.key1[i].key2) {
    for (var k in obj.key1[i].key2[j].key3.key4.key5[k]) {
      Logger.log(obj.key1[i].key2[j].key3.key4.key5[k].key7.key8)
    }
  }
}
</code>```

Error message

```<code>TypeError: Cannot read property "key5" from undefined.
</code>```

This error is at

```<code>for (var k in json.key1[i].key2[j].key3.key4.key5[k]) {
</code>```

My questions are

What is reason of error?

How modify should I my script to get values of "key8"?

Updated

I got 2 solutions of my question.

One is

```<code>var result = [];
for (var i in obj.key1) {
  for (var j in obj.key1[i].key2){
    if (obj.key1[i].key2[j].key3.key4) {
      for (var k in obj.key1[i].key2[j].key3.key4.key5) {
        if (obj.key1[i].key2[j].key3.key4.key5[k].key7) {
          result.push(obj.key1[i].key2[j].key3.key4.key5[k].key7.key8);
        }
      }
    } else {
      continue;
    }
  }
}
Logger.log(result) // >>> [value8, value8, value8, value8]
</code>```

https://jsfiddle.net/Lxa8tsfb/

Another is

```<code>var result = function () {
  var result = [];
  (function traverse(obj) {
    if (Array.isArray(obj)) {
      obj.forEach(traverse);
    } else if (typeof obj === 'object') {
      Object.keys(obj).forEach(function(key) {
        if (key === 'key8') {
          result.push(obj[key]);
        } else {
          traverse(obj[key]);
        }
      });
    }
  }(obj));
  return result;
}();
Logger.log(result) // >>> [value8, value8, value8, value8]
</code>```

https://jsfiddle.net/ffuuur0L/

1st one is my answer. 2nd one is an answer by @Petr. My answer can use only when users know the structure of object. Petr's answer can use when users know the key. I think Petr's answer is useful. So I accepted Petr's answer.

答:
You can use recursion here, something like this:

```<code>function traverse(json) {
    if (Array.isArray(json)) {
        json.forEach(traverse);
    } else if (typeof json === 'object') {
        Object.keys(json).forEach(function(key) {
            if (key === 'key8') {
                console.log(json[key]);
            } else {
               traverse(json[key]);
            }
        });
    }
};

traverse(json);
</code>```

This code is obviously imperfect, you might want to make key8 a parameter and wrap this into some method with a better name, but it works.

Title: Get values from deeply nested object

Body:
I am working to get values from deeply nested object. The data and expected output are below. I got this data like below from request of API.

I have to use this script at Google Apps Script. So please note I cannot use ECMAScript6.

Object

var obj = {
  "key1": [
    {
      "key2": [
        {
          "key3": {
            "key4": {
              "key5": [
                {
                  "key6": "value6"
                },
                {},
                {
                  "key7": {
                    "key8": "value8"
                  }
                }
              ]
            }
          }
        },
        {
          "key3": {
            "key4": {
              "key5": [
                {
                  "key6": "value6"
                },
                {
                  "key7": {
                    "key8": "value8"
                  }
                },
                {}
              ]
            }
          }
        },
        {
          "key3": {
            "key5": "value5"
          }
        }
      ]
    },
    {
      "key2": [
        {
          "key3": {
            "key4": {
              "key5": [
                {
                  "key6": "value6"
                },
                {
                  "key7": {
                    "key8": "value8"
                  }
                }
              ]
            }
          }
        },
        {
          "key3": {
            "key4": {
              "key5": [
                {
                  "key6": "value6"
                },
                {},
                {
                  "key7": {
                    "key8": "value8"
                  }
                },
                {}
              ]
            }
          }
        },
        {
          "key3": {
            "key5": "value5"
          }
        }
      ]
    }
  ]
};

Expected output

I want values of "key8".

value8
value8
value8
value8

My current script

for (var i in obj.key1) {
  for (var j in obj.key1[i].key2) {
    for (var k in obj.key1[i].key2[j].key3.key4.key5[k]) {
      Logger.log(obj.key1[i].key2[j].key3.key4.key5[k].key7.key8)
    }
  }
}

Error message

TypeError: Cannot read property "key5" from undefined.

This error is at

for (var k in json.key1[i].key2[j].key3.key4.key5[k]) {

My questions are

What is reason of error?

How modify should I my script to get values of "key8"?

Updated

I got 2 solutions of my question.

One is

var result = [];
for (var i in obj.key1) {
  for (var j in obj.key1[i].key2){
    if (obj.key1[i].key2[j].key3.key4) {
      for (var k in obj.key1[i].key2[j].key3.key4.key5) {
        if (obj.key1[i].key2[j].key3.key4.key5[k].key7) {
          result.push(obj.key1[i].key2[j].key3.key4.key5[k].key7.key8);
        }
      }
    } else {
      continue;
    }
  }
}
Logger.log(result) // >>> [value8, value8, value8, value8]

https://jsfiddle.net/Lxa8tsfb/

Another is

var result = function () {
  var result = [];
  (function traverse(obj) {
    if (Array.isArray(obj)) {
      obj.forEach(traverse);
    } else if (typeof obj === 'object') {
      Object.keys(obj).forEach(function(key) {
        if (key === 'key8') {
          result.push(obj[key]);
        } else {
          traverse(obj[key]);
        }
      });
    }
  }(obj));
  return result;
}();
Logger.log(result) // >>> [value8, value8, value8, value8]

https://jsfiddle.net/ffuuur0L/

1st one is my answer. 2nd one is an answer by @Petr. My answer can use only when users know the structure of object. Petr's answer can use when users know the key. I think Petr's answer is useful. So I accepted Petr's answer.

Body:
You can use recursion here, something like this:

function traverse(json) {
    if (Array.isArray(json)) {
        json.forEach(traverse);
    } else if (typeof json === 'object') {
        Object.keys(json).forEach(function(key) {
            if (key === 'key8') {
                console.log(json[key]);
            } else {
               traverse(json[key]);
            }
        });
    }
};

traverse(json);

This code is obviously imperfect, you might want to make key8 a parameter and wrap this into some method with a better name, but it works.