问:
How to display a streaming DataFrame (as show fails with AnalysisException)?
So I have some data I'm stream in a Kafka topic, I'm taking this streaming data and placing it into a DataFrame. I want to display the data inside of the DataFrame:

import os
from kafka import KafkaProducer
from pyspark.sql import SparkSession, DataFrame
import time
from datetime import datetime, timedelta

os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.2.0,org.apache.spark:spark-streaming-kafka-0-8_2.11:2.2.0 pyspark-shell'

topic_name = "my-topic"
kafka_broker = "localhost:9092"

producer = KafkaProducer(bootstrap_servers = kafka_broker)
spark = SparkSession.builder.getOrCreate()
terminate = datetime.now() + timedelta(seconds=30)

while datetime.now() < terminate:
    producer.send(topic = topic_name, value = str(datetime.now()).encode('utf-8'))
    time.sleep(1)

readDF = spark \
    .readStream \
    .format("kafka") \
    .option("kafka.bootstrap.servers", kafka_broker) \
    .option("subscribe", topic_name) \
    .load()
readDF = readDF.selectExpr("CAST(key AS STRING)","CAST(value AS STRING)")

readDF.writeStream.format("console").start()
readDF.show()

producer.close()
```

<p>However I keep on getting this error:</p>

```During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/spark/spark/python/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/home/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o30.showString.
: org.apache.spark.sql.AnalysisException: Queries with streaming sources must be executed with writeStream.start();;
kafka
    at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$.org$apache$spark$sql$catalyst$analysis$UnsupportedOperationChecker$$throwError(UnsupportedOperationChecker.scala:297)
    at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$$anonfun$checkForBatch$1.apply(UnsupportedOperationChecker.scala:36)
    at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$$anonfun$checkForBatch$1.apply(UnsupportedOperationChecker.scala:34)
    at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:127)
...
Traceback (most recent call last):
      File "test2.py", line 30, in <module>
        readDF.show()
      File "/home/spark/spark/python/pyspark/sql/dataframe.py", line 336, in show
        print(self._jdf.showString(n, 20))
      File "/home/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
      File "/home/spark/spark/python/pyspark/sql/utils.py", line 69, in deco
        raise AnalysisException(s.split(': ', 1)[1], stackTrace)
    pyspark.sql.utils.AnalysisException: 'Queries with streaming sources must be executed with writeStream.start();;\nkafka'
```

I don't understand why the exception is happening, I'm calling writeStream.start() right before show(). I tried getting rid of selectExpr() but that made no difference. Does anyone know how to display a stream sourced DataFrame? I'm using Python 3.6.1, Kafka 0.10.2.1, and Spark 2.2.0

答:
Streaming DataFrame doesn't support the show() method directly, but there is a way to see your data by making your back ground thread sleep for some moments and using the show() function on the  temp table created in memory  sink. I can help with the pyspark way of using the show() method.

Refer to my answer here

Body:
So I have some data I'm stream in a Kafka topic, I'm taking this streaming data and placing it into a DataFrame. I want to display the data inside of the DataFrame:

import os
from kafka import KafkaProducer
from pyspark.sql import SparkSession, DataFrame
import time
from datetime import datetime, timedelta

os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.2.0,org.apache.spark:spark-streaming-kafka-0-8_2.11:2.2.0 pyspark-shell'

topic_name = "my-topic"
kafka_broker = "localhost:9092"

producer = KafkaProducer(bootstrap_servers = kafka_broker)
spark = SparkSession.builder.getOrCreate()
terminate = datetime.now() + timedelta(seconds=30)

while datetime.now() < terminate:
    producer.send(topic = topic_name, value = str(datetime.now()).encode('utf-8'))
    time.sleep(1)

readDF = spark \
    .readStream \
    .format("kafka") \
    .option("kafka.bootstrap.servers", kafka_broker) \
    .option("subscribe", topic_name) \
    .load()
readDF = readDF.selectExpr("CAST(key AS STRING)","CAST(value AS STRING)")

readDF.writeStream.format("console").start()
readDF.show()

producer.close()

However I keep on getting this error:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/spark/spark/python/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/home/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o30.showString.
: org.apache.spark.sql.AnalysisException: Queries with streaming sources must be executed with writeStream.start();;
kafka
    at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$.org$apache$spark$sql$catalyst$analysis$UnsupportedOperationChecker$$throwError(UnsupportedOperationChecker.scala:297)
    at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$$anonfun$checkForBatch$1.apply(UnsupportedOperationChecker.scala:36)
    at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$$anonfun$checkForBatch$1.apply(UnsupportedOperationChecker.scala:34)
    at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:127)
...
Traceback (most recent call last):
      File "test2.py", line 30, in <module>
        readDF.show()
      File "/home/spark/spark/python/pyspark/sql/dataframe.py", line 336, in show
        print(self._jdf.showString(n, 20))
      File "/home/spark/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
      File "/home/spark/spark/python/pyspark/sql/utils.py", line 69, in deco
        raise AnalysisException(s.split(': ', 1)[1], stackTrace)
    pyspark.sql.utils.AnalysisException: 'Queries with streaming sources must be executed with writeStream.start();;\nkafka'

I don't understand why the exception is happening, I'm calling writeStream.start() right before show(). I tried getting rid of selectExpr() but that made no difference. Does anyone know how to display a stream sourced DataFrame? I'm using Python 3.6.1, Kafka 0.10.2.1, and Spark 2.2.0


来源: stackexchange

问:
Pandas: Conditional Rolling window by another column element?
I have a dataframe with dates, id's and values.

For example:

```<code>date        id        value
2016-08-28   A          1
2016-08-28   B          1
2016-08-29   C          2
2016-09-02   B          0
2016-09-03   A          3
2016-09-06   C          1
2017-01-15   B          2
2017-01-18   C          3
2017-01-18   A          2
</code>```

I want to apply a rolling mean by element, stating one after, so that the result would be like:

```<code>date        id        value    rolling_mean
2016-08-28   A          1           NaN
2016-08-28   B          1           NaN
2016-08-29   C          2           NaN
2016-09-02   B          0           0.5
2016-09-03   A          3           2.0
2016-09-06   C          1           1.5
2017-01-15   B          2           1.0
2017-01-18   C          3           2.0
2017-01-18   A          2           2.5
</code>```

The closest I've come to this was:

```<code>grouped = df.groupby(["id", "value"])
df["rolling_mean"] = grouped["value"].shift(1).rolling(window = 2).mean()
</code>```

But this gives me the wrong values back, as it keeps the order with the remaining elements.

Any ideia?

Thank you in advance,

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe with dates, id's and values.

For example:

date        id        value
2016-08-28   A          1
2016-08-28   B          1
2016-08-29   C          2
2016-09-02   B          0
2016-09-03   A          3
2016-09-06   C          1
2017-01-15   B          2
2017-01-18   C          3
2017-01-18   A          2

I want to apply a rolling mean by element, stating one after, so that the result would be like:

date        id        value    rolling_mean
2016-08-28   A          1           NaN
2016-08-28   B          1           NaN
2016-08-29   C          2           NaN
2016-09-02   B          0           0.5
2016-09-03   A          3           2.0
2016-09-06   C          1           1.5
2017-01-15   B          2           1.0
2017-01-18   C          3           2.0
2017-01-18   A          2           2.5

The closest I've come to this was:

grouped = df.groupby(["id", "value"])
df["rolling_mean"] = grouped["value"].shift(1).rolling(window = 2).mean()

But this gives me the wrong values back, as it keeps the order with the remaining elements.

Any ideia?

Thank you in advance,

Body:
Like this:

df['rolling_mean'] = df.groupby('id')['value'].rolling(2).mean().reset_index(0,drop=True).sort_index()

Output:

         date id  value  rolling_mean
0  2016-08-28  A      1           nan
1  2016-08-28  B      1           nan
2  2016-08-29  C      2           nan
3  2016-09-02  B      0          0.50
4  2016-09-03  A      3          2.00
5  2016-09-06  C      1          1.50
6  2017-01-15  B      2          1.00
7  2017-01-18  C      3          2.00
8  2017-01-18  A      2          2.50


问:
How to avoid repetition when calling async request?
I´m using Vue 2.6.10 and Vuesax 3 to build an application.

This app makes a lot of async like this:

```<code> async listResource() {
  this.$vs.loading(); //Start of the loading
  try {
    const response = await repository.get();
    this.list = response.data;
    this.$vs.notify({ title: "Success", text: "List fetched." });
    this.sdoSmething();
  } catch (err) {
    this.$vs.notify({
      title: err, //I´m not showing this error to the user, this is just to exemplify
      text: "There was an error when fetching the resource"
    });
  }
  finally{
    this.$vs.loading.close(); //Close the loading
  }
}
</code>```

The problem with this approach is that I´m repeating a lot of code over and over.

If I need to make another request, I´ll have to create another method, send a specific message if the promisses resolves or if it fails...

How would be a nice way to abstract this?

答:
Give your listResource method parameters to change the messages. For example two callback functions that will return a message, static or based on the input of those callbacks.

In the example below I've written two functions which will build a message object. The successMessage is static and the errorMessage takes in the error from the catch statement.

Both are passed to the listResource method in the order of the parameters and called whenever the request succeeded or failed.

```<code>class YourClass {

  async listResource(success, error) {
    this.$vs.loading(); //Start of the loading
    try {
      const response = await repository.get();
      this.list = response.data;
      this.$vs.notify(success());
      this.sdoSmething();
    } catch (err) {
      this.$vs.notify(error(err)); // Pass the message.
    } finally {
      this.$vs.loading.close(); //Close the loading
    }
  };

}

const successMessage = () => ({
  title: "Success",
  text: "List fetched."
});

const errorMessage = err => ({
  title: err,
  text: "There was an error when fetching the resource"
});

const instance = new YourClass();
instance.listResource(successMessage, errorMessage);

// Or inside the instance.
await this.listResource(successMessage, errorMessage);
</code>```

Body:
I´m using Vue 2.6.10 and Vuesax 3 to build an application.

This app makes a lot of async like this:

 async listResource() {
  this.$vs.loading(); //Start of the loading
  try {
    const response = await repository.get();
    this.list = response.data;
    this.$vs.notify({ title: "Success", text: "List fetched." });
    this.sdoSmething();
  } catch (err) {
    this.$vs.notify({
      title: err, //I´m not showing this error to the user, this is just to exemplify
      text: "There was an error when fetching the resource"
    });
  }
  finally{
    this.$vs.loading.close(); //Close the loading
  }
}

The problem with this approach is that I´m repeating a lot of code over and over.

If I need to make another request, I´ll have to create another method, send a specific message if the promisses resolves or if it fails...

How would be a nice way to abstract this?

Body:
Give your listResource method parameters to change the messages. For example two callback functions that will return a message, static or based on the input of those callbacks.

In the example below I've written two functions which will build a message object. The successMessage is static and the errorMessage takes in the error from the catch statement.

Both are passed to the listResource method in the order of the parameters and called whenever the request succeeded or failed.

class YourClass {

  async listResource(success, error) {
    this.$vs.loading(); //Start of the loading
    try {
      const response = await repository.get();
      this.list = response.data;
      this.$vs.notify(success());
      this.sdoSmething();
    } catch (err) {
      this.$vs.notify(error(err)); // Pass the message.
    } finally {
      this.$vs.loading.close(); //Close the loading
    }
  };

}

const successMessage = () => ({
  title: "Success",
  text: "List fetched."
});

const errorMessage = err => ({
  title: err,
  text: "There was an error when fetching the resource"
});

const instance = new YourClass();
instance.listResource(successMessage, errorMessage);

// Or inside the instance.
await this.listResource(successMessage, errorMessage);


问:
I have a large list of dataframes and need to extract multiple based on their names
I have a large list called "all_input" that contains 13 data.frames as such:

```<code>Name                  Type                Value
all_input             list[13]            List of length 13
  113_red.csv         list[649 x 14]      A data.frame with # rows and # columns
  blue_123.csv        list[389 x 14]      A data.frame with # rows and # columns
  blue_4.csv          list[428 x 14]      A data.frame with # rows and # columns
  greenblue_123.csv   list[789 x 14]      A data.frame with # rows and # columns
  greenblue_4.csv     list[132 x 14]      A data.frame with # rows and # columns
  greenblue_5.csv     list[245 x 14]      A data.frame with # rows and # columns
</code>```

I need to read just the files containing "blue" in the name, not "greenblue", just "blue".
I tried

```<code>blue <- grepl( "^blue", all_input$Name )
</code>```

and this returns a value "blue" logical (empty). For context, after extracting the blue data.frames, I am going to select specific columns and rbind them into a new data.frame.
str(my data) returns:

```<code>> str(all_input)
List of 13
 $ 113_red.csv:'data.frame':    6490785 obs. of  14 variables:
  ..$ state_and_county_fips_code: int [1:6490785] 88180 88180 88180 88180 88181 88181 88181 88181 88182 88182 ...
  ..$ tribal_name               : Factor w/ 14 levels "","Coeur d'Alene Tribe of the Coeur d'Alene Reservation, Idaho",..: 12 12 12 12 2 2 2 2 6 6 ...
  ..$ st_usps_cd                : Factor w/ 55 levels "","AK","AL","AR",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ county_name               : Factor w/ 1939 levels "","Abbeville",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ data_category_cd          : Factor w/ 1 level "NP": 1 1 1 1 1 1 1 1 1 1 ...
  ..$ scc                       : num [1:6490785] 2103008000 2302002100 2102008000 2302002200 2102008000 ...
  ..$ emissions_type_code       : Factor w/ 5 levels "","C","H","M",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ aircraft_engine_type_cd   : logi [1:6490785] NA NA NA NA NA NA ...
  ..$ emissions_op_type_code    : logi [1:6490785] NA NA NA NA NA NA ...
  ..$ data_set_short_name       : Factor w/ 72 levels "2011ADEM","2011AKDEC",..: 51 51 51 51 52 52 52 52 53 53 ...
  ..$ pollutant_cd              : Factor w/ 198 levels "100027","100414",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ description               : Factor w/ 198 levels "1-Methylphenanthrene",..: 25 25 25 25 25 25 25 25 25 25 ...
  ..$ total_emissions           : num [1:6490785] 0.000448 0.07679 0.006822 0.369756 0 ...
  ..$ uom                       : Factor w/ 2 levels "LB","TON": 1 1 1 1 1 1 1 1 1 1 ...
 $ blue_123.csv    :'data.frame':   3985783 obs. of  14 variables:
  ..$ state_and_county_fips_code: int [1:3985783] 42097 42031 42031 36097 51540 23009 72103 54037 25013 36119 ...
  ..$ tribal_name               : logi [1:3985783] NA NA NA NA NA NA ...
  ..$ st_usps_cd                : Factor w/ 16 levels "CT","DC","DE",..: 10 10 10 9 13 6 11 16 4 9 ...
  ..$ county_name               : Factor w/ 431 levels "Accomack","Adams",..: 284 101 101 361 90 174 267 200 171 414 ...
</code>```

and so on. 'Type' is a list, and 'Value' is a list of data.frames.

答:
We can filter by the names of the 'all_input' using grep, loop over the list elements with map, and select the columns of interest

```<code>library(dplyr)
library(purrr)
map_dfr(all_input[grep("^blue", names(all_input))], ~
            .x %>%
                select( state_and_county_fips_code,  tribal_name ))
</code>```

note: using grepl and "^blue" omit data.frames named "greenblue" from the selection.

Body:
I have a large list called "all_input" that contains 13 data.frames as such:

Name                  Type                Value
all_input             list[13]            List of length 13
  113_red.csv         list[649 x 14]      A data.frame with # rows and # columns
  blue_123.csv        list[389 x 14]      A data.frame with # rows and # columns
  blue_4.csv          list[428 x 14]      A data.frame with # rows and # columns
  greenblue_123.csv   list[789 x 14]      A data.frame with # rows and # columns
  greenblue_4.csv     list[132 x 14]      A data.frame with # rows and # columns
  greenblue_5.csv     list[245 x 14]      A data.frame with # rows and # columns

I need to read just the files containing "blue" in the name, not "greenblue", just "blue".
I tried

blue <- grepl( "^blue", all_input$Name )

and this returns a value "blue" logical (empty). For context, after extracting the blue data.frames, I am going to select specific columns and rbind them into a new data.frame.
str(my data) returns:

> str(all_input)
List of 13
 $ 113_red.csv:'data.frame':    6490785 obs. of  14 variables:
  ..$ state_and_county_fips_code: int [1:6490785] 88180 88180 88180 88180 88181 88181 88181 88181 88182 88182 ...
  ..$ tribal_name               : Factor w/ 14 levels "","Coeur d'Alene Tribe of the Coeur d'Alene Reservation, Idaho",..: 12 12 12 12 2 2 2 2 6 6 ...
  ..$ st_usps_cd                : Factor w/ 55 levels "","AK","AL","AR",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ county_name               : Factor w/ 1939 levels "","Abbeville",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ data_category_cd          : Factor w/ 1 level "NP": 1 1 1 1 1 1 1 1 1 1 ...
  ..$ scc                       : num [1:6490785] 2103008000 2302002100 2102008000 2302002200 2102008000 ...
  ..$ emissions_type_code       : Factor w/ 5 levels "","C","H","M",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ aircraft_engine_type_cd   : logi [1:6490785] NA NA NA NA NA NA ...
  ..$ emissions_op_type_code    : logi [1:6490785] NA NA NA NA NA NA ...
  ..$ data_set_short_name       : Factor w/ 72 levels "2011ADEM","2011AKDEC",..: 51 51 51 51 52 52 52 52 53 53 ...
  ..$ pollutant_cd              : Factor w/ 198 levels "100027","100414",..: 1 1 1 1 1 1 1 1 1 1 ...
  ..$ description               : Factor w/ 198 levels "1-Methylphenanthrene",..: 25 25 25 25 25 25 25 25 25 25 ...
  ..$ total_emissions           : num [1:6490785] 0.000448 0.07679 0.006822 0.369756 0 ...
  ..$ uom                       : Factor w/ 2 levels "LB","TON": 1 1 1 1 1 1 1 1 1 1 ...
 $ blue_123.csv    :'data.frame':   3985783 obs. of  14 variables:
  ..$ state_and_county_fips_code: int [1:3985783] 42097 42031 42031 36097 51540 23009 72103 54037 25013 36119 ...
  ..$ tribal_name               : logi [1:3985783] NA NA NA NA NA NA ...
  ..$ st_usps_cd                : Factor w/ 16 levels "CT","DC","DE",..: 10 10 10 9 13 6 11 16 4 9 ...
  ..$ county_name               : Factor w/ 431 levels "Accomack","Adams",..: 284 101 101 361 90 174 267 200 171 414 ...

and so on. 'Type' is a list, and 'Value' is a list of data.frames.

Body:
We can filter by the names of the 'all_input' using grep, loop over the list elements with map, and select the columns of interest

library(dplyr)
library(purrr)
map_dfr(all_input[grep("^blue", names(all_input))], ~
            .x %>%
                select( state_and_county_fips_code,  tribal_name ))

note: using grepl and "^blue" omit data.frames named "greenblue" from the selection.


问:
How to make this method more generic
i am having some trouble figuring something regarding inheritance in Java. I thought it would be straightforward but it has stumped me.

I have this superclass..

```<code>public class MyItem {

    private String barCode;
    private String price;

    public String getBarCode() {
        return barCode;
    }

    public void setBarCode(String barCode) {
        this.barCode = barCode;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

}
</code>```

And i have these 2 subclasses

```<code>public class PromotionalItem extends MyItem {

    private String promotion;

    public String setPromotion(String promotion) {
        this.promotion = promotion;
    }

    public void getPromotion() {
        this.promotion = promotion;
    }

}

public class SellableItem extends MyItem {

    private String quantity;

    public String setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public void getQuantity() {
        this.quantity = quantity;
    }

}
</code>```

Now i have a method that i want to make generic, i thought something like this could work...

```<code>public void processItem(MyItem item){
    if(item.getClass().isAssignableFrom(PromotionalItem.class)){
        processPromotionalItem((PromotionalItem)item);
    }
    else{
        processSellableItem((SellableItem)item);
    }
}
</code>```

But I am getting a ClassCastException when i try to cast these items as their respective subclasses. I thought something like this would be do-able. Am i missing something? What is the alternative do something like this?

答:
Make MyClass abstract and add an abstract process method, like @JoakimDanielson suggested. Then, in your child classes, override that method and implement your own logic.

```<code>public abstract class MyItem {
    ...
    public abstract void process();
}

public class PromotionalItem extends MyItem {
    ...
    @Override
    public void process() {
        // do whatever
    }
}

 public class SellableItem extends MyItem {
    ...
    @Override
    public void process() {
        // do whatever
    }
}
</code>```

Then, in your processItem method, just call process:

```<code>public void processItem(MyItem item) {
    item.process();
}
</code>```

Title: How to make this method more generic

Body:
i am having some trouble figuring something regarding inheritance in Java. I thought it would be straightforward but it has stumped me.

I have this superclass..

public class MyItem {

    private String barCode;
    private String price;

    public String getBarCode() {
        return barCode;
    }

    public void setBarCode(String barCode) {
        this.barCode = barCode;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

}

And i have these 2 subclasses

public class PromotionalItem extends MyItem {

    private String promotion;

    public String setPromotion(String promotion) {
        this.promotion = promotion;
    }

    public void getPromotion() {
        this.promotion = promotion;
    }

}

public class SellableItem extends MyItem {

    private String quantity;

    public String setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public void getQuantity() {
        this.quantity = quantity;
    }

}

Now i have a method that i want to make generic, i thought something like this could work...

public void processItem(MyItem item){
    if(item.getClass().isAssignableFrom(PromotionalItem.class)){
        processPromotionalItem((PromotionalItem)item);
    }
    else{
        processSellableItem((SellableItem)item);
    }
}

But I am getting a ClassCastException when i try to cast these items as their respective subclasses. I thought something like this would be do-able. Am i missing something? What is the alternative do something like this?

Body:
Make MyClass abstract and add an abstract process method, like @JoakimDanielson suggested. Then, in your child classes, override that method and implement your own logic.

public abstract class MyItem {
    ...
    public abstract void process();
}

public class PromotionalItem extends MyItem {
    ...
    @Override
    public void process() {
        // do whatever
    }
}

 public class SellableItem extends MyItem {
    ...
    @Override
    public void process() {
        // do whatever
    }
}

Then, in your processItem method, just call process:

public void processItem(MyItem item) {
    item.process();
}


问:
553 5.1.3 The recipient address is not a valid RFC-5321 address
When sending bulk emails I was receiving several error messages that said:

```<code>553 5.1.3 The recipient address <john@example.com > is not a valid RFC-5321 address.
</code>```

The format of the email addresses looked completely valid so I couldn't figure out at first why these messages weren't being delivered.

答: Upon further inspection, I noticed that the recipient email addresses for each of the failed messages had a single space on the end.  It's not as hard to see in the example I provided above, but the error report I was viewing had smaller font and would sometimes put a line break where the space was, so it wasn't as obvious.  By the way, I was using the SendGrid API to send these emails, but I don't think that the issue would be unique to using SendGrid.</p>

Body:
When sending bulk emails I was receiving several error messages that said:

553 5.1.3 The recipient address <john@example.com > is not a valid RFC-5321 address.

The format of the email addresses looked completely valid so I couldn't figure out at first why these messages weren't being delivered.


问:
Can I sniff UDP packets addressed another Linux machine using Python?
I have a Python process on one Linux machine server1 that receives and processes raw UDP packets. I want to have another Linux machine server2 capable of listening to the same UDP packets server1 is receiving.

Is there any Python solution capable of sniffing UDP packets addressed to the another (Linux) machine?

答:
If you want more than one machine to process the same data, you'd be better off going to mulitcast (if you can control the sender and the infrastructure)

Else, http://sourceforge.net/projects/pylibpcap/ will enable packet capture via python. You will still have to configure the infrastructure to get the packets to the machine you want to sniff them. Either by iptables (if is a Linux machine) or a mirror port on the switch etc.

Edit:

If you want the processes on different machines (you think one machine can't do it all) I would have a Linux machine receive the data, and using iptables, send it to multiple other machines. Maybe to a different socket on the same machine. This is possible because its UDP. If you want it all on the same machine, I would have a single process that spawns subprocesses with connected PIPEs, binds the UDP socket and copies the data to each subprocess' pipe; maybe after some input validation

ContentLicense: CC BY-SA 3.0


问:
How to sum variables in template vue?
now i'm working in VUE and i need to sum variables. In python (flask), i've been using such a code

```<code><!-- Creating vars (I have already created vars in data ())-->
    {% set transitions = namespace(amount=0) %}
    {% set downloads = namespace(amount=0) %}
    {% set registered = namespace(amount=0) %}
    {% set played = namespace(amount=0) %}

    {% for stat in stats %}
        <!-- So i need such a code in VUE -->
        {% set transitions.amount = transitions.amount + stat[1] | int %}
        {% set downloads.amount = downloads.amount + stat[2] | int %}
        {% set registered.amount = registered.amount + stat[3] | int %}
        {% set played.amount = played.amount + (stat[4] / 60) | round | int %}
    <tr>
        <td>{{ stat[5] }}</td>
        <td>{{ stat[1] }}</td>
        <td>{{ stat[2] }}</td>
        <td>{{ stat[3] }}</td>
        <td>{{ (stat[4] / 60)|round|int}}</td>
        <td>{{ stat[0] }}</td>
    </tr>
    {% endfor %}
</code>```

So i need to 'convert' it to vue like:

```<code>{{ var1 += stat[1] }}
</code>```

OK, i wrote such a dumy code:

```<code><tr v-for="promo in promoStats" :key="promo.ID">
                <td>{{ promo.date }}</td>
                <td>{{ sumTransfers(promo.transitions) }}</td>
                <td>{{ sumDownloads(promo.downloads) }}</td>
                <td>{{ sumRegisters(promo.registered) }}</td>
                <td>{{ sumHours(Math.round(promo.hoursPlayed / 60))}}</td>
              </tr>
</code>```

Script:

```<code>methods: {
    sumTransfers (val) {
      this.transitions += val
      console.log(this.transitions)
      return val
    },
    sumDownloads (val) {
      this.downloads += val
      return val
    },
    sumRegisters (val) {
      this.registered += val
      return val
    },
    sumHours (val) {
      this.played += val
      return val
    }
  }
</code>```

And i recieve an error:

You may have an infinite update loop in a component render function.

答:
A good way to do it is by calling a method:

```<code><template>
  <td>{{ sumStats(var1, stat[0]) }}</td> <!-- 12 + 1 -->
  <td>{{ sumStats(var1, stat[1]) }}</td> <!-- 12 + 2 -->
  <td>{{ sumStats(var1, stat[2]) }}</td> <!-- 12 + 3 -->
  <td>{{ sumStats(6, 5) }}</td> <!-- 6 + 5 -->
</template>
</code>```

In the script tag:

```<code><script>
export default {
  data: () => ({
    var1: 12,
    stat: [1,2,3,4,5]
  }),
  methods: {
    sumStats(num1, num2) {
      return num + num2;
    }
  }
}
</script>
</code>```

I'm guessing that you have something like:

```<code>promotions: [{
    date: 'somedate',
    transitions: 1,
    downloads: 2,
    registered: 3,
    played: 4,
  },{
    date: 'somedate2',
    transitions: 5,
    downloads: 6,
    registered: 7,
    played: 8,
  }
]
</code>```

If you want to show each object in one row :

```<code><tr v-for="promo in promotions">
    <td>{{ promo.date }}</td>
    <td>{{ promo.transitions }}</td>
    <td>{{ promo.downloads }}</td>
    <td>{{ promo.registered }}</td>
    <td>{{ promo.played }}</td>
</tr>
</code>```

Then you get:

```<code><tr>
    <td>somedate</td>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
</tr>
<tr>
    <td>somedate2</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
</tr>
</code>```

Now, if you want only one row with the sum of each variable, this is the way to do it:

```<code><template>
  <div>
    <!--  Show each promotion information in one row -->
    <tr v-for="promo in promotions">
      <td>{{ promo.date }}</td>
      <td>{{ promo.transitions }}</td>
      <td>{{ promo.downloads }}</td>
      <td>{{ promo.registered }}</td>
      <td>{{ promo.played }}</td>
    </tr>
    <tr>
      <!--  Show the sum of all the variables in one row -->
      <td>Empty date</td>
      <td>{{ totalpromotions.totalTransitions }}</td>
      <td>{{ totalPromotions.totalDownloads }}</td>
      <td>{{ totalPromotions.totalRegistered }}</td>
      <td>{{ totalPromotions.totalPlayed }}</td>
    </tr>
  </div>
</template>

<script>
  export default {
    data: () => ({
      promotions: [{
        date: 'somedate',
        transitions: 1,
        downloads: 2,
        registered: 3,
        played: 4,
      },{
        date: 'somedate2',
        transitions: 5,
        downloads: 6,
        registered: 7,
        played: 8,
      }]
    }),
    computed: {
      totalPromotions() {
        const accumulator = {
          totalDownloads: 0,
          totalPlayed: 0,
          totalRegistered: 0,
          totalTransitions: 0
        }
        // sum each promotion variable
        this.promotions.forEach(promotion => {
          accumulator.totalDownloads += promotion.downloads;
          accumulator.totalPlayed += promotion.played;
          accumulator.totalRegistered += promotion.registered;
          accumulator.totalTransitions += promotion.transitions
        });
        return accumulator;
      }
    }
  }
</script>
</code>```

Title: How to sum variables in template vue?

Body:
now i'm working in VUE and i need to sum variables. In python (flask), i've been using such a code

    {% set transitions = namespace(amount=0) %}
    {% set downloads = namespace(amount=0) %}
    {% set registered = namespace(amount=0) %}
    {% set played = namespace(amount=0) %}

    {% for stat in stats %}

        {% set transitions.amount = transitions.amount + stat[1] | int %}
        {% set downloads.amount = downloads.amount + stat[2] | int %}
        {% set registered.amount = registered.amount + stat[3] | int %}
        {% set played.amount = played.amount + (stat[4] / 60) | round | int %}

        {{ stat[5] }}
        {{ stat[1] }}
        {{ stat[2] }}
        {{ stat[3] }}
        {{ (stat[4] / 60)|round|int}}
        {{ stat[0] }}

    {% endfor %}

So i need to 'convert' it to vue like:

{{ var1 += stat[1] }}

OK, i wrote such a dumy code:

                {{ promo.date }}
                {{ sumTransfers(promo.transitions) }}
                {{ sumDownloads(promo.downloads) }}
                {{ sumRegisters(promo.registered) }}
                {{ sumHours(Math.round(promo.hoursPlayed / 60))}}

Script:

methods: {
    sumTransfers (val) {
      this.transitions += val
      console.log(this.transitions)
      return val
    },
    sumDownloads (val) {
      this.downloads += val
      return val
    },
    sumRegisters (val) {
      this.registered += val
      return val
    },
    sumHours (val) {
      this.played += val
      return val
    }
  }

And i recieve an error:

You may have an infinite update loop in a component render function.

Body:
A good way to do it is by calling a method:

<template>
  <td>{{ sumStats(var1, stat[0]) }}</td> <!-- 12 + 1 -->
  <td>{{ sumStats(var1, stat[1]) }}</td> <!-- 12 + 2 -->
  <td>{{ sumStats(var1, stat[2]) }}</td> <!-- 12 + 3 -->
  <td>{{ sumStats(6, 5) }}</td> <!-- 6 + 5 -->
</template>

In the script tag:

<script>
export default {
  data: () => ({
    var1: 12,
    stat: [1,2,3,4,5]
  }),
  methods: {
    sumStats(num1, num2) {
      return num + num2;
    }
  }
}
</script>

I'm guessing that you have something like:

promotions: [{
    date: 'somedate',
    transitions: 1,
    downloads: 2,
    registered: 3,
    played: 4,
  },{
    date: 'somedate2',
    transitions: 5,
    downloads: 6,
    registered: 7,
    played: 8,
  }
]

If you want to show each object in one row :

<tr v-for="promo in promotions">
    <td>{{ promo.date }}</td>
    <td>{{ promo.transitions }}</td>
    <td>{{ promo.downloads }}</td>
    <td>{{ promo.registered }}</td>
    <td>{{ promo.played }}</td>
</tr>

Then you get:

<tr>
    <td>somedate</td>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
</tr>
<tr>
    <td>somedate2</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
</tr>

Now, if you want only one row with the sum of each variable, this is the way to do it:

<template>
  <div>
    <!--  Show each promotion information in one row -->
    <tr v-for="promo in promotions">
      <td>{{ promo.date }}</td>
      <td>{{ promo.transitions }}</td>
      <td>{{ promo.downloads }}</td>
      <td>{{ promo.registered }}</td>
      <td>{{ promo.played }}</td>
    </tr>
    <tr>
      <!--  Show the sum of all the variables in one row -->
      <td>Empty date</td>
      <td>{{ totalpromotions.totalTransitions }}</td>
      <td>{{ totalPromotions.totalDownloads }}</td>
      <td>{{ totalPromotions.totalRegistered }}</td>
      <td>{{ totalPromotions.totalPlayed }}</td>
    </tr>
  </div>
</template>

<script>
  export default {
    data: () => ({
      promotions: [{
        date: 'somedate',
        transitions: 1,
        downloads: 2,
        registered: 3,
        played: 4,
      },{
        date: 'somedate2',
        transitions: 5,
        downloads: 6,
        registered: 7,
        played: 8,
      }]
    }),
    computed: {
      totalPromotions() {
        const accumulator = {
          totalDownloads: 0,
          totalPlayed: 0,
          totalRegistered: 0,
          totalTransitions: 0
        }
        // sum each promotion variable
        this.promotions.forEach(promotion => {
          accumulator.totalDownloads += promotion.downloads;
          accumulator.totalPlayed += promotion.played;
          accumulator.totalRegistered += promotion.registered;
          accumulator.totalTransitions += promotion.transitions
        });
        return accumulator;
      }
    }
  }
</script>


问:
using axios for post call in parallel
I’ve this axios request which is running ok I got http 200

```<code>import {AxiosResponse} from "axios";

const axios = require('axios').default;
const qs = require('qs');

//First query
axios({
    method: 'post',
    url: 'https://oauth2.-arch.mand.com/oauth2/token',
    data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'run:crud'}),
    headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
    }
}).then(function (response: AxiosResponse) {

    console.log(response.data);
}).catch(function (error: any) {
    console.log("Error: " + error);
});
</code>```

//Second query  (the only different is the scope )

```<code>axios({
    method: 'post',
    url: 'https://oauth2.-arch.mand.com/oauth2/token',
    data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': ‘exe:crud’}),
    headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
    }
}).then(function (response: AxiosResponse) {

    console.log(response.data);
}).catch(function (error: any) {
    console.log("Error: " + error);
});
</code>```

Now I want to run two request in parallel and get the results which is response.data (the data I sent to the request / headers etc)

I’ve tried with but the response I got is like the request , I don’t get the tokens/data? Any idea
How can I use this two request in parallel ?

```<code>axios.all([{
    method: 'post',
    url: 'https://oauth2.-arch.mand.com/oauth2/token',
    data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'run:crud'}),
        headers: {
            'Accept': 'application/json',
            'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    },

        {
            method: 'post',
            url: 'https://oauth2.-arch.mand.com/oauth2/token',
            data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'exe:crud'}),
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        }]).then(axios.spread((...responses: AxiosResponse[]) =>{

        const aToken = responses[0];
        const bToken = responses[1];
    }).catch(function (error: any) {
        console.log("Error: " + error);
    });
</code>```

If there is a better way , please let me know

Btw, if I run this two post request separated everything is working fine

答:
You need to provide promises to the axios.all not their config objects.

axios.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      const aToken = responses[0];
      const bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });
```

Keep in mind though that the axios.all and axios.spread are deprecated.

Use Promise.all directly

Title: using axios for post call in parallel

Body:
I’ve this axios request which is running ok I got http 200

import {AxiosResponse} from "axios";

const axios = require('axios').default;
const qs = require('qs');

//First query
axios({
    method: 'post',
    url: 'https://oauth2.-arch.mand.com/oauth2/token',
    data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'run:crud'}),
    headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
    }
}).then(function (response: AxiosResponse) {

    console.log(response.data);
}).catch(function (error: any) {
    console.log("Error: " + error);
});

//Second query  (the only different is the scope )

axios({
    method: 'post',
    url: 'https://oauth2.-arch.mand.com/oauth2/token',
    data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': ‘exe:crud’}),
    headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
    }
}).then(function (response: AxiosResponse) {

    console.log(response.data);
}).catch(function (error: any) {
    console.log("Error: " + error);
});

Now I want to run two request in parallel and get the results which is response.data (the data I sent to the request / headers etc)

I’ve tried with but the response I got is like the request , I don’t get the tokens/data? Any idea
How can I use this two request in parallel ?

axios.all([{
    method: 'post',
    url: 'https://oauth2.-arch.mand.com/oauth2/token',
    data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'run:crud'}),
        headers: {
            'Accept': 'application/json',
            'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    },

        {
            method: 'post',
            url: 'https://oauth2.-arch.mand.com/oauth2/token',
            data: qs.stringify({'grant_type': 'client_credentials'}, {'scope': 'exe:crud'}),
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        }]).then(axios.spread((...responses: AxiosResponse[]) =>{

        const aToken = responses[0];
        const bToken = responses[1];
    }).catch(function (error: any) {
        console.log("Error: " + error);
    });

If there is a better way , please let me know

Btw, if I run this two post request separated everything is working fine

Body:
You need to provide promises to the axios.all not their config objects.

axios.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      const aToken = responses[0];
      const bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

Keep in mind though that the axios.all and axios.spread are deprecated.

Use Promise.all directly


问:
Windows shortcuts without a path
'Regular' windows application shortcuts have a target which is a path to an executable file. This path is visible (and editable) in the shortcut's properties dialog.

But many shortcuts have no such path, only a (read only) application name is displayed. All the MS Office programs, for example, have such shortcuts.

How do these shortcuts work (I guess there's a progid involved), what are their advantages over 'regular' shortcuts and why would I want to use such shortcuts for my own applications?

Finally, can I create such a shortcut with an installer built by a Setup Project in Visual Studio 2008?

答: Read MSDN, everything is detailed about Links.</p>

OwnerDisplayName: Tor Haugen

ContentLicense: CC BY-SA 2.5

Title: Windows shortcuts without a path


问:
Optimize the code
I am new to python. I would like all the python gurus to suggest some ways to make the following code more pythonic and hence more efficient .
Its a simple code to find the edit distance between two words.

P.S. I would like improvements in code, not in the logic or algorithm optimization.

```<code>class test:
    def __init__(self,a,b,I=1,D=1,R=1):
        self.a = a
        self.b = b
        self.mem = dict()
        self.la = len(a)
        self.lb = len(b)
        self.I = I
        self.D = D
        self.R = R

    def diff(self,i=0,j=0):
        T = self.diff
        memo = self.mem
        if j == self.lb: return self.D * i
        if i == self.la: return self.D * j
        if (i,j) in memo:
            return memo[(i,j)]
        if self.a[i] == self.b[j]:
            memo[(i,j)] = T( i+1,j+1 )
            return memo[ (i,j) ]
        memo[(i,j)] = min(self.R + T(i+1,j+1) , self.D + T(i+1,j) , self.I + T(i,j+1) ,
         self.D + T(i,j+1) , self.I + T(i+1,j) )
        return memo[(i,j)]
</code>```

Variable explanation:

a,b are two string whose edit distance is to be found.
I,D,R Insertion Deletion and Replace cost of a single letter.
mem is dictionary used to memoize the recursive calls.
i and j are the pointers of the string a and b respectively

答: You might want to consider factoring the memoization layer out of your class, along the lines of this decorator.</p>

Title: Optimize the code

Body:
I am new to python. I would like all the python gurus to suggest some ways to make the following code more pythonic and hence more efficient .
Its a simple code to find the edit distance between two words.

P.S. I would like improvements in code, not in the logic or algorithm optimization.

class test:
    def __init__(self,a,b,I=1,D=1,R=1):
        self.a = a
        self.b = b
        self.mem = dict()
        self.la = len(a)
        self.lb = len(b)
        self.I = I
        self.D = D
        self.R = R

    def diff(self,i=0,j=0):
        T = self.diff
        memo = self.mem
        if j == self.lb: return self.D * i
        if i == self.la: return self.D * j
        if (i,j) in memo:
            return memo[(i,j)]
        if self.a[i] == self.b[j]:
            memo[(i,j)] = T( i+1,j+1 )
            return memo[ (i,j) ]
        memo[(i,j)] = min(self.R + T(i+1,j+1) , self.D + T(i+1,j) , self.I + T(i,j+1) ,
         self.D + T(i,j+1) , self.I + T(i+1,j) )
        return memo[(i,j)]

Variable explanation:

a,b are two string whose edit distance is to be found.
I,D,R Insertion Deletion and Replace cost of a single letter.
mem is dictionary used to memoize the recursive calls.
i and j are the pointers of the string a and b respectively


问:
Upload a Pdf file to another website using cURL
Specifically relating to this particular thread Upload a file to a website using php I want to implement this using cURL on PHP.

How do I set this up?

Below is what I have tried.

Note I just edited this by adding the codes I have tried.

```<code><?php

 if(isset($_POST["submit"])){

 $errors= array();//
 $name = $_FILES['fileToUpload']['name'];
 $size = $_FILES['fileToUpload']['size'];
 $type = $_FILES['fileToUpload']['type'];
 $tmp_name = $_FILES['fileToUpload']['tmp_name'];
 $upload_ok =1;
 $file_ext=strtolower(end(explode('.',$_FILES['fileToUpload']
 ['name'])));//

 $extensions= array("pdf","jpeg","jpg","png");

 $jj = file_get_contents($_FILES['fileToUpload']['tmp_name']);
 $mj = base64_encode($jj);

 if(in_array($file_ext,$extensions)=== false){
  $errors[]="vvvvv.";
 }

 if($size >= xxx){
  $errors[]='xxx;'
 }

 if(empty($errors)==true){

  echo  "Success </br>";

  $request  = "xxxxxxxxx";

  $headers = array(
    "Authorization: Bearer xxxxxx",
     "Content-type => multipart/form-data",

     "Accept:application/json",
  );

  $data = [

     'voucher_data' => 'base64_encode($tmp_name)',

   'callback_url' => 'xxxxxxxxx'
  ];

  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => "xxxxxxxxxx",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS =>  $data,
    CURLOPT_HTTPHEADER => $headers
  ));

  $response = curl_exec($curl);

  curl_close($curl);

  var_dump($response);

  }else{
  print_r($errors);
  }

?>
</code>```

I tried using curl_file_create($mj) as suggested below but on var_dump...it says bool(false)

答:
I see that you want to make a request that uploads a file to another server other than your own.

After PHP 5.5, there is a function named curl_file_create and as the name suggests, it's being used for uploading files.

```<code>$post = array (
    'extra_info' => '123456', // If required.. like user_id for avatar
    'file_contents' => curl_file_create ('path/to/file');
);

$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec ($ch);
curl_close ($ch);
</code>```

If you don't want to use that then there is a much simple way:

```<code>$args = [];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);

$args['file'] = '@/path/to/file';
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_close ($ch);
</code>```

Body:
Specifically relating to this particular thread Upload a file to a website using php I want to implement this using cURL on PHP.

How do I set this up?

Below is what I have tried.

Note I just edited this by adding the codes I have tried.

<?php

 if(isset($_POST["submit"])){

 $errors= array();//
 $name = $_FILES['fileToUpload']['name'];
 $size = $_FILES['fileToUpload']['size'];
 $type = $_FILES['fileToUpload']['type'];
 $tmp_name = $_FILES['fileToUpload']['tmp_name'];
 $upload_ok =1;
 $file_ext=strtolower(end(explode('.',$_FILES['fileToUpload']
 ['name'])));//

 $extensions= array("pdf","jpeg","jpg","png");

 $jj = file_get_contents($_FILES['fileToUpload']['tmp_name']);
 $mj = base64_encode($jj);

 if(in_array($file_ext,$extensions)=== false){
  $errors[]="vvvvv.";
 }

 if($size >= xxx){
  $errors[]='xxx;'
 }

 if(empty($errors)==true){

  echo  "Success
";

  $request  = "xxxxxxxxx";

  $headers = array(
    "Authorization: Bearer xxxxxx",
     "Content-type => multipart/form-data",

     "Accept:application/json",
  );

  $data = [

     'voucher_data' => 'base64_encode($tmp_name)',

   'callback_url' => 'xxxxxxxxx'
  ];

  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => "xxxxxxxxxx",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS =>  $data,
    CURLOPT_HTTPHEADER => $headers
  ));

  $response = curl_exec($curl);

  curl_close($curl);

  var_dump($response);

  }else{
  print_r($errors);
  }

?>

I tried using curl_file_create($mj) as suggested below but on var_dump...it says bool(false)

Body:
I see that you want to make a request that uploads a file to another server other than your own.

After PHP 5.5, there is a function named curl_file_create and as the name suggests, it's being used for uploading files.

$post = array (
    'extra_info' => '123456', // If required.. like user_id for avatar
    'file_contents' => curl_file_create ('path/to/file');
);

$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec ($ch);
curl_close ($ch);

If you don't want to use that then there is a much simple way:

$args = [];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);

$args['file'] = '@/path/to/file';
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_close ($ch);


问:
Using Firebase Phone number Auth with react-native
With the newly released Firebase Phone number Auth, I was wondering if it is possible to use it using the firebase JS SDK within react native. If so how?</p>

答:
For better user experience refer to this repo https://github.com/boudlal/react-native-firebase-phone-auth and i would suggest making some changes so that the user doesn't have to complete any challenges or click i am not a robot

In Captcha.html file change the size to invisible so that token is generated in the background

```<code>    var captcha = new firebase.auth.RecaptchaVerifier("captcha", {
          size: "normal",
          callback: function (token) {
            callback(token);
          },
          "expired-callback": function () {
            callback("");
          },
        });

</code>```

The Captcha.html  will be needed to be deployed to a server and is called via url in
react-native-webview

Style and remove unwanted text also make webview transparent by simply

style={{backgroundColor:'transparent'}}

Copy firebase config corresponding to your firebase project in the project and Captcha.html

Body:
For better user experience refer to this repo https://github.com/boudlal/react-native-firebase-phone-auth and i would suggest making some changes so that the user doesn't have to complete any challenges or click i am not a robot

In Captcha.html file change the size to invisible so that token is generated in the background

    var captcha = new firebase.auth.RecaptchaVerifier("captcha", {
          size: "normal",
          callback: function (token) {
            callback(token);
          },
          "expired-callback": function () {
            callback("");
          },
        });

The Captcha.html  will be needed to be deployed to a server and is called via url in
react-native-webview

Style and remove unwanted text also make webview transparent by simply

style={{backgroundColor:'transparent'}}

Copy firebase config corresponding to your firebase project in the project and Captcha.html


问:
.htacess Rewrite URL to Redirect certain request to subdmian
I want to redirect to the mobile version of the website when the request is made from Ios Browser  and Successfully able to do it with following rule

```<code>   RewriteCond %{HTTP_USER_AGENT} iPhone|iPod
   RewriteCond %{THE_REQUEST} !(reset) [NC]
   RewriteRule ^$ https://m.mydoamin1.com [L,R=302]
</code>```

But I don't want to hard code my domain name here since my website is accessible from 2 domains

For Example

mydomain1.com shud redirect to m.mydomain1.com

mydomain2.com shud redirect to m.mydomain2.com

I'm trying to archive this with a single rule-but this doesn't work

```<code> RewriteCond %{HTTP_USER_AGENT} iPhone|iPod
 RewriteCond %{THE_REQUEST} !(reset) [NC]
 RewriteRule ^$ https://m.{REQUEST_URI} [L,R=302]
</code>```

答:
This rule should work for you:

```<code>RewriteCond %{HTTP_USER_AGENT} iPhone|iPod [NC]
RewriteCond %{THE_REQUEST} !reset [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^/?$ https://m.%1 [L,R=301]
</code>```

Condition RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] will match mydomain1.com or www.mydomain1.com but will always grab mydomain1.com in capture group #1 which is used in RewriteRule as %1.

Body:
I want to redirect to the mobile version of the website when the request is made from Ios Browser  and Successfully able to do it with following rule

   RewriteCond %{HTTP_USER_AGENT} iPhone|iPod
   RewriteCond %{THE_REQUEST} !(reset) [NC]
   RewriteRule ^$ https://m.mydoamin1.com [L,R=302]

But I don't want to hard code my domain name here since my website is accessible from 2 domains

For Example

mydomain1.com shud redirect to m.mydomain1.com

mydomain2.com shud redirect to m.mydomain2.com

I'm trying to archive this with a single rule-but this doesn't work

 RewriteCond %{HTTP_USER_AGENT} iPhone|iPod
 RewriteCond %{THE_REQUEST} !(reset) [NC]
 RewriteRule ^$ https://m.{REQUEST_URI} [L,R=302]

Body:
This rule should work for you:

RewriteCond %{HTTP_USER_AGENT} iPhone|iPod [NC]
RewriteCond %{THE_REQUEST} !reset [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^/?$ https://m.%1 [L,R=301]

Condition RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] will match mydomain1.com or www.mydomain1.com but will always grab mydomain1.com in capture group #1 which is used in RewriteRule as %1.


问:
Firebase Authentication using custom fields
I have been using firebase authentication process using email and password. This is working perfectly fine. But i want to add the username while creating the account. But using this auth function i could send only two params like,

const promise = auth.createUserWithEmailAndPassword(name.value, email.value, password.value);

The workaround suggested to me is getting the username after creating the username. But i want the data to sent along with email while creating the account. Is there a way i could send the user name along with this create user request, so that i could get the username whenever i log in. Thanks in advance.

答:
You can only pass an email and a password to createUserWithEmailAndPassword(), so you can't set a name using this function.

If you want to set a name for the authenticated user, you need to use the updateProfile() method on the user object, like this:

user.updateProfile({
  displayName: "Jon Snow"
})
```

<p>Note that the property is called <code>displayName</code>, not <code>name</code>.</p>

<p>You can set the name right after creating the user. This example uses async/await:</p>

<pre class="lang-js prettyprint-override"><code>const { user } = await auth.createUserWithEmailAndPassword(
  email,
  password
)

await user.updateProfile({ displayName: name });
</code>```

Or, using promises:

auth.createUserWithEmailAndPassword(email, password)
  .then(({ user }) => user.updateProfile({ displayName: name }))
  .then(() => {
    console.log("User was updated!", auth.currentUser.displayName);
  });
```

If you need the user object somewhere else in your code, you can call firebase.auth().currentUser, or attach a listener to the authentication object.

You can only set a limited number of properties on Firebase users (like displayName, email and photoURL). Additional (custom) data must be stored somewhere else, e.g. in Firestore, together with the user's uid.

Body:
You can only pass an email and a password to createUserWithEmailAndPassword(), so you can't set a name using this function.

If you want to set a name for the authenticated user, you need to use the updateProfile() method on the user object, like this:

user.updateProfile({
  displayName: "Jon Snow"
})

Note that the property is called displayName, not name.

You can set the name right after creating the user. This example uses async/await:

const { user } = await auth.createUserWithEmailAndPassword(
  email,
  password
)

await user.updateProfile({ displayName: name });

Or, using promises:

auth.createUserWithEmailAndPassword(email, password)
  .then(({ user }) => user.updateProfile({ displayName: name }))
  .then(() => {
    console.log("User was updated!", auth.currentUser.displayName);
  });

If you need the user object somewhere else in your code, you can call firebase.auth().currentUser, or attach a listener to the authentication object.

You can only set a limited number of properties on Firebase users (like displayName, email and photoURL). Additional (custom) data must be stored somewhere else, e.g. in Firestore, together with the user's uid.


答:
The code looks like an anti-pattern. What I would do is have an abstract method called process in MyItem and have both subclasses implementing that method:

```<code>public class MyItem {

    private String barCode;
    private String price;

    public String getBarCode() {
        return barCode;
    }

    public void setBarCode(String barCode) {
        this.barCode = barCode;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public abstract void process();

}
</code>```

Now if you have a subclass you are forced to implement the process method, and then instead of checking what class it is you can just call the process method directly.

```<code>public void processItem(MyItem item){
    item.process();
}
</code>```

Title: How to make this method more generic

Body:
The code looks like an anti-pattern. What I would do is have an abstract method called process in MyItem and have both subclasses implementing that method:

public class MyItem {

    private String barCode;
    private String price;

    public String getBarCode() {
        return barCode;
    }

    public void setBarCode(String barCode) {
        this.barCode = barCode;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public abstract void process();

}

Now if you have a subclass you are forced to implement the process method, and then instead of checking what class it is you can just call the process method directly.

public void processItem(MyItem item){
    item.process();
}


问:
numpy range created using percentage increment
I would like to create a numpy range from start to stop using a (fixed) percentage increment based on the previous number eg start=100 increment=2% to get 100, 102, 104.04, 106.12 etc

Obviously this can be done by iterating over a list or, more elegantly, using a generator:

```<code>def pct_incrementer(start, stop, step_pct):
    val = start
    yield val
    while True:
        val += val * step_pct
        if val >= stop:
            break
        yield val

 np.array(list(pct_incrementer(100, 200, 0.02)))
 # or (as I've just learned!)
 np.fromiter(pct_incrementer(100, 200, 0.02), float)
</code>```

Does numpy (or pandas) have a function to do this natively??  (cos I can't find one!).  Is there, perhaps a way of manipulating np.array([100] * 10) to do the same thing?

Thanks!

答:
```<code>import numpy as np
start = 120
end = 255
display=[start]
 while True:
    xs1 = start * np.full(1,1.02).cumprod()
    if xs1.item(0)>=end:
        break
    else:
        display.append(xs1.item(0))
        start=xs1.item(0)
display = [ round(elem, 2) for elem in display ]
print(display)

#Result: [120, 122.4, 124.85, 127.34, 129.89, ... 254.68]
</code>```

this method is 20-40 times faster. Hope this helps :)

Body:
I would like to create a numpy range from start to stop using a (fixed) percentage increment based on the previous number eg start=100 increment=2% to get 100, 102, 104.04, 106.12 etc

Obviously this can be done by iterating over a list or, more elegantly, using a generator:

def pct_incrementer(start, stop, step_pct):
    val = start
    yield val
    while True:
        val += val * step_pct
        if val >= stop:
            break
        yield val

 np.array(list(pct_incrementer(100, 200, 0.02)))
 # or (as I've just learned!)
 np.fromiter(pct_incrementer(100, 200, 0.02), float)

Does numpy (or pandas) have a function to do this natively??  (cos I can't find one!).  Is there, perhaps a way of manipulating np.array([100] * 10) to do the same thing?

Thanks!

Body:
import numpy as np
start = 120
end = 255
display=[start]
 while True:
    xs1 = start * np.full(1,1.02).cumprod()
    if xs1.item(0)>=end:
        break
    else:
        display.append(xs1.item(0))
        start=xs1.item(0)
display = [ round(elem, 2) for elem in display ]
print(display)

#Result: [120, 122.4, 124.85, 127.34, 129.89, ... 254.68]

this method is 20-40 times faster. Hope this helps :)


问:
JPA

 are being ignored but the @PrePersist and @PreUpdate work fine
I ran into strange problem. I have the whole domain model defined in the orm.xml file. All my entities in my project are just simple POJOs (no jpa annotations at all). I want to save the last update and the insert timestamps of my entities and I've decided to use the "pre persist" and "pre update" like most of us. So I've defined a base entity class and let all my entities to extend it.

Strange is that the "pre persist" (and all others events) are being called only when I define them using annotations. When I define them in the orm.xml file instead - nothing happens, they are just ignored.

This works for me:

```<code>public abstract class BaseEntity {

  private Timestamp insertTimestamp;
  private Timestamp lastUpdateTimestamp;

  @PrePersist
  public void onPersist() {
  ...
  }

  @PreUpdate
  public void onUpdate() {
  ...
  }
}
</code>```

But after removing annotations and switching to the xml nothing works anymore:

```<code><mapped-superclass class="com.my.model.BaseEntity">
   <pre-persist method-name="onPersist"/>
   <pre-update method-name="onUpdate"/>
   <post-load method-name="postLoad"/>
</mapped-superclass>
</code>```

According to the JPA specification the above declarations in xml seem to be correct.

I have no idea where to dig for the problem.

I'm using EclipseLink 2.2.0 with H2 in the SE environment.

UPDATE:

Thanks for your answer. There are no errors in log/console to see. Events just seem being ignored.

As you thought is might be a bug because moving the methods and XML declarations from the superclass to the subclass solves the problem. It is not a desired solution for me as I want to have a global solution for all entities but moved me a bit forward.

I've sent the bug report to the EclipseLink guys :)

As you suggested I've tried with entity listener and it works for me. so I will stick to this solution. It even looks better then the solution with base entity class ;)

Thanks !

答:
Your XML looks correct.  Do any errors occur in the logs?

It could be a bug with MappedSuperClass and entity events.
Can you try setting the event on a subclass and see if it works?
If it does, then it is probably a bug, please log the bug in Eclipse Bugzilla.

Another workaround would be to use an entity listener.

Title: JPA <pre-persist> <pre-update> are being ignored but the @PrePersist and @PreUpdate work fine

Body:
I ran into strange problem. I have the whole domain model defined in the orm.xml file. All my entities in my project are just simple POJOs (no jpa annotations at all). I want to save the last update and the insert timestamps of my entities and I've decided to use the "pre persist" and "pre update" like most of us. So I've defined a base entity class and let all my entities to extend it.

Strange is that the "pre persist" (and all others events) are being called only when I define them using annotations. When I define them in the orm.xml file instead - nothing happens, they are just ignored.

This works for me:

public abstract class BaseEntity {

  private Timestamp insertTimestamp;
  private Timestamp lastUpdateTimestamp;

  @PrePersist
  public void onPersist() {
  ...
  }

  @PreUpdate
  public void onUpdate() {
  ...
  }
}

But after removing annotations and switching to the xml nothing works anymore:

<mapped-superclass class="com.my.model.BaseEntity">

   <post-load method-name="postLoad"/>
</mapped-superclass>

According to the JPA specification the above declarations in xml seem to be correct.

I have no idea where to dig for the problem.

I'm using EclipseLink 2.2.0 with H2 in the SE environment.

UPDATE:

Thanks for your answer. There are no errors in log/console to see. Events just seem being ignored.

As you thought is might be a bug because moving the methods and XML declarations from the superclass to the subclass solves the problem. It is not a desired solution for me as I want to have a global solution for all entities but moved me a bit forward.

I've sent the bug report to the EclipseLink guys :)

As you suggested I've tried with entity listener and it works for me. so I will stick to this solution. It even looks better then the solution with base entity class ;)

Thanks !


问:
How do you initialize variables inside function scope and avoid global scope?
I have in the global space a variable set as follows:

```<code>let hoverMessageLock = 0;
</code>```

This allows the function below to operate how I want. Its function is to add a message upon button hover and then delete said message and replace it with a new message upon another hover.

The issue I'm having is I would like to NOT use the global space for variables and instead put it inside the function itself. However the function itself is getting called over and over again per each hover event, so if I set hoverMessageLock = 0 in the function scope, it just keeps getting set to 0 over and over again. Therefor my switch statement doesn't work as intended as when its in the global scope.

I know in other programming languages that utilizes classes, you can set variables in the class scope and then alter them in the same way you would global scope inside your functions. Is there a way to do this as well here in Javascript?

```<code>let macroManager = {
    hoverMessage: function(message, style = "hovertext noTextSelect"){
        switch (hoverMessageLock){
            case 0:
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                hoverMessageLock = 1;
                break;
            case 1:
                uiManager.messageDirector.removeMessage();
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                break;
        }
    },
}
</code>```

答:
You could create a local scope using the IIFE expression:

var macroManager = getMacroManager();

function getMacroManager() {
    return (function () {
        var hoverMessageLock = 0;

        return {
            hoverMessage: function (message, style = "hovertext noTextSelect") {
                switch (hoverMessageLock) {
                    case 0:
                        uiManager.messageDirector.addMessage("" + message + "", 0, 0, style);
                        hoverMessageLock = 1;
                        break;
                    case 1:
                        uiManager.messageDirector.removeMessage();
                        uiManager.messageDirector.addMessage("" + message + "", 0, 0, style);
                        break;
                }
            },
        };
    })();
}
```

So each time you call getMacroManager() you will get a separate instance, thus, hoverMessageLock will work as a local variable, which is what you expect to happen.

Here's more info about IIFE:
https://developer.mozilla.org/en-US/docs/Glossary/IIFE.

Body:
I have in the global space a variable set as follows:

let hoverMessageLock = 0;

This allows the function below to operate how I want. Its function is to add a message upon button hover and then delete said message and replace it with a new message upon another hover.

The issue I'm having is I would like to NOT use the global space for variables and instead put it inside the function itself. However the function itself is getting called over and over again per each hover event, so if I set hoverMessageLock = 0 in the function scope, it just keeps getting set to 0 over and over again. Therefor my switch statement doesn't work as intended as when its in the global scope.

I know in other programming languages that utilizes classes, you can set variables in the class scope and then alter them in the same way you would global scope inside your functions. Is there a way to do this as well here in Javascript?

let macroManager = {
    hoverMessage: function(message, style = "hovertext noTextSelect"){
        switch (hoverMessageLock){
            case 0:
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                hoverMessageLock = 1;
                break;
            case 1:
                uiManager.messageDirector.removeMessage();
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                break;
        }
    },
}

Body:
You could create a local scope using the IIFE expression:

var macroManager = getMacroManager();

function getMacroManager() {
    return (function () {
        var hoverMessageLock = 0;

        return {
            hoverMessage: function (message, style = "hovertext noTextSelect") {
                switch (hoverMessageLock) {
                    case 0:
                        uiManager.messageDirector.addMessage("" + message + "", 0, 0, style);
                        hoverMessageLock = 1;
                        break;
                    case 1:
                        uiManager.messageDirector.removeMessage();
                        uiManager.messageDirector.addMessage("" + message + "", 0, 0, style);
                        break;
                }
            },
        };
    })();
}

So each time you call getMacroManager() you will get a separate instance, thus, hoverMessageLock will work as a local variable, which is what you expect to happen.

Here's more info about IIFE:
https://developer.mozilla.org/en-US/docs/Glossary/IIFE.


问:
How to use a hash table to find a cycle in a singly linked list?
I am aware this is a common question asked, but no answers I've found differ from my algorithm, yet leetcode states my algorithm doesn't work. How can I use a hash table to find if there is a cycle in a singly linked list in JS? I implemented the following algorithm:

```<code>var hasCycle = function(head) {
    let node = head;
    let table = {};

    while(node) {
        if(table[node.value]) {
            return true;
        }
        else {
            table[node.value] = true;
        }
        node = node.next;
    }

    return false;
};
</code>```

However on leetcode, my algorithm works until it hits the following test case:

```<code>Input: [1, 2], pos: -1
</code>```

Where [1, 2] is the linked list, and pos is the position of the node that the tail points to. Since it is -1, the tail points to null so there is no cycle.

Why does leetcode say my code returns true? In my while loop, the first iteration sets table[1] to true. In the second iteration, table[2] is set to true. Then we exit the while loop since node points to null now, so my code should return false. However, leetcode says my algorithm returns true. Where did I make a mistake?

I am aware of the tortoise and hare algorithm, but I am trying to understand the hash table method to find a cycle.

答:
Check this algorithm. It works fine for array</p>

```<code>var hasCycle = function(data) {
    let dataLength = data.length;
    let table = {};
    for(let i=0 ; i < dataLength; i++ ) {
      if(table[data[i]]) {
            return i;
        }
        table[data[i]] = true;
    }
    return -1;
};

console.log(hasCycle([1,2,1]));// 2
console.log(hasCycle([1,2])); // -1
</code>```

Body:
I am aware this is a common question asked, but no answers I've found differ from my algorithm, yet leetcode states my algorithm doesn't work. How can I use a hash table to find if there is a cycle in a singly linked list in JS? I implemented the following algorithm:

var hasCycle = function(head) {
    let node = head;
    let table = {};

    while(node) {
        if(table[node.value]) {
            return true;
        }
        else {
            table[node.value] = true;
        }
        node = node.next;
    }

    return false;
};

However on leetcode, my algorithm works until it hits the following test case:

Input: [1, 2], pos: -1

Where [1, 2] is the linked list, and pos is the position of the node that the tail points to. Since it is -1, the tail points to null so there is no cycle.

Why does leetcode say my code returns true? In my while loop, the first iteration sets table[1] to true. In the second iteration, table[2] is set to true. Then we exit the while loop since node points to null now, so my code should return false. However, leetcode says my algorithm returns true. Where did I make a mistake?

I am aware of the tortoise and hare algorithm, but I am trying to understand the hash table method to find a cycle.

Body:
Check this algorithm. It works fine for array

var hasCycle = function(data) {
    let dataLength = data.length;
    let table = {};
    for(let i=0 ; i < dataLength; i++ ) {
      if(table[data[i]]) {
            return i;
        }
        table[data[i]] = true;
    }
    return -1;
};

console.log(hasCycle([1,2,1]));// 2
console.log(hasCycle([1,2])); // -1


问:
Not allowed to load local resource: ionic 3 android
I am using ionic 3 android build apk and trying to laod image from file:///storage/emulated/0/data/io.ionic.vdeovalet/cache/image.jpeg

```

    takePicture(sourceType) {
        try {
    // Create options for the Camera Dialog
          var options = {
            quality: 100,
            destinationType: this.camera.DestinationType.FILE_URI,
            encodingType: this.camera.EncodingType.JPEG,
            sourceType: sourceType,
          };
          this.camera.getPicture(options).then((imagePath) => {
    // Special handling for Android library
            if (this.platform.is('android') && sourceType ===
              this.camera.PictureSourceType.PHOTOLIBRARY) {
              this.filePath.resolveNativePath(imagePath)
                .then(filePath => {
                  let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
                  let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1,
                    imagePath.lastIndexOf('?'));
                  this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
                  this.lastImage = filePath;
                });
            } else {
              var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
              var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
              this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
            }
          }, (err) => {
            this.presentToast('Error while selecting image.');
          });

        } catch (e) {
          console.error(e);
        }

      }

```

Error: Not allowed to load local resource

android 6.0.1

答:
When Ionic is used with Capacitor, we can get the correct path of an image or other resource on a native device by:

```<code>import { Capacitor } from '@capacitor/core';

Capacitor.convertFileSrc(filePath);
</code>```

https://ionicframework.com/docs/core-concepts/webview

Body:
I am using ionic 3 android build apk and trying to laod image from file:///storage/emulated/0/data/io.ionic.vdeovalet/cache/image.jpeg

    takePicture(sourceType) {
        try {
    // Create options for the Camera Dialog
          var options = {
            quality: 100,
            destinationType: this.camera.DestinationType.FILE_URI,
            encodingType: this.camera.EncodingType.JPEG,
            sourceType: sourceType,
          };
          this.camera.getPicture(options).then((imagePath) => {
    // Special handling for Android library
            if (this.platform.is('android') && sourceType ===
              this.camera.PictureSourceType.PHOTOLIBRARY) {
              this.filePath.resolveNativePath(imagePath)
                .then(filePath => {
                  let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
                  let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1,
                    imagePath.lastIndexOf('?'));
                  this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
                  this.lastImage = filePath;
                });
            } else {
              var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
              var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
              this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
            }
          }, (err) => {
            this.presentToast('Error while selecting image.');
          });

        } catch (e) {
          console.error(e);
        }

      }

Error: Not allowed to load local resource

android 6.0.1

Body:
When Ionic is used with Capacitor, we can get the correct path of an image or other resource on a native device by:

import { Capacitor } from '@capacitor/core';

Capacitor.convertFileSrc(filePath);

https://ionicframework.com/docs/core-concepts/webview


答:
You already have an object, and that works nicely, just as you describe in class-based languages. Classes are simply a way of creating objects, and objects are all you need here.

Just add the property to your object:

```<code>let macroManager = {
    hoverMessageLock: 0,
    hoverMessage: function(message, style = "hovertext noTextSelect"){
        switch (this.hoverMessageLock){
            case 0:
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                this.hoverMessageLock = 1;
                break;
            case 1:
                uiManager.messageDirector.removeMessage();
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                break;
        }
    },
}
</code>```

Note that, depending on how you use the hoverMessageLock method, it's possible its this context could be lost (eg if you use it as an event handler) - this is easily fixed by defining it as an arrow function instead: hoverMessage: (message, style = "hovertext noTextSelect") => { ... }.

I would also recommend, if 0 and 1 are the only intended values of the hoverMessageLock variable/property, using boolean false/true values instead.

Title: How do you initialize variables inside function scope and avoid global scope?

Body:
You already have an object, and that works nicely, just as you describe in class-based languages. Classes are simply a way of creating objects, and objects are all you need here.

Just add the property to your object:

let macroManager = {
    hoverMessageLock: 0,
    hoverMessage: function(message, style = "hovertext noTextSelect"){
        switch (this.hoverMessageLock){
            case 0:
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                this.hoverMessageLock = 1;
                break;
            case 1:
                uiManager.messageDirector.removeMessage();
                uiManager.messageDirector.addMessage(""+message+"", 0, 0, style);
                break;
        }
    },
}

Note that, depending on how you use the hoverMessageLock method, it's possible its this context could be lost (eg if you use it as an event handler) - this is easily fixed by defining it as an arrow function instead: hoverMessage: (message, style = "hovertext noTextSelect") => { ... }.

I would also recommend, if 0 and 1 are the only intended values of the hoverMessageLock variable/property, using boolean false/true values instead.


问:
Why AP_POWER_STATE_REQ is read only in Vehicle HAL
I see in type.hal , AP_POWER_STATE_REQ is read-only..
How can VMCU - Power Controller can change powerState of Android Automotive OS?
My assumtion is that there will be a native service- a client of VHAL where handle communication with VMCU and then request AP_POWER_STATE_REQ .. to enter shutdown, ON_FULL or DISP_OFF...
But how can i do that if AP_POWER_STATE_REQ is read-only.

答: Check Power management for understanding Automotive's power management and required properties to handle the power events.</p>


问:
apply function and top_n doesn't work well together
I have a simple dataframe df in R:

```<code>year, var1, var2, var3
1990, 23, 1, 133
1991, 25, 3, 120
1992, 28, 2, 110
...
</code>```

The data goes on for hundreds of rows.

I want to select top 10 values for var1, var2, var3 using apply() and top_n() in R, like this:

```<code>df %>%
 select(var1, var2, var3) %>%
 apply(2, top_n(10), na.rm = TRUE)
</code>```

But I get the error:
Error in UseMethod("tbl_vars"): no applicable method for "tbl_vars" applied to an object of class "c('double', 'numeric')"

I thought that apply could help me avoid using a for loop to get the top 10 values variable by variable but I wasn't able to do so.

It seems a simple problem, but I haven't found good answers online. Any thoughts?

答:
top_n expects a data.frame as input whereas when we do the looping with apply, MARGIN = 2, it is looping over each column i.e. a vector

```<code>library(purrr)
library(dplyr)
map_dfc(c('var1', 'var2', 'var3'), ~ df %>%
                                 select(.x) %>%
                                 top_n(10) %>%
                                  slice(seq_len(10)))
</code>```

Also, according to ?top_n, it is superseded by slice_max/slice_min

```<code>map(c('var1', 'var2', 'var3'), ~ df %>%
                                 select(.x) %>%
                                 slice_max(!! rlang::sym(.x), n = 10))
</code>```

Using a reproducible example with iris

```<code>map_dfc(names(iris)[1:4], ~
          iris %>%
              select(.x) %>%
              top_n(10) %>%
              slice(seq_len(10)))

map(names(iris)[1:4], ~
          iris %>%
              select(.x) %>%
              slice_max(!! rlang::sym(.x), n = 10))
</code>```

Or with summarise with across and sort

```<code>library(tidyr)
df %>%
     summarise(across(starts_with('var'), ~
       list(head(sort(., decreasing = TRUE), 10)))) %>%
     unnest(c(everything())
</code>```

Body:
I have a simple dataframe df in R:

year, var1, var2, var3
1990, 23, 1, 133
1991, 25, 3, 120
1992, 28, 2, 110
...

The data goes on for hundreds of rows.

I want to select top 10 values for var1, var2, var3 using apply() and top_n() in R, like this:

df %>%
 select(var1, var2, var3) %>%
 apply(2, top_n(10), na.rm = TRUE)

But I get the error:
Error in UseMethod("tbl_vars"): no applicable method for "tbl_vars" applied to an object of class "c('double', 'numeric')"

I thought that apply could help me avoid using a for loop to get the top 10 values variable by variable but I wasn't able to do so.

It seems a simple problem, but I haven't found good answers online. Any thoughts?

Body:
top_n expects a data.frame as input whereas when we do the looping with apply, MARGIN = 2, it is looping over each column i.e. a vector

library(purrr)
library(dplyr)
map_dfc(c('var1', 'var2', 'var3'), ~ df %>%
                                 select(.x) %>%
                                 top_n(10) %>%
                                  slice(seq_len(10)))

Also, according to ?top_n, it is superseded by slice_max/slice_min

map(c('var1', 'var2', 'var3'), ~ df %>%
                                 select(.x) %>%
                                 slice_max(!! rlang::sym(.x), n = 10))

Using a reproducible example with iris

map_dfc(names(iris)[1:4], ~
          iris %>%
              select(.x) %>%
              top_n(10) %>%
              slice(seq_len(10)))

map(names(iris)[1:4], ~
          iris %>%
              select(.x) %>%
              slice_max(!! rlang::sym(.x), n = 10))

Or with summarise with across and sort

library(tidyr)
df %>%
     summarise(across(starts_with('var'), ~
       list(head(sort(., decreasing = TRUE), 10)))) %>%
     unnest(c(everything())


问:
can't get location, 3D imaging or heading (direction) in ArcGIS
I'm a newbie to arcgis. I'm trying to show a particular location at a particular angle in 3D. The location is the corner of Water Street and Fifth Avenue in McKeesport, Pa. The angle is facing east. The tilt is 45. But this is what I'm getting: https://codepen.io/lschneiderman/pen/ZEQEWXG

My code is below:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>ArcGIS JavaScript Tutorials: Create a JavaScript starter app</title>
    <style>
      html, body, #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>
    <link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css">
      <script src="https://js.arcgis.com/4.15/"></script>
  </head>
  <body>
    <div id="viewDiv"></div>

    <script>
        require([
              "esri/Map",
              "esri/views/SceneView"
            ], function(Map, SceneView) {

            var map = new Map({
              basemap: "topo-vector",
              ground: "world-elevation"  // show elevation
            });

            var view = new SceneView({
              container: "viewDiv",
              map: map,
                heading: 90,
              camera: {
                position: {  // observation point
                  latitude: '40.350500',
                  longitude: '-79.868870',
                  z: 1000  // altitude in meters
                },
                tilt: 45  // perspective in degrees
              }
            });
          });
    </script>
  </body>
</html>
</code>```

答:
Make sure you set the heading (angle) of the viewing direction on the camera object. This will make the camera look east, positioned above the crossing

var view = new SceneView({
  container: "viewDiv",
  map: map,
  camera: {
    position: {
      // observation point
      latitude: "40.350500",
      longitude: "-79.868870",
      z: 700 // altitude in meters// altitude in meters
    },
    heading: 90,
    tilt: 45 // perspective in degrees
  }
});
```

<p>Here is a link to the modified CodePen: https://codepen.io/arnofiva/pen/688eee67141131712a12ccc3310a6ea4?editors=1010</p>

<p>If you want the camera to look at the crossing, you need to adopt the position by moving the camera east, e.g.:</p>

<pre class="lang-js prettyprint-override"><code>latitude: "40.350464",
longitude: "-79.874628",
</code>```

Here's another version of the CodePen that shows the crossing in the view field of the camera:
https://codepen.io/arnofiva/pen/a2da1acb4cba398721690bf4d0b2101a?editors=0010

Instead of setting these values manually, it might be easier to use SceneView.goTo() and pass the point you want it to focus on as an argument:

var view = new SceneView({
  container: "viewDiv",
  map: map
});

view.goTo({
  target: [-79.86887, 40.3505], // coordinates of crossing
  heading: 90,
  tilt: 45,
  zoom: 18 // instead of a z-value, we provide the zoom level
}, {
  duration: 0 // tell view not to animate camera movement
});
```

Here's the CodePen showing the use of goTo(): https://codepen.io/arnofiva/pen/e91dd1b257a002a0c4d007d3724e039f?editors=1010

Body:
I'm a newbie to arcgis. I'm trying to show a particular location at a particular angle in 3D. The location is the corner of Water Street and Fifth Avenue in McKeesport, Pa. The angle is facing east. The tilt is 45. But this is what I'm getting: https://codepen.io/lschneiderman/pen/ZEQEWXG

My code is below:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>ArcGIS JavaScript Tutorials: Create a JavaScript starter app</title>

    <link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css">

Body:
Make sure you set the heading (angle) of the viewing direction on the camera object. This will make the camera look east, positioned above the crossing

var view = new SceneView({
  container: "viewDiv",
  map: map,
  camera: {
    position: {
      // observation point
      latitude: "40.350500",
      longitude: "-79.868870",
      z: 700 // altitude in meters// altitude in meters
    },
    heading: 90,
    tilt: 45 // perspective in degrees
  }
});

Here is a link to the modified CodePen: https://codepen.io/arnofiva/pen/688eee67141131712a12ccc3310a6ea4?editors=1010

If you want the camera to look at the crossing, you need to adopt the position by moving the camera east, e.g.:

latitude: "40.350464",
longitude: "-79.874628",

Here's another version of the CodePen that shows the crossing in the view field of the camera:
https://codepen.io/arnofiva/pen/a2da1acb4cba398721690bf4d0b2101a?editors=0010

Instead of setting these values manually, it might be easier to use SceneView.goTo() and pass the point you want it to focus on as an argument:

var view = new SceneView({
  container: "viewDiv",
  map: map
});

view.goTo({
  target: [-79.86887, 40.3505], // coordinates of crossing
  heading: 90,
  tilt: 45,
  zoom: 18 // instead of a z-value, we provide the zoom level
}, {
  duration: 0 // tell view not to animate camera movement
});

Here's the CodePen showing the use of goTo(): https://codepen.io/arnofiva/pen/e91dd1b257a002a0c4d007d3724e039f?editors=1010


问:
How to detect that my application is running in vs2008 with debugger attached?
Previously I was doing a lot of WinFroms components and we had something InDesigner I'm wondering if there is something similar IsWithDebuggerAttached

Thanks

答: You could investigate System.Diagnostics.Debugger.IsAttached. This will tell you whether or not a debugger is attached to your application. Whether or not it's Visual Studio is another story.</p>


问:
Why is mySwiper is not defined but still works
I have swiperjs working except I am trying to access its methods to apply a slide centering hack. To do that I need to access its object but for some reason it tells me undefined even though the swiper works.

Swiper set is:

```<code>var mySwiper = new Swiper('#design', {
       slidesPerView: 3,
       spaceBetween: 30,
       loop: false,
       observer: true,
       observeParents: true,
       observeSlideChildren: true,
       preventClicksPropagation: false,
       centeredSlides: true,
       centeredSlidesBounds: true,
       centerInsufficientSlides: true,
       navigation: {
         nextEl: '.swiper-design #swiper-button-feature-next',
         prevEl: '.swiper-design #swiper-button-feature-prev',
       },
       breakpoints: {
        1024: {
          slidesPerView: 2,
          spaceBetween: 30,
        },
        768: {
          slidesPerView: 2,
          spaceBetween: 30,
        },
        640: {
          slidesPerView: 1,
          spaceBetween: 20,
        },
        320: {
          slidesPerView: 1,
          spaceBetween: 10,
        }
      },
      on: {
        init: function () {
          console.log('swiper initialized');
          console.log(mySwiper);
        },
      }
     });
</code>```

I am wanting to implement a hack along these lines, https://github.com/nolimits4web/swiper/issues/2081#issuecomment-296781831 so I can center swipers that have only one slide.

Any thoughts as to what is up here? Thank you.

答:
The init function within the swiper doesn't know that variable exists.

So change

```<code>init: function () {
</code>```

to

```<code>init: function (mySwiper) {
</code>```

Body:
I have swiperjs working except I am trying to access its methods to apply a slide centering hack. To do that I need to access its object but for some reason it tells me undefined even though the swiper works.

Swiper set is:

var mySwiper = new Swiper('#design', {
       slidesPerView: 3,
       spaceBetween: 30,
       loop: false,
       observer: true,
       observeParents: true,
       observeSlideChildren: true,
       preventClicksPropagation: false,
       centeredSlides: true,
       centeredSlidesBounds: true,
       centerInsufficientSlides: true,
       navigation: {
         nextEl: '.swiper-design #swiper-button-feature-next',
         prevEl: '.swiper-design #swiper-button-feature-prev',
       },
       breakpoints: {
        1024: {
          slidesPerView: 2,
          spaceBetween: 30,
        },
        768: {
          slidesPerView: 2,
          spaceBetween: 30,
        },
        640: {
          slidesPerView: 1,
          spaceBetween: 20,
        },
        320: {
          slidesPerView: 1,
          spaceBetween: 10,
        }
      },
      on: {
        init: function () {
          console.log('swiper initialized');
          console.log(mySwiper);
        },
      }
     });

I am wanting to implement a hack along these lines, https://github.com/nolimits4web/swiper/issues/2081#issuecomment-296781831 so I can center swipers that have only one slide.

Any thoughts as to what is up here? Thank you.

Body:
The init function within the swiper doesn't know that variable exists.

So change

init: function () {

to

init: function (mySwiper) {


问:
how to add datenow to the sql db2 date range?
I have the following code and I want to have date range from march 01 to datenow or current date but it was not working.

```<code>Select txnt_Date, item 1, item 2, item 3
from table A
where txnt_Date between '2020-03-01' and CURRENT DATE
</code>```

Can someone help me to fix or correct my script?

答:
You need to double quote mixed case names, or names with spaces in them. E.g. try</p>

```<code>Select "txnt_Date", "item 1", "item 2", "item 3"
from "table A"
where "txnt_Date" between '2020-03-01' and CURRENT DATE
</code>```

Body:
I have the following code and I want to have date range from march 01 to datenow or current date but it was not working.

Select txnt_Date, item 1, item 2, item 3
from table A
where txnt_Date between '2020-03-01' and CURRENT DATE

Can someone help me to fix or correct my script?

Body:
You need to double quote mixed case names, or names with spaces in them. E.g. try

Select "txnt_Date", "item 1", "item 2", "item 3"
from "table A"
where "txnt_Date" between '2020-03-01' and CURRENT DATE