问:
Structured Streaming with multiple Sink's for a single Source
We are creating a Spark Structured Streaming application where there is a Single Source and Multiple Sink's (Kafka & HDFS). We are on a Spark 2.3.1 cluster hence using foreachBatch on a DataStreamWriter is out of our reach. Hence I opted for the multiple Stream Writer approach as being advocated here and multiple other places. Unfortunately only one of that Stream is working for all batches and the other remains dormant. What am I missing here to solve my problem?

  val spark = SparkSession
      .builder
      .appName("Spark-Structured-Streaming")
      .enableHiveSupport()
      .getOrCreate()

  val lines = spark.readStream
    .format("socket")
    .option("host", "localhost")
    .option("port", 9999)
    .load()

  val words: Dataset[String] = lines.as[String]
    .flatMap(_.split(" "))
    .map(_.concat(Random.nextInt(10).toString))

  /** THIS DOESN'T STREAM TO HDFS (This work's only when the below one is commented) **/
  words.writeStream
    .format("parquet")
    .option("path", "path/to/destination/dir")
    .option("checkpointLocation", "some_location_1")
    .start()

  /** THIS WORK'S **/
  words.writeStream
    .format("kafka")
    .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    .option("topic", "updates")
    .option("checkpointLocation", "some_location_2")
    .start()

  spark.streams.awaitAnyTermination()
```

<p>I only see data published to Kafka but I don't see data written to HDFS. Only when I comment out Kafka publishing stream the dormant one come's to life.</p>

<p>UPDATE:
a similar easily reproducible script with simple Sink's</p>

<pre class="lang-scala prettyprint-override"><code>def main(args: Array[String]): Unit = {

    val spark = SparkSession.builder.appName("Spark-Structured-Streaming").master("local[4]").getOrCreate()

    val lines = spark.readStream.format("socket").option("host", "localhost").option("port", 9999).load()

    import spark.implicits._

    val words: Dataset[String] = lines.as[String].flatMap(_.split(" ")).map(_.concat(Random.nextInt(10).toString))

    words.writeStream.queryName("query1").format("console").start()

    words.writeStream.queryName("query2").foreach(new ForeachWriter[String] {
        override def open(partitionId: Long, version: Long): Boolean = true

        override def process(value: String): Unit = {
          println(value)
        }

        override def close(errorOrNull: Throwable): Unit = {}
      })
      .start()

    spark.streams.awaitAnyTermination()
  }
</code>```

LOGS: for an input of A B C

```<code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
20/05/30 12:17:37 INFO SparkContext: Running Spark version 2.3.1
20/05/30 12:17:38 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
20/05/30 12:17:38 INFO SparkContext: Submitted application: Spark-Structured-Streaming
20/05/30 12:17:38 INFO SecurityManager: Changing view acls to: z001v7w
20/05/30 12:17:38 INFO SecurityManager: Changing modify acls to: z001v7w
20/05/30 12:17:38 INFO SecurityManager: Changing view acls groups to:
20/05/30 12:17:38 INFO SecurityManager: Changing modify acls groups to:
20/05/30 12:17:38 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(z001v7w); groups with view permissions: Set(); users  with modify permissions: Set(z001v7w); groups with modify permissions: Set()
20/05/30 12:17:38 INFO Utils: Successfully started service 'sparkDriver' on port 49262.
20/05/30 12:17:39 INFO SparkEnv: Registering MapOutputTracker
20/05/30 12:17:39 INFO SparkEnv: Registering BlockManagerMaster
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
20/05/30 12:17:39 INFO DiskBlockManager: Created local directory at /private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/blockmgr-80dcbdff-eb1c-49e5-a33b-47a897735d31
20/05/30 12:17:39 INFO MemoryStore: MemoryStore started with capacity 2004.6 MB
20/05/30 12:17:39 INFO SparkEnv: Registering OutputCommitCoordinator
20/05/30 12:17:39 INFO Utils: Successfully started service 'SparkUI' on port 4040.
20/05/30 12:17:39 INFO SparkUI: Bound SparkUI to 127.0.0.1, and started at http://localhost:4040
20/05/30 12:17:39 INFO Executor: Starting executor ID driver on host localhost
20/05/30 12:17:39 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 49263.
20/05/30 12:17:39 INFO NettyBlockTransferService: Server created on localhost:49263
20/05/30 12:17:39 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
20/05/30 12:17:39 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: Registering block manager localhost:49263 with 2004.6 MB RAM, BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:40 INFO SharedState: Setting hive.metastore.warehouse.dir ('null') to the value of spark.sql.warehouse.dir ('file:/Users/****/spark-warehouse/').
20/05/30 12:17:40 INFO SharedState: Warehouse path is 'file:/****/spark-warehouse/'.
20/05/30 12:17:40 INFO StateStoreCoordinatorRef: Registered StateStoreCoordinator endpoint
20/05/30 12:17:40 WARN TextSocketSourceProvider: The socket source should not be used for production applications! It does not support recovery.
20/05/30 12:17:43 INFO MicroBatchExecution: Starting query1 [id = a5714e40-553f-4d21-9115-9c0d9ffe950b, runId = 8d206486-36d8-4319-ad3d-fa5cb00a79ca]. Use file:///private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/temporary-5f818bb9-b347-432f-8c43-07fccec0e9e8 to store the query checkpoint.
20/05/30 12:17:43 WARN ClosureCleaner: Expected a closure; got com.tgt.sign.POCTestMain$$anon$1
20/05/30 12:17:43 INFO MicroBatchExecution: Starting new streaming query.
20/05/30 12:17:43 INFO MicroBatchExecution: Streaming query made progress: {
  "id" : "a5714e40-553f-4d21-9115-9c0d9ffe950b",
  "runId" : "8d206486-36d8-4319-ad3d-fa5cb00a79ca",
  "name" : "query1",
  "timestamp" : "2020-05-30T17:17:43.915Z",
  "batchId" : 0,
  "numInputRows" : 0,
  "processedRowsPerSecond" : 0.0,
  "durationMs" : {
    "getOffset" : 0,
    "triggerExecution" : 10
  },
  "stateOperators" : [ ],
  "sources" : [ {
    "description" : "TextSocketSource[host: localhost, port: 9999]",
    "startOffset" : null,
    "endOffset" : null,
    "numInputRows" : 0,
    "processedRowsPerSecond" : 0.0
  } ],
  "sink" : {
    "description" : "org.apache.spark.sql.execution.streaming.ConsoleSinkProvider@5e761dda"
  }
}
20/05/30 12:17:43 INFO MicroBatchExecution: Starting query2 [id = 776c6082-920a-4406-913f-c1b2eda5f12d, runId = 7d066ebb-fe7b-454c-98c5-2ed05a8c0bda]. Use file:///private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/temporary-7a3485d8-9973-43a7-8a35-4a5dd0745719 to store the query checkpoint.
20/05/30 12:17:43 INFO MicroBatchExecution: Starting new streaming query.
20/05/30 12:17:43 INFO MicroBatchExecution: Streaming query made progress: {
  "id" : "776c6082-920a-4406-913f-c1b2eda5f12d",
  "runId" : "7d066ebb-fe7b-454c-98c5-2ed05a8c0bda",
  "name" : "query2",
  "timestamp" : "2020-05-30T17:17:43.991Z",
  "batchId" : 0,
  "numInputRows" : 0,
  "processedRowsPerSecond" : 0.0,
  "durationMs" : {
    "getOffset" : 0,
    "triggerExecution" : 1
  },
  "stateOperators" : [ ],
  "sources" : [ {
    "description" : "TextSocketSource[host: localhost, port: 9999]",
    "startOffset" : null,
    "endOffset" : null,
    "numInputRows" : 0,
    "processedRowsPerSecond" : 0.0
  } ],
  "sink" : {
    "description" : "ForeachSink"
  }
}
20/05/30 12:17:49 INFO MicroBatchExecution: Committed offsets for batch 0. Metadata OffsetSeqMetadata(0,1590859069597,Map(spark.sql.shuffle.partitions -> 200, spark.sql.streaming.stateStore.providerClass -> org.apache.spark.sql.execution.streaming.state.HDFSBackedStateStoreProvider))
20/05/30 12:17:50 INFO CodeGenerator: Code generated in 474.062005 ms
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 58.908865 ms
20/05/30 12:17:51 INFO WriteToDataSourceV2Exec: Start processing data source writer: org.apache.spark.sql.execution.streaming.sources.MicroBatchWriter@6ccc266. The input RDD has 4 partitions.
20/05/30 12:17:51 INFO SparkContext: Starting job: start at POCTestMain.scala:147
20/05/30 12:17:51 INFO DAGScheduler: Got job 0 (start at POCTestMain.scala:147) with 4 output partitions
20/05/30 12:17:51 INFO DAGScheduler: Final stage: ResultStage 0 (start at POCTestMain.scala:147)
20/05/30 12:17:51 INFO DAGScheduler: Parents of final stage: List()
20/05/30 12:17:51 INFO DAGScheduler: Missing parents: List()
20/05/30 12:17:51 INFO DAGScheduler: Submitting ResultStage 0 (MapPartitionsRDD[5] at start at POCTestMain.scala:147), which has no missing parents
20/05/30 12:17:51 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 12.0 KB, free 2004.6 MB)
20/05/30 12:17:51 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 5.3 KB, free 2004.6 MB)
20/05/30 12:17:51 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on localhost:49263 (size: 5.3 KB, free: 2004.6 MB)
20/05/30 12:17:51 INFO SparkContext: Created broadcast 0 from broadcast at DAGScheduler.scala:1039
20/05/30 12:17:51 INFO DAGScheduler: Submitting 4 missing tasks from ResultStage 0 (MapPartitionsRDD[5] at start at POCTestMain.scala:147) (first 15 tasks are for partitions Vector(0, 1, 2, 3))
20/05/30 12:17:51 INFO TaskSchedulerImpl: Adding task set 0.0 with 4 tasks
20/05/30 12:17:51 INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, localhost, executor driver, partition 0, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 1.0 in stage 0.0 (TID 1, localhost, executor driver, partition 1, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 2.0 in stage 0.0 (TID 2, localhost, executor driver, partition 2, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 3.0 in stage 0.0 (TID 3, localhost, executor driver, partition 3, PROCESS_LOCAL, 7995 bytes)
20/05/30 12:17:51 INFO Executor: Running task 3.0 in stage 0.0 (TID 3)
20/05/30 12:17:51 INFO Executor: Running task 0.0 in stage 0.0 (TID 0)
20/05/30 12:17:51 INFO Executor: Running task 1.0 in stage 0.0 (TID 1)
20/05/30 12:17:51 INFO Executor: Running task 2.0 in stage 0.0 (TID 2)
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 25.371124 ms
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 12.870672 ms
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 0 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 2 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 1 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 0 committed.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 1 committed.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 2 committed.
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 14.157876 ms
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 3 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 3 committed.
20/05/30 12:17:51 INFO Executor: Finished task 2.0 in stage 0.0 (TID 2). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 1.0 in stage 0.0 (TID 1). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 0.0 in stage 0.0 (TID 0). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 3.0 in stage 0.0 (TID 3). 2297 bytes result sent to driver
20/05/30 12:17:51 INFO TaskSetManager: Finished task 2.0 in stage 0.0 (TID 2) in 227 ms on localhost (executor driver) (1/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 256 ms on localhost (executor driver) (2/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 1.0 in stage 0.0 (TID 1) in 233 ms on localhost (executor driver) (3/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 3.0 in stage 0.0 (TID 3) in 232 ms on localhost (executor driver) (4/4)
20/05/30 12:17:51 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
20/05/30 12:17:51 INFO DAGScheduler: ResultStage 0 (start at POCTestMain.scala:147) finished in 0.557 s
20/05/30 12:17:51 INFO DAGScheduler: Job 0 finished: start at POCTestMain.scala:147, took 0.616436 s
20/05/30 12:17:51 INFO WriteToDataSourceV2Exec: Data source writer org.apache.spark.sql.execution.streaming.sources.MicroBatchWriter@6ccc266 is committing.
-------------------------------------------
Batch: 0
-------------------------------------------
+-----+
|value|
+-----+
|   A8|
|   B9|
|   C4|
+-----+
</code>```

答:
I too faced similiar issue and changed my code to</p>

```<code>/** THIS DOESN'T STREAM TO HDFS (This work's only when the below one is commented) **/
  val hdfsPush = words.write
    .format("parquet")
    .outputMode("append")
    .option("path", "path/to/destination/dir")
    .option("checkpointLocation", "some_location_1")

  /** THIS WORK'S **/
  val kafkaPush = words.writeStream
    .format("kafka")
    .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    .option("topic", "updates")
    .option("checkpointLocation", "some_location_2")

kafkaPush.start()
hdfsPush.start().awaitTermination()

</code>```

Body:
We are creating a Spark Structured Streaming application where there is a Single Source and Multiple Sink's (Kafka & HDFS). We are on a Spark 2.3.1 cluster hence using foreachBatch on a DataStreamWriter is out of our reach. Hence I opted for the multiple Stream Writer approach as being advocated here and multiple other places. Unfortunately only one of that Stream is working for all batches and the other remains dormant. What am I missing here to solve my problem?

  val spark = SparkSession
      .builder
      .appName("Spark-Structured-Streaming")
      .enableHiveSupport()
      .getOrCreate()

  val lines = spark.readStream
    .format("socket")
    .option("host", "localhost")
    .option("port", 9999)
    .load()

  val words: Dataset[String] = lines.as[String]
    .flatMap(_.split(" "))
    .map(_.concat(Random.nextInt(10).toString))

  /** THIS DOESN'T STREAM TO HDFS (This work's only when the below one is commented) **/
  words.writeStream
    .format("parquet")
    .option("path", "path/to/destination/dir")
    .option("checkpointLocation", "some_location_1")
    .start()

  /** THIS WORK'S **/
  words.writeStream
    .format("kafka")
    .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    .option("topic", "updates")
    .option("checkpointLocation", "some_location_2")
    .start()

  spark.streams.awaitAnyTermination()

I only see data published to Kafka but I don't see data written to HDFS. Only when I comment out Kafka publishing stream the dormant one come's to life.

UPDATE:
a similar easily reproducible script with simple Sink's

def main(args: Array[String]): Unit = {

    val spark = SparkSession.builder.appName("Spark-Structured-Streaming").master("local[4]").getOrCreate()

    val lines = spark.readStream.format("socket").option("host", "localhost").option("port", 9999).load()

    import spark.implicits._

    val words: Dataset[String] = lines.as[String].flatMap(_.split(" ")).map(_.concat(Random.nextInt(10).toString))

    words.writeStream.queryName("query1").format("console").start()

    words.writeStream.queryName("query2").foreach(new ForeachWriter[String] {
        override def open(partitionId: Long, version: Long): Boolean = true

        override def process(value: String): Unit = {
          println(value)
        }

        override def close(errorOrNull: Throwable): Unit = {}
      })
      .start()

    spark.streams.awaitAnyTermination()
  }

LOGS: for an input of A B C

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
20/05/30 12:17:37 INFO SparkContext: Running Spark version 2.3.1
20/05/30 12:17:38 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
20/05/30 12:17:38 INFO SparkContext: Submitted application: Spark-Structured-Streaming
20/05/30 12:17:38 INFO SecurityManager: Changing view acls to: z001v7w
20/05/30 12:17:38 INFO SecurityManager: Changing modify acls to: z001v7w
20/05/30 12:17:38 INFO SecurityManager: Changing view acls groups to:
20/05/30 12:17:38 INFO SecurityManager: Changing modify acls groups to:
20/05/30 12:17:38 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(z001v7w); groups with view permissions: Set(); users  with modify permissions: Set(z001v7w); groups with modify permissions: Set()
20/05/30 12:17:38 INFO Utils: Successfully started service 'sparkDriver' on port 49262.
20/05/30 12:17:39 INFO SparkEnv: Registering MapOutputTracker
20/05/30 12:17:39 INFO SparkEnv: Registering BlockManagerMaster
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
20/05/30 12:17:39 INFO DiskBlockManager: Created local directory at /private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/blockmgr-80dcbdff-eb1c-49e5-a33b-47a897735d31
20/05/30 12:17:39 INFO MemoryStore: MemoryStore started with capacity 2004.6 MB
20/05/30 12:17:39 INFO SparkEnv: Registering OutputCommitCoordinator
20/05/30 12:17:39 INFO Utils: Successfully started service 'SparkUI' on port 4040.
20/05/30 12:17:39 INFO SparkUI: Bound SparkUI to 127.0.0.1, and started at http://localhost:4040
20/05/30 12:17:39 INFO Executor: Starting executor ID driver on host localhost
20/05/30 12:17:39 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 49263.
20/05/30 12:17:39 INFO NettyBlockTransferService: Server created on localhost:49263
20/05/30 12:17:39 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
20/05/30 12:17:39 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManagerMasterEndpoint: Registering block manager localhost:49263 with 2004.6 MB RAM, BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:39 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, localhost, 49263, None)
20/05/30 12:17:40 INFO SharedState: Setting hive.metastore.warehouse.dir ('null') to the value of spark.sql.warehouse.dir ('file:/Users/****/spark-warehouse/').
20/05/30 12:17:40 INFO SharedState: Warehouse path is 'file:/****/spark-warehouse/'.
20/05/30 12:17:40 INFO StateStoreCoordinatorRef: Registered StateStoreCoordinator endpoint
20/05/30 12:17:40 WARN TextSocketSourceProvider: The socket source should not be used for production applications! It does not support recovery.
20/05/30 12:17:43 INFO MicroBatchExecution: Starting query1 [id = a5714e40-553f-4d21-9115-9c0d9ffe950b, runId = 8d206486-36d8-4319-ad3d-fa5cb00a79ca]. Use file:///private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/temporary-5f818bb9-b347-432f-8c43-07fccec0e9e8 to store the query checkpoint.
20/05/30 12:17:43 WARN ClosureCleaner: Expected a closure; got com.tgt.sign.POCTestMain$$anon$1
20/05/30 12:17:43 INFO MicroBatchExecution: Starting new streaming query.
20/05/30 12:17:43 INFO MicroBatchExecution: Streaming query made progress: {
  "id" : "a5714e40-553f-4d21-9115-9c0d9ffe950b",
  "runId" : "8d206486-36d8-4319-ad3d-fa5cb00a79ca",
  "name" : "query1",
  "timestamp" : "2020-05-30T17:17:43.915Z",
  "batchId" : 0,
  "numInputRows" : 0,
  "processedRowsPerSecond" : 0.0,
  "durationMs" : {
    "getOffset" : 0,
    "triggerExecution" : 10
  },
  "stateOperators" : [ ],
  "sources" : [ {
    "description" : "TextSocketSource[host: localhost, port: 9999]",
    "startOffset" : null,
    "endOffset" : null,
    "numInputRows" : 0,
    "processedRowsPerSecond" : 0.0
  } ],
  "sink" : {
    "description" : "org.apache.spark.sql.execution.streaming.ConsoleSinkProvider@5e761dda"
  }
}
20/05/30 12:17:43 INFO MicroBatchExecution: Starting query2 [id = 776c6082-920a-4406-913f-c1b2eda5f12d, runId = 7d066ebb-fe7b-454c-98c5-2ed05a8c0bda]. Use file:///private/var/folders/rr/vxr2k38j6_qcl3xmbf2g_25933gq0_/T/temporary-7a3485d8-9973-43a7-8a35-4a5dd0745719 to store the query checkpoint.
20/05/30 12:17:43 INFO MicroBatchExecution: Starting new streaming query.
20/05/30 12:17:43 INFO MicroBatchExecution: Streaming query made progress: {
  "id" : "776c6082-920a-4406-913f-c1b2eda5f12d",
  "runId" : "7d066ebb-fe7b-454c-98c5-2ed05a8c0bda",
  "name" : "query2",
  "timestamp" : "2020-05-30T17:17:43.991Z",
  "batchId" : 0,
  "numInputRows" : 0,
  "processedRowsPerSecond" : 0.0,
  "durationMs" : {
    "getOffset" : 0,
    "triggerExecution" : 1
  },
  "stateOperators" : [ ],
  "sources" : [ {
    "description" : "TextSocketSource[host: localhost, port: 9999]",
    "startOffset" : null,
    "endOffset" : null,
    "numInputRows" : 0,
    "processedRowsPerSecond" : 0.0
  } ],
  "sink" : {
    "description" : "ForeachSink"
  }
}
20/05/30 12:17:49 INFO MicroBatchExecution: Committed offsets for batch 0. Metadata OffsetSeqMetadata(0,1590859069597,Map(spark.sql.shuffle.partitions -> 200, spark.sql.streaming.stateStore.providerClass -> org.apache.spark.sql.execution.streaming.state.HDFSBackedStateStoreProvider))
20/05/30 12:17:50 INFO CodeGenerator: Code generated in 474.062005 ms
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 58.908865 ms
20/05/30 12:17:51 INFO WriteToDataSourceV2Exec: Start processing data source writer: org.apache.spark.sql.execution.streaming.sources.MicroBatchWriter@6ccc266. The input RDD has 4 partitions.
20/05/30 12:17:51 INFO SparkContext: Starting job: start at POCTestMain.scala:147
20/05/30 12:17:51 INFO DAGScheduler: Got job 0 (start at POCTestMain.scala:147) with 4 output partitions
20/05/30 12:17:51 INFO DAGScheduler: Final stage: ResultStage 0 (start at POCTestMain.scala:147)
20/05/30 12:17:51 INFO DAGScheduler: Parents of final stage: List()
20/05/30 12:17:51 INFO DAGScheduler: Missing parents: List()
20/05/30 12:17:51 INFO DAGScheduler: Submitting ResultStage 0 (MapPartitionsRDD[5] at start at POCTestMain.scala:147), which has no missing parents
20/05/30 12:17:51 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 12.0 KB, free 2004.6 MB)
20/05/30 12:17:51 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 5.3 KB, free 2004.6 MB)
20/05/30 12:17:51 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on localhost:49263 (size: 5.3 KB, free: 2004.6 MB)
20/05/30 12:17:51 INFO SparkContext: Created broadcast 0 from broadcast at DAGScheduler.scala:1039
20/05/30 12:17:51 INFO DAGScheduler: Submitting 4 missing tasks from ResultStage 0 (MapPartitionsRDD[5] at start at POCTestMain.scala:147) (first 15 tasks are for partitions Vector(0, 1, 2, 3))
20/05/30 12:17:51 INFO TaskSchedulerImpl: Adding task set 0.0 with 4 tasks
20/05/30 12:17:51 INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, localhost, executor driver, partition 0, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 1.0 in stage 0.0 (TID 1, localhost, executor driver, partition 1, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 2.0 in stage 0.0 (TID 2, localhost, executor driver, partition 2, PROCESS_LOCAL, 7851 bytes)
20/05/30 12:17:51 INFO TaskSetManager: Starting task 3.0 in stage 0.0 (TID 3, localhost, executor driver, partition 3, PROCESS_LOCAL, 7995 bytes)
20/05/30 12:17:51 INFO Executor: Running task 3.0 in stage 0.0 (TID 3)
20/05/30 12:17:51 INFO Executor: Running task 0.0 in stage 0.0 (TID 0)
20/05/30 12:17:51 INFO Executor: Running task 1.0 in stage 0.0 (TID 1)
20/05/30 12:17:51 INFO Executor: Running task 2.0 in stage 0.0 (TID 2)
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 25.371124 ms
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 12.870672 ms
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 0 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 2 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 1 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 0 committed.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 1 committed.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 2 committed.
20/05/30 12:17:51 INFO CodeGenerator: Code generated in 14.157876 ms
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 3 is committing.
20/05/30 12:17:51 INFO DataWritingSparkTask: Writer for partition 3 committed.
20/05/30 12:17:51 INFO Executor: Finished task 2.0 in stage 0.0 (TID 2). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 1.0 in stage 0.0 (TID 1). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 0.0 in stage 0.0 (TID 0). 1240 bytes result sent to driver
20/05/30 12:17:51 INFO Executor: Finished task 3.0 in stage 0.0 (TID 3). 2297 bytes result sent to driver
20/05/30 12:17:51 INFO TaskSetManager: Finished task 2.0 in stage 0.0 (TID 2) in 227 ms on localhost (executor driver) (1/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 256 ms on localhost (executor driver) (2/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 1.0 in stage 0.0 (TID 1) in 233 ms on localhost (executor driver) (3/4)
20/05/30 12:17:51 INFO TaskSetManager: Finished task 3.0 in stage 0.0 (TID 3) in 232 ms on localhost (executor driver) (4/4)
20/05/30 12:17:51 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
20/05/30 12:17:51 INFO DAGScheduler: ResultStage 0 (start at POCTestMain.scala:147) finished in 0.557 s
20/05/30 12:17:51 INFO DAGScheduler: Job 0 finished: start at POCTestMain.scala:147, took 0.616436 s
20/05/30 12:17:51 INFO WriteToDataSourceV2Exec: Data source writer org.apache.spark.sql.execution.streaming.sources.MicroBatchWriter@6ccc266 is committing.
-------------------------------------------
Batch: 0
-------------------------------------------
+-----+
|value|
+-----+
|   A8|
|   B9|
|   C4|
+-----+

Body:
I too faced similiar issue and changed my code to

/** THIS DOESN'T STREAM TO HDFS (This work's only when the below one is commented) **/
  val hdfsPush = words.write
    .format("parquet")
    .outputMode("append")
    .option("path", "path/to/destination/dir")
    .option("checkpointLocation", "some_location_1")

  /** THIS WORK'S **/
  val kafkaPush = words.writeStream
    .format("kafka")
    .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    .option("topic", "updates")
    .option("checkpointLocation", "some_location_2")

kafkaPush.start()
hdfsPush.start().awaitTermination()


来源: stackexchange

问:
How to add if else statement in python along with function defination
Sorry to bother i m new to coding just learning python. i just created some code by myself in python  no error shows. but why if else statement not executing. can someone help.

code:

```<code>def name(f_name, age):
    return f"Hi, {f_name} {age}"
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")

person = name("Aditya", 17)
print(person)
</code>```

答:
When you call a function, as soon as the function reaches a return statement, it will jump out of the function, because it already found what it was looking for, to return something. Because you returned your string at the very beginning, the program didn't get a chance to get the if/else statements.</p>

```<code>def name(f_name, age):
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")
    return f"Hi, {f_name} {age}"

person = name("Aditya", 17)
print(person)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Sorry to bother i m new to coding just learning python. i just created some code by myself in python  no error shows. but why if else statement not executing. can someone help.

code:

def name(f_name, age):
    return f"Hi, {f_name} {age}"
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")

person = name("Aditya", 17)
print(person)

Body:
When you call a function, as soon as the function reaches a return statement, it will jump out of the function, because it already found what it was looking for, to return something. Because you returned your string at the very beginning, the program didn't get a chance to get the if/else statements.

def name(f_name, age):
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")
    return f"Hi, {f_name} {age}"

person = name("Aditya", 17)
print(person)


问:
Show Hide div if, if statement is true
My code works to a point. What I want is that when this if statement is false, the
 doesn't show

```<code><?php
    $query3 = mysql_query($query3);
    $numrows = mysql_num_rows($query3);
    if ($numrows > 0) {
        $fvisit = mysql_fetch_array($result3);
    }
    else {
    }
?>
</code>```

答:
from php you can invoke jquery like this but my 2nd method is much cleaner and better for php

```<code>if($switchView) :?>
 <script>$('.container').hide();</script>
 <script>$('.confirm').show();</script>
<?php endif;
</code>```

another way is to initiate your class and dynamically invoke the condition like this

```<code>$registerForm ='block';
</code>```

then  in your html use this

```<code><div class="col" style="display: <?= $registerForm?>">
</code>```

now you can play with the view with if and else easily without having a messed code example

```<code>if($condition)  registerForm = 'none';
</code>```

Make sure you use 'block' to show and 'none' to hide. This is far the easiest way with php

ContentLicense: CC BY-SA 3.0

Title: Show Hide div if, if statement is true

Body:
My code works to a point. What I want is that when this if statement is false, the
 doesn't show

<?php
    $query3 = mysql_query($query3);
    $numrows = mysql_num_rows($query3);
    if ($numrows > 0) {
        $fvisit = mysql_fetch_array($result3);
    }
    else {
    }
?>

Body:
from php you can invoke jquery like this but my 2nd method is much cleaner and better for php

if($switchView) :?>
 <script>$('.container').hide();</script>
 <script>$('.confirm').show();</script>
<?php endif;

another way is to initiate your class and dynamically invoke the condition like this

$registerForm ='block';

then  in your html use this

<div class="col" style="display: <?= $registerForm?>">

now you can play with the view with if and else easily without having a messed code example

if($condition)  registerForm = 'none';

Make sure you use 'block' to show and 'none' to hide. This is far the easiest way with php


问:
How can i switch the stream I am listening to in a streambuilder in Dart?
Basically when the page first loads i want to use 1 stream that queries by geolocation but checks for documents where variable socialVisible is true, and then when the user clicks on a button to switch, i want the stream to instead still query by geolocation but now checks the documents with the field profVisible.

In theory this is very simple, whenever the corresponding button is pressed i set the state so that socialPressed=true and profPressed=false and then inside the streambuilder i used ternary operators to decide which stream should be used based on the truth values of socialPressed and profPressed.

However, this only works on the first click, the initial value of socialPressed is true so the initial stream is the social one and then when i click to go to the prof one it switches streams successfully. However after this time when i try to go back to social all the documents from prof remain instead of being replaced by social? This happens even when i switched the initial stream to prof, and i do not understand why this is happening?

```<code>StreamBuilder(
            stream:socialPressed==true?socStream:proStream,
            builder:
                (context, AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
              if (!snapshots.hasData) {
                return Container(
                    alignment: FractionalOffset.center,
                    child: CircularProgressIndicator());
              } else {
               return Container(
                    child: Container(
                      child: (snapshots.data.length == 0)
                          Container(
                        height: MediaQuery.of(context).size.height * 2 / 3,
                        child: ListView.builder(
                          itemBuilder: (context, index) {
                            DocumentSnapshot doc = snapshots.data[index];
                          return UserTile('this is where i use the doc data')},
                          itemCount: snapshots.data.length,
                        ),),));}},)
</code>```

This is the basic structure of my code, i have removed irrelevant info.

EDIT:
Button callback code was requested:

```<code> FloatingActionButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(16.0))),
                onPressed: () {
                  setState(() {
                    likeType='social';
                    socialPressed=!socialPressed;
                  });
                },
                elevation: 0,
                heroTag: 'socialButton',
                backgroundColor: socialPressed==false?Colors.grey[100]:Color(0xFFe0bdff),
                child: Icon(
                  Entypo.drink,
                  color: Color(0xFF8803fc),
                ),
              ),
              FloatingActionButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(16.0))),
                onPressed: () {
                  setState(() {
                    likeType='prof';
                    socialPressed=!socialPressed;
                  });
                },
                elevation: 0,
                heroTag: 'profButton',
                backgroundColor: socialPressed==true?Colors.grey[100]:Color(0xFFb9ebe9),
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      width: MediaQuery.of(context).size.width / 30,
                    ),
                    Icon(
                      FontAwesome.graduation_cap,
                      color: Color(0xFF096664),
                    ),
                  ],

                ),
              ),
</code>```

答:
I too faced this issue. I am using RX Dart and tried to switch streams based on a boolean variable.

I was initially using PublishSubject for my stream. Switching to Behaviour Subject solved the issue for me. At this moment I don't have sufficient knowledge on why this works but would try to explore it further and edit here if possible.

Previous code :

```<code>final _activeOrdersFetcher = PublishSubject<OrderListModel>();
final _completedOrdersFetcher = PublishSubject<OrderListModel>();

StreamBuilder<OrderListModel>(
      stream: isActive
          ? _ordersBloc.getActiveOrders
          : _ordersBloc.getCompletedOrders
</code>```

New Code Change :

```<code>final _activeOrdersFetcher = BehaviorSubject<OrderListModel>();
final _completedOrdersFetcher = BehaviorSubject<OrderListModel>();
</code>```

Body:
Basically when the page first loads i want to use 1 stream that queries by geolocation but checks for documents where variable socialVisible is true, and then when the user clicks on a button to switch, i want the stream to instead still query by geolocation but now checks the documents with the field profVisible.

In theory this is very simple, whenever the corresponding button is pressed i set the state so that socialPressed=true and profPressed=false and then inside the streambuilder i used ternary operators to decide which stream should be used based on the truth values of socialPressed and profPressed.

However, this only works on the first click, the initial value of socialPressed is true so the initial stream is the social one and then when i click to go to the prof one it switches streams successfully. However after this time when i try to go back to social all the documents from prof remain instead of being replaced by social? This happens even when i switched the initial stream to prof, and i do not understand why this is happening?

StreamBuilder(
            stream:socialPressed==true?socStream:proStream,
            builder:
                (context, AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
              if (!snapshots.hasData) {
                return Container(
                    alignment: FractionalOffset.center,
                    child: CircularProgressIndicator());
              } else {
               return Container(
                    child: Container(
                      child: (snapshots.data.length == 0)
                          Container(
                        height: MediaQuery.of(context).size.height * 2 / 3,
                        child: ListView.builder(
                          itemBuilder: (context, index) {
                            DocumentSnapshot doc = snapshots.data[index];
                          return UserTile('this is where i use the doc data')},
                          itemCount: snapshots.data.length,
                        ),),));}},)

This is the basic structure of my code, i have removed irrelevant info.

EDIT:
Button callback code was requested:

 FloatingActionButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(16.0))),
                onPressed: () {
                  setState(() {
                    likeType='social';
                    socialPressed=!socialPressed;
                  });
                },
                elevation: 0,
                heroTag: 'socialButton',
                backgroundColor: socialPressed==false?Colors.grey[100]:Color(0xFFe0bdff),
                child: Icon(
                  Entypo.drink,
                  color: Color(0xFF8803fc),
                ),
              ),
              FloatingActionButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(16.0))),
                onPressed: () {
                  setState(() {
                    likeType='prof';
                    socialPressed=!socialPressed;
                  });
                },
                elevation: 0,
                heroTag: 'profButton',
                backgroundColor: socialPressed==true?Colors.grey[100]:Color(0xFFb9ebe9),
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      width: MediaQuery.of(context).size.width / 30,
                    ),
                    Icon(
                      FontAwesome.graduation_cap,
                      color: Color(0xFF096664),
                    ),
                  ],

                ),
              ),

Body:
I too faced this issue. I am using RX Dart and tried to switch streams based on a boolean variable.

I was initially using PublishSubject for my stream. Switching to Behaviour Subject solved the issue for me. At this moment I don't have sufficient knowledge on why this works but would try to explore it further and edit here if possible.

Previous code :

final _activeOrdersFetcher = PublishSubject<OrderListModel>();
final _completedOrdersFetcher = PublishSubject<OrderListModel>();

StreamBuilder<OrderListModel>(
      stream: isActive
          ? _ordersBloc.getActiveOrders
          : _ordersBloc.getCompletedOrders

New Code Change :

final _activeOrdersFetcher = BehaviorSubject<OrderListModel>();
final _completedOrdersFetcher = BehaviorSubject<OrderListModel>();


问:
How to solve "type is partially unknown" warning from pyright?
I'm using strict type checks via pyright.

When I have a method that returns a pytorch DataLoader, then pyright complains about my type definition:

Declared return type, "DataLoader[Unknown]", is partially unknown
  Pyright (reportUnknownVariableType)

Taking a look at the type stub from pytorch's DataLoader (reduced to the important parts):

```<code>class DataLoader(Generic[T_co]):
    dataset: Dataset[T_co]

    @overload
    def __init__(self, dataset: Dataset[T_co], ...
</code>```

As far as I can see, the generic type T_co of the DataLoader should be defined by the __init__ dataset parameter.

Pyright also complains about my Dataset type definition:

Type of parameter "dataset" is partially unknown
    Parameter type is "Dataset[Unknown]"
  Pyright (reportUnknownParameterType)

Taking a look at the Dataset type stub:

```<code>class Dataset(Generic[T_co]):
    def __getitem__(self, index: int) -> T_co: ...
</code>```

shows to me that the type should be inferred by the return type of __getitem__.

My dataset's type signature of __getitem__ looks like this:

```<code>def __getitem__(self, index: int) -> Tuple[Tensor, Tensor]:
</code>```

Based on this I would expect Dataset and DataLoader to be inferred as Dataset[Tuple[Tensor, Tensor]] and DataLoader[Tuple[Tensor, Tensor]] but that is not the case.

My guess is that pyright fails to statically infer the types here.

I thought I could define the type signature my self like this:

```<code>Dataset[Tuple[Tensor, Tensor]]
</code>```

but that actually results in my python script crashing with:

TypeError: 'type' object is not subscriptable

How can I properly define the type for Dataset and DataLoader?

答:
Since there was no reply on this question I was not sure if it is actually a bug in pyright. I therefore opened this issue on the github repository: https://github.com/microsoft/pyright/issues/698

Eric Traut explained in detail what the issue is and that pyright is working as designed.
I try to give the gist of the main points here.

Problem explanation

Pyright attempts to infer return types if they are not provided but if they are provided as in this case, they need to be fully typed. Pyright does not fill in missing parts of a given type annotation.

For example, pyright will try to infer the return type for the following function definition:

```<code>def get_dataset():
</code>```

But if the return type is given as Dataset then that is the return type pyright expects.

```<code>def get_dataset() -> Dataset:
</code>```

In this case Dataset is a generic class that does not handle subscripting like Dataset[int].
In Python 3.7 (what we are using) the Python interpreter will evaluate these type annotations what leads to the mentioned exception.

Solution

As of Python 3.10 the Python interpreter will no longer evaluate type annotations and the following type annotation will just work:

```<code>def get_dataset() -> Dataset[int]:
</code>```

As of Python 3.7 it is possible to enable this behavior via the following import:

```<code>from __future__ import annotations
</code>```

This is documented in PEP 563.
You will also need to disable the rule E1136 for pylint to not warn about "unsubscriptable-object".

Another workaround is to quote the type definition like this:

```<code>def get_dataset() -> "Dataset[int]":
</code>```

Body:
I'm using strict type checks via pyright.

When I have a method that returns a pytorch DataLoader, then pyright complains about my type definition:

Declared return type, "DataLoader[Unknown]", is partially unknown
  Pyright (reportUnknownVariableType)

Taking a look at the type stub from pytorch's DataLoader (reduced to the important parts):

class DataLoader(Generic[T_co]):
    dataset: Dataset[T_co]

    @overload
    def __init__(self, dataset: Dataset[T_co], ...

As far as I can see, the generic type T_co of the DataLoader should be defined by the __init__ dataset parameter.

Pyright also complains about my Dataset type definition:

Type of parameter "dataset" is partially unknown
    Parameter type is "Dataset[Unknown]"
  Pyright (reportUnknownParameterType)

Taking a look at the Dataset type stub:

class Dataset(Generic[T_co]):
    def __getitem__(self, index: int) -> T_co: ...

shows to me that the type should be inferred by the return type of __getitem__.

My dataset's type signature of __getitem__ looks like this:

def __getitem__(self, index: int) -> Tuple[Tensor, Tensor]:

Based on this I would expect Dataset and DataLoader to be inferred as Dataset[Tuple[Tensor, Tensor]] and DataLoader[Tuple[Tensor, Tensor]] but that is not the case.

My guess is that pyright fails to statically infer the types here.

I thought I could define the type signature my self like this:

Dataset[Tuple[Tensor, Tensor]]

but that actually results in my python script crashing with:

TypeError: 'type' object is not subscriptable

How can I properly define the type for Dataset and DataLoader?

Body:
Since there was no reply on this question I was not sure if it is actually a bug in pyright. I therefore opened this issue on the github repository: https://github.com/microsoft/pyright/issues/698

Eric Traut explained in detail what the issue is and that pyright is working as designed.
I try to give the gist of the main points here.

Problem explanation

Pyright attempts to infer return types if they are not provided but if they are provided as in this case, they need to be fully typed. Pyright does not fill in missing parts of a given type annotation.

For example, pyright will try to infer the return type for the following function definition:

def get_dataset():

But if the return type is given as Dataset then that is the return type pyright expects.

def get_dataset() -> Dataset:

In this case Dataset is a generic class that does not handle subscripting like Dataset[int].
In Python 3.7 (what we are using) the Python interpreter will evaluate these type annotations what leads to the mentioned exception.

Solution

As of Python 3.10 the Python interpreter will no longer evaluate type annotations and the following type annotation will just work:

def get_dataset() -> Dataset[int]:

As of Python 3.7 it is possible to enable this behavior via the following import:

from __future__ import annotations

This is documented in PEP 563.
You will also need to disable the rule E1136 for pylint to not warn about "unsubscriptable-object".

Another workaround is to quote the type definition like this:

def get_dataset() -> "Dataset[int]":


问:
AdWhirl implementation in iPhone Cocoa touch
i'm starting to implement AdWhirl in my application. i follow the instructions which is belong to adwhirl but i cant see any ad in my application.i add the following methods in my viewcontroller class

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
 AdWhirlView *adView=[AdWhirlView requestAdWhirlViewWithDelegate:self];
 [self.view addSubview:adView];
}

-(NSString *) adWhirlApplicationKey{
 return @"myAdWhirlKey";
}

-(UIViewController *) viewControllerForPresentingModalView{
 return self;
}
</code>```

i doesn't display anything. please help how to implement AdWhirl

答: You need to pass the AdWhirl SDK key in adWhirlApplicationKey delegate to work. check the link to get adWhirlkey... http://chandanshetty01.blogspot.com/2011/06/integrating-ads-to-ios-apps-using.html</p>

ContentLicense: CC BY-SA 2.5

Body:
i'm starting to implement AdWhirl in my application. i follow the instructions which is belong to adwhirl but i cant see any ad in my application.i add the following methods in my viewcontroller class

- (void)viewDidLoad {
    [super viewDidLoad];
 AdWhirlView *adView=[AdWhirlView requestAdWhirlViewWithDelegate:self];
 [self.view addSubview:adView];
}

-(NSString *) adWhirlApplicationKey{
 return @"myAdWhirlKey";
}

-(UIViewController *) viewControllerForPresentingModalView{
 return self;
}

i doesn't display anything. please help how to implement AdWhirl


问:
Why use an array-like object in Javascript?
I get that since javascript allows numeric keys for objects, the existence of array-like objects is therefore technically possible, but why did they ever become common?

Maybe the thought was that these array-like objects don't just have numeric keys, e.g. arguments has the callee property, so they can't be proper arrays to accommodate those properties.

But in javascript, it's perfectly valid to treat an array as an object and use non-numeric keys:

```<code>var myArguments = [];
myArguments[0] = 0;
myArguments['callee'] = function(){console.log('callee')};
</code>```

If the object is array-like and would benefit from having access to the functions it would otherwise inherit from the array prototype, what would be advantage of making it an array-like object instead?

Edit: in case it wasn't clear in my question, an array like object would be something like the arguments object that has sequential numeric properties starting from zero, and has a length property that is one less than the highest numeric key. It also doesn't inherit from the array prototype, and doesn't provide access to array methods.

答: There is no big advantage, as you can access objects and arrays in very similar ways, array[number] for arrays, and object.propery, and object["property"] for objects. Arrays are better for storing data, not functions, in my opinion, and objects are better for storing sets of functions, in my opinion. For example, arrays could store your answers in a memory game, but an object would store the command for the game, like start or end.

Body:
I get that since javascript allows numeric keys for objects, the existence of array-like objects is therefore technically possible, but why did they ever become common?

Maybe the thought was that these array-like objects don't just have numeric keys, e.g. arguments has the callee property, so they can't be proper arrays to accommodate those properties.

But in javascript, it's perfectly valid to treat an array as an object and use non-numeric keys:

var myArguments = [];
myArguments[0] = 0;
myArguments['callee'] = function(){console.log('callee')};

If the object is array-like and would benefit from having access to the functions it would otherwise inherit from the array prototype, what would be advantage of making it an array-like object instead?

Edit: in case it wasn't clear in my question, an array like object would be something like the arguments object that has sequential numeric properties starting from zero, and has a length property that is one less than the highest numeric key. It also doesn't inherit from the array prototype, and doesn't provide access to array methods.


问:
How to share html component amount different page
In ASP.NET, I have a master page, and five other pages which are under master page.

In all five pages, I need to implement a button, after clicking it, will generate different download results.

My original implementation is, in all five page, will all have a "Button", so in code behind will have corresponding event method to generate the download.

But my approach, will have duplicated html compoents.

Is there a way I can define the download button in my master page, when clicking button in different page, event method from different page will be invoked?

答: Yes you can, on master page you can have a Download Button and on it click check the URL, which will help you to identify the request has come from which page. Then you can write code on the basis of current page being displayed.</p>


问:
SAP UI5 Object List item with "title" as hyperlink
Please suggest Object List Item "title" with hyperlink and on click of it, should navigate to some url in a new tab.

<List items="{ path: 'sonarReport>/measures' }"
        id="sonarRepId"
        mode="SingleSelectMaster"
        selectionChange="onChange"
        updateFinished="onFinsihed">
    <ObjectListItem icon="{sonarReport>imageL}"
            **title="{sonarReport>value}"**
            class="sonarCustom"
            type="Active">
        <attributes>
            <ObjectAttribute text="{sonarReport>metric}"></ObjectAttribute>
        </attributes>
        <firstStatus>
            <ObjectStatus title="{sonarReport>state}"
                icon="{sonarReport>image}"
                state="Success"></ObjectStatus>
        </firstStatus>
    </ObjectListItem>
</List>
```

答:
you can opt to extend the ObjectListItem like this

  ObjectListItem.extend("ObjectListItemEx", {
    metadata: {
      events: {
        titlePress: {}
      }
    },
    renderer: {},
    onAfterRendering: function() {
      if (ObjectListItem.prototype.onAfterRendering) {
        ObjectListItem.prototype.onAfterRendering.apply(this, arguments);
      }
      var that = this;
      this.$().find(".sapMObjLTitle").each(function() {
        var $this = $(this);
        $this.click(function() {
          that.fireTitlePress();
        });
        $this.css("cursor", "pointer");
      });
    }
  });
```

demo: https://jsbin.com/hofumej/1/edit?js,output

Body:
you can opt to extend the ObjectListItem like this

  ObjectListItem.extend("ObjectListItemEx", {
    metadata: {
      events: {
        titlePress: {}
      }
    },
    renderer: {},
    onAfterRendering: function() {
      if (ObjectListItem.prototype.onAfterRendering) {
        ObjectListItem.prototype.onAfterRendering.apply(this, arguments);
      }
      var that = this;
      this.$().find(".sapMObjLTitle").each(function() {
        var $this = $(this);
        $this.click(function() {
          that.fireTitlePress();
        });
        $this.css("cursor", "pointer");
      });
    }
  });

demo: https://jsbin.com/hofumej/1/edit?js,output


问:
How to change PageView after change tabs?
I apologize immediately for my English). I found a code from a google, I installed it on an android studio, but the result of the code is not the one I want. When I click on the tab the control comes to another (for example, item1, item2, item3, item4) from item1 to item2 come in but the ListViev elements remain the same. How to make PageViev elements change after clicking tab control?

```<code>  final TabLayout tab=findViewById(R.id.tabs);
    final ViewPager viewPager=findViewById(R.id.view_pager);
    tab.removeAllTabs();
    for (int k = 0; k <GoodsGroupList.size(); k++) {
       tab.addTab(tab.newTab().setText("" + GoodsGroupList.get(k)));
    }

    tab.setTabMode(TabLayout.MODE_SCROLLABLE);
    PlansPagerAdapter adapter = new PlansPagerAdapter(getSupportFragmentManager(), tab.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab));
</code>```

Fragment_home.xml

```<code><com.google.android.material.tabs.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#000000"
    tools:ignore="MissingConstraints" />

<androidx.viewpager.widget.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="48dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_below="@+id/tabs"/>
</code>```

Fragment_menu.xml

```<code><ListView
    android:id="@+id/ListViewer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@drawable/list_divider"
    tools:ignore="MissingConstraints" />
</code>```

答:
Tabview does not change tab on touch

I found a similar problem and added part of the code and in May the problem was resolved.

```<code>tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                Log.d("Tab", String.valueOf(tab.getPosition()));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
</code>```

Body:
I apologize immediately for my English). I found a code from a google, I installed it on an android studio, but the result of the code is not the one I want. When I click on the tab the control comes to another (for example, item1, item2, item3, item4) from item1 to item2 come in but the ListViev elements remain the same. How to make PageViev elements change after clicking tab control?

  final TabLayout tab=findViewById(R.id.tabs);
    final ViewPager viewPager=findViewById(R.id.view_pager);
    tab.removeAllTabs();
    for (int k = 0; k <GoodsGroupList.size(); k++) {
       tab.addTab(tab.newTab().setText("" + GoodsGroupList.get(k)));
    }

    tab.setTabMode(TabLayout.MODE_SCROLLABLE);
    PlansPagerAdapter adapter = new PlansPagerAdapter(getSupportFragmentManager(), tab.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab));

Fragment_home.xml

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#000000"
    tools:ignore="MissingConstraints" />

<androidx.viewpager.widget.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="48dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_below="@+id/tabs"/>

Fragment_menu.xml

<ListView
    android:id="@+id/ListViewer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@drawable/list_divider"
    tools:ignore="MissingConstraints" />

Body:
Tabview does not change tab on touch

I found a similar problem and added part of the code and in May the problem was resolved.

tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                Log.d("Tab", String.valueOf(tab.getPosition()));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


问:
No execution for functions with scanf
```<code>void reg() {
    char name[60];
    char city[1000];
    puts("Name");
    scanf("%s", name);
    puts("City?");
    scanf("%s", city);
    FILE *fptr = fopen("./src/details.txt", "a");
    fputs(strncat(strncat(name, " ", 61), city, 1061), fptr);
    fclose(fptr);
}
</code>```

<p>When I call this function (present in another file) from main, it doesn't execute (program runs without any output). In fact, any function with scanf in my file doesn't execute. However, functions without scanf work fine. Could anyone tell me what's wrong? </p>

答:
To wait for a user input after printing the text, you must use fflush(stdout) to clear buffer.

Rather than:

```<code>puts("Name");
scanf("%s", name);
</code>```

Do:

```<code>puts("Name");
fflush(stdout); // this
scanf("%s", name);
</code>```

Title: No execution for functions with scanf

Body:
void reg() {
    char name[60];
    char city[1000];
    puts("Name");
    scanf("%s", name);
    puts("City?");
    scanf("%s", city);
    FILE *fptr = fopen("./src/details.txt", "a");
    fputs(strncat(strncat(name, " ", 61), city, 1061), fptr);
    fclose(fptr);
}

When I call this function (present in another file) from main, it doesn't execute (program runs without any output). In fact, any function with scanf in my file doesn't execute. However, functions without scanf work fine. Could anyone tell me what's wrong?

Body:
To wait for a user input after printing the text, you must use fflush(stdout) to clear buffer.

Rather than:

puts("Name");
scanf("%s", name);

Do:

puts("Name");
fflush(stdout); // this
scanf("%s", name);


问:
How to generate XML for label to print in Javascript using DYMO Connect for Desktop
I manage to print a label from DYMO Connect for Desktop v1.3.1. Now I am trying to print the same label using Javascript. The example PrintMeThatLabel.js is a great example. It contains three different label designs in XML. However, I would like to use the design I created wtih DYMO Connect for Desktop. When I try to use the Dymo file (which is an XML file with extension ".dymo") that was saved with DYMO Connect, I get the following error message if I load it with dymo.label.framework.openLabelXml():

```<code>{"message":"An error has occurred.","exceptionMessage":"'Element' is an invalid XmlNodeType. Line 22, position 4.","exceptionType":"System.Xml.XmlException","stackTrace":"   at System.Xml.XmlReader.ReadEndElement()\r\n   at DYMO.LabelAPI.DYMOLabel`1.Deserialize(XmlReader reader)\r\n   at DYMO.CrossPlatform.Common.Helpers.SerializationHelper.Deserialize[T](XmlReader reader)\r\n   at DYMO.LabelAPI.LabelHelper.ReadAndOpenLabel(XmlReader reader)\r\n   at DYMO.LabelAPI.LabelHelper.OpenLabel(XmlReader reader)\r\n   at DymoSDK.Implementations.DymoLabel.LoadLabelFromXML(String xmlContent)\r\n   at DYMOWebApi.Windows.Controllers.DymoDLSSDKController.GetListLabelsFromSetXML(String labelXml, String labelSetXml)\r\n   at DYMOWebApi.Windows.Controllers.DymoDLSSDKController.PrintLabel2(FormDataCollection formDataCollection)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"}:
    at Td (DYMO.Label.Framework.3.0.js:61)
    at ae (DYMO.Label.Framework.3.0.js:66)
    at be.printLabel2 (DYMO.Label.Framework.3.0.js:67)
    at Object.printLabel2 (DYMO.Label.Framework.3.0.js:101)
    at oe (DYMO.Label.Framework.3.0.js:126)
    at qe (DYMO.Label.Framework.3.0.js:129)
    at Y.G (DYMO.Label.Framework.3.0.js:74)
    at printLabel (207:608)
    at startupCode (207:617)
    at DYMO.Label.Framework.3.0.js:110
</code>```

If I use openLabelFile instead of openLabelXml I get this error in the console:

```<code>Uncaught Error: "Illegal characters in path."

"Illegal characters in path.":
    at Td (DYMO.Label.Framework.3.0.js:61)
    at ae (DYMO.Label.Framework.3.0.js:66)
    at be.openLabelFile (DYMO.Label.Framework.3.0.js:67)
    at Object.openLabelFile (DYMO.Label.Framework.3.0.js:101)
    at Object.openLabelFile (DYMO.Label.Framework.3.0.js:122)
    at printLabel (207:595)
    at startupCode (207:617)
    at DYMO.Label.Framework.3.0.js:110
    at e (DYMO.Label.Framework.3.0.js:115)
    at cd.<anonymous> (DYMO.Label.Framework.3.0.js:62)
</code>```

The XML in the file from DYMO Connect looks very different from the XML of the label designs in PrintMeThatLabel.js. Can anyone help me?

答:
I had the same problem as you this morning!

The newest javascript framework is not compatible with label templates created with Dymo Connect. You need to create it with the previous software. Version 8.3.1 works.

Watch out though, both softwares installed and your code won't recognize the printer. You'll need to uninstall both softwares and re-install Dymo Connect.

Hope this helps!
Yan

Body:
I manage to print a label from DYMO Connect for Desktop v1.3.1. Now I am trying to print the same label using Javascript. The example PrintMeThatLabel.js is a great example. It contains three different label designs in XML. However, I would like to use the design I created wtih DYMO Connect for Desktop. When I try to use the Dymo file (which is an XML file with extension ".dymo") that was saved with DYMO Connect, I get the following error message if I load it with dymo.label.framework.openLabelXml():

{"message":"An error has occurred.","exceptionMessage":"'Element' is an invalid XmlNodeType. Line 22, position 4.","exceptionType":"System.Xml.XmlException","stackTrace":"   at System.Xml.XmlReader.ReadEndElement()\r\n   at DYMO.LabelAPI.DYMOLabel`1.Deserialize(XmlReader reader)\r\n   at DYMO.CrossPlatform.Common.Helpers.SerializationHelper.Deserialize[T](XmlReader reader)\r\n   at DYMO.LabelAPI.LabelHelper.ReadAndOpenLabel(XmlReader reader)\r\n   at DYMO.LabelAPI.LabelHelper.OpenLabel(XmlReader reader)\r\n   at DymoSDK.Implementations.DymoLabel.LoadLabelFromXML(String xmlContent)\r\n   at DYMOWebApi.Windows.Controllers.DymoDLSSDKController.GetListLabelsFromSetXML(String labelXml, String labelSetXml)\r\n   at DYMOWebApi.Windows.Controllers.DymoDLSSDKController.PrintLabel2(FormDataCollection formDataCollection)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"}:
    at Td (DYMO.Label.Framework.3.0.js:61)
    at ae (DYMO.Label.Framework.3.0.js:66)
    at be.printLabel2 (DYMO.Label.Framework.3.0.js:67)
    at Object.printLabel2 (DYMO.Label.Framework.3.0.js:101)
    at oe (DYMO.Label.Framework.3.0.js:126)
    at qe (DYMO.Label.Framework.3.0.js:129)
    at Y.G (DYMO.Label.Framework.3.0.js:74)
    at printLabel (207:608)
    at startupCode (207:617)
    at DYMO.Label.Framework.3.0.js:110

If I use openLabelFile instead of openLabelXml I get this error in the console:

Uncaught Error: "Illegal characters in path."

"Illegal characters in path.":
    at Td (DYMO.Label.Framework.3.0.js:61)
    at ae (DYMO.Label.Framework.3.0.js:66)
    at be.openLabelFile (DYMO.Label.Framework.3.0.js:67)
    at Object.openLabelFile (DYMO.Label.Framework.3.0.js:101)
    at Object.openLabelFile (DYMO.Label.Framework.3.0.js:122)
    at printLabel (207:595)
    at startupCode (207:617)
    at DYMO.Label.Framework.3.0.js:110
    at e (DYMO.Label.Framework.3.0.js:115)
    at cd.<anonymous> (DYMO.Label.Framework.3.0.js:62)

The XML in the file from DYMO Connect looks very different from the XML of the label designs in PrintMeThatLabel.js. Can anyone help me?


问:
Linkedin Sharing web page does not show summary
We have been sharing our website pages and articles to LinkedIn for almost 4 years using

https://www.linkedin.com/shareArticle?mini=true&url=https://example.com/page1/

Until recently, the share block would appear with an image, caption and summary. Just as in Facebook. But now, we find that the summary does not show. I know many have raised this same concern here. One solution I saw in this forum is to switch to forcing visitors to sign into our LinkedIn app and post the status via REST API. My question is, Is this really necessary. We don't have a login feature for our website and to force people to login to LinkedIn app just to show description which is already part of the og tags on the page. Surely someone from LinkedIn can respond to this issue since so many have raised it.

答:
Just take a quick look at the Official LinkedIn "Making Your Website Shareable on LinkedIn" Documentation.  I will bold areas of particular interest:

If you're the developer of your website, you'll need to make sure the source code complies with Open Graph Protocol (OGP) and certain image requirements specific to LinkedIn....

Below are the og: tags that must exist and their correct format:

```<code><meta property='og:title' content='Title of the article"/>
<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>
<meta property='og:description' content='Description that will show in the preview"/>
<meta property='og:url' content='//www.example.com/URL of the article" />
</code>```

And the requirements...

Here are the image requirements specific to the LinkedIn sharing module:

Max file size: 5 MB

Minimum image dimensions: 1200 (w) x 627 (h) pixels

Recommended ratio: 1.91:1

So, if you want to make sure your image displays correctly in the LinkedIn share functionality, make sure your webpage has the following...

```<code><html>
<head>
<meta property="og:image" content="someweburl.jpg" />
</head>
...
</html>
</code>```

Hope this helps!

Body:
Just take a quick look at the Official LinkedIn "Making Your Website Shareable on LinkedIn" Documentation.  I will bold areas of particular interest:

If you're the developer of your website, you'll need to make sure the source code complies with Open Graph Protocol (OGP) and certain image requirements specific to LinkedIn....

Below are the og: tags that must exist and their correct format:

<meta property='og:title' content='Title of the article"/>
<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>
<meta property='og:description' content='Description that will show in the preview"/>
<meta property='og:url' content='//www.example.com/URL of the article" />

And the requirements...

Here are the image requirements specific to the LinkedIn sharing module:

Max file size: 5 MB

Minimum image dimensions: 1200 (w) x 627 (h) pixels

Recommended ratio: 1.91:1

So, if you want to make sure your image displays correctly in the LinkedIn share functionality, make sure your webpage has the following...

<html>
<head>
<meta property="og:image" content="someweburl.jpg" />
</head>
...
</html>

Hope this helps!


问:
Parse vector into correct types
Is there a way to convert a String to some other type dynamically? I have a vector of values in the format key:type:value that I'd like to convert to key value pairs where the value has been converted to the correct type. In this case the types map as: i=i64, and f=f64.

So far I have this:

fn main() {
    let arr: Vec<String> = vec!["A:i:49".to_string(), "B:f:0.1374".to_string()];

    let tup: Vec<_> = arr
        .iter()
        .map(|s| s.split(":").collect::<Vec<&str>>())
        .collect();

    println!("Arr: {:#?}", arr);
    println!("Tup: {:?}", tup)
}

// Arr: [
//     "A:i:49",
//     "B:f:0.1374",
// ]
// Tup: [["A", "i", "49"], ["B", "f", "0.1374"]]
```

<p>Looking to acheive something like:</p>

```[("A", 49), ("B", 0.1374)]
```

I've looked at generics/implementations but cannot work out what to do.

Note: any vec may have any key, so the next set could be ["A:i:99", "C:i:0"], types are limited to integers, floats, and strings.

答:
A solution using Enum wrapper type

```<code>#[derive(Debug)]
enum Value {
    IntVal(i32),
    FloatVal(f64),
}

let tup: Vec<_> = arr
    .iter()
    .map(|s| {
        let mut values = s.split(":");
        let first_tk = values.next().unwrap();
        let second_tk = values.next().unwrap();
        let third_tk = values.next().unwrap();
        let value = match second_tk {
            "i" => Value::IntVal(FromStr::from_str(third_tk).expect("Invalid int")),
            "f" => Value::FloatVal(FromStr::from_str(third_tk).expect("invalid float")),
            _ => panic!("unexpected pattern {}", second_tk),
        };
        (first_tk, value)
    })
    .collect();
</code>```

playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0e8ae249e91cb0055f09c9b1bd96ebde

Note: You need to do proper error handling and current code just panics whenever it encounters unexpected value. You need to use Result type for that. Also, you could explore FromStr trait to parse from string

Title: Parse vector into correct types

Body:
Is there a way to convert a String to some other type dynamically? I have a vector of values in the format key:type:value that I'd like to convert to key value pairs where the value has been converted to the correct type. In this case the types map as: i=i64, and f=f64.

So far I have this:

fn main() {
    let arr: Vec<String> = vec!["A:i:49".to_string(), "B:f:0.1374".to_string()];

    let tup: Vec<_> = arr
        .iter()
        .map(|s| s.split(":").collect::<Vec<&str>>())
        .collect();

    println!("Arr: {:#?}", arr);
    println!("Tup: {:?}", tup)
}

// Arr: [
//     "A:i:49",
//     "B:f:0.1374",
// ]
// Tup: [["A", "i", "49"], ["B", "f", "0.1374"]]

Looking to acheive something like:

[("A", 49), ("B", 0.1374)]

I've looked at generics/implementations but cannot work out what to do.

Note: any vec may have any key, so the next set could be ["A:i:99", "C:i:0"], types are limited to integers, floats, and strings.

Body:
A solution using Enum wrapper type

#[derive(Debug)]
enum Value {
    IntVal(i32),
    FloatVal(f64),
}

let tup: Vec<_> = arr
    .iter()
    .map(|s| {
        let mut values = s.split(":");
        let first_tk = values.next().unwrap();
        let second_tk = values.next().unwrap();
        let third_tk = values.next().unwrap();
        let value = match second_tk {
            "i" => Value::IntVal(FromStr::from_str(third_tk).expect("Invalid int")),
            "f" => Value::FloatVal(FromStr::from_str(third_tk).expect("invalid float")),
            _ => panic!("unexpected pattern {}", second_tk),
        };
        (first_tk, value)
    })
    .collect();

playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0e8ae249e91cb0055f09c9b1bd96ebde

Note: You need to do proper error handling and current code just panics whenever it encounters unexpected value. You need to use Result type for that. Also, you could explore FromStr trait to parse from string


问:
Array of filtered data to populate ListBox
Okay so I am filtering a sheet ("Data") by a criteria:

```<code>Sub Filter_Offene()
    Sheets("Data").Range("A:R").AutoFilter Field:=18, Criteria1:="WAHR"
End Sub

</code>```

Then, I want to put the Filtered Table to populate a Listbox
My problem here is, that the amount of rows can vary, so I thought i could try and list where the filtered table "ends" by doing this cells.find routine:

```<code>Dim lRow As Long
Dim lCol As Long

    lRow = ThisWorkbook.Sheets("Data").Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lRow = lRow + 1
</code>```

This unfotunatly also counts "hidden" rows, so in my example it doesnt count 2 but 7..
I've used .Range.SpecialCells(xlCellTypeVisible)before, but It doesn't seem to function with the cells.find above.
Does someone have an Idea on how I can count the visible (=filtered) Table, and then put it in a Listbox?

EDIT: I populate the listbox (unfiltered) like this:

```<code>Dim lastrow As Long
With Sheets("Data")
    lastrow = .Cells(.Rows.Count, "R").End(xlUp).Row
End With

With Offene_PZ_Form.Offene_PZ
.ColumnCount = 18
.ColumnWidths = "0;80;0;100;100;0;50;50;80;50;0;0;0;0;0;150;150;0"
.List = Sheets("Data").Range("A2:R" & lastrow).Value
End With
</code>```

But this won't work with filtered Data.

答:
Here is a VBA code to populate UserForm1.ListBox1.List with filtered rows.
Thanks to @FaneDuru for improvements in the code edited as per his comments.

In Userform1 code

```<code>Private Sub UserForm_Initialize()
PopulateListBoxWithVisibleCells
End Sub
</code>```

In Module

Sub PopulateListBoxWithVisibleCells()

```<code>Dim wb As Workbook, ws As Worksheet
Dim filtRng As Range, rw As Range
Dim i As Long, j As Long, x As Long, y As Long, k As Long, filtRngArr
i = 0: j = 0: x = 0: y = 0

Set wb = ThisWorkbook: Set ws = wb.Sheets("Sheet1")

Set filtRng = ws.UsedRange.Cells.SpecialCells(xlCellTypeVisible)

For Each Area In filtRng.Areas
x = x + Area.Rows.Count
Next
y = filtRng.Columns.Count
ReDim filtRngArr(1 To x, 1 To y)

For k = 1 To filtRng.Areas.Count
For Each rw In filtRng.Areas(k).Rows
    i = i + 1
    arr = rw.Value
    For j = 1 To y
    filtRngArr(i, j) = Split(Join(Application.Index(arr, 1, 0), "|"), "|")(j - 1)

    Next
Next
Next

With UserForm1.ListBox1
.ColumnCount = y
.List = filtRngArr
End With

End Sub
</code>```

We can also add more fields say row number like Split(rw.Row & "|" & Join(Application.Index(arr, 1, 0), "|"), "|")(j - 1) but for every such intended column increments, we need to increment value of y like y = filtRng.Columns.Count + 1

In order to find x (Number of rows) we don't need the first loop... Simply, x = filtRng.Cells.Count / filtRng.Columns.Count is enough

Body:
Okay so I am filtering a sheet ("Data") by a criteria:

Sub Filter_Offene()
    Sheets("Data").Range("A:R").AutoFilter Field:=18, Criteria1:="WAHR"
End Sub

Then, I want to put the Filtered Table to populate a Listbox
My problem here is, that the amount of rows can vary, so I thought i could try and list where the filtered table "ends" by doing this cells.find routine:

Dim lRow As Long
Dim lCol As Long

    lRow = ThisWorkbook.Sheets("Data").Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lRow = lRow + 1

This unfotunatly also counts "hidden" rows, so in my example it doesnt count 2 but 7..
I've used .Range.SpecialCells(xlCellTypeVisible)before, but It doesn't seem to function with the cells.find above.
Does someone have an Idea on how I can count the visible (=filtered) Table, and then put it in a Listbox?

EDIT: I populate the listbox (unfiltered) like this:

Dim lastrow As Long
With Sheets("Data")
    lastrow = .Cells(.Rows.Count, "R").End(xlUp).Row
End With

With Offene_PZ_Form.Offene_PZ
.ColumnCount = 18
.ColumnWidths = "0;80;0;100;100;0;50;50;80;50;0;0;0;0;0;150;150;0"
.List = Sheets("Data").Range("A2:R" & lastrow).Value
End With

But this won't work with filtered Data.

Body:
Here is a VBA code to populate UserForm1.ListBox1.List with filtered rows.
Thanks to @FaneDuru for improvements in the code edited as per his comments.

In Userform1 code

Private Sub UserForm_Initialize()
PopulateListBoxWithVisibleCells
End Sub

In Module

Sub PopulateListBoxWithVisibleCells()

Dim wb As Workbook, ws As Worksheet
Dim filtRng As Range, rw As Range
Dim i As Long, j As Long, x As Long, y As Long, k As Long, filtRngArr
i = 0: j = 0: x = 0: y = 0

Set wb = ThisWorkbook: Set ws = wb.Sheets("Sheet1")

Set filtRng = ws.UsedRange.Cells.SpecialCells(xlCellTypeVisible)

For Each Area In filtRng.Areas
x = x + Area.Rows.Count
Next
y = filtRng.Columns.Count
ReDim filtRngArr(1 To x, 1 To y)

For k = 1 To filtRng.Areas.Count
For Each rw In filtRng.Areas(k).Rows
    i = i + 1
    arr = rw.Value
    For j = 1 To y
    filtRngArr(i, j) = Split(Join(Application.Index(arr, 1, 0), "|"), "|")(j - 1)

    Next
Next
Next

With UserForm1.ListBox1
.ColumnCount = y
.List = filtRngArr
End With

End Sub

We can also add more fields say row number like Split(rw.Row & "|" & Join(Application.Index(arr, 1, 0), "|"), "|")(j - 1) but for every such intended column increments, we need to increment value of y like y = filtRng.Columns.Count + 1

In order to find x (Number of rows) we don't need the first loop... Simply, x = filtRng.Cells.Count / filtRng.Columns.Count is enough


问:
Preventing UICollectionView from scrolling outside of contentOffset
I created a collectionView with 4 cells, the cell frames are equal to the entire window frame so that I can scroll through them as they were a PageViewController.

```<code>lazy var collectionView : PagesCollectionView = {
  let layout = UICollectionViewFlowLayout()
   layout.scrollDirection = .horizontal
  layout.minimumLineSpacing = 0
    let collectionView = PagesCollectionView(frame: .zero, collectionViewLayout: layout)
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.isPagingEnabled = true
    collectionView.alwaysBounceHorizontal = false

    return collectionView
}()
</code>```

The goal I want to accomplish is that when I am in the first cell and scroll on the left (contentOffset negative) the collectionView scrolling stops, and when I am on the last cell the collectionView stops scrolling in the right direction, I want to see the cell still.

I tried different procedures:
This one blocked the scrollView only after having scrolled it in the first place, never re-enabling the scrolling in the other direction:

```<code> func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if(scrollView.contentOffset.x == 0){
        scrollView.isScrollEnabled = false
    }

}
</code>```

As suggested on other StackOverflow topics:

```<code>  func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if(scrollView.contentOffset.x == 0){
            collectionView.isScrollEnabled = false

        }

        collectionView.isScrollEnabled = true

    }
</code>```

But this just blocks the scrolling in both directions.
I actually don't know how to solve this.

答:
I actually figured out how to solve this problem, it's really easy.

In my viewDidLoad method where I set the collectionView I set bounces equal to false:

```<code> collectionView.bounces = false
</code>```

Body:
I created a collectionView with 4 cells, the cell frames are equal to the entire window frame so that I can scroll through them as they were a PageViewController.

lazy var collectionView : PagesCollectionView = {
  let layout = UICollectionViewFlowLayout()
   layout.scrollDirection = .horizontal
  layout.minimumLineSpacing = 0
    let collectionView = PagesCollectionView(frame: .zero, collectionViewLayout: layout)
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.isPagingEnabled = true
    collectionView.alwaysBounceHorizontal = false

    return collectionView
}()

The goal I want to accomplish is that when I am in the first cell and scroll on the left (contentOffset negative) the collectionView scrolling stops, and when I am on the last cell the collectionView stops scrolling in the right direction, I want to see the cell still.

I tried different procedures:
This one blocked the scrollView only after having scrolled it in the first place, never re-enabling the scrolling in the other direction:

 func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if(scrollView.contentOffset.x == 0){
        scrollView.isScrollEnabled = false
    }

}

As suggested on other StackOverflow topics:

  func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if(scrollView.contentOffset.x == 0){
            collectionView.isScrollEnabled = false

        }

        collectionView.isScrollEnabled = true

    }

But this just blocks the scrolling in both directions.
I actually don't know how to solve this.

Body:
I actually figured out how to solve this problem, it's really easy.

In my viewDidLoad method where I set the collectionView I set bounces equal to false:

 collectionView.bounces = false


问:
Generate TYPECASE with macro in Common Lisp
I have a list of two element sublists which will change and grow in the course of the program. I want to write a macro which takes a key and generates a case dynamically like:

```<code>;; This is the List for saving CASE clauses
(setf l '((number 2) (symbol 3)))

;; and i want to have the following expansion
(typecase 'y
  (number 2)
  (symbol 3))
</code>```

I could have a macro which only refers to the global l:

```<code>(defmacro m (x)
  `(typecase ,x ,@l))
</code>```

which would expand correctly

```<code>(m 'y)  ;expands to (TYPECASE 'Y (number 2) (symbol 3))
</code>```

But how can i write the macro with a parameter for the list l so that it would work with other lists as well?

```<code>;; A macro which should generate the case based on the above list
(defmacro m (x l)
  `(typecase ,x ,@l))
</code>```

This doesn't work since l in the arguments list i a symbol and a call to (m 'y l) will expand to (TYPECASE 'Y . L).

Wanting to adhere to typecase mechanism, my workaround was as follows:

```<code>(setf types-x '(((integer 0 *) 38)
                ((eql neli) "Neli in X")
                (symbol 39))
            )
(setf types-y '(((eql neli) "Neli in Y")
                ((array bit *) "A Bit Vector")))

(defmacro m (x types-id)
  (case types-id
    (:x `(typecase ,x ,@types-x))
    (:y `(etypecase ,x ,@types-y))))

(m 'neli :x)                ;"Neli in X"
(m 'neli :y)                ;"Neli in Y"
(m 'foo :x)             ;39
</code>```

Any hints and comments is appreciated.

答:
You don't need a macro for what you're trying to do: use a function.

For instance, given

```<code>(defvar *type-matches*
  '((float 0)
    (number 1)
    (t 3)))
</code>```

Then

```<code>(defun type-match (thing &optional (against *type-matches*))
  (loop for (type val) in against
        when (typep thing type)
        return (values val type)
        finally (return (values nil nil))))
</code>```

Will match a thing against a type:

```<code>> (type-match 1.0)
0
float

> (type-match 1)
1
number
</code>```

You want to keep the variables sorted by type, which you can do by, for instance:

```<code>(setf *type-matches* (sort *type-matches* #'subtypep :key #'car))
</code>```

You want to keep the matches sorted of course.

If you want to delay the execution of the forms then you can do something like this (this also deals with sorting the types):

```<code>(defvar *type-matches*
  '())

(defmacro define-type-match (type/spec &body forms)
  ;; define a type match, optionally in a specified list
  (multiple-value-bind (type var)
      (etypecase type/spec
        (symbol (values type/spec '*type-matches*))
        (cons (values (first type/spec) (second type/spec))))
    (let ((foundn (gensym "FOUND")))
      `(let ((,foundn (assoc ',type ,var :test #'equal)))
         (if ,foundn
             (setf (cdr ,foundn) (lambda () ,@forms))
           (setf ,var (sort (acons ',type (lambda () ,@forms) ,var)
                            #'subtypep :key #'car)))
         ',type/spec))))

(defun type-match (thing &optional (against *type-matches*))
  (loop for (type . f) in against
        when (typep thing type)
        return (values (funcall f) type)
        finally (return (values nil nil))))
</code>```

Body:
I have a list of two element sublists which will change and grow in the course of the program. I want to write a macro which takes a key and generates a case dynamically like:

;; This is the List for saving CASE clauses
(setf l '((number 2) (symbol 3)))

;; and i want to have the following expansion
(typecase 'y
  (number 2)
  (symbol 3))

I could have a macro which only refers to the global l:

(defmacro m (x)
  `(typecase ,x ,@l))

which would expand correctly

(m 'y)  ;expands to (TYPECASE 'Y (number 2) (symbol 3))

But how can i write the macro with a parameter for the list l so that it would work with other lists as well?

;; A macro which should generate the case based on the above list
(defmacro m (x l)
  `(typecase ,x ,@l))

This doesn't work since l in the arguments list i a symbol and a call to (m 'y l) will expand to (TYPECASE 'Y . L).

Wanting to adhere to typecase mechanism, my workaround was as follows:

(setf types-x '(((integer 0 *) 38)
                ((eql neli) "Neli in X")
                (symbol 39))
            )
(setf types-y '(((eql neli) "Neli in Y")
                ((array bit *) "A Bit Vector")))

(defmacro m (x types-id)
  (case types-id
    (:x `(typecase ,x ,@types-x))
    (:y `(etypecase ,x ,@types-y))))

(m 'neli :x)                ;"Neli in X"
(m 'neli :y)                ;"Neli in Y"
(m 'foo :x)             ;39

Any hints and comments is appreciated.

Body:
You don't need a macro for what you're trying to do: use a function.

For instance, given

(defvar *type-matches*
  '((float 0)
    (number 1)
    (t 3)))

Then

(defun type-match (thing &optional (against *type-matches*))
  (loop for (type val) in against
        when (typep thing type)
        return (values val type)
        finally (return (values nil nil))))

Will match a thing against a type:

> (type-match 1.0)
0
float

> (type-match 1)
1
number

You want to keep the variables sorted by type, which you can do by, for instance:

(setf *type-matches* (sort *type-matches* #'subtypep :key #'car))

You want to keep the matches sorted of course.

If you want to delay the execution of the forms then you can do something like this (this also deals with sorting the types):

(defvar *type-matches*
  '())

(defmacro define-type-match (type/spec &body forms)
  ;; define a type match, optionally in a specified list
  (multiple-value-bind (type var)
      (etypecase type/spec
        (symbol (values type/spec '*type-matches*))
        (cons (values (first type/spec) (second type/spec))))
    (let ((foundn (gensym "FOUND")))
      `(let ((,foundn (assoc ',type ,var :test #'equal)))
         (if ,foundn
             (setf (cdr ,foundn) (lambda () ,@forms))
           (setf ,var (sort (acons ',type (lambda () ,@forms) ,var)
                            #'subtypep :key #'car)))
         ',type/spec))))

(defun type-match (thing &optional (against *type-matches*))
  (loop for (type . f) in against
        when (typep thing type)
        return (values (funcall f) type)
        finally (return (values nil nil))))


问:
AddEventListener for an array element is not a function
I want to receive the input and if it has some mistakes regarding the pre-typed text I want to (1) highlight the mistakes with the red color and (2) on hover show the correct version of the words.

I've managed to do the first part but I'm struggling with the second idea.

Here is my code:

let string = "The quick brown fox jumps over lazy the lazy dog";
let input = document.querySelector(".js-textarea");

let showRight = function(word) {
  let rightWord = document.querySelector(".right-word");
  rightWord.classList.remove("none");
  rightWord.innerText = word;
}

let checkValue = function() {
  let receivedValue = input.value.split(/(\s+)/).filter( e => e.trim().length > 0);
  let splitString = string.split(/(\s+)/).filter( e => e.trim().length > 0);
  for (let i = 0; i < receivedValue.length; i++) {
    if (receivedValue[i] !== splitString[i]) {
      receivedValue[i] = ''+receivedValue[i]+'';
      receivedValue[i].addEventListener('mouseover', showRight(splitString[i]));
    }
  }
  let output = receivedValue.join(" ");
  let correctedText = document.querySelector(".text");
  correctedText.innerHTML = output;
}

input.addEventListener("change",checkValue);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.error {
  color: red;
}

.matches {
   color: black
}

.related {
  position: related;
}

.absolute {
  position: absolute;
}

.none {
  display: none;
}

.right-word {
  top: -10px;
  left: 0;
}</code>```

  <textarea class="js-textarea"></textarea>

```

I don't really understand why it shows me that the addEventListener part is not a function. I assume it has to do something with the array, but I don't really see the problem.

Can anyone help me, please?

答:
Cuplrit statements:-

```<code>  receivedValue[i] = '<span class="error related">'+receivedValue[i]+'</span>';
  receivedValue[i].addEventListener('mouseover', showRight(splitString[i]));
</code>```

receivedValue[i] is being set to a string. And you're calling addEventListener on a string which is invalid. addEventListener should be called on a DOM element.

Body:
I want to receive the input and if it has some mistakes regarding the pre-typed text I want to (1) highlight the mistakes with the red color and (2) on hover show the correct version of the words.

I've managed to do the first part but I'm struggling with the second idea.

Here is my code:

let string = "The quick brown fox jumps over lazy the lazy dog";
let input = document.querySelector(".js-textarea");

let showRight = function(word) {
  let rightWord = document.querySelector(".right-word");
  rightWord.classList.remove("none");
  rightWord.innerText = word;
}

let checkValue = function() {
  let receivedValue = input.value.split(/(\s+)/).filter( e => e.trim().length > 0);
  let splitString = string.split(/(\s+)/).filter( e => e.trim().length > 0);
  for (let i = 0; i < receivedValue.length; i++) {
    if (receivedValue[i] !== splitString[i]) {
      receivedValue[i] = ''+receivedValue[i]+'';
      receivedValue[i].addEventListener('mouseover', showRight(splitString[i]));
    }
  }
  let output = receivedValue.join(" ");
  let correctedText = document.querySelector(".text");
  correctedText.innerHTML = output;
}

input.addEventListener("change",checkValue);

.error {
  color: red;
}

.matches {
   color: black
}

.related {
  position: related;
}

.absolute {
  position: absolute;
}

.none {
  display: none;
}

.right-word {
  top: -10px;
  left: 0;
}

  <textarea class="js-textarea"></textarea>

I don't really understand why it shows me that the addEventListener part is not a function. I assume it has to do something with the array, but I don't really see the problem.

Can anyone help me, please?

Body:
Cuplrit statements:-

  receivedValue[i] = '<span class="error related">'+receivedValue[i]+'</span>';
  receivedValue[i].addEventListener('mouseover', showRight(splitString[i]));

receivedValue[i] is being set to a string. And you're calling addEventListener on a string which is invalid. addEventListener should be called on a DOM element.


问:
Gedit command not working in kali linux terminal
Why Gedit command not working in kali linux terminal?

I am using kali in VMware and i am very new at it. Some basic commands are working fine but problem is when i am using gedit command to edit text file in gui, gedit does not work rather *terminal says - * "gedit: command not found" this.. Do i have to do something manually or actually what is the problem..? And i don't find any clear solution in online.

答:
Although I am not sure, what the actual error here is, but purging the package will help.

You can try this

```<code>sudo apt-get purge gedit gedit-common
sudo apt-get clean
</code>```

After this try reinstalling with

```<code>sudo apt-get install gedit
</code>```

Moreover, you should Prefer AskUbuntu and SuperUser for such questions, you can expect a detailed and possibly faster response.

Body:
Although I am not sure, what the actual error here is, but purging the package will help.

You can try this

sudo apt-get purge gedit gedit-common
sudo apt-get clean

After this try reinstalling with

sudo apt-get install gedit

Moreover, you should Prefer AskUbuntu and SuperUser for such questions, you can expect a detailed and possibly faster response.