问:
"Job aborted due to stage failure" when using CreateDataFrame in SparkR
Following the instructions in this post (https://spark.apache.org/docs/latest/sparkr.html#from-local-data-frames) I am creating a sparkdataframe using the following code:

```<code>library(SparkR, lib.loc = c(file.path(Sys.getenv("SPARK_HOME"), "R", "lib")))
sparkR.session(master = "spark://master:7077", sparkConfig = list(spark.cores.max="8", spark.executor.cores = "4"))
data(iris)
iris = createDataFrame(iris)
head(iris)
</code>```

But the head function always leads to the below error. I get the same error when I try to run dim as well. I have also tried as.DataFrame instead of createDataFrame.  I have also tried restarting the kernel in my ipython notebook and restarting my spark session.

My understanding is that this is a pretty basic function of SparkR, so I am really at a loss for why it isn't working. For some reason, when I read my SparkDataFrame diectly from a data source using read.jdbc I have no problem. Also, I noticed that the number in the line of the error ":Task 0 in stage XXX.." increments by one each time it fails.

I also noticed that the error seems to be coming from the fact that the executors can't find the binary for Rscript, though I'm not sure why this would be happening only for SparkDataFrames that are created from local data.frames, and not from ones that are pulled from an external datasource.

Could someone please help me with this?

The full error stack trace is:

Warning message in FUN(X[[i]], ...): “Use Sepal_Length instead of
  Sepal.Length  as column name”Warning message in FUN(X[[i]], ...): “Use
  Sepal_Width instead of Sepal.Width  as column name”Warning message in
  FUN(X[[i]], ...): “Use Petal_Length instead of Petal.Length  as column
  name”Warning message in FUN(X[[i]], ...): “Use Petal_Width instead of
  Petal.Width  as column name”

Error in invokeJava(isStatic = TRUE,
  className, methodName, ...): org.apache.spark.SparkException: Job
  aborted due to stage failure: Task 0 in stage 45.0 failed 4 times,
  most recent failure: Lost task 0.3 in stage 45.0 (TID 3372, 10.0.0.5):
  java.io.IOException: Cannot run program "Rscript": error=2, No such
  file or directory     at
  java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)  at
  org.apache.spark.api.r.RRunner$.createRProcess(RRunner.scala:348)     at
  org.apache.spark.api.r.RRunner$.createRWorker(RRunner.scala:364)  at
  org.apache.spark.api.r.RRunner.compute(RRunner.scala:69)  at
  org.apache.spark.api.r.BaseRRDD.compute(RRDD.scala:49)    at
  org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)   at
  org.apache.spark.rdd.RDD.iterator(RDD.scala:283)  at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70)    at
  org.apache.spark.scheduler.Task.run(Task.scala:85)    at
  org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748) Caused by:
  java.io.IOException: error=2, No such file or directory   at
  java.lang.UNIXProcess.forkAndExec(Native Method)  at
  java.lang.UNIXProcess.(UNIXProcess.java:247)    at
  java.lang.ProcessImpl.start(ProcessImpl.java:134)     at
  java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)  ... 24 more

Driver stacktrace:    at
  org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1450)
    at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1438)
    at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1437)
    at
  scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at
  org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1437)
    at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811)
    at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811)
    at scala.Option.foreach(Option.scala:257)   at
  org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:811)
    at
  org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1659)
    at
  org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1618)
    at
  org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1607)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at
  org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:632)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1871)    at
  org.apache.spark.SparkContext.runJob(SparkContext.scala:1884)     at
  org.apache.spark.SparkContext.runJob(SparkContext.scala:1897)     at
  org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:347)
    at
  org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:39)
    at
  org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$execute$1$1.apply(Dataset.scala:2183)
    at
  org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
    at
  org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2532)
    at
  org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$execute$1(Dataset.scala:2182)
    at
  org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$collect$1.apply(Dataset.scala:2187)
    at
  org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$collect$1.apply(Dataset.scala:2187)
    at org.apache.spark.sql.Dataset.withCallback(Dataset.scala:2545)    at
  org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collect(Dataset.scala:2187)
    at org.apache.spark.sql.Dataset.collect(Dataset.scala:2163)     at
  org.apache.spark.sql.api.r.SQLUtils$.dfToCols(SQLUtils.scala:208)     at
  org.apache.spark.sql.api.r.SQLUtils.dfToCols(SQLUtils.scala)  at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.apache.spark.api.r.RBackendHandler.handleMethodCall(RBackendHandler.scala:141)
    at
  org.apache.spark.api.r.RBackendHandler.channelRead0(RBackendHandler.scala:86)
    at
  org.apache.spark.api.r.RBackendHandler.channelRead0(RBackendHandler.scala:38)
    at
  io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
    at
  io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at
  io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at
  io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
    at
  io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at
  io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at
  io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:244)
    at
  io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at
  io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at
  io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:846)
    at
  io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
    at
  io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
    at
  io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
    at
  io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)     at
  io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:111)
    at
  io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
    at java.lang.Thread.run(Thread.java:745) Caused by:
  java.io.IOException: Cannot run program "Rscript": error=2, No such
  file or directory     at
  java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)  at
  org.apache.spark.api.r.RRunner$.createRProcess(RRunner.scala:348)     at
  org.apache.spark.api.r.RRunner$.createRWorker(RRunner.scala:364)  at
  org.apache.spark.api.r.RRunner.compute(RRunner.scala:69)  at
  org.apache.spark.api.r.BaseRRDD.compute(RRDD.scala:49)    at
  org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)   at
  org.apache.spark.rdd.RDD.iterator(RDD.scala:283)  at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark Traceback:

head(charEx)

head(charEx)

.local(x, ...)

take(x, num)

take(x, num)

collect(limited)

collect(limited)

.local(x, ...)

callJStatic("org.apache.spark.sql.api.r.SQLUtils", "dfToCols",   .     x@sdf)

invokeJava(isStatic = TRUE, className, methodName, ...)

stop(readString(conn))

答:
This is how i understand it:

The reason read.jdbc works is because, on the nodes, R is not needed to perform the operation: the driver (where R runs) translates the command to Spark before it gets copied to, and executed, on the worker nodes.

The reason createDataFrame fails is because that gets copied to the worker nodes as an R command, hence the nodes need to have access to Rscript.

If you want to use createDataFrame to be able to play around with your data a bit, i suggest you use a local Sparksession (otherwise you have to copy Rscript to your worker nodes). If you need to pass your data through R to get it into Spark in the first place, you may want to reconsider (you're probably using Spark because you have oodles of data, and it's usually better to load and keep everything on the Spark side and just pull, for instance, aggregated chunks to R in-memory).

Body:
Following the instructions in this post (https://spark.apache.org/docs/latest/sparkr.html#from-local-data-frames) I am creating a sparkdataframe using the following code:

library(SparkR, lib.loc = c(file.path(Sys.getenv("SPARK_HOME"), "R", "lib")))
sparkR.session(master = "spark://master:7077", sparkConfig = list(spark.cores.max="8", spark.executor.cores = "4"))
data(iris)
iris = createDataFrame(iris)
head(iris)

But the head function always leads to the below error. I get the same error when I try to run dim as well. I have also tried as.DataFrame instead of createDataFrame.  I have also tried restarting the kernel in my ipython notebook and restarting my spark session.

My understanding is that this is a pretty basic function of SparkR, so I am really at a loss for why it isn't working. For some reason, when I read my SparkDataFrame diectly from a data source using read.jdbc I have no problem. Also, I noticed that the number in the line of the error ":Task 0 in stage XXX.." increments by one each time it fails.

I also noticed that the error seems to be coming from the fact that the executors can't find the binary for Rscript, though I'm not sure why this would be happening only for SparkDataFrames that are created from local data.frames, and not from ones that are pulled from an external datasource.

Could someone please help me with this?

The full error stack trace is:

Warning message in FUN(X[[i]], ...): “Use Sepal_Length instead of
  Sepal.Length  as column name”Warning message in FUN(X[[i]], ...): “Use
  Sepal_Width instead of Sepal.Width  as column name”Warning message in
  FUN(X[[i]], ...): “Use Petal_Length instead of Petal.Length  as column
  name”Warning message in FUN(X[[i]], ...): “Use Petal_Width instead of
  Petal.Width  as column name”

Error in invokeJava(isStatic = TRUE,
  className, methodName, ...): org.apache.spark.SparkException: Job
  aborted due to stage failure: Task 0 in stage 45.0 failed 4 times,
  most recent failure: Lost task 0.3 in stage 45.0 (TID 3372, 10.0.0.5):
  java.io.IOException: Cannot run program "Rscript": error=2, No such
  file or directory     at
  java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)  at
  org.apache.spark.api.r.RRunner$.createRProcess(RRunner.scala:348)     at
  org.apache.spark.api.r.RRunner$.createRWorker(RRunner.scala:364)  at
  org.apache.spark.api.r.RRunner.compute(RRunner.scala:69)  at
  org.apache.spark.api.r.BaseRRDD.compute(RRDD.scala:49)    at
  org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)   at
  org.apache.spark.rdd.RDD.iterator(RDD.scala:283)  at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70)    at
  org.apache.spark.scheduler.Task.run(Task.scala:85)    at
  org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748) Caused by:
  java.io.IOException: error=2, No such file or directory   at
  java.lang.UNIXProcess.forkAndExec(Native Method)  at
  java.lang.UNIXProcess.(UNIXProcess.java:247)    at
  java.lang.ProcessImpl.start(ProcessImpl.java:134)     at
  java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)  ... 24 more

Driver stacktrace:    at
  org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1450)
    at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1438)
    at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1437)
    at
  scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at
  org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1437)
    at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811)
    at
  org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811)
    at scala.Option.foreach(Option.scala:257)   at
  org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:811)
    at
  org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1659)
    at
  org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1618)
    at
  org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1607)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at
  org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:632)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1871)    at
  org.apache.spark.SparkContext.runJob(SparkContext.scala:1884)     at
  org.apache.spark.SparkContext.runJob(SparkContext.scala:1897)     at
  org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:347)
    at
  org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:39)
    at
  org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$execute$1$1.apply(Dataset.scala:2183)
    at
  org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
    at
  org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2532)
    at
  org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$execute$1(Dataset.scala:2182)
    at
  org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$collect$1.apply(Dataset.scala:2187)
    at
  org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$collect$1.apply(Dataset.scala:2187)
    at org.apache.spark.sql.Dataset.withCallback(Dataset.scala:2545)    at
  org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collect(Dataset.scala:2187)
    at org.apache.spark.sql.Dataset.collect(Dataset.scala:2163)     at
  org.apache.spark.sql.api.r.SQLUtils$.dfToCols(SQLUtils.scala:208)     at
  org.apache.spark.sql.api.r.SQLUtils.dfToCols(SQLUtils.scala)  at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.apache.spark.api.r.RBackendHandler.handleMethodCall(RBackendHandler.scala:141)
    at
  org.apache.spark.api.r.RBackendHandler.channelRead0(RBackendHandler.scala:86)
    at
  org.apache.spark.api.r.RBackendHandler.channelRead0(RBackendHandler.scala:38)
    at
  io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
    at
  io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at
  io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at
  io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
    at
  io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at
  io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at
  io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:244)
    at
  io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at
  io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at
  io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:846)
    at
  io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
    at
  io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
    at
  io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
    at
  io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)     at
  io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:111)
    at
  io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
    at java.lang.Thread.run(Thread.java:745) Caused by:
  java.io.IOException: Cannot run program "Rscript": error=2, No such
  file or directory     at
  java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)  at
  org.apache.spark.api.r.RRunner$.createRProcess(RRunner.scala:348)     at
  org.apache.spark.api.r.RRunner$.createRWorker(RRunner.scala:364)  at
  org.apache.spark.api.r.RRunner.compute(RRunner.scala:69)  at
  org.apache.spark.api.r.BaseRRDD.compute(RRDD.scala:49)    at
  org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)   at
  org.apache.spark.rdd.RDD.iterator(RDD.scala:283)  at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)     at
  org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark Traceback:

head(charEx)

head(charEx)

.local(x, ...)

take(x, num)

take(x, num)

collect(limited)

collect(limited)

.local(x, ...)

callJStatic("org.apache.spark.sql.api.r.SQLUtils", "dfToCols",   .     x@sdf)

invokeJava(isStatic = TRUE, className, methodName, ...)

stop(readString(conn))


来源: stackexchange

问:
Open an XML, Read Text, Replace some Text, Write the file back in UTF-8 without BOM format
My IBM MQ is not accepting XML file saved in UTF-8 format. I want to try if it accepts UTF-8 without BOM format. I have tried multiple things, but was unable to save the file in non-BOM format. My code is below.

```<code>Dim objStreamUTF8      : Set objStreamUTF8      = CreateObject("ADODB.Stream")
Dim objStreamUTF8NoBOM : Set objStreamUTF8NoBOM = CreateObject("ADODB.Stream")

With objStreamUTF8
    .Charset = "UTF-8"
    .Mode = 3
    .Type = 2
    .Open
    objStreamUTF8.LoadFromFile uxtNewRenamePath'"C:\WINDOWS\Temp\DataFiles\TC10_ Apostrophe symbol in tag Cdtr_Adrline2_Pacs8_TxID201765133641.xml"
    objStreamUTF8.Flush
    strFileText = objStreamUTF8.ReadText()
    strFileText = Replace(strFileText,"&#", "&#")
    strFileText = Replace(Replace(Replace(Replace(Replace(strFileText, "GreaterThanSymbol", ">"), "LessThanSymbol", "<"), "ApostropheSymbol", "'"), "AmpersandSymbol", "&"), "DoubleQuotesSymbol", chr(34))
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    objFSO.DeleteFile uxtNewRenamePath, True
    Set objFSO = Nothing
    .Position = 0
    .Flush
    .WriteText strFileText
    .SaveToFile uxtNewRenamePath, 2
    .Close
    .Type = 1
    .Open
    .Position  = objStreamUTF8.Size
End With

With objStreamUTF8NoBOM
    .Mode = 3
    .Type = 1
    .Open
    objStreamUTF8.CopyTo objStreamUTF8NoBOM
    .SaveToFile uxtNewRenamePath, 2
End With

objStreamUTF8.Close
objStreamUTF8NoBOM.Close
</code>```

When objStreamUTF8NoBOM is saved to file, the file is completely blank. Can you please tell me what I am doing wrong or how I can save the file in the desired format?

答:
Got it. The position of the first stream has to be set to 3rd postion to skip BOM characters

i.e. objStreamUTF8.Position  = 3

ContentLicense: CC BY-SA 3.0

Body:
My IBM MQ is not accepting XML file saved in UTF-8 format. I want to try if it accepts UTF-8 without BOM format. I have tried multiple things, but was unable to save the file in non-BOM format. My code is below.

Dim objStreamUTF8      : Set objStreamUTF8      = CreateObject("ADODB.Stream")
Dim objStreamUTF8NoBOM : Set objStreamUTF8NoBOM = CreateObject("ADODB.Stream")

With objStreamUTF8
    .Charset = "UTF-8"
    .Mode = 3
    .Type = 2
    .Open
    objStreamUTF8.LoadFromFile uxtNewRenamePath'"C:\WINDOWS\Temp\DataFiles\TC10_ Apostrophe symbol in tag Cdtr_Adrline2_Pacs8_TxID201765133641.xml"
    objStreamUTF8.Flush
    strFileText = objStreamUTF8.ReadText()
    strFileText = Replace(strFileText,"&#", "&#")
    strFileText = Replace(Replace(Replace(Replace(Replace(strFileText, "GreaterThanSymbol", ">"), "LessThanSymbol", "<"), "ApostropheSymbol", "'"), "AmpersandSymbol", "&"), "DoubleQuotesSymbol", chr(34))
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    objFSO.DeleteFile uxtNewRenamePath, True
    Set objFSO = Nothing
    .Position = 0
    .Flush
    .WriteText strFileText
    .SaveToFile uxtNewRenamePath, 2
    .Close
    .Type = 1
    .Open
    .Position  = objStreamUTF8.Size
End With

With objStreamUTF8NoBOM
    .Mode = 3
    .Type = 1
    .Open
    objStreamUTF8.CopyTo objStreamUTF8NoBOM
    .SaveToFile uxtNewRenamePath, 2
End With

objStreamUTF8.Close
objStreamUTF8NoBOM.Close

When objStreamUTF8NoBOM is saved to file, the file is completely blank. Can you please tell me what I am doing wrong or how I can save the file in the desired format?


问:
How to append dynamically created div into current mainDiv not all the mainDiv when click on a button
I'm trying to appendTo a
 into current
 when click on a button. Now its appendTo all the class='mainDiv' & after the cloning. I need it only to the current clicked
. Can someone help me to solve it?

(function($) {

  function div2() {
    $('
').addClass('div2').text('This is a Content').appendTo('.mainDiv');
  }

  function cloneIt() {
    $('.mainDiv').clone().detach().appendTo('body');
  }

  $(document).on('click', '.div1', function() {
    div2();
  });

  $(document).on('click', 'span', function() {
    cloneIt();
  });

})(jQuery);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  display: flex;
  justify-content: space-around;
}

.mainDiv {
  background-color: #000;
  width: 100px;
  height: 100px;
  color: #fff;
  padding: 20px;
  margin-left: 15px;
  margin-right: 15px;
}

.div1 {
  background-color: blue;
  padding: 10px;
  cursor: pointer;
}

.div2 {
  background-color: red;
  padding: 10px;
}

span {
  display: block;
  padding: 10px;
  background-color: green;
  margin-bottom: 15px;
  cursor: pointer;
}</code>```

  Clone it

click to append div

```

答:
You can get the current element bu using $(this) and then get the parent using $(this).parent() and send it as parameter to the function div2($(this).parent()); and use it instead of using class selector

```<code>  function div2(item) {
    $('<div/>').addClass('div2').text('This is a Content').appendTo(item);
  }
</code>```

See code snippet:

(function($) {

  function div2(item) {
    if (item.has(".div2").length <= 0) {
      $('
').addClass('div2').text('This is a Content').appendTo(item);
    }

  }

  function cloneIt() {
    $('.mainDiv').clone().detach().appendTo('body');
  }

  $(document).on('click', '.div1', function() {
    div2($(this).parent());
  });

  $(document).on('click', 'span', function() {
    cloneIt();
  });

})(jQuery);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  display: flex;
  justify-content: space-around;
}

.mainDiv {
  background-color: #000;
  width: 100px;
  height: 100px;
  color: #fff;
  padding: 20px;
  margin-left: 15px;
  margin-right: 15px;
}

.div1 {
  background-color: blue;
  padding: 10px;
  cursor: pointer;
}

.div2 {
  background-color: red;
  padding: 10px;
}

span {
  display: block;
  padding: 10px;
  background-color: green;
  margin-bottom: 15px;
  cursor: pointer;
}</code>```

  Clone it

click to append div

```

Body:
I'm trying to appendTo a
 into current
 when click on a button. Now its appendTo all the class='mainDiv' & after the cloning. I need it only to the current clicked
. Can someone help me to solve it?

(function($) {

  function div2() {
    $('
').addClass('div2').text('This is a Content').appendTo('.mainDiv');
  }

  function cloneIt() {
    $('.mainDiv').clone().detach().appendTo('body');
  }

  $(document).on('click', '.div1', function() {
    div2();
  });

  $(document).on('click', 'span', function() {
    cloneIt();
  });

})(jQuery);

body {
  display: flex;
  justify-content: space-around;
}

.mainDiv {
  background-color: #000;
  width: 100px;
  height: 100px;
  color: #fff;
  padding: 20px;
  margin-left: 15px;
  margin-right: 15px;
}

.div1 {
  background-color: blue;
  padding: 10px;
  cursor: pointer;
}

.div2 {
  background-color: red;
  padding: 10px;
}

span {
  display: block;
  padding: 10px;
  background-color: green;
  margin-bottom: 15px;
  cursor: pointer;
}

  Clone it

click to append div

Body:
You can get the current element bu using $(this) and then get the parent using $(this).parent() and send it as parameter to the function div2($(this).parent()); and use it instead of using class selector

  function div2(item) {
    $('<div/>').addClass('div2').text('This is a Content').appendTo(item);
  }

See code snippet:

(function($) {

  function div2(item) {
    if (item.has(".div2").length <= 0) {
      $('<div/>').addClass('div2').text('This is a Content').appendTo(item);
    }

  }

  function cloneIt() {
    $('.mainDiv').clone().detach().appendTo('body');
  }

  $(document).on('click', '.div1', function() {
    div2($(this).parent());
  });

  $(document).on('click', 'span', function() {
    cloneIt();
  });

})(jQuery);

body {
  display: flex;
  justify-content: space-around;
}

.mainDiv {
  background-color: #000;
  width: 100px;
  height: 100px;
  color: #fff;
  padding: 20px;
  margin-left: 15px;
  margin-right: 15px;
}

.div1 {
  background-color: blue;
  padding: 10px;
  cursor: pointer;
}

.div2 {
  background-color: red;
  padding: 10px;
}

span {
  display: block;
  padding: 10px;
  background-color: green;
  margin-bottom: 15px;
  cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainDiv">
  <span>Clone it</span>
  <div class="div1">click to append div</div>
</div>


问:
Symfony2 : Entities not created in database
I'm making entities with Symfony2 and Doctrine2. I made some entities that represent a many-to-many relation between two of my entities.

An example of one of these entities :

```<code>/**
 * @ORM\Entity
 */
class Contact_Conference_Invitation
{
    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Aurae\UserBundle\Entity\Contact")
     */
    private $contact;

    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Aurae\ConferenceBundle\Entity\Conference")
     */
    private $conference;

    /**
     * @var datetime dateInvitation
     *
     * @ORM\Column(name="dateInvitation", type="datetime")
     */
    private $dateInvitation;

    //Getters and setters
}
</code>```

I have tried updating my sql schema, but the tables corresponding to these entities do not appear. Is there somewhere I have to declare them (config or such)? If not, what's wrong?

Thanks a lot

Edit : I had forgotten the namespace for these class, and that's why they were omitted by Doctrine. Another case closed :) thanks for the answers!

答:
Also don't forget to check that you have automapping enabled.

In your config.yml you should have

```<code>doctrine:
    orm:
        auto_mapping: true
</code>```

Came across this question because my entities weren't generated as well, this was my issue, it could save some time to people struggling with the same issue.

Body:
I'm making entities with Symfony2 and Doctrine2. I made some entities that represent a many-to-many relation between two of my entities.

An example of one of these entities :

/**
 * @ORM\Entity
 */
class Contact_Conference_Invitation
{
    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Aurae\UserBundle\Entity\Contact")
     */
    private $contact;

    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Aurae\ConferenceBundle\Entity\Conference")
     */
    private $conference;

    /**
     * @var datetime dateInvitation
     *
     * @ORM\Column(name="dateInvitation", type="datetime")
     */
    private $dateInvitation;

    //Getters and setters
}

I have tried updating my sql schema, but the tables corresponding to these entities do not appear. Is there somewhere I have to declare them (config or such)? If not, what's wrong?

Thanks a lot

Edit : I had forgotten the namespace for these class, and that's why they were omitted by Doctrine. Another case closed :) thanks for the answers!

Body:
Also don't forget to check that you have automapping enabled.

In your config.yml you should have

doctrine:
    orm:
        auto_mapping: true

Came across this question because my entities weren't generated as well, this was my issue, it could save some time to people struggling with the same issue.


问:
Enumerator for collection that is time/update aware
I have a situation where I want to be able to access historical information in order to retrospectively generate metrics or understand the way things stood at a point in the past, up until now I have been storing the most-recent content (e.g. the record with all of the updates ever applied) but would now like to be able to turn back the clock.

Before rolling my own solution:

Does something else already exist?

Is this a standard pattern?

Where am I likely to hit problems?

I'm not expecting consumers of the records to be able to change them, so any 'updates' should be marshalled through the repository and it will create new records containing the full content.

Ideally I'd like to move this over to an SQL backend, so if patterns exist there I'd like to remain close to them.

Basic Design thoughts are:

Define an interface, say IUpdatableRecord:

```<code>public interface IUpdatableRecord<K>
{
    K Key { get; }
    DateTime Updated { get; }
}
</code>```

Define a repository with enumeration capability:

```<code>public class DataRepository : IEnumerable<IUpdateableRecord<K>>
{
    // Some internal collection that allows duplicate keys
    private IList<IUpdateableRecord<K>> dataStore = ....;

    // Some enumerator overloads
    public IEnumerator<IUpdateableRecord<K>> GetEnumerator()
    {
        return dataStore.GetEnumerator();
    }

    // enumerator for contents as of a specific date-time
    public IEnumerator<IUpdateableRecord<K>> GetEnumerator(DateTime refDate)
    {
        // Group by key (so all versions of a record together)
        var groupedByKey = dataStore.GroupBy(r => r.Key);

        // Sort the keys within each group for a date/time order
        foreach ( var rec in groupedByKey )
        {
            var sorted = rec.OrderBy(r => r.Updated);

            // Ignore updates after the reference date & keep last (or default)
            var last = sorted.Where(r => r.Updated < refDate).LastOrDefault();

            // yield last record if any
            if ( last != null )
            {
                yield return last;
            }
        }
    }

    // code for 'adding/updating' a record.
}
</code>```

答:
There are a couple of solutions you can impelemt in an RDBMS; one is where you store all the historical values for a given key value along with a 'valid-from' and a 'valid-to' date. (This is commonly used in data warehousing solutions). This can complicate your queries quite a lot and is a pain to retrofit to an exisiting solution. One other way I have used is to hold history tables that are replicas of exisiting tables, plus a few extra metadata columns; by forcing all updates through procedures, you can write the pre-change record to the history table. Any existing queries on the core tables are fine because they see the current value, but for historical queries you can UNION the Core and history tables (via a view in my case) to provide the source for your LINQ objects.

In SQL Server, I use a seperate History schema for the history tables so you can re-use the table names.

ContentLicense: CC BY-SA 2.5

Body:
I have a situation where I want to be able to access historical information in order to retrospectively generate metrics or understand the way things stood at a point in the past, up until now I have been storing the most-recent content (e.g. the record with all of the updates ever applied) but would now like to be able to turn back the clock.

Before rolling my own solution:

Does something else already exist?

Is this a standard pattern?

Where am I likely to hit problems?

I'm not expecting consumers of the records to be able to change them, so any 'updates' should be marshalled through the repository and it will create new records containing the full content.

Ideally I'd like to move this over to an SQL backend, so if patterns exist there I'd like to remain close to them.

Basic Design thoughts are:

Define an interface, say IUpdatableRecord:

public interface IUpdatableRecord<K>
{
    K Key { get; }
    DateTime Updated { get; }
}

Define a repository with enumeration capability:

public class DataRepository : IEnumerable<IUpdateableRecord<K>>
{
    // Some internal collection that allows duplicate keys
    private IList<IUpdateableRecord<K>> dataStore = ....;

    // Some enumerator overloads
    public IEnumerator<IUpdateableRecord<K>> GetEnumerator()
    {
        return dataStore.GetEnumerator();
    }

    // enumerator for contents as of a specific date-time
    public IEnumerator<IUpdateableRecord<K>> GetEnumerator(DateTime refDate)
    {
        // Group by key (so all versions of a record together)
        var groupedByKey = dataStore.GroupBy(r => r.Key);

        // Sort the keys within each group for a date/time order
        foreach ( var rec in groupedByKey )
        {
            var sorted = rec.OrderBy(r => r.Updated);

            // Ignore updates after the reference date & keep last (or default)
            var last = sorted.Where(r => r.Updated < refDate).LastOrDefault();

            // yield last record if any
            if ( last != null )
            {
                yield return last;
            }
        }
    }

    // code for 'adding/updating' a record.
}


问:
Display an error message next to the input field if input field is blank
I am new to JavaScript and am a bit stuck...

I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.

Unfortunately is doesn't do anything...
Thanks for your help!!

My HTML:

```<code><form name="user_details" method="post" onsubmit="return checkform()">
    <table id="form_table">
        <tr>
            <td class="form_cell"><label for="first_name">First Name:</label></td>
            <td class="form_cell"><input type="text" id="first_name">*</td>
            <td id="error_first_name">The first name field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="surname">Surname:</label></td>
            <td class="form_cell"><input type="text" id="surname">*</td>
            <td id="error_surname">The surname field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="address">Address:</label></td>
            <td class="form_cell"><input type="text" id="address">*</td>
            <td id="error_address">The address field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="city">City:</label></td>
            <td class="form_cell"><input type="text" id="city">*</td>
            <td id="error_city">The city field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="post_code">Post Code:</label></td>
            <td class="form_cell"><input type="text" id="post_code">*</td>
            <td id="error_post_code">The post code field needs to contain a number.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="email">Email:</label></td>
            <td class="form_cell"><input type="email" id="email">*</td>
            <td id="error_email">The email field needs to contain an email address.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="phone_number">Phone Number:</label></td>
            <td class="form_cell"><input type="text" id="phone_number"></td>
        </tr>
    </table>
        <input type="submit"><input type=reset>
    </form>
</code>```

My JavaScript:

```<code>function checkform() {
var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
}

else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
}

else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
}

else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
}

else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
}

else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
}

else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
}

else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else {
    return ok;
}
</code>```

}

My CSS:

```<code>#error_first_name {
display: none;
}

#error_surname {
display: none;
}

#error_address {
display: none;
}

#error_city {
display: none;
}

#error_post_code {
display: none;
}

#error_email {
display: none;
}
</code>```

答:
If you used jquery ,you can shorten your code with making array for same pattern group and using .each

```<code>function checkform() {
    var ok = true;
    var character = [["first_name","surname","address"],["/^[A-Za-z]+$/"]];
    var city = [["city"],["/^[A-Za-z][0-9]+$/"]];
    var post = [["post_code"],["/^[0-9]+$/"]];
    var email = [["email"],["/\S+@\S+/"]];
    $("form[name='user_details'] input").each(function(){
        if($.inArray(this.id,character[0]) >= 0 ) {
            ok = showError(this,character[1]);
        } else if(this.id == city[0]) {
            ok = showError(this,city[1]);
        } else if(this.id == post[0]) {
            ok = showError(this,post[1]);
        } else if(this.id == email[0]) {
            ok = showError(this,email[1]);
        }
    });
    return ok;
}
function showError(t,p) {
    if(t.value == "" || !p.test(t.value)){
        $(t).css("borderColor","red");
        $("#error_"+t.id).show();
        return false;
    }
    return true;
}
</code>```

Body:
I am new to JavaScript and am a bit stuck...

I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.

Unfortunately is doesn't do anything...
Thanks for your help!!

My HTML:

<form name="user_details" method="post" onsubmit="return checkform()">

            First Name:
            <input type="text" id="first_name">*
            The first name field needs to contain at least one character.

            Surname:
            <input type="text" id="surname">*
            The surname field needs to contain at least one character.

            Address:
            <input type="text" id="address">*
            The address field needs to contain at least one character.

            City:
            <input type="text" id="city">*
            The city field needs to contain at least one character.

            Post Code:
            <input type="text" id="post_code">*
            The post code field needs to contain a number.

            Email:
            <input type="email" id="email">*
            The email field needs to contain an email address.

            Phone Number:
            <input type="text" id="phone_number">

        <input type="submit"><input type=reset>
    </form>

My JavaScript:

function checkform() {
var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
}

else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
}

else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
}

else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
}

else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
}

else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
}

else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
}

else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else {
    return ok;
}

}

My CSS:

#error_first_name {
display: none;
}

#error_surname {
display: none;
}

#error_address {
display: none;
}

#error_city {
display: none;
}

#error_post_code {
display: none;
}

#error_email {
display: none;
}

Body:
If you used jquery ,you can shorten your code with making array for same pattern group and using .each

function checkform() {
    var ok = true;
    var character = [["first_name","surname","address"],["/^[A-Za-z]+$/"]];
    var city = [["city"],["/^[A-Za-z][0-9]+$/"]];
    var post = [["post_code"],["/^[0-9]+$/"]];
    var email = [["email"],["/\S+@\S+/"]];
    $("form[name='user_details'] input").each(function(){
        if($.inArray(this.id,character[0]) >= 0 ) {
            ok = showError(this,character[1]);
        } else if(this.id == city[0]) {
            ok = showError(this,city[1]);
        } else if(this.id == post[0]) {
            ok = showError(this,post[1]);
        } else if(this.id == email[0]) {
            ok = showError(this,email[1]);
        }
    });
    return ok;
}
function showError(t,p) {
    if(t.value == "" || !p.test(t.value)){
        $(t).css("borderColor","red");
        $("#error_"+t.id).show();
        return false;
    }
    return true;
}


问:
ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory
I am trying to use tensorflow-gpu on my system. I have re-installed it many times, it gives the error give below. But when I use tensorflow-cpu it works fine. I have cuda 8.0 toolkit installed and cudnn 5.1.</p>

```<code>  Traceback (most recent call last):
  File "finetune.py", line 17, in <module>
    import tensorflow as tf
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 72, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 61, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

答:
If changing your path variable does not work, running the following in your terminal is what usually solves this for me:

```<code>sudo ldconfig /usr/local/cuda/lib64
</code>```

(sometimes cuda may need to be something like cuda-8.0, depending on your installation)

Body:
I am trying to use tensorflow-gpu on my system. I have re-installed it many times, it gives the error give below. But when I use tensorflow-cpu it works fine. I have cuda 8.0 toolkit installed and cudnn 5.1.

  Traceback (most recent call last):
  File "finetune.py", line 17, in <module>
    import tensorflow as tf
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 72, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 61, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/home/saurabh/code/env/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Body:
If changing your path variable does not work, running the following in your terminal is what usually solves this for me:

sudo ldconfig /usr/local/cuda/lib64

(sometimes cuda may need to be something like cuda-8.0, depending on your installation)


问:
QtCreator CMake project - how to show all project files
I use QtCreator to open CMake project. Some directories apart from CMakeLists.txt contains only headers files *.h and for those directories QtCreator in the project tree view shows only CMakeLists.txt. How to fix that ? I need to see all project files from QtCreator.</p>

答:
Based on another thread asking the same question, I found a generic solution to the problem, working for all IDE's (at least tested with QtCreator and Visual Studio).

Can be found here : https://github.com/sauter-hq/cmake-ide-support

```<code># \brief adds for the given target a fake executable targets which allows all
#        headers and symbols to be shown in IDEs.
# \param target_name Which target properties should be added to the IDE support target.
function(target_add_ide_support target_name)
  if (NOT TARGET ${target_name})
    message(FATAL_ERROR "No target defined with name ${target_name}, cannot target_add_ide_support it.")
  endif()

  set (target_for_ide "${target_name}_ide_support")
  if (NOT TARGET ${target_for_ide})
      file(GLOB_RECURSE target_for_ide_srcs "*.h" "*.hpp" "*.hxx" "*.c" "*.cpp" "*.cxx")
      add_executable(${target_for_ide} ${target_for_ide_srcs})
      set_target_properties(${target_for_ide} PROPERTIES EXCLUDE_FROM_ALL 1 EXCLUDE_FROM_DEFAULT_BUILD 1)
  endif()

  get_target_property(dirs ${target_name} INCLUDE_DIRECTORIES)
  target_include_directories(${target_for_ide} PRIVATE ${dirs})

endfunction(target_add_ide_support)
</code>```

Usage is then for any targets in the CMakeLists, add the following call (can be made in top-most CMakeLists.txt after all add_subdirectory :

```<code>include(add_ide_support.cmake)
target_add_ide_support(some-target)
</code>```

Body:
Based on another thread asking the same question, I found a generic solution to the problem, working for all IDE's (at least tested with QtCreator and Visual Studio).

Can be found here : https://github.com/sauter-hq/cmake-ide-support

# \brief adds for the given target a fake executable targets which allows all
#        headers and symbols to be shown in IDEs.
# \param target_name Which target properties should be added to the IDE support target.
function(target_add_ide_support target_name)
  if (NOT TARGET ${target_name})
    message(FATAL_ERROR "No target defined with name ${target_name}, cannot target_add_ide_support it.")
  endif()

  set (target_for_ide "${target_name}_ide_support")
  if (NOT TARGET ${target_for_ide})
      file(GLOB_RECURSE target_for_ide_srcs "*.h" "*.hpp" "*.hxx" "*.c" "*.cpp" "*.cxx")
      add_executable(${target_for_ide} ${target_for_ide_srcs})
      set_target_properties(${target_for_ide} PROPERTIES EXCLUDE_FROM_ALL 1 EXCLUDE_FROM_DEFAULT_BUILD 1)
  endif()

  get_target_property(dirs ${target_name} INCLUDE_DIRECTORIES)
  target_include_directories(${target_for_ide} PRIVATE ${dirs})

endfunction(target_add_ide_support)

Usage is then for any targets in the CMakeLists, add the following call (can be made in top-most CMakeLists.txt after all add_subdirectory :

include(add_ide_support.cmake)
target_add_ide_support(some-target)


问:
Stream over a List of Map and collect specific key
This is my List:

```<code>[
    {name: 'moe', age: 40},
    {name: 'larry', age: 50},
    {name: 'curly', age: 60}
];
</code>```

I want to pluck name values and create another List like this:

```<code>["moe", "larry", "curly"]
</code>```

I've written this code and it works:

```<code>List<String> newList = new ArrayList<>();
for(Map<String, Object> entry : list) {
    newList.add((String) entry.get("name"));
}
</code>```

But how to do it in using stream. I've tried this code which doesn't work.

```<code>List<String> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());
</code>```

答:
x.get("name") should be cast to String.

for example:

List<String> newList = list.stream().map(x -> (String) x.get("name")).collect(Collectors.toList());

Body:
This is my List:

[
    {name: 'moe', age: 40},
    {name: 'larry', age: 50},
    {name: 'curly', age: 60}
];

I want to pluck name values and create another List like this:

["moe", "larry", "curly"]

I've written this code and it works:

List<String> newList = new ArrayList<>();
for(Map<String, Object> entry : list) {
    newList.add((String) entry.get("name"));
}

But how to do it in using stream. I've tried this code which doesn't work.

List<String> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());


问:
Access a component and trigger click event from App.vue component
In my template I have one click event

```<code><span v-on:click="showGalery()">
</code>```

And I am using one method for it

```<code>export default {
  name: 'osaka',
  data: function () {
    return {
      galery: false,
    }
  },
  methods: {
    showGalery () {
      this.galery = true
    }
  }
}
</code>```

Is it possible to trigger this method from App.vue template where is my nav and router links is located?

I am using vue-webpack template.
I have components, router.js, App.js and main.js structure.

答:
Remember Vue has a one way data flow, so if you want to set something on the component you can simply pass a prop and use a watcher to trigger the change:

```<code>Vue.component('gallery', {
  template: `<div v-show="gallery">Gallery</div>`,
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.gallery = this.show;
  },
  watch: {
    show(val) {
      this.gallery = val;
    }
  },
  data() {
    return {
      gallery: false
    }
  }
});
</code>```

Then in the parent you would have:

```<code>new Vue({
  el: '#app',
  data: {
    showGallery: false
  }
});
</code>```

And use the following markup:

```<code><gallery :show="showGallery"></gallery>
</code>```

See this JSFiddle: https://jsfiddle.net/yx1uq370/

Incidentally, if you just want to show hide the entire component, then you can just use v-show on the component itself which

```<code>Vue.component('gallery', {
  template: `<div>Gallery</div>`
});

new Vue({
  el: '#app',
  data: {
    showGallery: false
  }
});
</code>```

Then your markup:

```<code><gallery v-show="showGallery"></gallery>
</code>```

And here's the fiddle for that: https://jsfiddle.net/gfr9kmub/

One final thing, are you sure that you really need to trigger this from your nav? I would assume that your nav would display the views and the views themselves would take care of this type of state management. Otherwise you may want to look at vuex to handle this situation

Body:
In my template I have one click event

And I am using one method for it

export default {
  name: 'osaka',
  data: function () {
    return {
      galery: false,
    }
  },
  methods: {
    showGalery () {
      this.galery = true
    }
  }
}

Is it possible to trigger this method from App.vue template where is my nav and router links is located?

I am using vue-webpack template.
I have components, router.js, App.js and main.js structure.

Body:
Remember Vue has a one way data flow, so if you want to set something on the component you can simply pass a prop and use a watcher to trigger the change:

Vue.component('gallery', {
  template: `<div v-show="gallery">Gallery</div>`,
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.gallery = this.show;
  },
  watch: {
    show(val) {
      this.gallery = val;
    }
  },
  data() {
    return {
      gallery: false
    }
  }
});

Then in the parent you would have:

new Vue({
  el: '#app',
  data: {
    showGallery: false
  }
});

And use the following markup:

<gallery :show="showGallery"></gallery>

See this JSFiddle: https://jsfiddle.net/yx1uq370/

Incidentally, if you just want to show hide the entire component, then you can just use v-show on the component itself which

Vue.component('gallery', {
  template: `<div>Gallery</div>`
});

new Vue({
  el: '#app',
  data: {
    showGallery: false
  }
});

Then your markup:

<gallery v-show="showGallery"></gallery>

And here's the fiddle for that: https://jsfiddle.net/gfr9kmub/

One final thing, are you sure that you really need to trigger this from your nav? I would assume that your nav would display the views and the views themselves would take care of this type of state management. Otherwise you may want to look at vuex to handle this situation


问:
How to get the project path at Design Time
I use a component (System.ComponentModel.Component) and I want to get the application path of my project in order to create a file within it.

Thx

Florian

答:
The only thing that seemed to work (consistently) for me was obtaining EnvDTE.DTE (from the IServiceProvider you get from EditValue()), i.e.:

```<code>EnvDTE.DTE dte = envProvider.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
string dir = Path.GetDirectoryName(dte.Solution.FullName);
</code>```

When I tried using Assembly.GetXAssembly, I got the temporary path VS uses in design-time.

Body:
The only thing that seemed to work (consistently) for me was obtaining EnvDTE.DTE (from the IServiceProvider you get from EditValue()), i.e.:

EnvDTE.DTE dte = envProvider.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
string dir = Path.GetDirectoryName(dte.Solution.FullName);

When I tried using Assembly.GetXAssembly, I got the temporary path VS uses in design-time.


问:
es6 arrow function
I would test this in browser

```<code>let foo = () => ({ bar: 2 })
</code>```

But accidentally typed

```<code>let foo = () => { bar: 2}
</code>```

Why didn't throw an error?

答:
Τhis is the basic syntax:

```<code>() => { statements }
</code>```

And the advanced:

```<code>// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
</code>```

MDN Arrow functions

Title: es6 arrow function

Body:
I would test this in browser

let foo = () => ({ bar: 2 })

But accidentally typed

let foo = () => { bar: 2}

Why didn't throw an error?

Body:
Τhis is the basic syntax:

() => { statements }

And the advanced:

// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})

MDN Arrow functions


问:
Azure Table Service - 409 errors all over the place
On the last 4 hours i've got 200+ requests failing on azure table reporting 409. I've looked around and this means PK duplication. Since this is a table specific for logging, I really don't care about the keys so my RowKey is Guid.NewGuid()...

Is there another reason for azure table to return a 409 or I'm actually seeing UUIDs colliding?

PS: i really hope that there's another reason, because on the last 4 hours I've handled only 50k requests...

答: If you are calling Guid.NewGuid() quicker than the clock, it may generate the same Guid. Try putting a few milliseconds between Guid.NewGuid() calls.


问:
C++ Checking if a double is an integer does not work in some cases
I am trying to print out the first few numbers that follow a certain rule: the sum of its digits can be raised to an integral power to get the number itself. (Basically if the sum is an nth root of the number).

For example, the sum of the digits in the number 81 is 9, and 9^2 is 81.

This is some of the code I am using:

```<code>#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <math.h>
using namespace std;

int sumOfDigits(int num) {
    int sum = 0;
    string numStr = "";
    stringstream s;
    s << num;
    s >> numStr;
    for (int i = 0; i < numStr.length(); i++) {
        int ad = 0;
        stringstream ss;
        ss << numStr[i]; // take each digit
        ss >> ad;
        sum += ad; // and add to sum
    }
    return sum;
}

int num = 10; // starting number
int numFound = 0; // how many such special numbers have been found

int main() {
    while (numFound < 5) {
        int sum = sumOfDigits(num);
        double exp = log10(num) / log10(sum);

        if (fmod(exp, 1.0) == 0.0 && sum != 1) { // if the exponent is an integer
            cout << num << "\t" << sum << endl; // then print out the number and the sum of its digits
            numFound++;
        }
        num++;
    }

    return 0;
}
</code>```

When I run this, I get the following output:

```<code>81      9
2401    7
4913    17
5832    18
17576   26
</code>```

The second entry should be 512 and 8 because 8^3 is 512. I don't understand why the test works with some numbers but doesn't work with others.

I've tried other methods of testing whether the exponent is an integer as well. I've tested it against the floor() expression, and I've tried casting the entire expression with (int).

I may be wrong and the problem may not be in that spot, but I would really appreciate it if you could help me with this. Thank you.

答:
It would be a lot faster to loop over sums and exponents:</p>

```<code>unsigned int number;
unsigned int min_sum =   3;
unsigned int max_sum = 100;
unsigned int min_exp =   2;
unsigned int max_exp =  20;

int main() {
    for (unsigned int exp = min_exp; exp <= max_exp; ++exp)
        for (unsigned int sum = min_sum; sum <= max_sum; ++sum) {
            number = pow(sum, exp);
            if ( sumOfDigits(number) == sum )
                cout << numFound++ << ":\t" << number << "\t = " << sum << " ^ \t" << exp << endl;
        }
    return 0;
}
</code>```

Body:
I am trying to print out the first few numbers that follow a certain rule: the sum of its digits can be raised to an integral power to get the number itself. (Basically if the sum is an nth root of the number).

For example, the sum of the digits in the number 81 is 9, and 9^2 is 81.

This is some of the code I am using:

#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <math.h>
using namespace std;

int sumOfDigits(int num) {
    int sum = 0;
    string numStr = "";
    stringstream s;
    s << num;
    s >> numStr;
    for (int i = 0; i < numStr.length(); i++) {
        int ad = 0;
        stringstream ss;
        ss << numStr[i]; // take each digit
        ss >> ad;
        sum += ad; // and add to sum
    }
    return sum;
}

int num = 10; // starting number
int numFound = 0; // how many such special numbers have been found

int main() {
    while (numFound < 5) {
        int sum = sumOfDigits(num);
        double exp = log10(num) / log10(sum);

        if (fmod(exp, 1.0) == 0.0 && sum != 1) { // if the exponent is an integer
            cout << num << "\t" << sum << endl; // then print out the number and the sum of its digits
            numFound++;
        }
        num++;
    }

    return 0;
}

When I run this, I get the following output:

81      9
2401    7
4913    17
5832    18
17576   26

The second entry should be 512 and 8 because 8^3 is 512. I don't understand why the test works with some numbers but doesn't work with others.

I've tried other methods of testing whether the exponent is an integer as well. I've tested it against the floor() expression, and I've tried casting the entire expression with (int).

I may be wrong and the problem may not be in that spot, but I would really appreciate it if you could help me with this. Thank you.

Body:
It would be a lot faster to loop over sums and exponents:

unsigned int number;
unsigned int min_sum =   3;
unsigned int max_sum = 100;
unsigned int min_exp =   2;
unsigned int max_exp =  20;

int main() {
    for (unsigned int exp = min_exp; exp <= max_exp; ++exp)
        for (unsigned int sum = min_sum; sum <= max_sum; ++sum) {
            number = pow(sum, exp);
            if ( sumOfDigits(number) == sum )
                cout << numFound++ << ":\t" << number << "\t = " << sum << " ^ \t" << exp << endl;
        }
    return 0;
}


答:
I don't know if I understand your question in the right way, but cloning the current clicked div could be solved like this

(function($){

$(document).on('click', '.mainDiv > div', function(){
    $(this).closest('.mainDiv').append($(this).clone(true));
});

})(jQuery);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  display: flex;
  justify-content: space-around;
}

.mainDiv {
  background-color: #000;
  width: 100px;
  /* height: 100px; */
  color: #fff;
  padding: 20px;
  margin-left: 15px;
  margin-right: 15px;
}

.div1 {
  background-color: blue;
  padding: 10px;
  cursor: pointer;
}

.div2 {
  background-color: red;
  padding: 10px;
}</code>```

DIV 1

DIV 2

```

Title: How to append dynamically created div into current mainDiv not all the mainDiv when click on a button

Body:
I'm trying to appendTo a
 into current
 when click on a button. Now its appendTo all the class='mainDiv' & after the cloning. I need it only to the current clicked
. Can someone help me to solve it?

(function($) {

  function div2() {
    $('
').addClass('div2').text('This is a Content').appendTo('.mainDiv');
  }

  function cloneIt() {
    $('.mainDiv').clone().detach().appendTo('body');
  }

  $(document).on('click', '.div1', function() {
    div2();
  });

  $(document).on('click', 'span', function() {
    cloneIt();
  });

})(jQuery);

body {
  display: flex;
  justify-content: space-around;
}

.mainDiv {
  background-color: #000;
  width: 100px;
  height: 100px;
  color: #fff;
  padding: 20px;
  margin-left: 15px;
  margin-right: 15px;
}

.div1 {
  background-color: blue;
  padding: 10px;
  cursor: pointer;
}

.div2 {
  background-color: red;
  padding: 10px;
}

span {
  display: block;
  padding: 10px;
  background-color: green;
  margin-bottom: 15px;
  cursor: pointer;
}

  Clone it

click to append div

Body:
I don't know if I understand your question in the right way, but cloning the current clicked div could be solved like this

(function($){

$(document).on('click', '.mainDiv > div', function(){
    $(this).closest('.mainDiv').append($(this).clone(true));
});

})(jQuery);

body {
  display: flex;
  justify-content: space-around;
}

.mainDiv {
  background-color: #000;
  width: 100px;
  /* height: 100px; */
  color: #fff;
  padding: 20px;
  margin-left: 15px;
  margin-right: 15px;
}

.div1 {
  background-color: blue;
  padding: 10px;
  cursor: pointer;
}

.div2 {
  background-color: red;
  padding: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="mainDiv">
  <div class="div1">DIV 1</div>
  <div class="div2">DIV 2</div>
</div>


问:
How to display response error message with axios
Been looking to achieve this few months now but now it's needed. I need to display the error message, set on server, about what went wrong:

Sever endpoint

```<code>abort(406, 'Foo bar!')
</code>```

Web:

```<code>[...]
 .catch(e => {
  console.log(e.response.data) // does not work
 })
</code>```

In chrome dev tools, under preview, I see the message Foo bar!. How to get this message on my console log?

This endpoint will have different abort messages based on actions so I do not want to set a static error message on web for the error.

Chrome dev tools message:

答:
This should work : console.log(e.response.data.message). I think this is what you looking for.

This is for this type of request:

```<code>axios.post(
    url,
    {},
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error.response.data.message);
    });
</code>```

Body:
Been looking to achieve this few months now but now it's needed. I need to display the error message, set on server, about what went wrong:

Sever endpoint

abort(406, 'Foo bar!')

Web:

[...]
 .catch(e => {
  console.log(e.response.data) // does not work
 })

In chrome dev tools, under preview, I see the message Foo bar!. How to get this message on my console log?

This endpoint will have different abort messages based on actions so I do not want to set a static error message on web for the error.

Chrome dev tools message:

Body:
This should work : console.log(e.response.data.message). I think this is what you looking for.

This is for this type of request:

axios.post(
    url,
    {},
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error.response.data.message);
    });


问:
How can I resolve 'module not found error' in webpack?
I have my reactjs app with react-bootstrap running on webpack 2. When I run the app I get this error:

```<code>ERROR in ./~/css-loader!./~/sass-loader/lib/loader.js!./app/css/bootstrap.css
Module not found: Error: Can't resolve '../fonts/glyphicons-halflings-regular.woff2' in '/Users/me/reactjs_dutchboiler/app/css'
 @ ./~/css-loader!./~/sass-loader/lib/loader.js!./app/css/bootstrap.css 6:4720-4774
 @ ./app/css/bootstrap.css
 @ ./app/app.jsx
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./app/app.jsx
</code>```

The app was running without errors until I imported bootstrap.css. Now I get the error above.
It looks like webpack does not have the right loader installed? How can I resolve this?

答:
Your question is your answer. Install the right loader. I would try url-loader.

```<code>rules: [
//your loaders
{
    test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
    use: 'url-loader'
}
</code>```

Also, check if the file glyphicons-halflings-regular.woff2 is actually in the folder and that you have the right path to it.

Body:
I have my reactjs app with react-bootstrap running on webpack 2. When I run the app I get this error:

ERROR in ./~/css-loader!./~/sass-loader/lib/loader.js!./app/css/bootstrap.css
Module not found: Error: Can't resolve '../fonts/glyphicons-halflings-regular.woff2' in '/Users/me/reactjs_dutchboiler/app/css'
 @ ./~/css-loader!./~/sass-loader/lib/loader.js!./app/css/bootstrap.css 6:4720-4774
 @ ./app/css/bootstrap.css
 @ ./app/app.jsx
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./app/app.jsx

The app was running without errors until I imported bootstrap.css. Now I get the error above.
It looks like webpack does not have the right loader installed? How can I resolve this?

Body:
Your question is your answer. Install the right loader. I would try url-loader.

rules: [
//your loaders
{
    test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
    use: 'url-loader'
}

Also, check if the file glyphicons-halflings-regular.woff2 is actually in the folder and that you have the right path to it.


问:
How to conclude if a content is gziped or not in safari?
If I compare the 'Content-Length' in chrome and safari, it shows same; but the 'Encoded' and 'Decoded' value is shown same in safari but varies in chrome. Also any other parameter I can use for comparing chrome and safari if gziped or not?

Please note, I am checking for an ajax response returning JSON object, and not any particular file as response.

答:
Inspect browser page and you will be able to see some tabs from that select network tab and refresh page, after that select any file which you want to check weather it is gzip or not. For selected file check response header which will show "Content-Encoding:gzip " if file is gziped.

Check screen shot for details :


问:
Android SDK: System Setting
How can i set the System Port and Proxy?
Is there any command in java that can do that?
If not, how can i change it with superuser permission?
I have tryed a lot of codes, but no one worked for me.
Please help.</p>

答:
```<code>String myProxy=Proxy.getDefaultHost() ;
        int myPort=Proxy.getDefaultPort();
        HttpHost proxy = new HttpHost(myProxy,myPort,"http");
        client.getParams().setParameter (ConnRoutePNames.DEFAULT_PROXY, proxy);
</code>```

try giving this within your java file. before that change your proxy settings in emulator!

Title: Android SDK: System Setting

Body:
String myProxy=Proxy.getDefaultHost() ;
        int myPort=Proxy.getDefaultPort();
        HttpHost proxy = new HttpHost(myProxy,myPort,"http");
        client.getParams().setParameter (ConnRoutePNames.DEFAULT_PROXY, proxy);

try giving this within your java file. before that change your proxy settings in emulator!


问:
How to monitor the size of a directory via Telegraf
We need to monitor the size of a directory (for example the data directory of InfluxDB) to set up alerts in Grafana. As mentioned here: How to configure telegraf to send a folder-size to influxDB , there is no built-in plugin for this.

We don't mind using the inputs.exec section of Telegraf. The directories are not huge (low filecount + dircount), so deep scanning (like the use of du) is fine by us.

One of the directories we need to monitor is /var/lib/influxdb/data.

What would be a simple script to execute, and what are the caveats?

答:
You could create a simple bash script metrics-exec_du.sh with the following content (chmod 755):

```<code>#!/usr/bin/env bash
du -bs "${1}" | awk '{print "[ { \"bytes\": "$1", \"dudir\": \""$2"\" } ]";}'
</code>```

And activate it by putting the following in the Telegraf config file:

[[inputs.exec]]
  commands = [ "YOUR_PATH/metrics-exec_du.sh /var/lib/influxdb/data" ]
  timeout = "5s"
  name_override = "du"
  name_suffix = ""
  data_format = "json"
  tag_keys = [ "dudir" ]

Caveats:

The du command can stress your server, so use with care

The user telegraf must be able to scan the dirs. There are several options, but since InfluxDB's directory mask is a bit unspecified (see: https://github.com/influxdata/influxdb/issues/5171#issuecomment-306419800), we applied a rather crude workaround (examples are for Ubuntu 16.04.2 LTS):

Add the influxdb group to the user telegraf : sudo usermod --groups influxdb --append telegraf

Put the following in the crontab, run for example each 10 minutes: 10 * * * * chmod -R g+rX /var/lib/influxdb/data > /var/log/influxdb/chmodfix.log 2>&1

Result, configured in Grafana (data source: InfluxDB):

Cheers, TW

Body:
You could create a simple bash script metrics-exec_du.sh with the following content (chmod 755):

#!/usr/bin/env bash
du -bs "${1}" | awk '{print "[ { \"bytes\": "$1", \"dudir\": \""$2"\" } ]";}'

And activate it by putting the following in the Telegraf config file:

[[inputs.exec]]
  commands = [ "YOUR_PATH/metrics-exec_du.sh /var/lib/influxdb/data" ]
  timeout = "5s"
  name_override = "du"
  name_suffix = ""
  data_format = "json"
  tag_keys = [ "dudir" ]

Caveats:

The du command can stress your server, so use with care

The user telegraf must be able to scan the dirs. There are several options, but since InfluxDB's directory mask is a bit unspecified (see: https://github.com/influxdata/influxdb/issues/5171#issuecomment-306419800), we applied a rather crude workaround (examples are for Ubuntu 16.04.2 LTS):

Add the influxdb group to the user telegraf : sudo usermod --groups influxdb --append telegraf

Put the following in the crontab, run for example each 10 minutes: 10 * * * * chmod -R g+rX /var/lib/influxdb/data > /var/log/influxdb/chmodfix.log 2>&1

Result, configured in Grafana (data source: InfluxDB):

Cheers, TW


问:
Android In-App Billing invalidKeySpecException wrong tag
I am implementing basic usage of android billing purchase v3 using IabHelper and I am still encountering this issue when I am testing on real device. I run the first time and after successful purchase i consume the product. Now I'am getting the error again and again.

I have already checked my public key (even using different encoding) so i don't think it is the problem. I have consumed all android.test.* products after testing static responses. I also tried to edit the verifyPurchase method in Security.java but it seems the error occurs at this call PublicKey key = Security.generatePublicKey(base64PublicKey);

Has somebody managed to solve definitely the issue?

Here is the log for the error :

```<code>java.lang.IllegalArgumentException: java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0890ba:ASN.1 encoding routines:asn1_check_tlen:WRONG_TAG
                                                                          at com.hubsante.nutrition.utils.util.Security.generatePublicKey(Security.java:82)
                                                                          at com.hubsante.nutrition.utils.util.Security.verifyPurchase(Security.java:62)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper.queryPurchases(IabHelper.java:972)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper.queryInventory(IabHelper.java:624)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper$2.run(IabHelper.java:698)
                                                                          at java.lang.Thread.run(Thread.java:818)
</code>```

答: maybe the var base64publickey length or format is invalid</p>

Body:
I am implementing basic usage of android billing purchase v3 using IabHelper and I am still encountering this issue when I am testing on real device. I run the first time and after successful purchase i consume the product. Now I'am getting the error again and again.

I have already checked my public key (even using different encoding) so i don't think it is the problem. I have consumed all android.test.* products after testing static responses. I also tried to edit the verifyPurchase method in Security.java but it seems the error occurs at this call PublicKey key = Security.generatePublicKey(base64PublicKey);

Has somebody managed to solve definitely the issue?

Here is the log for the error :

java.lang.IllegalArgumentException: java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0890ba:ASN.1 encoding routines:asn1_check_tlen:WRONG_TAG
                                                                          at com.hubsante.nutrition.utils.util.Security.generatePublicKey(Security.java:82)
                                                                          at com.hubsante.nutrition.utils.util.Security.verifyPurchase(Security.java:62)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper.queryPurchases(IabHelper.java:972)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper.queryInventory(IabHelper.java:624)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper$2.run(IabHelper.java:698)
                                                                          at java.lang.Thread.run(Thread.java:818)


问:
Same code but Strange behaviour
This is my code on implementation of merge sort , it is showing no error at all
and giving no output either :

```<code>#include<iostream>

using namespace std;

void merge(int arr[],int l,int m,int r)
{
    int i,j,k;
    int n1 = m-l+1;
    int n2 = r-m;

    int L[n1],R[n2];

    for(i=0;i<n1;i++)
    {
        L[i]=arr[i+l];
    }

    for(j=0;j<n2;j++)
    {
        R[j]=arr[m+1+j];
    }

    i=0;
    j=0;
    k=1;

    while(i<n1 && j<n2)
    {
        if(L[i]<=R[j])
        {
            arr[k]=L[i];
            i++;
        }
        else
        {
            arr[k]=R[j];
            j++;
        }
        k++;
    }

    while(i<n1)
    {
        arr[k]=L[i];
        i++;
        k++;
    }

    while(j<n2)
    {
        arr[k]=R[j];
        j++;
        k++;
    }

}

void mergeSort(int arr[], int l, int r)
{
    if(l < r)
    {

        int m = l+(r-1)/2;

        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

        merge(arr, l, m, r);
    }
}

void printArray(int A[],int size)
{
    int i;
   for( i=0;i<size;i++)
        cout<<A[i]<<" ";
}

int main()
{
    int arr[]={12,65,34,78,90,65,34};
    int arr_size = sizeof(arr)/sizeof(arr[0]);

    cout<<"Given array is \n";
    printArray(arr, arr_size);

    mergeSort(arr, 0, arr_size - 1);

    cout<<"\nSorted array is \n";
    printArray(arr, arr_size);
return 0;
}
</code>```

now here is the piece of code , which is the problem :

```<code>void mergeSort(int arr[], int l, int r)
{
    if (l < r)
    {

        int m = l+(r-l)/2;

        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

        merge(arr, l, m, r);
    }
}
</code>```

if i replace this mergeSort() code with the above program's mergeSort(),
the program gives output.
but have  a look , both mergeSort() codes are same (in program code as well as mentioned mergeSort() code)

link to original code ===> http://cpp.sh/6zdip

link to the code after replacing mergeSort ====> http://cpp.sh/7lfo

this is most strange problem ,i have ever faced.

答:
It's not the same code.

on your original code:    int m = l+(r-1)/2;

on the working code:    int m = l+(r-l)/2;

the letter L minuscule can look like '1', but it's not.

Now, try one thing: make the spacements of your code consistent (by running clang-format on both codes) then use a diff application to verify the differences on your code and the running one.

It was pretty easy to spot when I did this:

```<code>> int m = l + (r - 1) / 2;
>  ---
> int m = l + (r - l) / 2;
</code>```

Title: Same code but Strange behaviour

Body:
This is my code on implementation of merge sort , it is showing no error at all
and giving no output either :

#include<iostream>

using namespace std;

void merge(int arr[],int l,int m,int r)
{
    int i,j,k;
    int n1 = m-l+1;
    int n2 = r-m;

    int L[n1],R[n2];

    for(i=0;i<n1;i++)
    {
        L[i]=arr[i+l];
    }

    for(j=0;j<n2;j++)
    {
        R[j]=arr[m+1+j];
    }

    i=0;
    j=0;
    k=1;

    while(i<n1 && j<n2)
    {
        if(L[i]<=R[j])
        {
            arr[k]=L[i];
            i++;
        }
        else
        {
            arr[k]=R[j];
            j++;
        }
        k++;
    }

    while(i<n1)
    {
        arr[k]=L[i];
        i++;
        k++;
    }

    while(j<n2)
    {
        arr[k]=R[j];
        j++;
        k++;
    }

}

void mergeSort(int arr[], int l, int r)
{
    if(l < r)
    {

        int m = l+(r-1)/2;

        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

        merge(arr, l, m, r);
    }
}

void printArray(int A[],int size)
{
    int i;
   for( i=0;i<size;i++)
        cout<<A[i]<<" ";
}

int main()
{
    int arr[]={12,65,34,78,90,65,34};
    int arr_size = sizeof(arr)/sizeof(arr[0]);

    cout<<"Given array is \n";
    printArray(arr, arr_size);

    mergeSort(arr, 0, arr_size - 1);

    cout<<"\nSorted array is \n";
    printArray(arr, arr_size);
return 0;
}

now here is the piece of code , which is the problem :

void mergeSort(int arr[], int l, int r)
{
    if (l < r)
    {

        int m = l+(r-l)/2;

        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

        merge(arr, l, m, r);
    }
}

if i replace this mergeSort() code with the above program's mergeSort(),
the program gives output.
but have  a look , both mergeSort() codes are same (in program code as well as mentioned mergeSort() code)

link to original code ===> http://cpp.sh/6zdip

link to the code after replacing mergeSort ====> http://cpp.sh/7lfo

this is most strange problem ,i have ever faced.

Body:
It's not the same code.

on your original code:    int m = l+(r-1)/2;

on the working code:    int m = l+(r-l)/2;

the letter L minuscule can look like '1', but it's not.

Now, try one thing: make the spacements of your code consistent (by running clang-format on both codes) then use a diff application to verify the differences on your code and the running one.

It was pretty easy to spot when I did this:

> int m = l + (r - 1) / 2;
>  ---
> int m = l + (r - l) / 2;


问:
SoundPool won't play a passed raw from an other Activity
I have this problem I want to pass a raw from Activity 1 to be played in Activity 2

Here is my code

Activity 1

```<code>package com.ze.zeggar.tewt;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        int ThePlayedSound= R.raw.waterdrop;

        Intent MyIntent= new Intent(this, MainActivity.class);
               MyIntent.putExtra("key",ThePlayedSound);
        startActivity(MyIntent);
    }
}
</code>```

Activity 2

```<code>package com.ze.zeggar.tewt;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button button;
    SoundPool Sound_Pool_thing;
    int Click;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent MyIntent=getIntent();
        int ThePlayedSound= MyIntent.getIntExtra("key", 0);

        Sound_Pool_thing= new SoundPool(1, AudioManager.STREAM_MUSIC,0);

        Click = Sound_Pool_thing.load(this,ThePlayedSound , 1);

        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Sound_Pool_thing.play(Click,1,1,1,0,1);

            }
        });

    }
}
</code>```

and when I try to open the app I got "Unfortunately , My_App has stopped"
The app crashes
and here's the new crash Log after suggestions:

```<code>06-06 10:49:09.069 3424-3424/com.ze.zeggar.tewt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ze.zeggar.tewt, PID: 3424
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ze.zeggar.tewt/com.ze.zeggar.tewt.MainActivity}:
 android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
 at android.content.res.Resources.getValue(Resources.java:1269)
at android.content.res.Resources.openRawResourceFd(Resources.java:1227)
at android.media.SoundPool$SoundPoolImpl.load(SoundPool.java:566)
at android.media.SoundPool.load(SoundPool.java:229)
at com.ze.zeggar.tewt.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5977)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
</code>```

Any idea ?

答:
Ur getting resource not found exception since your not opening the raw type Resources properly

Try getting the raw audio file from resources like this:

```<code>            int ThePlayedSound = this.getResources().getIdentifier("waterdrop", "raw", getPackageName());

    Intent MyIntent= new Intent(this, MainActivity.class);
           MyIntent.putExtra("key",ThePlayedSound);
    startActivity(MyIntent);
</code>```

Body:
I have this problem I want to pass a raw from Activity 1 to be played in Activity 2

Here is my code

Activity 1

package com.ze.zeggar.tewt;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        int ThePlayedSound= R.raw.waterdrop;

        Intent MyIntent= new Intent(this, MainActivity.class);
               MyIntent.putExtra("key",ThePlayedSound);
        startActivity(MyIntent);
    }
}

Activity 2

package com.ze.zeggar.tewt;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button button;
    SoundPool Sound_Pool_thing;
    int Click;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent MyIntent=getIntent();
        int ThePlayedSound= MyIntent.getIntExtra("key", 0);

        Sound_Pool_thing= new SoundPool(1, AudioManager.STREAM_MUSIC,0);

        Click = Sound_Pool_thing.load(this,ThePlayedSound , 1);

        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Sound_Pool_thing.play(Click,1,1,1,0,1);

            }
        });

    }
}

and when I try to open the app I got "Unfortunately , My_App has stopped"
The app crashes
and here's the new crash Log after suggestions:

06-06 10:49:09.069 3424-3424/com.ze.zeggar.tewt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ze.zeggar.tewt, PID: 3424
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ze.zeggar.tewt/com.ze.zeggar.tewt.MainActivity}:
 android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
 at android.content.res.Resources.getValue(Resources.java:1269)
at android.content.res.Resources.openRawResourceFd(Resources.java:1227)
at android.media.SoundPool$SoundPoolImpl.load(SoundPool.java:566)
at android.media.SoundPool.load(SoundPool.java:229)
at com.ze.zeggar.tewt.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5977)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)

Any idea ?

Body:
Ur getting resource not found exception since your not opening the raw type Resources properly

Try getting the raw audio file from resources like this:

            int ThePlayedSound = this.getResources().getIdentifier("waterdrop", "raw", getPackageName());

    Intent MyIntent= new Intent(this, MainActivity.class);
           MyIntent.putExtra("key",ThePlayedSound);
    startActivity(MyIntent);