问:
k-means clustering in pyspark
I need to perform k-means clustering in my pre-processed dataset, but it gives me error message. Can anyone please help me?

Firstly i read my data in pyspark as below

```<code>import pyspark as spark
from pyspark.sql.types import *
from pyspark.sql import SparkSession
spark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()
dfSchema = StructType([
    StructField("InvoiceNo", StringType(), True),
    StructField("StockCode", StringType(), True),
    StructField("Description", StringType(), True),
    StructField("Quantity", IntegerType(), True),
    StructField("InvoiceDate", StringType(), True),
    StructField("UnitPrice", FloatType(), True),
    StructField("CustomerID", IntegerType(), True),
    StructField("Country", StringType(), True),
    StructField("Date", StringType(), True),
    StructField("Time", StringType(), True),
])
df = spark.read.csv('data.csv', header=True, schema=dfSchema, encoding='cp1252')
</code>```

Then i converted my spark dataframe into pandas dataframe and did some data analysis

```<code>data  = df.toPandas()
</code>```

After these i converted once again my pandas data frame into spark dataframe

```<code>data2 = spark.createDataFrame(Data2)
data2.printSchema()

'''Output

root
 |-- InvoiceNo: string (nullable = true)
 |-- StockCode: string (nullable = true)
 |-- Description: string (nullable = true)
 |-- Quantity: integer (nullable = true)
 |-- InvoiceDate: string (nullable = true)
 |-- UnitPrice: float (nullable = true)
 |-- CustomerID: integer (nullable = true)
 |-- Country: string (nullable = true)
 |-- Date: string (nullable = true)
 |-- Time: string (nullable = true)
 |-- year: integer (nullable = true)
 |-- month: integer (nullable = true)
 |-- dom: integer (nullable = true)
 |-- weekday: integer (nullable = true)
 |-- hour: integer (nullable = true)
 |-- Amount: float (nullable = true)
</code>```

In the end i try to perform k-means clustering

```<code>from pyspark.ml.clustering import KMeans
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler
feat_cols = ['CustomerID', 'Amount']
vec_assembler = VectorAssembler(inputCols = feat_cols, outputCol='features')
final_data = vec_assembler.transform(data2)
</code>```

The issue is that when i try to show the final_data, it gives me error message

```<code>final_data.show(5)

---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-43-b71ac3cae6de> in <module>
----> 1 scalerModel = scaler.fit(final_data)

C:\spark-2.4.0-bin-hadoop2.7\python\pyspark\ml\base.py in fit(self, dataset, params)
    130                 return self.copy(params)._fit(dataset)
    131             else:
--> 132                 return self._fit(dataset)
    133         else:
    134             raise ValueError("Params must be either a param map or a list/tuple of param maps, "

C:\spark-2.4.0-bin-hadoop2.7\python\pyspark\ml\wrapper.py in _fit(self, dataset)
    293
    294     def _fit(self, dataset):
--> 295         java_model = self._fit_java(dataset)
    296         model = self._create_model(java_model)
    297         return self._copyValues(model)

C:\spark-2.4.0-bin-hadoop2.7\python\pyspark\ml\wrapper.py in _fit_java(self, dataset)
    290         """
    291         self._transfer_params_to_java()
--> 292         return self._java_obj.fit(dataset._jdf)
    293
    294     def _fit(self, dataset):

C:\spark-2.4.0-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py in __call__(self, *args)
   1255         answer = self.gateway_client.send_command(command)
   1256         return_value = get_return_value(
-> 1257             answer, self.gateway_client, self.target_id, self.name)
   1258
   1259         for temp_arg in temp_args:

C:\spark-2.4.0-bin-hadoop2.7\python\pyspark\sql\utils.py in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

C:\spark-2.4.0-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o101.fit.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 5.0 failed 1 times, most recent failure: Lost task 1.0 in stage 5.0 (TID 19, localhost, executor driver): org.apache.spark.SparkException: Python worker failed to connect back.
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:170)
    at org.apache.spark.api.python.PythonWorkerFactory.create(PythonWorkerFactory.scala:97)
    at org.apache.spark.SparkEnv.createPythonWorker(SparkEnv.scala:117)
    at org.apache.spark.api.python.BasePythonRunner.compute(PythonRunner.scala:108)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:65)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:99)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:55)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketTimeoutException: Accept timed out
    at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
    at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135)
    at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:409)
    at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:199)
    at java.net.ServerSocket.implAccept(ServerSocket.java:545)
    at java.net.ServerSocket.accept(ServerSocket.java:513)
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:164)
    ... 45 more

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1887)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1875)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1874)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1874)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:926)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2108)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2057)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2046)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:737)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2061)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2158)
    at org.apache.spark.rdd.RDD$$anonfun$fold$1.apply(RDD.scala:1098)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
    at org.apache.spark.rdd.RDD.fold(RDD.scala:1092)
    at org.apache.spark.rdd.RDD$$anonfun$treeAggregate$1.apply(RDD.scala:1161)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
    at org.apache.spark.rdd.RDD.treeAggregate(RDD.scala:1137)
    at org.apache.spark.mllib.feature.StandardScaler.fit(StandardScaler.scala:57)
    at org.apache.spark.ml.feature.StandardScaler.fit(StandardScaler.scala:117)
    at org.apache.spark.ml.feature.StandardScaler.fit(StandardScaler.scala:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.spark.SparkException: Python worker failed to connect back.
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:170)
    at org.apache.spark.api.python.PythonWorkerFactory.create(PythonWorkerFactory.scala:97)
    at org.apache.spark.SparkEnv.createPythonWorker(SparkEnv.scala:117)
    at org.apache.spark.api.python.BasePythonRunner.compute(PythonRunner.scala:108)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:65)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:99)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:55)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    ... 1 more
Caused by: java.net.SocketTimeoutException: Accept timed out
    at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
    at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135)
    at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:409)
    at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:199)
    at java.net.ServerSocket.implAccept(ServerSocket.java:545)
    at java.net.ServerSocket.accept(ServerSocket.java:513)
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:164)
    ... 45 more
</code>```

答:
you must add to your  PYTHONPATH few things

```<code>export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH
export PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.8.2.1-src.zip:$PYTHONPATH
</code>```

Note: py4j-0.8.2.1-src.zip section depends on relaese you are using.

Title: k-means clustering in pyspark

Body:
I need to perform k-means clustering in my pre-processed dataset, but it gives me error message. Can anyone please help me?

Firstly i read my data in pyspark as below

import pyspark as spark
from pyspark.sql.types import *
from pyspark.sql import SparkSession
spark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()
dfSchema = StructType([
    StructField("InvoiceNo", StringType(), True),
    StructField("StockCode", StringType(), True),
    StructField("Description", StringType(), True),
    StructField("Quantity", IntegerType(), True),
    StructField("InvoiceDate", StringType(), True),
    StructField("UnitPrice", FloatType(), True),
    StructField("CustomerID", IntegerType(), True),
    StructField("Country", StringType(), True),
    StructField("Date", StringType(), True),
    StructField("Time", StringType(), True),
])
df = spark.read.csv('data.csv', header=True, schema=dfSchema, encoding='cp1252')

Then i converted my spark dataframe into pandas dataframe and did some data analysis

data  = df.toPandas()

After these i converted once again my pandas data frame into spark dataframe

data2 = spark.createDataFrame(Data2)
data2.printSchema()

'''Output

root
 |-- InvoiceNo: string (nullable = true)
 |-- StockCode: string (nullable = true)
 |-- Description: string (nullable = true)
 |-- Quantity: integer (nullable = true)
 |-- InvoiceDate: string (nullable = true)
 |-- UnitPrice: float (nullable = true)
 |-- CustomerID: integer (nullable = true)
 |-- Country: string (nullable = true)
 |-- Date: string (nullable = true)
 |-- Time: string (nullable = true)
 |-- year: integer (nullable = true)
 |-- month: integer (nullable = true)
 |-- dom: integer (nullable = true)
 |-- weekday: integer (nullable = true)
 |-- hour: integer (nullable = true)
 |-- Amount: float (nullable = true)

In the end i try to perform k-means clustering

from pyspark.ml.clustering import KMeans
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler
feat_cols = ['CustomerID', 'Amount']
vec_assembler = VectorAssembler(inputCols = feat_cols, outputCol='features')
final_data = vec_assembler.transform(data2)

The issue is that when i try to show the final_data, it gives me error message

final_data.show(5)

---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-43-b71ac3cae6de> in <module>
----> 1 scalerModel = scaler.fit(final_data)

C:\spark-2.4.0-bin-hadoop2.7\python\pyspark\ml\base.py in fit(self, dataset, params)
    130                 return self.copy(params)._fit(dataset)
    131             else:
--> 132                 return self._fit(dataset)
    133         else:
    134             raise ValueError("Params must be either a param map or a list/tuple of param maps, "

C:\spark-2.4.0-bin-hadoop2.7\python\pyspark\ml\wrapper.py in _fit(self, dataset)
    293
    294     def _fit(self, dataset):
--> 295         java_model = self._fit_java(dataset)
    296         model = self._create_model(java_model)
    297         return self._copyValues(model)

C:\spark-2.4.0-bin-hadoop2.7\python\pyspark\ml\wrapper.py in _fit_java(self, dataset)
    290         """
    291         self._transfer_params_to_java()
--> 292         return self._java_obj.fit(dataset._jdf)
    293
    294     def _fit(self, dataset):

C:\spark-2.4.0-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py in __call__(self, *args)
   1255         answer = self.gateway_client.send_command(command)
   1256         return_value = get_return_value(
-> 1257             answer, self.gateway_client, self.target_id, self.name)
   1258
   1259         for temp_arg in temp_args:

C:\spark-2.4.0-bin-hadoop2.7\python\pyspark\sql\utils.py in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

C:\spark-2.4.0-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o101.fit.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 5.0 failed 1 times, most recent failure: Lost task 1.0 in stage 5.0 (TID 19, localhost, executor driver): org.apache.spark.SparkException: Python worker failed to connect back.
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:170)
    at org.apache.spark.api.python.PythonWorkerFactory.create(PythonWorkerFactory.scala:97)
    at org.apache.spark.SparkEnv.createPythonWorker(SparkEnv.scala:117)
    at org.apache.spark.api.python.BasePythonRunner.compute(PythonRunner.scala:108)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:65)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:99)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:55)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketTimeoutException: Accept timed out
    at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
    at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135)
    at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:409)
    at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:199)
    at java.net.ServerSocket.implAccept(ServerSocket.java:545)
    at java.net.ServerSocket.accept(ServerSocket.java:513)
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:164)
    ... 45 more

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1887)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1875)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1874)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1874)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:926)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2108)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2057)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2046)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:737)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2061)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2158)
    at org.apache.spark.rdd.RDD$$anonfun$fold$1.apply(RDD.scala:1098)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
    at org.apache.spark.rdd.RDD.fold(RDD.scala:1092)
    at org.apache.spark.rdd.RDD$$anonfun$treeAggregate$1.apply(RDD.scala:1161)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
    at org.apache.spark.rdd.RDD.treeAggregate(RDD.scala:1137)
    at org.apache.spark.mllib.feature.StandardScaler.fit(StandardScaler.scala:57)
    at org.apache.spark.ml.feature.StandardScaler.fit(StandardScaler.scala:117)
    at org.apache.spark.ml.feature.StandardScaler.fit(StandardScaler.scala:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.spark.SparkException: Python worker failed to connect back.
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:170)
    at org.apache.spark.api.python.PythonWorkerFactory.create(PythonWorkerFactory.scala:97)
    at org.apache.spark.SparkEnv.createPythonWorker(SparkEnv.scala:117)
    at org.apache.spark.api.python.BasePythonRunner.compute(PythonRunner.scala:108)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:65)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:99)
    at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:55)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    ... 1 more
Caused by: java.net.SocketTimeoutException: Accept timed out
    at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
    at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135)
    at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:409)
    at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:199)
    at java.net.ServerSocket.implAccept(ServerSocket.java:545)
    at java.net.ServerSocket.accept(ServerSocket.java:513)
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:164)
    ... 45 more

Body:
you must add to your  PYTHONPATH few things

export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH
export PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.8.2.1-src.zip:$PYTHONPATH

Note: py4j-0.8.2.1-src.zip section depends on relaese you are using.


来源: stackexchange

问:
How to set radio button text dynamically using Reactive form? and and selected *radio button value and question title * onSubmit
I've added list of questions(2)  and  list of choices(3 or 4) dynamically using reactive form-array .

question 1)
How to set radio button text dynamically using form array?

question 2)
 and now I'm trying to get only selected choice Id respect to question Id  onSubmit method. How can I do that?

I tried code pasted below, please help me .

```<code>export class HomeComponent implements OnInit {
  survey: FormGroup;
  user: User[] = [
    {
      id: 1,
      question: 'Question 1',
      choice: [
        {
          ChoceId: 1,
          Value: '1choice 1'
        },
        {
          ChoceId: 2,
          Value: '1choice 2'
        },
        {
          ChoceId: 3,
          Value: '1choice 3'
        },
        {
          ChoceId: 4,
          Value: '1choice 4'
        }

      ]
    }, {
      id: 2,
      question: 'Question 2',
      choice: [
        {
          ChoceId: 1,
          Value: '2choice 1'
        },
        {
          ChoceId: 2,
          Value: '2choice 2'
        },
        {
          ChoceId: 3,
          Value: '2choice 3'
        }
      ]
    }, {
      id: 3,
      question: 'Question 3',
      choice: [
        {
          ChoceId: 1,
          Value: '3choice 1'
        },
        {
          ChoceId: 2,
          Value: '3choice 2'
        },
        {
          ChoceId: 3,
          Value: '3choice 3'
        }
      ]
    }
    , {
      id: 4,
      question: 'Question 4',
      choice: [
        {
          ChoceId: 1,
          Value: '4choice 1'
        },
        {
          ChoceId: 2,
          Value: '4choice 2'
        },
        {
          ChoceId: 3,
          Value: '4choice 3'
        },
        {
          ChoceId: 4,
          Value: '4choice 4'
        }
      ]
    }
    , {
      id: 5,
      question: 'Question 5',
      choice: [
        {
          ChoceId: 1,
          Value: '5choice 1'
        },
        {
          ChoceId: 2,
          Value: '5choice 2'
        },
        {
          ChoceId: 3,
          Value: '5choice 3'
        },
        {
          ChoceId: 4,
          Value: '5choice 4'
        }
      ]
    },
    {
      id: 6,
      question: 'Question 6',
      choice: [
        {
          ChoceId: 1,
          Value: '6choice 1'
        },
        {
          ChoceId: 2,
          Value: '6choice 2'
        },
        {
          ChoceId: 3,
          Value: '6choice 3'
        },
        {
          ChoceId: 4,
          Value: '6choice 4'
        }
      ]
    },
    {
      id: 7,
      question: 'Question 7',
      choice: [
        {
          ChoceId: 1,
          Value: '7choice 1'
        },
        {
          ChoceId: 2,
          Value: '7choice 2'
        },
        {
          ChoceId: 3,
          Value: '7choice 3'
        },
        {
          ChoceId: 4,
          Value: '7choice 4'
        }
        ,
        {
          ChoceId: 5,
          Value: '7choice 4'
        }
      ]
    }
  ]

  constructor() {

  }

  ngOnInit() {

    this.survey = new FormGroup({
      sections: new FormArray([
        this.initSection(),
      ]),
    });

    for (let i = 0; i < this.user.length; i++) {

      this.addQuestion(0, this.user[i].question)
        this.add(0, i+1,this.user[i].choice);
        this.removeOption(0, i, 0)
       }
    this.removeQuestion(0);
  }

  initSection() {
    return new FormGroup({
      questions: new FormArray([
        this.initQuestion('questionTitle')
      ])
    });
  }

  initQuestion(val: string) {
    return new FormGroup({
      questionTitle: new FormControl(val),
      options: new FormArray([
        this.initOptions('')
      ])
    });
  }

  initOptions(val: string) {
    return new FormGroup({
      optionTitle: new FormControl(val)
    });
  }

  addSection() {
    const control = <FormArray>this.survey.get('sections');
    control.push(this.initSection());
  }

  addQuestion(j, val: string) {
    console.log(j);
    const control = <FormArray>this.survey.get('sections').controls[j].get('questions');
    control.push(this.initQuestion(val));

  }

  add(i, j, choice: Choices[]) {

    const control = <FormArray>this.survey.get('sections').controls[i].get('questions').controls[j].get('options');
    if (choice) {
       for (j = i; j < choice.length; j++) {
        control.push(this.initOptions(choice[j] .Value));
      }
    }else{
      control.push(this.initOptions(''));
    }
  }

  getSections(form) {
    //console.log(form.get('sections').controls);
    return form.controls.sections.controls;
  }
  getQuestions(form) {
    //console.log(form.controls.questions.controls);
    return form.controls.questions.controls;
  }
  getOptions(form) {
    //console.log(form.get('options').controls);
    return form.controls.options.controls;

  }

  removeQuestion(j) {
    const control = <FormArray>this.survey.get('sections').controls[j].get('questions');
    control.removeAt(j);
  }

  removeSection(i) {
    const control = <FormArray>this.survey.get('sections');
    control.removeAt(i);

  }

  removeOption(i, j, k) {
    // debugger;
    console.log(i, j, k);
    const control = <FormArray>this.survey.get(['sections', i, 'questions', j, 'options']); // also try this new syntax
    control.removeAt(k);
  }

  remove(i, j) {
    const control = <FormArray>this.survey.get(['sections', i, 'questions', j, 'options']);
    control.removeAt(0);
    control.controls = [];
  }

  onSubmit(form:NgForm) {
    debugger;

    console.log(this.survey.value.optionTitle);
    console.log(form);

  }

}
</code>```

here is the html I tried

<form [formGroup]="survey" novalidate (ngSubmit)="onSubmit(survey)">

User likes and choices

              <input type="text" placeholder="Untitled Question" formControlName="questionTitle">

            {{ survey.errors }}

              Add_Option||
              Remove_whole_options

                   <input type="radio" id="{{ 'acceptable' + i}}" >
                  <input type="text" placeholder="Option 1" formControlName="optionTitle">

                   1" (click)="removeOption(i,j,k)">Remove_Option

              Add Question...
               1" (click)="removeQuestion(i)">Remove Question

        <button (click)="addSection()" class="point">Add Section </button>
         1" (click)="removeSection(i)">Remove Section

    <button type="submit">Get-Link</button>
  </form>

  ``` {{survey.value | json}} ```
```

Here is my output:

答:
If i understood your question correctly. In order to populate the values of the radio button dynamically use below code.

```<code>      dataSource = User[]; // you have to create a user class
      ngonInit() {
         this.populateUsers();
      }
        populateUsers() {
        this.dataSource = [];
        this.userService.getUserData().subscribe( resp => {
        resp.forEach(element => {
          console.log(element);
        const config = new  User(element.choiceId, element.Value); // User class have
             constructor taking these values
          this.dataSource.push(config);
      });
     }
</code>```

Below is the sample of dropdown List , you can do something similar for radio button

```<code> <select  formControlName= "user"  class="form-control"
                           (change)="selectUserOption($event.target.value);">
                             <option  [value]="d.value" *ngFor="let d of dataSource">
                                      {{d.ChoiceId}}
                                </option>
                          </select>
</code>```

here is the (change) event for the dropdown and then u can read the value of the selected button.

ContentLicense: CC BY-SA 4.0

Body:
I've added list of questions(2)  and  list of choices(3 or 4) dynamically using reactive form-array .

question 1)
How to set radio button text dynamically using form array?

question 2)
 and now I'm trying to get only selected choice Id respect to question Id  onSubmit method. How can I do that?

I tried code pasted below, please help me .

export class HomeComponent implements OnInit {
  survey: FormGroup;
  user: User[] = [
    {
      id: 1,
      question: 'Question 1',
      choice: [
        {
          ChoceId: 1,
          Value: '1choice 1'
        },
        {
          ChoceId: 2,
          Value: '1choice 2'
        },
        {
          ChoceId: 3,
          Value: '1choice 3'
        },
        {
          ChoceId: 4,
          Value: '1choice 4'
        }

      ]
    }, {
      id: 2,
      question: 'Question 2',
      choice: [
        {
          ChoceId: 1,
          Value: '2choice 1'
        },
        {
          ChoceId: 2,
          Value: '2choice 2'
        },
        {
          ChoceId: 3,
          Value: '2choice 3'
        }
      ]
    }, {
      id: 3,
      question: 'Question 3',
      choice: [
        {
          ChoceId: 1,
          Value: '3choice 1'
        },
        {
          ChoceId: 2,
          Value: '3choice 2'
        },
        {
          ChoceId: 3,
          Value: '3choice 3'
        }
      ]
    }
    , {
      id: 4,
      question: 'Question 4',
      choice: [
        {
          ChoceId: 1,
          Value: '4choice 1'
        },
        {
          ChoceId: 2,
          Value: '4choice 2'
        },
        {
          ChoceId: 3,
          Value: '4choice 3'
        },
        {
          ChoceId: 4,
          Value: '4choice 4'
        }
      ]
    }
    , {
      id: 5,
      question: 'Question 5',
      choice: [
        {
          ChoceId: 1,
          Value: '5choice 1'
        },
        {
          ChoceId: 2,
          Value: '5choice 2'
        },
        {
          ChoceId: 3,
          Value: '5choice 3'
        },
        {
          ChoceId: 4,
          Value: '5choice 4'
        }
      ]
    },
    {
      id: 6,
      question: 'Question 6',
      choice: [
        {
          ChoceId: 1,
          Value: '6choice 1'
        },
        {
          ChoceId: 2,
          Value: '6choice 2'
        },
        {
          ChoceId: 3,
          Value: '6choice 3'
        },
        {
          ChoceId: 4,
          Value: '6choice 4'
        }
      ]
    },
    {
      id: 7,
      question: 'Question 7',
      choice: [
        {
          ChoceId: 1,
          Value: '7choice 1'
        },
        {
          ChoceId: 2,
          Value: '7choice 2'
        },
        {
          ChoceId: 3,
          Value: '7choice 3'
        },
        {
          ChoceId: 4,
          Value: '7choice 4'
        }
        ,
        {
          ChoceId: 5,
          Value: '7choice 4'
        }
      ]
    }
  ]

  constructor() {

  }

  ngOnInit() {

    this.survey = new FormGroup({
      sections: new FormArray([
        this.initSection(),
      ]),
    });

    for (let i = 0; i < this.user.length; i++) {

      this.addQuestion(0, this.user[i].question)
        this.add(0, i+1,this.user[i].choice);
        this.removeOption(0, i, 0)
       }
    this.removeQuestion(0);
  }

  initSection() {
    return new FormGroup({
      questions: new FormArray([
        this.initQuestion('questionTitle')
      ])
    });
  }

  initQuestion(val: string) {
    return new FormGroup({
      questionTitle: new FormControl(val),
      options: new FormArray([
        this.initOptions('')
      ])
    });
  }

  initOptions(val: string) {
    return new FormGroup({
      optionTitle: new FormControl(val)
    });
  }

  addSection() {
    const control = <FormArray>this.survey.get('sections');
    control.push(this.initSection());
  }

  addQuestion(j, val: string) {
    console.log(j);
    const control = <FormArray>this.survey.get('sections').controls[j].get('questions');
    control.push(this.initQuestion(val));

  }

  add(i, j, choice: Choices[]) {

    const control = <FormArray>this.survey.get('sections').controls[i].get('questions').controls[j].get('options');
    if (choice) {
       for (j = i; j < choice.length; j++) {
        control.push(this.initOptions(choice[j] .Value));
      }
    }else{
      control.push(this.initOptions(''));
    }
  }

  getSections(form) {
    //console.log(form.get('sections').controls);
    return form.controls.sections.controls;
  }
  getQuestions(form) {
    //console.log(form.controls.questions.controls);
    return form.controls.questions.controls;
  }
  getOptions(form) {
    //console.log(form.get('options').controls);
    return form.controls.options.controls;

  }

  removeQuestion(j) {
    const control = <FormArray>this.survey.get('sections').controls[j].get('questions');
    control.removeAt(j);
  }

  removeSection(i) {
    const control = <FormArray>this.survey.get('sections');
    control.removeAt(i);

  }

  removeOption(i, j, k) {
    // debugger;
    console.log(i, j, k);
    const control = <FormArray>this.survey.get(['sections', i, 'questions', j, 'options']); // also try this new syntax
    control.removeAt(k);
  }

  remove(i, j) {
    const control = <FormArray>this.survey.get(['sections', i, 'questions', j, 'options']);
    control.removeAt(0);
    control.controls = [];
  }

  onSubmit(form:NgForm) {
    debugger;

    console.log(this.survey.value.optionTitle);
    console.log(form);

  }

}

here is the html I tried

<form [formGroup]="survey" novalidate (ngSubmit)="onSubmit(survey)">

User likes and choices

              <input type="text" placeholder="Untitled Question" formControlName="questionTitle">

            {{ survey.errors }}

              Add_Option||
              Remove_whole_options

                   <input type="radio" id="{{ 'acceptable' + i}}" >
                  <input type="text" placeholder="Option 1" formControlName="optionTitle">

                   1" (click)="removeOption(i,j,k)">Remove_Option

              Add Question...
               1" (click)="removeQuestion(i)">Remove Question

        <button (click)="addSection()" class="point">Add Section </button>
         1" (click)="removeSection(i)">Remove Section

    <button type="submit">Get-Link</button>
  </form>

 {{survey.value | json}}

Here is my output:

Body:
If i understood your question correctly. In order to populate the values of the radio button dynamically use below code.

      dataSource = User[]; // you have to create a user class
      ngonInit() {
         this.populateUsers();
      }
        populateUsers() {
        this.dataSource = [];
        this.userService.getUserData().subscribe( resp => {
        resp.forEach(element => {
          console.log(element);
        const config = new  User(element.choiceId, element.Value); // User class have
             constructor taking these values
          this.dataSource.push(config);
      });
     }

Below is the sample of dropdown List , you can do something similar for radio button

 <select  formControlName= "user"  class="form-control"
                           (change)="selectUserOption($event.target.value);">
                             <option  [value]="d.value" *ngFor="let d of dataSource">
                                      {{d.ChoiceId}}
                                </option>
                          </select>

here is the (change) event for the dropdown and then u can read the value of the selected button.


问:
Hide column from Query
I don't want rank column but still, want the data in the same format by applying dense rank.

```<code>select ename,position,deptno,dense_rank() over(partition by deptno order by ename asc) as rank from emp  where deptno in ('10','30');
</code>```

答:
Why do you need the rank just order by deptno first then ename.

```<code>SELECT ename,position,deptno,
FROM emp
WHERE deptno in ('10','30')
ORDER BY DeptNo, Ename
</code>```

Using the analytical function two options derived table or CTE

Derived table/inline view.

```<code>SELECT ename,position,deptno
FROM (select ename,position,deptno,dense_rank() over(partition by deptno order by ename asc) as rank
      from emp
      where deptno in ('10','30')) Z
ORDER BY deptNo, rank
</code>```

Common Table  Expression (CTE):

```<code>with Z AS (SELECT ename,position,deptno
                , dense_rank() over(partition by deptno order by ename asc) as rank
          FROM emp
          WHERE deptno in ('10','30'))
SELECT ename,position,deptno
FROM z
ORDER BY deptno, rank
</code>```

Both these last 2 techniques simply avoid exposing the rank function to the outer query in which the results are returned.   They are "Tricks" and sub-optimal execution time.  unless there's a specific reason to have the rank data; I'd not use it.

Title: Hide column from Query

Body:
I don't want rank column but still, want the data in the same format by applying dense rank.

select ename,position,deptno,dense_rank() over(partition by deptno order by ename asc) as rank from emp  where deptno in ('10','30');

Body:
Why do you need the rank just order by deptno first then ename.

SELECT ename,position,deptno,
FROM emp
WHERE deptno in ('10','30')
ORDER BY DeptNo, Ename

Using the analytical function two options derived table or CTE

Derived table/inline view.

SELECT ename,position,deptno
FROM (select ename,position,deptno,dense_rank() over(partition by deptno order by ename asc) as rank
      from emp
      where deptno in ('10','30')) Z
ORDER BY deptNo, rank

Common Table  Expression (CTE):

with Z AS (SELECT ename,position,deptno
                , dense_rank() over(partition by deptno order by ename asc) as rank
          FROM emp
          WHERE deptno in ('10','30'))
SELECT ename,position,deptno
FROM z
ORDER BY deptno, rank

Both these last 2 techniques simply avoid exposing the rank function to the outer query in which the results are returned.   They are "Tricks" and sub-optimal execution time.  unless there's a specific reason to have the rank data; I'd not use it.


问:
How to delete folder from git history permanently using BFG
I am using BFG to delete two of my folders. They were tracked from the inception of the repo. The reason to delete was those folder contains binary and other txt file that we no longer need. But When I try to delete those two folder, one gets deleted but the other one still ligers around.

I created my dummy repo and did some commits to recreate the problem.
I assume myRepo.git is clean repo to begin with.

Function I used to delete folders is :
java -jar bfg-1.13.0.jar --no-blob-protection --delete-folders "{system1, system2}" myRepo.git

```<code>#!/bin/bash

BUILD(){
  git clone https://github.com/xxxx/myRepo.git
  cd myRepo
  echo "Jpt test1" > jpt1.txt
  echo "Jpt test2" > jpt2.txt
  echo "Jpt test3" > jpt3.txt

  git add jpt1.txt jpt2.txt jpt3.txt
  git commit -m "first commit"
  git push origin master
  ######
  mkdir system1
  cd system1
  mkfile 14m outputfile1.out
  mkfile 14m outputfile2.out
  echo "Jpt test1" > sysjpt1.txt
  echo "Jpt test2" > sysjpt2.txt
  echo "Jpt test3" > sysjpt3.txt
  cd ..
  ######
  mkdir system2
  cd system2
  mkfile 14m outputfile1.out
  mkfile 14m outputfile2.out
  cd ..

  git add system1 system2
  git commit -m "tracking large file"
  git push origin master
  cd ..

  ##### Call function BFG which does BFG stuff.
  BFG

}

BFG(){
  # run bfg and let git clean history

  git clone --mirror https://github.com/xxxx/myRepo.git

  java -jar bfg-1.13.0.jar --no-blob-protection --delete-folders "{system1, system2}" myRepo.git

  cd myRepo.git
  git reflog expire --expire=now --all && git gc --prune=now --aggressive
  git push

  cd ..
  mkdir test_new
  cd test_new
  git clone https://github.com/xxx/myRepo.git
  cd myRepo
  ls

}

BUILD
</code>```

When I clone after cleaning and do ls on it. I get
jpt1.txt jpt2.txt jpt3.txt system2. See how system2 folder is still there.

答:
As you tested from my suggestions in the comments above, the problem is with the space in "{system1, system2}". When that expression is processed, it expands it to "system1" and " system2", with a space in front of system2, which is not what you want.

You can run the process in two commands, once with system1 and once with system2, or simply remove the space, and things will work.

Interestingly, the expansion of {a,b} appears to be done by bfg itself, not by bash: the quotes tell bash to pass that string literally, so although this looks like bash syntax it actually isn't a bash expansion.

Body:
I am using BFG to delete two of my folders. They were tracked from the inception of the repo. The reason to delete was those folder contains binary and other txt file that we no longer need. But When I try to delete those two folder, one gets deleted but the other one still ligers around.

I created my dummy repo and did some commits to recreate the problem.
I assume myRepo.git is clean repo to begin with.

Function I used to delete folders is :
java -jar bfg-1.13.0.jar --no-blob-protection --delete-folders "{system1, system2}" myRepo.git

#!/bin/bash

BUILD(){
  git clone https://github.com/xxxx/myRepo.git
  cd myRepo
  echo "Jpt test1" > jpt1.txt
  echo "Jpt test2" > jpt2.txt
  echo "Jpt test3" > jpt3.txt

  git add jpt1.txt jpt2.txt jpt3.txt
  git commit -m "first commit"
  git push origin master
  ######
  mkdir system1
  cd system1
  mkfile 14m outputfile1.out
  mkfile 14m outputfile2.out
  echo "Jpt test1" > sysjpt1.txt
  echo "Jpt test2" > sysjpt2.txt
  echo "Jpt test3" > sysjpt3.txt
  cd ..
  ######
  mkdir system2
  cd system2
  mkfile 14m outputfile1.out
  mkfile 14m outputfile2.out
  cd ..

  git add system1 system2
  git commit -m "tracking large file"
  git push origin master
  cd ..

  ##### Call function BFG which does BFG stuff.
  BFG

}

BFG(){
  # run bfg and let git clean history

  git clone --mirror https://github.com/xxxx/myRepo.git

  java -jar bfg-1.13.0.jar --no-blob-protection --delete-folders "{system1, system2}" myRepo.git

  cd myRepo.git
  git reflog expire --expire=now --all && git gc --prune=now --aggressive
  git push

  cd ..
  mkdir test_new
  cd test_new
  git clone https://github.com/xxx/myRepo.git
  cd myRepo
  ls

}

BUILD

When I clone after cleaning and do ls on it. I get
jpt1.txt jpt2.txt jpt3.txt system2. See how system2 folder is still there.


问:
When using jQuery's ".nextAll()", how would i make "$(this)" equal the current element?
im trying to get an element, then every element after that make the placeholder attribute of #taskid the current value - 1

this is what im currently working with:

```<code>$(this).nextAll('div').find('#taskid').attr('placeholder', ((parseInt($(this)
    .find('#taskid').attr('placeholder')) - 1).toString()))
</code>```

html:

```<code><div id="i0HYh" class="task" select="yes" style="background-color: rgb(240, 239, 255);">
  <input type="text" name="taskid" placeholder="1" readonly="" id="taskid">
  <input type="text" name="email1" placeholder="sdf" readonly="">
  <input type="text" name="taskproxy" id="esfes" placeholder="N/A" readonly="">
  <div id="headlessbox">
    <p>t</p>
  </div>
  <input type="text" name="status" placeholder="Idle" readonly="">
</div>
</code>```

The above jquery line works, it just changes the placeholder value to the first elements value - 1

for example, if the first elements value was 1, the rest of them would be 0

example of the placeholders right now (before running above code):
1
2
3
4
5
6

example of the placeholders right now (after running above code):
1
0
0
0
0
0

what i want (before running above code):
1
2
3
4
5
6

what i want (after running above code):
1
1
2
3
4
5

(sorry if this makes no sense, im trying my best to explain :( )

答:
```<code>$(this).nextAll('div').each(function() {
    // $(this) refers to each div in the array collected by nextAll()
    return $(this).find('#taskid').attr('placeholder', ((parseInt($(this)
        .find('#taskid').attr('placeholder')) - 1).toString()));
});
</code>```

For better readability:

```<code>$(this).nextAll('div').each(function() {
    let phText= parseInt($(this).find('#taskid').attr('placeholder') - 1).toString();

    return $(this).find('#taskid').attr('placeholder', phText);
});
</code>```

Body:
im trying to get an element, then every element after that make the placeholder attribute of #taskid the current value - 1

this is what im currently working with:

$(this).nextAll('div').find('#taskid').attr('placeholder', ((parseInt($(this)
    .find('#taskid').attr('placeholder')) - 1).toString()))

html:

  <input type="text" name="taskid" placeholder="1" readonly="" id="taskid">
  <input type="text" name="email1" placeholder="sdf" readonly="">
  <input type="text" name="taskproxy" id="esfes" placeholder="N/A" readonly="">

t

  <input type="text" name="status" placeholder="Idle" readonly="">

The above jquery line works, it just changes the placeholder value to the first elements value - 1

for example, if the first elements value was 1, the rest of them would be 0

example of the placeholders right now (before running above code):
1
2
3
4
5
6

example of the placeholders right now (after running above code):
1
0
0
0
0
0

what i want (before running above code):
1
2
3
4
5
6

what i want (after running above code):
1
1
2
3
4
5

(sorry if this makes no sense, im trying my best to explain :( )

Body:
$(this).nextAll('div').each(function() {
    // $(this) refers to each div in the array collected by nextAll()
    return $(this).find('#taskid').attr('placeholder', ((parseInt($(this)
        .find('#taskid').attr('placeholder')) - 1).toString()));
});

For better readability:

$(this).nextAll('div').each(function() {
    let phText= parseInt($(this).find('#taskid').attr('placeholder') - 1).toString();

    return $(this).find('#taskid').attr('placeholder', phText);
});


问:
Optimise a simple double for loop for IE
```<code>array.sort(function(left, right) {
    return index(otherArray, left) < index(otherArray, right);
});
</code>```

This is O(len(array) ^ 2) so for a reasonable size array of len = 1000 this takes constant * 1 million operations which easily overshoots the IE 5 million operators cap.

Thus IE throws a script is taking too long even though this is fast.

The problem is that IE does not have it's own Array.prototype.indexOf so I can't reduce the operation count down to O(len(array) and rely instead end up using a double for loop instead of a single for loop.

I considered array.join and using String.prototype.indexOf but the objects in the arrays are DOM elements and you can't convert them to a string (easily).

Telling IE users to remove this default cap is not an option.

答:
I can think of two possible solutions to this problem: one of which will work everywhere, the other which is entirely IE-proprietary (and I expect doesn't work in IE9, but that supports Array.prototype.indexOf, so that's a non-issue).

The first, simpler, solution is to just set a property on each HTMLElement of the desired order and sort by that. If you care about the desired order persisting, you'll have to make sure the HTMLElement objects don't get garbage collected, so you'll have to keep references to them around (it's probably simplest to just create an array in the global scope for it).

The IE-only solution is to do something similar to what @maclema was proposing, using a lookup object, and HTMLElement.uniqueID:

```<code>var otherArrayLookup = {};
for (var i=0; i < otherArray.length; i++) {
    otherArrayLookup[otherArray[i].uniqueID] = i;
}

array.sort(function(left, right) {
    return otherArrayLookup[left.uniqueID] < otherArrayLookup[right.uniqueID];
});
</code>```

You'll want to add some branches in there (don't put any within the callback function, but use different callback functions) for the Array.prototype.indexOf supported case, the HTMLElement.uniqueID supported case, and the none-of-the-above case.

ContentLicense: CC BY-SA 3.0

Body:
array.sort(function(left, right) {
    return index(otherArray, left) < index(otherArray, right);
});

This is O(len(array) ^ 2) so for a reasonable size array of len = 1000 this takes constant * 1 million operations which easily overshoots the IE 5 million operators cap.

Thus IE throws a script is taking too long even though this is fast.

The problem is that IE does not have it's own Array.prototype.indexOf so I can't reduce the operation count down to O(len(array) and rely instead end up using a double for loop instead of a single for loop.

I considered array.join and using String.prototype.indexOf but the objects in the arrays are DOM elements and you can't convert them to a string (easily).

Telling IE users to remove this default cap is not an option.

Body:
I can think of two possible solutions to this problem: one of which will work everywhere, the other which is entirely IE-proprietary (and I expect doesn't work in IE9, but that supports Array.prototype.indexOf, so that's a non-issue).

The first, simpler, solution is to just set a property on each HTMLElement of the desired order and sort by that. If you care about the desired order persisting, you'll have to make sure the HTMLElement objects don't get garbage collected, so you'll have to keep references to them around (it's probably simplest to just create an array in the global scope for it).

The IE-only solution is to do something similar to what @maclema was proposing, using a lookup object, and HTMLElement.uniqueID:

var otherArrayLookup = {};
for (var i=0; i < otherArray.length; i++) {
    otherArrayLookup[otherArray[i].uniqueID] = i;
}

array.sort(function(left, right) {
    return otherArrayLookup[left.uniqueID] < otherArrayLookup[right.uniqueID];
});

You'll want to add some branches in there (don't put any within the callback function, but use different callback functions) for the Array.prototype.indexOf supported case, the HTMLElement.uniqueID supported case, and the none-of-the-above case.


问:
How to <select> only none existing users from a case. SQL SELECT
Working on selecting all users into an html <select> that doesn't exist in it already.

I am working on a "case" website where I can put users on cases. Users can be put on multiple cases at once. I am making a html <select> with all the users I can add to the case and it is important that already existing users on that case aren't shown.

I have 3 SQL tables. Users, Cases, and Junc_jobs. Junc_Jobs works as a many to many relations to connect users and cases. All the users that I want to select are fk_role > 1.

```<code>USERS
+-------+------------+----------+
|  id   | firstName  | fk_case  |
+-------+------------+----------+
|  05   | Rasmus     | 57       |
|  06   | Ulrik      | 57       |
|  10   | Nick       | 59       |
|  12   | Lisa       | 59       |
|  22   | Marco      | 65       |
|  23   | Frederik   | 63       |
+-------+------------+----------+

CASES
+-------+------------+
|  id   | caseName   |
+-------+------------+
|  57   | case 1     |
|  59   | case 2     |
|  63   | case 3     |
|  64   | case 4     |
|  65   | case 5     |
+-------+------------+

JUNC_JOBS
+-------+------------+--------------+
|  id   | fk_case    | fk_employee  |
+-------+------------+--------------+
|  1    | 57         | 5            |
|  2    | 59         | 5            |
|  3    | 64         | 23           |
|  4    | 65         | 23           |
|  5    | 65         | 22           |
|  6    | 66         | 10           |
|  7    | 61         | 22           |
|  8    | 60         | 5            |
|  9    | 63         | 5            |
|  10   | 66         | 22           |
|  11   | 62         | 12           |
+-------+------------+--------------+
</code>```

So far I've tried doing something like this:

SELECT users.id, users.firstName, users.lastName, junc_jobs.fk_case FROM users
LEFT JOIN junc_jobs ON users.id = junc_jobs.fk_employee
WHERE (fk_case IS NULL AND users.fk_role > 1) OR (fk_case != 66 AND  users.fk_role > 1)
ORDER BY firstName
```

<p>BUT if <code>junc_jobs</code> contain users with multiple cases it stops working. We get something like this:</p>

```+-------+------------+----------+
|  id   | firstName  | fk_case  |
+-------+------------+----------+
|  06   | Ulrik      | 57       |
|  05   | Rasmus     | 57       |
|  12   | Lisa       | 59       |
|  10   | Nick       | 59       |
|  05   | Rasmus     | 59       |
|  23   | Frederik   | 63       |
|  06   | Macro      | 63       |
|  23   | Frederik   | 64       |
|  23   | Frederik   | 65       |
|  22   | Marco      | 65       |
|  10   | Nick       | 65       |
+-------+------------+----------+
```

As you can see, users that are on fk_case = 66 is removed, but if that user is already on other cases they still get shown. User with id = 22 is on fk_case 66 and this user removed from the list completely.

I tried using GROUP BY ID to only show one of each users, but the users that are already on the case and have other cases, is shown too.

答:
I dont think you need fk_case for the SELECT, because if user is on other projects doesn't matter. Only matter he isn't on the current one.

```<code>SELECT DISTINCT users.id, users.firstName, users.lastName
FROM users
LEFT JOIN junc_jobs ON users.id = junc_jobs.fk_employee
WHERE users.fk_role > 1
  AND (fk_case IS NULL OR fk_case != 66)
ORDER BY firstName
</code>```

Also not sure about what junc_jobs does, but maybe something like this may help

```<code>SELECT u.*
FROM users u
WHERE u.fk_role > 1
  AND NOT EXISTS ( SELECT 1
                   FROM junc_jobs j
                   WHERE j.fk_employee = u.id and j.fk_case = 66)
</code>```

Body:
Working on selecting all users into an html <select> that doesn't exist in it already.

I am working on a "case" website where I can put users on cases. Users can be put on multiple cases at once. I am making a html <select> with all the users I can add to the case and it is important that already existing users on that case aren't shown.

I have 3 SQL tables. Users, Cases, and Junc_jobs. Junc_Jobs works as a many to many relations to connect users and cases. All the users that I want to select are fk_role > 1.

USERS
+-------+------------+----------+
|  id   | firstName  | fk_case  |
+-------+------------+----------+
|  05   | Rasmus     | 57       |
|  06   | Ulrik      | 57       |
|  10   | Nick       | 59       |
|  12   | Lisa       | 59       |
|  22   | Marco      | 65       |
|  23   | Frederik   | 63       |
+-------+------------+----------+

CASES
+-------+------------+
|  id   | caseName   |
+-------+------------+
|  57   | case 1     |
|  59   | case 2     |
|  63   | case 3     |
|  64   | case 4     |
|  65   | case 5     |
+-------+------------+

JUNC_JOBS
+-------+------------+--------------+
|  id   | fk_case    | fk_employee  |
+-------+------------+--------------+
|  1    | 57         | 5            |
|  2    | 59         | 5            |
|  3    | 64         | 23           |
|  4    | 65         | 23           |
|  5    | 65         | 22           |
|  6    | 66         | 10           |
|  7    | 61         | 22           |
|  8    | 60         | 5            |
|  9    | 63         | 5            |
|  10   | 66         | 22           |
|  11   | 62         | 12           |
+-------+------------+--------------+

So far I've tried doing something like this:

SELECT users.id, users.firstName, users.lastName, junc_jobs.fk_case FROM users
LEFT JOIN junc_jobs ON users.id = junc_jobs.fk_employee
WHERE (fk_case IS NULL AND users.fk_role > 1) OR (fk_case != 66 AND  users.fk_role > 1)
ORDER BY firstName

BUT if junc_jobs contain users with multiple cases it stops working. We get something like this:

+-------+------------+----------+
|  id   | firstName  | fk_case  |
+-------+------------+----------+
|  06   | Ulrik      | 57       |
|  05   | Rasmus     | 57       |
|  12   | Lisa       | 59       |
|  10   | Nick       | 59       |
|  05   | Rasmus     | 59       |
|  23   | Frederik   | 63       |
|  06   | Macro      | 63       |
|  23   | Frederik   | 64       |
|  23   | Frederik   | 65       |
|  22   | Marco      | 65       |
|  10   | Nick       | 65       |
+-------+------------+----------+

As you can see, users that are on fk_case = 66 is removed, but if that user is already on other cases they still get shown. User with id = 22 is on fk_case 66 and this user removed from the list completely.

I tried using GROUP BY ID to only show one of each users, but the users that are already on the case and have other cases, is shown too.

Body:
I dont think you need fk_case for the SELECT, because if user is on other projects doesn't matter. Only matter he isn't on the current one.

SELECT DISTINCT users.id, users.firstName, users.lastName
FROM users
LEFT JOIN junc_jobs ON users.id = junc_jobs.fk_employee
WHERE users.fk_role > 1
  AND (fk_case IS NULL OR fk_case != 66)
ORDER BY firstName

Also not sure about what junc_jobs does, but maybe something like this may help

SELECT u.*
FROM users u
WHERE u.fk_role > 1
  AND NOT EXISTS ( SELECT 1
                   FROM junc_jobs j
                   WHERE j.fk_employee = u.id and j.fk_case = 66)


问:
function row.add() not work in my function:
function row.add no work correctly, to create the datatable:

```<code>var target=$(table.dt-table); //i test and only exist one.
target.DataTable(options);
</code>```

try to add a row in same function:

```<code>if(addrow!=null){target.row.add(addrow).draw();} //addrow i a var with array.
</code>```

i get this error:

```<code>Uncaught TypeError: Cannot read property 'add' of undefined
</code>```

i need add a row to existing datatable. in any way with row.add() or adding html raw code.

答:
From the api documentation on row.add()

```<code>var table = $('#example').DataTable(); // <-- use the returned object from .DataTable() and not the jQuery object

table.row.add( {
        "name":       "Tiger Nixon",
        "position":   "System Architect",
        "salary":     "$3,120",
        "start_date": "2011/04/25",
        "office":     "Edinburgh",
        "extn":       "5421"
    } ).draw();
</code>```

Body:
function row.add no work correctly, to create the datatable:

var target=$(table.dt-table); //i test and only exist one.
target.DataTable(options);

try to add a row in same function:

if(addrow!=null){target.row.add(addrow).draw();} //addrow i a var with array.

i get this error:

Uncaught TypeError: Cannot read property 'add' of undefined

i need add a row to existing datatable. in any way with row.add() or adding html raw code.

Body:
From the api documentation on row.add()

var table = $('#example').DataTable(); // <-- use the returned object from .DataTable() and not the jQuery object

table.row.add( {
        "name":       "Tiger Nixon",
        "position":   "System Architect",
        "salary":     "$3,120",
        "start_date": "2011/04/25",
        "office":     "Edinburgh",
        "extn":       "5421"
    } ).draw();


问:
Using plotly without online plotly account
Is it possible to use the plotly library to create charts in python without having an online plotly account? I think the code is opensource https://github.com/plotly/plotly.py. I would like to know whether we can use this without an online account.</p>

答:
You can use:

```<code>import plotly
plotly.offline.init_notebook_mode(connected=True)
</code>```

To use Plotly offline.

Body:
You can use:

import plotly
plotly.offline.init_notebook_mode(connected=True)

To use Plotly offline.


问:
Julia only imports names from first homemade Module
I have made two modules in Julia. One is for plotting graphs of trees structures, and one is for estimating entropy from simbolic secuences.
The first one has this first lines:

```<code>  module ArbolGrafosTikz

using LightGraphs, TikzGraphs

abstract type LabelledDiGraph
end

export LabelledTree, Nodo, Subarbol, Arbol,
       walk_tree, walk_tree!, tikz_representation

struct LabelledTree <: LabelledDiGraph
    g::DiGraph
    labels::Vector{Any}
end
</code>```

etcetera.
The second one has this header:

```<code>module EntropySymb

using Base.Iterators

export simboliza, problock, ncartprod, issubvec, allprobsn

function simboliza(x, delta=epsi)
    # funcion que pasa floats a tres simbolos.
    result=0
    if x>delta
</code>```

etcetera.

In my main program I have the first lines as thus:

```<code>push!(LOAD_PATH,".")
include("EntropySymb.jl")
include("ArbolGrafosTikz.jl")
using ArbolGrafosTikz
using EntropySymb
</code>```

but I can only have direct access to the names of objects in ArbolGrafosTikz
directly, for EntropySymb I have to use the name prefixed with the module, or Julia REPL doesn't seem to know about them.
Why is this?

答: You are running into the difference between using and import. using MyModule brings MyModule into scope, but import MyModel brings all exported names.

Body:
I have made two modules in Julia. One is for plotting graphs of trees structures, and one is for estimating entropy from simbolic secuences.
The first one has this first lines:

  module ArbolGrafosTikz

using LightGraphs, TikzGraphs

abstract type LabelledDiGraph
end

export LabelledTree, Nodo, Subarbol, Arbol,
       walk_tree, walk_tree!, tikz_representation

struct LabelledTree <: LabelledDiGraph
    g::DiGraph
    labels::Vector{Any}
end

etcetera.
The second one has this header:

module EntropySymb

using Base.Iterators

export simboliza, problock, ncartprod, issubvec, allprobsn

function simboliza(x, delta=epsi)
    # funcion que pasa floats a tres simbolos.
    result=0
    if x>delta

etcetera.

In my main program I have the first lines as thus:

push!(LOAD_PATH,".")
include("EntropySymb.jl")
include("ArbolGrafosTikz.jl")
using ArbolGrafosTikz
using EntropySymb

but I can only have direct access to the names of objects in ArbolGrafosTikz
directly, for EntropySymb I have to use the name prefixed with the module, or Julia REPL doesn't seem to know about them.
Why is this?


问:
Count specific value in pandas rolling window
I have a dataframe with thousands rows. One column consists of only 3 values: -1, 0, 1. I would like to count in rolling window (let's say 100) how many times a specific value (let's say 0) occurs.

How can I do it? I do not see such a method related to the object Rolling and I don't know how to do it by apply.

答:
It's pretty simple, I coded up a quick demo. You should get the idea.

Example

# Parameters
# iterable - column
# size - window size (100)

def window(iterable, size=2):
    i = iter(iterable)
    win = []
    for e in range(0, size):
        win.append(next(i))
    yield win
    for e in i:
        win = win[1:] + [e]
        yield win

# Sample data
a = [1, 0, 0, 0, 1, 1]

from collections import Counter

result = []
value = 1 # Value to keep count (-1, 0, 1)

for i in window(a, 2):
    count = Counter(i)[value]
    result.append(count)

# Sample output
print(result)
[1, 0, 0, 1, 2]
```


问:
How to add 3rd party JARs to Maven project
My area of expertise is not Java. I develop in other languages on other platforms.

Right now I'm developing a series of Java servlets for a project. The servlets are to run on a CentOS server running FileNetP8.

I actually got all of the planned items finished and running.

Now when I am trying to add a few more services, the library I came across is available via Maven. I have no idea what Maven is. Read up on it today. Created a test project to try it out.

My development environment is Eclipse Photon on Windows 10.

Now my problem is I can't figure out how to add the Filenet JARs to the project. I can't upload them to some Maven repo. Searching the Web says to add them to the local repo, but I don't understand how to do that to the Local repo in Eclipse's builtin Maven.

I think that the JARs don't need to be packaged within the deployment WAR because the app will be deployed to the Websphere server that runs Filenet so they should be available on it. Should I add them as external JAR references to get the project to compile?

答: Seeing as every answer involves maven i'll try to provide a different and somewhat old school approach. You could always import your jars directly into your project by right clicking on it -> properties -> Add Jars. Apply when done and Voilà. This is far easier than understanding the complexity of maven.</p>


问:
How to overflow image inside Bootstrap row
I'm trying to display an oversized image to fix inside a bootstrap row with the size col of 12. But whenever I do this, the image makes the row stretch all the way across and outside of the screen. I want keep the row width the same, but have it overflow with a scroll if the image gets too big inside the div. How should I do this? Below is the code that I've got.

HTML

```<code><div id="imageRow" class="row">
        <div class="col-md-12">
            <div id='imgContainer' runat="server" class='imgContainer' visible="false">
                <asp:Image runat='server' ID='imgDocument' Visible="false" CssClass='imgDocument clear'/>
            </div>
        </div>
    </div>
</code>```

CSS

```<code>.imgContainer {
    position: relative;
    overflow: scroll;
    width: 100%;
    height: 600px;
}
</code>```

P.S. I tried using Max-width, but it doesn't work as this will just simply limits the width of my image to fix inside the div without a scrollbar for it. I.e. it won't allow it to go oversize

答:
I've found a newer solution. Add this to the image:

.image {
  object-fit: fill;
}

Body:
I'm trying to display an oversized image to fix inside a bootstrap row with the size col of 12. But whenever I do this, the image makes the row stretch all the way across and outside of the screen. I want keep the row width the same, but have it overflow with a scroll if the image gets too big inside the div. How should I do this? Below is the code that I've got.

HTML

                <asp:Image runat='server' ID='imgDocument' Visible="false" CssClass='imgDocument clear'/>

CSS

.imgContainer {
    position: relative;
    overflow: scroll;
    width: 100%;
    height: 600px;
}

P.S. I tried using Max-width, but it doesn't work as this will just simply limits the width of my image to fix inside the div without a scrollbar for it. I.e. it won't allow it to go oversize


问:
phpinfo() shows wrong location for php.ini
phpinfo() show php.ini location as /usr/local/zend/etc where as the actual location is /etc/php5/apache2 . How do i fix this.

I am trying to debug drupal from eclipse ide .. so i have installed zend debugger plugin .
Now i have to edit php.ini and add the following code

```<code>zend_extension=full_path_to_zend_debugger_extension^gt;
zend_debugger.allow_hosts=127.0.0.1
zend_debugger.expose_remotely=allowed_hosts
</code>```

So before editing the php.ini, I am just using phpinfo() to find the location of php.ini. But it shows me some location where php.ini doesn't even exists.. please help

答:
phpinfo() shows the php.ini file that is loaded by the version of PHP loaded by apache. You may have php.ini files in other locations, but it's the one that reported by phpinfo() that is loaded (and used) by apache.

What are you trying to do? We can help you "fix" that problem.

Body:
phpinfo() show php.ini location as /usr/local/zend/etc where as the actual location is /etc/php5/apache2 . How do i fix this.

I am trying to debug drupal from eclipse ide .. so i have installed zend debugger plugin .
Now i have to edit php.ini and add the following code

zend_extension=full_path_to_zend_debugger_extension^gt;
zend_debugger.allow_hosts=127.0.0.1
zend_debugger.expose_remotely=allowed_hosts

So before editing the php.ini, I am just using phpinfo() to find the location of php.ini. But it shows me some location where php.ini doesn't even exists.. please help


问:
Pattern Matching In SQL where characters appears anywhere but in sequence
I'm attempting to write a query to fix invalid email formats. The invalid email format I am getting is of the form first@name_company@com.

The characters always appear as '@' '_' '@' in that sequence.

If this is the format then I am replacing @ with . and _ with @ to get a correct format as:

```<code>first.name@company.com
</code>```

I am considering a case condition like this:

```<code>When @email like '[a-z,0-9,_,-,@]_[a-z,0-9,_,-@]'  THEN replace(replace(replace(@email,'@','.'),'_','@'))
</code>```

This only seems to work if I put "_" as a wildcard like this '[a-z,0-9,_,-,@]%_%[a-z,0-9,_,-@]'

答:
Thanks Everyone. I used the following and it seems to be working:</p>

```<code>case when charindex('@',@email,patindex ('%@%',@email)+1) - (patindex ('%@%',@email)+1)>1 and

substring(@email,
     patindex ('%@%',@email)+1,

     charindex('@',@email,patindex ('%@%',@email)+1) - (patindex ('%@%',@email)+1)

     ) like '%_%'
</code>```

Body:
I'm attempting to write a query to fix invalid email formats. The invalid email format I am getting is of the form first@name_company@com.

The characters always appear as '@' '_' '@' in that sequence.

If this is the format then I am replacing @ with . and _ with @ to get a correct format as:

first.name@company.com

I am considering a case condition like this:

When @email like '[a-z,0-9,_,-,@]_[a-z,0-9,_,-@]'  THEN replace(replace(replace(@email,'@','.'),'_','@'))

This only seems to work if I put "_" as a wildcard like this '[a-z,0-9,_,-,@]%_%[a-z,0-9,_,-@]'

Body:
Thanks Everyone. I used the following and it seems to be working:

case when charindex('@',@email,patindex ('%@%',@email)+1) - (patindex ('%@%',@email)+1)>1 and

substring(@email,
     patindex ('%@%',@email)+1,

     charindex('@',@email,patindex ('%@%',@email)+1) - (patindex ('%@%',@email)+1)

     ) like '%_%'


问:
Implementing CQRS in PHP
I'm researching about CQRS pattern and our team wants to develop a system based on CQRS in PHP.

I know we can simulate event system in PHP, but I found that CQRS implements better/easier if the programming language would be event based (I'm not sure about this).

I have two questions:

I want to know that if we develop our system by CQRS pattern in PHP could be reliable or switch to other(event-based) programming language give us more consistency?

what kind of benefits CQRS has in micro-services system? is there any other pattern that reliable and easier to implements?

答:
I don't recommend you to use PHP for building a CQRS. The first question that you should ask yourself is, "what are the reasons why you need to implement an event-sourcing technology like CQRS?"

If the answer is because you need to have an architecture that allows you to distribute all your systems in a more efficient way, you should reconsider to use PHP. It runs in a single-thread processor and it has so many limits.

During a couple of months, we have been working in a PHP project based in CQRS, but at the end of the day, we were struggling with a lot of issues related to the performance. Finally, we discover the functional programming with Elixir and we decided to give up an opportunity.

During multiple months I was reading a lot of information about CQRS and I found to Martin Fowler, who is one of the contributors more relevant in the microservices world. And even he recommend highly to use a functional programming language to do event-sourcing.

However, if you have been decided to use PHP to build a CQRS project, you can give a chance and test it by yourself.

Conversely, if you are interested in using Elixir, you can start by reading some real examples https://leanpub.com/buildingconduit/read which is a blog based site using Elixir with CQRS + Commanded library.

Title: Implementing CQRS in PHP


问:
Ajax call returns wrong Date format in Datalist form
I have this Ajax Call function:

```<code>$(document).ready(function(){
v
var TesterID = "<?php echo $_GET['TesterID']; ?>"; /* value der Tester erhalten */

        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var len = response.length;

                $("#Teststart").empty(); /* Die erhaltenden Daten werden bei der ID angezeigt */
                for( var i = 0; i<len; i++){
                    var CID = response[i]['CID'];
                    var Datum = response[i]['Datum'];

                    $("#Teststart").append("<option value='"+Datum+"'>"+Datum+"</option>");

                }
            }
        });
});
</code>```

The Ajax return the Dates from the Database with this Code:

```<code>$sqlreadZeit = "Select TOP 10 CID,Datum from DB.dbo.xxx where TesterID = '".$_GET['TesterID']."' order by Datum DESC";
                $result1 = sqlsrv_query($conn, $sqlreadZeit);
                $zeiten_arr = array();
                while ($row = sqlsrv_fetch_array($result1, SQLSRV_FETCH_ASSOC)) {
                $CID = $row['CID'];

                $Datum = $row['Datum']->format('d.m.Y H:m:s');

                $zeiten_arr[] = array("CID" => $CID, "Datum" => $Datum);

                }
    header('Content-type: application/json');
  echo json_encode($zeiten_arr); /* Ausgabe printen die Erhalten werden soll */
</code>```

These are the results when I execute the query in SQL:

But in the Datalist it shows the date like this, seems like rounded.

In which part could be the problem? I don't see it.

I use MS SQL Server and moment-with-locales.js in a other Javascript function.

答:
Consider the following:

Change your date format to 'd.m.Y H:i:s' and format your dates using next statement: $Datum = $row['Datum']->format('d.m.Y H:i:s'); ('i' is for minutes with leading zeros).

Take a look at ReturnDatesAsStrings connection option when you call sqlsrv_connect(). When this option is true, date/time values are returned as strings.

Body:
I have this Ajax Call function:

$(document).ready(function(){
v
var TesterID = "<?php echo $_GET['TesterID']; ?>"; /* value der Tester erhalten */

        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var len = response.length;

                $("#Teststart").empty(); /* Die erhaltenden Daten werden bei der ID angezeigt */
                for( var i = 0; i<len; i++){
                    var CID = response[i]['CID'];
                    var Datum = response[i]['Datum'];

                    $("#Teststart").append("<option value='"+Datum+"'>"+Datum+"</option>");

                }
            }
        });
});

The Ajax return the Dates from the Database with this Code:

$sqlreadZeit = "Select TOP 10 CID,Datum from DB.dbo.xxx where TesterID = '".$_GET['TesterID']."' order by Datum DESC";
                $result1 = sqlsrv_query($conn, $sqlreadZeit);
                $zeiten_arr = array();
                while ($row = sqlsrv_fetch_array($result1, SQLSRV_FETCH_ASSOC)) {
                $CID = $row['CID'];

                $Datum = $row['Datum']->format('d.m.Y H:m:s');

                $zeiten_arr[] = array("CID" => $CID, "Datum" => $Datum);

                }
    header('Content-type: application/json');
  echo json_encode($zeiten_arr); /* Ausgabe printen die Erhalten werden soll */

These are the results when I execute the query in SQL:

But in the Datalist it shows the date like this, seems like rounded.

In which part could be the problem? I don't see it.

I use MS SQL Server and moment-with-locales.js in a other Javascript function.


问:
Cannot upload media files in Django production to external folder
I have an issue on my Django production server.
When I try to upload images, they always go to the app/media/ folder.
However I want them to be uploaded to /mnt/data.
In the admin panel, when I upload the image, it is always uploading in the app/media/ folder.
I tried adjusting the Nginx config file and the settings.py, but I guess I am lost.

Here is my Nginx configuration:

```<code>     location /static/ {
            root /home/somthing/something/;
        }
        location /media/ {
        root /mnt/data/;
        }
</code>```

and the Settings.py:

```<code>STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

    # Media files

    MEDIA_URL = '/media/'

    MEDIA_ROOT = (
        os.path.join(BASE_DIR, 'media')
    )
</code>```

and in my model this is how I create the image:

```<code>    pictures = models.ImageField(
            upload_to='postings/',
            verbose_name=_('Posting_picture'),
            blank=True, null=True,
            validators=[validate_image],
        )
</code>```

I guess following this configuration, the uploaded picture is supposed to be in mnt/data/media/postings.

The media folder on the mnt/data/ is chmod 777, I did it when I lost hope in writing/reading the folder.

答:
Currently  you are uploading to:

```<code>MEDIA_ROOT = (
    os.path.join(BASE_DIR, 'media')
)
</code>```

Basically means:

```<code>/path/to/project/media
</code>```

In your case it should be:

```<code>MEDIA_ROOT = '/mnt/data'
</code>```

Body:
I have an issue on my Django production server.
When I try to upload images, they always go to the app/media/ folder.
However I want them to be uploaded to /mnt/data.
In the admin panel, when I upload the image, it is always uploading in the app/media/ folder.
I tried adjusting the Nginx config file and the settings.py, but I guess I am lost.

Here is my Nginx configuration:

     location /static/ {
            root /home/somthing/something/;
        }
        location /media/ {
        root /mnt/data/;
        }

and the Settings.py:

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

    # Media files

    MEDIA_URL = '/media/'

    MEDIA_ROOT = (
        os.path.join(BASE_DIR, 'media')
    )

and in my model this is how I create the image:

    pictures = models.ImageField(
            upload_to='postings/',
            verbose_name=_('Posting_picture'),
            blank=True, null=True,
            validators=[validate_image],
        )

I guess following this configuration, the uploaded picture is supposed to be in mnt/data/media/postings.

The media folder on the mnt/data/ is chmod 777, I did it when I lost hope in writing/reading the folder.

Body:
Currently  you are uploading to:

MEDIA_ROOT = (
    os.path.join(BASE_DIR, 'media')
)

Basically means:

/path/to/project/media

In your case it should be:

MEDIA_ROOT = '/mnt/data'


问:
Side menu not covering all screen (DrawerNavigator - React Native)
I adding image of screen, this work in part of screen.
The Contacts screen need to be main page and not screen1 but its didn't work if i replace between them.
I adding the code, in 'LogedInNavigator' have there TabNavigator and DrawerNavigator - the 'Contants' page initializing from TabNavigator and part two - Screen1 with the side menu it's from DrawerNavigator - maybe it's doing the problem?

LogedInNavigator.js

```<code>import.......
styles......

const LoggedInNavigator = TabNavigator(
  {
    Contacts: {screen: ContactScreen,},
    Chat: {screen: ChatScreen,},
    Dashbaord: {screen: DashbaordScreen,},
    Profile: {screen: ProfileScreen,},
    Search: {screen: SearchScreen,},
  },
  {
    initialRouteName: "Contacts",
    tabBarPosition: "bottom",
    tabBarOptions: {
      showIcon: true,
      activeTintColor: 'white',
    }
  }
);

export default () => <LoggedInNavigator onNavigationStateChange={null} />

export const Drawer = DrawerNavigator ({
  Home:{
    screen: Screen1,
    navigationOptions: {
      drawer:{
        label: 'Home',
      },
    }
  },
  Camera: {
    screen: Screen2,
    navigationOptions: {
      drawer:{
        label: 'Camera',
      },
    }
  },
})
</code>```

Contants.js

```<code>class Contacts extends Component {
  componentDidMount() {
    // TBD loggedin should come from login process and removed from here
    const { loggedIn, getContacts } = this.props;
    loggedIn(1);
    getContacts();
  }

  render() {
    const Router = createRouter( () => ({})); //IDAN
    const { navigation, avatar, contacts } = this.props;
    return (
      <NavigationProvider router={Router}>
        <View style={{flex:1}}>
          <ContactView
            navigation={navigation}
            avatar={avatar}
            contacts={contacts}
          />
         <Drawer />
        </View>
      </NavigationProvider>
    );
  }
}

const mapStateToProps = (state) => {
  return (
    {
      avatar: state.user.user.avatar,
      contacts: state.contacts.contacts,
    }
  );
};

export default connect(mapStateToProps, { loggedIn, getContacts })(Contacts);
</code>```

Help me please..

答:
After a while, i want to answer on my own question (with react-navigation v2)
everything inside <RootNavigator/>

```<code>const RootNavigator= createDrawerNavigator({ Tabs }, {
    contentComponent: SideMenu,
    drawerWidth: Dimensions.get('window').width * .75,
})
</code>```

SideMenu:

```<code>class SideMenu extends Component {
   render() {
        return ( //...your side menu view )
   }
}
</code>```

Tab:

```<code>export default createBottomTabNavigator({
    Menu: {
        screen: HomeStack,
        navigationOptions: {
            title: 'תפריט',
            tabBarIcon: ({ focused, tintColor }) => {
                return <Icon name={'home'} size={20} color={tintColor} />;
            },
        }
    },
    Dashboard: {
        screen: DashboardStack,
        navigationOptions: {
            title: 'בית',
            tabBarOnPress: ({ navigation, defaultHandler }) => handleTabPress(navigation, defaultHandler),
            tabBarIcon: ({ focused, tintColor }) => {
                return <Icon name={'dashboard'} size={20} color={'green'} />;
            },
        }
    },
    QuickView: {
        screen: QuickNav,
        navigationOptions: {
            title: 'מבט מהיר',
            tabBarIcon: ({ focused, tintColor }) => {
                return <Icon name={'short-list'} size={20} color={tintColor} />;
            },
        },
    },
    Chat: {
        screen: Chat,
        navigationOptions: {
            title: "צ'אט",
            tabBarIcon: ({ focused, tintColor }) => {
                return <Icon name={'chat'} size={20} color={tintColor} />;
            },
        },
    },
},
    {
        initialRouteName: 'Dashboard',
        tabBarOptions: {
            activeTintColor: 'green',
            labelStyle: {
                fontSize: 16,
                marginBottom: 3,
            },
        },
    },
)
</code>```

Body:
I adding image of screen, this work in part of screen.
The Contacts screen need to be main page and not screen1 but its didn't work if i replace between them.
I adding the code, in 'LogedInNavigator' have there TabNavigator and DrawerNavigator - the 'Contants' page initializing from TabNavigator and part two - Screen1 with the side menu it's from DrawerNavigator - maybe it's doing the problem?

LogedInNavigator.js

import.......
styles......

const LoggedInNavigator = TabNavigator(
  {
    Contacts: {screen: ContactScreen,},
    Chat: {screen: ChatScreen,},
    Dashbaord: {screen: DashbaordScreen,},
    Profile: {screen: ProfileScreen,},
    Search: {screen: SearchScreen,},
  },
  {
    initialRouteName: "Contacts",
    tabBarPosition: "bottom",
    tabBarOptions: {
      showIcon: true,
      activeTintColor: 'white',
    }
  }
);

export default () => <LoggedInNavigator onNavigationStateChange={null} />

export const Drawer = DrawerNavigator ({
  Home:{
    screen: Screen1,
    navigationOptions: {
      drawer:{
        label: 'Home',
      },
    }
  },
  Camera: {
    screen: Screen2,
    navigationOptions: {
      drawer:{
        label: 'Camera',
      },
    }
  },
})

Contants.js

class Contacts extends Component {
  componentDidMount() {
    // TBD loggedin should come from login process and removed from here
    const { loggedIn, getContacts } = this.props;
    loggedIn(1);
    getContacts();
  }

  render() {
    const Router = createRouter( () => ({})); //IDAN
    const { navigation, avatar, contacts } = this.props;
    return (
      <NavigationProvider router={Router}>
        <View style={{flex:1}}>
          <ContactView
            navigation={navigation}
            avatar={avatar}
            contacts={contacts}
          />
         <Drawer />
        </View>
      </NavigationProvider>
    );
  }
}

const mapStateToProps = (state) => {
  return (
    {
      avatar: state.user.user.avatar,
      contacts: state.contacts.contacts,
    }
  );
};

export default connect(mapStateToProps, { loggedIn, getContacts })(Contacts);

Help me please..

Body:
After a while, i want to answer on my own question (with react-navigation v2)
everything inside <RootNavigator/>

const RootNavigator= createDrawerNavigator({ Tabs }, {
    contentComponent: SideMenu,
    drawerWidth: Dimensions.get('window').width * .75,
})

SideMenu:

class SideMenu extends Component {
   render() {
        return ( //...your side menu view )
   }
}

Tab:

export default createBottomTabNavigator({
    Menu: {
        screen: HomeStack,
        navigationOptions: {
            title: 'תפריט',
            tabBarIcon: ({ focused, tintColor }) => {
                return <Icon name={'home'} size={20} color={tintColor} />;
            },
        }
    },
    Dashboard: {
        screen: DashboardStack,
        navigationOptions: {
            title: 'בית',
            tabBarOnPress: ({ navigation, defaultHandler }) => handleTabPress(navigation, defaultHandler),
            tabBarIcon: ({ focused, tintColor }) => {
                return <Icon name={'dashboard'} size={20} color={'green'} />;
            },
        }
    },
    QuickView: {
        screen: QuickNav,
        navigationOptions: {
            title: 'מבט מהיר',
            tabBarIcon: ({ focused, tintColor }) => {
                return <Icon name={'short-list'} size={20} color={tintColor} />;
            },
        },
    },
    Chat: {
        screen: Chat,
        navigationOptions: {
            title: "צ'אט",
            tabBarIcon: ({ focused, tintColor }) => {
                return <Icon name={'chat'} size={20} color={tintColor} />;
            },
        },
    },
},
    {
        initialRouteName: 'Dashboard',
        tabBarOptions: {
            activeTintColor: 'green',
            labelStyle: {
                fontSize: 16,
                marginBottom: 3,
            },
        },
    },
)