问:
How to pivot on arbitrary column?
I use Apache Spark 2.2.0 and Scala.

I'm following the question as a guide to pivot a dataframe without using the pivot function.

I need to pivot the dataframe without using the pivot function as I have non-numerical data and pivot works with an aggregation function like sum, min, max on numerical data only. I've got a non-numerical column I'd like to use in pivot aggregation.

Here's my data:

```<code>+---+-------------+----------+-------------+----------+-------+
|Qid|     Question|AnswerText|ParticipantID|Assessment| GeoTag|
+---+-------------+----------+-------------+----------+-------+
|  1|Question1Text|       Yes|       abcde1|         0|(x1,y1)|
|  2|Question2Text|        No|       abcde1|         0|(x1,y1)|
|  3|Question3Text|         3|       abcde1|         0|(x1,y1)|
|  1|Question1Text|        No|       abcde2|         0|(x2,y2)|
|  2|Question2Text|       Yes|       abcde2|         0|(x2,y2)|
+---+-------------+----------+-------------+----------+-------+
</code>```

I want it to group by ParticipantID, Assessment and GeoTag tags and "pivot" on Question column and take the values from AnswerText column. In the end, the output should look as follows:

```<code>+-------------+-----------+----------+-------+-----+----- +
|ParticipantID|Assessment |GeoTag    |Qid_1  |Qid_2|Qid_3 |
+-------------+-----------+----------+-------+-----+------+
|abcde1       |0          |(x1,y1)   |Yes    |No   |3     |
|abcde2       |0          |(x2,y2)   |No     |Yes  |null  |
+-------------+-----------+----------+-------+-----+------+
</code>```

I have tried this:

```<code>val questions: Array[String] = df.select("Q_id")
      .distinct()
      .collect()
      .map(_.getAs[String]("Q_id"))
      .sortWith(_<_)

val df2: DataFrame = questions.foldLeft(df) {
      case (data, question) => data.selectExpr("*", s"IF(Q_id = '$question', AnswerText, 0) AS $question")
    }
</code>```

[followed by a GroupBy expression]

But I'm getting the following error, which must be something to do with the syntax of the final statement AS $question

```<code>17/12/08 16:13:12 INFO SparkSqlParser: Parsing command: *
17/12/08 16:13:12 INFO SparkSqlParser: Parsing command: IF(Q_id_string_new_2 = '101_Who_is_with_you_right_now?', AnswerText, 0) AS 101_Who_is_with_you_right_now?

extraneous input '?' expecting <EOF>(line 1, pos 104)

== SQL ==
IF(Q_id_string_new_2 = '101_Who_is_with_you_right_now?', AnswerText, 0) AS 101_Who_is_with_you_right_now?
--------------------------------------------------------------------------------------------------------^^^

org.apache.spark.sql.catalyst.parser.ParseException:
extraneous input '?' expecting <EOF>(line 1, pos 104)

== SQL ==
IF(Q_id_string_new_2 = '101_Who_is_with_you_right_now?', AnswerText, 0) AS 101_Who_is_with_you_right_now?
--------------------------------------------------------------------------------------------------------^^^

    at org.apache.spark.sql.catalyst.parser.ParseException.withCommand(ParseDriver.scala:217)
</code>```

Any ideas where I am going wrong? Is there a better way? I thought about reverting to Pandas and Python outside Spark if necessary, but I'd rather write all the code within the same framework if possible.

答:
As $question is substituting the value of the question variable into the SQL statement, you end up with a column name with '?' in it in SQL. ? is not a valid character in a column name so you have to at least use backticks to quote:

```<code>s"IF(Q_id = '$question', AnswerText, 0) AS `$question`"
</code>```

or use select / withColumn:

```<code>import org.apache.spark.sql.functions.when

case (data, question) =>
  data.withColumn(question, when($"Q_id" === question, $"AnswerText"))
</code>```

or santize strings first, using regexp_replace.

need to pivot the dataframe without using the pivot function as I have non-numerical data and df.pivot only works with an aggregation function like sum, min, max on numerical data.

You can use first: How to use pivot and calculate average on a non-numeric column (facing AnalysisException "is not a numeric column")?

```<code>data.groupBy($"ParticipantID", $"Assessment", $"GeoTag")
  .pivot($"Question", questions).agg(first($"AnswerText"))
</code>```

Title: How to pivot on arbitrary column?

Body:
I use Apache Spark 2.2.0 and Scala.

I'm following the question as a guide to pivot a dataframe without using the pivot function.

I need to pivot the dataframe without using the pivot function as I have non-numerical data and pivot works with an aggregation function like sum, min, max on numerical data only. I've got a non-numerical column I'd like to use in pivot aggregation.

Here's my data:

+---+-------------+----------+-------------+----------+-------+
|Qid|     Question|AnswerText|ParticipantID|Assessment| GeoTag|
+---+-------------+----------+-------------+----------+-------+
|  1|Question1Text|       Yes|       abcde1|         0|(x1,y1)|
|  2|Question2Text|        No|       abcde1|         0|(x1,y1)|
|  3|Question3Text|         3|       abcde1|         0|(x1,y1)|
|  1|Question1Text|        No|       abcde2|         0|(x2,y2)|
|  2|Question2Text|       Yes|       abcde2|         0|(x2,y2)|
+---+-------------+----------+-------------+----------+-------+

I want it to group by ParticipantID, Assessment and GeoTag tags and "pivot" on Question column and take the values from AnswerText column. In the end, the output should look as follows:

+-------------+-----------+----------+-------+-----+----- +
|ParticipantID|Assessment |GeoTag    |Qid_1  |Qid_2|Qid_3 |
+-------------+-----------+----------+-------+-----+------+
|abcde1       |0          |(x1,y1)   |Yes    |No   |3     |
|abcde2       |0          |(x2,y2)   |No     |Yes  |null  |
+-------------+-----------+----------+-------+-----+------+

I have tried this:

val questions: Array[String] = df.select("Q_id")
      .distinct()
      .collect()
      .map(_.getAs[String]("Q_id"))
      .sortWith(_<_)

val df2: DataFrame = questions.foldLeft(df) {
      case (data, question) => data.selectExpr("*", s"IF(Q_id = '$question', AnswerText, 0) AS $question")
    }

[followed by a GroupBy expression]

But I'm getting the following error, which must be something to do with the syntax of the final statement AS $question

17/12/08 16:13:12 INFO SparkSqlParser: Parsing command: *
17/12/08 16:13:12 INFO SparkSqlParser: Parsing command: IF(Q_id_string_new_2 = '101_Who_is_with_you_right_now?', AnswerText, 0) AS 101_Who_is_with_you_right_now?

extraneous input '?' expecting <EOF>(line 1, pos 104)

== SQL ==
IF(Q_id_string_new_2 = '101_Who_is_with_you_right_now?', AnswerText, 0) AS 101_Who_is_with_you_right_now?
--------------------------------------------------------------------------------------------------------^^^

org.apache.spark.sql.catalyst.parser.ParseException:
extraneous input '?' expecting <EOF>(line 1, pos 104)

== SQL ==
IF(Q_id_string_new_2 = '101_Who_is_with_you_right_now?', AnswerText, 0) AS 101_Who_is_with_you_right_now?
--------------------------------------------------------------------------------------------------------^^^

    at org.apache.spark.sql.catalyst.parser.ParseException.withCommand(ParseDriver.scala:217)

Any ideas where I am going wrong? Is there a better way? I thought about reverting to Pandas and Python outside Spark if necessary, but I'd rather write all the code within the same framework if possible.

Body:
As $question is substituting the value of the question variable into the SQL statement, you end up with a column name with '?' in it in SQL. ? is not a valid character in a column name so you have to at least use backticks to quote:

s"IF(Q_id = '$question', AnswerText, 0) AS `$question`"

or use select / withColumn:

import org.apache.spark.sql.functions.when

case (data, question) =>
  data.withColumn(question, when($"Q_id" === question, $"AnswerText"))

or santize strings first, using regexp_replace.

need to pivot the dataframe without using the pivot function as I have non-numerical data and df.pivot only works with an aggregation function like sum, min, max on numerical data.

You can use first: How to use pivot and calculate average on a non-numeric column (facing AnalysisException "is not a numeric column")?

data.groupBy($"ParticipantID", $"Assessment", $"GeoTag")
  .pivot($"Question", questions).agg(first($"AnswerText"))


来源: stackexchange

问:
S3 hive external table on subdirectories is not working
I have following s3 directory structure.

```<code>Data/
   Year=2015/
         Month=01/
            Day=01/
                files
            Day=02/
                files
         Month=02/
            Day=01/
                files
            Day=02/
                files
         .
         .
         .

   Year=2014/
         Month=01/
            Day=01/
                files
            Day=02/
                files
         Month=02/
            Day=01/
                files
            Day=02/
                files
</code>```

So i am creating hive external table as follow

```<code>CREATE external TABLE trips
(
 trip_id  STRING,probe_id STRING,provider_id STRING,
 is_moving TINYINT,is_completed BOOLEAN,start_time STRING,
 start_lat  DOUBLE,start_lon DOUBLE,start_lat_adj DOUBLE)
  PARTITIONED BY (year INT,month INT,day INT)
  STORED AS TEXTFILE
  LOCATION 's3n://accesskey:secretkey@bucket/data/';
</code>```

When i run query on this table no data is returned without any exception. If i place same files in one directory only and without partitioning, then it runs fine. I also tried bey setting

```<code>set mapred.input.dir.recursive=true;
set hive.mapred.supports.subdirectories=true;
</code>```

Any idea where i am wrong?

答: You need to run ALTER TABLE trips RECOVER PARTITIONS command. This command will create metadata for table partitions which exist in S3. See docs here: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-RecoverPartitions(MSCKREPAIRTABLE)

ContentLicense: CC BY-SA 3.0

Body:
I have following s3 directory structure.

Data/
   Year=2015/
         Month=01/
            Day=01/
                files
            Day=02/
                files
         Month=02/
            Day=01/
                files
            Day=02/
                files
         .
         .
         .

   Year=2014/
         Month=01/
            Day=01/
                files
            Day=02/
                files
         Month=02/
            Day=01/
                files
            Day=02/
                files

So i am creating hive external table as follow

CREATE external TABLE trips
(
 trip_id  STRING,probe_id STRING,provider_id STRING,
 is_moving TINYINT,is_completed BOOLEAN,start_time STRING,
 start_lat  DOUBLE,start_lon DOUBLE,start_lat_adj DOUBLE)
  PARTITIONED BY (year INT,month INT,day INT)
  STORED AS TEXTFILE
  LOCATION 's3n://accesskey:secretkey@bucket/data/';

When i run query on this table no data is returned without any exception. If i place same files in one directory only and without partitioning, then it runs fine. I also tried bey setting

set mapred.input.dir.recursive=true;
set hive.mapred.supports.subdirectories=true;

Any idea where i am wrong?


问:
converted desktop bridge applications and account type
I just finally converted a free desktop win32 windows application that I've developed in order to submit it in the windows 10 store.

Following these instructions:
https://learn.microsoft.com/en-us/windows/uwp/porting/desktop-to-uwp-manual-conversion
I was finally able to create the package and install it on my machine. Everything works perfectly. So I thought I was ready to submit it on the store.

However, when I try to submit it on the Microsoft developer dashboard i get these errors:

Package acceptance validation error: You don't have permissions to specify the following namespaces in the appx manifest file of the package SpeedyPainter.appx: restricted namespace: http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities
Package acceptance validation error: Your developer account doesn’t have permission to submit apps converted with the Desktop Bridge at this time. https://aka.ms/desktopbridgeforwindowsstore

I have an individual developer account. Maybe the reason of the failure in the submission process is due to type of my account? Maybe only company accounts can post desktop bridge converted apps, even if an app is free?

Thank you in advance!
kind regards,
Andrea

答:
You need to fill in this form first. Then related team who then review it can make sure it has all of the information and once that information is verified then they move forwards having it assigned out and have the developer contacted to be worked with.

The process could take a couple of business days. If you don't receive response from it, please create a support ticket through your developer account.


问:
Get condition of a ConditionalExpression
Given a conditional expression cE = ConditionalExpression[ Value, Condition ] how can I extract the Condition of cE?

I tried indexing, but that didn't help.

答:
Maybe it is interesting to give a cleaner version that you can use in more complex situations.

Consider ConditionalExpression official documentation example

```<code>In[]:= ce = Integrate[x^n, {x, 0, 1}]
</code>```

with the following output:

```<code>                               1
Out[]= ConditionalExpression[-----, Re[n] > -1]
                             1 + n
</code>```

To extract the condition Re[n] > -1 you can use:

```<code>In[]:= FirstCase[ce, ConditionalExpression[_, c_] :> c, Missing[], {0,-1}]
</code>```

which prints:

```<code>Out[]= Re[n] > -1
</code>```

In your comment you mentionned a nested expression, with the previous approach this will work too. For instance:

```<code> In[]:= FirstCase[{{5, 6, ce, 1}}, ConditionalExpression[_, c_] :> c, Missing[], {0,-1}]
</code>```

still returns

```<code>Out[]= Re[n] > -1
</code>```

If the pattern is not found, the command gently returns Missing[]. For instance with Sin[6]:

```<code>In[]:= FirstCase[Sin[6], ConditionalExpression[_, c_] :> c, Missing[], {0,-1}]
</code>```

the output is:

```<code>Out[]= Missing[]
</code>```

Body:
Maybe it is interesting to give a cleaner version that you can use in more complex situations.

Consider ConditionalExpression official documentation example

In[]:= ce = Integrate[x^n, {x, 0, 1}]

with the following output:

                               1
Out[]= ConditionalExpression[-----, Re[n] > -1]
                             1 + n

To extract the condition Re[n] > -1 you can use:

In[]:= FirstCase[ce, ConditionalExpression[_, c_] :> c, Missing[], {0,-1}]

which prints:

Out[]= Re[n] > -1

In your comment you mentionned a nested expression, with the previous approach this will work too. For instance:

 In[]:= FirstCase[{{5, 6, ce, 1}}, ConditionalExpression[_, c_] :> c, Missing[], {0,-1}]

still returns

Out[]= Re[n] > -1

If the pattern is not found, the command gently returns Missing[]. For instance with Sin[6]:

In[]:= FirstCase[Sin[6], ConditionalExpression[_, c_] :> c, Missing[], {0,-1}]

the output is:

Out[]= Missing[]


问:
Jenkins can't launch real browser on Ubuntu 16.04
I've selenium script which launches chrome browser, goes to a website and does basic checks.

When I tried running same script locally through jenkins I got error

```<code>selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.33.506092 (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 4.13.0-17-generic x86_64)
</code>```

This is resolved by Unknown error: Chrome failed to start: exited abnormally

I'm confused why Jenkins can't launch real chrome browser on Ubuntu ?

答:
Because Jenkins server normally does not have a graphical subsystem installed in the operating system. When a real browser (or any app) tries to create a window that fails.

You will need to run your tests on Jenkins using a headless browser - one that does not need a graphical subsystem. Chrome-headless is currently the preferred option, replacing the now abandoned PhantomJS.

Body:
I've selenium script which launches chrome browser, goes to a website and does basic checks.

When I tried running same script locally through jenkins I got error

selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.33.506092 (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 4.13.0-17-generic x86_64)

This is resolved by Unknown error: Chrome failed to start: exited abnormally

I'm confused why Jenkins can't launch real chrome browser on Ubuntu ?


问:
How to calculate alternating sum of digits of an integer in Perl 6?

A number is divisible by 11 if its alternating sum of digits is
  divisible by 11.

So, e.g. if number is 1595, +1 -5 +9 -5 == 0, so 1595 is divisible by 11. How to implement such a sum? Here is my solution, but it's too complex and works only if the number of digits is even.

```<code>my $number = 1595;
say [+] $number.comb.map({$^a - $^b});
</code>```

What's the best way to do it?

答:
```<code>say [+] 1595.comb Z* (1, -1, 1 ... *)
</code>```

To break it down: .comb returns a list of characters, and Z* multiplies that list element-wise with the sequence on the RHS.

This sequence is a geometric sequence, which the ... series operator can deduce from the three elements. Since the zip operator Z stops at the shortest sequence, we don't have to take care to terminate the sequence on the RHS.

Another way to write the same thing is:

```<code>say [+] 1595.comb Z* (1, -* ... *)
</code>```

Where -* is the explicit negation of the previous value, applied to the initial element to generate the next one.

You could also write that as

```<code>say [+] 1595.comb Z* (1, &prefix:<-> ... *)
</code>```

Body:
A number is divisible by 11 if its alternating sum of digits is
  divisible by 11.

So, e.g. if number is 1595, +1 -5 +9 -5 == 0, so 1595 is divisible by 11. How to implement such a sum? Here is my solution, but it's too complex and works only if the number of digits is even.

my $number = 1595;
say [+] $number.comb.map({$^a - $^b});

What's the best way to do it?

Body:
say [+] 1595.comb Z* (1, -1, 1 ... *)

To break it down: .comb returns a list of characters, and Z* multiplies that list element-wise with the sequence on the RHS.

This sequence is a geometric sequence, which the ... series operator can deduce from the three elements. Since the zip operator Z stops at the shortest sequence, we don't have to take care to terminate the sequence on the RHS.

Another way to write the same thing is:

say [+] 1595.comb Z* (1, -* ... *)

Where -* is the explicit negation of the previous value, applied to the initial element to generate the next one.

You could also write that as

say [+] 1595.comb Z* (1, &prefix:<-> ... *)

ContentLicense: CC BY-SA 4.0


问:
Two label align vertically in tableView cell auto resizing swift
Try to auto resizing two labels align vertically within a cell, is that possible?

In the storyboard, we have to set autolayout, since I want to auto resizing two labels(one is on top of another).

I can't set each height so that the storyboard doesn't know what is the height of these two labels so it shows an error for autolayout.

if I click "Add Missing Constraints" button it will add a height for "subtitle"

or I can set height for "title" rather than "subtitle",

or make "title" equal to "subtitle" it will still accept.

here is the result:

A workaround will be separate these two to a different cell.
Any better solution? or am I just simply forget to do anything?

P.S. I'm using Xcode 8 with iOS 10.3.

答:
Try setting out Proper constraints for both the labels-:

Storyboard-:

Constraints for first label-:

Constraints for second label-:

Controller class(use Automatic Dimensions for table view)-:

```<code>class ViewController1: UIViewController {

    var dataForTableView:[ProductImage]?

    @IBOutlet weak var secondTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        secondTable.estimatedRowHeight = 96
        secondTable.rowHeight = UITableViewAutomaticDimension
        // CHECK FOR DATA

        //print(dataForTableView?[0].url as Any)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension ViewController1 : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! testingCell2
        cell.backgroundColor = UIColor.blue;
        cell.secondLabel.text = "agfhjsgfhjsgdshgfhjsfjhvhssajs hjfbvhjfbvjhfgafgfhlgkaghkfakfhkflbvhfbvhfvbhfv ah fvfhbvfjhvbfhdavhfvhv"
        return cell
    }

    // Number of sections in table

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }// Default is 1 if not implemented

    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return UITableViewAutomaticDimension
    }

}
</code>```

Output-:

I hope that is what you looking for, let me know if any issues.Thanks

Body:
Try setting out Proper constraints for both the labels-:

Storyboard-:

Constraints for first label-:

Constraints for second label-:

Controller class(use Automatic Dimensions for table view)-:

class ViewController1: UIViewController {

    var dataForTableView:[ProductImage]?

    @IBOutlet weak var secondTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        secondTable.estimatedRowHeight = 96
        secondTable.rowHeight = UITableViewAutomaticDimension
        // CHECK FOR DATA

        //print(dataForTableView?[0].url as Any)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension ViewController1 : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! testingCell2
        cell.backgroundColor = UIColor.blue;
        cell.secondLabel.text = "agfhjsgfhjsgdshgfhjsfjhvhssajs hjfbvhjfbvjhfgafgfhlgkaghkfakfhkflbvhfbvhfvbhfv ah fvfhbvfjhvbfhdavhfvhv"
        return cell
    }

    // Number of sections in table

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }// Default is 1 if not implemented

    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return UITableViewAutomaticDimension
    }

}

Output-:

I hope that is what you looking for, let me know if any issues.Thanks


问:
React-native const component doesn't receive props?
Coming from React, I thought passing props was the same, apparently it is not?

I have a login form in which I'd like to have a sign in, and sign up button with different styling.

In my loginform, I have the following method:

```<code>   renderButton (type, text) {
        if (this.state.loading) {
            return <Spinner size="small" />;
        }

        let btnColors = {
            bgColor: colors.whiteText,
            textColor: colors.primaryTeal
        };

        if (type === "signUp") {
            btnColors.bgColor = colors.whiteText;
            btnColors.textColor =  colors.primaryTeal;

        } else if (type === "logIn") {
            btnColors.bgColor = colors.darkTeal;
            btnColors.textColor = colors.whiteText;
        }
        return (
            <Button colors={btnColors} onPress={this.onButtonPress.bind(this)}>
                {text}
            </Button>
        );
    }
</code>```

Invoked in Render by:

```<code>{this.renderButton("signUp", "SIGN UP")}
</code>```

Button.js looks like:

```<code>import React from 'react';
import { Text, TouchableOpacity, View, StyleSheet} from 'react-native';

const Button = ({colors, onPress, children }) => {

    const styles =  StyleSheet.create({
        textStyle: {
            alignSelf: 'center',
            color: colors.textColor,
            fontSize: 16,
            fontWeight: '900',
            paddingTop: 10,
            paddingBottom: 10,
        },
        buttonStyle: {
            flex: 1,
            backgroundColor: colors.bgColor,
            borderRadius: 50
        },
    });

      return (
            <TouchableOpacity onPress={onPress} style={styles.buttonStyle}>
              <Text style={styles.textStyle}>
                  {children}
              </Text>
            </TouchableOpacity>
      );
};

export { Button };
</code>```

With the error:

undefined is not an object (evaluating 'colors.textColor')

Why doesn't it work, and how would I conditionally pass props as an object to use for styling?

答:
Try changing the component to a class component instead of a functional component, this should do the trick... alternatove ypu can use the fat arrow syntax as shown below: </p>

```<code>const HelloWorld = ({name}) => ( <div>{`Hi ${name}`}</div>);
</code>```

Body:
Coming from React, I thought passing props was the same, apparently it is not?

I have a login form in which I'd like to have a sign in, and sign up button with different styling.

In my loginform, I have the following method:

   renderButton (type, text) {
        if (this.state.loading) {
            return <Spinner size="small" />;
        }

        let btnColors = {
            bgColor: colors.whiteText,
            textColor: colors.primaryTeal
        };

        if (type === "signUp") {
            btnColors.bgColor = colors.whiteText;
            btnColors.textColor =  colors.primaryTeal;

        } else if (type === "logIn") {
            btnColors.bgColor = colors.darkTeal;
            btnColors.textColor = colors.whiteText;
        }
        return (
            <Button colors={btnColors} onPress={this.onButtonPress.bind(this)}>
                {text}
            </Button>
        );
    }

Invoked in Render by:

{this.renderButton("signUp", "SIGN UP")}

Button.js looks like:

import React from 'react';
import { Text, TouchableOpacity, View, StyleSheet} from 'react-native';

const Button = ({colors, onPress, children }) => {

    const styles =  StyleSheet.create({
        textStyle: {
            alignSelf: 'center',
            color: colors.textColor,
            fontSize: 16,
            fontWeight: '900',
            paddingTop: 10,
            paddingBottom: 10,
        },
        buttonStyle: {
            flex: 1,
            backgroundColor: colors.bgColor,
            borderRadius: 50
        },
    });

      return (
            <TouchableOpacity onPress={onPress} style={styles.buttonStyle}>
              <Text style={styles.textStyle}>
                  {children}
              </Text>
            </TouchableOpacity>
      );
};

export { Button };

With the error:

undefined is not an object (evaluating 'colors.textColor')

Why doesn't it work, and how would I conditionally pass props as an object to use for styling?

Body:
Try changing the component to a class component instead of a functional component, this should do the trick... alternatove ypu can use the fat arrow syntax as shown below:

const HelloWorld = ({name}) => ( <div>{`Hi ${name}`}</div>);


问:
disadvantage of using php's mysqli library over mysql
hello I have an assignment that asking me to give at least one disadvantage of using php's MySQLi library over php's MySQL .. I don't see any .. can any one give me some disadvantage because I can never find one</p>

答:
MySQLi has this feature called prepared statements which is nothing but a safer way of sending data to MySQL and protecting yourself from getting hacked using SQL injection. This is the foremost reason why one should always prefer MySQLi over MySQL.

MySQLi extension has been specifically developed to take advantage of the new features available in MySQL Server version 4.1.3 and above. So the thing is if you still use the MySQL extension then you might not be able to take full advantage of the new MySQL server features.

MySQLi is object orientated and a lot has already been talked about how useful Object Oriented programming is.

MySQLi supports multiple Statements, Complex Transaction statements and has enhanced debugging capabilities and embedded server support.


问:
centralManager:didDiscoverPeripheral:advertisementData:RSSI: only called once per advertising period
I would like to capture all BLE device advertisements.
The BLE device is set to wake ever minute then broad cast every 3 seconds for a total of 15 seconds.

But I have noticed centralManager:didDiscoverPeripheral:advertisementData:RSSI: is only called once per advertising period (15 seconds) that is seen by the handset while the app is in the foreground.

This is what I have monitored over the last couple of hours. Which has generate two questions.

One, How can i capture ever 3 second advertisement for the 15 second period?
Two, Why are there increasing dead periods in my captured data.

答:
CentralManager has an option CBCentralManagerScanOptionAllowDuplicatesKey wehn you initiate Scanning
by default it is false.

Set it to true and you should get multiple scans for the same device

```<code>scanForPeripheralsWithServices(nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])
</code>```

Body:
CentralManager has an option CBCentralManagerScanOptionAllowDuplicatesKey wehn you initiate Scanning
by default it is false.

Set it to true and you should get multiple scans for the same device

scanForPeripheralsWithServices(nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])


问:
Why should LiveData objects in ViewModel be instantiated during declaration?
Please consider the following code from Google's Architecture Components tutorial:

```<code>class MyViewModel extends ViewModel {
    private final PostalCodeRepository repository;
    private final MutableLiveData<String> addressInput = new MutableLiveData();
    public final LiveData<String> postalCode =
            Transformations.switchMap(addressInput, (address) -> {
                return repository.getPostCode(address);
             });

  public MyViewModel(PostalCodeRepository repository) {
      this.repository = repository
  }

  private void setInput(String address) {
      addressInput.setValue(address);
  }
}
</code>```

Please note that LiveData objects are instantiated during declaration.

From what I can tell from this answer, there is very little difference difference between instantiating them during declaration or inside of a constrictor. Yet, from what I understand, there is a possibility of having NPEs or having stale references when LiveData objects are instantiated through a constructer, so Googles' recommendation is to instantiate them during declaration.

My hunch is that it may have something to do with creating ViewModel objects through reflection, however I have been unable to find how exactly it could effect creation of those objects.

Why should LiveData objects be instantiated during declaration?

答:
Please consider the following code from Google's Architecture Components tutorial:

That is not a tutorial. It is a reference with some code snippets, many of which will not compile, as they are there to illustrate syntax and call structure, not actually run.

Please note that LiveData objects are instantiated during declaration.

That is what the person who wrote that code snippet elected to do.

so Googles' recommendation is to instantiate them during declaration.

Google makes no such recommendation. The code snippet that you cite is an example, nothing more.

Why should LiveData objects be instantiated during declaration?

They do not have be fields with initializers. You are welcome to instantiate them in the constructor if you so choose. ViewModel has specific rules about constructors (e.g., if you are not providing a factory, it needs to have a zero-argument constructor, or a one-Application-argument constructor for AndroidViewModel). But, other than that, you can do whatever you want.

It is frequently more concise to use an initializer — where the initializer is an available option — so there may be a tendency to use initalizers.

Body:
Please consider the following code from Google's Architecture Components tutorial:

class MyViewModel extends ViewModel {
    private final PostalCodeRepository repository;
    private final MutableLiveData<String> addressInput = new MutableLiveData();
    public final LiveData<String> postalCode =
            Transformations.switchMap(addressInput, (address) -> {
                return repository.getPostCode(address);
             });

  public MyViewModel(PostalCodeRepository repository) {
      this.repository = repository
  }

  private void setInput(String address) {
      addressInput.setValue(address);
  }
}

Please note that LiveData objects are instantiated during declaration.

From what I can tell from this answer, there is very little difference difference between instantiating them during declaration or inside of a constrictor. Yet, from what I understand, there is a possibility of having NPEs or having stale references when LiveData objects are instantiated through a constructer, so Googles' recommendation is to instantiate them during declaration.

My hunch is that it may have something to do with creating ViewModel objects through reflection, however I have been unable to find how exactly it could effect creation of those objects.

Why should LiveData objects be instantiated during declaration?


问:
Access to redirectToRoute in CustomExceptionController
In /src/AppBundle/Controller/CustomExceptionController.php I have:

```<code>namespace AppBundle\Controller;

use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class CustomExceptionController extends \Symfony\Bundle\TwigBundle\Controller\ExceptionController
{

    public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
    {
        return $this->redirectToRoute('custom_error'); //not working
    }
}
</code>```

This not working because \Symfony\Bundle\TwigBundle\Controller\ExceptionController not extends class Controller. So how can I use $this->redirectToRoute in this class?

答:
easy way with using UrlGeneratorInterface like

```<code> getContainer()->get('router')->generate( 'custom_error', ['key' => 'some val'], 0 );
</code>```

getContainer() - is own funct, see manual If you need to generate a URL from a service, type-hint the UrlGeneratorInterface service:

```<code>// src/Service/SomeService.php

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SomeService
{
    private $router;

    public function __construct(UrlGeneratorInterface $router)
    {
        $this->router = $router;
    }

    public function someMethod()
    {
        $url = $this->router->generate( 'custom_error', [ 'key' => 'some value' ] );

    }
}
</code>```

Body:
In /src/AppBundle/Controller/CustomExceptionController.php I have:

namespace AppBundle\Controller;

use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class CustomExceptionController extends \Symfony\Bundle\TwigBundle\Controller\ExceptionController
{

    public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
    {
        return $this->redirectToRoute('custom_error'); //not working
    }
}

This not working because \Symfony\Bundle\TwigBundle\Controller\ExceptionController not extends class Controller. So how can I use $this->redirectToRoute in this class?

Body:
easy way with using UrlGeneratorInterface like

 getContainer()->get('router')->generate( 'custom_error', ['key' => 'some val'], 0 );

getContainer() - is own funct, see manual If you need to generate a URL from a service, type-hint the UrlGeneratorInterface service:

// src/Service/SomeService.php

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SomeService
{
    private $router;

    public function __construct(UrlGeneratorInterface $router)
    {
        $this->router = $router;
    }

    public function someMethod()
    {
        $url = $this->router->generate( 'custom_error', [ 'key' => 'some value' ] );

    }
}


问:
dyld: Library not loaded: @rpath/MicroBlink.framework/MicroBlink

dyld: Library not loaded: @rpath/MicroBlink.framework/MicroBlink

Referenced from: /var/containers/Bundle/Application/F6A7AA6C-73C0-479C-8E6B-C679D3C1E515/text.app/text

Reason: image not found

答:
MicroBlink.framework is a dynamic framework and as such you need to embed it in the app's bundle.

Here are the generic instructions about embedding frameworks: https://www.youtube.com/watch?v=A7KhnHdOs6A


问:
responseData gives an error ReactNative
```<code>fetch(loginApi, {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    Password: password,
    UserName: username
  })
})
  .then(response => response.json())
  .then(responseData => {
    console.log(responseData); //// <--- getting error at this line
  })
  .catch(error => {
    console.error(error);
  });
</code>```

enter image description here

Any idea how to solve it??? Thanks in advance.

答:
Luckily I have found the solution.

```<code>var loginParams = {
        Password: password,
        UserName: username
    };

    var loginFormData = new FormData();

    for (var param in loginParams) {
        loginFormData.append(param, loginParams[param]);
    }

    fetch(loginApi, {
     method: "POST",
      headers: { /// <---- you can remove this headers if you are not using any headers in postman..
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: loginFormData
})
  .then(response => response.json())
  .then(responseData => {
    console.log(responseData); //// <--- getting error at this line
  })
  .catch(error => {
    console.error(error);
  });
</code>```

for more information please check this enter link description here

Title: responseData gives an error ReactNative

Body:
fetch(loginApi, {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    Password: password,
    UserName: username
  })
})
  .then(response => response.json())
  .then(responseData => {
    console.log(responseData); //// <--- getting error at this line
  })
  .catch(error => {
    console.error(error);
  });

enter image description here

Any idea how to solve it??? Thanks in advance.

Body:
Luckily I have found the solution.

var loginParams = {
        Password: password,
        UserName: username
    };

    var loginFormData = new FormData();

    for (var param in loginParams) {
        loginFormData.append(param, loginParams[param]);
    }

    fetch(loginApi, {
     method: "POST",
      headers: { /// <---- you can remove this headers if you are not using any headers in postman..
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: loginFormData
})
  .then(response => response.json())
  .then(responseData => {
    console.log(responseData); //// <--- getting error at this line
  })
  .catch(error => {
    console.error(error);
  });

for more information please check this enter link description here


问:
Matplotlib how to plot in two y axis
I have tried the following code, try to plot two curves in two axis and one graph. But I can only see one curve, anything I did wrong?</p>

```<code>import matplotlib.pyplot as plt
PlotFigure_1 = plt.figure()
ax1 = PlotFigure_1.add_subplot(111)
par1 = ax1.twinx()
ax1.cla()
par1.cla()
x=[1, 2, 3, 4]
y=[1, 2, 3, 5]
ax1.plot(x, y, 'r')
x1=[1, 2, 3, 4]
y1=[10, 20, 30, 50]
par1.plot(x1, y1, 'b')
plt.subplots_adjust(right=0.75) # was 0.7 try
plt.show()
</code>```

答:
The first line is just hidden behind the second.

Because y1 == 10 * y, the curves have the same "shape". But each y-axis is scaled independently, so the curves lie in the same position relative to their respective axes. The data differs by a factor of 10, but so does the extent of their y-axes, i.e., par1.get_ylim() == 10 * ax1.get_ylim().

To prove this to yourself, you can:

Force the axes to have different extents relative to their data, e.g., by doing ax1.set_ylim(0, 6).

Plot data in each axes where there is a different linear factor for at least some of the points (e.g., use y1 = [10, 20, 30, 60]).

Title: Matplotlib how to plot in two y axis

Body:
I have tried the following code, try to plot two curves in two axis and one graph. But I can only see one curve, anything I did wrong?

import matplotlib.pyplot as plt
PlotFigure_1 = plt.figure()
ax1 = PlotFigure_1.add_subplot(111)
par1 = ax1.twinx()
ax1.cla()
par1.cla()
x=[1, 2, 3, 4]
y=[1, 2, 3, 5]
ax1.plot(x, y, 'r')
x1=[1, 2, 3, 4]
y1=[10, 20, 30, 50]
par1.plot(x1, y1, 'b')
plt.subplots_adjust(right=0.75) # was 0.7 try
plt.show()


问:
SAS - Transpose all colums by unique records in each column with counts
I am trying to find efficient, transpose-like code that can convert the Test table below into the Final table. I have code below that works for this example, but for practical purposes, the split data step can produce a very deep table (137 million records in my case, vs 2k as aggregated).

I was hoping there was some Proc or Data step trick I was missing that could skip that intermediate step and be more efficient.

```<code>Data test;
    Input f1 $ f2 $ f3 $ f4 $ f5 $ f6 $ f7 $ f8 $;

    DataLines;
a c f h k l o q
a c f h k l o q
a c g h k m o q
b c g h k m o q
b d g i k m o r
b d g i k n o r
b e g j k n o s
b e g j k n p s
    ;

Run;

Data final;
    Input field $ values $ records;

    DataLines;
f1 a 3
f1 b 5
f2 c 4
f2 d 2
f2 e 2
f3 f 2
f3 g 6
f4 h 4
f4 i 2
f4 j 2
f5 k 8
f6 l 2
f6 m 3
f6 n 3
f7 o 7
f7 p 1
f8 q 4
f8 r 2
f8 s 2
    ;

Run;

/*Working solution - could it be done more efficiently?*/
Data split;
    Set test;

    Array f{8} f1-f8;
    Do i=1 To 8;
        field = 'f'||PUT(i,best2.);
        values = f{i};
        Output;
    End;

    Drop i f1-f8;
Run;

Proc SQL;
    Create Table final As
    Select
        field
        ,values
        ,COUNT(*) As records Format=comma8.0
    From split
    Group By 1,2
    Order By 1,2
    ;
Quit;
</code>```

答:
Easy enough to do with PROC SUMMARY. Use your variable list as CLASS variables. You can use the WAYS statement to limit it to one-way classification groups. You can use the CHARTYPE option to make it easy to transform the results.  You probably will also want to add the MISSING option to prevent proc summary eliminating input observations that have a missing value for any of the variables.

```<code>%let varlist=f1-f8 ;

proc summary data=test chartype missing ;
 class &varlist ;
 ways 1 ;
 output out=result ;
run;

data want ;
  set result ;
  length field $32 value $8 count 8 ;
  array fields &varlist ;
  index=indexc(_type_,'1');
  field=vname(fields(index));
  value=fields(index);
  count=_freq_;
  keep field value count;
run;
</code>```

You might want to reverse the order of the variables so that they come out in the original order.  So use F8-F1 instead of F1-F8.

Note that all of the variables need to be of the same type because of the ARRAY statement in the data step.

Body:
I am trying to find efficient, transpose-like code that can convert the Test table below into the Final table. I have code below that works for this example, but for practical purposes, the split data step can produce a very deep table (137 million records in my case, vs 2k as aggregated).

I was hoping there was some Proc or Data step trick I was missing that could skip that intermediate step and be more efficient.

Data test;
    Input f1 $ f2 $ f3 $ f4 $ f5 $ f6 $ f7 $ f8 $;

    DataLines;
a c f h k l o q
a c f h k l o q
a c g h k m o q
b c g h k m o q
b d g i k m o r
b d g i k n o r
b e g j k n o s
b e g j k n p s
    ;

Run;

Data final;
    Input field $ values $ records;

    DataLines;
f1 a 3
f1 b 5
f2 c 4
f2 d 2
f2 e 2
f3 f 2
f3 g 6
f4 h 4
f4 i 2
f4 j 2
f5 k 8
f6 l 2
f6 m 3
f6 n 3
f7 o 7
f7 p 1
f8 q 4
f8 r 2
f8 s 2
    ;

Run;

/*Working solution - could it be done more efficiently?*/
Data split;
    Set test;

    Array f{8} f1-f8;
    Do i=1 To 8;
        field = 'f'||PUT(i,best2.);
        values = f{i};
        Output;
    End;

    Drop i f1-f8;
Run;

Proc SQL;
    Create Table final As
    Select
        field
        ,values
        ,COUNT(*) As records Format=comma8.0
    From split
    Group By 1,2
    Order By 1,2
    ;
Quit;

Body:
Easy enough to do with PROC SUMMARY. Use your variable list as CLASS variables. You can use the WAYS statement to limit it to one-way classification groups. You can use the CHARTYPE option to make it easy to transform the results.  You probably will also want to add the MISSING option to prevent proc summary eliminating input observations that have a missing value for any of the variables.

%let varlist=f1-f8 ;

proc summary data=test chartype missing ;
 class &varlist ;
 ways 1 ;
 output out=result ;
run;

data want ;
  set result ;
  length field $32 value $8 count 8 ;
  array fields &varlist ;
  index=indexc(_type_,'1');
  field=vname(fields(index));
  value=fields(index);
  count=_freq_;
  keep field value count;
run;

You might want to reverse the order of the variables so that they come out in the original order.  So use F8-F1 instead of F1-F8.

Note that all of the variables need to be of the same type because of the ARRAY statement in the data step.


问:
Simulate HTTP responses to test a node.js HTTP client
How can I simulate HTTP responses to test an app?

What I'd like to do is to simulate HTTP responses to test a HTTP node.js client. Is there something I can use like fakeweb but for node.js?

答:
Why not use a node.js server? They're trivial to write and would give you complete control over the response.

Here's an example, straight from http://nodejs.org/

```<code>var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
</code>```

Body:
Why not use a node.js server? They're trivial to write and would give you complete control over the response.

Here's an example, straight from http://nodejs.org/

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

ContentLicense: CC BY-SA 2.5


问:
Convert a List of Object to Map<String,String> using jdk 8 lambdas
I want to convert a List<Properies> to a Map<String,String> using jdk 8 lambdas without doing a for loop. The map should contain the key as SubProperty.name and value as Properties.value.

```<code>public class Properties
{
    private SubProperty subProperty;

    private String value;

    public SubProperty getSubProperty()
    {
        return subProperty;
    }

    public void setSubProperty(SubProperty subProperty)
    {
        this.subProperty = subProperty;
    }

    public String getValue()
    {
        return value;
    }

    public void setValue(String value)
    {
        this.value = value;
    }
}

public class SubProperty
{
    private String category;
    private String name;

    public String getCategory()
    {
        return category;
    }

    public void setCategory(String category)
    {
        this.category = category;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}
</code>```

答:
Something like this:</p>

```<code>List<Properties> properties = ...
Map<String, String> map = properties.stream()
    .collect(Collectors.toMap(prop -> prop.getSubProperty().getName(), prop -> prop.getValue()));
</code>```

Body:
I want to convert a List<Properies> to a Map<String,String> using jdk 8 lambdas without doing a for loop. The map should contain the key as SubProperty.name and value as Properties.value.

public class Properties
{
    private SubProperty subProperty;

    private String value;

    public SubProperty getSubProperty()
    {
        return subProperty;
    }

    public void setSubProperty(SubProperty subProperty)
    {
        this.subProperty = subProperty;
    }

    public String getValue()
    {
        return value;
    }

    public void setValue(String value)
    {
        this.value = value;
    }
}

public class SubProperty
{
    private String category;
    private String name;

    public String getCategory()
    {
        return category;
    }

    public void setCategory(String category)
    {
        this.category = category;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}

Body:
Something like this:

List<Properties> properties = ...
Map<String, String> map = properties.stream()
    .collect(Collectors.toMap(prop -> prop.getSubProperty().getName(), prop -> prop.getValue()));


问:
Twitter api text field value is truncated
why text field value is truncated and how can i get complete value.
As of now i am trying to get text field value like below

```<code>do {
       if let responseObject = try NSJSONSerialization.JSONObjectWithData(response, options: []) as? [String:AnyObject],
           arrayStatuses = responseObject["statuses"] as? [[String:AnyObject]] {
               let arrTweets:NSMutableArray = NSMutableArray()
               for status in arrayStatuses {
                   let text = status["text"]!
                   print(status["text"]!)
               }
       }
}
</code>```

output is

RT @WarfareWW: #Russia/#India may hold launches of BrahMos cruise missiles from Su-30MKI vs sea/grnd trgts at the end of this year https://…

three dots at the end of line. i need to print complete text without truncation.

Twitter sample search result JSON Data

```<code>{
      "created_at": "Mon Aug 01 08:07:43 +0000 2016",
      "id": 760024194079916032,
      "id_str": "760024194079916032",
      "text": "RT @khalidasopore: #KEXIT #KASHEXIT #KashmirKillings #Inida #Pakistan Just trend it my dear Indians to save #Kashmir from Pak Goons https:/…",
      "truncated": false
}
</code>```

答:
The status in this example is a retweet, and the text for retweets will be truncated to 140 characters even after including tweet_mode=extended. The full text of the original tweet is in the retweeted_status field of the JSON response. Here's what you want:

let text = status["retweeted_status"]["full_text"].

Keep in mind that you should still include tweet_mode=extended in your request.

Body:
why text field value is truncated and how can i get complete value.
As of now i am trying to get text field value like below

do {
       if let responseObject = try NSJSONSerialization.JSONObjectWithData(response, options: []) as? [String:AnyObject],
           arrayStatuses = responseObject["statuses"] as? [[String:AnyObject]] {
               let arrTweets:NSMutableArray = NSMutableArray()
               for status in arrayStatuses {
                   let text = status["text"]!
                   print(status["text"]!)
               }
       }
}

output is

RT @WarfareWW: #Russia/#India may hold launches of BrahMos cruise missiles from Su-30MKI vs sea/grnd trgts at the end of this year https://…

three dots at the end of line. i need to print complete text without truncation.

Twitter sample search result JSON Data

{
      "created_at": "Mon Aug 01 08:07:43 +0000 2016",
      "id": 760024194079916032,
      "id_str": "760024194079916032",
      "text": "RT @khalidasopore: #KEXIT #KASHEXIT #KashmirKillings #Inida #Pakistan Just trend it my dear Indians to save #Kashmir from Pak Goons https:/…",
      "truncated": false
}


问:
Bootstrap columns in a php while loop
I've read a ton of different ideas out there for this but can't seem to get any of them to work for my piece of code. Currently my products are displaying in a singular column but I'd like them to display in either a 3 or 4 column grid. Here's the code I have so far, hopefully someone can see where I'm going wrong.</p>

```<code>if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) { ?>
        <div class="container">
          <div class="col-sm-4">
            <?php echo $row["ID"] . " - " . $row["item"] . "<br>";?>
            <img src="img/<?php echo $row["image"] ?>" style="width:150px;height:150px;"><br>
            <?php echo $row["description"] . " - $" . $row["price"]; ?>
        <form method="post" action="viewcart.php">
            <input type="hidden" name="item" value="<?php echo $row["item"]?>" />
            <input type="hidden" name="price" value="<?php echo $row["price"]?>" />
            <button type="submit">Add To Cart</button>
       </form>
    </div>
</div>
</code>```

答:
You have the .container being looped inside the while loop as well, which is the problem. The correct format is:

```<code>.container
  .row
    .col-XX-X
</code>```

Put the container and the row outside and you are good to go.

```<code><?php
if ($result->num_rows > 0) {
  echo '<div class="container"><div class="row">'; // You left a row. Change here.
    while($row = $result->fetch_assoc()) { ?>
      <div class="col-sm-4">
        <?php echo $row["ID"] . " - " . $row["item"] . "<br>";?>
          <img src="img/<?php echo $row["image"] ?>" style="width:150px;height:150px;"><br>
          <?php echo $row["description"] . " - $" . $row["price"]; ?>
          <form method="post" action="viewcart.php">
            <input type="hidden" name="item" value="<?php echo $row["item"]?>" />
            <input type="hidden" name="price" value="<?php echo $row["price"]?>" />
            <button type="submit">Add To Cart</button>
        </form>
      </div>
<?php } ?>
  </div>
</div>
</code>```

Title: Bootstrap columns in a php while loop

Body:
I've read a ton of different ideas out there for this but can't seem to get any of them to work for my piece of code. Currently my products are displaying in a singular column but I'd like them to display in either a 3 or 4 column grid. Here's the code I have so far, hopefully someone can see where I'm going wrong.

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) { ?>

            <?php echo $row["ID"] . " - " . $row["item"] . "
";?>
            <img src="img/<?php echo $row["image"] ?>" style="width:150px;height:150px;">

            <?php echo $row["description"] . " - $" . $row["price"]; ?>
        <form method="post" action="viewcart.php">
            <input type="hidden" name="item" value="<?php echo $row["item"]?>" />
            <input type="hidden" name="price" value="<?php echo $row["price"]?>" />
            <button type="submit">Add To Cart</button>
       </form>

Body:
You have the .container being looped inside the while loop as well, which is the problem. The correct format is:

.container
  .row
    .col-XX-X

Put the container and the row outside and you are good to go.

<?php
if ($result->num_rows > 0) {
  echo '<div class="container"><div class="row">'; // You left a row. Change here.
    while($row = $result->fetch_assoc()) { ?>
      <div class="col-sm-4">
        <?php echo $row["ID"] . " - " . $row["item"] . "<br>";?>
          <img src="img/<?php echo $row["image"] ?>" style="width:150px;height:150px;"><br>
          <?php echo $row["description"] . " - $" . $row["price"]; ?>
          <form method="post" action="viewcart.php">
            <input type="hidden" name="item" value="<?php echo $row["item"]?>" />
            <input type="hidden" name="price" value="<?php echo $row["price"]?>" />
            <button type="submit">Add To Cart</button>
        </form>
      </div>
<?php } ?>
  </div>
</div>


问:
Write a Mockito test to verify Class2 method invoked in Class1 method return value
```<code>Class1 {
    private Class2 class2;
    public void f1() {
      class2.f2();
    }}
</code>```

Right now I have Class2 instance mock injected into Class1 instance.
I need to write a test to verify Class2 f2 method return value.
How do I do it?

答:
I understand you to be saying that in your test your class2 member is a mock.  And if so, then you don't test the return value of the mock's f2() method call.  Since it is a mock, you can make the method call on the mock do/return whatever you need it to return.  The way to validate this is to use a verify statement to verify that the mock object's f2() method was invoked.  If the f2() method had been passed parameters, you could also verify that it was invoked with the correct parameters passed.  Then you don't have to care or worry about what it returns because you are verifying that it was called as expected.  You will test the actual f2() method in a unit test for that class and can verify in that test that it does what you expect, but here where you are testing Class1 you just need to verify the method was called as expected.

See https://static.javadoc.io/org.mockito/mockito-core/2.13.0/org/mockito/Mockito.html#1

Body:
Class1 {
    private Class2 class2;
    public void f1() {
      class2.f2();
    }}

Right now I have Class2 instance mock injected into Class1 instance.
I need to write a test to verify Class2 f2 method return value.
How do I do it?


问:
Can't play a reversed .wav file with MediaPlayer
I've created an app that records audio, saves the sample to the sd card then plays it back, using the record and play buttons. I need to reverse this sample. I can do all this and the the reversed sample is saved on the SD card under a different name. The original sample is test.wav and the same sample reversed is save as revFile.wav. when i try play revFile.wav android says it can't play this format.

I've litterally put the sample in an array then reversed the contents, something is telling me that there could be header info at the start of the sample that needs striping first, any ideas. thanks.

Here's what i have so far.

```<code>public class recorder extends Activity  {
    MediaRecorder myRecorder = null;
    DataInputStream dis = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void onClickPlay(View v){
        Log.v("onClickplay", "play clicked");

        try{
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/test.wav");
            mp.prepare();
            mp.start();
        } catch(Exception e3) {
            e3.printStackTrace();
        }
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("playing");
    }

    public void onClickRecord(View v){
        Log.v("onClickRecord", "record clicked");

        File path = Environment.getExternalStorageDirectory();
        Log.v("file path", ""+path.getAbsolutePath());

        File file = new File(path, "test.wav");
        if(file.exists()){
            file.delete();
        }
        path.mkdirs();
        Log.v("file path", ""+file.getAbsolutePath());
        myRecorder = new MediaRecorder();
        myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        myRecorder.setOutputFile(file.getAbsolutePath());
        Log.i("myrecorder", "about to prepare recording");
        try{
            myRecorder.prepare();
        } catch(Exception e) {
            e.printStackTrace();
        }

        Log.i("myrecorder", "prepared");
        myRecorder.start();   // Recording is now started
        Log.i("myrecorder", "recording");
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("recording");
    }

    public void onClickStop(View v){
        Log.v("onClickStop", "stop clicked");

            try{
             myRecorder.stop();
             myRecorder.reset();   // You can reuse the object by going back to setAudioSource() step
             myRecorder.release(); // Now the object cannot be reused
            }catch(Exception e){}

            TextView text = (TextView)findViewById(R.id.TextView01);
             text.setText("recording stopped");

        }

public void onClickReverse(View v){
        Log.v("onClickReverse", "reverse clicked");

        File f = Environment.getExternalStorageDirectory();
        String path = f.getAbsolutePath();
        path = path + "/test.wav";
        Log.v("path = ", ""+path);
        Log.v("dir = ", ""+f.getAbsolutePath());
        Log.v("test file exists? = ", ""+f.getAbsolutePath()+"/test.wav");

        File f2 = new File(path);
        Log.v("f2 = ", ""+f2.getAbsolutePath());

        try {
            InputStream is = new FileInputStream(f2);
            BufferedInputStream bis = new BufferedInputStream(is);
            dis = new DataInputStream(bis);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int fileLength = (int)f2.length();
        byte[] buffer = new byte[fileLength];

        /*File reversedFile = Environment.getExternalStorageDirectory();
          File revFile = new File(reversedFile, "reversedFile.wav");
          Log.v("reversedfile path", ""+ revFile.getAbsolutePath());

          if(revFile.exists()){
              revFile.delete();
          }

          reversedFile.mkdirs();
    */

        byte[] byteArray = new byte[fileLength +1];
        Log.v("bytearray size = ", ""+byteArray.length);

        try {
            while(dis.read(buffer) != -1 ) {
                dis.read(buffer);
                Log.v("about to read buffer", "buffer");

                byteArray = buffer;
            }

            Log.v(" buffer size = ", ""+ buffer.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

          byte[] tempArray = new byte[fileLength];

          int j=0;
          for (int i=byteArray.length-1; i >=0; i--) {
              tempArray[ j++ ] = byteArray[i];
          }

          File revPath = Environment.getExternalStorageDirectory();
          Log.v("revpath path", ""+revPath.getAbsolutePath());

          File revFile = new File(revPath, "revFile.wav");
          Log.v("revfile path ", ""+revFile.getAbsolutePath());
          if(revFile.exists()){
              revFile.delete();
          }

          revPath.mkdirs();

          try {
              OutputStream os = new FileOutputStream(revFile);
              BufferedOutputStream bos = new BufferedOutputStream(os);
              DataOutputStream dos = new DataOutputStream(bos);
              Log.v("temparray size = ", ""+ tempArray.length);
              dos.write(tempArray);
              dos.flush();
              dos.close();
          } catch (Exception e) {
              e.printStackTrace();
          }

          try{
              MediaPlayer mp = new MediaPlayer();
              mp.setDataSource(Environment.getExternalStorageDirectory().getPath()
                                                                    +"/revFile.wav");

              mp.prepare();
              mp.start();
         } catch(Exception e3) {
                e3.printStackTrace();
         }
          TextView text = (TextView)findViewById(R.id.TextView01);
           text.setText("playing reversed file");
      }

}// end of onclickrev
</code>```

答:
The WAV file format includes a 44-byte header chunk.  Most WAV files consist of this 44 byte header, followed by the actual sample data.  So, to reverse a WAV file, you should first copy the 44 byte header from the original file, and then copy the inverted sample data from the original after the header.  If you just reverse the byte order of the original entire file, it definitely won't work.  It also won't work if you copy the header and then reverse the byte order of the remainder of the file (actually it will sort of work, except what you get will be just noise).  You actually need to reverse the frames, where the frame size is dependent on the bytes-per-sample and whether the file is stereo or mono (for example, if the file is stereo and 2 bytes per sample, then each frame is 4 bytes).

Note that not all WAV files are "canonical" like this.  WAV files are actually a variant of RIFF files, so technically you need much more complicated code to find the various parts of the header and sample data within the original file.  However, most WAV files are just the header followed by the samples (and this will certainly be true if you're recording the audio yourself), in which case you can save yourself a lot of work.

Joe Cullity's link is a good description of the WAV file format.

Body:
I've created an app that records audio, saves the sample to the sd card then plays it back, using the record and play buttons. I need to reverse this sample. I can do all this and the the reversed sample is saved on the SD card under a different name. The original sample is test.wav and the same sample reversed is save as revFile.wav. when i try play revFile.wav android says it can't play this format.

I've litterally put the sample in an array then reversed the contents, something is telling me that there could be header info at the start of the sample that needs striping first, any ideas. thanks.

Here's what i have so far.

public class recorder extends Activity  {
    MediaRecorder myRecorder = null;
    DataInputStream dis = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void onClickPlay(View v){
        Log.v("onClickplay", "play clicked");

        try{
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/test.wav");
            mp.prepare();
            mp.start();
        } catch(Exception e3) {
            e3.printStackTrace();
        }
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("playing");
    }

    public void onClickRecord(View v){
        Log.v("onClickRecord", "record clicked");

        File path = Environment.getExternalStorageDirectory();
        Log.v("file path", ""+path.getAbsolutePath());

        File file = new File(path, "test.wav");
        if(file.exists()){
            file.delete();
        }
        path.mkdirs();
        Log.v("file path", ""+file.getAbsolutePath());
        myRecorder = new MediaRecorder();
        myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        myRecorder.setOutputFile(file.getAbsolutePath());
        Log.i("myrecorder", "about to prepare recording");
        try{
            myRecorder.prepare();
        } catch(Exception e) {
            e.printStackTrace();
        }

        Log.i("myrecorder", "prepared");
        myRecorder.start();   // Recording is now started
        Log.i("myrecorder", "recording");
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("recording");
    }

    public void onClickStop(View v){
        Log.v("onClickStop", "stop clicked");

            try{
             myRecorder.stop();
             myRecorder.reset();   // You can reuse the object by going back to setAudioSource() step
             myRecorder.release(); // Now the object cannot be reused
            }catch(Exception e){}

            TextView text = (TextView)findViewById(R.id.TextView01);
             text.setText("recording stopped");

        }

public void onClickReverse(View v){
        Log.v("onClickReverse", "reverse clicked");

        File f = Environment.getExternalStorageDirectory();
        String path = f.getAbsolutePath();
        path = path + "/test.wav";
        Log.v("path = ", ""+path);
        Log.v("dir = ", ""+f.getAbsolutePath());
        Log.v("test file exists? = ", ""+f.getAbsolutePath()+"/test.wav");

        File f2 = new File(path);
        Log.v("f2 = ", ""+f2.getAbsolutePath());

        try {
            InputStream is = new FileInputStream(f2);
            BufferedInputStream bis = new BufferedInputStream(is);
            dis = new DataInputStream(bis);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int fileLength = (int)f2.length();
        byte[] buffer = new byte[fileLength];

        /*File reversedFile = Environment.getExternalStorageDirectory();
          File revFile = new File(reversedFile, "reversedFile.wav");
          Log.v("reversedfile path", ""+ revFile.getAbsolutePath());

          if(revFile.exists()){
              revFile.delete();
          }

          reversedFile.mkdirs();
    */

        byte[] byteArray = new byte[fileLength +1];
        Log.v("bytearray size = ", ""+byteArray.length);

        try {
            while(dis.read(buffer) != -1 ) {
                dis.read(buffer);
                Log.v("about to read buffer", "buffer");

                byteArray = buffer;
            }

            Log.v(" buffer size = ", ""+ buffer.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

          byte[] tempArray = new byte[fileLength];

          int j=0;
          for (int i=byteArray.length-1; i >=0; i--) {
              tempArray[ j++ ] = byteArray[i];
          }

          File revPath = Environment.getExternalStorageDirectory();
          Log.v("revpath path", ""+revPath.getAbsolutePath());

          File revFile = new File(revPath, "revFile.wav");
          Log.v("revfile path ", ""+revFile.getAbsolutePath());
          if(revFile.exists()){
              revFile.delete();
          }

          revPath.mkdirs();

          try {
              OutputStream os = new FileOutputStream(revFile);
              BufferedOutputStream bos = new BufferedOutputStream(os);
              DataOutputStream dos = new DataOutputStream(bos);
              Log.v("temparray size = ", ""+ tempArray.length);
              dos.write(tempArray);
              dos.flush();
              dos.close();
          } catch (Exception e) {
              e.printStackTrace();
          }

          try{
              MediaPlayer mp = new MediaPlayer();
              mp.setDataSource(Environment.getExternalStorageDirectory().getPath()
                                                                    +"/revFile.wav");

              mp.prepare();
              mp.start();
         } catch(Exception e3) {
                e3.printStackTrace();
         }
          TextView text = (TextView)findViewById(R.id.TextView01);
           text.setText("playing reversed file");
      }

}// end of onclickrev


问:
add material-components-web.css via webpack
I added the mterial-components-web.css to the header of my index.html file.

```<code> <script src="node_modules/material-components-web/dist/material-components-web.js"></script>
 <script  src="dist/bundle.js"></script>
</code>```

the css components work great. Now I added a few javscript components via webpack. Now I thouhgt I could add all vai webpack into my bundle.js.

```<code>import 'material-components-web/dist/material-components-web.js';
</code>```

no error, but no styles loaded! wheres the problem?

regards

my webpack config.

```<code>const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  entry: './src/app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
       {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader']
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('style.css')
  ],
  devServer: {
    contentBase: "./build"
  }
};
</code>```

答:
Its difficult to pin down the exact cause without looking at webpack config.

Nevertheless, CSS needs two loaders as suggested in webpack docs. I can only guess that the loaders are not in place.

One can use inline import too as explained here

Though not near to what you are trying feel free to scan through this simple code that have. It basically has bootstrap css bundled via webpack. Note, however though, i have used require() and not import. Shouldnt be difficult to switch with proper js precompiler added in webpack config.

Body:
I added the mterial-components-web.css to the header of my index.html file.

the css components work great. Now I added a few javscript components via webpack. Now I thouhgt I could add all vai webpack into my bundle.js.

import 'material-components-web/dist/material-components-web.js';

no error, but no styles loaded! wheres the problem?

regards

my webpack config.

const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  entry: './src/app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
       {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader']
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('style.css')
  ],
  devServer: {
    contentBase: "./build"
  }
};


问:
ASP.NET Core automatically resolve all dependencies
Is it possible to configure ASP.NET Core DI to resolve all classes?
Something similar to Autofac AnyConcreteTypeNotAlreadyRegisteredSource functionality.

I'm able to use Autofac in ASP.NET Core, but I do not want to add additional library to my application, because ASP.NET Core already has DI.

So basically instead of:

```<code>services.AddTransient<MyService>();
services.AddTransient<MyAnotherService>();
</code>```

I'd prefer to do something like:

```<code>services.ResolveAll();
</code>```

答:
it seems we can start down this general automatic injection concept with a little reflection

i've filtered on "Provider" namespace and look for class names spelled the same as interfaces without "I", but of course season to your own taste

(this code works under an asp.net core 2.0 context)

```<code>  var allProviderTypes = System.Reflection.Assembly.GetExecutingAssembly()
    .GetTypes().Where(t=>t.Namespace != null && t.Namespace.Contains("Providers"));

  foreach(var intfc in allProviderTypes.Where(t=>t.IsInterface)) {
    var impl = allProviderTypes.FirstOrDefault(c=>c.IsClass && intfc.Name.Substring(1) == c.Name);
    if (impl != null) services.AddScoped(intfc, impl);
  }
</code>```

Body:
Is it possible to configure ASP.NET Core DI to resolve all classes?
Something similar to Autofac AnyConcreteTypeNotAlreadyRegisteredSource functionality.

I'm able to use Autofac in ASP.NET Core, but I do not want to add additional library to my application, because ASP.NET Core already has DI.

So basically instead of:

services.AddTransient<MyService>();
services.AddTransient<MyAnotherService>();

I'd prefer to do something like:

services.ResolveAll();

Body:
it seems we can start down this general automatic injection concept with a little reflection

i've filtered on "Provider" namespace and look for class names spelled the same as interfaces without "I", but of course season to your own taste

(this code works under an asp.net core 2.0 context)

  var allProviderTypes = System.Reflection.Assembly.GetExecutingAssembly()
    .GetTypes().Where(t=>t.Namespace != null && t.Namespace.Contains("Providers"));

  foreach(var intfc in allProviderTypes.Where(t=>t.IsInterface)) {
    var impl = allProviderTypes.FirstOrDefault(c=>c.IsClass && intfc.Name.Substring(1) == c.Name);
    if (impl != null) services.AddScoped(intfc, impl);
  }


问:
I want to calculate cross entropy at all outputs of LSTM

I am writing a program of classification problem using LSTM.
However, I do not know how to calculate cross entropy with all the output of LSTM.
Here is a part of my program.

cell_fw = tf.nn.rnn_cell.LSTMCell(num_hidden)
cell_bw = tf.nn.rnn_cell.LSTMCell(num_hidden)
outputs, _ = tf.nn.bidirectional_dynamic_rnn(cell_fw,cell_bw,inputs = inputs3, dtype=tf.float32,sequence_length= seq_len)

outputs = tf.concat(outputs,axis=2)

#outputs [batch_size,max_timestep,num_features]
outputs = tf.reshape(outputs, [-1, num_hidden*2])

W = tf.Variable(tf.truncated_normal([num_hidden*2,
                                     num_classes],
                                    stddev=0.1))

b = tf.Variable(tf.constant(0., shape=[num_classes]))

logits = tf.matmul(outputs, W) + b
```

How can I apply crossentropy error to this?
Should I create a vector that represents the same class as the number of max_timestep for each batch and calculate the error with that?

答:
Have you looked at cross_entropy documentation: https://www.tensorflow.org/api_docs/python/tf/losses/softmax_cross_entropy ?

The dimension of onehot_labels should answer your question.

Body:
I am writing a program of classification problem using LSTM.
However, I do not know how to calculate cross entropy with all the output of LSTM.
Here is a part of my program.

cell_fw = tf.nn.rnn_cell.LSTMCell(num_hidden)
cell_bw = tf.nn.rnn_cell.LSTMCell(num_hidden)
outputs, _ = tf.nn.bidirectional_dynamic_rnn(cell_fw,cell_bw,inputs = inputs3, dtype=tf.float32,sequence_length= seq_len)

outputs = tf.concat(outputs,axis=2)

#outputs [batch_size,max_timestep,num_features]
outputs = tf.reshape(outputs, [-1, num_hidden*2])

W = tf.Variable(tf.truncated_normal([num_hidden*2,
                                     num_classes],
                                    stddev=0.1))

b = tf.Variable(tf.constant(0., shape=[num_classes]))

logits = tf.matmul(outputs, W) + b

How can I apply crossentropy error to this?
Should I create a vector that represents the same class as the number of max_timestep for each batch and calculate the error with that?


问:
Play Framework CORS request
I have two apps:

Play 2.6.7 app running at localhost:9000

webpack dev server that runs at localhost:3000

The webpack app makes a POST request to the Play app

```<code>$.ajax({
  url: 'http://localhost:9000/users',
  data: JSON.stringify(data),
  dataType: 'json',
  method: 'POST'
})
</code>```

To which the Play app responds with

```<code>Failed to load http://localhost:9000/users: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
</code>```

Only when I explicitly set the header in the Play app with

```<code>def create = Action {
  Ok("stuff").withHeaders(
    "Access-Control-Allow-Origin" -> "http://localhost:3000"
  )
}
</code>```

does the request go through without error.

My question is: why doesn't Play set this header automatically as the docs seem to suggest? My application.conf is an empty file.

答:
The CORS filter isn't enabled by default. Adding

```<code>play.filters.enabled += play.filters.cors.CORSFilter
</code>```

to application.conf solves this issue

Title: Play Framework CORS request

Body:
I have two apps:

Play 2.6.7 app running at localhost:9000

webpack dev server that runs at localhost:3000

The webpack app makes a POST request to the Play app

$.ajax({
  url: 'http://localhost:9000/users',
  data: JSON.stringify(data),
  dataType: 'json',
  method: 'POST'
})

To which the Play app responds with

Failed to load http://localhost:9000/users: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Only when I explicitly set the header in the Play app with

def create = Action {
  Ok("stuff").withHeaders(
    "Access-Control-Allow-Origin" -> "http://localhost:3000"
  )
}

does the request go through without error.

My question is: why doesn't Play set this header automatically as the docs seem to suggest? My application.conf is an empty file.

Body:
The CORS filter isn't enabled by default. Adding

play.filters.enabled += play.filters.cors.CORSFilter

to application.conf solves this issue


问:
Kotlin Extension Any?.toString()
I have been trying to use extension functions in Kotlin.

```<code>class ExtensionExample() {

   var name: String? = null

   fun Any?.toString() : String {

       if (this == null) {
           return "Value is null"
       }

       return "Value is not null"
   }
}
</code>```

When I print the name variable like below

```<code>println(ExtensionExample().name.toString())
</code>```

It should print like

```<code>Value is null
</code>```

But it doesn't print like I expected. It only prints null.

Can someone explain please?

答:
Extension functions have scopes. This is why it is not accessible outside of the ExtensionExample class.

Usually, extension functions are defined as top-level functions. That is, they tend to belong outside of a class.

Your toString extension is defined within ExtensionExample. This is possible, but it means it is only available in the scope of this class, and this class only.

Your main method is likely a top-level function (and not a member of that class), so it doesn't have access to this extension function.

Only other members can access this extension function:

```<code>class ExtensionExample {

    var name: String? = null

    fun Any?.toString(): String {
        return if (this == null) "Value is null" else "Value is not null"
    }

    fun foo() {
        println(name.toString())
    }

}

fun main(args: Array<String>) {
    ExtensionExample().foo()
}
</code>```

prints "Value is null"

Try it online!

The reason why it compiles is that the toString method that is being called is the Any?.toString method from the kotlin-stdlib. That is, this method already exists.

fun Any?.toString(): String

Returns a string representation of the object. Can be called with a null receiver, in which case it returns the string "null".

Move your extension function out of the class. Your extension function will then hide the stdlib's extension, and any invocation in the same package not explicitly importing kotlin.toString will use your function.

Here is a working version of your code:

```<code>class ExtensionExample {

    var name: String? = null

}

fun Any?.toString(): String {
    return if (this == null) "Value is null" else "Value is not null"
}

fun main(args: Array<String>) {
    println(ExtensionExample().name.toString())
}
</code>```

prints "Value is null", as you wanted.

Try it online!

Note that you cannot hide a member function using an extension function. That is,

```<code>class Test {

    fun a() {
        println("a")
    }

}

fun Test.a() {
    println("b")
}

...
Test().a()
</code>```

will result in "a" being printed.

The only reason why your Any?.toString works (after being moved out of the class) is that Any? has no members as it is not a class, but a nullable type with the class Any. The already existing toString method is also an extension, so yours is not hidden by any members.

Title: Kotlin Extension Any?.toString()

Body:
I have been trying to use extension functions in Kotlin.

class ExtensionExample() {

   var name: String? = null

   fun Any?.toString() : String {

       if (this == null) {
           return "Value is null"
       }

       return "Value is not null"
   }
}

When I print the name variable like below

println(ExtensionExample().name.toString())

It should print like

Value is null

But it doesn't print like I expected. It only prints null.

Can someone explain please?

Body:
Extension functions have scopes. This is why it is not accessible outside of the ExtensionExample class.

Usually, extension functions are defined as top-level functions. That is, they tend to belong outside of a class.

Your toString extension is defined within ExtensionExample. This is possible, but it means it is only available in the scope of this class, and this class only.

Your main method is likely a top-level function (and not a member of that class), so it doesn't have access to this extension function.

Only other members can access this extension function:

class ExtensionExample {

    var name: String? = null

    fun Any?.toString(): String {
        return if (this == null) "Value is null" else "Value is not null"
    }

    fun foo() {
        println(name.toString())
    }

}

fun main(args: Array<String>) {
    ExtensionExample().foo()
}

prints "Value is null"

Try it online!

The reason why it compiles is that the toString method that is being called is the Any?.toString method from the kotlin-stdlib. That is, this method already exists.

fun Any?.toString(): String

Returns a string representation of the object. Can be called with a null receiver, in which case it returns the string "null".

Move your extension function out of the class. Your extension function will then hide the stdlib's extension, and any invocation in the same package not explicitly importing kotlin.toString will use your function.

Here is a working version of your code:

class ExtensionExample {

    var name: String? = null

}

fun Any?.toString(): String {
    return if (this == null) "Value is null" else "Value is not null"
}

fun main(args: Array<String>) {
    println(ExtensionExample().name.toString())
}

prints "Value is null", as you wanted.

Try it online!

Note that you cannot hide a member function using an extension function. That is,

class Test {

    fun a() {
        println("a")
    }

}

fun Test.a() {
    println("b")
}

...
Test().a()

will result in "a" being printed.

The only reason why your Any?.toString works (after being moved out of the class) is that Any? has no members as it is not a class, but a nullable type with the class Any. The already existing toString method is also an extension, so yours is not hidden by any members.


问:
Practical Experience using Stripes?
I am coming from an Enterprise Java background which involves a fairly heavyweight software stack, and have recently discovered the
Stripes framework; my initial impression is that this seems to do a good job of minimising the unpleasant parts of building a web application in Java.

Has anyone used Stripes for a project that has gone live? And can you share your experiences from the project? Also, did you consider any other technologies and (if so) why did you chose Stripes?

答:
We converted a home-grown web framework to stripes in about a week. We're using it in production at this time and it's a great framework. The community is extremely helpful, and the framework doesn't get in your way. It can be extended in many places to change the behavior as you see fit. The url binding feature is awesome as well. We implemented a robust security framework using annotations and interceptors. We're using spring for dependency injection and stripes has excellent support for that.

I'd definitely use the new 1.5 release if you're going to use it.

I'm a huge fan of the framework. I came from a struts background and it's the exact framework I was looking for. The other developers on our team really enjoy using the stripes framework.

I just bought the stripes beta book from the pragmatic programmer's site. It's a great resource on Stripes 1.5.

OwnerDisplayName: Andrew Whitehouse

Title: Practical Experience using Stripes?


问:
PHP reflection and invokeArgs(): forcing a parameter to use its default value
I need to call a function using the Reflection API. The function has optional parameters, and I need to invoke it providing just some of them.

For example, I have this function:

```<code>public function doSomething($firstParam, $secondParam = "default", $thirdParam = "default)
</code>```

And I'm using invokeArgs() to invoke doSomething(), passing an array of values representing the arguments omitting to set a value to the optional $secondParam:

```<code>$parameters = array("firstParam"=>"value", "thirdParam"=>"thirdValue");
$reflectedDoSomething->invokeArgs($instance, $parameters);
</code>```

What happens here is that invokeArgs() invokes the method setting its parameters in a row, without skipping the $secondParam, that now is valued "thirdValue" and omitting the $thirdParam. And that's logically correct. The method is invoked like doSomething("value", "thirdValue").

What I'd like to do here is to force the $secondParam to use its default value. Setting "secondParam" => null in the $parameters array is not a solution because null is a value.

Is it possibile using Reflection?

Thanks

答:
How about not setting the associative name secondParam, but rather putting a null as a second second parameter.

```<code>$parameters = array("firstParam"=>"value", null, "thirdParam"=>"thirdValue");
</code>```

Body:
I need to call a function using the Reflection API. The function has optional parameters, and I need to invoke it providing just some of them.

For example, I have this function:

public function doSomething($firstParam, $secondParam = "default", $thirdParam = "default)

And I'm using invokeArgs() to invoke doSomething(), passing an array of values representing the arguments omitting to set a value to the optional $secondParam:

$parameters = array("firstParam"=>"value", "thirdParam"=>"thirdValue");
$reflectedDoSomething->invokeArgs($instance, $parameters);

What happens here is that invokeArgs() invokes the method setting its parameters in a row, without skipping the $secondParam, that now is valued "thirdValue" and omitting the $thirdParam. And that's logically correct. The method is invoked like doSomething("value", "thirdValue").

What I'd like to do here is to force the $secondParam to use its default value. Setting "secondParam" => null in the $parameters array is not a solution because null is a value.

Is it possibile using Reflection?

Thanks

Body:
How about not setting the associative name secondParam, but rather putting a null as a second second parameter.

$parameters = array("firstParam"=>"value", null, "thirdParam"=>"thirdValue");


问:
How do I disable a CSS rule?
I have the following CSS rule

#class {
    margin: 4px 5px 6px 7px;
    color: red;
}
```

<p>What I usualy do is</p>

```document.getElementById('class').style.margin= '0px';
```

<p>Then after doing that to reset I go the same step</p>

```document.getElementById('class').style.margin= '4px 5px 6px 7px';
```

How do I disable the margin using JavaScript\JQuery instead of changing the value to 0 then reset it to 4px 5px 6px 7px

答:
The easiest solution here is to use classes, and use jquery or javascript to change the class of the element whenever you want different behavior as on button click in the example I have shown below.

$("#add").click(function() {
  $("#exd").addClass('margin');
  $("#exd").removeClass('no-margin');
});

$("#rem").click(function() {
  $("#exd").removeClass('margin');
  $("#exd").addClass('no-margin');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.no-margin {
  margin: 0px;
}

.margin {
  margin: 15px 15px 15px 15px;
}</code>```

Example Div

<button id="add">Add margin</button>
<button id="rem">Remove margin</button>```

Hope this is clear.

Title: How do I disable a CSS rule?

Body:
I have the following CSS rule

#class {
    margin: 4px 5px 6px 7px;
    color: red;
}

What I usualy do is

document.getElementById('class').style.margin= '0px';

Then after doing that to reset I go the same step

document.getElementById('class').style.margin= '4px 5px 6px 7px';

How do I disable the margin using JavaScript\JQuery instead of changing the value to 0 then reset it to 4px 5px 6px 7px

Body:
The easiest solution here is to use classes, and use jquery or javascript to change the class of the element whenever you want different behavior as on button click in the example I have shown below.

$("#add").click(function() {
  $("#exd").addClass('margin');
  $("#exd").removeClass('no-margin');
});

$("#rem").click(function() {
  $("#exd").removeClass('margin');
  $("#exd").addClass('no-margin');
});

.no-margin {
  margin: 0px;
}

.margin {
  margin: 15px 15px 15px 15px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="exd">Example Div</div>

<button id="add">Add margin</button>
<button id="rem">Remove margin</button>

Hope this is clear.


答:
A slight alteration to Scath's answer

```<code>.margin {
    margin: 4px 5px 6px 7px;
    color: red;
}
.margin.noMargin {
    margin: 0px;
}
</code>```

Then all you have to do is add/remove the noMargin class.  More specific css rules take precedence.

Title: How do I disable a CSS rule?

Body:
A slight alteration to Scath's answer

.margin {
    margin: 4px 5px 6px 7px;
    color: red;
}
.margin.noMargin {
    margin: 0px;
}

Then all you have to do is add/remove the noMargin class.  More specific css rules take precedence.


问:
M - Transforming cumulative value (running total) to actual value
A user recieves monthly customer reports with running totals of monthly sales (few tens of thousand lines). The sales are displayed as running total, I'm trying to find a powerquery solution to get the actual sales as (*Required*) output:

```<code>╔══════╦═══════╦═════════╦═══════╦════════════╗
║ Year ║ Month ║ StoreID ║ Sales ║ *Required* ║
╠══════╬═══════╬═════════╬═══════╬════════════╣
║ 2017 ║    10 ║       1 ║     5 ║          5 ║
║ 2017 ║    11 ║       1 ║    11 ║          6 ║
║ 2017 ║    12 ║       1 ║    18 ║          7 ║
║ 2017 ║    11 ║       2 ║    10 ║         10 ║
╚══════╩═══════╩═════════╩═══════╩════════════╝
</code>```

In tSQL I'd do something like

```<code>Sales - LAG(Sales,1,0)OVER(Partiton by Year, StoreID Order by Month)
</code>```

A simular question (but in reverse) was answered, but the proposed solution looks like the equivalent of a Cross Join. I'm new to powerquery (so I may be misunderstanding) but I cant see this being viable as datasets grow every month. Is there a better way to approach this, I cannot find an example in "M"?

Edit: List.Range looks promising

答:
Actually you require values from the previous row on the current row.
A common approach is to add 2 Index columns, one starting with 0 and the other starting with 1. Next, merge the table with itself using the Index columns as join columns. After expanding the required columns from the nested tables, you can add a custom column with the required calculation.</p>

```<code>let
    Source = Sales,
    #"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1),
    #"Added Index1" = Table.AddIndexColumn(#"Added Index", "Index.1", 1, 1),
    #"Merged Queries" = Table.NestedJoin(#"Added Index1",{"Index"},#"Added Index1",{"Index.1"},"Previous",JoinKind.LeftOuter),
    #"Expanded Previous" = Table.ExpandTableColumn(#"Merged Queries", "Previous", {"StoreID", "Sales"}, {"Previous.StoreID", "Previous.Sales"}),
    #"Sorted Rows" = Table.Sort(#"Expanded Previous",{{"Index", Order.Ascending}}),
    #"Added Custom" = Table.AddColumn(#"Sorted Rows", "Required", each [Sales] - (if [StoreID] = [Previous.StoreID] then [Previous.Sales] else 0), Int64.Type),
    #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index", "Index.1", "Previous.StoreID", "Previous.Sales"})
in
    #"Removed Columns"
</code>```

Body:
A user recieves monthly customer reports with running totals of monthly sales (few tens of thousand lines). The sales are displayed as running total, I'm trying to find a powerquery solution to get the actual sales as (*Required*) output:

╔══════╦═══════╦═════════╦═══════╦════════════╗
║ Year ║ Month ║ StoreID ║ Sales ║ *Required* ║
╠══════╬═══════╬═════════╬═══════╬════════════╣
║ 2017 ║    10 ║       1 ║     5 ║          5 ║
║ 2017 ║    11 ║       1 ║    11 ║          6 ║
║ 2017 ║    12 ║       1 ║    18 ║          7 ║
║ 2017 ║    11 ║       2 ║    10 ║         10 ║
╚══════╩═══════╩═════════╩═══════╩════════════╝

In tSQL I'd do something like

Sales - LAG(Sales,1,0)OVER(Partiton by Year, StoreID Order by Month)

A simular question (but in reverse) was answered, but the proposed solution looks like the equivalent of a Cross Join. I'm new to powerquery (so I may be misunderstanding) but I cant see this being viable as datasets grow every month. Is there a better way to approach this, I cannot find an example in "M"?

Edit: List.Range looks promising

Body:
Actually you require values from the previous row on the current row.
A common approach is to add 2 Index columns, one starting with 0 and the other starting with 1. Next, merge the table with itself using the Index columns as join columns. After expanding the required columns from the nested tables, you can add a custom column with the required calculation.

let
    Source = Sales,
    #"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1),
    #"Added Index1" = Table.AddIndexColumn(#"Added Index", "Index.1", 1, 1),
    #"Merged Queries" = Table.NestedJoin(#"Added Index1",{"Index"},#"Added Index1",{"Index.1"},"Previous",JoinKind.LeftOuter),
    #"Expanded Previous" = Table.ExpandTableColumn(#"Merged Queries", "Previous", {"StoreID", "Sales"}, {"Previous.StoreID", "Previous.Sales"}),
    #"Sorted Rows" = Table.Sort(#"Expanded Previous",{{"Index", Order.Ascending}}),
    #"Added Custom" = Table.AddColumn(#"Sorted Rows", "Required", each [Sales] - (if [StoreID] = [Previous.StoreID] then [Previous.Sales] else 0), Int64.Type),
    #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index", "Index.1", "Previous.StoreID", "Previous.Sales"})
in
    #"Removed Columns"