问:
The mapper function returned a null value
I set same build types for debug and release,

```<code>buildTypes {
    debug {
        buildConfigField "String", "API_BASE_URL", "\"https://www.testUrl.com/api/\""
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.release_key
    }
    release {
        buildConfigField "String", "API_BASE_URL", "\"https://www.testUrl.com/api/\""
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.release_key
    }
}
</code>```

But If I build with the release, I got the below error.
Also, the server response is exactly same.

```<code>W/System.err: java.lang.NullPointerException: The mapper function returned a null value.
W/System.err:     at b.a.e.b.b.a(Unknown Source)
W/System.err:     at b.a.e.e.b.bs$a.onNext(Unknown Source)
W/System.err:     at b.a.e.e.b.cm$a.onNext(Unknown Source)
W/System.err:     at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(Unknown Source)
W/System.err:     at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(Unknown Source)
W/System.err:     at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(Unknown Source)
W/System.err:     at b.a.l.subscribe(Unknown Source)
W/System.err:     at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(Unknown Source)
W/System.err:     at b.a.l.subscribe(Unknown Source)
W/System.err:     at b.a.e.e.b.cm$a.a(Unknown Source)
W/System.err:     at b.a.e.e.b.cm.subscribeActual(Unknown Source)
W/System.err:     at b.a.l.subscribe(Unknown Source)
W/System.err:     at b.a.e.e.b.bs.subscribeActual(Unknown Source)
W/System.err:     at b.a.l.subscribe(Unknown Source)
W/System.err:     at b.a.e.e.b.bw.subscribeActual(Unknown Source)
W/System.err:     at b.a.l.subscribe(Unknown Source)
W/System.err:     at b.a.e.e.b.dd$b.run(Unknown Source)
W/System.err:     at b.a.s$a.run(Unknown Source)
W/System.err:     at b.a.e.g.j.run(Unknown Source)
W/System.err:     at b.a.e.g.j.call(Unknown Source)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
W/System.err:     at java.lang.Thread.run(Thread.java:761)
</code>```

答:
The problem comes from RxJava 2, which won't allow null values to be passed down the stream. In particularly your case, you have a mapper function, that returns a null value, which the exception clearly states.

You can reproduce that with following chunk of code:

```
<code>
    Observable.just(1)
              .map(integer -> null)
              .test()
              .assertError(throwable ->
                    "The mapper function returned a null value.".equals(throwable.getMessage()));
</code>
```

Body:
I set same build types for debug and release,

buildTypes {
    debug {
        buildConfigField "String", "API_BASE_URL", "\"https://www.testUrl.com/api/\""
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.release_key
    }
    release {
        buildConfigField "String", "API_BASE_URL", "\"https://www.testUrl.com/api/\""
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.release_key
    }
}

But If I build with the release, I got the below error.
Also, the server response is exactly same.

W/System.err: java.lang.NullPointerException: The mapper function returned a null value.
W/System.err:     at b.a.e.b.b.a(Unknown Source)
W/System.err:     at b.a.e.e.b.bs$a.onNext(Unknown Source)
W/System.err:     at b.a.e.e.b.cm$a.onNext(Unknown Source)
W/System.err:     at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(Unknown Source)
W/System.err:     at retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(Unknown Source)
W/System.err:     at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(Unknown Source)
W/System.err:     at b.a.l.subscribe(Unknown Source)
W/System.err:     at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(Unknown Source)
W/System.err:     at b.a.l.subscribe(Unknown Source)
W/System.err:     at b.a.e.e.b.cm$a.a(Unknown Source)
W/System.err:     at b.a.e.e.b.cm.subscribeActual(Unknown Source)
W/System.err:     at b.a.l.subscribe(Unknown Source)
W/System.err:     at b.a.e.e.b.bs.subscribeActual(Unknown Source)
W/System.err:     at b.a.l.subscribe(Unknown Source)
W/System.err:     at b.a.e.e.b.bw.subscribeActual(Unknown Source)
W/System.err:     at b.a.l.subscribe(Unknown Source)
W/System.err:     at b.a.e.e.b.dd$b.run(Unknown Source)
W/System.err:     at b.a.s$a.run(Unknown Source)
W/System.err:     at b.a.e.g.j.run(Unknown Source)
W/System.err:     at b.a.e.g.j.call(Unknown Source)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
W/System.err:     at java.lang.Thread.run(Thread.java:761)

Body:
The problem comes from RxJava 2, which won't allow null values to be passed down the stream. In particularly your case, you have a mapper function, that returns a null value, which the exception clearly states.

You can reproduce that with following chunk of code:

    Observable.just(1)
              .map(integer -> null)
              .test()
              .assertError(throwable ->
                    "The mapper function returned a null value.".equals(throwable.getMessage()));


来源: stackexchange

问:
parse array and pick information that is the same
Hey is an example of an array return from my soap response (i have no control over webservice)

```<code>[Names]
 [Name]
  [ID] => GH01
  [First] => Greg
  [Last] => Hobb
  [DateAvailable] =>12.04.2011
  [Contactable] => true

 [Name]

  [ID] => JM01
  [First] => James
  [Last] => Murr;
  [DatesAvailable] => 12.04.2011
  [Contactable] => true

 [Name]
  [ID] => GH01
  [First] => Greg
  [Last] => Hobb
  [DateAvailable] => 13.04.2011
  [Contactable] => true

 [Name]
  [ID] => JM01
  [First] => James
  [Last] => Murr;
  [DatesAvailable] => 13.04.2011
  [Contactable] => true
</code>```

I cannot suitable form a loop that will take each name and group together the available dates. feeling so stupid. seems simple but i cannot get my head around it. perhaps one of your formula gurus can put me in the correct direction.

the code to get the object is as follows:

$result->Names;

how i would like to display:

Name: Greg Hobb
Dates Avaiable: 12.04.2011 - 13.04.2011

hope that makes sense, i understasnd how to display them, just not grab them in the correct way.

答:
It seems that the way you are implementing your array/data is unnecessary and overcomplicated. You have two array elements that are the same, except the date, so that you can take the two DatesAvailable (a start date and end date) and put them together to make your actual DatesAvailble.
In your Name array, just put a startDate and endDate field. That way each element is a different individual holding all data you need.

Here's some real choppy code (whipped it up quickly) of how you could take this, and create a new array like the one I described above:

```<code>$newArray; $flag; $num;
for($i = 0; $i < count($Names); $i++)
{
    $flag = false;
    for($c = 0; $c < count($newArray); $c++)
    {
         if($names[$i][$ID] == $newArray[$c][$ID])
         {
              $newArray[$c][$endDate] = $Names[$i][$datesAvailable];
              $flag = true;
              break;
         }
     }
    if(!$flag)
    {
         //create a new element in $newArray. set ur ID, contact fields, etc.
         $newArray[count($newArray)][$startDate] = $names[$i][$datesAvailable];
     }
 }
</code>```

Hope this is of any help ><

ContentLicense: CC BY-SA 2.5

Body:
Hey is an example of an array return from my soap response (i have no control over webservice)

[Names]
 [Name]
  [ID] => GH01
  [First] => Greg
  [Last] => Hobb
  [DateAvailable] =>12.04.2011
  [Contactable] => true

 [Name]

  [ID] => JM01
  [First] => James
  [Last] => Murr;
  [DatesAvailable] => 12.04.2011
  [Contactable] => true

 [Name]
  [ID] => GH01
  [First] => Greg
  [Last] => Hobb
  [DateAvailable] => 13.04.2011
  [Contactable] => true

 [Name]
  [ID] => JM01
  [First] => James
  [Last] => Murr;
  [DatesAvailable] => 13.04.2011
  [Contactable] => true

I cannot suitable form a loop that will take each name and group together the available dates. feeling so stupid. seems simple but i cannot get my head around it. perhaps one of your formula gurus can put me in the correct direction.

the code to get the object is as follows:

$result->Names;

how i would like to display:

Name: Greg Hobb
Dates Avaiable: 12.04.2011 - 13.04.2011

hope that makes sense, i understasnd how to display them, just not grab them in the correct way.

Body:
It seems that the way you are implementing your array/data is unnecessary and overcomplicated. You have two array elements that are the same, except the date, so that you can take the two DatesAvailable (a start date and end date) and put them together to make your actual DatesAvailble.
In your Name array, just put a startDate and endDate field. That way each element is a different individual holding all data you need.

Here's some real choppy code (whipped it up quickly) of how you could take this, and create a new array like the one I described above:

$newArray; $flag; $num;
for($i = 0; $i < count($Names); $i++)
{
    $flag = false;
    for($c = 0; $c < count($newArray); $c++)
    {
         if($names[$i][$ID] == $newArray[$c][$ID])
         {
              $newArray[$c][$endDate] = $Names[$i][$datesAvailable];
              $flag = true;
              break;
         }
     }
    if(!$flag)
    {
         //create a new element in $newArray. set ur ID, contact fields, etc.
         $newArray[count($newArray)][$startDate] = $names[$i][$datesAvailable];
     }
 }

Hope this is of any help ><


问:
Trying to keep an anonymous variable alive in C++
This simple block of code is behaving in an unexpected way.

```<code>#include <iostream>
using namespace std;

class Node
{
 public:
    char* data;
    Node(char d)
    {
       data = &d;
    }
};

int main()
{
   Node NodeA = Node('c');
   cout<<*(NodeA.data)<<endl;
   return 0;
}
</code>```

I was expecting to get 'c' as the output, but instead it outputs '}'.
I had the feeling that it must be related to assigning the "data" pointer to an anonymous variable which is the 'c'.

I found this question discussing a similar issue.

But as it was mentioned in the top answer, the anonymous variable will only be killed if it was not bounded by a pointer referencing it by the end of the expression. Which is what I believe is not the case here as I am binding the pointer ("data") to it, but somehow it still gets killed.

I want to know what is going here that is causing the unexpected output.

答:
In your class:

```<code>Node(char d)
{
   data = &d;
}
</code>```

char d is a parameter to constructor Node. The problem is that d lives only in local scope on the program stack. It ceases to exist when the code returns from constructor.
data now has an address pointing somewhere in the program stack. If you try to read the data, you could read some other thing that was pushed on the stack later. If you write to this address you'll overwrite some other variables in your program. It could crash or just do something unexpected.

ContentLicense: CC BY-SA 3.0

Body:
This simple block of code is behaving in an unexpected way.

#include <iostream>
using namespace std;

class Node
{
 public:
    char* data;
    Node(char d)
    {
       data = &d;
    }
};

int main()
{
   Node NodeA = Node('c');
   cout<<*(NodeA.data)<<endl;
   return 0;
}

I was expecting to get 'c' as the output, but instead it outputs '}'.
I had the feeling that it must be related to assigning the "data" pointer to an anonymous variable which is the 'c'.

I found this question discussing a similar issue.

But as it was mentioned in the top answer, the anonymous variable will only be killed if it was not bounded by a pointer referencing it by the end of the expression. Which is what I believe is not the case here as I am binding the pointer ("data") to it, but somehow it still gets killed.

I want to know what is going here that is causing the unexpected output.

Body:
In your class:

Node(char d)
{
   data = &d;
}

char d is a parameter to constructor Node. The problem is that d lives only in local scope on the program stack. It ceases to exist when the code returns from constructor.
data now has an address pointing somewhere in the program stack. If you try to read the data, you could read some other thing that was pushed on the stack later. If you write to this address you'll overwrite some other variables in your program. It could crash or just do something unexpected.


问:
How to write the output of the dataframe into CSV file in pyspark
I am working on regression classification algorithm using pyspark. I would like to save model output into a CSV file. I have used

```<code>dataframe.savaAstextFile('hdfs://a/b/x')
</code>```

but it throws an error stating saveAstextFile attribute not in the list. Please see the below code and advise:

```<code>from __future__ import print_function
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
from pyspark.ml import Pipeline, PipelineModel
from pyspark.ml.classification import RandomForestClassifier as RF
from pyspark.ml.classification import DecisionTreeClassifier
from pyspark.ml.clustering import KMeans
from pyspark.ml.feature import StringIndexer, VectorIndexer, VectorAssembler, SQLTransformer
from pyspark.ml.evaluation import MulticlassClassificationEvaluator, BinaryClassificationEvaluator
from pyspark.mllib.evaluation import BinaryClassificationMetrics as metric
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder
import pandas
import numpy as np
#from matplotlib import pyplot as plt
from pyspark.ml.feature import OneHotEncoder
from pyspark.sql.functions import udf
from pyspark.sql.types import StructType

from sklearn.metrics import roc_curve, auc, accuracy_score, adjusted_rand_score, roc_auc_score

sc = SparkContext()
sqlContext = SQLContext(sc)

inData = sc.textFile("hdfs://ML_test_data/train2.csv")
header = inData.first()

fields = [StructField(field_name, StringType(), True) for field_name in header.split(',')]

fields[0].dataType = IntegerType()
fields[4].dataType = IntegerType()
fields[7].dataType = IntegerType()
fields[8].dataType = IntegerType()
#fields[9].dataType = IntegerType()
#fields[10].dataType = StructType()
fields[11].dataType = IntegerType()

schema = StructType(fields)

actualData = inData.filter(lambda x: x != header)

data_temp = actualData.map(lambda x:x.split(',')).map(lambda p:(int(p[0]),p[1], p[2], p[3], int(p[4]),
                                                             p[5], p[6], int(p[7]), int(p[8]), p[9], p[10], int(p[11])))

df = sqlContext.createDataFrame(data_temp, schema)
print (df.dtypes)
'''
df.createOrReplaceTempView("testTab")
result_df = sqlContext.sql("select Product_Category_2 from testTab ")
print (result_df.show)

result_collect = result_df.collect()
for i in result_collect:
    avg_prod_cat2 = i
    print ("avg_prod_cat2",avg_prod_cat2 )

'''

def prodCat2(originalCol):

     if originalCol == '':
         return '2'
     else:

         return originalCol

udfValProdCt2 = udf(prodCat2, StringType())
df = df.withColumn("prod_cat2", udfValProdCt2("Product_Category_2"))
df = df.withColumn("prod_cat3", udfValProdCt2("Product_Category_3") )
print (df.dtypes)
df = df.drop("Product_Category_2")
df = df.drop("Product_Category_3")
print (df.dtypes)
print (df.show)
#p_df = df.toPandas()
#print (p_df.head(15))

column_vec_in = ['User_ID', 'Product_ID', 'Gender', 'Age', 'Occupation', 'City_Category', 'Stay_In_Current_City_Years', 'Marital_Status',
              'Product_Category_1', 'Purchase', 'prod_cat2', 'prod_cat3']
column_vec_out = ['User_ID_catVec', 'Product_ID_catVec', 'Gender_catVec', 'Age_catVec', 'Occupation_catVec', 'City_Category_catVec',
                  'Stay_In_Current_City_Years_catVec', 'Marital_Status_catVec', 'Product_Category_1_catVec',
                  'Purchase_catVec', 'prod_cat2_catVec', 'prod_cat3_catVec']

indexers = [StringIndexer(inputCol=x, outputCol=x +'_tmp') for x in column_vec_in]

encoders = [OneHotEncoder(dropLast=False, inputCol=x+'_tmp', outputCol=y) for x,y in zip(column_vec_in, column_vec_out)]

tmp = [[i,j] for i, j in zip(indexers, encoders)]
tmp = [i for sublist in tmp for i in sublist]

cols_now = ['Product_ID_catVec', 'Gender_catVec', 'Age_catVec', 'Occupation_catVec', 'City_Category_catVec',
            'Stay_In_Current_City_Years_catVec', 'Product_Category_1', 'Purchase', 'prod_cat2_catVec', 'prod_cat3_catVec']
assembler_features = VectorAssembler(inputCols=cols_now, outputCol='features')
labelIndexer = StringIndexer(inputCol='Purchase', outputCol="label")
tmp += [assembler_features, labelIndexer]

pipeline = Pipeline(stages=tmp)

pipelineModel = pipeline.fit(df)

allData = pipelineModel.transform(df)

allData.cache()
trainingData, testData  = allData.randomSplit([0.7,0.3], seed=4)
print (trainingData.count())
print(testData.count())

rf = RF(labelCol='label', featuresCol='features', numTrees=20)

rfModel= rf.fit(trainingData)
#print("Coefficients : \n" + str(rfModel.coefficientMatrix))
predictions = rfModel.transform(testData)

predictions.printSchema()

result = predictions.select('User_ID', 'Product_ID', 'Gender', 'Age', 'Occupation', 'City_Category', 'Stay_In_Current_City_Years', 'Marital_Status',
              'Product_Category_1', 'Purchase', 'prod_cat2', 'prod_cat3', 'label', 'probability', 'prediction').collect()

result.saveAsTextFile()

for row in result:
    print("User_ID= %s, Product_id= %s -> prob= %s, prediction= %s"  %(row.User_ID, row.Product_ID, row.probability, row.prediction))
</code>```

Appreciate your quick help.
Thanks.

答:
Maybe you have already found the perfect solution, however let me write a short code to write and read pyspark Dataframes

this is a short code to create dataframe

```<code>x = [1,2,3,4]
y = [0,1,0,1]
df = sc.parallelize([x,y]).toDF(['A', 'B','C','D'])
</code>```

Spark 2.2.X

write dataframe to csv

```<code>df.write.csv('/tmp/out')
</code>```

read csv to dataframe

```<code>newdf = spark.read.csv("/tmp/out")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on regression classification algorithm using pyspark. I would like to save model output into a CSV file. I have used

dataframe.savaAstextFile('hdfs://a/b/x')

but it throws an error stating saveAstextFile attribute not in the list. Please see the below code and advise:

from __future__ import print_function
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
from pyspark.ml import Pipeline, PipelineModel
from pyspark.ml.classification import RandomForestClassifier as RF
from pyspark.ml.classification import DecisionTreeClassifier
from pyspark.ml.clustering import KMeans
from pyspark.ml.feature import StringIndexer, VectorIndexer, VectorAssembler, SQLTransformer
from pyspark.ml.evaluation import MulticlassClassificationEvaluator, BinaryClassificationEvaluator
from pyspark.mllib.evaluation import BinaryClassificationMetrics as metric
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder
import pandas
import numpy as np
#from matplotlib import pyplot as plt
from pyspark.ml.feature import OneHotEncoder
from pyspark.sql.functions import udf
from pyspark.sql.types import StructType

from sklearn.metrics import roc_curve, auc, accuracy_score, adjusted_rand_score, roc_auc_score

sc = SparkContext()
sqlContext = SQLContext(sc)

inData = sc.textFile("hdfs://ML_test_data/train2.csv")
header = inData.first()

fields = [StructField(field_name, StringType(), True) for field_name in header.split(',')]

fields[0].dataType = IntegerType()
fields[4].dataType = IntegerType()
fields[7].dataType = IntegerType()
fields[8].dataType = IntegerType()
#fields[9].dataType = IntegerType()
#fields[10].dataType = StructType()
fields[11].dataType = IntegerType()

schema = StructType(fields)

actualData = inData.filter(lambda x: x != header)

data_temp = actualData.map(lambda x:x.split(',')).map(lambda p:(int(p[0]),p[1], p[2], p[3], int(p[4]),
                                                             p[5], p[6], int(p[7]), int(p[8]), p[9], p[10], int(p[11])))

df = sqlContext.createDataFrame(data_temp, schema)
print (df.dtypes)
'''
df.createOrReplaceTempView("testTab")
result_df = sqlContext.sql("select Product_Category_2 from testTab ")
print (result_df.show)

result_collect = result_df.collect()
for i in result_collect:
    avg_prod_cat2 = i
    print ("avg_prod_cat2",avg_prod_cat2 )

'''

def prodCat2(originalCol):

     if originalCol == '':
         return '2'
     else:

         return originalCol

udfValProdCt2 = udf(prodCat2, StringType())
df = df.withColumn("prod_cat2", udfValProdCt2("Product_Category_2"))
df = df.withColumn("prod_cat3", udfValProdCt2("Product_Category_3") )
print (df.dtypes)
df = df.drop("Product_Category_2")
df = df.drop("Product_Category_3")
print (df.dtypes)
print (df.show)
#p_df = df.toPandas()
#print (p_df.head(15))

column_vec_in = ['User_ID', 'Product_ID', 'Gender', 'Age', 'Occupation', 'City_Category', 'Stay_In_Current_City_Years', 'Marital_Status',
              'Product_Category_1', 'Purchase', 'prod_cat2', 'prod_cat3']
column_vec_out = ['User_ID_catVec', 'Product_ID_catVec', 'Gender_catVec', 'Age_catVec', 'Occupation_catVec', 'City_Category_catVec',
                  'Stay_In_Current_City_Years_catVec', 'Marital_Status_catVec', 'Product_Category_1_catVec',
                  'Purchase_catVec', 'prod_cat2_catVec', 'prod_cat3_catVec']

indexers = [StringIndexer(inputCol=x, outputCol=x +'_tmp') for x in column_vec_in]

encoders = [OneHotEncoder(dropLast=False, inputCol=x+'_tmp', outputCol=y) for x,y in zip(column_vec_in, column_vec_out)]

tmp = [[i,j] for i, j in zip(indexers, encoders)]
tmp = [i for sublist in tmp for i in sublist]

cols_now = ['Product_ID_catVec', 'Gender_catVec', 'Age_catVec', 'Occupation_catVec', 'City_Category_catVec',
            'Stay_In_Current_City_Years_catVec', 'Product_Category_1', 'Purchase', 'prod_cat2_catVec', 'prod_cat3_catVec']
assembler_features = VectorAssembler(inputCols=cols_now, outputCol='features')
labelIndexer = StringIndexer(inputCol='Purchase', outputCol="label")
tmp += [assembler_features, labelIndexer]

pipeline = Pipeline(stages=tmp)

pipelineModel = pipeline.fit(df)

allData = pipelineModel.transform(df)

allData.cache()
trainingData, testData  = allData.randomSplit([0.7,0.3], seed=4)
print (trainingData.count())
print(testData.count())

rf = RF(labelCol='label', featuresCol='features', numTrees=20)

rfModel= rf.fit(trainingData)
#print("Coefficients : \n" + str(rfModel.coefficientMatrix))
predictions = rfModel.transform(testData)

predictions.printSchema()

result = predictions.select('User_ID', 'Product_ID', 'Gender', 'Age', 'Occupation', 'City_Category', 'Stay_In_Current_City_Years', 'Marital_Status',
              'Product_Category_1', 'Purchase', 'prod_cat2', 'prod_cat3', 'label', 'probability', 'prediction').collect()

result.saveAsTextFile()

for row in result:
    print("User_ID= %s, Product_id= %s -> prob= %s, prediction= %s"  %(row.User_ID, row.Product_ID, row.probability, row.prediction))

Appreciate your quick help.
Thanks.

Body:
Maybe you have already found the perfect solution, however let me write a short code to write and read pyspark Dataframes

this is a short code to create dataframe

x = [1,2,3,4]
y = [0,1,0,1]
df = sc.parallelize([x,y]).toDF(['A', 'B','C','D'])

Spark 2.2.X

write dataframe to csv

df.write.csv('/tmp/out')

read csv to dataframe

newdf = spark.read.csv("/tmp/out")


问:
Java and Javascript - Lastmodified on Linux
I  wrote a script on the Jmeter Web Driver in javascript and Java .

On a Windows system , the script is running perfectly . But on a Linux System , i have a weird problem . The lastmodifed then i obtain is not good. front_end.jtl has been modified yesterday , but the script say today at 10:00 in milliseconds timestamp .

Please help me.

```<code>    // Importing packages (and all classes in package) from Java into Javascript var pkg = JavaImporter(org.openqa.selenium)
    var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
    // We don't use wait in this very simple test, but here is way to access for more realistic testing
    var wait=new support_ui.WebDriverWait(WDS.browser, 5)

    // Start recording the time for this request

    WDS.sampleResult.sampleStart();

    // Let's get a page

    var baseUrl = "cnyw${FE}.mycore.core-cloud.net"

    WDS.browser.get("https://"+ baseUrl)

    var frontjtl = new java.io.File('/home/mycore/front_end.jtl')
    var frontlog = new java.io.File('/home/mycore/jmeter_front_end.log')

    var lastmodifjtl = frontjtl.lastModified()
    var lastmodiflog = frontlog.lastModified()

    if ( lastmodifjtl = lastmodiflog ) {
     var screenshot = WDS.browser.getScreenshotAs(pkg.OutputType.FILE)
     screenshot.renameTo(new java.io.File('/home/mycore/screenshots/tools/screenshot_cnyw${FE}.png'))
   }

    // Record the time of the request
    WDS.sampleResult.sampleEnd();
</code>```

答:
I would recommend using Files.getLastModifiedTime() instead, something like:

```<code>var lastmodifjtl = java.nio.file.Files.getLastModifiedTime(java.nio.file.Paths.get(frontjtl.toURI()))
</code>```

should do the trick for you.

Just in case see The WebDriver Sampler: Your Top 10 Questions Answered article for more information

Body:
I  wrote a script on the Jmeter Web Driver in javascript and Java .

On a Windows system , the script is running perfectly . But on a Linux System , i have a weird problem . The lastmodifed then i obtain is not good. front_end.jtl has been modified yesterday , but the script say today at 10:00 in milliseconds timestamp .

Please help me.

    // Importing packages (and all classes in package) from Java into Javascript var pkg = JavaImporter(org.openqa.selenium)
    var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
    // We don't use wait in this very simple test, but here is way to access for more realistic testing
    var wait=new support_ui.WebDriverWait(WDS.browser, 5)

    // Start recording the time for this request

    WDS.sampleResult.sampleStart();

    // Let's get a page

    var baseUrl = "cnyw${FE}.mycore.core-cloud.net"

    WDS.browser.get("https://"+ baseUrl)

    var frontjtl = new java.io.File('/home/mycore/front_end.jtl')
    var frontlog = new java.io.File('/home/mycore/jmeter_front_end.log')

    var lastmodifjtl = frontjtl.lastModified()
    var lastmodiflog = frontlog.lastModified()

    if ( lastmodifjtl = lastmodiflog ) {
     var screenshot = WDS.browser.getScreenshotAs(pkg.OutputType.FILE)
     screenshot.renameTo(new java.io.File('/home/mycore/screenshots/tools/screenshot_cnyw${FE}.png'))
   }

    // Record the time of the request
    WDS.sampleResult.sampleEnd();

Body:
I would recommend using Files.getLastModifiedTime() instead, something like:

var lastmodifjtl = java.nio.file.Files.getLastModifiedTime(java.nio.file.Paths.get(frontjtl.toURI()))

should do the trick for you.

Just in case see The WebDriver Sampler: Your Top 10 Questions Answered article for more information


问:
JHipster keycloak docker configuration for production
My JHipster(v4.11.1) project is using Monolithic architecture with OAuth 2.0 authentication type. I did face couple of issue for hosting it in a production server. Currently here are not fixed yet ones:

After I do click 'Sign in' link I get redirect into following url:

https://my-domain-name/auth/realms/jhipster/protocol/openid-connect/auth?client_id=web_app&redirect_uri=http://my-docker-service-name/login&response_type=code&scope=openid%20profile%20email&state=hO2NCQ

First issue is, here I need my-docker-service-name to be my-domain-name (and using https).

Note: Here I do see keycloak login page with following error message: Invalid parameter: redirect_uri

If I do change redirect_uri into my domain name manually, then I see keycloak login page without error. Next issue is after I do enter username/password, I get redirect into following url:

http://keycloak/auth/realms/jhipster/login-actions/authenticate?code=3MADiKg19-SL1L_lOmMEJv4w3kmGlF--0hyIDInKPm8&execution=07cacbc6-5b72-407e-9a0c-9a1b6447a7ff&client_id=web_app

And as you can see my second issue is keycloak need to be my-domain-name (and using https).

Note: Here if change the url manually into my-domain-name, then I see login page with invalid username/password error message.

Moreover I do have same problem for accessing keycloak administration console(it get redirect into http://keycloak) and I can't see the login page(Invalid parameter: redirect_uri).

I can provide more information regards to my production configurations if needed? for instance I do use Nginx as reverse proxy and also for handling https requests. My Nginx instance is a docker container and using default docker network for finding it's upstreams (keycloak(for /auth path) and my-app(for / path).

Even I did face above issues, so far I am very happy with the result and I would like to Thank you JHipster team, Keycloak team and Matt Raible! :-) for making it possible for us to use this great frameworks together! Cheers!

答:
First of all this section(8.3. Setting Up a Load Balancer or Proxy) of Keycloak documentation was absolutely helpful. I was able to make things somehow working but I still feel things can get done better and in more secure way!

I am not going to repeat needed configuration for Keycloak side, but I rather provide some hints for you in case you are using Nginx as reverse proxy.

Here is my nginx.conf which includes required configs:

```</p>

```upstream rock-app {
    server rock-app:8080;
}
upstream keycloak {
    server keycloak:9080;
}

server {
    listen 80;
    listen 443 ssl http2;
    ...
    add_header Strict-Transport-Security "max-age=86400; includeSubdomains; preload" always;
    ...
}

location / {
    proxy_set_header HOST $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://rock-app;
}

location /auth {
    proxy_set_header HOST $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://keycloak;
}
```

<p>```

Note: add_header Strict-Transport-Security ... part is important and ensure us users will stay in https protocol when they enter the site with a https url. please correct me if I am wrong!?

Now If I visit following url:

https://my-example.com/auth/realms/jhipster/.well-known/openid-configuration

I will see this response:

```<code>{
    "issuer": "http://my-example.com/auth/realms/jhipster",
    "authorization_endpoint": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/auth",
    "token_endpoint": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/token",
    "token_introspection_endpoint": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/token/introspect",
    "userinfo_endpoint": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/userinfo",
    "end_session_endpoint": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/logout",
    "jwks_uri": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/certs",
    "check_session_iframe": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/login-status-iframe.html",
    "grant_types_supported": ["authorization_code", "implicit", "refresh_token", "password", "client_credentials"],
    "response_types_supported": ["code", "none", "id_token", "token", "id_token token", "code id_token", "code token", "code id_token token"],
    "subject_types_supported": ["public", "pairwise"],
    "id_token_signing_alg_values_supported": ["RS256"],
    "userinfo_signing_alg_values_supported": ["RS256"],
    "request_object_signing_alg_values_supported": ["none", "RS256"],
    "response_modes_supported": ["query", "fragment", "form_post"],
    "registration_endpoint": "http://my-example.com/auth/realms/jhipster/clients-registrations/openid-connect",
    "token_endpoint_auth_methods_supported": ["private_key_jwt", "client_secret_basic", "client_secret_post"],
    "token_endpoint_auth_signing_alg_values_supported": ["RS256"],
    "claims_supported": ["sub", "iss", "auth_time", "name", "given_name", "family_name", "preferred_username", "email"],
    "claim_types_supported": ["normal"],
    "claims_parameter_supported": false,
    "scopes_supported": ["openid", "offline_access"],
    "request_parameter_supported": true,
    "request_uri_parameter_supported": true
}
</code>```

As you may notice http://my-example.com/... is shown instead of https://my-example.com/...

Therefore I had to change following config of my realm(jhipster-realm.json) from
"sslRequired" : "external",
to
"sslRequired" : "none", which I don't know if is a bad thing? considering (1) my browser never leaves https when I do test login workflow and (2) my keycloak instance is not accessible through any public port.

Well I am not going to accept my own answer as accepted answer, because as I said earlier I feel things can get done better and in more secure way. Thanks!

Update

I've done following changes for using https protocol:

Dockerfile

```<code>FROM jboss/keycloak:3.4.1.Final
</code>```

standalone.xml

```<code><server name="default-server">
    ...
    <http-listener name="default" socket-binding="http" redirect-socket="proxy-https" proxy-address-forwarding="${env.PROXY_ADDRESS_FORWARDING}" certificate-forwarding="true" enable-http2="true"/>
    <https-listener name="https" socket-binding="https" security-realm="ApplicationRealm" proxy-address-forwarding="${env.PROXY_ADDRESS_FORWARDING}" certificate-forwarding="true" enable-http2="true"/>
...

<socket-binding-group ...
    <socket-binding name="proxy-https" port="443"/>
...
</code>```

nginx.conf

```<code>upstream keycloak {
    server keycloak:9443;
}
...
server {
    listen 80;
    return 301 https://$host$request_uri;
}
server {
    listen 443 ssl http2;
    ...
    location /auth {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass https://keycloak;
    }
...
</code>```

jhipster-realm.json

```<code>...
"sslRequired": "external",
</code>```

HTH, Thanks!

Body:
First of all this section(8.3. Setting Up a Load Balancer or Proxy) of Keycloak documentation was absolutely helpful. I was able to make things somehow working but I still feel things can get done better and in more secure way!

I am not going to repeat needed configuration for Keycloak side, but I rather provide some hints for you in case you are using Nginx as reverse proxy.

Here is my nginx.conf which includes required configs:

```</p>

<pre><code>upstream rock-app {
    server rock-app:8080;
}
upstream keycloak {
    server keycloak:9080;
}

server {
    listen 80;
    listen 443 ssl http2;
    ...
    add_header Strict-Transport-Security "max-age=86400; includeSubdomains; preload" always;
    ...
}

location / {
    proxy_set_header HOST $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://rock-app;
}

location /auth {
    proxy_set_header HOST $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://keycloak;
}
</code></pre>

<p>```

Note: add_header Strict-Transport-Security ... part is important and ensure us users will stay in https protocol when they enter the site with a https url. please correct me if I am wrong!?

Now If I visit following url:

https://my-example.com/auth/realms/jhipster/.well-known/openid-configuration

I will see this response:

{
    "issuer": "http://my-example.com/auth/realms/jhipster",
    "authorization_endpoint": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/auth",
    "token_endpoint": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/token",
    "token_introspection_endpoint": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/token/introspect",
    "userinfo_endpoint": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/userinfo",
    "end_session_endpoint": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/logout",
    "jwks_uri": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/certs",
    "check_session_iframe": "http://my-example.com/auth/realms/jhipster/protocol/openid-connect/login-status-iframe.html",
    "grant_types_supported": ["authorization_code", "implicit", "refresh_token", "password", "client_credentials"],
    "response_types_supported": ["code", "none", "id_token", "token", "id_token token", "code id_token", "code token", "code id_token token"],
    "subject_types_supported": ["public", "pairwise"],
    "id_token_signing_alg_values_supported": ["RS256"],
    "userinfo_signing_alg_values_supported": ["RS256"],
    "request_object_signing_alg_values_supported": ["none", "RS256"],
    "response_modes_supported": ["query", "fragment", "form_post"],
    "registration_endpoint": "http://my-example.com/auth/realms/jhipster/clients-registrations/openid-connect",
    "token_endpoint_auth_methods_supported": ["private_key_jwt", "client_secret_basic", "client_secret_post"],
    "token_endpoint_auth_signing_alg_values_supported": ["RS256"],
    "claims_supported": ["sub", "iss", "auth_time", "name", "given_name", "family_name", "preferred_username", "email"],
    "claim_types_supported": ["normal"],
    "claims_parameter_supported": false,
    "scopes_supported": ["openid", "offline_access"],
    "request_parameter_supported": true,
    "request_uri_parameter_supported": true
}

As you may notice http://my-example.com/... is shown instead of https://my-example.com/...

Therefore I had to change following config of my realm(jhipster-realm.json) from
"sslRequired" : "external",
to
"sslRequired" : "none", which I don't know if is a bad thing? considering (1) my browser never leaves https when I do test login workflow and (2) my keycloak instance is not accessible through any public port.

Well I am not going to accept my own answer as accepted answer, because as I said earlier I feel things can get done better and in more secure way. Thanks!

Update

I've done following changes for using https protocol:

Dockerfile

FROM jboss/keycloak:3.4.1.Final

standalone.xml

<server name="default-server">
    ...
    <http-listener name="default" socket-binding="http" redirect-socket="proxy-https" proxy-address-forwarding="${env.PROXY_ADDRESS_FORWARDING}" certificate-forwarding="true" enable-http2="true"/>
    <https-listener name="https" socket-binding="https" security-realm="ApplicationRealm" proxy-address-forwarding="${env.PROXY_ADDRESS_FORWARDING}" certificate-forwarding="true" enable-http2="true"/>
...

<socket-binding-group ...
    <socket-binding name="proxy-https" port="443"/>
...

nginx.conf

upstream keycloak {
    server keycloak:9443;
}
...
server {
    listen 80;
    return 301 https://$host$request_uri;
}
server {
    listen 443 ssl http2;
    ...
    location /auth {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass https://keycloak;
    }
...

jhipster-realm.json

...
"sslRequired": "external",

HTH, Thanks!


问:
How to get Visual Studio to launch correct url when using docker-compose with https
I've created a .net core 2.0 project and configured it to run over HTTPS, however I cannot get Visual Studio to launch the browser with the correct scheme/port when running in Docker debug mode.

The current behaviour is VS always launches on port 80 (HTTP), and I therefore have to manually change the url each time, which is cumbersome.

Program.cs

```<code>public class Program {
    public static void Main (string[] args) {
        BuildWebHost(args).Run ();
    }

    public static IWebHost BuildWebHost (string[] args) =>
        WebHost.CreateDefaultBuilder (args)
        .UseKestrel (options => {
            options.Listen (IPAddress.Any, GetPort(), listenOptions => {
                // todo: Change this for production
                listenOptions.UseHttps ("dev-cert.pfx", "idsrv3test");
            });
        })
        .UseStartup<Startup> ()
        .Build ();

    public static int GetPort() => int.Parse(Environment.GetEnvironmentVariable("Port") ?? "443");
}
</code>```

Dockerfile

```<code>FROM microsoft/aspnetcore:2.0
ARG source
WORKDIR /app
EXPOSE 443
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT ["dotnet", "MyApp.dll"]
</code>```

docker-compose.override.yml

```<code>version: '3'

services:
  myapp:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - Port=443
    ports:
      - 443
networks:
  default:
    external:
      name: nat
</code>```

答:
Okay I have found out how to solve this myself.

Right-click the docker-compose project and go to properties.

There you can configure the Service URL that gets launched on run.

Body:
I've created a .net core 2.0 project and configured it to run over HTTPS, however I cannot get Visual Studio to launch the browser with the correct scheme/port when running in Docker debug mode.

The current behaviour is VS always launches on port 80 (HTTP), and I therefore have to manually change the url each time, which is cumbersome.

Program.cs

public class Program {
    public static void Main (string[] args) {
        BuildWebHost(args).Run ();
    }

    public static IWebHost BuildWebHost (string[] args) =>
        WebHost.CreateDefaultBuilder (args)
        .UseKestrel (options => {
            options.Listen (IPAddress.Any, GetPort(), listenOptions => {
                // todo: Change this for production
                listenOptions.UseHttps ("dev-cert.pfx", "idsrv3test");
            });
        })
        .UseStartup<Startup> ()
        .Build ();

    public static int GetPort() => int.Parse(Environment.GetEnvironmentVariable("Port") ?? "443");
}

Dockerfile

FROM microsoft/aspnetcore:2.0
ARG source
WORKDIR /app
EXPOSE 443
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT ["dotnet", "MyApp.dll"]

docker-compose.override.yml

version: '3'

services:
  myapp:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - Port=443
    ports:
      - 443
networks:
  default:
    external:
      name: nat


问:
iOS - Animating background issue
I am trying to animate few elements on a screen, here's the code:

```<code>  private func setupAnimations() {

    self.emailAddress.alpha = 0
    self.fullName.alpha = 0
    self.password.alpha = 0
    self.confirmPassword.alpha = 0
    self.signUp.alpha = 0
    self.fullName.leftView?.alpha = 0
    self.emailAddress.leftView?.alpha = 0
    self.password.leftView?.alpha = 0
    self.confirmPassword.leftView?.alpha = 0

    self.emailAddress.center.x += self.view.bounds.width-10
    self.fullName.center.x -= self.view.bounds.width-10
    self.password.center.x -= self.view.bounds.width-10
    self.confirmPassword.center.x += self.view.bounds.width-10
    self.signUp.center.y += self.view.bounds.height/2

    UIView.animate(withDuration: 1.7, delay: 0.2, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [.allowUserInteraction,.curveEaseInOut], animations: {

        self.emailAddress.alpha = 1
        self.emailAddress.center.x -= self.view.bounds.width-10
        self.view.layoutIfNeeded()

    }, completion: {(completed) in

        if completed {

            UIView.animate(withDuration: 1, animations: {
                self.fullName.leftView?.alpha = 1
                self.emailAddress.leftView?.alpha = 1
                self.password.leftView?.alpha = 1
                self.confirmPassword.leftView?.alpha = 1
            })

        }

    })

    UIView.animate(withDuration: 1.7, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [.allowUserInteraction,.curveEaseInOut], animations: {

        self.fullName.alpha = 1
        self.fullName.center.x += self.view.bounds.width-10
        self.view.layoutIfNeeded()

    }, completion: {(completed) in

        if completed {

            UIView.animate(withDuration: 1, animations: {
                self.fullName.leftView?.alpha = 1
                self.emailAddress.leftView?.alpha = 1
                self.password.leftView?.alpha = 1
                self.confirmPassword.leftView?.alpha = 1
            })

        }

    })
</code>```

And so on.. you get the idea - Im setting the alpha to 0 and center x to be off screen, and animate it "arriving" on the screen, its being called in viewDidLoad(). Everything worked out for a month, but recently I have checked this and here's the problem:

video link: https://streamable.com/lhqvu

The background, which is an UIImage in a superview is also being animated, making the superview (red background) being seen.

Any help would be appreciated. Thank you in advance.

答: When it comes to animations you should call the function on viewDidAppear rather than viewDidLoad.

Title: iOS - Animating background issue

Body:
I am trying to animate few elements on a screen, here's the code:

  private func setupAnimations() {

    self.emailAddress.alpha = 0
    self.fullName.alpha = 0
    self.password.alpha = 0
    self.confirmPassword.alpha = 0
    self.signUp.alpha = 0
    self.fullName.leftView?.alpha = 0
    self.emailAddress.leftView?.alpha = 0
    self.password.leftView?.alpha = 0
    self.confirmPassword.leftView?.alpha = 0

    self.emailAddress.center.x += self.view.bounds.width-10
    self.fullName.center.x -= self.view.bounds.width-10
    self.password.center.x -= self.view.bounds.width-10
    self.confirmPassword.center.x += self.view.bounds.width-10
    self.signUp.center.y += self.view.bounds.height/2

    UIView.animate(withDuration: 1.7, delay: 0.2, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [.allowUserInteraction,.curveEaseInOut], animations: {

        self.emailAddress.alpha = 1
        self.emailAddress.center.x -= self.view.bounds.width-10
        self.view.layoutIfNeeded()

    }, completion: {(completed) in

        if completed {

            UIView.animate(withDuration: 1, animations: {
                self.fullName.leftView?.alpha = 1
                self.emailAddress.leftView?.alpha = 1
                self.password.leftView?.alpha = 1
                self.confirmPassword.leftView?.alpha = 1
            })

        }

    })

    UIView.animate(withDuration: 1.7, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [.allowUserInteraction,.curveEaseInOut], animations: {

        self.fullName.alpha = 1
        self.fullName.center.x += self.view.bounds.width-10
        self.view.layoutIfNeeded()

    }, completion: {(completed) in

        if completed {

            UIView.animate(withDuration: 1, animations: {
                self.fullName.leftView?.alpha = 1
                self.emailAddress.leftView?.alpha = 1
                self.password.leftView?.alpha = 1
                self.confirmPassword.leftView?.alpha = 1
            })

        }

    })

And so on.. you get the idea - Im setting the alpha to 0 and center x to be off screen, and animate it "arriving" on the screen, its being called in viewDidLoad(). Everything worked out for a month, but recently I have checked this and here's the problem:

video link: https://streamable.com/lhqvu

The background, which is an UIImage in a superview is also being animated, making the superview (red background) being seen.

Any help would be appreciated. Thank you in advance.


问:
How to execute unix 'top' command with options in android
I am trying to execute 'top' command with following code which is working correctly:

```<code>try {

        Process proc = Runtime.getRuntime().exec("top");

        InputStream is = proc.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 500);
        StringBuilder output = new StringBuilder();
        String line = "";
        int count = 0;
        while ((line = reader.readLine()) != null) {
            if(line.trim().equals(""))
                continue;
            if (line.trim().startsWith("User")) {
                count++;
                if (count > 2)
                    break; //'top' command keeps repeating call to itself. we need to stop after 1 call
            }
            if (line.contains("PID")) {
                mainInfo.append(output.toString());
                output.delete(0,output.length());
                continue;
            }

            output.append(line)
                    .append(CPUInfoUtil.SEPARATOR_LINE); //append this separator to help parsing

        }
        reader.close();
        proc.destroy();
        return output.toString();
    } catch (FileNotFoundException e) {

        return null;
    } catch (IOException e) {

        throw new RuntimeException(e);

    }
</code>```

This is returning me all processes including kernel/root processes. I want to get only system processes except woner=root. For that I tried following 'top' with following options, which didn't work:

```<code>Process proc = Runtime.getRuntime().exec(new String[]{"top","U","!root"});
</code>```

I know I can also get running processes using following code but it does not provide additional information that 'top' provides (e.g. Cpu%, thread count etc):

```<code>((ActivityManager) act.getSystemService(Context.ACTIVITY_SERVICE)).getRunningServices(Integer.MAX_VALUE);
</code>```

答:
I am using

```<code>Process psProc = Runtime.getRuntime().exec("top -n 1 -d 5");
</code>```

to get all the process running and then calculate CPU usage for android apps.

Body:
I am trying to execute 'top' command with following code which is working correctly:

try {

        Process proc = Runtime.getRuntime().exec("top");

        InputStream is = proc.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 500);
        StringBuilder output = new StringBuilder();
        String line = "";
        int count = 0;
        while ((line = reader.readLine()) != null) {
            if(line.trim().equals(""))
                continue;
            if (line.trim().startsWith("User")) {
                count++;
                if (count > 2)
                    break; //'top' command keeps repeating call to itself. we need to stop after 1 call
            }
            if (line.contains("PID")) {
                mainInfo.append(output.toString());
                output.delete(0,output.length());
                continue;
            }

            output.append(line)
                    .append(CPUInfoUtil.SEPARATOR_LINE); //append this separator to help parsing

        }
        reader.close();
        proc.destroy();
        return output.toString();
    } catch (FileNotFoundException e) {

        return null;
    } catch (IOException e) {

        throw new RuntimeException(e);

    }

This is returning me all processes including kernel/root processes. I want to get only system processes except woner=root. For that I tried following 'top' with following options, which didn't work:

Process proc = Runtime.getRuntime().exec(new String[]{"top","U","!root"});

I know I can also get running processes using following code but it does not provide additional information that 'top' provides (e.g. Cpu%, thread count etc):

((ActivityManager) act.getSystemService(Context.ACTIVITY_SERVICE)).getRunningServices(Integer.MAX_VALUE);

Body:
I am using

Process psProc = Runtime.getRuntime().exec("top -n 1 -d 5");

to get all the process running and then calculate CPU usage for android apps.


问:
Text inside div wont center
Problem Statement : Center alignment not happening

Relevant code:

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  color: #EFEFEF;
  width: 100%;
  height: 30%;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="innhold">
  <div id="tekst"> text </div>
</div></code>```

any help would be appreciated.

答:
You need to add the CSS property text-align:center;.

Hope this helps.

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  text-align:center;
  color: #EFEFEF;
  width: 100%;
  height: 30%;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="innhold">
  <div id="tekst"> text </div>
</div></code>```

Title: Text inside div wont center

Body:
Problem Statement : Center alignment not happening

Relevant code:

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  color: #EFEFEF;
  width: 100%;
  height: 30%;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
}

 text

any help would be appreciated.

Body:
You need to add the CSS property text-align:center;.

Hope this helps.

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  text-align:center;
  color: #EFEFEF;
  width: 100%;
  height: 30%;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
}

<div id="innhold">
  <div id="tekst"> text </div>
</div>


问:
Django "Did you mean?" query
I am writing a fairly simple Django application where users can enter string queries. The application will the search through the database for this string.

```<code>Entry.objects.filter(headline__contains=query)
</code>```

This query is pretty strait forward but not really helpful to someone who isn't 100% sure what they are looking for. So I expanded the search.

```<code>from django.utils import stopwords

results = Entry.objects.filter(headline__contains=query)
if(!results):
    query = strip_stopwords(query)
    for(q in query.split(' ')):
        results += Entry.objects.filter(headline__contains=q)
</code>```

I would like to add some additional functionality to this. Searching for miss spelled words, plurals, common homophones (sound the same spelled differently), ect. I was just wondering if any of these things were built into Djangos query language. It isn't important enough for me to write a huge algorithm for I am really just looking for something built in.

Thanks in advance for all the answers.

答:
djangos orm doesn't have this behavior out-of-box, but there are several projects that integrate django w/ search services like:

sphinx (django-sphinx)

solr, a lightweight version of lucene (djangosearch)

lucene (django-search-lucene)

I cant speak to how well options #2 and #3 work, but I've used django-sphinx quite a lot, and am very happy with the results.

OwnerDisplayName: Matt Campbell

Title: Django "Did you mean?" query

Body:
I am writing a fairly simple Django application where users can enter string queries. The application will the search through the database for this string.

Entry.objects.filter(headline__contains=query)

This query is pretty strait forward but not really helpful to someone who isn't 100% sure what they are looking for. So I expanded the search.

from django.utils import stopwords

results = Entry.objects.filter(headline__contains=query)
if(!results):
    query = strip_stopwords(query)
    for(q in query.split(' ')):
        results += Entry.objects.filter(headline__contains=q)

I would like to add some additional functionality to this. Searching for miss spelled words, plurals, common homophones (sound the same spelled differently), ect. I was just wondering if any of these things were built into Djangos query language. It isn't important enough for me to write a huge algorithm for I am really just looking for something built in.

Thanks in advance for all the answers.

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: mattdennewitz


问:
Tar archive: How reliable is append?
I noticed that the -a option in TAR allows appending files to an existing archive. How reliable is this for creating incremented backups of a set folder?
Is there anyone here who can share their experiences?

From the TAR manual:

```<code> -A, --catenate, --concatenate
       append tar files to an archive
</code>```

答:
As others have pointed out, tar really does append to the file, even if you just keep appending the same file to the tar ball:

```<code>makholm@korovyov:~$ dd if=/dev/urandom bs=1M count=1 of=./foo
1+0 records in
1+0 records out
1048576 bytes (1.0 MB) copied, 0.513785 s, 2.0 MB/s
makholm@korovyov:~$ for i in {1..5} ; do tar -rf foo.tar foo ; ls -lh foo.tar ; done
-rw-r--r-- 1 makholm makholm 1.1M 2011-01-22 01:07 foo.tar
-rw-r--r-- 1 makholm makholm 2.1M 2011-01-22 01:07 foo.tar
-rw-r--r-- 1 makholm makholm 3.1M 2011-01-22 01:07 foo.tar
-rw-r--r-- 1 makholm makholm 4.1M 2011-01-22 01:07 foo.tar
-rw-r--r-- 1 makholm makholm 5.1M 2011-01-22 01:07 foo.tar
makholm@korovyov:~$
</code>```

This makes it pretty useless for something like incremental backups since your tarball will just grow with tons of duplicate files with each run...

Even cpio, which is generally a much more robust archiver does the same thing in this case.

If you want to do incremental backups, look into rsync and what it can do for you in terms of delta transfers and linking to previous versions of files...

Title: Tar archive: How reliable is append?

Body:
I noticed that the -a option in TAR allows appending files to an existing archive. How reliable is this for creating incremented backups of a set folder?
Is there anyone here who can share their experiences?

From the TAR manual:

 -A, --catenate, --concatenate
       append tar files to an archive

Body:
As others have pointed out, tar really does append to the file, even if you just keep appending the same file to the tar ball:

makholm@korovyov:~$ dd if=/dev/urandom bs=1M count=1 of=./foo
1+0 records in
1+0 records out
1048576 bytes (1.0 MB) copied, 0.513785 s, 2.0 MB/s
makholm@korovyov:~$ for i in {1..5} ; do tar -rf foo.tar foo ; ls -lh foo.tar ; done
-rw-r--r-- 1 makholm makholm 1.1M 2011-01-22 01:07 foo.tar
-rw-r--r-- 1 makholm makholm 2.1M 2011-01-22 01:07 foo.tar
-rw-r--r-- 1 makholm makholm 3.1M 2011-01-22 01:07 foo.tar
-rw-r--r-- 1 makholm makholm 4.1M 2011-01-22 01:07 foo.tar
-rw-r--r-- 1 makholm makholm 5.1M 2011-01-22 01:07 foo.tar
makholm@korovyov:~$

This makes it pretty useless for something like incremental backups since your tarball will just grow with tons of duplicate files with each run...

Even cpio, which is generally a much more robust archiver does the same thing in this case.

If you want to do incremental backups, look into rsync and what it can do for you in terms of delta transfers and linking to previous versions of files...


问:
Serverless Framework: How to add external NPM packages?
My situation is that I am having a bit of trouble in adding external NPM packages to my Serverless Framework project (specific package is geopoint).

I went to the root folder of the Serverless project and ran npm install geopoint --save. package.json got updated with dependencies": { "geopoint": "^1.0.1" } and node_modules folder was created.

My folder structure looks like this:

root-project-folder

-functions

--geospatial

---handler.js

-node_modules

--geopoint

In my functions/geospatial/handler.js I declared the geopoint module with:

```<code>    var geopoint = require('geopoint');
    var geopoint = require('../../geopoint');
    var geopoint = require('../../../geopoint');
</code>```

The lambda console returns an error of:

```<code>    {
      "errorMessage": "Cannot find module '../../geopoint'",
      "errorType": "Error",
      "stackTrace": []
    }
</code>```

How can I properly add external NPM modules to a Serverless Framework project?

答:
For me best solution was Serverless plugin: serverless-plugin-include-dependencies

serverless-plugin-include-dependencies

Body:
My situation is that I am having a bit of trouble in adding external NPM packages to my Serverless Framework project (specific package is geopoint).

I went to the root folder of the Serverless project and ran npm install geopoint --save. package.json got updated with dependencies": { "geopoint": "^1.0.1" } and node_modules folder was created.

My folder structure looks like this:

root-project-folder

-functions

--geospatial

---handler.js

-node_modules

--geopoint

In my functions/geospatial/handler.js I declared the geopoint module with:

    var geopoint = require('geopoint');
    var geopoint = require('../../geopoint');
    var geopoint = require('../../../geopoint');

The lambda console returns an error of:

    {
      "errorMessage": "Cannot find module '../../geopoint'",
      "errorType": "Error",
      "stackTrace": []
    }

How can I properly add external NPM modules to a Serverless Framework project?


问:
MongoDB: all full leaf path
Having a Document, I would like to obtain in Java the list of all full paths, only for the leafs.

For example, having this Document:

```<code>{A : {
    B : {
        D : "d"
    }
    C : {
        E : "e",
        F : "f"
    }
}
</code>```

I would like to obtain this List<String>:

```<code>"A.B.D",
"A.C.E",
"A.C.F"
</code>```

Is there a functionality into some "mongodb" library to do this?
How could I write it manually without using recursion?

答:
I've found a solution.

I used the power of Gson library to transfor the Document into a json and after read it with using com.google.gson.stream.JsonReader.

The code could be better with more performance, but for my necessity this code is ok, I just have to read only few Documents.

```<code>public static List<String> leafPaths(Document document) {
    String json = gson.toJson(document);
    List<String> leafPaths = new ArrayList<>();
    try (JsonReader reader = new JsonReader(new StringReader(json))) {
        // scorro tutti gli elemento dello json
        while (true) {
            JsonToken token = reader.peek();
            switch (token) {
                case BEGIN_ARRAY:
                    reader.beginArray();
                    break;
                case END_ARRAY:
                    reader.endArray();
                    break;
                case BEGIN_OBJECT:
                    reader.beginObject();
                    break;
                case END_OBJECT:
                    reader.endObject();
                    break;
                case NAME:
                    reader.nextName();
                    break;
                case STRING:
                    reader.nextString();
                    leafPaths.add(reader.getPath());
                    break;
                case NUMBER:
                    reader.nextDouble();
                    leafPaths.add(reader.getPath());
                    break;
                case BOOLEAN:
                    reader.nextBoolean();
                    leafPaths.add(reader.getPath());
                    break;
                case NULL:
                    reader.nextNull();
                    break;
                case END_DOCUMENT:
                    // tutti i campi
                    return leafPaths.stream().map(field -> field.substring(2)).collect(toList());
                default:
                    break;
            }
        }

    } catch (Exception e) {
        return leafPaths;
    }
}
</code>```

Title: MongoDB: all full leaf path

Body:
Having a Document, I would like to obtain in Java the list of all full paths, only for the leafs.

For example, having this Document:

{A : {
    B : {
        D : "d"
    }
    C : {
        E : "e",
        F : "f"
    }
}

I would like to obtain this List<String>:

"A.B.D",
"A.C.E",
"A.C.F"

Is there a functionality into some "mongodb" library to do this?
How could I write it manually without using recursion?

Body:
I've found a solution.

I used the power of Gson library to transfor the Document into a json and after read it with using com.google.gson.stream.JsonReader.

The code could be better with more performance, but for my necessity this code is ok, I just have to read only few Documents.

public static List<String> leafPaths(Document document) {
    String json = gson.toJson(document);
    List<String> leafPaths = new ArrayList<>();
    try (JsonReader reader = new JsonReader(new StringReader(json))) {
        // scorro tutti gli elemento dello json
        while (true) {
            JsonToken token = reader.peek();
            switch (token) {
                case BEGIN_ARRAY:
                    reader.beginArray();
                    break;
                case END_ARRAY:
                    reader.endArray();
                    break;
                case BEGIN_OBJECT:
                    reader.beginObject();
                    break;
                case END_OBJECT:
                    reader.endObject();
                    break;
                case NAME:
                    reader.nextName();
                    break;
                case STRING:
                    reader.nextString();
                    leafPaths.add(reader.getPath());
                    break;
                case NUMBER:
                    reader.nextDouble();
                    leafPaths.add(reader.getPath());
                    break;
                case BOOLEAN:
                    reader.nextBoolean();
                    leafPaths.add(reader.getPath());
                    break;
                case NULL:
                    reader.nextNull();
                    break;
                case END_DOCUMENT:
                    // tutti i campi
                    return leafPaths.stream().map(field -> field.substring(2)).collect(toList());
                default:
                    break;
            }
        }

    } catch (Exception e) {
        return leafPaths;
    }
}


问:
What is the point of printf's length modifier flags?
printf has a series of "length modifier" flags you can pass in the format specifications, for example %d is for an int argument, but %hhd is for a signed char (8-bit) and %lld is a long long (64-bit).

I can see why this is necessary for larger-than-int types, but smaller types are implicitly promoted to int anyway.

In what situation would %hhd give a different output to %d, assuming you actually do pass a signed char?

答: You need the length modifiers for reading shorter data with scanf. Because printf and scanf shares the mostly same set of formatting strings, including modifiers, it's retained primarily of consistence concerns.


问:
How to debug uncaught (in promise): EmptyError: no elements in sequence caused by router.navigate?
I'm trying to implement a simple angular route

```<code>const appRoutes: Routes = [
   { path: ''        ,redirectTo: '/recipes', pathMatch: 'full'},
   { path: 'recipes'              , component: RecipesComponent},
   { path: 'recipes/:recipeName'  , component: RecipesComponent},
];
</code>```

in some component that generates the list, i have a function that on click of a
updates state variable and routes, though I also have fetching mechanism subscriber happening on initialization.

```<code>  ngOnInit() {
    this.route.params
      .subscribe(
        (params: {Params}) => {

          this.selectedRecipe = this.findRecipeByName(params['recipeName']);
        });
  }

   navRecipe(recipeName: string): void {
      let path = '/recipes/' + recipeName;
      this.selectedRecipe = this.findRecipeByName(recipeName);
      this.router.navigate([path]);
   }
</code>```

But when I try to click on a link that reroutes to component with parameter I get the following:

```<code>core.js:1350 ERROR Error: Uncaught (in promise): EmptyError: no elements in sequence
EmptyError: no elements in sequence
    at new EmptyError (EmptyError.js:28)
    at FirstSubscriber._complete (first.js:154)
    at FirstSubscriber.Subscriber.complete (Subscriber.js:122)
    at MergeMapSubscriber._complete (mergeMap.js:150)
    at MergeMapSubscriber.Subscriber.complete (Subscriber.js:122)
    at MapSubscriber.Subscriber._complete (Subscriber.js:140)
    at MapSubscriber.Subscriber.complete (Subscriber.js:122)
    at EmptyObservable._subscribe (EmptyObservable.js:83)
    at EmptyObservable.Observable._trySubscribe (Observable.js:172)
    at EmptyObservable.Observable.subscribe (Observable.js:160)
    at new EmptyError (EmptyError.js:28)
    at FirstSubscriber._complete (first.js:154)
    at FirstSubscriber.Subscriber.complete (Subscriber.js:122)
    at MergeMapSubscriber._complete (mergeMap.js:150)
    at MergeMapSubscriber.Subscriber.complete (Subscriber.js:122)
    at MapSubscriber.Subscriber._complete (Subscriber.js:140)
    at MapSubscriber.Subscriber.complete (Subscriber.js:122)
    at EmptyObservable._subscribe (EmptyObservable.js:83)
    at EmptyObservable.Observable._trySubscribe (Observable.js:172)
    at EmptyObservable.Observable.subscribe (Observable.js:160)
    at resolvePromise (zone.js:824)
    at resolvePromise (zone.js:795)
    at eval (zone.js:873)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4621)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at ZoneTask.invokeTask [as invoke] (zone.js:503)
    at invokeTask (zone.js:1540)
</code>```

答:
I encountered the same error with Angular 5.0.1 and rxjs 5.5.3. We did not encounter the exception when we changed the order in the routes array. So for your example:

```<code>const appRoutes: Routes = [
    { path: '',                    redirectTo: '/recipes', pathMatch: 'full'},
    { path: 'recipes/:recipeName', component: RecipesComponent},
    { path: 'recipes',             component: RecipesComponent},
];
</code>```

Putting the more detailed path (recipes/:recipeName) before the general path (recipes).

Body:
I'm trying to implement a simple angular route

const appRoutes: Routes = [
   { path: ''        ,redirectTo: '/recipes', pathMatch: 'full'},
   { path: 'recipes'              , component: RecipesComponent},
   { path: 'recipes/:recipeName'  , component: RecipesComponent},
];

in some component that generates the list, i have a function that on click of a
updates state variable and routes, though I also have fetching mechanism subscriber happening on initialization.

  ngOnInit() {
    this.route.params
      .subscribe(
        (params: {Params}) => {

          this.selectedRecipe = this.findRecipeByName(params['recipeName']);
        });
  }

   navRecipe(recipeName: string): void {
      let path = '/recipes/' + recipeName;
      this.selectedRecipe = this.findRecipeByName(recipeName);
      this.router.navigate([path]);
   }

But when I try to click on a link that reroutes to component with parameter I get the following:

core.js:1350 ERROR Error: Uncaught (in promise): EmptyError: no elements in sequence
EmptyError: no elements in sequence
    at new EmptyError (EmptyError.js:28)
    at FirstSubscriber._complete (first.js:154)
    at FirstSubscriber.Subscriber.complete (Subscriber.js:122)
    at MergeMapSubscriber._complete (mergeMap.js:150)
    at MergeMapSubscriber.Subscriber.complete (Subscriber.js:122)
    at MapSubscriber.Subscriber._complete (Subscriber.js:140)
    at MapSubscriber.Subscriber.complete (Subscriber.js:122)
    at EmptyObservable._subscribe (EmptyObservable.js:83)
    at EmptyObservable.Observable._trySubscribe (Observable.js:172)
    at EmptyObservable.Observable.subscribe (Observable.js:160)
    at new EmptyError (EmptyError.js:28)
    at FirstSubscriber._complete (first.js:154)
    at FirstSubscriber.Subscriber.complete (Subscriber.js:122)
    at MergeMapSubscriber._complete (mergeMap.js:150)
    at MergeMapSubscriber.Subscriber.complete (Subscriber.js:122)
    at MapSubscriber.Subscriber._complete (Subscriber.js:140)
    at MapSubscriber.Subscriber.complete (Subscriber.js:122)
    at EmptyObservable._subscribe (EmptyObservable.js:83)
    at EmptyObservable.Observable._trySubscribe (Observable.js:172)
    at EmptyObservable.Observable.subscribe (Observable.js:160)
    at resolvePromise (zone.js:824)
    at resolvePromise (zone.js:795)
    at eval (zone.js:873)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4621)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at ZoneTask.invokeTask [as invoke] (zone.js:503)
    at invokeTask (zone.js:1540)

Body:
I encountered the same error with Angular 5.0.1 and rxjs 5.5.3. We did not encounter the exception when we changed the order in the routes array. So for your example:

const appRoutes: Routes = [
    { path: '',                    redirectTo: '/recipes', pathMatch: 'full'},
    { path: 'recipes/:recipeName', component: RecipesComponent},
    { path: 'recipes',             component: RecipesComponent},
];

Putting the more detailed path (recipes/:recipeName) before the general path (recipes).


问:
mousedown event not happening
in the snippet below, only the 'mousemove' event is working. 'mousedown' has no effect and I'm not able to decipher why this is happening. If I replace 'mousedown' with 'click', it does work, however I want to use mousedown so the fadeOut event happens immediately (at the start of a click, rather than using click which relies on the users mouse going down and then back up.</p>

```<code>$('.issue-carousel').on({
    // On mousemove, controls follow cursor
    mousemove: function(e) {
        var parentOffset = $(this).offset();
        var relX = e.pageX - parentOffset.left;
        var relY = e.pageY - parentOffset.top;
        $('.drag-indicator').css({
            left: relX,
            top: relY
        });
    },
    mousedown: function() {
       $('.drag-indicator').fadeOut(300);
    }
});
</code>```

答:
As per my comment, your code works fine - with one exception. The mousedown fadeout doesn't work because you technically aren't clicking the carousel but instead the drag indicator. I've updated the code as per below where I have changed the mousedown target accordingly;

```<code>$('.issue-carousel').on({
    // On mousemove, controls follow cursor
    mousemove: function(e) {
        var parentOffset = $(this).offset();
        var relX = e.pageX - parentOffset.left;
        var relY = e.pageY - parentOffset.top;
        $('.drag-indicator').css({
            left: relX,
            top: relY
        });
    }
});

$('.drag-indicator').on({
    mousedown: function(e){
    $(this).fadeOut(300);
  }
})
</code>```

A working fiddle can be found here: https://jsfiddle.net/o3cdLjp7/2/

Title: mousedown event not happening

Body:
in the snippet below, only the 'mousemove' event is working. 'mousedown' has no effect and I'm not able to decipher why this is happening. If I replace 'mousedown' with 'click', it does work, however I want to use mousedown so the fadeOut event happens immediately (at the start of a click, rather than using click which relies on the users mouse going down and then back up.

$('.issue-carousel').on({
    // On mousemove, controls follow cursor
    mousemove: function(e) {
        var parentOffset = $(this).offset();
        var relX = e.pageX - parentOffset.left;
        var relY = e.pageY - parentOffset.top;
        $('.drag-indicator').css({
            left: relX,
            top: relY
        });
    },
    mousedown: function() {
       $('.drag-indicator').fadeOut(300);
    }
});

Body:
As per my comment, your code works fine - with one exception. The mousedown fadeout doesn't work because you technically aren't clicking the carousel but instead the drag indicator. I've updated the code as per below where I have changed the mousedown target accordingly;

$('.issue-carousel').on({
    // On mousemove, controls follow cursor
    mousemove: function(e) {
        var parentOffset = $(this).offset();
        var relX = e.pageX - parentOffset.left;
        var relY = e.pageY - parentOffset.top;
        $('.drag-indicator').css({
            left: relX,
            top: relY
        });
    }
});

$('.drag-indicator').on({
    mousedown: function(e){
    $(this).fadeOut(300);
  }
})

A working fiddle can be found here: https://jsfiddle.net/o3cdLjp7/2/


问:
Trivial query with if statements
How to achieve this simple logic?

```<code>void IRQHandler(void)
{
   if(update_variable == 0)
    {
        if(CONDITION1)
         {

            /* MORE CODE */
            update_variable = 1;
          }
    } /* Here i want to exit the loop */

    if(update_variable == 1) /* execute in next loop */
     {
         if(CONDITION1)
          {
            /* MORE CODE */
            /*UPDATE SOME ARRAY */
            update_variable = 0; /* reset variable for next loop */
          }
      }
  }
</code>```

Essentially, I want to check for the same CONDITION1 over two consecutive interrupts. For 1st interrupt, I want to update the variable value to 1 and exit the loop (precisely do not execute the following if condition).  As I see, I cannot use break condition with "if"! I am struck here for a while! Please help me!

答:
```<code>if(CONDITION1)
{
   if(update_variable == 0)
   {
         /* MORE CODE */
          update_variable = 1;
   }
   else if(update_variable == 1)
   {
         /*Update Some Array*/
         /* MORE CODE */
          update_variable == 0;
   }
}
</code>```

Just use an else condition and it would be better if you check CONDITION1 initially.

Title: Trivial query with if statements

Body:
How to achieve this simple logic?

void IRQHandler(void)
{
   if(update_variable == 0)
    {
        if(CONDITION1)
         {

            /* MORE CODE */
            update_variable = 1;
          }
    } /* Here i want to exit the loop */

    if(update_variable == 1) /* execute in next loop */
     {
         if(CONDITION1)
          {
            /* MORE CODE */
            /*UPDATE SOME ARRAY */
            update_variable = 0; /* reset variable for next loop */
          }
      }
  }

Essentially, I want to check for the same CONDITION1 over two consecutive interrupts. For 1st interrupt, I want to update the variable value to 1 and exit the loop (precisely do not execute the following if condition).  As I see, I cannot use break condition with "if"! I am struck here for a while! Please help me!

Body:
if(CONDITION1)
{
   if(update_variable == 0)
   {
         /* MORE CODE */
          update_variable = 1;
   }
   else if(update_variable == 1)
   {
         /*Update Some Array*/
         /* MORE CODE */
          update_variable == 0;
   }
}

Just use an else condition and it would be better if you check CONDITION1 initially.


问:
Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(CharacterList)
I am trying to test my React "supersquadapp" and getting the following error.

Uncaught Error: Could not find "store" in either the context or props of "Connect(CharacterList)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(CharacterList)".

characterlist.js

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';

class CharacterList extends Component {
    render() {
        console.log('this.props', this.props);
        return (
            <div>
                <h4>characters</h4>
            </div>
        )
    }

}
function mapStateToProps(state) {
    return {
        characters: state.characters
    }
}

export default connect(mapStateToProps, null)(CharacterList);
</code>```

app.js

```<code>import React, {Component} from 'react';
import CharacterList from './CharacterList';

class App extends Component {
    render() {
        return (
            <div>
                <h2>SUPER SQUAD</h2>
                <CharacterList />
            </div>
        )
    }
}
export default App;
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './Components/App';

import { createStore } from 'redux';
import { Provider } from 'react-redux';

import rootReducers from './reducers';
import { addCharacterById } from './actions';

const store = createStore(rootReducers);
console.log(store.getState());
store.subscribe(() => console.log('store',store.getState()))
store.dispatch(addCharacterById(3));

ReactDOM.render(
    <Provider>
        <App />
     </Provider>
    ,document.getElementById('root')
)
</code>```

character.js(in reducers folder)

```<code>import characters_json from '../Data/characters.json';
import { ADD_CHARACTER } from '../actions';

function characters(state = characters_json, action) {
    switch(action.type) {
        case ADD_CHARACTER:
        let characters = state.filter(item => item.id !== action.id);
        return characters;
        default:
            return state;
    }
}
export default characters;
</code>```

heroes.js(reducers folder)

```<code>import { ADD_CHARACTER } from '../actions';
import {createCharacter} from './helper';

function heroes(state = [], action) {
    switch(action.type) {
        case ADD_CHARACTER:
        let heroes = [...state, createCharacter(action.id)];
        return heroes;
        default:
        return state;
    }
}
export default heroes;
</code>```

helper.js(reducers folder)

```<code>import characters_json from '../Data/characters.json';

export function createCharacter(id) {
    let character = characters_json.find(c => c.id === id);
    return character;
}
</code>```

index.js(reducers folder)

```<code>import { combineReducers } from 'redux';
import characters from './characters_reducer';
import heroes from './heroes_reducer';

const rootReducer = combineReducers({
    characters,
    heroes
})
export default rootReducer;
</code>```

index.js(action folder)

```<code>export const ADD_CHARACTER = 'ADD_CHARACTER';

export function addCharacterById(id) {
    const action = {
        type:ADD_CHARACTER,
        id
    }
    return action;
}
</code>```

The above error occurred in the  component:

in Connect(CharacterList) (at App.js:9)

in div (at App.js:7)

in App (at index.js:19)

in Provider (at index.js:18)

please help me...?

答:
You must pass the store instance to Provider...</p>

```<code>ReactDOM.render(
    <Provider store={store}>
        <App />
     </Provider>
    , document.getElementById('root')
)
</code>```

Body:
I am trying to test my React "supersquadapp" and getting the following error.

Uncaught Error: Could not find "store" in either the context or props of "Connect(CharacterList)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(CharacterList)".

characterlist.js

import React, { Component } from 'react';
import { connect } from 'react-redux';

class CharacterList extends Component {
    render() {
        console.log('this.props', this.props);
        return (

characters

        )
    }

}
function mapStateToProps(state) {
    return {
        characters: state.characters
    }
}

export default connect(mapStateToProps, null)(CharacterList);

app.js

import React, {Component} from 'react';
import CharacterList from './CharacterList';

class App extends Component {
    render() {
        return (

SUPER SQUAD

                <CharacterList />

        )
    }
}
export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './Components/App';

import { createStore } from 'redux';
import { Provider } from 'react-redux';

import rootReducers from './reducers';
import { addCharacterById } from './actions';

const store = createStore(rootReducers);
console.log(store.getState());
store.subscribe(() => console.log('store',store.getState()))
store.dispatch(addCharacterById(3));

ReactDOM.render(
    <Provider>
        <App />
     </Provider>
    ,document.getElementById('root')
)

character.js(in reducers folder)

import characters_json from '../Data/characters.json';
import { ADD_CHARACTER } from '../actions';

function characters(state = characters_json, action) {
    switch(action.type) {
        case ADD_CHARACTER:
        let characters = state.filter(item => item.id !== action.id);
        return characters;
        default:
            return state;
    }
}
export default characters;

heroes.js(reducers folder)

import { ADD_CHARACTER } from '../actions';
import {createCharacter} from './helper';

function heroes(state = [], action) {
    switch(action.type) {
        case ADD_CHARACTER:
        let heroes = [...state, createCharacter(action.id)];
        return heroes;
        default:
        return state;
    }
}
export default heroes;

helper.js(reducers folder)

import characters_json from '../Data/characters.json';

export function createCharacter(id) {
    let character = characters_json.find(c => c.id === id);
    return character;
}

index.js(reducers folder)

import { combineReducers } from 'redux';
import characters from './characters_reducer';
import heroes from './heroes_reducer';

const rootReducer = combineReducers({
    characters,
    heroes
})
export default rootReducer;

index.js(action folder)

export const ADD_CHARACTER = 'ADD_CHARACTER';

export function addCharacterById(id) {
    const action = {
        type:ADD_CHARACTER,
        id
    }
    return action;
}

The above error occurred in the  component:

in Connect(CharacterList) (at App.js:9)

in div (at App.js:7)

in App (at index.js:19)

in Provider (at index.js:18)

please help me...?

Body:
You must pass the store instance to Provider...

ReactDOM.render(
    <Provider store={store}>
        <App />
     </Provider>
    , document.getElementById('root')
)


问:
How to compulsory close message box for Toplevel window
image for  that
I have few lines of code here which is login system which works fine but i can click on the Toplevel button multiple times when i provide the wrong password without closing the messagebox.How can i make it so that it has to be closed messagebox before i can make attempt again.

```<code>from tkinter import *
from tkinter import messagebox

def top():
    if entry1.get() == "333":
       log.destroy()
       root.deiconify()
    else:
       messagebox.showerror("error", "try again")

root = Tk()
root.geometry("300x300")

log = Toplevel(root)
log.geometry("200x200")

label1 = Label(log, text="password")
entry1 = Entry(log)
button1 = Button(log, text="login", command=top)

label1.pack()
entry1.pack()
button1.pack(side="bottom")

lab = Label(root, text="welcome bro").pack()

root.withdraw()
root.mainloop()
</code>```

答:
You need to make the log window the parent of the dialog:

```<code>messagebox.showerror("error", "try again", parent=log)
</code>```

By default it will use the root window (the Tk instance) as the parent which in this case is not what you want.

Body:
image for  that
I have few lines of code here which is login system which works fine but i can click on the Toplevel button multiple times when i provide the wrong password without closing the messagebox.How can i make it so that it has to be closed messagebox before i can make attempt again.

from tkinter import *
from tkinter import messagebox

def top():
    if entry1.get() == "333":
       log.destroy()
       root.deiconify()
    else:
       messagebox.showerror("error", "try again")

root = Tk()
root.geometry("300x300")

log = Toplevel(root)
log.geometry("200x200")

label1 = Label(log, text="password")
entry1 = Entry(log)
button1 = Button(log, text="login", command=top)

label1.pack()
entry1.pack()
button1.pack(side="bottom")

lab = Label(root, text="welcome bro").pack()

root.withdraw()
root.mainloop()

Body:
You need to make the log window the parent of the dialog:

messagebox.showerror("error", "try again", parent=log)

By default it will use the root window (the Tk instance) as the parent which in this case is not what you want.


问:
Scientific notation mobile number - Excel Javascript
I am reading excel file in my JS App. I am using xlsx npm module to read excel file.

But if MobileNumber in file = 9.23052E+8 then how can i convert it back into plain mobile number in javascript?

Here is example code of how i am reading file:

```<code>const bstr = evt.target.result;
const wb = XLSX.read(bstr, {type:'binary'});
const wsname = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
const data = XLSX.utils.sheet_to_csv(ws, {header:1});
console.log("Data>>>"+data);
</code>```

I don't want to tell user to change format of your cells to plain text or numbers. (Sorry but that is a requirement).

Any help would be appreciated.

答:
This code resolved my issue:

```<code>Object.keys(sheet).forEach(function(s) {
    if(sheet[s].w) {
        delete sheet[s].w;
        sheet[s].z = '0';
    }
});
</code>```

More on this post:

Body:
I am reading excel file in my JS App. I am using xlsx npm module to read excel file.

But if MobileNumber in file = 9.23052E+8 then how can i convert it back into plain mobile number in javascript?

Here is example code of how i am reading file:

const bstr = evt.target.result;
const wb = XLSX.read(bstr, {type:'binary'});
const wsname = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
const data = XLSX.utils.sheet_to_csv(ws, {header:1});
console.log("Data>>>"+data);

I don't want to tell user to change format of your cells to plain text or numbers. (Sorry but that is a requirement).

Any help would be appreciated.

Body:
This code resolved my issue:

Object.keys(sheet).forEach(function(s) {
    if(sheet[s].w) {
        delete sheet[s].w;
        sheet[s].z = '0';
    }
});

More on this post:


问:
FIrebase deploy error: Cannot find module 'firebase-admin'
I recently started getting the error below when trying to deploy to Firebase (after having done so successfully in the past). I'm not sure what might have changed for this to start occurring. If I run firebase serve to serve on the localhost, everything works fine. My package.json and requires from index.js are also below.

```<code>i  deploying functions, hosting
i  functions: ensuring necessary APIs are enabled...
i  runtimeconfig: ensuring necessary APIs are enabled...
+  runtimeconfig: all necessary APIs are enabled
+  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (46.02 KB) for uploading
+  functions: functions folder uploaded successfully
i  hosting: preparing public directory for upload...
!  Warning: Public directory does not contain index.html
+  hosting: 9 files uploaded successfully
i  starting release process (may take several minutes)...
i  functions: updating function app...
!  functions[app]: Deploy Error: Function load error: Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'firebase-admin'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/apps.j
s:25:16)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

Functions deploy had errors. To continue deploying other features (such as datab
ase), run:
firebase deploy --except functions

Error: Functions did not deploy properly.
</code>```

package.json:

```<code>{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"@google-cloud/vision": "^0.12.0",
"async": "^2.5.0",
"consolidate": "^0.14.5",
"express": "^4.15.4",
"firebase-admin": "^5.4.0",
"firebase-functions": "^0.5.7",
"handlebars": "^4.0.10",
"jquery": "^3.2.1",
"js-levenshtein": "^1.1.3",
"json-query": "^2.2.2"
},
"private": true
}
</code>```

From index.js:

```<code>const functions = require('firebase-functions');
const firebase = require('firebase-admin');
const express = require('express');
const engines = require('consolidate');
const Vision = require('@google-cloud/vision');
const levenshtein = require('js-levenshtein');
const restName = require('./restName');
const parser = require('./parser');
const jsonQuery = require('json-query')

const firebaseApp = firebase.initializeApp(
functions.config().firebase
);
</code>```

答: I also got same error. i fix that error from installing different version in nodejs. I uninstall my new version and i install Node v7.8.0. then it works fine :)

Body:
I recently started getting the error below when trying to deploy to Firebase (after having done so successfully in the past). I'm not sure what might have changed for this to start occurring. If I run firebase serve to serve on the localhost, everything works fine. My package.json and requires from index.js are also below.

i  deploying functions, hosting
i  functions: ensuring necessary APIs are enabled...
i  runtimeconfig: ensuring necessary APIs are enabled...
+  runtimeconfig: all necessary APIs are enabled
+  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (46.02 KB) for uploading
+  functions: functions folder uploaded successfully
i  hosting: preparing public directory for upload...
!  Warning: Public directory does not contain index.html
+  hosting: 9 files uploaded successfully
i  starting release process (may take several minutes)...
i  functions: updating function app...
!  functions[app]: Deploy Error: Function load error: Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'firebase-admin'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/apps.j
s:25:16)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

Functions deploy had errors. To continue deploying other features (such as datab
ase), run:
firebase deploy --except functions

Error: Functions did not deploy properly.

package.json:

{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"@google-cloud/vision": "^0.12.0",
"async": "^2.5.0",
"consolidate": "^0.14.5",
"express": "^4.15.4",
"firebase-admin": "^5.4.0",
"firebase-functions": "^0.5.7",
"handlebars": "^4.0.10",
"jquery": "^3.2.1",
"js-levenshtein": "^1.1.3",
"json-query": "^2.2.2"
},
"private": true
}

From index.js:

const functions = require('firebase-functions');
const firebase = require('firebase-admin');
const express = require('express');
const engines = require('consolidate');
const Vision = require('@google-cloud/vision');
const levenshtein = require('js-levenshtein');
const restName = require('./restName');
const parser = require('./parser');
const jsonQuery = require('json-query')

const firebaseApp = firebase.initializeApp(
functions.config().firebase
);


答:
To fully center your text you can use flexbox:

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  color: #EFEFEF;
  height: 30%;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
  display: flex;
  justify-content: center;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="innhold">
  <div id="tekst"> text </div>
</div></code>```

Title: Text inside div wont center

Body:
Problem Statement : Center alignment not happening

Relevant code:

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  color: #EFEFEF;
  width: 100%;
  height: 30%;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
}

 text

any help would be appreciated.

Body:
To fully center your text you can use flexbox:

#tekst {
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  color: #EFEFEF;
  height: 30%;
}

#innhold {
  width: 100%;
  height: 30%;
  top: 18%;
  left: 0%;
  background-color: #7e7e7e;
  position: absolute;
  border-radius: 5px;
  z-index: 2;
  display: flex;
  justify-content: center;
  align-items: center;
}

<div id="innhold">
  <div id="tekst"> text </div>
</div>